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