1 //===- llvm/ADT/STLExtras.h - Useful STL related functions ------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains some templates that are useful if you are working with the
13 // No library is required when using these functions.
15 //===----------------------------------------------------------------------===//
17 #ifndef LLVM_ADT_STLEXTRAS_H
18 #define LLVM_ADT_STLEXTRAS_H
20 #include <algorithm> // for std::all_of
22 #include <cstddef> // for std::size_t
23 #include <cstdlib> // for qsort
29 #include <utility> // for std::pair
31 #include "llvm/ADT/Optional.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/iterator.h"
34 #include "llvm/ADT/iterator_range.h"
35 #include "llvm/Support/Compiler.h"
36 #include "llvm/Support/ErrorHandling.h"
40 // Only used by compiler if both template types are the same. Useful when
41 // using SFINAE to test for the existence of member functions.
42 template <typename T, T> struct SameType;
46 template <typename RangeT>
47 using IterOfRange = decltype(std::begin(std::declval<RangeT &>()));
49 template <typename RangeT>
50 using ValueOfRange = typename std::remove_reference<decltype(
51 *std::begin(std::declval<RangeT &>()))>::type;
53 } // End detail namespace
55 //===----------------------------------------------------------------------===//
56 // Extra additions to <functional>
57 //===----------------------------------------------------------------------===//
60 struct identity : public std::unary_function<Ty, Ty> {
61 Ty &operator()(Ty &self) const {
64 const Ty &operator()(const Ty &self) const {
70 struct less_ptr : public std::binary_function<Ty, Ty, bool> {
71 bool operator()(const Ty* left, const Ty* right) const {
72 return *left < *right;
77 struct greater_ptr : public std::binary_function<Ty, Ty, bool> {
78 bool operator()(const Ty* left, const Ty* right) const {
79 return *right < *left;
83 /// An efficient, type-erasing, non-owning reference to a callable. This is
84 /// intended for use as the type of a function parameter that is not used
85 /// after the function in question returns.
87 /// This class does not own the callable, so it is not in general safe to store
89 template<typename Fn> class function_ref;
91 template<typename Ret, typename ...Params>
92 class function_ref<Ret(Params...)> {
93 Ret (*callback)(intptr_t callable, Params ...params);
96 template<typename Callable>
97 static Ret callback_fn(intptr_t callable, Params ...params) {
98 return (*reinterpret_cast<Callable*>(callable))(
99 std::forward<Params>(params)...);
103 function_ref() : callback(nullptr) {}
105 template <typename Callable>
106 function_ref(Callable &&callable,
107 typename std::enable_if<
108 !std::is_same<typename std::remove_reference<Callable>::type,
109 function_ref>::value>::type * = nullptr)
110 : callback(callback_fn<typename std::remove_reference<Callable>::type>),
111 callable(reinterpret_cast<intptr_t>(&callable)) {}
112 Ret operator()(Params ...params) const {
113 return callback(callable, std::forward<Params>(params)...);
116 operator bool() const { return callback; }
119 // deleter - Very very very simple method that is used to invoke operator
120 // delete on something. It is used like this:
122 // for_each(V.begin(), B.end(), deleter<Interval>);
125 inline void deleter(T *Ptr) {
131 //===----------------------------------------------------------------------===//
132 // Extra additions to <iterator>
133 //===----------------------------------------------------------------------===//
135 // mapped_iterator - This is a simple iterator adapter that causes a function to
136 // be applied whenever operator* is invoked on the iterator.
138 template <class RootIt, class UnaryFunc>
139 class mapped_iterator {
143 typedef typename std::iterator_traits<RootIt>::iterator_category
145 typedef typename std::iterator_traits<RootIt>::difference_type
147 typedef decltype(std::declval<UnaryFunc>()(*std::declval<RootIt>()))
150 typedef void pointer;
151 //typedef typename UnaryFunc::result_type *pointer;
152 typedef void reference; // Can't modify value returned by fn
154 typedef RootIt iterator_type;
156 inline const RootIt &getCurrent() const { return current; }
157 inline const UnaryFunc &getFunc() const { return Fn; }
159 inline explicit mapped_iterator(const RootIt &I, UnaryFunc F)
160 : current(I), Fn(F) {}
162 inline value_type operator*() const { // All this work to do this
163 return Fn(*current); // little change
166 mapped_iterator &operator++() {
170 mapped_iterator &operator--() {
174 mapped_iterator operator++(int) {
175 mapped_iterator __tmp = *this;
179 mapped_iterator operator--(int) {
180 mapped_iterator __tmp = *this;
184 mapped_iterator operator+(difference_type n) const {
185 return mapped_iterator(current + n, Fn);
187 mapped_iterator &operator+=(difference_type n) {
191 mapped_iterator operator-(difference_type n) const {
192 return mapped_iterator(current - n, Fn);
194 mapped_iterator &operator-=(difference_type n) {
198 reference operator[](difference_type n) const { return *(*this + n); }
200 bool operator!=(const mapped_iterator &X) const { return !operator==(X); }
201 bool operator==(const mapped_iterator &X) const {
202 return current == X.current;
204 bool operator<(const mapped_iterator &X) const { return current < X.current; }
206 difference_type operator-(const mapped_iterator &X) const {
207 return current - X.current;
211 template <class Iterator, class Func>
212 inline mapped_iterator<Iterator, Func>
213 operator+(typename mapped_iterator<Iterator, Func>::difference_type N,
214 const mapped_iterator<Iterator, Func> &X) {
215 return mapped_iterator<Iterator, Func>(X.getCurrent() - N, X.getFunc());
219 // map_iterator - Provide a convenient way to create mapped_iterators, just like
220 // make_pair is useful for creating pairs...
222 template <class ItTy, class FuncTy>
223 inline mapped_iterator<ItTy, FuncTy> map_iterator(const ItTy &I, FuncTy F) {
224 return mapped_iterator<ItTy, FuncTy>(I, F);
227 /// Helper to determine if type T has a member called rbegin().
228 template <typename Ty> class has_rbegin_impl {
232 template <typename Inner>
233 static yes& test(Inner *I, decltype(I->rbegin()) * = nullptr);
236 static no& test(...);
239 static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
242 /// Metafunction to determine if T& or T has a member called rbegin().
243 template <typename Ty>
244 struct has_rbegin : has_rbegin_impl<typename std::remove_reference<Ty>::type> {
247 // Returns an iterator_range over the given container which iterates in reverse.
248 // Note that the container must have rbegin()/rend() methods for this to work.
249 template <typename ContainerTy>
250 auto reverse(ContainerTy &&C,
251 typename std::enable_if<has_rbegin<ContainerTy>::value>::type * =
252 nullptr) -> decltype(make_range(C.rbegin(), C.rend())) {
253 return make_range(C.rbegin(), C.rend());
256 // Returns a std::reverse_iterator wrapped around the given iterator.
257 template <typename IteratorTy>
258 std::reverse_iterator<IteratorTy> make_reverse_iterator(IteratorTy It) {
259 return std::reverse_iterator<IteratorTy>(It);
262 // Returns an iterator_range over the given container which iterates in reverse.
263 // Note that the container must have begin()/end() methods which return
264 // bidirectional iterators for this to work.
265 template <typename ContainerTy>
268 typename std::enable_if<!has_rbegin<ContainerTy>::value>::type * = nullptr)
269 -> decltype(make_range(llvm::make_reverse_iterator(std::end(C)),
270 llvm::make_reverse_iterator(std::begin(C)))) {
271 return make_range(llvm::make_reverse_iterator(std::end(C)),
272 llvm::make_reverse_iterator(std::begin(C)));
275 /// An iterator adaptor that filters the elements of given inner iterators.
277 /// The predicate parameter should be a callable object that accepts the wrapped
278 /// iterator's reference type and returns a bool. When incrementing or
279 /// decrementing the iterator, it will call the predicate on each element and
280 /// skip any where it returns false.
283 /// int A[] = { 1, 2, 3, 4 };
284 /// auto R = make_filter_range(A, [](int N) { return N % 2 == 1; });
285 /// // R contains { 1, 3 }.
287 template <typename WrappedIteratorT, typename PredicateT>
288 class filter_iterator
289 : public iterator_adaptor_base<
290 filter_iterator<WrappedIteratorT, PredicateT>, WrappedIteratorT,
291 typename std::common_type<
292 std::forward_iterator_tag,
293 typename std::iterator_traits<
294 WrappedIteratorT>::iterator_category>::type> {
295 using BaseT = iterator_adaptor_base<
296 filter_iterator<WrappedIteratorT, PredicateT>, WrappedIteratorT,
297 typename std::common_type<
298 std::forward_iterator_tag,
299 typename std::iterator_traits<WrappedIteratorT>::iterator_category>::
303 WrappedIteratorT End;
307 Optional<PayloadType> Payload;
309 void findNextValid() {
310 assert(Payload && "Payload should be engaged when findNextValid is called");
311 while (this->I != Payload->End && !Payload->Pred(*this->I))
315 // Construct the begin iterator. The begin iterator requires to know where end
316 // is, so that it can properly stop when it hits end.
317 filter_iterator(WrappedIteratorT Begin, WrappedIteratorT End, PredicateT Pred)
318 : BaseT(std::move(Begin)),
319 Payload(PayloadType{std::move(End), std::move(Pred)}) {
323 // Construct the end iterator. It's not incrementable, so Payload doesn't
324 // have to be engaged.
325 filter_iterator(WrappedIteratorT End) : BaseT(End) {}
328 using BaseT::operator++;
330 filter_iterator &operator++() {
336 template <typename RT, typename PT>
337 friend iterator_range<filter_iterator<detail::IterOfRange<RT>, PT>>
338 make_filter_range(RT &&, PT);
341 /// Convenience function that takes a range of elements and a predicate,
342 /// and return a new filter_iterator range.
344 /// FIXME: Currently if RangeT && is a rvalue reference to a temporary, the
345 /// lifetime of that temporary is not kept by the returned range object, and the
346 /// temporary is going to be dropped on the floor after the make_iterator_range
347 /// full expression that contains this function call.
348 template <typename RangeT, typename PredicateT>
349 iterator_range<filter_iterator<detail::IterOfRange<RangeT>, PredicateT>>
350 make_filter_range(RangeT &&Range, PredicateT Pred) {
351 using FilterIteratorT =
352 filter_iterator<detail::IterOfRange<RangeT>, PredicateT>;
353 return make_range(FilterIteratorT(std::begin(std::forward<RangeT>(Range)),
354 std::end(std::forward<RangeT>(Range)),
356 FilterIteratorT(std::end(std::forward<RangeT>(Range))));
359 // forward declarations required by zip_shortest/zip_first
360 template <typename R, typename UnaryPredicate>
361 bool all_of(R &&range, UnaryPredicate P);
363 template <size_t... I> struct index_sequence;
365 template <class... Ts> struct index_sequence_for;
370 // We have to alias this since inlining the actual type at the usage site
371 // in the parameter list of iterator_facade_base<> below ICEs MSVC 2017.
372 template<typename... Iters> struct ZipTupleType {
373 typedef std::tuple<decltype(*declval<Iters>())...> type;
376 template <typename ZipType, typename... Iters>
377 using zip_traits = iterator_facade_base<
378 ZipType, typename std::common_type<std::bidirectional_iterator_tag,
379 typename std::iterator_traits<
380 Iters>::iterator_category...>::type,
381 // ^ TODO: Implement random access methods.
382 typename ZipTupleType<Iters...>::type,
383 typename std::iterator_traits<typename std::tuple_element<
384 0, std::tuple<Iters...>>::type>::difference_type,
385 // ^ FIXME: This follows boost::make_zip_iterator's assumption that all
386 // inner iterators have the same difference_type. It would fail if, for
387 // instance, the second field's difference_type were non-numeric while the
389 typename ZipTupleType<Iters...>::type *,
390 typename ZipTupleType<Iters...>::type>;
392 template <typename ZipType, typename... Iters>
393 struct zip_common : public zip_traits<ZipType, Iters...> {
394 using Base = zip_traits<ZipType, Iters...>;
395 using value_type = typename Base::value_type;
397 std::tuple<Iters...> iterators;
400 template <size_t... Ns> value_type deref(index_sequence<Ns...>) const {
401 return value_type(*std::get<Ns>(iterators)...);
404 template <size_t... Ns>
405 decltype(iterators) tup_inc(index_sequence<Ns...>) const {
406 return std::tuple<Iters...>(std::next(std::get<Ns>(iterators))...);
409 template <size_t... Ns>
410 decltype(iterators) tup_dec(index_sequence<Ns...>) const {
411 return std::tuple<Iters...>(std::prev(std::get<Ns>(iterators))...);
415 zip_common(Iters &&... ts) : iterators(std::forward<Iters>(ts)...) {}
417 value_type operator*() { return deref(index_sequence_for<Iters...>{}); }
419 const value_type operator*() const {
420 return deref(index_sequence_for<Iters...>{});
423 ZipType &operator++() {
424 iterators = tup_inc(index_sequence_for<Iters...>{});
425 return *reinterpret_cast<ZipType *>(this);
428 ZipType &operator--() {
429 static_assert(Base::IsBidirectional,
430 "All inner iterators must be at least bidirectional.");
431 iterators = tup_dec(index_sequence_for<Iters...>{});
432 return *reinterpret_cast<ZipType *>(this);
436 template <typename... Iters>
437 struct zip_first : public zip_common<zip_first<Iters...>, Iters...> {
438 using Base = zip_common<zip_first<Iters...>, Iters...>;
440 bool operator==(const zip_first<Iters...> &other) const {
441 return std::get<0>(this->iterators) == std::get<0>(other.iterators);
444 zip_first(Iters &&... ts) : Base(std::forward<Iters>(ts)...) {}
447 template <typename... Iters>
448 class zip_shortest : public zip_common<zip_shortest<Iters...>, Iters...> {
449 template <size_t... Ns>
450 bool test(const zip_shortest<Iters...> &other, index_sequence<Ns...>) const {
451 return all_of(std::initializer_list<bool>{std::get<Ns>(this->iterators) !=
452 std::get<Ns>(other.iterators)...},
457 using Base = zip_common<zip_shortest<Iters...>, Iters...>;
459 bool operator==(const zip_shortest<Iters...> &other) const {
460 return !test(other, index_sequence_for<Iters...>{});
463 zip_shortest(Iters &&... ts) : Base(std::forward<Iters>(ts)...) {}
466 template <template <typename...> class ItType, typename... Args> class zippy {
468 using iterator = ItType<decltype(std::begin(std::declval<Args>()))...>;
469 using iterator_category = typename iterator::iterator_category;
470 using value_type = typename iterator::value_type;
471 using difference_type = typename iterator::difference_type;
472 using pointer = typename iterator::pointer;
473 using reference = typename iterator::reference;
476 std::tuple<Args...> ts;
478 template <size_t... Ns> iterator begin_impl(index_sequence<Ns...>) const {
479 return iterator(std::begin(std::get<Ns>(ts))...);
481 template <size_t... Ns> iterator end_impl(index_sequence<Ns...>) const {
482 return iterator(std::end(std::get<Ns>(ts))...);
486 iterator begin() const { return begin_impl(index_sequence_for<Args...>{}); }
487 iterator end() const { return end_impl(index_sequence_for<Args...>{}); }
488 zippy(Args &&... ts_) : ts(std::forward<Args>(ts_)...) {}
490 } // End detail namespace
492 /// zip iterator for two or more iteratable types.
493 template <typename T, typename U, typename... Args>
494 detail::zippy<detail::zip_shortest, T, U, Args...> zip(T &&t, U &&u,
496 return detail::zippy<detail::zip_shortest, T, U, Args...>(
497 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
500 /// zip iterator that, for the sake of efficiency, assumes the first iteratee to
502 template <typename T, typename U, typename... Args>
503 detail::zippy<detail::zip_first, T, U, Args...> zip_first(T &&t, U &&u,
505 return detail::zippy<detail::zip_first, T, U, Args...>(
506 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
509 /// Iterator wrapper that concatenates sequences together.
511 /// This can concatenate different iterators, even with different types, into
512 /// a single iterator provided the value types of all the concatenated
513 /// iterators expose `reference` and `pointer` types that can be converted to
514 /// `ValueT &` and `ValueT *` respectively. It doesn't support more
515 /// interesting/customized pointer or reference types.
517 /// Currently this only supports forward or higher iterator categories as
518 /// inputs and always exposes a forward iterator interface.
519 template <typename ValueT, typename... IterTs>
520 class concat_iterator
521 : public iterator_facade_base<concat_iterator<ValueT, IterTs...>,
522 std::forward_iterator_tag, ValueT> {
523 typedef typename concat_iterator::iterator_facade_base BaseT;
525 /// We store both the current and end iterators for each concatenated
526 /// sequence in a tuple of pairs.
528 /// Note that something like iterator_range seems nice at first here, but the
529 /// range properties are of little benefit and end up getting in the way
530 /// because we need to do mutation on the current iterators.
531 std::tuple<std::pair<IterTs, IterTs>...> IterPairs;
533 /// Attempts to increment a specific iterator.
535 /// Returns true if it was able to increment the iterator. Returns false if
536 /// the iterator is already at the end iterator.
537 template <size_t Index> bool incrementHelper() {
538 auto &IterPair = std::get<Index>(IterPairs);
539 if (IterPair.first == IterPair.second)
546 /// Increments the first non-end iterator.
548 /// It is an error to call this with all iterators at the end.
549 template <size_t... Ns> void increment(index_sequence<Ns...>) {
550 // Build a sequence of functions to increment each iterator if possible.
551 bool (concat_iterator::*IncrementHelperFns[])() = {
552 &concat_iterator::incrementHelper<Ns>...};
554 // Loop over them, and stop as soon as we succeed at incrementing one.
555 for (auto &IncrementHelperFn : IncrementHelperFns)
556 if ((this->*IncrementHelperFn)())
559 llvm_unreachable("Attempted to increment an end concat iterator!");
562 /// Returns null if the specified iterator is at the end. Otherwise,
563 /// dereferences the iterator and returns the address of the resulting
565 template <size_t Index> ValueT *getHelper() const {
566 auto &IterPair = std::get<Index>(IterPairs);
567 if (IterPair.first == IterPair.second)
570 return &*IterPair.first;
573 /// Finds the first non-end iterator, dereferences, and returns the resulting
576 /// It is an error to call this with all iterators at the end.
577 template <size_t... Ns> ValueT &get(index_sequence<Ns...>) const {
578 // Build a sequence of functions to get from iterator if possible.
579 ValueT *(concat_iterator::*GetHelperFns[])() const = {
580 &concat_iterator::getHelper<Ns>...};
582 // Loop over them, and return the first result we find.
583 for (auto &GetHelperFn : GetHelperFns)
584 if (ValueT *P = (this->*GetHelperFn)())
587 llvm_unreachable("Attempted to get a pointer from an end concat iterator!");
591 /// Constructs an iterator from a squence of ranges.
593 /// We need the full range to know how to switch between each of the
595 template <typename... RangeTs>
596 explicit concat_iterator(RangeTs &&... Ranges)
597 : IterPairs({std::begin(Ranges), std::end(Ranges)}...) {}
599 using BaseT::operator++;
600 concat_iterator &operator++() {
601 increment(index_sequence_for<IterTs...>());
605 ValueT &operator*() const { return get(index_sequence_for<IterTs...>()); }
607 bool operator==(const concat_iterator &RHS) const {
608 return IterPairs == RHS.IterPairs;
613 /// Helper to store a sequence of ranges being concatenated and access them.
615 /// This is designed to facilitate providing actual storage when temporaries
616 /// are passed into the constructor such that we can use it as part of range
618 template <typename ValueT, typename... RangeTs> class concat_range {
620 typedef concat_iterator<ValueT,
621 decltype(std::begin(std::declval<RangeTs &>()))...>
625 std::tuple<RangeTs...> Ranges;
627 template <size_t... Ns> iterator begin_impl(index_sequence<Ns...>) {
628 return iterator(std::get<Ns>(Ranges)...);
630 template <size_t... Ns> iterator end_impl(index_sequence<Ns...>) {
631 return iterator(make_range(std::end(std::get<Ns>(Ranges)),
632 std::end(std::get<Ns>(Ranges)))...);
636 iterator begin() { return begin_impl(index_sequence_for<RangeTs...>{}); }
637 iterator end() { return end_impl(index_sequence_for<RangeTs...>{}); }
638 concat_range(RangeTs &&... Ranges)
639 : Ranges(std::forward<RangeTs>(Ranges)...) {}
643 /// Concatenated range across two or more ranges.
645 /// The desired value type must be explicitly specified.
646 template <typename ValueT, typename... RangeTs>
647 detail::concat_range<ValueT, RangeTs...> concat(RangeTs &&... Ranges) {
648 static_assert(sizeof...(RangeTs) > 1,
649 "Need more than one range to concatenate!");
650 return detail::concat_range<ValueT, RangeTs...>(
651 std::forward<RangeTs>(Ranges)...);
654 //===----------------------------------------------------------------------===//
655 // Extra additions to <utility>
656 //===----------------------------------------------------------------------===//
658 /// \brief Function object to check whether the first component of a std::pair
659 /// compares less than the first component of another std::pair.
661 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
662 return lhs.first < rhs.first;
666 /// \brief Function object to check whether the second component of a std::pair
667 /// compares less than the second component of another std::pair.
669 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
670 return lhs.second < rhs.second;
674 // A subset of N3658. More stuff can be added as-needed.
676 /// \brief Represents a compile-time sequence of integers.
677 template <class T, T... I> struct integer_sequence {
678 typedef T value_type;
680 static constexpr size_t size() { return sizeof...(I); }
683 /// \brief Alias for the common case of a sequence of size_ts.
684 template <size_t... I>
685 struct index_sequence : integer_sequence<std::size_t, I...> {};
687 template <std::size_t N, std::size_t... I>
688 struct build_index_impl : build_index_impl<N - 1, N - 1, I...> {};
689 template <std::size_t... I>
690 struct build_index_impl<0, I...> : index_sequence<I...> {};
692 /// \brief Creates a compile-time integer sequence for a parameter pack.
693 template <class... Ts>
694 struct index_sequence_for : build_index_impl<sizeof...(Ts)> {};
696 /// Utility type to build an inheritance chain that makes it easy to rank
697 /// overload candidates.
698 template <int N> struct rank : rank<N - 1> {};
699 template <> struct rank<0> {};
701 /// \brief traits class for checking whether type T is one of any of the given
702 /// types in the variadic list.
703 template <typename T, typename... Ts> struct is_one_of {
704 static const bool value = false;
707 template <typename T, typename U, typename... Ts>
708 struct is_one_of<T, U, Ts...> {
709 static const bool value =
710 std::is_same<T, U>::value || is_one_of<T, Ts...>::value;
713 /// \brief traits class for checking whether type T is a base class for all
714 /// the given types in the variadic list.
715 template <typename T, typename... Ts> struct are_base_of {
716 static const bool value = true;
719 template <typename T, typename U, typename... Ts>
720 struct are_base_of<T, U, Ts...> {
721 static const bool value =
722 std::is_base_of<T, U>::value && are_base_of<T, Ts...>::value;
725 //===----------------------------------------------------------------------===//
726 // Extra additions for arrays
727 //===----------------------------------------------------------------------===//
729 /// Find the length of an array.
730 template <class T, std::size_t N>
731 constexpr inline size_t array_lengthof(T (&)[N]) {
735 /// Adapt std::less<T> for array_pod_sort.
737 inline int array_pod_sort_comparator(const void *P1, const void *P2) {
738 if (std::less<T>()(*reinterpret_cast<const T*>(P1),
739 *reinterpret_cast<const T*>(P2)))
741 if (std::less<T>()(*reinterpret_cast<const T*>(P2),
742 *reinterpret_cast<const T*>(P1)))
747 /// get_array_pod_sort_comparator - This is an internal helper function used to
748 /// get type deduction of T right.
750 inline int (*get_array_pod_sort_comparator(const T &))
751 (const void*, const void*) {
752 return array_pod_sort_comparator<T>;
756 /// array_pod_sort - This sorts an array with the specified start and end
757 /// extent. This is just like std::sort, except that it calls qsort instead of
758 /// using an inlined template. qsort is slightly slower than std::sort, but
759 /// most sorts are not performance critical in LLVM and std::sort has to be
760 /// template instantiated for each type, leading to significant measured code
761 /// bloat. This function should generally be used instead of std::sort where
764 /// This function assumes that you have simple POD-like types that can be
765 /// compared with std::less and can be moved with memcpy. If this isn't true,
766 /// you should use std::sort.
768 /// NOTE: If qsort_r were portable, we could allow a custom comparator and
769 /// default to std::less.
770 template<class IteratorTy>
771 inline void array_pod_sort(IteratorTy Start, IteratorTy End) {
772 // Don't inefficiently call qsort with one element or trigger undefined
773 // behavior with an empty sequence.
774 auto NElts = End - Start;
775 if (NElts <= 1) return;
776 qsort(&*Start, NElts, sizeof(*Start), get_array_pod_sort_comparator(*Start));
779 template <class IteratorTy>
780 inline void array_pod_sort(
781 IteratorTy Start, IteratorTy End,
783 const typename std::iterator_traits<IteratorTy>::value_type *,
784 const typename std::iterator_traits<IteratorTy>::value_type *)) {
785 // Don't inefficiently call qsort with one element or trigger undefined
786 // behavior with an empty sequence.
787 auto NElts = End - Start;
788 if (NElts <= 1) return;
789 qsort(&*Start, NElts, sizeof(*Start),
790 reinterpret_cast<int (*)(const void *, const void *)>(Compare));
793 //===----------------------------------------------------------------------===//
794 // Extra additions to <algorithm>
795 //===----------------------------------------------------------------------===//
797 /// For a container of pointers, deletes the pointers and then clears the
799 template<typename Container>
800 void DeleteContainerPointers(Container &C) {
806 /// In a container of pairs (usually a map) whose second element is a pointer,
807 /// deletes the second elements and then clears the container.
808 template<typename Container>
809 void DeleteContainerSeconds(Container &C) {
815 /// Provide wrappers to std::all_of which take ranges instead of having to pass
816 /// begin/end explicitly.
817 template <typename R, typename UnaryPredicate>
818 bool all_of(R &&Range, UnaryPredicate P) {
819 return std::all_of(std::begin(Range), std::end(Range), P);
822 /// Provide wrappers to std::any_of which take ranges instead of having to pass
823 /// begin/end explicitly.
824 template <typename R, typename UnaryPredicate>
825 bool any_of(R &&Range, UnaryPredicate P) {
826 return std::any_of(std::begin(Range), std::end(Range), P);
829 /// Provide wrappers to std::none_of which take ranges instead of having to pass
830 /// begin/end explicitly.
831 template <typename R, typename UnaryPredicate>
832 bool none_of(R &&Range, UnaryPredicate P) {
833 return std::none_of(std::begin(Range), std::end(Range), P);
836 /// Provide wrappers to std::find which take ranges instead of having to pass
837 /// begin/end explicitly.
838 template <typename R, typename T>
839 auto find(R &&Range, const T &Val) -> decltype(std::begin(Range)) {
840 return std::find(std::begin(Range), std::end(Range), Val);
843 /// Provide wrappers to std::find_if which take ranges instead of having to pass
844 /// begin/end explicitly.
845 template <typename R, typename UnaryPredicate>
846 auto find_if(R &&Range, UnaryPredicate P) -> decltype(std::begin(Range)) {
847 return std::find_if(std::begin(Range), std::end(Range), P);
850 template <typename R, typename UnaryPredicate>
851 auto find_if_not(R &&Range, UnaryPredicate P) -> decltype(std::begin(Range)) {
852 return std::find_if_not(std::begin(Range), std::end(Range), P);
855 /// Provide wrappers to std::remove_if which take ranges instead of having to
856 /// pass begin/end explicitly.
857 template <typename R, typename UnaryPredicate>
858 auto remove_if(R &&Range, UnaryPredicate P) -> decltype(std::begin(Range)) {
859 return std::remove_if(std::begin(Range), std::end(Range), P);
862 /// Provide wrappers to std::copy_if which take ranges instead of having to
863 /// pass begin/end explicitly.
864 template <typename R, typename OutputIt, typename UnaryPredicate>
865 OutputIt copy_if(R &&Range, OutputIt Out, UnaryPredicate P) {
866 return std::copy_if(std::begin(Range), std::end(Range), Out, P);
869 /// Wrapper function around std::find to detect if an element exists
871 template <typename R, typename E>
872 bool is_contained(R &&Range, const E &Element) {
873 return std::find(std::begin(Range), std::end(Range), Element) !=
877 /// Wrapper function around std::count to count the number of times an element
878 /// \p Element occurs in the given range \p Range.
879 template <typename R, typename E>
880 auto count(R &&Range, const E &Element) -> typename std::iterator_traits<
881 decltype(std::begin(Range))>::difference_type {
882 return std::count(std::begin(Range), std::end(Range), Element);
885 /// Wrapper function around std::count_if to count the number of times an
886 /// element satisfying a given predicate occurs in a range.
887 template <typename R, typename UnaryPredicate>
888 auto count_if(R &&Range, UnaryPredicate P) -> typename std::iterator_traits<
889 decltype(std::begin(Range))>::difference_type {
890 return std::count_if(std::begin(Range), std::end(Range), P);
893 /// Wrapper function around std::transform to apply a function to a range and
894 /// store the result elsewhere.
895 template <typename R, typename OutputIt, typename UnaryPredicate>
896 OutputIt transform(R &&Range, OutputIt d_first, UnaryPredicate P) {
897 return std::transform(std::begin(Range), std::end(Range), d_first, P);
900 /// Provide wrappers to std::partition which take ranges instead of having to
901 /// pass begin/end explicitly.
902 template <typename R, typename UnaryPredicate>
903 auto partition(R &&Range, UnaryPredicate P) -> decltype(std::begin(Range)) {
904 return std::partition(std::begin(Range), std::end(Range), P);
907 /// \brief Given a range of type R, iterate the entire range and return a
908 /// SmallVector with elements of the vector. This is useful, for example,
909 /// when you want to iterate a range and then sort the results.
910 template <unsigned Size, typename R>
911 SmallVector<typename std::remove_const<detail::ValueOfRange<R>>::type, Size>
912 to_vector(R &&Range) {
913 return {std::begin(Range), std::end(Range)};
916 /// Provide a container algorithm similar to C++ Library Fundamentals v2's
917 /// `erase_if` which is equivalent to:
919 /// C.erase(remove_if(C, pred), C.end());
921 /// This version works for any container with an erase method call accepting
923 template <typename Container, typename UnaryPredicate>
924 void erase_if(Container &C, UnaryPredicate P) {
925 C.erase(remove_if(C, P), C.end());
928 //===----------------------------------------------------------------------===//
929 // Extra additions to <memory>
930 //===----------------------------------------------------------------------===//
932 // Implement make_unique according to N3656.
934 /// \brief Constructs a `new T()` with the given args and returns a
935 /// `unique_ptr<T>` which owns the object.
939 /// auto p = make_unique<int>();
940 /// auto p = make_unique<std::tuple<int, int>>(0, 1);
941 template <class T, class... Args>
942 typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
943 make_unique(Args &&... args) {
944 return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
947 /// \brief Constructs a `new T[n]` with the given args and returns a
948 /// `unique_ptr<T[]>` which owns the object.
950 /// \param n size of the new array.
954 /// auto p = make_unique<int[]>(2); // value-initializes the array with 0's.
956 typename std::enable_if<std::is_array<T>::value && std::extent<T>::value == 0,
957 std::unique_ptr<T>>::type
958 make_unique(size_t n) {
959 return std::unique_ptr<T>(new typename std::remove_extent<T>::type[n]());
962 /// This function isn't used and is only here to provide better compile errors.
963 template <class T, class... Args>
964 typename std::enable_if<std::extent<T>::value != 0>::type
965 make_unique(Args &&...) = delete;
968 void operator()(void* v) {
973 template<typename First, typename Second>
975 size_t operator()(const std::pair<First, Second> &P) const {
976 return std::hash<First>()(P.first) * 31 + std::hash<Second>()(P.second);
980 /// A functor like C++14's std::less<void> in its absence.
982 template <typename A, typename B> bool operator()(A &&a, B &&b) const {
983 return std::forward<A>(a) < std::forward<B>(b);
987 /// A functor like C++14's std::equal<void> in its absence.
989 template <typename A, typename B> bool operator()(A &&a, B &&b) const {
990 return std::forward<A>(a) == std::forward<B>(b);
994 /// Binary functor that adapts to any other binary functor after dereferencing
996 template <typename T> struct deref {
998 // Could be further improved to cope with non-derivable functors and
999 // non-binary functors (should be a variadic template member function
1001 template <typename A, typename B>
1002 auto operator()(A &lhs, B &rhs) const -> decltype(func(*lhs, *rhs)) {
1005 return func(*lhs, *rhs);
1010 template <typename R> class enumerator_iter;
1012 template <typename R> struct result_pair {
1013 friend class enumerator_iter<R>;
1015 result_pair() : Index(-1) {}
1016 result_pair(std::size_t Index, IterOfRange<R> Iter)
1017 : Index(Index), Iter(Iter) {}
1019 result_pair<R> &operator=(const result_pair<R> &Other) {
1020 Index = Other.Index;
1025 std::size_t index() const { return Index; }
1026 const ValueOfRange<R> &value() const { return *Iter; }
1027 ValueOfRange<R> &value() { return *Iter; }
1031 IterOfRange<R> Iter;
1034 template <typename R>
1035 class enumerator_iter
1036 : public iterator_facade_base<
1037 enumerator_iter<R>, std::forward_iterator_tag, result_pair<R>,
1038 typename std::iterator_traits<IterOfRange<R>>::difference_type,
1039 typename std::iterator_traits<IterOfRange<R>>::pointer,
1040 typename std::iterator_traits<IterOfRange<R>>::reference> {
1041 using result_type = result_pair<R>;
1044 explicit enumerator_iter(IterOfRange<R> EndIter)
1045 : Result(std::numeric_limits<size_t>::max(), EndIter) { }
1047 enumerator_iter(std::size_t Index, IterOfRange<R> Iter)
1048 : Result(Index, Iter) {}
1050 result_type &operator*() { return Result; }
1051 const result_type &operator*() const { return Result; }
1053 enumerator_iter<R> &operator++() {
1054 assert(Result.Index != std::numeric_limits<size_t>::max());
1060 bool operator==(const enumerator_iter<R> &RHS) const {
1061 // Don't compare indices here, only iterators. It's possible for an end
1062 // iterator to have different indices depending on whether it was created
1063 // by calling std::end() versus incrementing a valid iterator.
1064 return Result.Iter == RHS.Result.Iter;
1067 enumerator_iter<R> &operator=(const enumerator_iter<R> &Other) {
1068 Result = Other.Result;
1076 template <typename R> class enumerator {
1078 explicit enumerator(R &&Range) : TheRange(std::forward<R>(Range)) {}
1080 enumerator_iter<R> begin() {
1081 return enumerator_iter<R>(0, std::begin(TheRange));
1083 enumerator_iter<R> end() {
1084 return enumerator_iter<R>(std::end(TheRange));
1092 /// Given an input range, returns a new range whose values are are pair (A,B)
1093 /// such that A is the 0-based index of the item in the sequence, and B is
1094 /// the value from the original sequence. Example:
1096 /// std::vector<char> Items = {'A', 'B', 'C', 'D'};
1097 /// for (auto X : enumerate(Items)) {
1098 /// printf("Item %d - %c\n", X.index(), X.value());
1107 template <typename R> detail::enumerator<R> enumerate(R &&TheRange) {
1108 return detail::enumerator<R>(std::forward<R>(TheRange));
1112 template <typename F, typename Tuple, std::size_t... I>
1113 auto apply_tuple_impl(F &&f, Tuple &&t, index_sequence<I...>)
1114 -> decltype(std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...)) {
1115 return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...);
1119 /// Given an input tuple (a1, a2, ..., an), pass the arguments of the
1120 /// tuple variadically to f as if by calling f(a1, a2, ..., an) and
1121 /// return the result.
1122 template <typename F, typename Tuple>
1123 auto apply_tuple(F &&f, Tuple &&t) -> decltype(detail::apply_tuple_impl(
1124 std::forward<F>(f), std::forward<Tuple>(t),
1126 std::tuple_size<typename std::decay<Tuple>::type>::value>{})) {
1127 using Indices = build_index_impl<
1128 std::tuple_size<typename std::decay<Tuple>::type>::value>;
1130 return detail::apply_tuple_impl(std::forward<F>(f), std::forward<Tuple>(t),
1133 } // End llvm namespace