• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===- llvm/ADT/STLExtras.h - Useful STL related functions ------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains some templates that are useful if you are working with the
11 // STL at all.
12 //
13 // No library is required when using these functions.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #ifndef LLVM_ADT_STLEXTRAS_H
18 #define LLVM_ADT_STLEXTRAS_H
19 
20 #include <stdint.h>
21 
22 #include <algorithm>  // for std::all_of
23 #include <cassert>
24 #include <cstddef>  // for std::size_t
25 #include <cstdlib>  // for qsort
26 #include <functional>
27 #include <iterator>
28 #include <memory>
29 #include <tuple>
30 #include <utility>  // for std::pair
31 
32 #include "llvm/ADT/Optional.h"
33 #include "llvm/ADT/iterator.h"
34 #include "llvm/ADT/iterator_range.h"
35 #include "llvm/Support/Compiler.h"
36 
37 namespace llvm {
38 
39 // Only used by compiler if both template types are the same.  Useful when
40 // using SFINAE to test for the existence of member functions.
41 template <typename T, T> struct SameType;
42 
43 namespace detail {
44 
45 template <typename RangeT>
46 using IterOfRange = decltype(std::begin(std::declval<RangeT &>()));
47 
48 } // End detail namespace
49 
50 /// An efficient, type-erasing, non-owning reference to a callable. This is
51 /// intended for use as the type of a function parameter that is not used
52 /// after the function in question returns.
53 ///
54 /// This class does not own the callable, so it is not in general safe to store
55 /// a function_ref.
56 template<typename Fn> class function_ref;
57 
58 template<typename Ret, typename ...Params>
59 class function_ref<Ret(Params...)> {
60   Ret (*callback)(intptr_t callable, Params ...params);
61   intptr_t callable;
62 
63   template<typename Callable>
callback_fn(intptr_t callable,Params...params)64   static Ret callback_fn(intptr_t callable, Params ...params) {
65     return (*reinterpret_cast<Callable*>(callable))(
66         std::forward<Params>(params)...);
67   }
68 
69 public:
70   template <typename Callable>
71   function_ref(Callable &&callable,
72                typename std::enable_if<
73                    !std::is_same<typename std::remove_reference<Callable>::type,
74                                  function_ref>::value>::type * = nullptr)
callback(callback_fn<typename std::remove_reference<Callable>::type>)75       : callback(callback_fn<typename std::remove_reference<Callable>::type>),
76         callable(reinterpret_cast<intptr_t>(&callable)) {}
operator()77   Ret operator()(Params ...params) const {
78     return callback(callable, std::forward<Params>(params)...);
79   }
80 };
81 
82 // deleter - Very very very simple method that is used to invoke operator
83 // delete on something.  It is used like this:
84 //
85 //   for_each(V.begin(), B.end(), deleter<Interval>);
86 //
87 template <class T>
deleter(T * Ptr)88 inline void deleter(T *Ptr) {
89   delete Ptr;
90 }
91 
92 
93 
94 //===----------------------------------------------------------------------===//
95 //     Extra additions to <iterator>
96 //===----------------------------------------------------------------------===//
97 
98 // mapped_iterator - This is a simple iterator adapter that causes a function to
99 // be dereferenced whenever operator* is invoked on the iterator.
100 //
101 template <class RootIt, class UnaryFunc>
102 class mapped_iterator {
103   RootIt current;
104   UnaryFunc Fn;
105 public:
106   typedef typename std::iterator_traits<RootIt>::iterator_category
107           iterator_category;
108   typedef typename std::iterator_traits<RootIt>::difference_type
109           difference_type;
110   typedef typename std::invoke_result_t<UnaryFunc,
111                                         decltype(*std::declval<RootIt>())>
112           value_type;
113 
114   typedef void pointer;
115   //typedef typename UnaryFunc::result_type *pointer;
116   typedef void reference;        // Can't modify value returned by fn
117 
118   typedef RootIt iterator_type;
119 
getCurrent()120   inline const RootIt &getCurrent() const { return current; }
getFunc()121   inline const UnaryFunc &getFunc() const { return Fn; }
122 
mapped_iterator(const RootIt & I,UnaryFunc F)123   inline explicit mapped_iterator(const RootIt &I, UnaryFunc F)
124     : current(I), Fn(F) {}
125 
126   inline value_type operator*() const {   // All this work to do this
127     return Fn(*current);         // little change
128   }
129 
130   mapped_iterator &operator++() {
131     ++current;
132     return *this;
133   }
134   mapped_iterator &operator--() {
135     --current;
136     return *this;
137   }
138   mapped_iterator operator++(int) {
139     mapped_iterator __tmp = *this;
140     ++current;
141     return __tmp;
142   }
143   mapped_iterator operator--(int) {
144     mapped_iterator __tmp = *this;
145     --current;
146     return __tmp;
147   }
148   mapped_iterator operator+(difference_type n) const {
149     return mapped_iterator(current + n, Fn);
150   }
151   mapped_iterator &operator+=(difference_type n) {
152     current += n;
153     return *this;
154   }
155   mapped_iterator operator-(difference_type n) const {
156     return mapped_iterator(current - n, Fn);
157   }
158   mapped_iterator &operator-=(difference_type n) {
159     current -= n;
160     return *this;
161   }
162   reference operator[](difference_type n) const { return *(*this + n); }
163 
164   bool operator!=(const mapped_iterator &X) const { return !operator==(X); }
165   bool operator==(const mapped_iterator &X) const {
166     return current == X.current;
167   }
168   bool operator<(const mapped_iterator &X) const { return current < X.current; }
169 
170   difference_type operator-(const mapped_iterator &X) const {
171     return current - X.current;
172   }
173 };
174 
175 template <class Iterator, class Func>
176 inline mapped_iterator<Iterator, Func>
177 operator+(typename mapped_iterator<Iterator, Func>::difference_type N,
178           const mapped_iterator<Iterator, Func> &X) {
179   return mapped_iterator<Iterator, Func>(X.getCurrent() - N, X.getFunc());
180 }
181 
182 
183 // map_iterator - Provide a convenient way to create mapped_iterators, just like
184 // make_pair is useful for creating pairs...
185 //
186 template <class ItTy, class FuncTy>
map_iterator(const ItTy & I,FuncTy F)187 inline mapped_iterator<ItTy, FuncTy> map_iterator(const ItTy &I, FuncTy F) {
188   return mapped_iterator<ItTy, FuncTy>(I, F);
189 }
190 
191 /// Helper to determine if type T has a member called rbegin().
192 template <typename Ty> class has_rbegin_impl {
193   typedef char yes[1];
194   typedef char no[2];
195 
196   template <typename Inner>
197   static yes& test(Inner *I, decltype(I->rbegin()) * = nullptr);
198 
199   template <typename>
200   static no& test(...);
201 
202 public:
203   static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
204 };
205 
206 /// Metafunction to determine if T& or T has a member called rbegin().
207 template <typename Ty>
208 struct has_rbegin : has_rbegin_impl<typename std::remove_reference<Ty>::type> {
209 };
210 
211 // Returns an iterator_range over the given container which iterates in reverse.
212 // Note that the container must have rbegin()/rend() methods for this to work.
213 template <typename ContainerTy>
214 auto reverse(ContainerTy &&C,
215              typename std::enable_if<has_rbegin<ContainerTy>::value>::type * =
216                  nullptr) -> decltype(make_range(C.rbegin(), C.rend())) {
217   return make_range(C.rbegin(), C.rend());
218 }
219 
220 // Returns a std::reverse_iterator wrapped around the given iterator.
221 template <typename IteratorTy>
make_reverse_iterator(IteratorTy It)222 std::reverse_iterator<IteratorTy> make_reverse_iterator(IteratorTy It) {
223   return std::reverse_iterator<IteratorTy>(It);
224 }
225 
226 // Returns an iterator_range over the given container which iterates in reverse.
227 // Note that the container must have begin()/end() methods which return
228 // bidirectional iterators for this to work.
229 template <typename ContainerTy>
230 auto reverse(
231     ContainerTy &&C,
232     typename std::enable_if<!has_rbegin<ContainerTy>::value>::type * = nullptr)
233     -> decltype(make_range(llvm::make_reverse_iterator(std::end(C)),
234                            llvm::make_reverse_iterator(std::begin(C)))) {
235   return make_range(llvm::make_reverse_iterator(std::end(C)),
236                     llvm::make_reverse_iterator(std::begin(C)));
237 }
238 
239 /// An iterator adaptor that filters the elements of given inner iterators.
240 ///
241 /// The predicate parameter should be a callable object that accepts the wrapped
242 /// iterator's reference type and returns a bool. When incrementing or
243 /// decrementing the iterator, it will call the predicate on each element and
244 /// skip any where it returns false.
245 ///
246 /// \code
247 ///   int A[] = { 1, 2, 3, 4 };
248 ///   auto R = make_filter_range(A, [](int N) { return N % 2 == 1; });
249 ///   // R contains { 1, 3 }.
250 /// \endcode
251 template <typename WrappedIteratorT, typename PredicateT>
252 class filter_iterator
253     : public iterator_adaptor_base<
254           filter_iterator<WrappedIteratorT, PredicateT>, WrappedIteratorT,
255           typename std::common_type<
256               std::forward_iterator_tag,
257               typename std::iterator_traits<
258                   WrappedIteratorT>::iterator_category>::type> {
259   using BaseT = iterator_adaptor_base<
260       filter_iterator<WrappedIteratorT, PredicateT>, WrappedIteratorT,
261       typename std::common_type<
262           std::forward_iterator_tag,
263           typename std::iterator_traits<WrappedIteratorT>::iterator_category>::
264           type>;
265 
266   struct PayloadType {
267     WrappedIteratorT End;
268     PredicateT Pred;
269   };
270 
271   Optional<PayloadType> Payload;
272 
findNextValid()273   void findNextValid() {
274     assert(Payload && "Payload should be engaged when findNextValid is called");
275     while (this->I != Payload->End && !Payload->Pred(*this->I))
276       BaseT::operator++();
277   }
278 
279   // Construct the begin iterator. The begin iterator requires to know where end
280   // is, so that it can properly stop when it hits end.
filter_iterator(WrappedIteratorT Begin,WrappedIteratorT End,PredicateT Pred)281   filter_iterator(WrappedIteratorT Begin, WrappedIteratorT End, PredicateT Pred)
282       : BaseT(std::move(Begin)),
283         Payload(PayloadType{std::move(End), std::move(Pred)}) {
284     findNextValid();
285   }
286 
287   // Construct the end iterator. It's not incrementable, so Payload doesn't
288   // have to be engaged.
filter_iterator(WrappedIteratorT End)289   filter_iterator(WrappedIteratorT End) : BaseT(End) {}
290 
291 public:
292   using BaseT::operator++;
293 
294   filter_iterator &operator++() {
295     BaseT::operator++();
296     findNextValid();
297     return *this;
298   }
299 
300   template <typename RT, typename PT>
301   friend iterator_range<filter_iterator<detail::IterOfRange<RT>, PT>>
302   make_filter_range(RT &&, PT);
303 };
304 
305 /// Convenience function that takes a range of elements and a predicate,
306 /// and return a new filter_iterator range.
307 ///
308 /// FIXME: Currently if RangeT && is a rvalue reference to a temporary, the
309 /// lifetime of that temporary is not kept by the returned range object, and the
310 /// temporary is going to be dropped on the floor after the make_iterator_range
311 /// full expression that contains this function call.
312 template <typename RangeT, typename PredicateT>
313 iterator_range<filter_iterator<detail::IterOfRange<RangeT>, PredicateT>>
make_filter_range(RangeT && Range,PredicateT Pred)314 make_filter_range(RangeT &&Range, PredicateT Pred) {
315   using FilterIteratorT =
316       filter_iterator<detail::IterOfRange<RangeT>, PredicateT>;
317   return make_range(FilterIteratorT(std::begin(std::forward<RangeT>(Range)),
318                                     std::end(std::forward<RangeT>(Range)),
319                                     std::move(Pred)),
320                     FilterIteratorT(std::end(std::forward<RangeT>(Range))));
321 }
322 
323 //===----------------------------------------------------------------------===//
324 //     Extra additions to <utility>
325 //===----------------------------------------------------------------------===//
326 
327 /// \brief Function object to check whether the first component of a std::pair
328 /// compares less than the first component of another std::pair.
329 struct less_first {
operatorless_first330   template <typename T> bool operator()(const T &lhs, const T &rhs) const {
331     return lhs.first < rhs.first;
332   }
333 };
334 
335 /// \brief Function object to check whether the second component of a std::pair
336 /// compares less than the second component of another std::pair.
337 struct less_second {
operatorless_second338   template <typename T> bool operator()(const T &lhs, const T &rhs) const {
339     return lhs.second < rhs.second;
340   }
341 };
342 
343 // A subset of N3658. More stuff can be added as-needed.
344 
345 /// \brief Represents a compile-time sequence of integers.
346 template <class T, T... I> struct integer_sequence {
347   typedef T value_type;
348 
sizeinteger_sequence349   static constexpr size_t size() { return sizeof...(I); }
350 };
351 
352 /// \brief Alias for the common case of a sequence of size_ts.
353 template <size_t... I>
354 struct index_sequence : integer_sequence<std::size_t, I...> {};
355 
356 template <std::size_t N, std::size_t... I>
357 struct build_index_impl : build_index_impl<N - 1, N - 1, I...> {};
358 template <std::size_t... I>
359 struct build_index_impl<0, I...> : index_sequence<I...> {};
360 
361 /// \brief Creates a compile-time integer sequence for a parameter pack.
362 template <class... Ts>
363 struct index_sequence_for : build_index_impl<sizeof...(Ts)> {};
364 
365 /// Utility type to build an inheritance chain that makes it easy to rank
366 /// overload candidates.
367 template <int N> struct rank : rank<N - 1> {};
368 template <> struct rank<0> {};
369 
370 /// \brief traits class for checking whether type T is one of any of the given
371 /// types in the variadic list.
372 template <typename T, typename... Ts> struct is_one_of {
373   static const bool value = false;
374 };
375 
376 template <typename T, typename U, typename... Ts>
377 struct is_one_of<T, U, Ts...> {
378   static const bool value =
379       std::is_same<T, U>::value || is_one_of<T, Ts...>::value;
380 };
381 
382 //===----------------------------------------------------------------------===//
383 //     Extra additions for arrays
384 //===----------------------------------------------------------------------===//
385 
386 /// Find the length of an array.
387 template <class T, std::size_t N>
388 constexpr inline size_t array_lengthof(T (&)[N]) {
389   return N;
390 }
391 
392 /// Adapt std::less<T> for array_pod_sort.
393 template<typename T>
394 inline int array_pod_sort_comparator(const void *P1, const void *P2) {
395   if (std::less<T>()(*reinterpret_cast<const T*>(P1),
396                      *reinterpret_cast<const T*>(P2)))
397     return -1;
398   if (std::less<T>()(*reinterpret_cast<const T*>(P2),
399                      *reinterpret_cast<const T*>(P1)))
400     return 1;
401   return 0;
402 }
403 
404 /// get_array_pod_sort_comparator - This is an internal helper function used to
405 /// get type deduction of T right.
406 template<typename T>
407 inline int (*get_array_pod_sort_comparator(const T &))
408              (const void*, const void*) {
409   return array_pod_sort_comparator<T>;
410 }
411 
412 
413 /// array_pod_sort - This sorts an array with the specified start and end
414 /// extent.  This is just like std::sort, except that it calls qsort instead of
415 /// using an inlined template.  qsort is slightly slower than std::sort, but
416 /// most sorts are not performance critical in LLVM and std::sort has to be
417 /// template instantiated for each type, leading to significant measured code
418 /// bloat.  This function should generally be used instead of std::sort where
419 /// possible.
420 ///
421 /// This function assumes that you have simple POD-like types that can be
422 /// compared with std::less and can be moved with memcpy.  If this isn't true,
423 /// you should use std::sort.
424 ///
425 /// NOTE: If qsort_r were portable, we could allow a custom comparator and
426 /// default to std::less.
427 template<class IteratorTy>
428 inline void array_pod_sort(IteratorTy Start, IteratorTy End) {
429   // Don't inefficiently call qsort with one element or trigger undefined
430   // behavior with an empty sequence.
431   auto NElts = End - Start;
432   if (NElts <= 1) return;
433   qsort(&*Start, NElts, sizeof(*Start), get_array_pod_sort_comparator(*Start));
434 }
435 
436 template <class IteratorTy>
437 inline void array_pod_sort(
438     IteratorTy Start, IteratorTy End,
439     int (*Compare)(
440         const typename std::iterator_traits<IteratorTy>::value_type *,
441         const typename std::iterator_traits<IteratorTy>::value_type *)) {
442   // Don't inefficiently call qsort with one element or trigger undefined
443   // behavior with an empty sequence.
444   auto NElts = End - Start;
445   if (NElts <= 1) return;
446   qsort(&*Start, NElts, sizeof(*Start),
447         reinterpret_cast<int (*)(const void *, const void *)>(Compare));
448 }
449 
450 //===----------------------------------------------------------------------===//
451 //     Extra additions to <algorithm>
452 //===----------------------------------------------------------------------===//
453 
454 /// For a container of pointers, deletes the pointers and then clears the
455 /// container.
456 template<typename Container>
457 void DeleteContainerPointers(Container &C) {
458   for (auto V : C)
459     delete V;
460   C.clear();
461 }
462 
463 /// In a container of pairs (usually a map) whose second element is a pointer,
464 /// deletes the second elements and then clears the container.
465 template<typename Container>
466 void DeleteContainerSeconds(Container &C) {
467   for (auto &V : C)
468     delete V.second;
469   C.clear();
470 }
471 
472 /// Provide wrappers to std::all_of which take ranges instead of having to pass
473 /// begin/end explicitly.
474 template <typename R, typename UnaryPredicate>
475 bool all_of(R &&Range, UnaryPredicate P) {
476   return std::all_of(std::begin(Range), std::end(Range), P);
477 }
478 
479 /// Provide wrappers to std::any_of which take ranges instead of having to pass
480 /// begin/end explicitly.
481 template <typename R, typename UnaryPredicate>
482 bool any_of(R &&Range, UnaryPredicate P) {
483   return std::any_of(std::begin(Range), std::end(Range), P);
484 }
485 
486 /// Provide wrappers to std::none_of which take ranges instead of having to pass
487 /// begin/end explicitly.
488 template <typename R, typename UnaryPredicate>
489 bool none_of(R &&Range, UnaryPredicate P) {
490   return std::none_of(std::begin(Range), std::end(Range), P);
491 }
492 
493 /// Provide wrappers to std::find which take ranges instead of having to pass
494 /// begin/end explicitly.
495 template <typename R, typename T>
496 auto find(R &&Range, const T &Val) -> decltype(std::begin(Range)) {
497   return std::find(std::begin(Range), std::end(Range), Val);
498 }
499 
500 /// Provide wrappers to std::find_if which take ranges instead of having to pass
501 /// begin/end explicitly.
502 template <typename R, typename UnaryPredicate>
503 auto find_if(R &&Range, UnaryPredicate P) -> decltype(std::begin(Range)) {
504   return std::find_if(std::begin(Range), std::end(Range), P);
505 }
506 
507 template <typename R, typename UnaryPredicate>
508 auto find_if_not(R &&Range, UnaryPredicate P) -> decltype(std::begin(Range)) {
509   return std::find_if_not(std::begin(Range), std::end(Range), P);
510 }
511 
512 /// Provide wrappers to std::remove_if which take ranges instead of having to
513 /// pass begin/end explicitly.
514 template <typename R, typename UnaryPredicate>
515 auto remove_if(R &&Range, UnaryPredicate P) -> decltype(std::begin(Range)) {
516   return std::remove_if(std::begin(Range), std::end(Range), P);
517 }
518 
519 /// Wrapper function around std::find to detect if an element exists
520 /// in a container.
521 template <typename R, typename E>
522 bool is_contained(R &&Range, const E &Element) {
523   return std::find(std::begin(Range), std::end(Range), Element) !=
524          std::end(Range);
525 }
526 
527 /// Wrapper function around std::count to count the number of times an element
528 /// \p Element occurs in the given range \p Range.
529 template <typename R, typename E>
530 auto count(R &&Range, const E &Element) -> typename std::iterator_traits<
531     decltype(std::begin(Range))>::difference_type {
532   return std::count(std::begin(Range), std::end(Range), Element);
533 }
534 
535 /// Wrapper function around std::count_if to count the number of times an
536 /// element satisfying a given predicate occurs in a range.
537 template <typename R, typename UnaryPredicate>
538 auto count_if(R &&Range, UnaryPredicate P) -> typename std::iterator_traits<
539     decltype(std::begin(Range))>::difference_type {
540   return std::count_if(std::begin(Range), std::end(Range), P);
541 }
542 
543 /// Wrapper function around std::transform to apply a function to a range and
544 /// store the result elsewhere.
545 template <typename R, typename OutputIt, typename UnaryPredicate>
546 OutputIt transform(R &&Range, OutputIt d_first, UnaryPredicate P) {
547   return std::transform(std::begin(Range), std::end(Range), d_first, P);
548 }
549 
550 //===----------------------------------------------------------------------===//
551 //     Extra additions to <memory>
552 //===----------------------------------------------------------------------===//
553 
554 // Implement make_unique according to N3656.
555 
556 /// \brief Constructs a `new T()` with the given args and returns a
557 ///        `unique_ptr<T>` which owns the object.
558 ///
559 /// Example:
560 ///
561 ///     auto p = make_unique<int>();
562 ///     auto p = make_unique<std::tuple<int, int>>(0, 1);
563 template <class T, class... Args>
564 typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
565 make_unique(Args &&... args) {
566   return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
567 }
568 
569 /// \brief Constructs a `new T[n]` with the given args and returns a
570 ///        `unique_ptr<T[]>` which owns the object.
571 ///
572 /// \param n size of the new array.
573 ///
574 /// Example:
575 ///
576 ///     auto p = make_unique<int[]>(2); // value-initializes the array with 0's.
577 template <class T>
578 typename std::enable_if<std::is_array<T>::value && std::extent<T>::value == 0,
579                         std::unique_ptr<T>>::type
580 make_unique(size_t n) {
581   return std::unique_ptr<T>(new typename std::remove_extent<T>::type[n]());
582 }
583 
584 /// This function isn't used and is only here to provide better compile errors.
585 template <class T, class... Args>
586 typename std::enable_if<std::extent<T>::value != 0>::type
587 make_unique(Args &&...) = delete;
588 
589 struct FreeDeleter {
590   void operator()(void* v) {
591     ::free(v);
592   }
593 };
594 
595 template<typename First, typename Second>
596 struct pair_hash {
597   size_t operator()(const std::pair<First, Second> &P) const {
598     return std::hash<First>()(P.first) * 31 + std::hash<Second>()(P.second);
599   }
600 };
601 
602 /// A functor like C++14's std::less<void> in its absence.
603 struct less {
604   template <typename A, typename B> bool operator()(A &&a, B &&b) const {
605     return std::forward<A>(a) < std::forward<B>(b);
606   }
607 };
608 
609 /// A functor like C++14's std::equal<void> in its absence.
610 struct equal {
611   template <typename A, typename B> bool operator()(A &&a, B &&b) const {
612     return std::forward<A>(a) == std::forward<B>(b);
613   }
614 };
615 
616 /// Binary functor that adapts to any other binary functor after dereferencing
617 /// operands.
618 template <typename T> struct deref {
619   T func;
620   // Could be further improved to cope with non-derivable functors and
621   // non-binary functors (should be a variadic template member function
622   // operator()).
623   template <typename A, typename B>
624   auto operator()(A &lhs, B &rhs) const -> decltype(func(*lhs, *rhs)) {
625     assert(lhs);
626     assert(rhs);
627     return func(*lhs, *rhs);
628   }
629 };
630 
631 namespace detail {
632 template <typename R> class enumerator_impl {
633 public:
634   template <typename X> struct result_pair {
635     result_pair(std::size_t Index, X Value) : Index(Index), Value(Value) {}
636 
637     const std::size_t Index;
638     X Value;
639   };
640 
641   class iterator {
642     typedef
643         typename std::iterator_traits<IterOfRange<R>>::reference iter_reference;
644     typedef result_pair<iter_reference> result_type;
645 
646   public:
647     iterator(IterOfRange<R> &&Iter, std::size_t Index)
648         : Iter(Iter), Index(Index) {}
649 
650     result_type operator*() const { return result_type(Index, *Iter); }
651 
652     iterator &operator++() {
653       ++Iter;
654       ++Index;
655       return *this;
656     }
657 
658     bool operator!=(const iterator &RHS) const { return Iter != RHS.Iter; }
659 
660   private:
661     IterOfRange<R> Iter;
662     std::size_t Index;
663   };
664 
665 public:
666   explicit enumerator_impl(R &&Range) : Range(std::forward<R>(Range)) {}
667 
668   iterator begin() { return iterator(std::begin(Range), 0); }
669   iterator end() { return iterator(std::end(Range), std::size_t(-1)); }
670 
671 private:
672   R Range;
673 };
674 }
675 
676 /// Given an input range, returns a new range whose values are are pair (A,B)
677 /// such that A is the 0-based index of the item in the sequence, and B is
678 /// the value from the original sequence.  Example:
679 ///
680 /// std::vector<char> Items = {'A', 'B', 'C', 'D'};
681 /// for (auto X : enumerate(Items)) {
682 ///   printf("Item %d - %c\n", X.Index, X.Value);
683 /// }
684 ///
685 /// Output:
686 ///   Item 0 - A
687 ///   Item 1 - B
688 ///   Item 2 - C
689 ///   Item 3 - D
690 ///
691 template <typename R> detail::enumerator_impl<R> enumerate(R &&Range) {
692   return detail::enumerator_impl<R>(std::forward<R>(Range));
693 }
694 
695 namespace detail {
696 template <typename F, typename Tuple, std::size_t... I>
697 auto apply_tuple_impl(F &&f, Tuple &&t, index_sequence<I...>)
698     -> decltype(std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...)) {
699   return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...);
700 }
701 }
702 
703 /// Given an input tuple (a1, a2, ..., an), pass the arguments of the
704 /// tuple variadically to f as if by calling f(a1, a2, ..., an) and
705 /// return the result.
706 template <typename F, typename Tuple>
707 auto apply_tuple(F &&f, Tuple &&t) -> decltype(detail::apply_tuple_impl(
708     std::forward<F>(f), std::forward<Tuple>(t),
709     build_index_impl<
710         std::tuple_size<typename std::decay<Tuple>::type>::value>{})) {
711   using Indices = build_index_impl<
712       std::tuple_size<typename std::decay<Tuple>::type>::value>;
713 
714   return detail::apply_tuple_impl(std::forward<F>(f), std::forward<Tuple>(t),
715                                   Indices{});
716 }
717 } // End llvm namespace
718 
719 #endif
720