LLVM  8.0.0svn
STLExtras.h
Go to the documentation of this file.
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 "llvm/ADT/Optional.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/iterator.h"
24 #include "llvm/Config/abi-breaking.h"
26 #include <algorithm>
27 #include <cassert>
28 #include <cstddef>
29 #include <cstdint>
30 #include <cstdlib>
31 #include <functional>
32 #include <initializer_list>
33 #include <iterator>
34 #include <limits>
35 #include <memory>
36 #include <tuple>
37 #include <type_traits>
38 #include <utility>
39 
40 #ifdef EXPENSIVE_CHECKS
41 #include <random> // for std::mt19937
42 #endif
43 
44 namespace llvm {
45 
46 // Only used by compiler if both template types are the same. Useful when
47 // using SFINAE to test for the existence of member functions.
48 template <typename T, T> struct SameType;
49 
50 namespace detail {
51 
52 template <typename RangeT>
53 using IterOfRange = decltype(std::begin(std::declval<RangeT &>()));
54 
55 template <typename RangeT>
56 using ValueOfRange = typename std::remove_reference<decltype(
57  *std::begin(std::declval<RangeT &>()))>::type;
58 
59 } // end namespace detail
60 
61 //===----------------------------------------------------------------------===//
62 // Extra additions to <type_traits>
63 //===----------------------------------------------------------------------===//
64 
65 template <typename T>
66 struct negation : std::integral_constant<bool, !bool(T::value)> {};
67 
68 template <typename...> struct conjunction : std::true_type {};
69 template <typename B1> struct conjunction<B1> : B1 {};
70 template <typename B1, typename... Bn>
71 struct conjunction<B1, Bn...>
72  : std::conditional<bool(B1::value), conjunction<Bn...>, B1>::type {};
73 
74 //===----------------------------------------------------------------------===//
75 // Extra additions to <functional>
76 //===----------------------------------------------------------------------===//
77 
78 template <class Ty> struct identity {
79  using argument_type = Ty;
80 
81  Ty &operator()(Ty &self) const {
82  return self;
83  }
84  const Ty &operator()(const Ty &self) const {
85  return self;
86  }
87 };
88 
89 template <class Ty> struct less_ptr {
90  bool operator()(const Ty* left, const Ty* right) const {
91  return *left < *right;
92  }
93 };
94 
95 template <class Ty> struct greater_ptr {
96  bool operator()(const Ty* left, const Ty* right) const {
97  return *right < *left;
98  }
99 };
100 
101 /// An efficient, type-erasing, non-owning reference to a callable. This is
102 /// intended for use as the type of a function parameter that is not used
103 /// after the function in question returns.
104 ///
105 /// This class does not own the callable, so it is not in general safe to store
106 /// a function_ref.
107 template<typename Fn> class function_ref;
108 
109 template<typename Ret, typename ...Params>
110 class function_ref<Ret(Params...)> {
111  Ret (*callback)(intptr_t callable, Params ...params) = nullptr;
112  intptr_t callable;
113 
114  template<typename Callable>
115  static Ret callback_fn(intptr_t callable, Params ...params) {
116  return (*reinterpret_cast<Callable*>(callable))(
117  std::forward<Params>(params)...);
118  }
119 
120 public:
121  function_ref() = default;
122  function_ref(std::nullptr_t) {}
123 
124  template <typename Callable>
125  function_ref(Callable &&callable,
126  typename std::enable_if<
127  !std::is_same<typename std::remove_reference<Callable>::type,
128  function_ref>::value>::type * = nullptr)
129  : callback(callback_fn<typename std::remove_reference<Callable>::type>),
130  callable(reinterpret_cast<intptr_t>(&callable)) {}
131 
132  Ret operator()(Params ...params) const {
133  return callback(callable, std::forward<Params>(params)...);
134  }
135 
136  operator bool() const { return callback; }
137 };
138 
139 // deleter - Very very very simple method that is used to invoke operator
140 // delete on something. It is used like this:
141 //
142 // for_each(V.begin(), B.end(), deleter<Interval>);
143 template <class T>
144 inline void deleter(T *Ptr) {
145  delete Ptr;
146 }
147 
148 //===----------------------------------------------------------------------===//
149 // Extra additions to <iterator>
150 //===----------------------------------------------------------------------===//
151 
152 namespace adl_detail {
153 
154 using std::begin;
155 
156 template <typename ContainerTy>
157 auto adl_begin(ContainerTy &&container)
158  -> decltype(begin(std::forward<ContainerTy>(container))) {
159  return begin(std::forward<ContainerTy>(container));
160 }
161 
162 using std::end;
163 
164 template <typename ContainerTy>
165 auto adl_end(ContainerTy &&container)
166  -> decltype(end(std::forward<ContainerTy>(container))) {
167  return end(std::forward<ContainerTy>(container));
168 }
169 
170 using std::swap;
171 
172 template <typename T>
173 void adl_swap(T &&lhs, T &&rhs) noexcept(noexcept(swap(std::declval<T>(),
174  std::declval<T>()))) {
175  swap(std::forward<T>(lhs), std::forward<T>(rhs));
176 }
177 
178 } // end namespace adl_detail
179 
180 template <typename ContainerTy>
181 auto adl_begin(ContainerTy &&container)
182  -> decltype(adl_detail::adl_begin(std::forward<ContainerTy>(container))) {
183  return adl_detail::adl_begin(std::forward<ContainerTy>(container));
184 }
185 
186 template <typename ContainerTy>
187 auto adl_end(ContainerTy &&container)
188  -> decltype(adl_detail::adl_end(std::forward<ContainerTy>(container))) {
189  return adl_detail::adl_end(std::forward<ContainerTy>(container));
190 }
191 
192 template <typename T>
193 void adl_swap(T &&lhs, T &&rhs) noexcept(
194  noexcept(adl_detail::adl_swap(std::declval<T>(), std::declval<T>()))) {
195  adl_detail::adl_swap(std::forward<T>(lhs), std::forward<T>(rhs));
196 }
197 
198 // mapped_iterator - This is a simple iterator adapter that causes a function to
199 // be applied whenever operator* is invoked on the iterator.
200 
201 template <typename ItTy, typename FuncTy,
202  typename FuncReturnTy =
203  decltype(std::declval<FuncTy>()(*std::declval<ItTy>()))>
205  : public iterator_adaptor_base<
206  mapped_iterator<ItTy, FuncTy>, ItTy,
207  typename std::iterator_traits<ItTy>::iterator_category,
208  typename std::remove_reference<FuncReturnTy>::type> {
209 public:
210  mapped_iterator(ItTy U, FuncTy F)
211  : mapped_iterator::iterator_adaptor_base(std::move(U)), F(std::move(F)) {}
212 
213  ItTy getCurrent() { return this->I; }
214 
215  FuncReturnTy operator*() { return F(*this->I); }
216 
217 private:
218  FuncTy F;
219 };
220 
221 // map_iterator - Provide a convenient way to create mapped_iterators, just like
222 // make_pair is useful for creating pairs...
223 template <class ItTy, class FuncTy>
225  return mapped_iterator<ItTy, FuncTy>(std::move(I), std::move(F));
226 }
227 
228 /// Helper to determine if type T has a member called rbegin().
229 template <typename Ty> class has_rbegin_impl {
230  using yes = char[1];
231  using no = char[2];
232 
233  template <typename Inner>
234  static yes& test(Inner *I, decltype(I->rbegin()) * = nullptr);
235 
236  template <typename>
237  static no& test(...);
238 
239 public:
240  static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
241 };
242 
243 /// Metafunction to determine if T& or T has a member called rbegin().
244 template <typename Ty>
245 struct has_rbegin : has_rbegin_impl<typename std::remove_reference<Ty>::type> {
246 };
247 
248 // Returns an iterator_range over the given container which iterates in reverse.
249 // Note that the container must have rbegin()/rend() methods for this to work.
250 template <typename ContainerTy>
251 auto reverse(ContainerTy &&C,
252  typename std::enable_if<has_rbegin<ContainerTy>::value>::type * =
253  nullptr) -> decltype(make_range(C.rbegin(), C.rend())) {
254  return make_range(C.rbegin(), C.rend());
255 }
256 
257 // Returns a std::reverse_iterator wrapped around the given iterator.
258 template <typename IteratorTy>
259 std::reverse_iterator<IteratorTy> make_reverse_iterator(IteratorTy It) {
260  return std::reverse_iterator<IteratorTy>(It);
261 }
262 
263 // Returns an iterator_range over the given container which iterates in reverse.
264 // Note that the container must have begin()/end() methods which return
265 // bidirectional iterators for this to work.
266 template <typename ContainerTy>
267 auto reverse(
268  ContainerTy &&C,
269  typename std::enable_if<!has_rbegin<ContainerTy>::value>::type * = nullptr)
274 }
275 
276 /// An iterator adaptor that filters the elements of given inner iterators.
277 ///
278 /// The predicate parameter should be a callable object that accepts the wrapped
279 /// iterator's reference type and returns a bool. When incrementing or
280 /// decrementing the iterator, it will call the predicate on each element and
281 /// skip any where it returns false.
282 ///
283 /// \code
284 /// int A[] = { 1, 2, 3, 4 };
285 /// auto R = make_filter_range(A, [](int N) { return N % 2 == 1; });
286 /// // R contains { 1, 3 }.
287 /// \endcode
288 ///
289 /// Note: filter_iterator_base implements support for forward iteration.
290 /// filter_iterator_impl exists to provide support for bidirectional iteration,
291 /// conditional on whether the wrapped iterator supports it.
292 template <typename WrappedIteratorT, typename PredicateT, typename IterTag>
294  : public iterator_adaptor_base<
295  filter_iterator_base<WrappedIteratorT, PredicateT, IterTag>,
296  WrappedIteratorT,
297  typename std::common_type<
298  IterTag, typename std::iterator_traits<
299  WrappedIteratorT>::iterator_category>::type> {
302  WrappedIteratorT,
303  typename std::common_type<
304  IterTag, typename std::iterator_traits<
305  WrappedIteratorT>::iterator_category>::type>;
306 
307 protected:
308  WrappedIteratorT End;
309  PredicateT Pred;
310 
311  void findNextValid() {
312  while (this->I != End && !Pred(*this->I))
313  BaseT::operator++();
314  }
315 
316  // Construct the iterator. The begin iterator needs to know where the end
317  // is, so that it can properly stop when it gets there. The end iterator only
318  // needs the predicate to support bidirectional iteration.
319  filter_iterator_base(WrappedIteratorT Begin, WrappedIteratorT End,
320  PredicateT Pred)
321  : BaseT(Begin), End(End), Pred(Pred) {
322  findNextValid();
323  }
324 
325 public:
326  using BaseT::operator++;
327 
329  BaseT::operator++();
330  findNextValid();
331  return *this;
332  }
333 };
334 
335 /// Specialization of filter_iterator_base for forward iteration only.
336 template <typename WrappedIteratorT, typename PredicateT,
337  typename IterTag = std::forward_iterator_tag>
339  : public filter_iterator_base<WrappedIteratorT, PredicateT, IterTag> {
341 
342 public:
343  filter_iterator_impl(WrappedIteratorT Begin, WrappedIteratorT End,
344  PredicateT Pred)
345  : BaseT(Begin, End, Pred) {}
346 };
347 
348 /// Specialization of filter_iterator_base for bidirectional iteration.
349 template <typename WrappedIteratorT, typename PredicateT>
350 class filter_iterator_impl<WrappedIteratorT, PredicateT,
351  std::bidirectional_iterator_tag>
352  : public filter_iterator_base<WrappedIteratorT, PredicateT,
353  std::bidirectional_iterator_tag> {
354  using BaseT = filter_iterator_base<WrappedIteratorT, PredicateT,
355  std::bidirectional_iterator_tag>;
356  void findPrevValid() {
357  while (!this->Pred(*this->I))
358  BaseT::operator--();
359  }
360 
361 public:
362  using BaseT::operator--;
363 
364  filter_iterator_impl(WrappedIteratorT Begin, WrappedIteratorT End,
365  PredicateT Pred)
366  : BaseT(Begin, End, Pred) {}
367 
369  BaseT::operator--();
370  findPrevValid();
371  return *this;
372  }
373 };
374 
375 namespace detail {
376 
377 template <bool is_bidirectional> struct fwd_or_bidi_tag_impl {
378  using type = std::forward_iterator_tag;
379 };
380 
381 template <> struct fwd_or_bidi_tag_impl<true> {
382  using type = std::bidirectional_iterator_tag;
383 };
384 
385 /// Helper which sets its type member to forward_iterator_tag if the category
386 /// of \p IterT does not derive from bidirectional_iterator_tag, and to
387 /// bidirectional_iterator_tag otherwise.
388 template <typename IterT> struct fwd_or_bidi_tag {
389  using type = typename fwd_or_bidi_tag_impl<std::is_base_of<
390  std::bidirectional_iterator_tag,
391  typename std::iterator_traits<IterT>::iterator_category>::value>::type;
392 };
393 
394 } // namespace detail
395 
396 /// Defines filter_iterator to a suitable specialization of
397 /// filter_iterator_impl, based on the underlying iterator's category.
398 template <typename WrappedIteratorT, typename PredicateT>
400  WrappedIteratorT, PredicateT,
402 
403 /// Convenience function that takes a range of elements and a predicate,
404 /// and return a new filter_iterator range.
405 ///
406 /// FIXME: Currently if RangeT && is a rvalue reference to a temporary, the
407 /// lifetime of that temporary is not kept by the returned range object, and the
408 /// temporary is going to be dropped on the floor after the make_iterator_range
409 /// full expression that contains this function call.
410 template <typename RangeT, typename PredicateT>
412 make_filter_range(RangeT &&Range, PredicateT Pred) {
413  using FilterIteratorT =
415  return make_range(
416  FilterIteratorT(std::begin(std::forward<RangeT>(Range)),
417  std::end(std::forward<RangeT>(Range)), Pred),
418  FilterIteratorT(std::end(std::forward<RangeT>(Range)),
419  std::end(std::forward<RangeT>(Range)), Pred));
420 }
421 
422 /// A pseudo-iterator adaptor that is designed to implement "early increment"
423 /// style loops.
424 ///
425 /// This is *not a normal iterator* and should almost never be used directly. It
426 /// is intended primarily to be used with range based for loops and some range
427 /// algorithms.
428 ///
429 /// The iterator isn't quite an `OutputIterator` or an `InputIterator` but
430 /// somewhere between them. The constraints of these iterators are:
431 ///
432 /// - On construction or after being incremented, it is comparable and
433 /// dereferencable. It is *not* incrementable.
434 /// - After being dereferenced, it is neither comparable nor dereferencable, it
435 /// is only incrementable.
436 ///
437 /// This means you can only dereference the iterator once, and you can only
438 /// increment it once between dereferences.
439 template <typename WrappedIteratorT>
441  : public iterator_adaptor_base<early_inc_iterator_impl<WrappedIteratorT>,
442  WrappedIteratorT, std::input_iterator_tag> {
443  using BaseT =
445  WrappedIteratorT, std::input_iterator_tag>;
446 
447  using PointerT = typename std::iterator_traits<WrappedIteratorT>::pointer;
448 
449 protected:
450 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
451  bool IsEarlyIncremented = false;
452 #endif
453 
454 public:
455  early_inc_iterator_impl(WrappedIteratorT I) : BaseT(I) {}
456 
457  using BaseT::operator*;
458  typename BaseT::reference operator*() {
459 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
460  assert(!IsEarlyIncremented && "Cannot dereference twice!");
461  IsEarlyIncremented = true;
462 #endif
463  return *(this->I)++;
464  }
465 
466  using BaseT::operator++;
468 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
469  assert(IsEarlyIncremented && "Cannot increment before dereferencing!");
470  IsEarlyIncremented = false;
471 #endif
472  return *this;
473  }
474 
475  using BaseT::operator==;
476  bool operator==(const early_inc_iterator_impl &RHS) const {
477 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
478  assert(!IsEarlyIncremented && "Cannot compare after dereferencing!");
479 #endif
480  return BaseT::operator==(RHS);
481  }
482 };
483 
484 /// Make a range that does early increment to allow mutation of the underlying
485 /// range without disrupting iteration.
486 ///
487 /// The underlying iterator will be incremented immediately after it is
488 /// dereferenced, allowing deletion of the current node or insertion of nodes to
489 /// not disrupt iteration provided they do not invalidate the *next* iterator --
490 /// the current iterator can be invalidated.
491 ///
492 /// This requires a very exact pattern of use that is only really suitable to
493 /// range based for loops and other range algorithms that explicitly guarantee
494 /// to dereference exactly once each element, and to increment exactly once each
495 /// element.
496 template <typename RangeT>
498 make_early_inc_range(RangeT &&Range) {
499  using EarlyIncIteratorT =
501  return make_range(EarlyIncIteratorT(std::begin(std::forward<RangeT>(Range))),
502  EarlyIncIteratorT(std::end(std::forward<RangeT>(Range))));
503 }
504 
505 // forward declarations required by zip_shortest/zip_first
506 template <typename R, typename UnaryPredicate>
507 bool all_of(R &&range, UnaryPredicate P);
508 
509 template <size_t... I> struct index_sequence;
510 
511 template <class... Ts> struct index_sequence_for;
512 
513 namespace detail {
514 
515 using std::declval;
516 
517 // We have to alias this since inlining the actual type at the usage site
518 // in the parameter list of iterator_facade_base<> below ICEs MSVC 2017.
519 template<typename... Iters> struct ZipTupleType {
520  using type = std::tuple<decltype(*declval<Iters>())...>;
521 };
522 
523 template <typename ZipType, typename... Iters>
525  ZipType, typename std::common_type<std::bidirectional_iterator_tag,
526  typename std::iterator_traits<
527  Iters>::iterator_category...>::type,
528  // ^ TODO: Implement random access methods.
529  typename ZipTupleType<Iters...>::type,
530  typename std::iterator_traits<typename std::tuple_element<
531  0, std::tuple<Iters...>>::type>::difference_type,
532  // ^ FIXME: This follows boost::make_zip_iterator's assumption that all
533  // inner iterators have the same difference_type. It would fail if, for
534  // instance, the second field's difference_type were non-numeric while the
535  // first is.
536  typename ZipTupleType<Iters...>::type *,
537  typename ZipTupleType<Iters...>::type>;
538 
539 template <typename ZipType, typename... Iters>
540 struct zip_common : public zip_traits<ZipType, Iters...> {
541  using Base = zip_traits<ZipType, Iters...>;
542  using value_type = typename Base::value_type;
543 
544  std::tuple<Iters...> iterators;
545 
546 protected:
547  template <size_t... Ns> value_type deref(index_sequence<Ns...>) const {
548  return value_type(*std::get<Ns>(iterators)...);
549  }
550 
551  template <size_t... Ns>
552  decltype(iterators) tup_inc(index_sequence<Ns...>) const {
553  return std::tuple<Iters...>(std::next(std::get<Ns>(iterators))...);
554  }
555 
556  template <size_t... Ns>
557  decltype(iterators) tup_dec(index_sequence<Ns...>) const {
558  return std::tuple<Iters...>(std::prev(std::get<Ns>(iterators))...);
559  }
560 
561 public:
562  zip_common(Iters &&... ts) : iterators(std::forward<Iters>(ts)...) {}
563 
565 
566  const value_type operator*() const {
568  }
569 
570  ZipType &operator++() {
571  iterators = tup_inc(index_sequence_for<Iters...>{});
572  return *reinterpret_cast<ZipType *>(this);
573  }
574 
575  ZipType &operator--() {
576  static_assert(Base::IsBidirectional,
577  "All inner iterators must be at least bidirectional.");
578  iterators = tup_dec(index_sequence_for<Iters...>{});
579  return *reinterpret_cast<ZipType *>(this);
580  }
581 };
582 
583 template <typename... Iters>
584 struct zip_first : public zip_common<zip_first<Iters...>, Iters...> {
585  using Base = zip_common<zip_first<Iters...>, Iters...>;
586 
587  bool operator==(const zip_first<Iters...> &other) const {
588  return std::get<0>(this->iterators) == std::get<0>(other.iterators);
589  }
590 
591  zip_first(Iters &&... ts) : Base(std::forward<Iters>(ts)...) {}
592 };
593 
594 template <typename... Iters>
595 class zip_shortest : public zip_common<zip_shortest<Iters...>, Iters...> {
596  template <size_t... Ns>
597  bool test(const zip_shortest<Iters...> &other, index_sequence<Ns...>) const {
598  return all_of(std::initializer_list<bool>{std::get<Ns>(this->iterators) !=
599  std::get<Ns>(other.iterators)...},
600  identity<bool>{});
601  }
602 
603 public:
604  using Base = zip_common<zip_shortest<Iters...>, Iters...>;
605 
606  zip_shortest(Iters &&... ts) : Base(std::forward<Iters>(ts)...) {}
607 
608  bool operator==(const zip_shortest<Iters...> &other) const {
609  return !test(other, index_sequence_for<Iters...>{});
610  }
611 };
612 
613 template <template <typename...> class ItType, typename... Args> class zippy {
614 public:
616  using iterator_category = typename iterator::iterator_category;
617  using value_type = typename iterator::value_type;
618  using difference_type = typename iterator::difference_type;
619  using pointer = typename iterator::pointer;
620  using reference = typename iterator::reference;
621 
622 private:
623  std::tuple<Args...> ts;
624 
625  template <size_t... Ns> iterator begin_impl(index_sequence<Ns...>) const {
626  return iterator(std::begin(std::get<Ns>(ts))...);
627  }
628  template <size_t... Ns> iterator end_impl(index_sequence<Ns...>) const {
629  return iterator(std::end(std::get<Ns>(ts))...);
630  }
631 
632 public:
633  zippy(Args &&... ts_) : ts(std::forward<Args>(ts_)...) {}
634 
635  iterator begin() const { return begin_impl(index_sequence_for<Args...>{}); }
636  iterator end() const { return end_impl(index_sequence_for<Args...>{}); }
637 };
638 
639 } // end namespace detail
640 
641 /// zip iterator for two or more iteratable types.
642 template <typename T, typename U, typename... Args>
644  Args &&... args) {
645  return detail::zippy<detail::zip_shortest, T, U, Args...>(
646  std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
647 }
648 
649 /// zip iterator that, for the sake of efficiency, assumes the first iteratee to
650 /// be the shortest.
651 template <typename T, typename U, typename... Args>
653  Args &&... args) {
654  return detail::zippy<detail::zip_first, T, U, Args...>(
655  std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
656 }
657 
658 /// Iterator wrapper that concatenates sequences together.
659 ///
660 /// This can concatenate different iterators, even with different types, into
661 /// a single iterator provided the value types of all the concatenated
662 /// iterators expose `reference` and `pointer` types that can be converted to
663 /// `ValueT &` and `ValueT *` respectively. It doesn't support more
664 /// interesting/customized pointer or reference types.
665 ///
666 /// Currently this only supports forward or higher iterator categories as
667 /// inputs and always exposes a forward iterator interface.
668 template <typename ValueT, typename... IterTs>
670  : public iterator_facade_base<concat_iterator<ValueT, IterTs...>,
671  std::forward_iterator_tag, ValueT> {
672  using BaseT = typename concat_iterator::iterator_facade_base;
673 
674  /// We store both the current and end iterators for each concatenated
675  /// sequence in a tuple of pairs.
676  ///
677  /// Note that something like iterator_range seems nice at first here, but the
678  /// range properties are of little benefit and end up getting in the way
679  /// because we need to do mutation on the current iterators.
680  std::tuple<IterTs...> Begins;
681  std::tuple<IterTs...> Ends;
682 
683  /// Attempts to increment a specific iterator.
684  ///
685  /// Returns true if it was able to increment the iterator. Returns false if
686  /// the iterator is already at the end iterator.
687  template <size_t Index> bool incrementHelper() {
688  auto &Begin = std::get<Index>(Begins);
689  auto &End = std::get<Index>(Ends);
690  if (Begin == End)
691  return false;
692 
693  ++Begin;
694  return true;
695  }
696 
697  /// Increments the first non-end iterator.
698  ///
699  /// It is an error to call this with all iterators at the end.
700  template <size_t... Ns> void increment(index_sequence<Ns...>) {
701  // Build a sequence of functions to increment each iterator if possible.
702  bool (concat_iterator::*IncrementHelperFns[])() = {
703  &concat_iterator::incrementHelper<Ns>...};
704 
705  // Loop over them, and stop as soon as we succeed at incrementing one.
706  for (auto &IncrementHelperFn : IncrementHelperFns)
707  if ((this->*IncrementHelperFn)())
708  return;
709 
710  llvm_unreachable("Attempted to increment an end concat iterator!");
711  }
712 
713  /// Returns null if the specified iterator is at the end. Otherwise,
714  /// dereferences the iterator and returns the address of the resulting
715  /// reference.
716  template <size_t Index> ValueT *getHelper() const {
717  auto &Begin = std::get<Index>(Begins);
718  auto &End = std::get<Index>(Ends);
719  if (Begin == End)
720  return nullptr;
721 
722  return &*Begin;
723  }
724 
725  /// Finds the first non-end iterator, dereferences, and returns the resulting
726  /// reference.
727  ///
728  /// It is an error to call this with all iterators at the end.
729  template <size_t... Ns> ValueT &get(index_sequence<Ns...>) const {
730  // Build a sequence of functions to get from iterator if possible.
731  ValueT *(concat_iterator::*GetHelperFns[])() const = {
732  &concat_iterator::getHelper<Ns>...};
733 
734  // Loop over them, and return the first result we find.
735  for (auto &GetHelperFn : GetHelperFns)
736  if (ValueT *P = (this->*GetHelperFn)())
737  return *P;
738 
739  llvm_unreachable("Attempted to get a pointer from an end concat iterator!");
740  }
741 
742 public:
743  /// Constructs an iterator from a squence of ranges.
744  ///
745  /// We need the full range to know how to switch between each of the
746  /// iterators.
747  template <typename... RangeTs>
748  explicit concat_iterator(RangeTs &&... Ranges)
749  : Begins(std::begin(Ranges)...), Ends(std::end(Ranges)...) {}
750 
751  using BaseT::operator++;
752 
754  increment(index_sequence_for<IterTs...>());
755  return *this;
756  }
757 
758  ValueT &operator*() const { return get(index_sequence_for<IterTs...>()); }
759 
760  bool operator==(const concat_iterator &RHS) const {
761  return Begins == RHS.Begins && Ends == RHS.Ends;
762  }
763 };
764 
765 namespace detail {
766 
767 /// Helper to store a sequence of ranges being concatenated and access them.
768 ///
769 /// This is designed to facilitate providing actual storage when temporaries
770 /// are passed into the constructor such that we can use it as part of range
771 /// based for loops.
772 template <typename ValueT, typename... RangeTs> class concat_range {
773 public:
774  using iterator =
776  decltype(std::begin(std::declval<RangeTs &>()))...>;
777 
778 private:
779  std::tuple<RangeTs...> Ranges;
780 
781  template <size_t... Ns> iterator begin_impl(index_sequence<Ns...>) {
782  return iterator(std::get<Ns>(Ranges)...);
783  }
784  template <size_t... Ns> iterator end_impl(index_sequence<Ns...>) {
785  return iterator(make_range(std::end(std::get<Ns>(Ranges)),
786  std::end(std::get<Ns>(Ranges)))...);
787  }
788 
789 public:
790  concat_range(RangeTs &&... Ranges)
791  : Ranges(std::forward<RangeTs>(Ranges)...) {}
792 
793  iterator begin() { return begin_impl(index_sequence_for<RangeTs...>{}); }
794  iterator end() { return end_impl(index_sequence_for<RangeTs...>{}); }
795 };
796 
797 } // end namespace detail
798 
799 /// Concatenated range across two or more ranges.
800 ///
801 /// The desired value type must be explicitly specified.
802 template <typename ValueT, typename... RangeTs>
803 detail::concat_range<ValueT, RangeTs...> concat(RangeTs &&... Ranges) {
804  static_assert(sizeof...(RangeTs) > 1,
805  "Need more than one range to concatenate!");
806  return detail::concat_range<ValueT, RangeTs...>(
807  std::forward<RangeTs>(Ranges)...);
808 }
809 
810 //===----------------------------------------------------------------------===//
811 // Extra additions to <utility>
812 //===----------------------------------------------------------------------===//
813 
814 /// Function object to check whether the first component of a std::pair
815 /// compares less than the first component of another std::pair.
816 struct less_first {
817  template <typename T> bool operator()(const T &lhs, const T &rhs) const {
818  return lhs.first < rhs.first;
819  }
820 };
821 
822 /// Function object to check whether the second component of a std::pair
823 /// compares less than the second component of another std::pair.
824 struct less_second {
825  template <typename T> bool operator()(const T &lhs, const T &rhs) const {
826  return lhs.second < rhs.second;
827  }
828 };
829 
830 /// \brief Function object to apply a binary function to the first component of
831 /// a std::pair.
832 template<typename FuncTy>
833 struct on_first {
834  FuncTy func;
835 
836  template <typename T>
837  auto operator()(const T &lhs, const T &rhs) const
838  -> decltype(func(lhs.first, rhs.first)) {
839  return func(lhs.first, rhs.first);
840  }
841 };
842 
843 // A subset of N3658. More stuff can be added as-needed.
844 
845 /// Represents a compile-time sequence of integers.
846 template <class T, T... I> struct integer_sequence {
847  using value_type = T;
848 
849  static constexpr size_t size() { return sizeof...(I); }
850 };
851 
852 /// Alias for the common case of a sequence of size_ts.
853 template <size_t... I>
854 struct index_sequence : integer_sequence<std::size_t, I...> {};
855 
856 template <std::size_t N, std::size_t... I>
857 struct build_index_impl : build_index_impl<N - 1, N - 1, I...> {};
858 template <std::size_t... I>
859 struct build_index_impl<0, I...> : index_sequence<I...> {};
860 
861 /// Creates a compile-time integer sequence for a parameter pack.
862 template <class... Ts>
863 struct index_sequence_for : build_index_impl<sizeof...(Ts)> {};
864 
865 /// Utility type to build an inheritance chain that makes it easy to rank
866 /// overload candidates.
867 template <int N> struct rank : rank<N - 1> {};
868 template <> struct rank<0> {};
869 
870 /// traits class for checking whether type T is one of any of the given
871 /// types in the variadic list.
872 template <typename T, typename... Ts> struct is_one_of {
873  static const bool value = false;
874 };
875 
876 template <typename T, typename U, typename... Ts>
877 struct is_one_of<T, U, Ts...> {
878  static const bool value =
879  std::is_same<T, U>::value || is_one_of<T, Ts...>::value;
880 };
881 
882 /// traits class for checking whether type T is a base class for all
883 /// the given types in the variadic list.
884 template <typename T, typename... Ts> struct are_base_of {
885  static const bool value = true;
886 };
887 
888 template <typename T, typename U, typename... Ts>
889 struct are_base_of<T, U, Ts...> {
890  static const bool value =
891  std::is_base_of<T, U>::value && are_base_of<T, Ts...>::value;
892 };
893 
894 //===----------------------------------------------------------------------===//
895 // Extra additions for arrays
896 //===----------------------------------------------------------------------===//
897 
898 /// Find the length of an array.
899 template <class T, std::size_t N>
900 constexpr inline size_t array_lengthof(T (&)[N]) {
901  return N;
902 }
903 
904 /// Adapt std::less<T> for array_pod_sort.
905 template<typename T>
906 inline int array_pod_sort_comparator(const void *P1, const void *P2) {
907  if (std::less<T>()(*reinterpret_cast<const T*>(P1),
908  *reinterpret_cast<const T*>(P2)))
909  return -1;
910  if (std::less<T>()(*reinterpret_cast<const T*>(P2),
911  *reinterpret_cast<const T*>(P1)))
912  return 1;
913  return 0;
914 }
915 
916 /// get_array_pod_sort_comparator - This is an internal helper function used to
917 /// get type deduction of T right.
918 template<typename T>
919 inline int (*get_array_pod_sort_comparator(const T &))
920  (const void*, const void*) {
921  return array_pod_sort_comparator<T>;
922 }
923 
924 /// array_pod_sort - This sorts an array with the specified start and end
925 /// extent. This is just like std::sort, except that it calls qsort instead of
926 /// using an inlined template. qsort is slightly slower than std::sort, but
927 /// most sorts are not performance critical in LLVM and std::sort has to be
928 /// template instantiated for each type, leading to significant measured code
929 /// bloat. This function should generally be used instead of std::sort where
930 /// possible.
931 ///
932 /// This function assumes that you have simple POD-like types that can be
933 /// compared with std::less and can be moved with memcpy. If this isn't true,
934 /// you should use std::sort.
935 ///
936 /// NOTE: If qsort_r were portable, we could allow a custom comparator and
937 /// default to std::less.
938 template<class IteratorTy>
939 inline void array_pod_sort(IteratorTy Start, IteratorTy End) {
940  // Don't inefficiently call qsort with one element or trigger undefined
941  // behavior with an empty sequence.
942  auto NElts = End - Start;
943  if (NElts <= 1) return;
944 #ifdef EXPENSIVE_CHECKS
945  std::mt19937 Generator(std::random_device{}());
946  std::shuffle(Start, End, Generator);
947 #endif
948  qsort(&*Start, NElts, sizeof(*Start), get_array_pod_sort_comparator(*Start));
949 }
950 
951 template <class IteratorTy>
952 inline void array_pod_sort(
953  IteratorTy Start, IteratorTy End,
954  int (*Compare)(
955  const typename std::iterator_traits<IteratorTy>::value_type *,
956  const typename std::iterator_traits<IteratorTy>::value_type *)) {
957  // Don't inefficiently call qsort with one element or trigger undefined
958  // behavior with an empty sequence.
959  auto NElts = End - Start;
960  if (NElts <= 1) return;
961 #ifdef EXPENSIVE_CHECKS
962  std::mt19937 Generator(std::random_device{}());
963  std::shuffle(Start, End, Generator);
964 #endif
965  qsort(&*Start, NElts, sizeof(*Start),
966  reinterpret_cast<int (*)(const void *, const void *)>(Compare));
967 }
968 
969 // Provide wrappers to std::sort which shuffle the elements before sorting
970 // to help uncover non-deterministic behavior (PR35135).
971 template <typename IteratorTy>
972 inline void sort(IteratorTy Start, IteratorTy End) {
973 #ifdef EXPENSIVE_CHECKS
974  std::mt19937 Generator(std::random_device{}());
975  std::shuffle(Start, End, Generator);
976 #endif
977  std::sort(Start, End);
978 }
979 
980 template <typename Container> inline void sort(Container &&C) {
982 }
983 
984 template <typename IteratorTy, typename Compare>
985 inline void sort(IteratorTy Start, IteratorTy End, Compare Comp) {
986 #ifdef EXPENSIVE_CHECKS
987  std::mt19937 Generator(std::random_device{}());
988  std::shuffle(Start, End, Generator);
989 #endif
990  std::sort(Start, End, Comp);
991 }
992 
993 template <typename Container, typename Compare>
994 inline void sort(Container &&C, Compare Comp) {
995  llvm::sort(adl_begin(C), adl_end(C), Comp);
996 }
997 
998 //===----------------------------------------------------------------------===//
999 // Extra additions to <algorithm>
1000 //===----------------------------------------------------------------------===//
1001 
1002 /// For a container of pointers, deletes the pointers and then clears the
1003 /// container.
1004 template<typename Container>
1005 void DeleteContainerPointers(Container &C) {
1006  for (auto V : C)
1007  delete V;
1008  C.clear();
1009 }
1010 
1011 /// In a container of pairs (usually a map) whose second element is a pointer,
1012 /// deletes the second elements and then clears the container.
1013 template<typename Container>
1014 void DeleteContainerSeconds(Container &C) {
1015  for (auto &V : C)
1016  delete V.second;
1017  C.clear();
1018 }
1019 
1020 /// Get the size of a range. This is a wrapper function around std::distance
1021 /// which is only enabled when the operation is O(1).
1022 template <typename R>
1023 auto size(R &&Range, typename std::enable_if<
1024  std::is_same<typename std::iterator_traits<decltype(
1025  Range.begin())>::iterator_category,
1026  std::random_access_iterator_tag>::value,
1027  void>::type * = nullptr)
1028  -> decltype(std::distance(Range.begin(), Range.end())) {
1029  return std::distance(Range.begin(), Range.end());
1030 }
1031 
1032 /// Provide wrappers to std::for_each which take ranges instead of having to
1033 /// pass begin/end explicitly.
1034 template <typename R, typename UnaryPredicate>
1035 UnaryPredicate for_each(R &&Range, UnaryPredicate P) {
1036  return std::for_each(adl_begin(Range), adl_end(Range), P);
1037 }
1038 
1039 /// Provide wrappers to std::all_of which take ranges instead of having to pass
1040 /// begin/end explicitly.
1041 template <typename R, typename UnaryPredicate>
1042 bool all_of(R &&Range, UnaryPredicate P) {
1043  return std::all_of(adl_begin(Range), adl_end(Range), P);
1044 }
1045 
1046 /// Provide wrappers to std::any_of which take ranges instead of having to pass
1047 /// begin/end explicitly.
1048 template <typename R, typename UnaryPredicate>
1049 bool any_of(R &&Range, UnaryPredicate P) {
1050  return std::any_of(adl_begin(Range), adl_end(Range), P);
1051 }
1052 
1053 /// Provide wrappers to std::none_of which take ranges instead of having to pass
1054 /// begin/end explicitly.
1055 template <typename R, typename UnaryPredicate>
1056 bool none_of(R &&Range, UnaryPredicate P) {
1057  return std::none_of(adl_begin(Range), adl_end(Range), P);
1058 }
1059 
1060 /// Provide wrappers to std::find which take ranges instead of having to pass
1061 /// begin/end explicitly.
1062 template <typename R, typename T>
1063 auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range)) {
1064  return std::find(adl_begin(Range), adl_end(Range), Val);
1065 }
1066 
1067 /// Provide wrappers to std::find_if which take ranges instead of having to pass
1068 /// begin/end explicitly.
1069 template <typename R, typename UnaryPredicate>
1070 auto find_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) {
1071  return std::find_if(adl_begin(Range), adl_end(Range), P);
1072 }
1073 
1074 template <typename R, typename UnaryPredicate>
1075 auto find_if_not(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) {
1076  return std::find_if_not(adl_begin(Range), adl_end(Range), P);
1077 }
1078 
1079 /// Provide wrappers to std::remove_if which take ranges instead of having to
1080 /// pass begin/end explicitly.
1081 template <typename R, typename UnaryPredicate>
1082 auto remove_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) {
1083  return std::remove_if(adl_begin(Range), adl_end(Range), P);
1084 }
1085 
1086 /// Provide wrappers to std::copy_if which take ranges instead of having to
1087 /// pass begin/end explicitly.
1088 template <typename R, typename OutputIt, typename UnaryPredicate>
1089 OutputIt copy_if(R &&Range, OutputIt Out, UnaryPredicate P) {
1090  return std::copy_if(adl_begin(Range), adl_end(Range), Out, P);
1091 }
1092 
1093 template <typename R, typename OutputIt>
1094 OutputIt copy(R &&Range, OutputIt Out) {
1095  return std::copy(adl_begin(Range), adl_end(Range), Out);
1096 }
1097 
1098 /// Wrapper function around std::find to detect if an element exists
1099 /// in a container.
1100 template <typename R, typename E>
1101 bool is_contained(R &&Range, const E &Element) {
1102  return std::find(adl_begin(Range), adl_end(Range), Element) != adl_end(Range);
1103 }
1104 
1105 /// Wrapper function around std::count to count the number of times an element
1106 /// \p Element occurs in the given range \p Range.
1107 template <typename R, typename E>
1108 auto count(R &&Range, const E &Element) ->
1109  typename std::iterator_traits<decltype(adl_begin(Range))>::difference_type {
1110  return std::count(adl_begin(Range), adl_end(Range), Element);
1111 }
1112 
1113 /// Wrapper function around std::count_if to count the number of times an
1114 /// element satisfying a given predicate occurs in a range.
1115 template <typename R, typename UnaryPredicate>
1116 auto count_if(R &&Range, UnaryPredicate P) ->
1117  typename std::iterator_traits<decltype(adl_begin(Range))>::difference_type {
1118  return std::count_if(adl_begin(Range), adl_end(Range), P);
1119 }
1120 
1121 /// Wrapper function around std::transform to apply a function to a range and
1122 /// store the result elsewhere.
1123 template <typename R, typename OutputIt, typename UnaryPredicate>
1124 OutputIt transform(R &&Range, OutputIt d_first, UnaryPredicate P) {
1125  return std::transform(adl_begin(Range), adl_end(Range), d_first, P);
1126 }
1127 
1128 /// Provide wrappers to std::partition which take ranges instead of having to
1129 /// pass begin/end explicitly.
1130 template <typename R, typename UnaryPredicate>
1131 auto partition(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) {
1132  return std::partition(adl_begin(Range), adl_end(Range), P);
1133 }
1134 
1135 /// Provide wrappers to std::lower_bound which take ranges instead of having to
1136 /// pass begin/end explicitly.
1137 template <typename R, typename ForwardIt>
1138 auto lower_bound(R &&Range, ForwardIt I) -> decltype(adl_begin(Range)) {
1139  return std::lower_bound(adl_begin(Range), adl_end(Range), I);
1140 }
1141 
1142 /// Provide wrappers to std::upper_bound which take ranges instead of having to
1143 /// pass begin/end explicitly.
1144 template <typename R, typename ForwardIt>
1145 auto upper_bound(R &&Range, ForwardIt I) -> decltype(adl_begin(Range)) {
1146  return std::upper_bound(adl_begin(Range), adl_end(Range), I);
1147 }
1148 
1149 template <typename R, typename ForwardIt, typename Compare>
1150 auto upper_bound(R &&Range, ForwardIt I, Compare C)
1151  -> decltype(adl_begin(Range)) {
1152  return std::upper_bound(adl_begin(Range), adl_end(Range), I, C);
1153 }
1154 /// Wrapper function around std::equal to detect if all elements
1155 /// in a container are same.
1156 template <typename R>
1157 bool is_splat(R &&Range) {
1158  size_t range_size = size(Range);
1159  return range_size != 0 && (range_size == 1 ||
1160  std::equal(adl_begin(Range) + 1, adl_end(Range), adl_begin(Range)));
1161 }
1162 
1163 /// Given a range of type R, iterate the entire range and return a
1164 /// SmallVector with elements of the vector. This is useful, for example,
1165 /// when you want to iterate a range and then sort the results.
1166 template <unsigned Size, typename R>
1168 to_vector(R &&Range) {
1169  return {adl_begin(Range), adl_end(Range)};
1170 }
1171 
1172 /// Provide a container algorithm similar to C++ Library Fundamentals v2's
1173 /// `erase_if` which is equivalent to:
1174 ///
1175 /// C.erase(remove_if(C, pred), C.end());
1176 ///
1177 /// This version works for any container with an erase method call accepting
1178 /// two iterators.
1179 template <typename Container, typename UnaryPredicate>
1180 void erase_if(Container &C, UnaryPredicate P) {
1181  C.erase(remove_if(C, P), C.end());
1182 }
1183 
1184 //===----------------------------------------------------------------------===//
1185 // Extra additions to <memory>
1186 //===----------------------------------------------------------------------===//
1187 
1188 // Implement make_unique according to N3656.
1189 
1190 /// Constructs a `new T()` with the given args and returns a
1191 /// `unique_ptr<T>` which owns the object.
1192 ///
1193 /// Example:
1194 ///
1195 /// auto p = make_unique<int>();
1196 /// auto p = make_unique<std::tuple<int, int>>(0, 1);
1197 template <class T, class... Args>
1198 typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
1199 make_unique(Args &&... args) {
1200  return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
1201 }
1202 
1203 /// Constructs a `new T[n]` with the given args and returns a
1204 /// `unique_ptr<T[]>` which owns the object.
1205 ///
1206 /// \param n size of the new array.
1207 ///
1208 /// Example:
1209 ///
1210 /// auto p = make_unique<int[]>(2); // value-initializes the array with 0's.
1211 template <class T>
1212 typename std::enable_if<std::is_array<T>::value && std::extent<T>::value == 0,
1213  std::unique_ptr<T>>::type
1214 make_unique(size_t n) {
1215  return std::unique_ptr<T>(new typename std::remove_extent<T>::type[n]());
1216 }
1217 
1218 /// This function isn't used and is only here to provide better compile errors.
1219 template <class T, class... Args>
1220 typename std::enable_if<std::extent<T>::value != 0>::type
1221 make_unique(Args &&...) = delete;
1222 
1223 struct FreeDeleter {
1224  void operator()(void* v) {
1225  ::free(v);
1226  }
1227 };
1228 
1229 template<typename First, typename Second>
1230 struct pair_hash {
1231  size_t operator()(const std::pair<First, Second> &P) const {
1232  return std::hash<First>()(P.first) * 31 + std::hash<Second>()(P.second);
1233  }
1234 };
1235 
1236 /// A functor like C++14's std::less<void> in its absence.
1237 struct less {
1238  template <typename A, typename B> bool operator()(A &&a, B &&b) const {
1239  return std::forward<A>(a) < std::forward<B>(b);
1240  }
1241 };
1242 
1243 /// A functor like C++14's std::equal<void> in its absence.
1244 struct equal {
1245  template <typename A, typename B> bool operator()(A &&a, B &&b) const {
1246  return std::forward<A>(a) == std::forward<B>(b);
1247  }
1248 };
1249 
1250 /// Binary functor that adapts to any other binary functor after dereferencing
1251 /// operands.
1252 template <typename T> struct deref {
1253  T func;
1254 
1255  // Could be further improved to cope with non-derivable functors and
1256  // non-binary functors (should be a variadic template member function
1257  // operator()).
1258  template <typename A, typename B>
1259  auto operator()(A &lhs, B &rhs) const -> decltype(func(*lhs, *rhs)) {
1260  assert(lhs);
1261  assert(rhs);
1262  return func(*lhs, *rhs);
1263  }
1264 };
1265 
1266 namespace detail {
1267 
1268 template <typename R> class enumerator_iter;
1269 
1270 template <typename R> struct result_pair {
1271  friend class enumerator_iter<R>;
1272 
1273  result_pair() = default;
1274  result_pair(std::size_t Index, IterOfRange<R> Iter)
1275  : Index(Index), Iter(Iter) {}
1276 
1278  Index = Other.Index;
1279  Iter = Other.Iter;
1280  return *this;
1281  }
1282 
1283  std::size_t index() const { return Index; }
1284  const ValueOfRange<R> &value() const { return *Iter; }
1285  ValueOfRange<R> &value() { return *Iter; }
1286 
1287 private:
1289  IterOfRange<R> Iter;
1290 };
1291 
1292 template <typename R>
1293 class enumerator_iter
1294  : public iterator_facade_base<
1295  enumerator_iter<R>, std::forward_iterator_tag, result_pair<R>,
1296  typename std::iterator_traits<IterOfRange<R>>::difference_type,
1297  typename std::iterator_traits<IterOfRange<R>>::pointer,
1298  typename std::iterator_traits<IterOfRange<R>>::reference> {
1299  using result_type = result_pair<R>;
1300 
1301 public:
1303  : Result(std::numeric_limits<size_t>::max(), EndIter) {}
1304 
1306  : Result(Index, Iter) {}
1307 
1308  result_type &operator*() { return Result; }
1309  const result_type &operator*() const { return Result; }
1310 
1313  ++Result.Iter;
1314  ++Result.Index;
1315  return *this;
1316  }
1317 
1318  bool operator==(const enumerator_iter<R> &RHS) const {
1319  // Don't compare indices here, only iterators. It's possible for an end
1320  // iterator to have different indices depending on whether it was created
1321  // by calling std::end() versus incrementing a valid iterator.
1322  return Result.Iter == RHS.Result.Iter;
1323  }
1324 
1326  Result = Other.Result;
1327  return *this;
1328  }
1329 
1330 private:
1331  result_type Result;
1332 };
1333 
1334 template <typename R> class enumerator {
1335 public:
1336  explicit enumerator(R &&Range) : TheRange(std::forward<R>(Range)) {}
1337 
1339  return enumerator_iter<R>(0, std::begin(TheRange));
1340  }
1341 
1343  return enumerator_iter<R>(std::end(TheRange));
1344  }
1345 
1346 private:
1347  R TheRange;
1348 };
1349 
1350 } // end namespace detail
1351 
1352 /// Given an input range, returns a new range whose values are are pair (A,B)
1353 /// such that A is the 0-based index of the item in the sequence, and B is
1354 /// the value from the original sequence. Example:
1355 ///
1356 /// std::vector<char> Items = {'A', 'B', 'C', 'D'};
1357 /// for (auto X : enumerate(Items)) {
1358 /// printf("Item %d - %c\n", X.index(), X.value());
1359 /// }
1360 ///
1361 /// Output:
1362 /// Item 0 - A
1363 /// Item 1 - B
1364 /// Item 2 - C
1365 /// Item 3 - D
1366 ///
1367 template <typename R> detail::enumerator<R> enumerate(R &&TheRange) {
1368  return detail::enumerator<R>(std::forward<R>(TheRange));
1369 }
1370 
1371 namespace detail {
1372 
1373 template <typename F, typename Tuple, std::size_t... I>
1375  -> decltype(std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...)) {
1376  return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...);
1377 }
1378 
1379 } // end namespace detail
1380 
1381 /// Given an input tuple (a1, a2, ..., an), pass the arguments of the
1382 /// tuple variadically to f as if by calling f(a1, a2, ..., an) and
1383 /// return the result.
1384 template <typename F, typename Tuple>
1385 auto apply_tuple(F &&f, Tuple &&t) -> decltype(detail::apply_tuple_impl(
1386  std::forward<F>(f), std::forward<Tuple>(t),
1388  std::tuple_size<typename std::decay<Tuple>::type>::value>{})) {
1389  using Indices = build_index_impl<
1390  std::tuple_size<typename std::decay<Tuple>::type>::value>;
1391 
1392  return detail::apply_tuple_impl(std::forward<F>(f), std::forward<Tuple>(t),
1393  Indices{});
1394 }
1395 
1396 } // end namespace llvm
1397 
1398 #endif // LLVM_ADT_STLEXTRAS_H
detail::concat_range< ValueT, RangeTs... > concat(RangeTs &&... Ranges)
Concatenated range across two or more ranges.
Definition: STLExtras.h:803
result_pair(std::size_t Index, IterOfRange< R > Iter)
Definition: STLExtras.h:1274
void DeleteContainerSeconds(Container &C)
In a container of pairs (usually a map) whose second element is a pointer, deletes the second element...
Definition: STLExtras.h:1014
uint64_t CallInst * C
void DeleteContainerPointers(Container &C)
For a container of pointers, deletes the pointers and then clears the container.
Definition: STLExtras.h:1005
bool operator()(const Ty *left, const Ty *right) const
Definition: STLExtras.h:96
ZipType & operator++()
Definition: STLExtras.h:570
bool operator==(const enumerator_iter< R > &RHS) const
Definition: STLExtras.h:1318
const_iterator end(StringRef path)
Get end iterator over path.
Definition: Path.cpp:259
filter_iterator_impl(WrappedIteratorT Begin, WrappedIteratorT End, PredicateT Pred)
Definition: STLExtras.h:364
zippy(Args &&... ts_)
Definition: STLExtras.h:633
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
Ret operator()(Params ...params) const
Definition: STLExtras.h:132
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
Definition: Path.cpp:250
bool operator()(const T &lhs, const T &rhs) const
Definition: STLExtras.h:817
typename fwd_or_bidi_tag_impl< std::is_base_of< std::bidirectional_iterator_tag, typename std::iterator_traits< IterT >::iterator_category >::value >::type type
Definition: STLExtras.h:391
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
A pseudo-iterator adaptor that is designed to implement "early increment" style loops.
Definition: STLExtras.h:440
typename std::remove_reference< decltype(*std::begin(std::declval< RangeT & >()))>::type ValueOfRange
Definition: STLExtras.h:57
decltype(iterators) tup_inc(index_sequence< Ns... >) const
Definition: STLExtras.h:552
Function object to check whether the second component of a std::pair compares less than the second co...
Definition: STLExtras.h:824
OutputIt copy_if(R &&Range, OutputIt Out, UnaryPredicate P)
Provide wrappers to std::copy_if which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1089
typename iterator::value_type value_type
Definition: STLExtras.h:617
const Ty & operator()(const Ty &self) const
Definition: STLExtras.h:84
This provides a very simple, boring adaptor for a begin and end iterator into a range type...
filter_iterator_base(WrappedIteratorT Begin, WrappedIteratorT End, PredicateT Pred)
Definition: STLExtras.h:319
int(*)(const void *, const void *) get_array_pod_sort_comparator(const T &)
get_array_pod_sort_comparator - This is an internal helper function used to get type deduction of T r...
Definition: STLExtras.h:919
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition: STLExtras.h:498
auto operator()(const T &lhs, const T &rhs) const -> decltype(func(lhs.first, rhs.first))
Definition: STLExtras.h:837
bool operator()(const T &lhs, const T &rhs) const
Definition: STLExtras.h:825
An efficient, type-erasing, non-owning reference to a callable.
Definition: STLExtras.h:107
A functor like C++14&#39;s std::less<void> in its absence.
Definition: STLExtras.h:1237
zip_common(Iters &&... ts)
Definition: STLExtras.h:562
void adl_swap(T &&lhs, T &&rhs) noexcept(noexcept(adl_detail::adl_swap(std::declval< T >(), std::declval< T >())))
Definition: STLExtras.h:193
enumerator_iter(IterOfRange< R > EndIter)
Definition: STLExtras.h:1302
auto count_if(R &&Range, UnaryPredicate P) -> typename std::iterator_traits< decltype(adl_begin(Range))>::difference_type
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition: STLExtras.h:1116
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1042
early_inc_iterator_impl(WrappedIteratorT I)
Definition: STLExtras.h:455
F(f)
block Block Frequency true
std::tuple< decltype(*declval< Iters >())... > type
Definition: STLExtras.h:520
std::enable_if<!std::is_array< T >::value, std::unique_ptr< T > >::type make_unique(Args &&... args)
Constructs a new T() with the given args and returns a unique_ptr<T> which owns the object...
Definition: STLExtras.h:1199
BaseT::reference operator*()
Definition: STLExtras.h:458
typename iterator::pointer pointer
Definition: STLExtras.h:619
int array_pod_sort_comparator(const void *P1, const void *P2)
Adapt std::less<T> for array_pod_sort.
Definition: STLExtras.h:906
void adl_swap(T &&lhs, T &&rhs) noexcept(noexcept(swap(std::declval< T >(), std::declval< T >())))
Definition: STLExtras.h:173
Metafunction to determine if T& or T has a member called rbegin().
Definition: STLExtras.h:245
function_ref(Callable &&callable, typename std::enable_if< !std::is_same< typename std::remove_reference< Callable >::type, function_ref >::value >::type *=nullptr)
Definition: STLExtras.h:125
Ty & operator()(Ty &self) const
Definition: STLExtras.h:81
Definition: BitVector.h:938
void sort(Container &&C, Compare Comp)
Definition: STLExtras.h:994
concat_range(RangeTs &&... Ranges)
Definition: STLExtras.h:790
std::bidirectional_iterator_tag type
Definition: STLExtras.h:382
void operator()(void *v)
Definition: STLExtras.h:1224
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1056
decltype(iterators) tup_dec(index_sequence< Ns... >) const
Definition: STLExtras.h:557
auto upper_bound(R &&Range, ForwardIt I, Compare C) -> decltype(adl_begin(Range))
Definition: STLExtras.h:1150
SmallVector< typename std::remove_const< detail::ValueOfRange< R > >::type, Size > to_vector(R &&Range)
Given a range of type R, iterate the entire range and return a SmallVector with elements of the vecto...
Definition: STLExtras.h:1168
Alias for the common case of a sequence of size_ts.
Definition: STLExtras.h:509
ELFYAML::ELF_STO Other
Definition: ELFYAML.cpp:773
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
Definition: STLExtras.h:251
bool operator()(const Ty *left, const Ty *right) const
Definition: STLExtras.h:90
#define T
enumerator_iter< R > & operator++()
Definition: STLExtras.h:1311
auto apply_tuple(F &&f, Tuple &&t) -> decltype(detail::apply_tuple_impl(std::forward< F >(f), std::forward< Tuple >(t), build_index_impl< std::tuple_size< typename std::decay< Tuple >::type >::value >
Given an input tuple (a1, a2, ..., an), pass the arguments of the tuple variadically to f as if by ca...
Definition: STLExtras.h:1385
auto partition(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
Provide wrappers to std::partition which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1131
auto lower_bound(R &&Range, ForwardIt I) -> decltype(adl_begin(Range))
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1138
CRTP base class which implements the entire standard iterator facade in terms of a minimal subset of ...
Definition: iterator.h:68
enumerator_iter(std::size_t Index, IterOfRange< R > Iter)
Definition: STLExtras.h:1305
Helper to store a sequence of ranges being concatenated and access them.
Definition: STLExtras.h:772
auto count(R &&Range, const E &Element) -> typename std::iterator_traits< decltype(adl_begin(Range))>::difference_type
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition: STLExtras.h:1108
traits class for checking whether type T is one of any of the given types in the variadic list...
Definition: STLExtras.h:872
ValueOfRange< R > & value()
Definition: STLExtras.h:1285
typename iterator::reference reference
Definition: STLExtras.h:620
#define P(N)
void array_pod_sort(IteratorTy Start, IteratorTy End)
array_pod_sort - This sorts an array with the specified start and end extent.
Definition: STLExtras.h:939
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
auto operator()(A &lhs, B &rhs) const -> decltype(func(*lhs, *rhs))
Definition: STLExtras.h:1259
auto adl_end(ContainerTy &&container) -> decltype(end(std::forward< ContainerTy >(container)))
Definition: STLExtras.h:165
ZipType & operator--()
Definition: STLExtras.h:575
bool operator==(const early_inc_iterator_impl &RHS) const
Definition: STLExtras.h:476
bool is_splat(R &&Range)
Wrapper function around std::equal to detect if all elements in a container are same.
Definition: STLExtras.h:1157
CRTP base class for adapting an iterator to a different type.
Definition: iterator.h:208
mapped_iterator(ItTy U, FuncTy F)
Definition: STLExtras.h:210
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&... args)
zip iterator for two or more iteratable types.
Definition: STLExtras.h:643
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
const result_type & operator*() const
Definition: STLExtras.h:1309
mapped_iterator< ItTy, FuncTy > map_iterator(ItTy I, FuncTy F)
Definition: STLExtras.h:224
auto adl_begin(ContainerTy &&container) -> decltype(adl_detail::adl_begin(std::forward< ContainerTy >(container)))
Definition: STLExtras.h:181
filter_iterator_impl(WrappedIteratorT Begin, WrappedIteratorT End, PredicateT Pred)
Definition: STLExtras.h:343
Helper to determine if type T has a member called rbegin().
Definition: STLExtras.h:229
bool any_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1049
auto find_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1070
auto remove_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
Provide wrappers to std::remove_if which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1082
auto find_if_not(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
Definition: STLExtras.h:1075
detail::zippy< detail::zip_first, T, U, Args... > zip_first(T &&t, U &&u, Args &&... args)
zip iterator that, for the sake of efficiency, assumes the first iteratee to be the shortest...
Definition: STLExtras.h:652
auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1063
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
static constexpr size_t size()
Definition: STLExtras.h:849
iterator end() const
Definition: STLExtras.h:636
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:972
bool operator()(A &&a, B &&b) const
Definition: STLExtras.h:1238
auto apply_tuple_impl(F &&f, Tuple &&t, index_sequence< I... >) -> decltype(std::forward< F >(f)(std::get< I >(std::forward< Tuple >(t))...))
Definition: STLExtras.h:1374
A functor like C++14&#39;s std::equal<void> in its absence.
Definition: STLExtras.h:1244
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
value_type deref(index_sequence< Ns... >) const
Definition: STLExtras.h:547
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
Definition: STLExtras.h:1023
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:847
constexpr size_t array_lengthof(T(&)[N])
Find the length of an array.
Definition: STLExtras.h:900
An iterator adaptor that filters the elements of given inner iterators.
Definition: STLExtras.h:293
Creates a compile-time integer sequence for a parameter pack.
Definition: STLExtras.h:511
auto adl_begin(ContainerTy &&container) -> decltype(begin(std::forward< ContainerTy >(container)))
Definition: STLExtras.h:157
typename iterator::difference_type difference_type
Definition: STLExtras.h:618
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2&#39;s erase_if which is equivalent t...
Definition: STLExtras.h:1180
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:941
A range adaptor for a pair of iterators.
bool operator()(A &&a, B &&b) const
Definition: STLExtras.h:1245
std::forward_iterator_tag type
Definition: STLExtras.h:378
Represents a compile-time sequence of integers.
Definition: STLExtras.h:846
filter_iterator_base & operator++()
Definition: STLExtras.h:328
bool operator==(const StringView &LHS, const StringView &RHS)
Definition: StringView.h:116
Helper which sets its type member to forward_iterator_tag if the category of IterT does not derive fr...
Definition: STLExtras.h:388
enumerator_iter< R > & operator=(const enumerator_iter< R > &Other)
Definition: STLExtras.h:1325
concat_iterator & operator++()
Definition: STLExtras.h:753
FuncReturnTy operator*()
Definition: STLExtras.h:215
result_pair< R > & operator=(const result_pair< R > &Other)
Definition: STLExtras.h:1277
ValueT & operator*() const
Definition: STLExtras.h:758
bool operator==(const zip_first< Iters... > &other) const
Definition: STLExtras.h:587
WrappedIteratorT End
Definition: STLExtras.h:308
#define I(x, y, z)
Definition: MD5.cpp:58
#define N
bool operator==(const concat_iterator &RHS) const
Definition: STLExtras.h:760
typename iterator::iterator_category iterator_category
Definition: STLExtras.h:616
value_type operator*()
Definition: STLExtras.h:564
decltype(std::begin(std::declval< RangeT & >())) IterOfRange
Definition: STLExtras.h:53
uint32_t Size
Definition: Profile.cpp:47
const ValueOfRange< R > & value() const
Definition: STLExtras.h:1284
iterator_range< filter_iterator< detail::IterOfRange< RangeT >, PredicateT > > make_filter_range(RangeT &&Range, PredicateT Pred)
Convenience function that takes a range of elements and a predicate, and return a new filter_iterator...
Definition: STLExtras.h:412
std::tuple< Iters... > iterators
Definition: STLExtras.h:544
OutputIt transform(R &&Range, OutputIt d_first, UnaryPredicate P)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere...
Definition: STLExtras.h:1124
const value_type operator*() const
Definition: STLExtras.h:566
auto upper_bound(R &&Range, ForwardIt I) -> decltype(adl_begin(Range))
Provide wrappers to std::upper_bound which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1145
auto adl_end(ContainerTy &&container) -> decltype(adl_detail::adl_end(std::forward< ContainerTy >(container)))
Definition: STLExtras.h:187
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
std::reverse_iterator< IteratorTy > make_reverse_iterator(IteratorTy It)
Definition: STLExtras.h:259
traits class for checking whether type T is a base class for all the given types in the variadic list...
Definition: STLExtras.h:884
enumerator_iter< R > begin()
Definition: STLExtras.h:1338
early_inc_iterator_impl & operator++()
Definition: STLExtras.h:467
Function object to apply a binary function to the first component of a std::pair. ...
Definition: STLExtras.h:833
enumerator_iter< R > end()
Definition: STLExtras.h:1342
Specialization of filter_iterator_base for forward iteration only.
Definition: STLExtras.h:338
iterator begin() const
Definition: STLExtras.h:635
Binary functor that adapts to any other binary functor after dereferencing operands.
Definition: STLExtras.h:1252
Iterator wrapper that concatenates sequences together.
Definition: STLExtras.h:669
Utility type to build an inheritance chain that makes it easy to rank overload candidates.
Definition: STLExtras.h:867
zip_shortest(Iters &&... ts)
Definition: STLExtras.h:606
UnaryPredicate for_each(R &&Range, UnaryPredicate P)
Provide wrappers to std::for_each which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1035
void deleter(T *Ptr)
Definition: STLExtras.h:144
OutputIt copy(R &&Range, OutputIt Out)
Definition: STLExtras.h:1094
zip_first(Iters &&... ts)
Definition: STLExtras.h:591
std::size_t index() const
Definition: STLExtras.h:1283
Function object to check whether the first component of a std::pair compares less than the first comp...
Definition: STLExtras.h:816
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
concat_iterator(RangeTs &&... Ranges)
Constructs an iterator from a squence of ranges.
Definition: STLExtras.h:748
bool operator==(const zip_shortest< Iters... > &other) const
Definition: STLExtras.h:608
detail::enumerator< R > enumerate(R &&TheRange)
Given an input range, returns a new range whose values are are pair (A,B) such that A is the 0-based ...
Definition: STLExtras.h:1367
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.
Definition: STLExtras.h:1101
size_t operator()(const std::pair< First, Second > &P) const
Definition: STLExtras.h:1231