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// This file contains some templates that are useful if you are working with the
10// STL at all.
11//
12// No library is required when using these functions.
13//
14//===----------------------------------------------------------------------===//
15
16#ifndef LLVM_ADT_STLEXTRAS_H
17#define LLVM_ADT_STLEXTRAS_H
18
19#include "llvm/ADT/Optional.h"
20#include "llvm/ADT/STLForwardCompat.h"
21#include "llvm/ADT/iterator.h"
22#include "llvm/ADT/iterator_range.h"
23#include "llvm/Config/abi-breaking.h"
24#include "llvm/Support/ErrorHandling.h"
25#include <algorithm>
26#include <cassert>
27#include <cstddef>
28#include <cstdint>
29#include <cstdlib>
30#include <functional>
31#include <initializer_list>
32#include <iterator>
33#include <limits>
34#include <memory>
35#include <tuple>
36#include <type_traits>
37#include <utility>
38
39#ifdef EXPENSIVE_CHECKS
40#include <random> // for std::mt19937
41#endif
42
43namespace llvm {
44
45// Only used by compiler if both template types are the same. Useful when
46// using SFINAE to test for the existence of member functions.
47template <typename T, T> struct SameType;
48
49namespace detail {
50
51template <typename RangeT>
52using IterOfRange = decltype(std::begin(std::declval<RangeT &>()));
53
54template <typename RangeT>
55using ValueOfRange = typename std::remove_reference<decltype(
56 *std::begin(std::declval<RangeT &>()))>::type;
57
58} // end namespace detail
59
60//===----------------------------------------------------------------------===//
61// Extra additions to <type_traits>
62//===----------------------------------------------------------------------===//
63
64template <typename T> struct make_const_ptr {
65 using type =
66 typename std::add_pointer<typename std::add_const<T>::type>::type;
67};
68
69template <typename T> struct make_const_ref {
70 using type = typename std::add_lvalue_reference<
71 typename std::add_const<T>::type>::type;
72};
73
74namespace detail {
75template <typename...> using void_t = void;
76template <class, template <class...> class Op, class... Args> struct detector {
77 using value_t = std::false_type;
78};
79template <template <class...> class Op, class... Args>
80struct detector<void_t<Op<Args...>>, Op, Args...> {
81 using value_t = std::true_type;
82};
83} // end namespace detail
84
85/// Detects if a given trait holds for some set of arguments 'Args'.
86/// For example, the given trait could be used to detect if a given type
87/// has a copy assignment operator:
88/// template<class T>
89/// using has_copy_assign_t = decltype(std::declval<T&>()
90/// = std::declval<const T&>());
91/// bool fooHasCopyAssign = is_detected<has_copy_assign_t, FooClass>::value;
92template <template <class...> class Op, class... Args>
93using is_detected = typename detail::detector<void, Op, Args...>::value_t;
94
95namespace detail {
96template <typename Callable, typename... Args>
97using is_invocable =
98 decltype(std::declval<Callable &>()(std::declval<Args>()...));
99} // namespace detail
100
101/// Check if a Callable type can be invoked with the given set of arg types.
102template <typename Callable, typename... Args>
103using is_invocable = is_detected<detail::is_invocable, Callable, Args...>;
104
105/// This class provides various trait information about a callable object.
106/// * To access the number of arguments: Traits::num_args
107/// * To access the type of an argument: Traits::arg_t<Index>
108/// * To access the type of the result: Traits::result_t
109template <typename T, bool isClass = std::is_class<T>::value>
110struct function_traits : public function_traits<decltype(&T::operator())> {};
111
112/// Overload for class function types.
113template <typename ClassType, typename ReturnType, typename... Args>
114struct function_traits<ReturnType (ClassType::*)(Args...) const, false> {
115 /// The number of arguments to this function.
116 enum { num_args = sizeof...(Args) };
117
118 /// The result type of this function.
119 using result_t = ReturnType;
120
121 /// The type of an argument to this function.
122 template <size_t Index>
123 using arg_t = typename std::tuple_element<Index, std::tuple<Args...>>::type;
124};
125/// Overload for class function types.
126template <typename ClassType, typename ReturnType, typename... Args>
127struct function_traits<ReturnType (ClassType::*)(Args...), false>
128 : function_traits<ReturnType (ClassType::*)(Args...) const> {};
129/// Overload for non-class function types.
130template <typename ReturnType, typename... Args>
131struct function_traits<ReturnType (*)(Args...), false> {
132 /// The number of arguments to this function.
133 enum { num_args = sizeof...(Args) };
134
135 /// The result type of this function.
136 using result_t = ReturnType;
137
138 /// The type of an argument to this function.
139 template <size_t i>
140 using arg_t = typename std::tuple_element<i, std::tuple<Args...>>::type;
141};
142/// Overload for non-class function type references.
143template <typename ReturnType, typename... Args>
144struct function_traits<ReturnType (&)(Args...), false>
145 : public function_traits<ReturnType (*)(Args...)> {};
146
147//===----------------------------------------------------------------------===//
148// Extra additions to <functional>
149//===----------------------------------------------------------------------===//
150
151template <class Ty> struct identity {
152 using argument_type = Ty;
153
154 Ty &operator()(Ty &self) const {
155 return self;
156 }
157 const Ty &operator()(const Ty &self) const {
158 return self;
159 }
160};
161
162/// An efficient, type-erasing, non-owning reference to a callable. This is
163/// intended for use as the type of a function parameter that is not used
164/// after the function in question returns.
165///
166/// This class does not own the callable, so it is not in general safe to store
167/// a function_ref.
168template<typename Fn> class function_ref;
169
170template<typename Ret, typename ...Params>
171class function_ref<Ret(Params...)> {
172 Ret (*callback)(intptr_t callable, Params ...params) = nullptr;
173 intptr_t callable;
174
175 template<typename Callable>
176 static Ret callback_fn(intptr_t callable, Params ...params) {
177 return (*reinterpret_cast<Callable*>(callable))(
178 std::forward<Params>(params)...);
179 }
180
181public:
182 function_ref() = default;
183 function_ref(std::nullptr_t) {}
184
185 template <typename Callable>
186 function_ref(
187 Callable &&callable,
188 // This is not the copy-constructor.
189 std::enable_if_t<!std::is_same<remove_cvref_t<Callable>,
190 function_ref>::value> * = nullptr,
191 // Functor must be callable and return a suitable type.
192 std::enable_if_t<std::is_void<Ret>::value ||
193 std::is_convertible<decltype(std::declval<Callable>()(
194 std::declval<Params>()...)),
195 Ret>::value> * = nullptr)
196 : callback(callback_fn<typename std::remove_reference<Callable>::type>),
197 callable(reinterpret_cast<intptr_t>(&callable)) {}
198
199 Ret operator()(Params ...params) const {
200 return callback(callable, std::forward<Params>(params)...);
201 }
202
203 explicit operator bool() const { return callback; }
204};
205
206//===----------------------------------------------------------------------===//
207// Extra additions to <iterator>
208//===----------------------------------------------------------------------===//
209
210namespace adl_detail {
211
212using std::begin;
213
214template <typename ContainerTy>
215decltype(auto) adl_begin(ContainerTy &&container) {
216 return begin(std::forward<ContainerTy>(container));
217}
218
219using std::end;
220
221template <typename ContainerTy>
222decltype(auto) adl_end(ContainerTy &&container) {
223 return end(std::forward<ContainerTy>(container));
224}
225
226using std::swap;
227
228template <typename T>
229void adl_swap(T &&lhs, T &&rhs) noexcept(noexcept(swap(std::declval<T>(),
230 std::declval<T>()))) {
231 swap(std::forward<T>(lhs), std::forward<T>(rhs));
232}
233
234} // end namespace adl_detail
235
236template <typename ContainerTy>
237decltype(auto) adl_begin(ContainerTy &&container) {
238 return adl_detail::adl_begin(std::forward<ContainerTy>(container));
239}
240
241template <typename ContainerTy>
242decltype(auto) adl_end(ContainerTy &&container) {
243 return adl_detail::adl_end(std::forward<ContainerTy>(container));
244}
245
246template <typename T>
247void adl_swap(T &&lhs, T &&rhs) noexcept(
248 noexcept(adl_detail::adl_swap(std::declval<T>(), std::declval<T>()))) {
249 adl_detail::adl_swap(std::forward<T>(lhs), std::forward<T>(rhs));
250}
251
252/// Test whether \p RangeOrContainer is empty. Similar to C++17 std::empty.
253template <typename T>
254constexpr bool empty(const T &RangeOrContainer) {
255 return adl_begin(RangeOrContainer) == adl_end(RangeOrContainer);
256}
257
258/// Returns true if the given container only contains a single element.
259template <typename ContainerTy> bool hasSingleElement(ContainerTy &&C) {
260 auto B = std::begin(C), E = std::end(C);
261 return B != E && std::next(B) == E;
262}
263
264/// Return a range covering \p RangeOrContainer with the first N elements
265/// excluded.
266template <typename T> auto drop_begin(T &&RangeOrContainer, size_t N = 1) {
267 return make_range(std::next(adl_begin(RangeOrContainer), N),
268 adl_end(RangeOrContainer));
269}
270
271// mapped_iterator - This is a simple iterator adapter that causes a function to
272// be applied whenever operator* is invoked on the iterator.
273
274template <typename ItTy, typename FuncTy,
275 typename FuncReturnTy =
276 decltype(std::declval<FuncTy>()(*std::declval<ItTy>()))>
277class mapped_iterator
278 : public iterator_adaptor_base<
279 mapped_iterator<ItTy, FuncTy>, ItTy,
280 typename std::iterator_traits<ItTy>::iterator_category,
281 typename std::remove_reference<FuncReturnTy>::type> {
282public:
283 mapped_iterator(ItTy U, FuncTy F)
284 : mapped_iterator::iterator_adaptor_base(std::move(U)), F(std::move(F)) {}
285
286 ItTy getCurrent() { return this->I; }
287
288 FuncReturnTy operator*() const { return F(*this->I); }
289
290private:
291 FuncTy F;
292};
293
294// map_iterator - Provide a convenient way to create mapped_iterators, just like
295// make_pair is useful for creating pairs...
296template <class ItTy, class FuncTy>
297inline mapped_iterator<ItTy, FuncTy> map_iterator(ItTy I, FuncTy F) {
298 return mapped_iterator<ItTy, FuncTy>(std::move(I), std::move(F));
299}
300
301template <class ContainerTy, class FuncTy>
302auto map_range(ContainerTy &&C, FuncTy F) {
303 return make_range(map_iterator(C.begin(), F), map_iterator(C.end(), F));
304}
305
306/// Helper to determine if type T has a member called rbegin().
307template <typename Ty> class has_rbegin_impl {
308 using yes = char[1];
309 using no = char[2];
310
311 template <typename Inner>
312 static yes& test(Inner *I, decltype(I->rbegin()) * = nullptr);
313
314 template <typename>
315 static no& test(...);
316
317public:
318 static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
319};
320
321/// Metafunction to determine if T& or T has a member called rbegin().
322template <typename Ty>
323struct has_rbegin : has_rbegin_impl<typename std::remove_reference<Ty>::type> {
324};
325
326// Returns an iterator_range over the given container which iterates in reverse.
327// Note that the container must have rbegin()/rend() methods for this to work.
328template <typename ContainerTy>
329auto reverse(ContainerTy &&C,
330 std::enable_if_t<has_rbegin<ContainerTy>::value> * = nullptr) {
331 return make_range(C.rbegin(), C.rend());
332}
333
334// Returns a std::reverse_iterator wrapped around the given iterator.
335template <typename IteratorTy>
336std::reverse_iterator<IteratorTy> make_reverse_iterator(IteratorTy It) {
337 return std::reverse_iterator<IteratorTy>(It);
338}
339
340// Returns an iterator_range over the given container which iterates in reverse.
341// Note that the container must have begin()/end() methods which return
342// bidirectional iterators for this to work.
343template <typename ContainerTy>
344auto reverse(ContainerTy &&C,
345 std::enable_if_t<!has_rbegin<ContainerTy>::value> * = nullptr) {
346 return make_range(llvm::make_reverse_iterator(std::end(C)),
347 llvm::make_reverse_iterator(std::begin(C)));
348}
349
350/// An iterator adaptor that filters the elements of given inner iterators.
351///
352/// The predicate parameter should be a callable object that accepts the wrapped
353/// iterator's reference type and returns a bool. When incrementing or
354/// decrementing the iterator, it will call the predicate on each element and
355/// skip any where it returns false.
356///
357/// \code
358/// int A[] = { 1, 2, 3, 4 };
359/// auto R = make_filter_range(A, [](int N) { return N % 2 == 1; });
360/// // R contains { 1, 3 }.
361/// \endcode
362///
363/// Note: filter_iterator_base implements support for forward iteration.
364/// filter_iterator_impl exists to provide support for bidirectional iteration,
365/// conditional on whether the wrapped iterator supports it.
366template <typename WrappedIteratorT, typename PredicateT, typename IterTag>
367class filter_iterator_base
368 : public iterator_adaptor_base<
369 filter_iterator_base<WrappedIteratorT, PredicateT, IterTag>,
370 WrappedIteratorT,
371 typename std::common_type<
372 IterTag, typename std::iterator_traits<
373 WrappedIteratorT>::iterator_category>::type> {
374 using BaseT = iterator_adaptor_base<
375 filter_iterator_base<WrappedIteratorT, PredicateT, IterTag>,
376 WrappedIteratorT,
377 typename std::common_type<
378 IterTag, typename std::iterator_traits<
379 WrappedIteratorT>::iterator_category>::type>;
380
381protected:
382 WrappedIteratorT End;
383 PredicateT Pred;
384
385 void findNextValid() {
386 while (this->I != End && !Pred(*this->I))
387 BaseT::operator++();
388 }
389
390 // Construct the iterator. The begin iterator needs to know where the end
391 // is, so that it can properly stop when it gets there. The end iterator only
392 // needs the predicate to support bidirectional iteration.
393 filter_iterator_base(WrappedIteratorT Begin, WrappedIteratorT End,
394 PredicateT Pred)
395 : BaseT(Begin), End(End), Pred(Pred) {
396 findNextValid();
397 }
398
399public:
400 using BaseT::operator++;
401
402 filter_iterator_base &operator++() {
403 BaseT::operator++();
404 findNextValid();
405 return *this;
406 }
407};
408
409/// Specialization of filter_iterator_base for forward iteration only.
410template <typename WrappedIteratorT, typename PredicateT,
411 typename IterTag = std::forward_iterator_tag>
412class filter_iterator_impl
413 : public filter_iterator_base<WrappedIteratorT, PredicateT, IterTag> {
414 using BaseT = filter_iterator_base<WrappedIteratorT, PredicateT, IterTag>;
415
416public:
417 filter_iterator_impl(WrappedIteratorT Begin, WrappedIteratorT End,
418 PredicateT Pred)
419 : BaseT(Begin, End, Pred) {}
420};
421
422/// Specialization of filter_iterator_base for bidirectional iteration.
423template <typename WrappedIteratorT, typename PredicateT>
424class filter_iterator_impl<WrappedIteratorT, PredicateT,
425 std::bidirectional_iterator_tag>
426 : public filter_iterator_base<WrappedIteratorT, PredicateT,
427 std::bidirectional_iterator_tag> {
428 using BaseT = filter_iterator_base<WrappedIteratorT, PredicateT,
429 std::bidirectional_iterator_tag>;
430 void findPrevValid() {
431 while (!this->Pred(*this->I))
432 BaseT::operator--();
433 }
434
435public:
436 using BaseT::operator--;
437
438 filter_iterator_impl(WrappedIteratorT Begin, WrappedIteratorT End,
439 PredicateT Pred)
440 : BaseT(Begin, End, Pred) {}
441
442 filter_iterator_impl &operator--() {
443 BaseT::operator--();
444 findPrevValid();
445 return *this;
446 }
447};
448
449namespace detail {
450
451template <bool is_bidirectional> struct fwd_or_bidi_tag_impl {
452 using type = std::forward_iterator_tag;
453};
454
455template <> struct fwd_or_bidi_tag_impl<true> {
456 using type = std::bidirectional_iterator_tag;
457};
458
459/// Helper which sets its type member to forward_iterator_tag if the category
460/// of \p IterT does not derive from bidirectional_iterator_tag, and to
461/// bidirectional_iterator_tag otherwise.
462template <typename IterT> struct fwd_or_bidi_tag {
463 using type = typename fwd_or_bidi_tag_impl<std::is_base_of<
464 std::bidirectional_iterator_tag,
465 typename std::iterator_traits<IterT>::iterator_category>::value>::type;
466};
467
468} // namespace detail
469
470/// Defines filter_iterator to a suitable specialization of
471/// filter_iterator_impl, based on the underlying iterator's category.
472template <typename WrappedIteratorT, typename PredicateT>
473using filter_iterator = filter_iterator_impl<
474 WrappedIteratorT, PredicateT,
475 typename detail::fwd_or_bidi_tag<WrappedIteratorT>::type>;
476
477/// Convenience function that takes a range of elements and a predicate,
478/// and return a new filter_iterator range.
479///
480/// FIXME: Currently if RangeT && is a rvalue reference to a temporary, the
481/// lifetime of that temporary is not kept by the returned range object, and the
482/// temporary is going to be dropped on the floor after the make_iterator_range
483/// full expression that contains this function call.
484template <typename RangeT, typename PredicateT>
485iterator_range<filter_iterator<detail::IterOfRange<RangeT>, PredicateT>>
486make_filter_range(RangeT &&Range, PredicateT Pred) {
487 using FilterIteratorT =
488 filter_iterator<detail::IterOfRange<RangeT>, PredicateT>;
489 return make_range(
490 FilterIteratorT(std::begin(std::forward<RangeT>(Range)),
491 std::end(std::forward<RangeT>(Range)), Pred),
492 FilterIteratorT(std::end(std::forward<RangeT>(Range)),
493 std::end(std::forward<RangeT>(Range)), Pred));
494}
495
496/// A pseudo-iterator adaptor that is designed to implement "early increment"
497/// style loops.
498///
499/// This is *not a normal iterator* and should almost never be used directly. It
500/// is intended primarily to be used with range based for loops and some range
501/// algorithms.
502///
503/// The iterator isn't quite an `OutputIterator` or an `InputIterator` but
504/// somewhere between them. The constraints of these iterators are:
505///
506/// - On construction or after being incremented, it is comparable and
507/// dereferencable. It is *not* incrementable.
508/// - After being dereferenced, it is neither comparable nor dereferencable, it
509/// is only incrementable.
510///
511/// This means you can only dereference the iterator once, and you can only
512/// increment it once between dereferences.
513template <typename WrappedIteratorT>
514class early_inc_iterator_impl
515 : public iterator_adaptor_base<early_inc_iterator_impl<WrappedIteratorT>,
516 WrappedIteratorT, std::input_iterator_tag> {
517 using BaseT =
518 iterator_adaptor_base<early_inc_iterator_impl<WrappedIteratorT>,
519 WrappedIteratorT, std::input_iterator_tag>;
520
521 using PointerT = typename std::iterator_traits<WrappedIteratorT>::pointer;
522
523protected:
524#if LLVM_ENABLE_ABI_BREAKING_CHECKS
525 bool IsEarlyIncremented = false;
526#endif
527
528public:
529 early_inc_iterator_impl(WrappedIteratorT I) : BaseT(I) {}
530
531 using BaseT::operator*;
532 decltype(*std::declval<WrappedIteratorT>()) operator*() {
533#if LLVM_ENABLE_ABI_BREAKING_CHECKS
534 assert(!IsEarlyIncremented && "Cannot dereference twice!");
535 IsEarlyIncremented = true;
536#endif
537 return *(this->I)++;
538 }
539
540 using BaseT::operator++;
541 early_inc_iterator_impl &operator++() {
542#if LLVM_ENABLE_ABI_BREAKING_CHECKS
543 assert(IsEarlyIncremented && "Cannot increment before dereferencing!");
544 IsEarlyIncremented = false;
545#endif
546 return *this;
547 }
548
549 friend bool operator==(const early_inc_iterator_impl &LHS,
550 const early_inc_iterator_impl &RHS) {
551#if LLVM_ENABLE_ABI_BREAKING_CHECKS
552 assert(!LHS.IsEarlyIncremented && "Cannot compare after dereferencing!");
553#endif
554 return (const BaseT &)LHS == (const BaseT &)RHS;
555 }
556};
557
558/// Make a range that does early increment to allow mutation of the underlying
559/// range without disrupting iteration.
560///
561/// The underlying iterator will be incremented immediately after it is
562/// dereferenced, allowing deletion of the current node or insertion of nodes to
563/// not disrupt iteration provided they do not invalidate the *next* iterator --
564/// the current iterator can be invalidated.
565///
566/// This requires a very exact pattern of use that is only really suitable to
567/// range based for loops and other range algorithms that explicitly guarantee
568/// to dereference exactly once each element, and to increment exactly once each
569/// element.
570template <typename RangeT>
571iterator_range<early_inc_iterator_impl<detail::IterOfRange<RangeT>>>
572make_early_inc_range(RangeT &&Range) {
573 using EarlyIncIteratorT =
574 early_inc_iterator_impl<detail::IterOfRange<RangeT>>;
575 return make_range(EarlyIncIteratorT(std::begin(std::forward<RangeT>(Range))),
576 EarlyIncIteratorT(std::end(std::forward<RangeT>(Range))));
577}
578
579// forward declarations required by zip_shortest/zip_first/zip_longest
580template <typename R, typename UnaryPredicate>
581bool all_of(R &&range, UnaryPredicate P);
582template <typename R, typename UnaryPredicate>
583bool any_of(R &&range, UnaryPredicate P);
584
585namespace detail {
586
587using std::declval;
588
589// We have to alias this since inlining the actual type at the usage site
590// in the parameter list of iterator_facade_base<> below ICEs MSVC 2017.
591template<typename... Iters> struct ZipTupleType {
592 using type = std::tuple<decltype(*declval<Iters>())...>;
593};
594
595template <typename ZipType, typename... Iters>
596using zip_traits = iterator_facade_base<
597 ZipType, typename std::common_type<std::bidirectional_iterator_tag,
598 typename std::iterator_traits<
599 Iters>::iterator_category...>::type,
600 // ^ TODO: Implement random access methods.
601 typename ZipTupleType<Iters...>::type,
602 typename std::iterator_traits<typename std::tuple_element<
603 0, std::tuple<Iters...>>::type>::difference_type,
604 // ^ FIXME: This follows boost::make_zip_iterator's assumption that all
605 // inner iterators have the same difference_type. It would fail if, for
606 // instance, the second field's difference_type were non-numeric while the
607 // first is.
608 typename ZipTupleType<Iters...>::type *,
609 typename ZipTupleType<Iters...>::type>;
610
611template <typename ZipType, typename... Iters>
612struct zip_common : public zip_traits<ZipType, Iters...> {
613 using Base = zip_traits<ZipType, Iters...>;
614 using value_type = typename Base::value_type;
615
616 std::tuple<Iters...> iterators;
617
618protected:
619 template <size_t... Ns> value_type deref(std::index_sequence<Ns...>) const {
620 return value_type(*std::get<Ns>(iterators)...);
621 }
622
623 template <size_t... Ns>
624 decltype(iterators) tup_inc(std::index_sequence<Ns...>) const {
625 return std::tuple<Iters...>(std::next(std::get<Ns>(iterators))...);
626 }
627
628 template <size_t... Ns>
629 decltype(iterators) tup_dec(std::index_sequence<Ns...>) const {
630 return std::tuple<Iters...>(std::prev(std::get<Ns>(iterators))...);
631 }
632
633public:
634 zip_common(Iters &&... ts) : iterators(std::forward<Iters>(ts)...) {}
635
636 value_type operator*() { return deref(std::index_sequence_for<Iters...>{}); }
637
638 const value_type operator*() const {
639 return deref(std::index_sequence_for<Iters...>{});
640 }
641
642 ZipType &operator++() {
643 iterators = tup_inc(std::index_sequence_for<Iters...>{});
644 return *reinterpret_cast<ZipType *>(this);
645 }
646
647 ZipType &operator--() {
648 static_assert(Base::IsBidirectional,
649 "All inner iterators must be at least bidirectional.");
650 iterators = tup_dec(std::index_sequence_for<Iters...>{});
651 return *reinterpret_cast<ZipType *>(this);
652 }
653};
654
655template <typename... Iters>
656struct zip_first : public zip_common<zip_first<Iters...>, Iters...> {
657 using Base = zip_common<zip_first<Iters...>, Iters...>;
658
659 bool operator==(const zip_first<Iters...> &other) const {
660 return std::get<0>(this->iterators) == std::get<0>(other.iterators);
661 }
662
663 zip_first(Iters &&... ts) : Base(std::forward<Iters>(ts)...) {}
664};
665
666template <typename... Iters>
667class zip_shortest : public zip_common<zip_shortest<Iters...>, Iters...> {
668 template <size_t... Ns>
669 bool test(const zip_shortest<Iters...> &other,
670 std::index_sequence<Ns...>) const {
671 return all_of(std::initializer_list<bool>{std::get<Ns>(this->iterators) !=
672 std::get<Ns>(other.iterators)...},
673 identity<bool>{});
674 }
675
676public:
677 using Base = zip_common<zip_shortest<Iters...>, Iters...>;
678
679 zip_shortest(Iters &&... ts) : Base(std::forward<Iters>(ts)...) {}
680
681 bool operator==(const zip_shortest<Iters...> &other) const {
682 return !test(other, std::index_sequence_for<Iters...>{});
683 }
684};
685
686template <template <typename...> class ItType, typename... Args> class zippy {
687public:
688 using iterator = ItType<decltype(std::begin(std::declval<Args>()))...>;
689 using iterator_category = typename iterator::iterator_category;
690 using value_type = typename iterator::value_type;
691 using difference_type = typename iterator::difference_type;
692 using pointer = typename iterator::pointer;
693 using reference = typename iterator::reference;
694
695private:
696 std::tuple<Args...> ts;
697
698 template <size_t... Ns>
699 iterator begin_impl(std::index_sequence<Ns...>) const {
700 return iterator(std::begin(std::get<Ns>(ts))...);
701 }
702 template <size_t... Ns> iterator end_impl(std::index_sequence<Ns...>) const {
703 return iterator(std::end(std::get<Ns>(ts))...);
704 }
705
706public:
707 zippy(Args &&... ts_) : ts(std::forward<Args>(ts_)...) {}
708
709 iterator begin() const {
710 return begin_impl(std::index_sequence_for<Args...>{});
711 }
712 iterator end() const { return end_impl(std::index_sequence_for<Args...>{}); }
713};
714
715} // end namespace detail
716
717/// zip iterator for two or more iteratable types.
718template <typename T, typename U, typename... Args>
719detail::zippy<detail::zip_shortest, T, U, Args...> zip(T &&t, U &&u,
720 Args &&... args) {
721 return detail::zippy<detail::zip_shortest, T, U, Args...>(
722 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
723}
724
725/// zip iterator that, for the sake of efficiency, assumes the first iteratee to
726/// be the shortest.
727template <typename T, typename U, typename... Args>
728detail::zippy<detail::zip_first, T, U, Args...> zip_first(T &&t, U &&u,
729 Args &&... args) {
730 return detail::zippy<detail::zip_first, T, U, Args...>(
731 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
732}
733
734namespace detail {
735template <typename Iter>
736Iter next_or_end(const Iter &I, const Iter &End) {
737 if (I == End)
738 return End;
739 return std::next(I);
740}
741
742template <typename Iter>
743auto deref_or_none(const Iter &I, const Iter &End) -> llvm::Optional<
744 std::remove_const_t<std::remove_reference_t<decltype(*I)>>> {
745 if (I == End)
746 return None;
747 return *I;
748}
749
750template <typename Iter> struct ZipLongestItemType {
751 using type =
752 llvm::Optional<typename std::remove_const<typename std::remove_reference<
753 decltype(*std::declval<Iter>())>::type>::type>;
754};
755
756template <typename... Iters> struct ZipLongestTupleType {
757 using type = std::tuple<typename ZipLongestItemType<Iters>::type...>;
758};
759
760template <typename... Iters>
761class zip_longest_iterator
762 : public iterator_facade_base<
763 zip_longest_iterator<Iters...>,
764 typename std::common_type<
765 std::forward_iterator_tag,
766 typename std::iterator_traits<Iters>::iterator_category...>::type,
767 typename ZipLongestTupleType<Iters...>::type,
768 typename std::iterator_traits<typename std::tuple_element<
769 0, std::tuple<Iters...>>::type>::difference_type,
770 typename ZipLongestTupleType<Iters...>::type *,
771 typename ZipLongestTupleType<Iters...>::type> {
772public:
773 using value_type = typename ZipLongestTupleType<Iters...>::type;
774
775private:
776 std::tuple<Iters...> iterators;
777 std::tuple<Iters...> end_iterators;
778
779 template <size_t... Ns>
780 bool test(const zip_longest_iterator<Iters...> &other,
781 std::index_sequence<Ns...>) const {
782 return llvm::any_of(
783 std::initializer_list<bool>{std::get<Ns>(this->iterators) !=
784 std::get<Ns>(other.iterators)...},
785 identity<bool>{});
786 }
787
788 template <size_t... Ns> value_type deref(std::index_sequence<Ns...>) const {
789 return value_type(
790 deref_or_none(std::get<Ns>(iterators), std::get<Ns>(end_iterators))...);
791 }
792
793 template <size_t... Ns>
794 decltype(iterators) tup_inc(std::index_sequence<Ns...>) const {
795 return std::tuple<Iters...>(
796 next_or_end(std::get<Ns>(iterators), std::get<Ns>(end_iterators))...);
797 }
798
799public:
800 zip_longest_iterator(std::pair<Iters &&, Iters &&>... ts)
801 : iterators(std::forward<Iters>(ts.first)...),
802 end_iterators(std::forward<Iters>(ts.second)...) {}
803
804 value_type operator*() { return deref(std::index_sequence_for<Iters...>{}); }
805
806 value_type operator*() const {
807 return deref(std::index_sequence_for<Iters...>{});
808 }
809
810 zip_longest_iterator<Iters...> &operator++() {
811 iterators = tup_inc(std::index_sequence_for<Iters...>{});
812 return *this;
813 }
814
815 bool operator==(const zip_longest_iterator<Iters...> &other) const {
816 return !test(other, std::index_sequence_for<Iters...>{});
817 }
818};
819
820template <typename... Args> class zip_longest_range {
821public:
822 using iterator =
823 zip_longest_iterator<decltype(adl_begin(std::declval<Args>()))...>;
824 using iterator_category = typename iterator::iterator_category;
825 using value_type = typename iterator::value_type;
826 using difference_type = typename iterator::difference_type;
827 using pointer = typename iterator::pointer;
828 using reference = typename iterator::reference;
829
830private:
831 std::tuple<Args...> ts;
832
833 template <size_t... Ns>
834 iterator begin_impl(std::index_sequence<Ns...>) const {
835 return iterator(std::make_pair(adl_begin(std::get<Ns>(ts)),
836 adl_end(std::get<Ns>(ts)))...);
837 }
838
839 template <size_t... Ns> iterator end_impl(std::index_sequence<Ns...>) const {
840 return iterator(std::make_pair(adl_end(std::get<Ns>(ts)),
841 adl_end(std::get<Ns>(ts)))...);
842 }
843
844public:
845 zip_longest_range(Args &&... ts_) : ts(std::forward<Args>(ts_)...) {}
846
847 iterator begin() const {
848 return begin_impl(std::index_sequence_for<Args...>{});
849 }
850 iterator end() const { return end_impl(std::index_sequence_for<Args...>{}); }
851};
852} // namespace detail
853
854/// Iterate over two or more iterators at the same time. Iteration continues
855/// until all iterators reach the end. The llvm::Optional only contains a value
856/// if the iterator has not reached the end.
857template <typename T, typename U, typename... Args>
858detail::zip_longest_range<T, U, Args...> zip_longest(T &&t, U &&u,
859 Args &&... args) {
860 return detail::zip_longest_range<T, U, Args...>(
861 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
862}
863
864/// Iterator wrapper that concatenates sequences together.
865///
866/// This can concatenate different iterators, even with different types, into
867/// a single iterator provided the value types of all the concatenated
868/// iterators expose `reference` and `pointer` types that can be converted to
869/// `ValueT &` and `ValueT *` respectively. It doesn't support more
870/// interesting/customized pointer or reference types.
871///
872/// Currently this only supports forward or higher iterator categories as
873/// inputs and always exposes a forward iterator interface.
874template <typename ValueT, typename... IterTs>
875class concat_iterator
876 : public iterator_facade_base<concat_iterator<ValueT, IterTs...>,
877 std::forward_iterator_tag, ValueT> {
878 using BaseT = typename concat_iterator::iterator_facade_base;
879
880 /// We store both the current and end iterators for each concatenated
881 /// sequence in a tuple of pairs.
882 ///
883 /// Note that something like iterator_range seems nice at first here, but the
884 /// range properties are of little benefit and end up getting in the way
885 /// because we need to do mutation on the current iterators.
886 std::tuple<IterTs...> Begins;
887 std::tuple<IterTs...> Ends;
888
889 /// Attempts to increment a specific iterator.
890 ///
891 /// Returns true if it was able to increment the iterator. Returns false if
892 /// the iterator is already at the end iterator.
893 template <size_t Index> bool incrementHelper() {
894 auto &Begin = std::get<Index>(Begins);
895 auto &End = std::get<Index>(Ends);
896 if (Begin == End)
897 return false;
898
899 ++Begin;
900 return true;
901 }
902
903 /// Increments the first non-end iterator.
904 ///
905 /// It is an error to call this with all iterators at the end.
906 template <size_t... Ns> void increment(std::index_sequence<Ns...>) {
907 // Build a sequence of functions to increment each iterator if possible.
908 bool (concat_iterator::*IncrementHelperFns[])() = {
909 &concat_iterator::incrementHelper<Ns>...};
910
911 // Loop over them, and stop as soon as we succeed at incrementing one.
912 for (auto &IncrementHelperFn : IncrementHelperFns)
913 if ((this->*IncrementHelperFn)())
914 return;
915
916 llvm_unreachable("Attempted to increment an end concat iterator!");
917 }
918
919 /// Returns null if the specified iterator is at the end. Otherwise,
920 /// dereferences the iterator and returns the address of the resulting
921 /// reference.
922 template <size_t Index> ValueT *getHelper() const {
923 auto &Begin = std::get<Index>(Begins);
924 auto &End = std::get<Index>(Ends);
925 if (Begin == End)
926 return nullptr;
927
928 return &*Begin;
929 }
930
931 /// Finds the first non-end iterator, dereferences, and returns the resulting
932 /// reference.
933 ///
934 /// It is an error to call this with all iterators at the end.
935 template <size_t... Ns> ValueT &get(std::index_sequence<Ns...>) const {
936 // Build a sequence of functions to get from iterator if possible.
937 ValueT *(concat_iterator::*GetHelperFns[])() const = {
938 &concat_iterator::getHelper<Ns>...};
939
940 // Loop over them, and return the first result we find.
941 for (auto &GetHelperFn : GetHelperFns)
942 if (ValueT *P = (this->*GetHelperFn)())
943 return *P;
944
945 llvm_unreachable("Attempted to get a pointer from an end concat iterator!");
946 }
947
948public:
949 /// Constructs an iterator from a sequence of ranges.
950 ///
951 /// We need the full range to know how to switch between each of the
952 /// iterators.
953 template <typename... RangeTs>
954 explicit concat_iterator(RangeTs &&... Ranges)
955 : Begins(std::begin(Ranges)...), Ends(std::end(Ranges)...) {}
956
957 using BaseT::operator++;
958
959 concat_iterator &operator++() {
960 increment(std::index_sequence_for<IterTs...>());
961 return *this;
962 }
963
964 ValueT &operator*() const {
965 return get(std::index_sequence_for<IterTs...>());
966 }
967
968 bool operator==(const concat_iterator &RHS) const {
969 return Begins == RHS.Begins && Ends == RHS.Ends;
970 }
971};
972
973namespace detail {
974
975/// Helper to store a sequence of ranges being concatenated and access them.
976///
977/// This is designed to facilitate providing actual storage when temporaries
978/// are passed into the constructor such that we can use it as part of range
979/// based for loops.
980template <typename ValueT, typename... RangeTs> class concat_range {
981public:
982 using iterator =
983 concat_iterator<ValueT,
984 decltype(std::begin(std::declval<RangeTs &>()))...>;
985
986private:
987 std::tuple<RangeTs...> Ranges;
988
989 template <size_t... Ns> iterator begin_impl(std::index_sequence<Ns...>) {
990 return iterator(std::get<Ns>(Ranges)...);
991 }
992 template <size_t... Ns> iterator end_impl(std::index_sequence<Ns...>) {
993 return iterator(make_range(std::end(std::get<Ns>(Ranges)),
994 std::end(std::get<Ns>(Ranges)))...);
995 }
996
997public:
998 concat_range(RangeTs &&... Ranges)
999 : Ranges(std::forward<RangeTs>(Ranges)...) {}
1000
1001 iterator begin() { return begin_impl(std::index_sequence_for<RangeTs...>{}); }
1002 iterator end() { return end_impl(std::index_sequence_for<RangeTs...>{}); }
1003};
1004
1005} // end namespace detail
1006
1007/// Concatenated range across two or more ranges.
1008///
1009/// The desired value type must be explicitly specified.
1010template <typename ValueT, typename... RangeTs>
1011detail::concat_range<ValueT, RangeTs...> concat(RangeTs &&... Ranges) {
1012 static_assert(sizeof...(RangeTs) > 1,
1013 "Need more than one range to concatenate!");
1014 return detail::concat_range<ValueT, RangeTs...>(
1015 std::forward<RangeTs>(Ranges)...);
1016}
1017
1018/// A utility class used to implement an iterator that contains some base object
1019/// and an index. The iterator moves the index but keeps the base constant.
1020template <typename DerivedT, typename BaseT, typename T,
1021 typename PointerT = T *, typename ReferenceT = T &>
1022class indexed_accessor_iterator
1023 : public llvm::iterator_facade_base<DerivedT,
1024 std::random_access_iterator_tag, T,
1025 std::ptrdiff_t, PointerT, ReferenceT> {
1026public:
1027 ptrdiff_t operator-(const indexed_accessor_iterator &rhs) const {
1028 assert(base == rhs.base && "incompatible iterators");
1029 return index - rhs.index;
1030 }
1031 bool operator==(const indexed_accessor_iterator &rhs) const {
1032 return base == rhs.base && index == rhs.index;
1033 }
1034 bool operator<(const indexed_accessor_iterator &rhs) const {
1035 assert(base == rhs.base && "incompatible iterators");
1036 return index < rhs.index;
1037 }
1038
1039 DerivedT &operator+=(ptrdiff_t offset) {
1040 this->index += offset;
1041 return static_cast<DerivedT &>(*this);
1042 }
1043 DerivedT &operator-=(ptrdiff_t offset) {
1044 this->index -= offset;
1045 return static_cast<DerivedT &>(*this);
1046 }
1047
1048 /// Returns the current index of the iterator.
1049 ptrdiff_t getIndex() const { return index; }
1050
1051 /// Returns the current base of the iterator.
1052 const BaseT &getBase() const { return base; }
1053
1054protected:
1055 indexed_accessor_iterator(BaseT base, ptrdiff_t index)
1056 : base(base), index(index) {}
1057 BaseT base;
1058 ptrdiff_t index;
1059};
1060
1061namespace detail {
1062/// The class represents the base of a range of indexed_accessor_iterators. It
1063/// provides support for many different range functionalities, e.g.
1064/// drop_front/slice/etc.. Derived range classes must implement the following
1065/// static methods:
1066/// * ReferenceT dereference_iterator(const BaseT &base, ptrdiff_t index)
1067/// - Dereference an iterator pointing to the base object at the given
1068/// index.
1069/// * BaseT offset_base(const BaseT &base, ptrdiff_t index)
1070/// - Return a new base that is offset from the provide base by 'index'
1071/// elements.
1072template <typename DerivedT, typename BaseT, typename T,
1073 typename PointerT = T *, typename ReferenceT = T &>
1074class indexed_accessor_range_base {
1075public:
1076 using RangeBaseT =
1077 indexed_accessor_range_base<DerivedT, BaseT, T, PointerT, ReferenceT>;
1078
1079 /// An iterator element of this range.
1080 class iterator : public indexed_accessor_iterator<iterator, BaseT, T,
1081 PointerT, ReferenceT> {
1082 public:
1083 // Index into this iterator, invoking a static method on the derived type.
1084 ReferenceT operator*() const {
1085 return DerivedT::dereference_iterator(this->getBase(), this->getIndex());
1086 }
1087
1088 private:
1089 iterator(BaseT owner, ptrdiff_t curIndex)
1090 : indexed_accessor_iterator<iterator, BaseT, T, PointerT, ReferenceT>(
1091 owner, curIndex) {}
1092
1093 /// Allow access to the constructor.
1094 friend indexed_accessor_range_base<DerivedT, BaseT, T, PointerT,
1095 ReferenceT>;
1096 };
1097
1098 indexed_accessor_range_base(iterator begin, iterator end)
1099 : base(offset_base(begin.getBase(), begin.getIndex())),
1100 count(end.getIndex() - begin.getIndex()) {}
1101 indexed_accessor_range_base(const iterator_range<iterator> &range)
1102 : indexed_accessor_range_base(range.begin(), range.end()) {}
1103 indexed_accessor_range_base(BaseT base, ptrdiff_t count)
1104 : base(base), count(count) {}
1105
1106 iterator begin() const { return iterator(base, 0); }
1107 iterator end() const { return iterator(base, count); }
1108 ReferenceT operator[](size_t Index) const {
1109 assert(Index < size() && "invalid index for value range");
1110 return DerivedT::dereference_iterator(base, static_cast<ptrdiff_t>(Index));
1111 }
1112 ReferenceT front() const {
1113 assert(!empty() && "expected non-empty range");
1114 return (*this)[0];
1115 }
1116 ReferenceT back() const {
1117 assert(!empty() && "expected non-empty range");
1118 return (*this)[size() - 1];
1119 }
1120
1121 /// Compare this range with another.
1122 template <typename OtherT> bool operator==(const OtherT &other) const {
1123 return size() ==
1124 static_cast<size_t>(std::distance(other.begin(), other.end())) &&
1125 std::equal(begin(), end(), other.begin());
1126 }
1127 template <typename OtherT> bool operator!=(const OtherT &other) const {
1128 return !(*this == other);
1129 }
1130
1131 /// Return the size of this range.
1132 size_t size() const { return count; }
1133
1134 /// Return if the range is empty.
1135 bool empty() const { return size() == 0; }
1136
1137 /// Drop the first N elements, and keep M elements.
1138 DerivedT slice(size_t n, size_t m) const {
1139 assert(n + m <= size() && "invalid size specifiers");
1140 return DerivedT(offset_base(base, n), m);
1141 }
1142
1143 /// Drop the first n elements.
1144 DerivedT drop_front(size_t n = 1) const {
1145 assert(size() >= n && "Dropping more elements than exist");
1146 return slice(n, size() - n);
1147 }
1148 /// Drop the last n elements.
1149 DerivedT drop_back(size_t n = 1) const {
1150 assert(size() >= n && "Dropping more elements than exist");
1151 return DerivedT(base, size() - n);
1152 }
1153
1154 /// Take the first n elements.
1155 DerivedT take_front(size_t n = 1) const {
1156 return n < size() ? drop_back(size() - n)
1157 : static_cast<const DerivedT &>(*this);
1158 }
1159
1160 /// Take the last n elements.
1161 DerivedT take_back(size_t n = 1) const {
1162 return n < size() ? drop_front(size() - n)
1163 : static_cast<const DerivedT &>(*this);
1164 }
1165
1166 /// Allow conversion to any type accepting an iterator_range.
1167 template <typename RangeT, typename = std::enable_if_t<std::is_constructible<
1168 RangeT, iterator_range<iterator>>::value>>
1169 operator RangeT() const {
1170 return RangeT(iterator_range<iterator>(*this));
1171 }
1172
1173 /// Returns the base of this range.
1174 const BaseT &getBase() const { return base; }
1175
1176private:
1177 /// Offset the given base by the given amount.
1178 static BaseT offset_base(const BaseT &base, size_t n) {
1179 return n == 0 ? base : DerivedT::offset_base(base, n);
1180 }
1181
1182protected:
1183 indexed_accessor_range_base(const indexed_accessor_range_base &) = default;
1184 indexed_accessor_range_base(indexed_accessor_range_base &&) = default;
1185 indexed_accessor_range_base &
1186 operator=(const indexed_accessor_range_base &) = default;
1187
1188 /// The base that owns the provided range of values.
1189 BaseT base;
1190 /// The size from the owning range.
1191 ptrdiff_t count;
1192};
1193} // end namespace detail
1194
1195/// This class provides an implementation of a range of
1196/// indexed_accessor_iterators where the base is not indexable. Ranges with
1197/// bases that are offsetable should derive from indexed_accessor_range_base
1198/// instead. Derived range classes are expected to implement the following
1199/// static method:
1200/// * ReferenceT dereference(const BaseT &base, ptrdiff_t index)
1201/// - Dereference an iterator pointing to a parent base at the given index.
1202template <typename DerivedT, typename BaseT, typename T,
1203 typename PointerT = T *, typename ReferenceT = T &>
1204class indexed_accessor_range
1205 : public detail::indexed_accessor_range_base<
1206 DerivedT, std::pair<BaseT, ptrdiff_t>, T, PointerT, ReferenceT> {
1207public:
1208 indexed_accessor_range(BaseT base, ptrdiff_t startIndex, ptrdiff_t count)
1209 : detail::indexed_accessor_range_base<
1210 DerivedT, std::pair<BaseT, ptrdiff_t>, T, PointerT, ReferenceT>(
1211 std::make_pair(base, startIndex), count) {}
1212 using detail::indexed_accessor_range_base<
1213 DerivedT, std::pair<BaseT, ptrdiff_t>, T, PointerT,
1214 ReferenceT>::indexed_accessor_range_base;
1215
1216 /// Returns the current base of the range.
1217 const BaseT &getBase() const { return this->base.first; }
1218
1219 /// Returns the current start index of the range.
1220 ptrdiff_t getStartIndex() const { return this->base.second; }
1221
1222 /// See `detail::indexed_accessor_range_base` for details.
1223 static std::pair<BaseT, ptrdiff_t>
1224 offset_base(const std::pair<BaseT, ptrdiff_t> &base, ptrdiff_t index) {
1225 // We encode the internal base as a pair of the derived base and a start
1226 // index into the derived base.
1227 return std::make_pair(base.first, base.second + index);
1228 }
1229 /// See `detail::indexed_accessor_range_base` for details.
1230 static ReferenceT
1231 dereference_iterator(const std::pair<BaseT, ptrdiff_t> &base,
1232 ptrdiff_t index) {
1233 return DerivedT::dereference(base.first, base.second + index);
1234 }
1235};
1236
1237/// Given a container of pairs, return a range over the first elements.
1238template <typename ContainerTy> auto make_first_range(ContainerTy &&c) {
1239 return llvm::map_range(
1240 std::forward<ContainerTy>(c),
1241 [](decltype((*std::begin(c))) elt) -> decltype((elt.first)) {
1242 return elt.first;
1243 });
1244}
1245
1246/// Given a container of pairs, return a range over the second elements.
1247template <typename ContainerTy> auto make_second_range(ContainerTy &&c) {
1248 return llvm::map_range(
1249 std::forward<ContainerTy>(c),
1250 [](decltype((*std::begin(c))) elt) -> decltype((elt.second)) {
1251 return elt.second;
1252 });
1253}
1254
1255//===----------------------------------------------------------------------===//
1256// Extra additions to <utility>
1257//===----------------------------------------------------------------------===//
1258
1259/// Function object to check whether the first component of a std::pair
1260/// compares less than the first component of another std::pair.
1261struct less_first {
1262 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
1263 return lhs.first < rhs.first;
1264 }
1265};
1266
1267/// Function object to check whether the second component of a std::pair
1268/// compares less than the second component of another std::pair.
1269struct less_second {
1270 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
1271 return lhs.second < rhs.second;
1272 }
1273};
1274
1275/// \brief Function object to apply a binary function to the first component of
1276/// a std::pair.
1277template<typename FuncTy>
1278struct on_first {
1279 FuncTy func;
1280
1281 template <typename T>
1282 decltype(auto) operator()(const T &lhs, const T &rhs) const {
1283 return func(lhs.first, rhs.first);
1284 }
1285};
1286
1287/// Utility type to build an inheritance chain that makes it easy to rank
1288/// overload candidates.
1289template <int N> struct rank : rank<N - 1> {};
1290template <> struct rank<0> {};
1291
1292/// traits class for checking whether type T is one of any of the given
1293/// types in the variadic list.
1294template <typename T, typename... Ts>
1295using is_one_of = disjunction<std::is_same<T, Ts>...>;
1296
1297/// traits class for checking whether type T is a base class for all
1298/// the given types in the variadic list.
1299template <typename T, typename... Ts>
1300using are_base_of = conjunction<std::is_base_of<T, Ts>...>;
1301
1302//===----------------------------------------------------------------------===//
1303// Extra additions for arrays
1304//===----------------------------------------------------------------------===//
1305
1306// We have a copy here so that LLVM behaves the same when using different
1307// standard libraries.
1308template <class Iterator, class RNG>
1309void shuffle(Iterator first, Iterator last, RNG &&g) {
1310 // It would be better to use a std::uniform_int_distribution,
1311 // but that would be stdlib dependent.
1312 typedef
1313 typename std::iterator_traits<Iterator>::difference_type difference_type;
1314 for (auto size = last - first; size > 1; ++first, (void)--size) {
1315 difference_type offset = g() % size;
1316 // Avoid self-assignment due to incorrect assertions in libstdc++
1317 // containers (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85828).
1318 if (offset != difference_type(0))
1319 std::iter_swap(first, first + offset);
1320 }
1321}
1322
1323/// Find the length of an array.
1324template <class T, std::size_t N>
1325constexpr inline size_t array_lengthof(T (&)[N]) {
1326 return N;
1327}
1328
1329/// Adapt std::less<T> for array_pod_sort.
1330template<typename T>
1331inline int array_pod_sort_comparator(const void *P1, const void *P2) {
1332 if (std::less<T>()(*reinterpret_cast<const T*>(P1),
1333 *reinterpret_cast<const T*>(P2)))
1334 return -1;
1335 if (std::less<T>()(*reinterpret_cast<const T*>(P2),
1336 *reinterpret_cast<const T*>(P1)))
1337 return 1;
1338 return 0;
1339}
1340
1341/// get_array_pod_sort_comparator - This is an internal helper function used to
1342/// get type deduction of T right.
1343template<typename T>
1344inline int (*get_array_pod_sort_comparator(const T &))
1345 (const void*, const void*) {
1346 return array_pod_sort_comparator<T>;
1347}
1348
1349#ifdef EXPENSIVE_CHECKS
1350namespace detail {
1351
1352inline unsigned presortShuffleEntropy() {
1353 static unsigned Result(std::random_device{}());
1354 return Result;
1355}
1356
1357template <class IteratorTy>
1358inline void presortShuffle(IteratorTy Start, IteratorTy End) {
1359 std::mt19937 Generator(presortShuffleEntropy());
1360 llvm::shuffle(Start, End, Generator);
1361}
1362
1363} // end namespace detail
1364#endif
1365
1366/// array_pod_sort - This sorts an array with the specified start and end
1367/// extent. This is just like std::sort, except that it calls qsort instead of
1368/// using an inlined template. qsort is slightly slower than std::sort, but
1369/// most sorts are not performance critical in LLVM and std::sort has to be
1370/// template instantiated for each type, leading to significant measured code
1371/// bloat. This function should generally be used instead of std::sort where
1372/// possible.
1373///
1374/// This function assumes that you have simple POD-like types that can be
1375/// compared with std::less and can be moved with memcpy. If this isn't true,
1376/// you should use std::sort.
1377///
1378/// NOTE: If qsort_r were portable, we could allow a custom comparator and
1379/// default to std::less.
1380template<class IteratorTy>
1381inline void array_pod_sort(IteratorTy Start, IteratorTy End) {
1382 // Don't inefficiently call qsort with one element or trigger undefined
1383 // behavior with an empty sequence.
1384 auto NElts = End - Start;
1385 if (NElts <= 1) return;
1386#ifdef EXPENSIVE_CHECKS
1387 detail::presortShuffle<IteratorTy>(Start, End);
1388#endif
1389 qsort(&*Start, NElts, sizeof(*Start), get_array_pod_sort_comparator(*Start));
1390}
1391
1392template <class IteratorTy>
1393inline void array_pod_sort(
1394 IteratorTy Start, IteratorTy End,
1395 int (*Compare)(
1396 const typename std::iterator_traits<IteratorTy>::value_type *,
1397 const typename std::iterator_traits<IteratorTy>::value_type *)) {
1398 // Don't inefficiently call qsort with one element or trigger undefined
1399 // behavior with an empty sequence.
1400 auto NElts = End - Start;
1401 if (NElts <= 1) return;
1402#ifdef EXPENSIVE_CHECKS
1403 detail::presortShuffle<IteratorTy>(Start, End);
1404#endif
1405 qsort(&*Start, NElts, sizeof(*Start),
1406 reinterpret_cast<int (*)(const void *, const void *)>(Compare));
1407}
1408
1409namespace detail {
1410template <typename T>
1411// We can use qsort if the iterator type is a pointer and the underlying value
1412// is trivially copyable.
1413using sort_trivially_copyable = conjunction<
1414 std::is_pointer<T>,
1415 std::is_trivially_copyable<typename std::iterator_traits<T>::value_type>>;
1416} // namespace detail
1417
1418// Provide wrappers to std::sort which shuffle the elements before sorting
1419// to help uncover non-deterministic behavior (PR35135).
1420template <typename IteratorTy,
1421 std::enable_if_t<!detail::sort_trivially_copyable<IteratorTy>::value,
1422 int> = 0>
1423inline void sort(IteratorTy Start, IteratorTy End) {
1424#ifdef EXPENSIVE_CHECKS
1425 detail::presortShuffle<IteratorTy>(Start, End);
1426#endif
1427 std::sort(Start, End);
1428}
1429
1430// Forward trivially copyable types to array_pod_sort. This avoids a large
1431// amount of code bloat for a minor performance hit.
1432template <typename IteratorTy,
1433 std::enable_if_t<detail::sort_trivially_copyable<IteratorTy>::value,
1434 int> = 0>
1435inline void sort(IteratorTy Start, IteratorTy End) {
1436 array_pod_sort(Start, End);
1437}
1438
1439template <typename Container> inline void sort(Container &&C) {
1440 llvm::sort(adl_begin(C), adl_end(C));
1441}
1442
1443template <typename IteratorTy, typename Compare>
1444inline void sort(IteratorTy Start, IteratorTy End, Compare Comp) {
1445#ifdef EXPENSIVE_CHECKS
1446 detail::presortShuffle<IteratorTy>(Start, End);
1447#endif
1448 std::sort(Start, End, Comp);
1449}
1450
1451template <typename Container, typename Compare>
1452inline void sort(Container &&C, Compare Comp) {
1453 llvm::sort(adl_begin(C), adl_end(C), Comp);
1454}
1455
1456//===----------------------------------------------------------------------===//
1457// Extra additions to <algorithm>
1458//===----------------------------------------------------------------------===//
1459
1460/// Get the size of a range. This is a wrapper function around std::distance
1461/// which is only enabled when the operation is O(1).
1462template <typename R>
1463auto size(R &&Range,
1464 std::enable_if_t<
1465 std::is_base_of<std::random_access_iterator_tag,
1466 typename std::iterator_traits<decltype(
1467 Range.begin())>::iterator_category>::value,
1468 void> * = nullptr) {
1469 return std::distance(Range.begin(), Range.end());
1470}
1471
1472/// Provide wrappers to std::for_each which take ranges instead of having to
1473/// pass begin/end explicitly.
1474template <typename R, typename UnaryFunction>
1475UnaryFunction for_each(R &&Range, UnaryFunction F) {
1476 return std::for_each(adl_begin(Range), adl_end(Range), F);
1477}
1478
1479/// Provide wrappers to std::all_of which take ranges instead of having to pass
1480/// begin/end explicitly.
1481template <typename R, typename UnaryPredicate>
1482bool all_of(R &&Range, UnaryPredicate P) {
1483 return std::all_of(adl_begin(Range), adl_end(Range), P);
1484}
1485
1486/// Provide wrappers to std::any_of which take ranges instead of having to pass
1487/// begin/end explicitly.
1488template <typename R, typename UnaryPredicate>
1489bool any_of(R &&Range, UnaryPredicate P) {
1490 return std::any_of(adl_begin(Range), adl_end(Range), P);
1491}
1492
1493/// Provide wrappers to std::none_of which take ranges instead of having to pass
1494/// begin/end explicitly.
1495template <typename R, typename UnaryPredicate>
1496bool none_of(R &&Range, UnaryPredicate P) {
1497 return std::none_of(adl_begin(Range), adl_end(Range), P);
1498}
1499
1500/// Provide wrappers to std::find which take ranges instead of having to pass
1501/// begin/end explicitly.
1502template <typename R, typename T> auto find(R &&Range, const T &Val) {
1503 return std::find(adl_begin(Range), adl_end(Range), Val);
1504}
1505
1506/// Provide wrappers to std::find_if which take ranges instead of having to pass
1507/// begin/end explicitly.
1508template <typename R, typename UnaryPredicate>
1509auto find_if(R &&Range, UnaryPredicate P) {
1510 return std::find_if(adl_begin(Range), adl_end(Range), P);
1511}
1512
1513template <typename R, typename UnaryPredicate>
1514auto find_if_not(R &&Range, UnaryPredicate P) {
1515 return std::find_if_not(adl_begin(Range), adl_end(Range), P);
1516}
1517
1518/// Provide wrappers to std::remove_if which take ranges instead of having to
1519/// pass begin/end explicitly.
1520template <typename R, typename UnaryPredicate>
1521auto remove_if(R &&Range, UnaryPredicate P) {
1522 return std::remove_if(adl_begin(Range), adl_end(Range), P);
1523}
1524
1525/// Provide wrappers to std::copy_if which take ranges instead of having to
1526/// pass begin/end explicitly.
1527template <typename R, typename OutputIt, typename UnaryPredicate>
1528OutputIt copy_if(R &&Range, OutputIt Out, UnaryPredicate P) {
1529 return std::copy_if(adl_begin(Range), adl_end(Range), Out, P);
1530}
1531
1532template <typename R, typename OutputIt>
1533OutputIt copy(R &&Range, OutputIt Out) {
1534 return std::copy(adl_begin(Range), adl_end(Range), Out);
1535}
1536
1537/// Provide wrappers to std::move which take ranges instead of having to
1538/// pass begin/end explicitly.
1539template <typename R, typename OutputIt>
1540OutputIt move(R &&Range, OutputIt Out) {
1541 return std::move(adl_begin(Range), adl_end(Range), Out);
1542}
1543
1544/// Wrapper function around std::find to detect if an element exists
1545/// in a container.
1546template <typename R, typename E>
1547bool is_contained(R &&Range, const E &Element) {
1548 return std::find(adl_begin(Range), adl_end(Range), Element) != adl_end(Range);
1549}
1550
1551/// Wrapper function around std::is_sorted to check if elements in a range \p R
1552/// are sorted with respect to a comparator \p C.
1553template <typename R, typename Compare> bool is_sorted(R &&Range, Compare C) {
1554 return std::is_sorted(adl_begin(Range), adl_end(Range), C);
1555}
1556
1557/// Wrapper function around std::is_sorted to check if elements in a range \p R
1558/// are sorted in non-descending order.
1559template <typename R> bool is_sorted(R &&Range) {
1560 return std::is_sorted(adl_begin(Range), adl_end(Range));
1561}
1562
1563/// Wrapper function around std::count to count the number of times an element
1564/// \p Element occurs in the given range \p Range.
1565template <typename R, typename E> auto count(R &&Range, const E &Element) {
1566 return std::count(adl_begin(Range), adl_end(Range), Element);
1567}
1568
1569/// Wrapper function around std::count_if to count the number of times an
1570/// element satisfying a given predicate occurs in a range.
1571template <typename R, typename UnaryPredicate>
1572auto count_if(R &&Range, UnaryPredicate P) {
1573 return std::count_if(adl_begin(Range), adl_end(Range), P);
1574}
1575
1576/// Wrapper function around std::transform to apply a function to a range and
1577/// store the result elsewhere.
1578template <typename R, typename OutputIt, typename UnaryFunction>
1579OutputIt transform(R &&Range, OutputIt d_first, UnaryFunction F) {
1580 return std::transform(adl_begin(Range), adl_end(Range), d_first, F);
1581}
1582
1583/// Provide wrappers to std::partition which take ranges instead of having to
1584/// pass begin/end explicitly.
1585template <typename R, typename UnaryPredicate>
1586auto partition(R &&Range, UnaryPredicate P) {
1587 return std::partition(adl_begin(Range), adl_end(Range), P);
1588}
1589
1590/// Provide wrappers to std::lower_bound which take ranges instead of having to
1591/// pass begin/end explicitly.
1592template <typename R, typename T> auto lower_bound(R &&Range, T &&Value) {
1593 return std::lower_bound(adl_begin(Range), adl_end(Range),
1594 std::forward<T>(Value));
1595}
1596
1597template <typename R, typename T, typename Compare>
1598auto lower_bound(R &&Range, T &&Value, Compare C) {
1599 return std::lower_bound(adl_begin(Range), adl_end(Range),
1600 std::forward<T>(Value), C);
1601}
1602
1603/// Provide wrappers to std::upper_bound which take ranges instead of having to
1604/// pass begin/end explicitly.
1605template <typename R, typename T> auto upper_bound(R &&Range, T &&Value) {
1606 return std::upper_bound(adl_begin(Range), adl_end(Range),
1607 std::forward<T>(Value));
1608}
1609
1610template <typename R, typename T, typename Compare>
1611auto upper_bound(R &&Range, T &&Value, Compare C) {
1612 return std::upper_bound(adl_begin(Range), adl_end(Range),
1613 std::forward<T>(Value), C);
1614}
1615
1616template <typename R>
1617void stable_sort(R &&Range) {
1618 std::stable_sort(adl_begin(Range), adl_end(Range));
1619}
1620
1621template <typename R, typename Compare>
1622void stable_sort(R &&Range, Compare C) {
1623 std::stable_sort(adl_begin(Range), adl_end(Range), C);
1624}
1625
1626/// Binary search for the first iterator in a range where a predicate is false.
1627/// Requires that C is always true below some limit, and always false above it.
1628template <typename R, typename Predicate,
1629 typename Val = decltype(*adl_begin(std::declval<R>()))>
1630auto partition_point(R &&Range, Predicate P) {
1631 return std::partition_point(adl_begin(Range), adl_end(Range), P);
1632}
1633
1634/// Wrapper function around std::equal to detect if all elements
1635/// in a container are same.
1636template <typename R>
1637bool is_splat(R &&Range) {
1638 size_t range_size = size(Range);
1639 return range_size != 0 && (range_size == 1 ||
1640 std::equal(adl_begin(Range) + 1, adl_end(Range), adl_begin(Range)));
1641}
1642
1643/// Provide a container algorithm similar to C++ Library Fundamentals v2's
1644/// `erase_if` which is equivalent to:
1645///
1646/// C.erase(remove_if(C, pred), C.end());
1647///
1648/// This version works for any container with an erase method call accepting
1649/// two iterators.
1650template <typename Container, typename UnaryPredicate>
1651void erase_if(Container &C, UnaryPredicate P) {
1652 C.erase(remove_if(C, P), C.end());
1653}
1654
1655/// Wrapper function to remove a value from a container:
1656///
1657/// C.erase(remove(C.begin(), C.end(), V), C.end());
1658template <typename Container, typename ValueType>
1659void erase_value(Container &C, ValueType V) {
1660 C.erase(std::remove(C.begin(), C.end(), V), C.end());
1661}
1662
1663/// Wrapper function to append a range to a container.
1664///
1665/// C.insert(C.end(), R.begin(), R.end());
1666template <typename Container, typename Range>
1667inline void append_range(Container &C, Range &&R) {
1668 C.insert(C.end(), R.begin(), R.end());
1669}
1670
1671/// Given a sequence container Cont, replace the range [ContIt, ContEnd) with
1672/// the range [ValIt, ValEnd) (which is not from the same container).
1673template<typename Container, typename RandomAccessIterator>
1674void replace(Container &Cont, typename Container::iterator ContIt,
1675 typename Container::iterator ContEnd, RandomAccessIterator ValIt,
1676 RandomAccessIterator ValEnd) {
1677 while (true) {
1678 if (ValIt == ValEnd) {
1679 Cont.erase(ContIt, ContEnd);
1680 return;
1681 } else if (ContIt == ContEnd) {
1682 Cont.insert(ContIt, ValIt, ValEnd);
1683 return;
1684 }
1685 *ContIt++ = *ValIt++;
1686 }
1687}
1688
1689/// Given a sequence container Cont, replace the range [ContIt, ContEnd) with
1690/// the range R.
1691template<typename Container, typename Range = std::initializer_list<
1692 typename Container::value_type>>
1693void replace(Container &Cont, typename Container::iterator ContIt,
1694 typename Container::iterator ContEnd, Range R) {
1695 replace(Cont, ContIt, ContEnd, R.begin(), R.end());
1696}
1697
1698/// An STL-style algorithm similar to std::for_each that applies a second
1699/// functor between every pair of elements.
1700///
1701/// This provides the control flow logic to, for example, print a
1702/// comma-separated list:
1703/// \code
1704/// interleave(names.begin(), names.end(),
1705/// [&](StringRef name) { os << name; },
1706/// [&] { os << ", "; });
1707/// \endcode
1708template <typename ForwardIterator, typename UnaryFunctor,
1709 typename NullaryFunctor,
1710 typename = typename std::enable_if<
1711 !std::is_constructible<StringRef, UnaryFunctor>::value &&
1712 !std::is_constructible<StringRef, NullaryFunctor>::value>::type>
1713inline void interleave(ForwardIterator begin, ForwardIterator end,
1714 UnaryFunctor each_fn, NullaryFunctor between_fn) {
1715 if (begin == end)
1716 return;
1717 each_fn(*begin);
1718 ++begin;
1719 for (; begin != end; ++begin) {
1720 between_fn();
1721 each_fn(*begin);
1722 }
1723}
1724
1725template <typename Container, typename UnaryFunctor, typename NullaryFunctor,
1726 typename = typename std::enable_if<
1727 !std::is_constructible<StringRef, UnaryFunctor>::value &&
1728 !std::is_constructible<StringRef, NullaryFunctor>::value>::type>
1729inline void interleave(const Container &c, UnaryFunctor each_fn,
1730 NullaryFunctor between_fn) {
1731 interleave(c.begin(), c.end(), each_fn, between_fn);
1732}
1733
1734/// Overload of interleave for the common case of string separator.
1735template <typename Container, typename UnaryFunctor, typename StreamT,
1736 typename T = detail::ValueOfRange<Container>>
1737inline void interleave(const Container &c, StreamT &os, UnaryFunctor each_fn,
1738 const StringRef &separator) {
1739 interleave(c.begin(), c.end(), each_fn, [&] { os << separator; });
1740}
1741template <typename Container, typename StreamT,
1742 typename T = detail::ValueOfRange<Container>>
1743inline void interleave(const Container &c, StreamT &os,
1744 const StringRef &separator) {
1745 interleave(
1746 c, os, [&](const T &a) { os << a; }, separator);
1747}
1748
1749template <typename Container, typename UnaryFunctor, typename StreamT,
1750 typename T = detail::ValueOfRange<Container>>
1751inline void interleaveComma(const Container &c, StreamT &os,
1752 UnaryFunctor each_fn) {
1753 interleave(c, os, each_fn, ", ");
1754}
1755template <typename Container, typename StreamT,
1756 typename T = detail::ValueOfRange<Container>>
1757inline void interleaveComma(const Container &c, StreamT &os) {
1758 interleaveComma(c, os, [&](const T &a) { os << a; });
1759}
1760
1761//===----------------------------------------------------------------------===//
1762// Extra additions to <memory>
1763//===----------------------------------------------------------------------===//
1764
1765struct FreeDeleter {
1766 void operator()(void* v) {
1767 ::free(v);
1768 }
1769};
1770
1771template<typename First, typename Second>
1772struct pair_hash {
1773 size_t operator()(const std::pair<First, Second> &P) const {
1774 return std::hash<First>()(P.first) * 31 + std::hash<Second>()(P.second);
1775 }
1776};
1777
1778/// Binary functor that adapts to any other binary functor after dereferencing
1779/// operands.
1780template <typename T> struct deref {
1781 T func;
1782
1783 // Could be further improved to cope with non-derivable functors and
1784 // non-binary functors (should be a variadic template member function
1785 // operator()).
1786 template <typename A, typename B> auto operator()(A &lhs, B &rhs) const {
1787 assert(lhs);
1788 assert(rhs);
1789 return func(*lhs, *rhs);
1790 }
1791};
1792
1793namespace detail {
1794
1795template <typename R> class enumerator_iter;
1796
1797template <typename R> struct result_pair {
1798 using value_reference =
1799 typename std::iterator_traits<IterOfRange<R>>::reference;
1800
1801 friend class enumerator_iter<R>;
1802
1803 result_pair() = default;
1804 result_pair(std::size_t Index, IterOfRange<R> Iter)
1805 : Index(Index), Iter(Iter) {}
1806
1807 result_pair(const result_pair<R> &Other)
1808 : Index(Other.Index), Iter(Other.Iter) {}
1809 result_pair &operator=(const result_pair &Other) {
1810 Index = Other.Index;
1811 Iter = Other.Iter;
1812 return *this;
1813 }
1814
1815 std::size_t index() const { return Index; }
1816 const value_reference value() const { return *Iter; }
1817 value_reference value() { return *Iter; }
1818
1819private:
1820 std::size_t Index = std::numeric_limits<std::size_t>::max();
1821 IterOfRange<R> Iter;
1822};
1823
1824template <typename R>
1825class enumerator_iter
1826 : public iterator_facade_base<
1827 enumerator_iter<R>, std::forward_iterator_tag, result_pair<R>,
1828 typename std::iterator_traits<IterOfRange<R>>::difference_type,
1829 typename std::iterator_traits<IterOfRange<R>>::pointer,
1830 typename std::iterator_traits<IterOfRange<R>>::reference> {
1831 using result_type = result_pair<R>;
1832
1833public:
1834 explicit enumerator_iter(IterOfRange<R> EndIter)
1835 : Result(std::numeric_limits<size_t>::max(), EndIter) {}
1836
1837 enumerator_iter(std::size_t Index, IterOfRange<R> Iter)
1838 : Result(Index, Iter) {}
1839
1840 result_type &operator*() { return Result; }
1841 const result_type &operator*() const { return Result; }
1842
1843 enumerator_iter &operator++() {
1844 assert(Result.Index != std::numeric_limits<size_t>::max());
1845 ++Result.Iter;
1846 ++Result.Index;
1847 return *this;
1848 }
1849
1850 bool operator==(const enumerator_iter &RHS) const {
1851 // Don't compare indices here, only iterators. It's possible for an end
1852 // iterator to have different indices depending on whether it was created
1853 // by calling std::end() versus incrementing a valid iterator.
1854 return Result.Iter == RHS.Result.Iter;
1855 }
1856
1857 enumerator_iter(const enumerator_iter &Other) : Result(Other.Result) {}
1858 enumerator_iter &operator=(const enumerator_iter &Other) {
1859 Result = Other.Result;
1860 return *this;
1861 }
1862
1863private:
1864 result_type Result;
1865};
1866
1867template <typename R> class enumerator {
1868public:
1869 explicit enumerator(R &&Range) : TheRange(std::forward<R>(Range)) {}
1870
1871 enumerator_iter<R> begin() {
1872 return enumerator_iter<R>(0, std::begin(TheRange));
1873 }
1874
1875 enumerator_iter<R> end() {
1876 return enumerator_iter<R>(std::end(TheRange));
1877 }
1878
1879private:
1880 R TheRange;
1881};
1882
1883} // end namespace detail
1884
1885/// Given an input range, returns a new range whose values are are pair (A,B)
1886/// such that A is the 0-based index of the item in the sequence, and B is
1887/// the value from the original sequence. Example:
1888///
1889/// std::vector<char> Items = {'A', 'B', 'C', 'D'};
1890/// for (auto X : enumerate(Items)) {
1891/// printf("Item %d - %c\n", X.index(), X.value());
1892/// }
1893///
1894/// Output:
1895/// Item 0 - A
1896/// Item 1 - B
1897/// Item 2 - C
1898/// Item 3 - D
1899///
1900template <typename R> detail::enumerator<R> enumerate(R &&TheRange) {
1901 return detail::enumerator<R>(std::forward<R>(TheRange));
1902}
1903
1904namespace detail {
1905
1906template <typename F, typename Tuple, std::size_t... I>
1907decltype(auto) apply_tuple_impl(F &&f, Tuple &&t, std::index_sequence<I...>) {
1908 return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...);
1909}
1910
1911} // end namespace detail
1912
1913/// Given an input tuple (a1, a2, ..., an), pass the arguments of the
1914/// tuple variadically to f as if by calling f(a1, a2, ..., an) and
1915/// return the result.
1916template <typename F, typename Tuple>
1917decltype(auto) apply_tuple(F &&f, Tuple &&t) {
1918 using Indices = std::make_index_sequence<
1919 std::tuple_size<typename std::decay<Tuple>::type>::value>;
1920
1921 return detail::apply_tuple_impl(std::forward<F>(f), std::forward<Tuple>(t),
1922 Indices{});
1923}
1924
1925/// Return true if the sequence [Begin, End) has exactly N items. Runs in O(N)
1926/// time. Not meant for use with random-access iterators.
1927/// Can optionally take a predicate to filter lazily some items.
1928template <typename IterTy,
1929 typename Pred = bool (*)(const decltype(*std::declval<IterTy>()) &)>
1930bool hasNItems(
1931 IterTy &&Begin, IterTy &&End, unsigned N,
1932 Pred &&ShouldBeCounted =
1933 [](const decltype(*std::declval<IterTy>()) &) { return true; },
1934 std::enable_if_t<
1935 !std::is_base_of<std::random_access_iterator_tag,
1936 typename std::iterator_traits<std::remove_reference_t<
1937 decltype(Begin)>>::iterator_category>::value,
1938 void> * = nullptr) {
1939 for (; N; ++Begin) {
1940 if (Begin == End)
1941 return false; // Too few.
1942 N -= ShouldBeCounted(*Begin);
1943 }
1944 for (; Begin != End; ++Begin)
1945 if (ShouldBeCounted(*Begin))
1946 return false; // Too many.
1947 return true;
1948}
1949
1950/// Return true if the sequence [Begin, End) has N or more items. Runs in O(N)
1951/// time. Not meant for use with random-access iterators.
1952/// Can optionally take a predicate to lazily filter some items.
1953template <typename IterTy,
1954 typename Pred = bool (*)(const decltype(*std::declval<IterTy>()) &)>
1955bool hasNItemsOrMore(
1956 IterTy &&Begin, IterTy &&End, unsigned N,
1957 Pred &&ShouldBeCounted =
1958 [](const decltype(*std::declval<IterTy>()) &) { return true; },
1959 std::enable_if_t<
1960 !std::is_base_of<std::random_access_iterator_tag,
1961 typename std::iterator_traits<std::remove_reference_t<
1962 decltype(Begin)>>::iterator_category>::value,
1963 void> * = nullptr) {
1964 for (; N; ++Begin) {
1965 if (Begin == End)
1966 return false; // Too few.
1967 N -= ShouldBeCounted(*Begin);
1968 }
1969 return true;
1970}
1971
1972/// Returns true if the sequence [Begin, End) has N or less items. Can
1973/// optionally take a predicate to lazily filter some items.
1974template <typename IterTy,
1975 typename Pred = bool (*)(const decltype(*std::declval<IterTy>()) &)>
1976bool hasNItemsOrLess(
1977 IterTy &&Begin, IterTy &&End, unsigned N,
1978 Pred &&ShouldBeCounted = [](const decltype(*std::declval<IterTy>()) &) {
1979 return true;
1980 }) {
1981 assert(N != std::numeric_limits<unsigned>::max());
1982 return !hasNItemsOrMore(Begin, End, N + 1, ShouldBeCounted);
1983}
1984
1985/// Returns true if the given container has exactly N items
1986template <typename ContainerTy> bool hasNItems(ContainerTy &&C, unsigned N) {
1987 return hasNItems(std::begin(C), std::end(C), N);
1988}
1989
1990/// Returns true if the given container has N or more items
1991template <typename ContainerTy>
1992bool hasNItemsOrMore(ContainerTy &&C, unsigned N) {
1993 return hasNItemsOrMore(std::begin(C), std::end(C), N);
1994}
1995
1996/// Returns true if the given container has N or less items
1997template <typename ContainerTy>
1998bool hasNItemsOrLess(ContainerTy &&C, unsigned N) {
1999 return hasNItemsOrLess(std::begin(C), std::end(C), N);
2000}
2001
2002/// Returns a raw pointer that represents the same address as the argument.
2003///
2004/// This implementation can be removed once we move to C++20 where it's defined
2005/// as std::to_address().
2006///
2007/// The std::pointer_traits<>::to_address(p) variations of these overloads has
2008/// not been implemented.
2009template <class Ptr> auto to_address(const Ptr &P) { return P.operator->(); }
2010template <class T> constexpr T *to_address(T *P) { return P; }
2011
2012} // end namespace llvm
2013
2014#endif // LLVM_ADT_STLEXTRAS_H
2015