1 //===- llvm/ADT/STLExtras.h - Useful STL related functions ------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains some templates that are useful if you are working with the
13 // No library is required when using these functions.
15 //===----------------------------------------------------------------------===//
17 #ifndef LLVM_ADT_STLEXTRAS_H
18 #define LLVM_ADT_STLEXTRAS_H
20 #include "llvm/Support/Compiler.h"
21 #include <algorithm> // for std::all_of
23 #include <cstddef> // for std::size_t
24 #include <cstdlib> // for qsort
28 #include <utility> // for std::pair
32 //===----------------------------------------------------------------------===//
33 // Extra additions to <functional>
34 //===----------------------------------------------------------------------===//
37 struct identity : public std::unary_function<Ty, Ty> {
38 Ty &operator()(Ty &self) const {
41 const Ty &operator()(const Ty &self) const {
47 struct less_ptr : public std::binary_function<Ty, Ty, bool> {
48 bool operator()(const Ty* left, const Ty* right) const {
49 return *left < *right;
54 struct greater_ptr : public std::binary_function<Ty, Ty, bool> {
55 bool operator()(const Ty* left, const Ty* right) const {
56 return *right < *left;
60 /// An efficient, type-erasing, non-owning reference to a callable. This is
61 /// intended for use as the type of a function parameter that is not used
62 /// after the function in question returns.
64 /// This class does not own the callable, so it is not in general safe to store
66 template<typename Fn> class function_ref;
68 template<typename Ret, typename ...Params>
69 class function_ref<Ret(Params...)> {
70 Ret (*callback)(intptr_t callable, Params ...params);
73 template<typename Callable>
74 static Ret callback_fn(intptr_t callable, Params ...params) {
75 return (*reinterpret_cast<Callable*>(callable))(
76 std::forward<Params>(params)...);
80 template <typename Callable>
81 function_ref(Callable &&callable,
82 typename std::enable_if<
83 !std::is_same<typename std::remove_reference<Callable>::type,
84 function_ref>::value>::type * = nullptr)
85 : callback(callback_fn<typename std::remove_reference<Callable>::type>),
86 callable(reinterpret_cast<intptr_t>(&callable)) {}
87 Ret operator()(Params ...params) const {
88 return callback(callable, std::forward<Params>(params)...);
92 // deleter - Very very very simple method that is used to invoke operator
93 // delete on something. It is used like this:
95 // for_each(V.begin(), B.end(), deleter<Interval>);
98 inline void deleter(T *Ptr) {
104 //===----------------------------------------------------------------------===//
105 // Extra additions to <iterator>
106 //===----------------------------------------------------------------------===//
108 // mapped_iterator - This is a simple iterator adapter that causes a function to
109 // be dereferenced whenever operator* is invoked on the iterator.
111 template <class RootIt, class UnaryFunc>
112 class mapped_iterator {
116 typedef typename std::iterator_traits<RootIt>::iterator_category
118 typedef typename std::iterator_traits<RootIt>::difference_type
120 typedef typename UnaryFunc::result_type value_type;
122 typedef void pointer;
123 //typedef typename UnaryFunc::result_type *pointer;
124 typedef void reference; // Can't modify value returned by fn
126 typedef RootIt iterator_type;
128 inline const RootIt &getCurrent() const { return current; }
129 inline const UnaryFunc &getFunc() const { return Fn; }
131 inline explicit mapped_iterator(const RootIt &I, UnaryFunc F)
132 : current(I), Fn(F) {}
134 inline value_type operator*() const { // All this work to do this
135 return Fn(*current); // little change
138 mapped_iterator &operator++() {
142 mapped_iterator &operator--() {
146 mapped_iterator operator++(int) {
147 mapped_iterator __tmp = *this;
151 mapped_iterator operator--(int) {
152 mapped_iterator __tmp = *this;
156 mapped_iterator operator+(difference_type n) const {
157 return mapped_iterator(current + n, Fn);
159 mapped_iterator &operator+=(difference_type n) {
163 mapped_iterator operator-(difference_type n) const {
164 return mapped_iterator(current - n, Fn);
166 mapped_iterator &operator-=(difference_type n) {
170 reference operator[](difference_type n) const { return *(*this + n); }
172 bool operator!=(const mapped_iterator &X) const { return !operator==(X); }
173 bool operator==(const mapped_iterator &X) const {
174 return current == X.current;
176 bool operator<(const mapped_iterator &X) const { return current < X.current; }
178 difference_type operator-(const mapped_iterator &X) const {
179 return current - X.current;
183 template <class Iterator, class Func>
184 inline mapped_iterator<Iterator, Func>
185 operator+(typename mapped_iterator<Iterator, Func>::difference_type N,
186 const mapped_iterator<Iterator, Func> &X) {
187 return mapped_iterator<Iterator, Func>(X.getCurrent() - N, X.getFunc());
191 // map_iterator - Provide a convenient way to create mapped_iterators, just like
192 // make_pair is useful for creating pairs...
194 template <class ItTy, class FuncTy>
195 inline mapped_iterator<ItTy, FuncTy> map_iterator(const ItTy &I, FuncTy F) {
196 return mapped_iterator<ItTy, FuncTy>(I, F);
199 // Returns an iterator_range over the given container which iterates in reverse.
200 // Note that the container must have rbegin()/rend() methods for this to work.
201 template<typename ContainerTy>
202 auto reverse(ContainerTy &C)->decltype(make_range(C.rbegin(), C.rend())) {
203 return make_range(C.rbegin(), C.rend());
206 // Returns a std::reverse_iterator wrapped around the given iterator.
207 template<typename IteratorTy>
208 std::reverse_iterator<IteratorTy> make_reverse_iterator(IteratorTy It) {
209 return std::reverse_iterator<IteratorTy>(It);
212 // Returns an iterator_range over the given container which iterates in reverse.
213 // Note that the container must have begin()/end() methods which return
214 // bidirectional iterators for this to work.
215 template<typename ContainerTy>
216 auto reverse(ContainerTy &&C)
217 ->decltype(make_range(make_reverse_iterator(std::end(C)),
218 make_reverse_iterator(std::begin(C)))) {
219 return make_range(make_reverse_iterator(std::end(C)),
220 make_reverse_iterator(std::begin(C)));
223 //===----------------------------------------------------------------------===//
224 // Extra additions to <utility>
225 //===----------------------------------------------------------------------===//
227 /// \brief Function object to check whether the first component of a std::pair
228 /// compares less than the first component of another std::pair.
230 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
231 return lhs.first < rhs.first;
235 /// \brief Function object to check whether the second component of a std::pair
236 /// compares less than the second component of another std::pair.
238 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
239 return lhs.second < rhs.second;
243 // A subset of N3658. More stuff can be added as-needed.
245 /// \brief Represents a compile-time sequence of integers.
246 template <class T, T... I> struct integer_sequence {
247 typedef T value_type;
249 static LLVM_CONSTEXPR size_t size() { return sizeof...(I); }
252 /// \brief Alias for the common case of a sequence of size_ts.
253 template <size_t... I>
254 struct index_sequence : integer_sequence<std::size_t, I...> {};
256 template <std::size_t N, std::size_t... I>
257 struct build_index_impl : build_index_impl<N - 1, N - 1, I...> {};
258 template <std::size_t... I>
259 struct build_index_impl<0, I...> : index_sequence<I...> {};
261 /// \brief Creates a compile-time integer sequence for a parameter pack.
262 template <class... Ts>
263 struct index_sequence_for : build_index_impl<sizeof...(Ts)> {};
265 //===----------------------------------------------------------------------===//
266 // Extra additions for arrays
267 //===----------------------------------------------------------------------===//
269 /// Find the length of an array.
270 template <class T, std::size_t N>
271 LLVM_CONSTEXPR inline size_t array_lengthof(T (&)[N]) {
275 /// Adapt std::less<T> for array_pod_sort.
277 inline int array_pod_sort_comparator(const void *P1, const void *P2) {
278 if (std::less<T>()(*reinterpret_cast<const T*>(P1),
279 *reinterpret_cast<const T*>(P2)))
281 if (std::less<T>()(*reinterpret_cast<const T*>(P2),
282 *reinterpret_cast<const T*>(P1)))
287 /// get_array_pod_sort_comparator - This is an internal helper function used to
288 /// get type deduction of T right.
290 inline int (*get_array_pod_sort_comparator(const T &))
291 (const void*, const void*) {
292 return array_pod_sort_comparator<T>;
296 /// array_pod_sort - This sorts an array with the specified start and end
297 /// extent. This is just like std::sort, except that it calls qsort instead of
298 /// using an inlined template. qsort is slightly slower than std::sort, but
299 /// most sorts are not performance critical in LLVM and std::sort has to be
300 /// template instantiated for each type, leading to significant measured code
301 /// bloat. This function should generally be used instead of std::sort where
304 /// This function assumes that you have simple POD-like types that can be
305 /// compared with std::less and can be moved with memcpy. If this isn't true,
306 /// you should use std::sort.
308 /// NOTE: If qsort_r were portable, we could allow a custom comparator and
309 /// default to std::less.
310 template<class IteratorTy>
311 inline void array_pod_sort(IteratorTy Start, IteratorTy End) {
312 // Don't inefficiently call qsort with one element or trigger undefined
313 // behavior with an empty sequence.
314 auto NElts = End - Start;
315 if (NElts <= 1) return;
316 qsort(&*Start, NElts, sizeof(*Start), get_array_pod_sort_comparator(*Start));
319 template <class IteratorTy>
320 inline void array_pod_sort(
321 IteratorTy Start, IteratorTy End,
323 const typename std::iterator_traits<IteratorTy>::value_type *,
324 const typename std::iterator_traits<IteratorTy>::value_type *)) {
325 // Don't inefficiently call qsort with one element or trigger undefined
326 // behavior with an empty sequence.
327 auto NElts = End - Start;
328 if (NElts <= 1) return;
329 qsort(&*Start, NElts, sizeof(*Start),
330 reinterpret_cast<int (*)(const void *, const void *)>(Compare));
333 //===----------------------------------------------------------------------===//
334 // Extra additions to <algorithm>
335 //===----------------------------------------------------------------------===//
337 /// For a container of pointers, deletes the pointers and then clears the
339 template<typename Container>
340 void DeleteContainerPointers(Container &C) {
341 for (typename Container::iterator I = C.begin(), E = C.end(); I != E; ++I)
346 /// In a container of pairs (usually a map) whose second element is a pointer,
347 /// deletes the second elements and then clears the container.
348 template<typename Container>
349 void DeleteContainerSeconds(Container &C) {
350 for (typename Container::iterator I = C.begin(), E = C.end(); I != E; ++I)
355 /// Provide wrappers to std::all_of which take ranges instead of having to pass
356 /// being/end explicitly.
357 template<typename R, class UnaryPredicate>
358 bool all_of(R &&Range, UnaryPredicate &&P) {
359 return std::all_of(Range.begin(), Range.end(),
360 std::forward<UnaryPredicate>(P));
363 //===----------------------------------------------------------------------===//
364 // Extra additions to <memory>
365 //===----------------------------------------------------------------------===//
367 // Implement make_unique according to N3656.
369 /// \brief Constructs a `new T()` with the given args and returns a
370 /// `unique_ptr<T>` which owns the object.
374 /// auto p = make_unique<int>();
375 /// auto p = make_unique<std::tuple<int, int>>(0, 1);
376 template <class T, class... Args>
377 typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
378 make_unique(Args &&... args) {
379 return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
382 /// \brief Constructs a `new T[n]` with the given args and returns a
383 /// `unique_ptr<T[]>` which owns the object.
385 /// \param n size of the new array.
389 /// auto p = make_unique<int[]>(2); // value-initializes the array with 0's.
391 typename std::enable_if<std::is_array<T>::value && std::extent<T>::value == 0,
392 std::unique_ptr<T>>::type
393 make_unique(size_t n) {
394 return std::unique_ptr<T>(new typename std::remove_extent<T>::type[n]());
397 /// This function isn't used and is only here to provide better compile errors.
398 template <class T, class... Args>
399 typename std::enable_if<std::extent<T>::value != 0>::type
400 make_unique(Args &&...) = delete;
403 void operator()(void* v) {
408 template<typename First, typename Second>
410 size_t operator()(const std::pair<First, Second> &P) const {
411 return std::hash<First>()(P.first) * 31 + std::hash<Second>()(P.second);
415 /// A functor like C++14's std::less<void> in its absence.
417 template <typename A, typename B> bool operator()(A &&a, B &&b) const {
418 return std::forward<A>(a) < std::forward<B>(b);
422 /// A functor like C++14's std::equal<void> in its absence.
424 template <typename A, typename B> bool operator()(A &&a, B &&b) const {
425 return std::forward<A>(a) == std::forward<B>(b);
429 /// Binary functor that adapts to any other binary functor after dereferencing
431 template <typename T> struct deref {
433 // Could be further improved to cope with non-derivable functors and
434 // non-binary functors (should be a variadic template member function
436 template <typename A, typename B>
437 auto operator()(A &lhs, B &rhs) const -> decltype(func(*lhs, *rhs)) {
440 return func(*lhs, *rhs);
444 } // End llvm namespace