STLExtras.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. //===- llvm/ADT/STLExtras.h - Useful STL related functions ------*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file contains some templates that are useful if you are working with the
  11. // STL at all.
  12. //
  13. // No library is required when using these functions.
  14. //
  15. //===----------------------------------------------------------------------===//
  16. #ifndef LLVM_ADT_STLEXTRAS_H
  17. #define LLVM_ADT_STLEXTRAS_H
  18. #include "dxc/Support/WinAdapter.h" // HLSL Change
  19. #include "llvm/Support/Compiler.h"
  20. #include <algorithm> // for std::all_of
  21. #include <cassert>
  22. #include <cstddef> // for std::size_t
  23. #include <cstdlib> // for qsort
  24. #include <functional>
  25. #include <iterator>
  26. #include <memory>
  27. #include <utility> // for std::pair
  28. namespace llvm {
  29. //===----------------------------------------------------------------------===//
  30. // Extra additions to <functional>
  31. //===----------------------------------------------------------------------===//
  32. template<class Ty>
  33. struct identity : public std::unary_function<Ty, Ty> {
  34. Ty &operator()(Ty &self) const {
  35. return self;
  36. }
  37. const Ty &operator()(const Ty &self) const {
  38. return self;
  39. }
  40. };
  41. template<class Ty>
  42. struct less_ptr : public std::binary_function<Ty, Ty, bool> {
  43. bool operator()(const Ty* left, const Ty* right) const {
  44. return *left < *right;
  45. }
  46. };
  47. template<class Ty>
  48. struct greater_ptr : public std::binary_function<Ty, Ty, bool> {
  49. bool operator()(const Ty* left, const Ty* right) const {
  50. return *right < *left;
  51. }
  52. };
  53. /// An efficient, type-erasing, non-owning reference to a callable. This is
  54. /// intended for use as the type of a function parameter that is not used
  55. /// after the function in question returns.
  56. ///
  57. /// This class does not own the callable, so it is not in general safe to store
  58. /// a function_ref.
  59. template<typename Fn> class function_ref;
  60. template<typename Ret, typename ...Params>
  61. class function_ref<Ret(Params...)> {
  62. Ret (*callback)(intptr_t callable, Params ...params);
  63. intptr_t callable;
  64. template<typename Callable>
  65. static Ret callback_fn(intptr_t callable, Params ...params) {
  66. return (*reinterpret_cast<Callable*>(callable))(
  67. std::forward<Params>(params)...);
  68. }
  69. public:
  70. template <typename Callable>
  71. function_ref(Callable &&callable,
  72. typename std::enable_if<
  73. !std::is_same<typename std::remove_reference<Callable>::type,
  74. function_ref>::value>::type * = nullptr)
  75. : callback(callback_fn<typename std::remove_reference<Callable>::type>),
  76. callable(reinterpret_cast<intptr_t>(&callable)) {}
  77. Ret operator()(Params ...params) const {
  78. return callback(callable, std::forward<Params>(params)...);
  79. }
  80. };
  81. // deleter - Very very very simple method that is used to invoke operator
  82. // delete on something. It is used like this:
  83. //
  84. // for_each(V.begin(), B.end(), deleter<Interval>);
  85. //
  86. template <class T>
  87. inline void deleter(T *Ptr) {
  88. delete Ptr;
  89. }
  90. //===----------------------------------------------------------------------===//
  91. // Extra additions to <iterator>
  92. //===----------------------------------------------------------------------===//
  93. // mapped_iterator - This is a simple iterator adapter that causes a function to
  94. // be dereferenced whenever operator* is invoked on the iterator.
  95. //
  96. template <class RootIt, class UnaryFunc>
  97. class mapped_iterator {
  98. RootIt current;
  99. UnaryFunc Fn;
  100. public:
  101. typedef typename std::iterator_traits<RootIt>::iterator_category
  102. iterator_category;
  103. typedef typename std::iterator_traits<RootIt>::difference_type
  104. difference_type;
  105. typedef typename UnaryFunc::result_type value_type;
  106. typedef void pointer;
  107. //typedef typename UnaryFunc::result_type *pointer;
  108. typedef void reference; // Can't modify value returned by fn
  109. typedef RootIt iterator_type;
  110. inline const RootIt &getCurrent() const { return current; }
  111. inline const UnaryFunc &getFunc() const { return Fn; }
  112. inline explicit mapped_iterator(const RootIt &I, UnaryFunc F)
  113. : current(I), Fn(F) {}
  114. inline value_type operator*() const { // All this work to do this
  115. return Fn(*current); // little change
  116. }
  117. mapped_iterator &operator++() {
  118. ++current;
  119. return *this;
  120. }
  121. mapped_iterator &operator--() {
  122. --current;
  123. return *this;
  124. }
  125. mapped_iterator operator++(int) {
  126. mapped_iterator __tmp = *this;
  127. ++current;
  128. return __tmp;
  129. }
  130. mapped_iterator operator--(int) {
  131. mapped_iterator __tmp = *this;
  132. --current;
  133. return __tmp;
  134. }
  135. mapped_iterator operator+(difference_type n) const {
  136. return mapped_iterator(current + n, Fn);
  137. }
  138. mapped_iterator &operator+=(difference_type n) {
  139. current += n;
  140. return *this;
  141. }
  142. mapped_iterator operator-(difference_type n) const {
  143. return mapped_iterator(current - n, Fn);
  144. }
  145. mapped_iterator &operator-=(difference_type n) {
  146. current -= n;
  147. return *this;
  148. }
  149. reference operator[](difference_type n) const { return *(*this + n); }
  150. bool operator!=(const mapped_iterator &X) const { return !operator==(X); }
  151. bool operator==(const mapped_iterator &X) const {
  152. return current == X.current;
  153. }
  154. bool operator<(const mapped_iterator &X) const { return current < X.current; }
  155. difference_type operator-(const mapped_iterator &X) const {
  156. return current - X.current;
  157. }
  158. };
  159. template <class Iterator, class Func>
  160. inline mapped_iterator<Iterator, Func>
  161. operator+(typename mapped_iterator<Iterator, Func>::difference_type N,
  162. const mapped_iterator<Iterator, Func> &X) {
  163. return mapped_iterator<Iterator, Func>(X.getCurrent() - N, X.getFunc());
  164. }
  165. // map_iterator - Provide a convenient way to create mapped_iterators, just like
  166. // make_pair is useful for creating pairs...
  167. //
  168. template <class ItTy, class FuncTy>
  169. inline mapped_iterator<ItTy, FuncTy> map_iterator(const ItTy &I, FuncTy F) {
  170. return mapped_iterator<ItTy, FuncTy>(I, F);
  171. }
  172. //===----------------------------------------------------------------------===//
  173. // Extra additions to <utility>
  174. //===----------------------------------------------------------------------===//
  175. /// \brief Function object to check whether the first component of a std::pair
  176. /// compares less than the first component of another std::pair.
  177. struct less_first {
  178. template <typename T> bool operator()(const T &lhs, const T &rhs) const {
  179. return lhs.first < rhs.first;
  180. }
  181. };
  182. /// \brief Function object to check whether the second component of a std::pair
  183. /// compares less than the second component of another std::pair.
  184. struct less_second {
  185. template <typename T> bool operator()(const T &lhs, const T &rhs) const {
  186. return lhs.second < rhs.second;
  187. }
  188. };
  189. // A subset of N3658. More stuff can be added as-needed.
  190. /// \brief Represents a compile-time sequence of integers.
  191. template <class T, T... I> struct integer_sequence {
  192. typedef T value_type;
  193. static LLVM_CONSTEXPR size_t size() { return sizeof...(I); }
  194. };
  195. /// \brief Alias for the common case of a sequence of size_ts.
  196. template <size_t... I>
  197. struct index_sequence : integer_sequence<std::size_t, I...> {};
  198. template <std::size_t N, std::size_t... I>
  199. struct build_index_impl : build_index_impl<N - 1, N - 1, I...> {};
  200. template <std::size_t... I>
  201. struct build_index_impl<0, I...> : index_sequence<I...> {};
  202. /// \brief Creates a compile-time integer sequence for a parameter pack.
  203. template <class... Ts>
  204. struct index_sequence_for : build_index_impl<sizeof...(Ts)> {};
  205. //===----------------------------------------------------------------------===//
  206. // Extra additions for arrays
  207. //===----------------------------------------------------------------------===//
  208. /// Find the length of an array.
  209. template <class T, std::size_t N>
  210. LLVM_CONSTEXPR inline size_t array_lengthof(T (&)[N]) {
  211. return N;
  212. }
  213. /// Adapt std::less<T> for array_pod_sort.
  214. // HLSL Change: changed calling convention to __cdecl
  215. template<typename T>
  216. inline int __cdecl array_pod_sort_comparator(const void *P1, const void *P2) {
  217. if (std::less<T>()(*reinterpret_cast<const T*>(P1),
  218. *reinterpret_cast<const T*>(P2)))
  219. return -1;
  220. if (std::less<T>()(*reinterpret_cast<const T*>(P2),
  221. *reinterpret_cast<const T*>(P1)))
  222. return 1;
  223. return 0;
  224. }
  225. /// get_array_pod_sort_comparator - This is an internal helper function used to
  226. /// get type deduction of T right.
  227. //
  228. // HLSL Change: changed calling convention to __cdecl
  229. // HLSL Change: pulled this out into a typdef to make it easier to make change
  230. typedef int(__cdecl *llvm_cmp_func)(const void *, const void *);
  231. template<typename T>
  232. inline llvm_cmp_func get_array_pod_sort_comparator(const T &) {
  233. return array_pod_sort_comparator<T>;
  234. }
  235. /// array_pod_sort - This sorts an array with the specified start and end
  236. /// extent. This is just like std::sort, except that it calls qsort instead of
  237. /// using an inlined template. qsort is slightly slower than std::sort, but
  238. /// most sorts are not performance critical in LLVM and std::sort has to be
  239. /// template instantiated for each type, leading to significant measured code
  240. /// bloat. This function should generally be used instead of std::sort where
  241. /// possible.
  242. ///
  243. /// This function assumes that you have simple POD-like types that can be
  244. /// compared with std::less and can be moved with memcpy. If this isn't true,
  245. /// you should use std::sort.
  246. ///
  247. /// NOTE: If qsort_r were portable, we could allow a custom comparator and
  248. /// default to std::less.
  249. template<class IteratorTy>
  250. inline void array_pod_sort(IteratorTy Start, IteratorTy End) {
  251. // Don't inefficiently call qsort with one element or trigger undefined
  252. // behavior with an empty sequence.
  253. auto NElts = End - Start;
  254. if (NElts <= 1) return;
  255. qsort(&*Start, NElts, sizeof(*Start), get_array_pod_sort_comparator(*Start));
  256. }
  257. // HLSL Change: changed calling convention of Compare to __cdecl
  258. template <class IteratorTy>
  259. inline void array_pod_sort(
  260. IteratorTy Start, IteratorTy End,
  261. int (__cdecl *Compare)(
  262. const typename std::iterator_traits<IteratorTy>::value_type *,
  263. const typename std::iterator_traits<IteratorTy>::value_type *)) {
  264. // Don't inefficiently call qsort with one element or trigger undefined
  265. // behavior with an empty sequence.
  266. auto NElts = End - Start;
  267. if (NElts <= 1) return;
  268. qsort(&*Start, NElts, sizeof(*Start),
  269. reinterpret_cast<int (__cdecl *)(const void *, const void *)>(Compare)); // HLSL Change - __cdecl
  270. }
  271. //===----------------------------------------------------------------------===//
  272. // Extra additions to <algorithm>
  273. //===----------------------------------------------------------------------===//
  274. /// For a container of pointers, deletes the pointers and then clears the
  275. /// container.
  276. template<typename Container>
  277. void DeleteContainerPointers(Container &C) {
  278. for (typename Container::iterator I = C.begin(), E = C.end(); I != E; ++I)
  279. delete *I;
  280. C.clear();
  281. }
  282. /// In a container of pairs (usually a map) whose second element is a pointer,
  283. /// deletes the second elements and then clears the container.
  284. template<typename Container>
  285. void DeleteContainerSeconds(Container &C) {
  286. for (typename Container::iterator I = C.begin(), E = C.end(); I != E; ++I)
  287. delete I->second;
  288. C.clear();
  289. }
  290. /// Provide wrappers to std::all_of which take ranges instead of having to pass
  291. /// being/end explicitly.
  292. template<typename R, class UnaryPredicate>
  293. bool all_of(R &&Range, UnaryPredicate &&P) {
  294. return std::all_of(Range.begin(), Range.end(),
  295. std::forward<UnaryPredicate>(P));
  296. }
  297. //===----------------------------------------------------------------------===//
  298. // Extra additions to <memory>
  299. // //
  300. ///////////////////////////////////////////////////////////////////////////////
  301. // Implement make_unique according to N3656.
  302. /// \brief Constructs a `new T()` with the given args and returns a
  303. /// `unique_ptr<T>` which owns the object.
  304. ///
  305. /// Example:
  306. ///
  307. /// auto p = make_unique<int>();
  308. /// auto p = make_unique<std::tuple<int, int>>(0, 1);
  309. template <class T, class... Args>
  310. typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
  311. make_unique(Args &&... args) {
  312. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  313. }
  314. /// \brief Constructs a `new T[n]` with the given args and returns a
  315. /// `unique_ptr<T[]>` which owns the object.
  316. ///
  317. /// \param n size of the new array.
  318. ///
  319. /// Example:
  320. ///
  321. /// auto p = make_unique<int[]>(2); // value-initializes the array with 0's.
  322. template <class T>
  323. typename std::enable_if<std::is_array<T>::value && std::extent<T>::value == 0,
  324. std::unique_ptr<T>>::type
  325. make_unique(size_t n) {
  326. return std::unique_ptr<T>(new typename std::remove_extent<T>::type[n]());
  327. }
  328. /// This function isn't used and is only here to provide better compile errors.
  329. template <class T, class... Args>
  330. typename std::enable_if<std::extent<T>::value != 0>::type
  331. make_unique(Args &&...) = delete;
  332. struct FreeDeleter {
  333. void operator()(void* v) {
  334. ::free(v);
  335. }
  336. };
  337. template<typename First, typename Second>
  338. struct pair_hash {
  339. size_t operator()(const std::pair<First, Second> &P) const {
  340. return std::hash<First>()(P.first) * 31 + std::hash<Second>()(P.second);
  341. }
  342. };
  343. /// A functor like C++14's std::less<void> in its absence.
  344. struct less {
  345. template <typename A, typename B> bool operator()(A &&a, B &&b) const {
  346. return std::forward<A>(a) < std::forward<B>(b);
  347. }
  348. };
  349. /// A functor like C++14's std::equal<void> in its absence.
  350. struct equal {
  351. template <typename A, typename B> bool operator()(A &&a, B &&b) const {
  352. return std::forward<A>(a) == std::forward<B>(b);
  353. }
  354. };
  355. /// Binary functor that adapts to any other binary functor after dereferencing
  356. /// operands.
  357. template <typename T> struct deref {
  358. T func;
  359. // Could be further improved to cope with non-derivable functors and
  360. // non-binary functors (should be a variadic template member function
  361. // operator()).
  362. template <typename A, typename B>
  363. auto operator()(A &lhs, B &rhs) const -> decltype(func(*lhs, *rhs)) {
  364. assert(lhs);
  365. assert(rhs);
  366. return func(*lhs, *rhs);
  367. }
  368. };
  369. } // End llvm namespace
  370. #endif