STLExtras.h 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/ADT/STLExtras.h - Useful STL related functions ------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. ///
  14. /// \file
  15. /// This file contains some templates that are useful if you are working with
  16. /// the STL at all.
  17. ///
  18. /// No library is required when using these functions.
  19. ///
  20. //===----------------------------------------------------------------------===//
  21. #ifndef LLVM_ADT_STLEXTRAS_H
  22. #define LLVM_ADT_STLEXTRAS_H
  23. #include "llvm/ADT/Optional.h"
  24. #include "llvm/ADT/STLArrayExtras.h"
  25. #include "llvm/ADT/STLForwardCompat.h"
  26. #include "llvm/ADT/STLFunctionalExtras.h"
  27. #include "llvm/ADT/identity.h"
  28. #include "llvm/ADT/iterator.h"
  29. #include "llvm/ADT/iterator_range.h"
  30. #include "llvm/Config/abi-breaking.h"
  31. #include "llvm/Support/ErrorHandling.h"
  32. #include <algorithm>
  33. #include <cassert>
  34. #include <cstddef>
  35. #include <cstdint>
  36. #include <cstdlib>
  37. #include <functional>
  38. #include <initializer_list>
  39. #include <iterator>
  40. #include <limits>
  41. #include <memory>
  42. #include <tuple>
  43. #include <type_traits>
  44. #include <utility>
  45. #ifdef EXPENSIVE_CHECKS
  46. #include <random> // for std::mt19937
  47. #endif
  48. namespace llvm {
  49. // Only used by compiler if both template types are the same. Useful when
  50. // using SFINAE to test for the existence of member functions.
  51. template <typename T, T> struct SameType;
  52. namespace detail {
  53. template <typename RangeT>
  54. using IterOfRange = decltype(std::begin(std::declval<RangeT &>()));
  55. template <typename RangeT>
  56. using ValueOfRange = typename std::remove_reference<decltype(
  57. *std::begin(std::declval<RangeT &>()))>::type;
  58. } // end namespace detail
  59. //===----------------------------------------------------------------------===//
  60. // Extra additions to <type_traits>
  61. //===----------------------------------------------------------------------===//
  62. template <typename T> struct make_const_ptr {
  63. using type =
  64. typename std::add_pointer<typename std::add_const<T>::type>::type;
  65. };
  66. template <typename T> struct make_const_ref {
  67. using type = typename std::add_lvalue_reference<
  68. typename std::add_const<T>::type>::type;
  69. };
  70. namespace detail {
  71. template <typename...> using void_t = void;
  72. template <class, template <class...> class Op, class... Args> struct detector {
  73. using value_t = std::false_type;
  74. };
  75. template <template <class...> class Op, class... Args>
  76. struct detector<void_t<Op<Args...>>, Op, Args...> {
  77. using value_t = std::true_type;
  78. };
  79. } // end namespace detail
  80. /// Detects if a given trait holds for some set of arguments 'Args'.
  81. /// For example, the given trait could be used to detect if a given type
  82. /// has a copy assignment operator:
  83. /// template<class T>
  84. /// using has_copy_assign_t = decltype(std::declval<T&>()
  85. /// = std::declval<const T&>());
  86. /// bool fooHasCopyAssign = is_detected<has_copy_assign_t, FooClass>::value;
  87. template <template <class...> class Op, class... Args>
  88. using is_detected = typename detail::detector<void, Op, Args...>::value_t;
  89. namespace detail {
  90. template <typename Callable, typename... Args>
  91. using is_invocable =
  92. decltype(std::declval<Callable &>()(std::declval<Args>()...));
  93. } // namespace detail
  94. /// Check if a Callable type can be invoked with the given set of arg types.
  95. template <typename Callable, typename... Args>
  96. using is_invocable = is_detected<detail::is_invocable, Callable, Args...>;
  97. /// This class provides various trait information about a callable object.
  98. /// * To access the number of arguments: Traits::num_args
  99. /// * To access the type of an argument: Traits::arg_t<Index>
  100. /// * To access the type of the result: Traits::result_t
  101. template <typename T, bool isClass = std::is_class<T>::value>
  102. struct function_traits : public function_traits<decltype(&T::operator())> {};
  103. /// Overload for class function types.
  104. template <typename ClassType, typename ReturnType, typename... Args>
  105. struct function_traits<ReturnType (ClassType::*)(Args...) const, false> {
  106. /// The number of arguments to this function.
  107. enum { num_args = sizeof...(Args) };
  108. /// The result type of this function.
  109. using result_t = ReturnType;
  110. /// The type of an argument to this function.
  111. template <size_t Index>
  112. using arg_t = typename std::tuple_element<Index, std::tuple<Args...>>::type;
  113. };
  114. /// Overload for class function types.
  115. template <typename ClassType, typename ReturnType, typename... Args>
  116. struct function_traits<ReturnType (ClassType::*)(Args...), false>
  117. : function_traits<ReturnType (ClassType::*)(Args...) const> {};
  118. /// Overload for non-class function types.
  119. template <typename ReturnType, typename... Args>
  120. struct function_traits<ReturnType (*)(Args...), false> {
  121. /// The number of arguments to this function.
  122. enum { num_args = sizeof...(Args) };
  123. /// The result type of this function.
  124. using result_t = ReturnType;
  125. /// The type of an argument to this function.
  126. template <size_t i>
  127. using arg_t = typename std::tuple_element<i, std::tuple<Args...>>::type;
  128. };
  129. /// Overload for non-class function type references.
  130. template <typename ReturnType, typename... Args>
  131. struct function_traits<ReturnType (&)(Args...), false>
  132. : public function_traits<ReturnType (*)(Args...)> {};
  133. /// traits class for checking whether type T is one of any of the given
  134. /// types in the variadic list.
  135. template <typename T, typename... Ts>
  136. using is_one_of = disjunction<std::is_same<T, Ts>...>;
  137. /// traits class for checking whether type T is a base class for all
  138. /// the given types in the variadic list.
  139. template <typename T, typename... Ts>
  140. using are_base_of = conjunction<std::is_base_of<T, Ts>...>;
  141. namespace detail {
  142. template <typename T, typename... Us> struct TypesAreDistinct;
  143. template <typename T, typename... Us>
  144. struct TypesAreDistinct
  145. : std::integral_constant<bool, !is_one_of<T, Us...>::value &&
  146. TypesAreDistinct<Us...>::value> {};
  147. template <typename T> struct TypesAreDistinct<T> : std::true_type {};
  148. } // namespace detail
  149. /// Determine if all types in Ts are distinct.
  150. ///
  151. /// Useful to statically assert when Ts is intended to describe a non-multi set
  152. /// of types.
  153. ///
  154. /// Expensive (currently quadratic in sizeof(Ts...)), and so should only be
  155. /// asserted once per instantiation of a type which requires it.
  156. template <typename... Ts> struct TypesAreDistinct;
  157. template <> struct TypesAreDistinct<> : std::true_type {};
  158. template <typename... Ts>
  159. struct TypesAreDistinct
  160. : std::integral_constant<bool, detail::TypesAreDistinct<Ts...>::value> {};
  161. /// Find the first index where a type appears in a list of types.
  162. ///
  163. /// FirstIndexOfType<T, Us...>::value is the first index of T in Us.
  164. ///
  165. /// Typically only meaningful when it is otherwise statically known that the
  166. /// type pack has no duplicate types. This should be guaranteed explicitly with
  167. /// static_assert(TypesAreDistinct<Us...>::value).
  168. ///
  169. /// It is a compile-time error to instantiate when T is not present in Us, i.e.
  170. /// if is_one_of<T, Us...>::value is false.
  171. template <typename T, typename... Us> struct FirstIndexOfType;
  172. template <typename T, typename U, typename... Us>
  173. struct FirstIndexOfType<T, U, Us...>
  174. : std::integral_constant<size_t, 1 + FirstIndexOfType<T, Us...>::value> {};
  175. template <typename T, typename... Us>
  176. struct FirstIndexOfType<T, T, Us...> : std::integral_constant<size_t, 0> {};
  177. /// Find the type at a given index in a list of types.
  178. ///
  179. /// TypeAtIndex<I, Ts...> is the type at index I in Ts.
  180. template <size_t I, typename... Ts>
  181. using TypeAtIndex = std::tuple_element_t<I, std::tuple<Ts...>>;
  182. //===----------------------------------------------------------------------===//
  183. // Extra additions to <iterator>
  184. //===----------------------------------------------------------------------===//
  185. namespace adl_detail {
  186. using std::begin;
  187. template <typename ContainerTy>
  188. decltype(auto) adl_begin(ContainerTy &&container) {
  189. return begin(std::forward<ContainerTy>(container));
  190. }
  191. using std::end;
  192. template <typename ContainerTy>
  193. decltype(auto) adl_end(ContainerTy &&container) {
  194. return end(std::forward<ContainerTy>(container));
  195. }
  196. using std::swap;
  197. template <typename T>
  198. void adl_swap(T &&lhs, T &&rhs) noexcept(noexcept(swap(std::declval<T>(),
  199. std::declval<T>()))) {
  200. swap(std::forward<T>(lhs), std::forward<T>(rhs));
  201. }
  202. } // end namespace adl_detail
  203. template <typename ContainerTy>
  204. decltype(auto) adl_begin(ContainerTy &&container) {
  205. return adl_detail::adl_begin(std::forward<ContainerTy>(container));
  206. }
  207. template <typename ContainerTy>
  208. decltype(auto) adl_end(ContainerTy &&container) {
  209. return adl_detail::adl_end(std::forward<ContainerTy>(container));
  210. }
  211. template <typename T>
  212. void adl_swap(T &&lhs, T &&rhs) noexcept(
  213. noexcept(adl_detail::adl_swap(std::declval<T>(), std::declval<T>()))) {
  214. adl_detail::adl_swap(std::forward<T>(lhs), std::forward<T>(rhs));
  215. }
  216. /// Test whether \p RangeOrContainer is empty. Similar to C++17 std::empty.
  217. template <typename T>
  218. constexpr bool empty(const T &RangeOrContainer) {
  219. return adl_begin(RangeOrContainer) == adl_end(RangeOrContainer);
  220. }
  221. /// Returns true if the given container only contains a single element.
  222. template <typename ContainerTy> bool hasSingleElement(ContainerTy &&C) {
  223. auto B = std::begin(C), E = std::end(C);
  224. return B != E && std::next(B) == E;
  225. }
  226. /// Return a range covering \p RangeOrContainer with the first N elements
  227. /// excluded.
  228. template <typename T> auto drop_begin(T &&RangeOrContainer, size_t N = 1) {
  229. return make_range(std::next(adl_begin(RangeOrContainer), N),
  230. adl_end(RangeOrContainer));
  231. }
  232. // mapped_iterator - This is a simple iterator adapter that causes a function to
  233. // be applied whenever operator* is invoked on the iterator.
  234. template <typename ItTy, typename FuncTy,
  235. typename ReferenceTy =
  236. decltype(std::declval<FuncTy>()(*std::declval<ItTy>()))>
  237. class mapped_iterator
  238. : public iterator_adaptor_base<
  239. mapped_iterator<ItTy, FuncTy>, ItTy,
  240. typename std::iterator_traits<ItTy>::iterator_category,
  241. std::remove_reference_t<ReferenceTy>,
  242. typename std::iterator_traits<ItTy>::difference_type,
  243. std::remove_reference_t<ReferenceTy> *, ReferenceTy> {
  244. public:
  245. mapped_iterator(ItTy U, FuncTy F)
  246. : mapped_iterator::iterator_adaptor_base(std::move(U)), F(std::move(F)) {}
  247. ItTy getCurrent() { return this->I; }
  248. const FuncTy &getFunction() const { return F; }
  249. ReferenceTy operator*() const { return F(*this->I); }
  250. private:
  251. FuncTy F;
  252. };
  253. // map_iterator - Provide a convenient way to create mapped_iterators, just like
  254. // make_pair is useful for creating pairs...
  255. template <class ItTy, class FuncTy>
  256. inline mapped_iterator<ItTy, FuncTy> map_iterator(ItTy I, FuncTy F) {
  257. return mapped_iterator<ItTy, FuncTy>(std::move(I), std::move(F));
  258. }
  259. template <class ContainerTy, class FuncTy>
  260. auto map_range(ContainerTy &&C, FuncTy F) {
  261. return make_range(map_iterator(C.begin(), F), map_iterator(C.end(), F));
  262. }
  263. /// A base type of mapped iterator, that is useful for building derived
  264. /// iterators that do not need/want to store the map function (as in
  265. /// mapped_iterator). These iterators must simply provide a `mapElement` method
  266. /// that defines how to map a value of the iterator to the provided reference
  267. /// type.
  268. template <typename DerivedT, typename ItTy, typename ReferenceTy>
  269. class mapped_iterator_base
  270. : public iterator_adaptor_base<
  271. DerivedT, ItTy,
  272. typename std::iterator_traits<ItTy>::iterator_category,
  273. std::remove_reference_t<ReferenceTy>,
  274. typename std::iterator_traits<ItTy>::difference_type,
  275. std::remove_reference_t<ReferenceTy> *, ReferenceTy> {
  276. public:
  277. using BaseT = mapped_iterator_base;
  278. mapped_iterator_base(ItTy U)
  279. : mapped_iterator_base::iterator_adaptor_base(std::move(U)) {}
  280. ItTy getCurrent() { return this->I; }
  281. ReferenceTy operator*() const {
  282. return static_cast<const DerivedT &>(*this).mapElement(*this->I);
  283. }
  284. };
  285. /// Helper to determine if type T has a member called rbegin().
  286. template <typename Ty> class has_rbegin_impl {
  287. using yes = char[1];
  288. using no = char[2];
  289. template <typename Inner>
  290. static yes& test(Inner *I, decltype(I->rbegin()) * = nullptr);
  291. template <typename>
  292. static no& test(...);
  293. public:
  294. static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
  295. };
  296. /// Metafunction to determine if T& or T has a member called rbegin().
  297. template <typename Ty>
  298. struct has_rbegin : has_rbegin_impl<typename std::remove_reference<Ty>::type> {
  299. };
  300. // Returns an iterator_range over the given container which iterates in reverse.
  301. // Note that the container must have rbegin()/rend() methods for this to work.
  302. template <typename ContainerTy>
  303. auto reverse(ContainerTy &&C,
  304. std::enable_if_t<has_rbegin<ContainerTy>::value> * = nullptr) {
  305. return make_range(C.rbegin(), C.rend());
  306. }
  307. // Returns an iterator_range over the given container which iterates in reverse.
  308. // Note that the container must have begin()/end() methods which return
  309. // bidirectional iterators for this to work.
  310. template <typename ContainerTy>
  311. auto reverse(ContainerTy &&C,
  312. std::enable_if_t<!has_rbegin<ContainerTy>::value> * = nullptr) {
  313. return make_range(std::make_reverse_iterator(std::end(C)),
  314. std::make_reverse_iterator(std::begin(C)));
  315. }
  316. /// An iterator adaptor that filters the elements of given inner iterators.
  317. ///
  318. /// The predicate parameter should be a callable object that accepts the wrapped
  319. /// iterator's reference type and returns a bool. When incrementing or
  320. /// decrementing the iterator, it will call the predicate on each element and
  321. /// skip any where it returns false.
  322. ///
  323. /// \code
  324. /// int A[] = { 1, 2, 3, 4 };
  325. /// auto R = make_filter_range(A, [](int N) { return N % 2 == 1; });
  326. /// // R contains { 1, 3 }.
  327. /// \endcode
  328. ///
  329. /// Note: filter_iterator_base implements support for forward iteration.
  330. /// filter_iterator_impl exists to provide support for bidirectional iteration,
  331. /// conditional on whether the wrapped iterator supports it.
  332. template <typename WrappedIteratorT, typename PredicateT, typename IterTag>
  333. class filter_iterator_base
  334. : public iterator_adaptor_base<
  335. filter_iterator_base<WrappedIteratorT, PredicateT, IterTag>,
  336. WrappedIteratorT,
  337. typename std::common_type<
  338. IterTag, typename std::iterator_traits<
  339. WrappedIteratorT>::iterator_category>::type> {
  340. using BaseT = typename filter_iterator_base::iterator_adaptor_base;
  341. protected:
  342. WrappedIteratorT End;
  343. PredicateT Pred;
  344. void findNextValid() {
  345. while (this->I != End && !Pred(*this->I))
  346. BaseT::operator++();
  347. }
  348. // Construct the iterator. The begin iterator needs to know where the end
  349. // is, so that it can properly stop when it gets there. The end iterator only
  350. // needs the predicate to support bidirectional iteration.
  351. filter_iterator_base(WrappedIteratorT Begin, WrappedIteratorT End,
  352. PredicateT Pred)
  353. : BaseT(Begin), End(End), Pred(Pred) {
  354. findNextValid();
  355. }
  356. public:
  357. using BaseT::operator++;
  358. filter_iterator_base &operator++() {
  359. BaseT::operator++();
  360. findNextValid();
  361. return *this;
  362. }
  363. };
  364. /// Specialization of filter_iterator_base for forward iteration only.
  365. template <typename WrappedIteratorT, typename PredicateT,
  366. typename IterTag = std::forward_iterator_tag>
  367. class filter_iterator_impl
  368. : public filter_iterator_base<WrappedIteratorT, PredicateT, IterTag> {
  369. public:
  370. filter_iterator_impl(WrappedIteratorT Begin, WrappedIteratorT End,
  371. PredicateT Pred)
  372. : filter_iterator_impl::filter_iterator_base(Begin, End, Pred) {}
  373. };
  374. /// Specialization of filter_iterator_base for bidirectional iteration.
  375. template <typename WrappedIteratorT, typename PredicateT>
  376. class filter_iterator_impl<WrappedIteratorT, PredicateT,
  377. std::bidirectional_iterator_tag>
  378. : public filter_iterator_base<WrappedIteratorT, PredicateT,
  379. std::bidirectional_iterator_tag> {
  380. using BaseT = typename filter_iterator_impl::filter_iterator_base;
  381. void findPrevValid() {
  382. while (!this->Pred(*this->I))
  383. BaseT::operator--();
  384. }
  385. public:
  386. using BaseT::operator--;
  387. filter_iterator_impl(WrappedIteratorT Begin, WrappedIteratorT End,
  388. PredicateT Pred)
  389. : BaseT(Begin, End, Pred) {}
  390. filter_iterator_impl &operator--() {
  391. BaseT::operator--();
  392. findPrevValid();
  393. return *this;
  394. }
  395. };
  396. namespace detail {
  397. template <bool is_bidirectional> struct fwd_or_bidi_tag_impl {
  398. using type = std::forward_iterator_tag;
  399. };
  400. template <> struct fwd_or_bidi_tag_impl<true> {
  401. using type = std::bidirectional_iterator_tag;
  402. };
  403. /// Helper which sets its type member to forward_iterator_tag if the category
  404. /// of \p IterT does not derive from bidirectional_iterator_tag, and to
  405. /// bidirectional_iterator_tag otherwise.
  406. template <typename IterT> struct fwd_or_bidi_tag {
  407. using type = typename fwd_or_bidi_tag_impl<std::is_base_of<
  408. std::bidirectional_iterator_tag,
  409. typename std::iterator_traits<IterT>::iterator_category>::value>::type;
  410. };
  411. } // namespace detail
  412. /// Defines filter_iterator to a suitable specialization of
  413. /// filter_iterator_impl, based on the underlying iterator's category.
  414. template <typename WrappedIteratorT, typename PredicateT>
  415. using filter_iterator = filter_iterator_impl<
  416. WrappedIteratorT, PredicateT,
  417. typename detail::fwd_or_bidi_tag<WrappedIteratorT>::type>;
  418. /// Convenience function that takes a range of elements and a predicate,
  419. /// and return a new filter_iterator range.
  420. ///
  421. /// FIXME: Currently if RangeT && is a rvalue reference to a temporary, the
  422. /// lifetime of that temporary is not kept by the returned range object, and the
  423. /// temporary is going to be dropped on the floor after the make_iterator_range
  424. /// full expression that contains this function call.
  425. template <typename RangeT, typename PredicateT>
  426. iterator_range<filter_iterator<detail::IterOfRange<RangeT>, PredicateT>>
  427. make_filter_range(RangeT &&Range, PredicateT Pred) {
  428. using FilterIteratorT =
  429. filter_iterator<detail::IterOfRange<RangeT>, PredicateT>;
  430. return make_range(
  431. FilterIteratorT(std::begin(std::forward<RangeT>(Range)),
  432. std::end(std::forward<RangeT>(Range)), Pred),
  433. FilterIteratorT(std::end(std::forward<RangeT>(Range)),
  434. std::end(std::forward<RangeT>(Range)), Pred));
  435. }
  436. /// A pseudo-iterator adaptor that is designed to implement "early increment"
  437. /// style loops.
  438. ///
  439. /// This is *not a normal iterator* and should almost never be used directly. It
  440. /// is intended primarily to be used with range based for loops and some range
  441. /// algorithms.
  442. ///
  443. /// The iterator isn't quite an `OutputIterator` or an `InputIterator` but
  444. /// somewhere between them. The constraints of these iterators are:
  445. ///
  446. /// - On construction or after being incremented, it is comparable and
  447. /// dereferencable. It is *not* incrementable.
  448. /// - After being dereferenced, it is neither comparable nor dereferencable, it
  449. /// is only incrementable.
  450. ///
  451. /// This means you can only dereference the iterator once, and you can only
  452. /// increment it once between dereferences.
  453. template <typename WrappedIteratorT>
  454. class early_inc_iterator_impl
  455. : public iterator_adaptor_base<early_inc_iterator_impl<WrappedIteratorT>,
  456. WrappedIteratorT, std::input_iterator_tag> {
  457. using BaseT = typename early_inc_iterator_impl::iterator_adaptor_base;
  458. using PointerT = typename std::iterator_traits<WrappedIteratorT>::pointer;
  459. protected:
  460. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  461. bool IsEarlyIncremented = false;
  462. #endif
  463. public:
  464. early_inc_iterator_impl(WrappedIteratorT I) : BaseT(I) {}
  465. using BaseT::operator*;
  466. decltype(*std::declval<WrappedIteratorT>()) operator*() {
  467. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  468. assert(!IsEarlyIncremented && "Cannot dereference twice!");
  469. IsEarlyIncremented = true;
  470. #endif
  471. return *(this->I)++;
  472. }
  473. using BaseT::operator++;
  474. early_inc_iterator_impl &operator++() {
  475. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  476. assert(IsEarlyIncremented && "Cannot increment before dereferencing!");
  477. IsEarlyIncremented = false;
  478. #endif
  479. return *this;
  480. }
  481. friend bool operator==(const early_inc_iterator_impl &LHS,
  482. const early_inc_iterator_impl &RHS) {
  483. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  484. assert(!LHS.IsEarlyIncremented && "Cannot compare after dereferencing!");
  485. #endif
  486. return (const BaseT &)LHS == (const BaseT &)RHS;
  487. }
  488. };
  489. /// Make a range that does early increment to allow mutation of the underlying
  490. /// range without disrupting iteration.
  491. ///
  492. /// The underlying iterator will be incremented immediately after it is
  493. /// dereferenced, allowing deletion of the current node or insertion of nodes to
  494. /// not disrupt iteration provided they do not invalidate the *next* iterator --
  495. /// the current iterator can be invalidated.
  496. ///
  497. /// This requires a very exact pattern of use that is only really suitable to
  498. /// range based for loops and other range algorithms that explicitly guarantee
  499. /// to dereference exactly once each element, and to increment exactly once each
  500. /// element.
  501. template <typename RangeT>
  502. iterator_range<early_inc_iterator_impl<detail::IterOfRange<RangeT>>>
  503. make_early_inc_range(RangeT &&Range) {
  504. using EarlyIncIteratorT =
  505. early_inc_iterator_impl<detail::IterOfRange<RangeT>>;
  506. return make_range(EarlyIncIteratorT(std::begin(std::forward<RangeT>(Range))),
  507. EarlyIncIteratorT(std::end(std::forward<RangeT>(Range))));
  508. }
  509. // forward declarations required by zip_shortest/zip_first/zip_longest
  510. template <typename R, typename UnaryPredicate>
  511. bool all_of(R &&range, UnaryPredicate P);
  512. template <typename R, typename UnaryPredicate>
  513. bool any_of(R &&range, UnaryPredicate P);
  514. namespace detail {
  515. using std::declval;
  516. // We have to alias this since inlining the actual type at the usage site
  517. // in the parameter list of iterator_facade_base<> below ICEs MSVC 2017.
  518. template<typename... Iters> struct ZipTupleType {
  519. using type = std::tuple<decltype(*declval<Iters>())...>;
  520. };
  521. template <typename ZipType, typename... Iters>
  522. using zip_traits = iterator_facade_base<
  523. ZipType, typename std::common_type<std::bidirectional_iterator_tag,
  524. typename std::iterator_traits<
  525. Iters>::iterator_category...>::type,
  526. // ^ TODO: Implement random access methods.
  527. typename ZipTupleType<Iters...>::type,
  528. typename std::iterator_traits<typename std::tuple_element<
  529. 0, std::tuple<Iters...>>::type>::difference_type,
  530. // ^ FIXME: This follows boost::make_zip_iterator's assumption that all
  531. // inner iterators have the same difference_type. It would fail if, for
  532. // instance, the second field's difference_type were non-numeric while the
  533. // first is.
  534. typename ZipTupleType<Iters...>::type *,
  535. typename ZipTupleType<Iters...>::type>;
  536. template <typename ZipType, typename... Iters>
  537. struct zip_common : public zip_traits<ZipType, Iters...> {
  538. using Base = zip_traits<ZipType, Iters...>;
  539. using value_type = typename Base::value_type;
  540. std::tuple<Iters...> iterators;
  541. protected:
  542. template <size_t... Ns> value_type deref(std::index_sequence<Ns...>) const {
  543. return value_type(*std::get<Ns>(iterators)...);
  544. }
  545. template <size_t... Ns>
  546. decltype(iterators) tup_inc(std::index_sequence<Ns...>) const {
  547. return std::tuple<Iters...>(std::next(std::get<Ns>(iterators))...);
  548. }
  549. template <size_t... Ns>
  550. decltype(iterators) tup_dec(std::index_sequence<Ns...>) const {
  551. return std::tuple<Iters...>(std::prev(std::get<Ns>(iterators))...);
  552. }
  553. template <size_t... Ns>
  554. bool test_all_equals(const zip_common &other,
  555. std::index_sequence<Ns...>) const {
  556. return all_of(std::initializer_list<bool>{std::get<Ns>(this->iterators) ==
  557. std::get<Ns>(other.iterators)...},
  558. identity<bool>{});
  559. }
  560. public:
  561. zip_common(Iters &&... ts) : iterators(std::forward<Iters>(ts)...) {}
  562. value_type operator*() const {
  563. return deref(std::index_sequence_for<Iters...>{});
  564. }
  565. ZipType &operator++() {
  566. iterators = tup_inc(std::index_sequence_for<Iters...>{});
  567. return *reinterpret_cast<ZipType *>(this);
  568. }
  569. ZipType &operator--() {
  570. static_assert(Base::IsBidirectional,
  571. "All inner iterators must be at least bidirectional.");
  572. iterators = tup_dec(std::index_sequence_for<Iters...>{});
  573. return *reinterpret_cast<ZipType *>(this);
  574. }
  575. /// Return true if all the iterator are matching `other`'s iterators.
  576. bool all_equals(zip_common &other) {
  577. return test_all_equals(other, std::index_sequence_for<Iters...>{});
  578. }
  579. };
  580. template <typename... Iters>
  581. struct zip_first : public zip_common<zip_first<Iters...>, Iters...> {
  582. using Base = zip_common<zip_first<Iters...>, Iters...>;
  583. bool operator==(const zip_first<Iters...> &other) const {
  584. return std::get<0>(this->iterators) == std::get<0>(other.iterators);
  585. }
  586. zip_first(Iters &&... ts) : Base(std::forward<Iters>(ts)...) {}
  587. };
  588. template <typename... Iters>
  589. class zip_shortest : public zip_common<zip_shortest<Iters...>, Iters...> {
  590. template <size_t... Ns>
  591. bool test(const zip_shortest<Iters...> &other,
  592. std::index_sequence<Ns...>) const {
  593. return all_of(std::initializer_list<bool>{std::get<Ns>(this->iterators) !=
  594. std::get<Ns>(other.iterators)...},
  595. identity<bool>{});
  596. }
  597. public:
  598. using Base = zip_common<zip_shortest<Iters...>, Iters...>;
  599. zip_shortest(Iters &&... ts) : Base(std::forward<Iters>(ts)...) {}
  600. bool operator==(const zip_shortest<Iters...> &other) const {
  601. return !test(other, std::index_sequence_for<Iters...>{});
  602. }
  603. };
  604. template <template <typename...> class ItType, typename... Args> class zippy {
  605. public:
  606. using iterator = ItType<decltype(std::begin(std::declval<Args>()))...>;
  607. using iterator_category = typename iterator::iterator_category;
  608. using value_type = typename iterator::value_type;
  609. using difference_type = typename iterator::difference_type;
  610. using pointer = typename iterator::pointer;
  611. using reference = typename iterator::reference;
  612. private:
  613. std::tuple<Args...> ts;
  614. template <size_t... Ns>
  615. iterator begin_impl(std::index_sequence<Ns...>) const {
  616. return iterator(std::begin(std::get<Ns>(ts))...);
  617. }
  618. template <size_t... Ns> iterator end_impl(std::index_sequence<Ns...>) const {
  619. return iterator(std::end(std::get<Ns>(ts))...);
  620. }
  621. public:
  622. zippy(Args &&... ts_) : ts(std::forward<Args>(ts_)...) {}
  623. iterator begin() const {
  624. return begin_impl(std::index_sequence_for<Args...>{});
  625. }
  626. iterator end() const { return end_impl(std::index_sequence_for<Args...>{}); }
  627. };
  628. } // end namespace detail
  629. /// zip iterator for two or more iteratable types.
  630. template <typename T, typename U, typename... Args>
  631. detail::zippy<detail::zip_shortest, T, U, Args...> zip(T &&t, U &&u,
  632. Args &&... args) {
  633. return detail::zippy<detail::zip_shortest, T, U, Args...>(
  634. std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
  635. }
  636. /// zip iterator that, for the sake of efficiency, assumes the first iteratee to
  637. /// be the shortest.
  638. template <typename T, typename U, typename... Args>
  639. detail::zippy<detail::zip_first, T, U, Args...> zip_first(T &&t, U &&u,
  640. Args &&... args) {
  641. return detail::zippy<detail::zip_first, T, U, Args...>(
  642. std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
  643. }
  644. namespace detail {
  645. template <typename Iter>
  646. Iter next_or_end(const Iter &I, const Iter &End) {
  647. if (I == End)
  648. return End;
  649. return std::next(I);
  650. }
  651. template <typename Iter>
  652. auto deref_or_none(const Iter &I, const Iter &End) -> llvm::Optional<
  653. std::remove_const_t<std::remove_reference_t<decltype(*I)>>> {
  654. if (I == End)
  655. return None;
  656. return *I;
  657. }
  658. template <typename Iter> struct ZipLongestItemType {
  659. using type =
  660. llvm::Optional<typename std::remove_const<typename std::remove_reference<
  661. decltype(*std::declval<Iter>())>::type>::type>;
  662. };
  663. template <typename... Iters> struct ZipLongestTupleType {
  664. using type = std::tuple<typename ZipLongestItemType<Iters>::type...>;
  665. };
  666. template <typename... Iters>
  667. class zip_longest_iterator
  668. : public iterator_facade_base<
  669. zip_longest_iterator<Iters...>,
  670. typename std::common_type<
  671. std::forward_iterator_tag,
  672. typename std::iterator_traits<Iters>::iterator_category...>::type,
  673. typename ZipLongestTupleType<Iters...>::type,
  674. typename std::iterator_traits<typename std::tuple_element<
  675. 0, std::tuple<Iters...>>::type>::difference_type,
  676. typename ZipLongestTupleType<Iters...>::type *,
  677. typename ZipLongestTupleType<Iters...>::type> {
  678. public:
  679. using value_type = typename ZipLongestTupleType<Iters...>::type;
  680. private:
  681. std::tuple<Iters...> iterators;
  682. std::tuple<Iters...> end_iterators;
  683. template <size_t... Ns>
  684. bool test(const zip_longest_iterator<Iters...> &other,
  685. std::index_sequence<Ns...>) const {
  686. return llvm::any_of(
  687. std::initializer_list<bool>{std::get<Ns>(this->iterators) !=
  688. std::get<Ns>(other.iterators)...},
  689. identity<bool>{});
  690. }
  691. template <size_t... Ns> value_type deref(std::index_sequence<Ns...>) const {
  692. return value_type(
  693. deref_or_none(std::get<Ns>(iterators), std::get<Ns>(end_iterators))...);
  694. }
  695. template <size_t... Ns>
  696. decltype(iterators) tup_inc(std::index_sequence<Ns...>) const {
  697. return std::tuple<Iters...>(
  698. next_or_end(std::get<Ns>(iterators), std::get<Ns>(end_iterators))...);
  699. }
  700. public:
  701. zip_longest_iterator(std::pair<Iters &&, Iters &&>... ts)
  702. : iterators(std::forward<Iters>(ts.first)...),
  703. end_iterators(std::forward<Iters>(ts.second)...) {}
  704. value_type operator*() const {
  705. return deref(std::index_sequence_for<Iters...>{});
  706. }
  707. zip_longest_iterator<Iters...> &operator++() {
  708. iterators = tup_inc(std::index_sequence_for<Iters...>{});
  709. return *this;
  710. }
  711. bool operator==(const zip_longest_iterator<Iters...> &other) const {
  712. return !test(other, std::index_sequence_for<Iters...>{});
  713. }
  714. };
  715. template <typename... Args> class zip_longest_range {
  716. public:
  717. using iterator =
  718. zip_longest_iterator<decltype(adl_begin(std::declval<Args>()))...>;
  719. using iterator_category = typename iterator::iterator_category;
  720. using value_type = typename iterator::value_type;
  721. using difference_type = typename iterator::difference_type;
  722. using pointer = typename iterator::pointer;
  723. using reference = typename iterator::reference;
  724. private:
  725. std::tuple<Args...> ts;
  726. template <size_t... Ns>
  727. iterator begin_impl(std::index_sequence<Ns...>) const {
  728. return iterator(std::make_pair(adl_begin(std::get<Ns>(ts)),
  729. adl_end(std::get<Ns>(ts)))...);
  730. }
  731. template <size_t... Ns> iterator end_impl(std::index_sequence<Ns...>) const {
  732. return iterator(std::make_pair(adl_end(std::get<Ns>(ts)),
  733. adl_end(std::get<Ns>(ts)))...);
  734. }
  735. public:
  736. zip_longest_range(Args &&... ts_) : ts(std::forward<Args>(ts_)...) {}
  737. iterator begin() const {
  738. return begin_impl(std::index_sequence_for<Args...>{});
  739. }
  740. iterator end() const { return end_impl(std::index_sequence_for<Args...>{}); }
  741. };
  742. } // namespace detail
  743. /// Iterate over two or more iterators at the same time. Iteration continues
  744. /// until all iterators reach the end. The llvm::Optional only contains a value
  745. /// if the iterator has not reached the end.
  746. template <typename T, typename U, typename... Args>
  747. detail::zip_longest_range<T, U, Args...> zip_longest(T &&t, U &&u,
  748. Args &&... args) {
  749. return detail::zip_longest_range<T, U, Args...>(
  750. std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
  751. }
  752. /// Iterator wrapper that concatenates sequences together.
  753. ///
  754. /// This can concatenate different iterators, even with different types, into
  755. /// a single iterator provided the value types of all the concatenated
  756. /// iterators expose `reference` and `pointer` types that can be converted to
  757. /// `ValueT &` and `ValueT *` respectively. It doesn't support more
  758. /// interesting/customized pointer or reference types.
  759. ///
  760. /// Currently this only supports forward or higher iterator categories as
  761. /// inputs and always exposes a forward iterator interface.
  762. template <typename ValueT, typename... IterTs>
  763. class concat_iterator
  764. : public iterator_facade_base<concat_iterator<ValueT, IterTs...>,
  765. std::forward_iterator_tag, ValueT> {
  766. using BaseT = typename concat_iterator::iterator_facade_base;
  767. /// We store both the current and end iterators for each concatenated
  768. /// sequence in a tuple of pairs.
  769. ///
  770. /// Note that something like iterator_range seems nice at first here, but the
  771. /// range properties are of little benefit and end up getting in the way
  772. /// because we need to do mutation on the current iterators.
  773. std::tuple<IterTs...> Begins;
  774. std::tuple<IterTs...> Ends;
  775. /// Attempts to increment a specific iterator.
  776. ///
  777. /// Returns true if it was able to increment the iterator. Returns false if
  778. /// the iterator is already at the end iterator.
  779. template <size_t Index> bool incrementHelper() {
  780. auto &Begin = std::get<Index>(Begins);
  781. auto &End = std::get<Index>(Ends);
  782. if (Begin == End)
  783. return false;
  784. ++Begin;
  785. return true;
  786. }
  787. /// Increments the first non-end iterator.
  788. ///
  789. /// It is an error to call this with all iterators at the end.
  790. template <size_t... Ns> void increment(std::index_sequence<Ns...>) {
  791. // Build a sequence of functions to increment each iterator if possible.
  792. bool (concat_iterator::*IncrementHelperFns[])() = {
  793. &concat_iterator::incrementHelper<Ns>...};
  794. // Loop over them, and stop as soon as we succeed at incrementing one.
  795. for (auto &IncrementHelperFn : IncrementHelperFns)
  796. if ((this->*IncrementHelperFn)())
  797. return;
  798. llvm_unreachable("Attempted to increment an end concat iterator!");
  799. }
  800. /// Returns null if the specified iterator is at the end. Otherwise,
  801. /// dereferences the iterator and returns the address of the resulting
  802. /// reference.
  803. template <size_t Index> ValueT *getHelper() const {
  804. auto &Begin = std::get<Index>(Begins);
  805. auto &End = std::get<Index>(Ends);
  806. if (Begin == End)
  807. return nullptr;
  808. return &*Begin;
  809. }
  810. /// Finds the first non-end iterator, dereferences, and returns the resulting
  811. /// reference.
  812. ///
  813. /// It is an error to call this with all iterators at the end.
  814. template <size_t... Ns> ValueT &get(std::index_sequence<Ns...>) const {
  815. // Build a sequence of functions to get from iterator if possible.
  816. ValueT *(concat_iterator::*GetHelperFns[])() const = {
  817. &concat_iterator::getHelper<Ns>...};
  818. // Loop over them, and return the first result we find.
  819. for (auto &GetHelperFn : GetHelperFns)
  820. if (ValueT *P = (this->*GetHelperFn)())
  821. return *P;
  822. llvm_unreachable("Attempted to get a pointer from an end concat iterator!");
  823. }
  824. public:
  825. /// Constructs an iterator from a sequence of ranges.
  826. ///
  827. /// We need the full range to know how to switch between each of the
  828. /// iterators.
  829. template <typename... RangeTs>
  830. explicit concat_iterator(RangeTs &&... Ranges)
  831. : Begins(std::begin(Ranges)...), Ends(std::end(Ranges)...) {}
  832. using BaseT::operator++;
  833. concat_iterator &operator++() {
  834. increment(std::index_sequence_for<IterTs...>());
  835. return *this;
  836. }
  837. ValueT &operator*() const {
  838. return get(std::index_sequence_for<IterTs...>());
  839. }
  840. bool operator==(const concat_iterator &RHS) const {
  841. return Begins == RHS.Begins && Ends == RHS.Ends;
  842. }
  843. };
  844. namespace detail {
  845. /// Helper to store a sequence of ranges being concatenated and access them.
  846. ///
  847. /// This is designed to facilitate providing actual storage when temporaries
  848. /// are passed into the constructor such that we can use it as part of range
  849. /// based for loops.
  850. template <typename ValueT, typename... RangeTs> class concat_range {
  851. public:
  852. using iterator =
  853. concat_iterator<ValueT,
  854. decltype(std::begin(std::declval<RangeTs &>()))...>;
  855. private:
  856. std::tuple<RangeTs...> Ranges;
  857. template <size_t... Ns>
  858. iterator begin_impl(std::index_sequence<Ns...>) {
  859. return iterator(std::get<Ns>(Ranges)...);
  860. }
  861. template <size_t... Ns>
  862. iterator begin_impl(std::index_sequence<Ns...>) const {
  863. return iterator(std::get<Ns>(Ranges)...);
  864. }
  865. template <size_t... Ns> iterator end_impl(std::index_sequence<Ns...>) {
  866. return iterator(make_range(std::end(std::get<Ns>(Ranges)),
  867. std::end(std::get<Ns>(Ranges)))...);
  868. }
  869. template <size_t... Ns> iterator end_impl(std::index_sequence<Ns...>) const {
  870. return iterator(make_range(std::end(std::get<Ns>(Ranges)),
  871. std::end(std::get<Ns>(Ranges)))...);
  872. }
  873. public:
  874. concat_range(RangeTs &&... Ranges)
  875. : Ranges(std::forward<RangeTs>(Ranges)...) {}
  876. iterator begin() {
  877. return begin_impl(std::index_sequence_for<RangeTs...>{});
  878. }
  879. iterator begin() const {
  880. return begin_impl(std::index_sequence_for<RangeTs...>{});
  881. }
  882. iterator end() {
  883. return end_impl(std::index_sequence_for<RangeTs...>{});
  884. }
  885. iterator end() const {
  886. return end_impl(std::index_sequence_for<RangeTs...>{});
  887. }
  888. };
  889. } // end namespace detail
  890. /// Concatenated range across two or more ranges.
  891. ///
  892. /// The desired value type must be explicitly specified.
  893. template <typename ValueT, typename... RangeTs>
  894. detail::concat_range<ValueT, RangeTs...> concat(RangeTs &&... Ranges) {
  895. static_assert(sizeof...(RangeTs) > 1,
  896. "Need more than one range to concatenate!");
  897. return detail::concat_range<ValueT, RangeTs...>(
  898. std::forward<RangeTs>(Ranges)...);
  899. }
  900. /// A utility class used to implement an iterator that contains some base object
  901. /// and an index. The iterator moves the index but keeps the base constant.
  902. template <typename DerivedT, typename BaseT, typename T,
  903. typename PointerT = T *, typename ReferenceT = T &>
  904. class indexed_accessor_iterator
  905. : public llvm::iterator_facade_base<DerivedT,
  906. std::random_access_iterator_tag, T,
  907. std::ptrdiff_t, PointerT, ReferenceT> {
  908. public:
  909. ptrdiff_t operator-(const indexed_accessor_iterator &rhs) const {
  910. assert(base == rhs.base && "incompatible iterators");
  911. return index - rhs.index;
  912. }
  913. bool operator==(const indexed_accessor_iterator &rhs) const {
  914. return base == rhs.base && index == rhs.index;
  915. }
  916. bool operator<(const indexed_accessor_iterator &rhs) const {
  917. assert(base == rhs.base && "incompatible iterators");
  918. return index < rhs.index;
  919. }
  920. DerivedT &operator+=(ptrdiff_t offset) {
  921. this->index += offset;
  922. return static_cast<DerivedT &>(*this);
  923. }
  924. DerivedT &operator-=(ptrdiff_t offset) {
  925. this->index -= offset;
  926. return static_cast<DerivedT &>(*this);
  927. }
  928. /// Returns the current index of the iterator.
  929. ptrdiff_t getIndex() const { return index; }
  930. /// Returns the current base of the iterator.
  931. const BaseT &getBase() const { return base; }
  932. protected:
  933. indexed_accessor_iterator(BaseT base, ptrdiff_t index)
  934. : base(base), index(index) {}
  935. BaseT base;
  936. ptrdiff_t index;
  937. };
  938. namespace detail {
  939. /// The class represents the base of a range of indexed_accessor_iterators. It
  940. /// provides support for many different range functionalities, e.g.
  941. /// drop_front/slice/etc.. Derived range classes must implement the following
  942. /// static methods:
  943. /// * ReferenceT dereference_iterator(const BaseT &base, ptrdiff_t index)
  944. /// - Dereference an iterator pointing to the base object at the given
  945. /// index.
  946. /// * BaseT offset_base(const BaseT &base, ptrdiff_t index)
  947. /// - Return a new base that is offset from the provide base by 'index'
  948. /// elements.
  949. template <typename DerivedT, typename BaseT, typename T,
  950. typename PointerT = T *, typename ReferenceT = T &>
  951. class indexed_accessor_range_base {
  952. public:
  953. using RangeBaseT = indexed_accessor_range_base;
  954. /// An iterator element of this range.
  955. class iterator : public indexed_accessor_iterator<iterator, BaseT, T,
  956. PointerT, ReferenceT> {
  957. public:
  958. // Index into this iterator, invoking a static method on the derived type.
  959. ReferenceT operator*() const {
  960. return DerivedT::dereference_iterator(this->getBase(), this->getIndex());
  961. }
  962. private:
  963. iterator(BaseT owner, ptrdiff_t curIndex)
  964. : iterator::indexed_accessor_iterator(owner, curIndex) {}
  965. /// Allow access to the constructor.
  966. friend indexed_accessor_range_base<DerivedT, BaseT, T, PointerT,
  967. ReferenceT>;
  968. };
  969. indexed_accessor_range_base(iterator begin, iterator end)
  970. : base(offset_base(begin.getBase(), begin.getIndex())),
  971. count(end.getIndex() - begin.getIndex()) {}
  972. indexed_accessor_range_base(const iterator_range<iterator> &range)
  973. : indexed_accessor_range_base(range.begin(), range.end()) {}
  974. indexed_accessor_range_base(BaseT base, ptrdiff_t count)
  975. : base(base), count(count) {}
  976. iterator begin() const { return iterator(base, 0); }
  977. iterator end() const { return iterator(base, count); }
  978. ReferenceT operator[](size_t Index) const {
  979. assert(Index < size() && "invalid index for value range");
  980. return DerivedT::dereference_iterator(base, static_cast<ptrdiff_t>(Index));
  981. }
  982. ReferenceT front() const {
  983. assert(!empty() && "expected non-empty range");
  984. return (*this)[0];
  985. }
  986. ReferenceT back() const {
  987. assert(!empty() && "expected non-empty range");
  988. return (*this)[size() - 1];
  989. }
  990. /// Compare this range with another.
  991. template <typename OtherT> bool operator==(const OtherT &other) const {
  992. return size() ==
  993. static_cast<size_t>(std::distance(other.begin(), other.end())) &&
  994. std::equal(begin(), end(), other.begin());
  995. }
  996. template <typename OtherT> bool operator!=(const OtherT &other) const {
  997. return !(*this == other);
  998. }
  999. /// Return the size of this range.
  1000. size_t size() const { return count; }
  1001. /// Return if the range is empty.
  1002. bool empty() const { return size() == 0; }
  1003. /// Drop the first N elements, and keep M elements.
  1004. DerivedT slice(size_t n, size_t m) const {
  1005. assert(n + m <= size() && "invalid size specifiers");
  1006. return DerivedT(offset_base(base, n), m);
  1007. }
  1008. /// Drop the first n elements.
  1009. DerivedT drop_front(size_t n = 1) const {
  1010. assert(size() >= n && "Dropping more elements than exist");
  1011. return slice(n, size() - n);
  1012. }
  1013. /// Drop the last n elements.
  1014. DerivedT drop_back(size_t n = 1) const {
  1015. assert(size() >= n && "Dropping more elements than exist");
  1016. return DerivedT(base, size() - n);
  1017. }
  1018. /// Take the first n elements.
  1019. DerivedT take_front(size_t n = 1) const {
  1020. return n < size() ? drop_back(size() - n)
  1021. : static_cast<const DerivedT &>(*this);
  1022. }
  1023. /// Take the last n elements.
  1024. DerivedT take_back(size_t n = 1) const {
  1025. return n < size() ? drop_front(size() - n)
  1026. : static_cast<const DerivedT &>(*this);
  1027. }
  1028. /// Allow conversion to any type accepting an iterator_range.
  1029. template <typename RangeT, typename = std::enable_if_t<std::is_constructible<
  1030. RangeT, iterator_range<iterator>>::value>>
  1031. operator RangeT() const {
  1032. return RangeT(iterator_range<iterator>(*this));
  1033. }
  1034. /// Returns the base of this range.
  1035. const BaseT &getBase() const { return base; }
  1036. private:
  1037. /// Offset the given base by the given amount.
  1038. static BaseT offset_base(const BaseT &base, size_t n) {
  1039. return n == 0 ? base : DerivedT::offset_base(base, n);
  1040. }
  1041. protected:
  1042. indexed_accessor_range_base(const indexed_accessor_range_base &) = default;
  1043. indexed_accessor_range_base(indexed_accessor_range_base &&) = default;
  1044. indexed_accessor_range_base &
  1045. operator=(const indexed_accessor_range_base &) = default;
  1046. /// The base that owns the provided range of values.
  1047. BaseT base;
  1048. /// The size from the owning range.
  1049. ptrdiff_t count;
  1050. };
  1051. } // end namespace detail
  1052. /// This class provides an implementation of a range of
  1053. /// indexed_accessor_iterators where the base is not indexable. Ranges with
  1054. /// bases that are offsetable should derive from indexed_accessor_range_base
  1055. /// instead. Derived range classes are expected to implement the following
  1056. /// static method:
  1057. /// * ReferenceT dereference(const BaseT &base, ptrdiff_t index)
  1058. /// - Dereference an iterator pointing to a parent base at the given index.
  1059. template <typename DerivedT, typename BaseT, typename T,
  1060. typename PointerT = T *, typename ReferenceT = T &>
  1061. class indexed_accessor_range
  1062. : public detail::indexed_accessor_range_base<
  1063. DerivedT, std::pair<BaseT, ptrdiff_t>, T, PointerT, ReferenceT> {
  1064. public:
  1065. indexed_accessor_range(BaseT base, ptrdiff_t startIndex, ptrdiff_t count)
  1066. : detail::indexed_accessor_range_base<
  1067. DerivedT, std::pair<BaseT, ptrdiff_t>, T, PointerT, ReferenceT>(
  1068. std::make_pair(base, startIndex), count) {}
  1069. using detail::indexed_accessor_range_base<
  1070. DerivedT, std::pair<BaseT, ptrdiff_t>, T, PointerT,
  1071. ReferenceT>::indexed_accessor_range_base;
  1072. /// Returns the current base of the range.
  1073. const BaseT &getBase() const { return this->base.first; }
  1074. /// Returns the current start index of the range.
  1075. ptrdiff_t getStartIndex() const { return this->base.second; }
  1076. /// See `detail::indexed_accessor_range_base` for details.
  1077. static std::pair<BaseT, ptrdiff_t>
  1078. offset_base(const std::pair<BaseT, ptrdiff_t> &base, ptrdiff_t index) {
  1079. // We encode the internal base as a pair of the derived base and a start
  1080. // index into the derived base.
  1081. return std::make_pair(base.first, base.second + index);
  1082. }
  1083. /// See `detail::indexed_accessor_range_base` for details.
  1084. static ReferenceT
  1085. dereference_iterator(const std::pair<BaseT, ptrdiff_t> &base,
  1086. ptrdiff_t index) {
  1087. return DerivedT::dereference(base.first, base.second + index);
  1088. }
  1089. };
  1090. namespace detail {
  1091. /// Return a reference to the first or second member of a reference. Otherwise,
  1092. /// return a copy of the member of a temporary.
  1093. ///
  1094. /// When passing a range whose iterators return values instead of references,
  1095. /// the reference must be dropped from `decltype((elt.first))`, which will
  1096. /// always be a reference, to avoid returning a reference to a temporary.
  1097. template <typename EltTy, typename FirstTy> class first_or_second_type {
  1098. public:
  1099. using type =
  1100. typename std::conditional_t<std::is_reference<EltTy>::value, FirstTy,
  1101. std::remove_reference_t<FirstTy>>;
  1102. };
  1103. } // end namespace detail
  1104. /// Given a container of pairs, return a range over the first elements.
  1105. template <typename ContainerTy> auto make_first_range(ContainerTy &&c) {
  1106. using EltTy = decltype((*std::begin(c)));
  1107. return llvm::map_range(std::forward<ContainerTy>(c),
  1108. [](EltTy elt) -> typename detail::first_or_second_type<
  1109. EltTy, decltype((elt.first))>::type {
  1110. return elt.first;
  1111. });
  1112. }
  1113. /// Given a container of pairs, return a range over the second elements.
  1114. template <typename ContainerTy> auto make_second_range(ContainerTy &&c) {
  1115. return llvm::map_range(
  1116. std::forward<ContainerTy>(c),
  1117. [](decltype((*std::begin(c))) elt) -> decltype((elt.second)) {
  1118. return elt.second;
  1119. });
  1120. }
  1121. //===----------------------------------------------------------------------===//
  1122. // Extra additions to <utility>
  1123. //===----------------------------------------------------------------------===//
  1124. /// Function object to check whether the first component of a std::pair
  1125. /// compares less than the first component of another std::pair.
  1126. struct less_first {
  1127. template <typename T> bool operator()(const T &lhs, const T &rhs) const {
  1128. return std::less<>()(lhs.first, rhs.first);
  1129. }
  1130. };
  1131. /// Function object to check whether the second component of a std::pair
  1132. /// compares less than the second component of another std::pair.
  1133. struct less_second {
  1134. template <typename T> bool operator()(const T &lhs, const T &rhs) const {
  1135. return std::less<>()(lhs.second, rhs.second);
  1136. }
  1137. };
  1138. /// \brief Function object to apply a binary function to the first component of
  1139. /// a std::pair.
  1140. template<typename FuncTy>
  1141. struct on_first {
  1142. FuncTy func;
  1143. template <typename T>
  1144. decltype(auto) operator()(const T &lhs, const T &rhs) const {
  1145. return func(lhs.first, rhs.first);
  1146. }
  1147. };
  1148. /// Utility type to build an inheritance chain that makes it easy to rank
  1149. /// overload candidates.
  1150. template <int N> struct rank : rank<N - 1> {};
  1151. template <> struct rank<0> {};
  1152. /// traits class for checking whether type T is one of any of the given
  1153. /// types in the variadic list.
  1154. template <typename T, typename... Ts>
  1155. using is_one_of = disjunction<std::is_same<T, Ts>...>;
  1156. /// traits class for checking whether type T is a base class for all
  1157. /// the given types in the variadic list.
  1158. template <typename T, typename... Ts>
  1159. using are_base_of = conjunction<std::is_base_of<T, Ts>...>;
  1160. namespace detail {
  1161. template <typename... Ts> struct Visitor;
  1162. template <typename HeadT, typename... TailTs>
  1163. struct Visitor<HeadT, TailTs...> : remove_cvref_t<HeadT>, Visitor<TailTs...> {
  1164. explicit constexpr Visitor(HeadT &&Head, TailTs &&...Tail)
  1165. : remove_cvref_t<HeadT>(std::forward<HeadT>(Head)),
  1166. Visitor<TailTs...>(std::forward<TailTs>(Tail)...) {}
  1167. using remove_cvref_t<HeadT>::operator();
  1168. using Visitor<TailTs...>::operator();
  1169. };
  1170. template <typename HeadT> struct Visitor<HeadT> : remove_cvref_t<HeadT> {
  1171. explicit constexpr Visitor(HeadT &&Head)
  1172. : remove_cvref_t<HeadT>(std::forward<HeadT>(Head)) {}
  1173. using remove_cvref_t<HeadT>::operator();
  1174. };
  1175. } // namespace detail
  1176. /// Returns an opaquely-typed Callable object whose operator() overload set is
  1177. /// the sum of the operator() overload sets of each CallableT in CallableTs.
  1178. ///
  1179. /// The type of the returned object derives from each CallableT in CallableTs.
  1180. /// The returned object is constructed by invoking the appropriate copy or move
  1181. /// constructor of each CallableT, as selected by overload resolution on the
  1182. /// corresponding argument to makeVisitor.
  1183. ///
  1184. /// Example:
  1185. ///
  1186. /// \code
  1187. /// auto visitor = makeVisitor([](auto) { return "unhandled type"; },
  1188. /// [](int i) { return "int"; },
  1189. /// [](std::string s) { return "str"; });
  1190. /// auto a = visitor(42); // `a` is now "int".
  1191. /// auto b = visitor("foo"); // `b` is now "str".
  1192. /// auto c = visitor(3.14f); // `c` is now "unhandled type".
  1193. /// \endcode
  1194. ///
  1195. /// Example of making a visitor with a lambda which captures a move-only type:
  1196. ///
  1197. /// \code
  1198. /// std::unique_ptr<FooHandler> FH = /* ... */;
  1199. /// auto visitor = makeVisitor(
  1200. /// [FH{std::move(FH)}](Foo F) { return FH->handle(F); },
  1201. /// [](int i) { return i; },
  1202. /// [](std::string s) { return atoi(s); });
  1203. /// \endcode
  1204. template <typename... CallableTs>
  1205. constexpr decltype(auto) makeVisitor(CallableTs &&...Callables) {
  1206. return detail::Visitor<CallableTs...>(std::forward<CallableTs>(Callables)...);
  1207. }
  1208. //===----------------------------------------------------------------------===//
  1209. // Extra additions to <algorithm>
  1210. //===----------------------------------------------------------------------===//
  1211. // We have a copy here so that LLVM behaves the same when using different
  1212. // standard libraries.
  1213. template <class Iterator, class RNG>
  1214. void shuffle(Iterator first, Iterator last, RNG &&g) {
  1215. // It would be better to use a std::uniform_int_distribution,
  1216. // but that would be stdlib dependent.
  1217. typedef
  1218. typename std::iterator_traits<Iterator>::difference_type difference_type;
  1219. for (auto size = last - first; size > 1; ++first, (void)--size) {
  1220. difference_type offset = g() % size;
  1221. // Avoid self-assignment due to incorrect assertions in libstdc++
  1222. // containers (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85828).
  1223. if (offset != difference_type(0))
  1224. std::iter_swap(first, first + offset);
  1225. }
  1226. }
  1227. /// Adapt std::less<T> for array_pod_sort.
  1228. template<typename T>
  1229. inline int array_pod_sort_comparator(const void *P1, const void *P2) {
  1230. if (std::less<T>()(*reinterpret_cast<const T*>(P1),
  1231. *reinterpret_cast<const T*>(P2)))
  1232. return -1;
  1233. if (std::less<T>()(*reinterpret_cast<const T*>(P2),
  1234. *reinterpret_cast<const T*>(P1)))
  1235. return 1;
  1236. return 0;
  1237. }
  1238. /// get_array_pod_sort_comparator - This is an internal helper function used to
  1239. /// get type deduction of T right.
  1240. template<typename T>
  1241. inline int (*get_array_pod_sort_comparator(const T &))
  1242. (const void*, const void*) {
  1243. return array_pod_sort_comparator<T>;
  1244. }
  1245. #ifdef EXPENSIVE_CHECKS
  1246. namespace detail {
  1247. inline unsigned presortShuffleEntropy() {
  1248. static unsigned Result(std::random_device{}());
  1249. return Result;
  1250. }
  1251. template <class IteratorTy>
  1252. inline void presortShuffle(IteratorTy Start, IteratorTy End) {
  1253. std::mt19937 Generator(presortShuffleEntropy());
  1254. llvm::shuffle(Start, End, Generator);
  1255. }
  1256. } // end namespace detail
  1257. #endif
  1258. /// array_pod_sort - This sorts an array with the specified start and end
  1259. /// extent. This is just like std::sort, except that it calls qsort instead of
  1260. /// using an inlined template. qsort is slightly slower than std::sort, but
  1261. /// most sorts are not performance critical in LLVM and std::sort has to be
  1262. /// template instantiated for each type, leading to significant measured code
  1263. /// bloat. This function should generally be used instead of std::sort where
  1264. /// possible.
  1265. ///
  1266. /// This function assumes that you have simple POD-like types that can be
  1267. /// compared with std::less and can be moved with memcpy. If this isn't true,
  1268. /// you should use std::sort.
  1269. ///
  1270. /// NOTE: If qsort_r were portable, we could allow a custom comparator and
  1271. /// default to std::less.
  1272. template<class IteratorTy>
  1273. inline void array_pod_sort(IteratorTy Start, IteratorTy End) {
  1274. // Don't inefficiently call qsort with one element or trigger undefined
  1275. // behavior with an empty sequence.
  1276. auto NElts = End - Start;
  1277. if (NElts <= 1) return;
  1278. #ifdef EXPENSIVE_CHECKS
  1279. detail::presortShuffle<IteratorTy>(Start, End);
  1280. #endif
  1281. qsort(&*Start, NElts, sizeof(*Start), get_array_pod_sort_comparator(*Start));
  1282. }
  1283. template <class IteratorTy>
  1284. inline void array_pod_sort(
  1285. IteratorTy Start, IteratorTy End,
  1286. int (*Compare)(
  1287. const typename std::iterator_traits<IteratorTy>::value_type *,
  1288. const typename std::iterator_traits<IteratorTy>::value_type *)) {
  1289. // Don't inefficiently call qsort with one element or trigger undefined
  1290. // behavior with an empty sequence.
  1291. auto NElts = End - Start;
  1292. if (NElts <= 1) return;
  1293. #ifdef EXPENSIVE_CHECKS
  1294. detail::presortShuffle<IteratorTy>(Start, End);
  1295. #endif
  1296. qsort(&*Start, NElts, sizeof(*Start),
  1297. reinterpret_cast<int (*)(const void *, const void *)>(Compare));
  1298. }
  1299. namespace detail {
  1300. template <typename T>
  1301. // We can use qsort if the iterator type is a pointer and the underlying value
  1302. // is trivially copyable.
  1303. using sort_trivially_copyable = conjunction<
  1304. std::is_pointer<T>,
  1305. std::is_trivially_copyable<typename std::iterator_traits<T>::value_type>>;
  1306. } // namespace detail
  1307. // Provide wrappers to std::sort which shuffle the elements before sorting
  1308. // to help uncover non-deterministic behavior (PR35135).
  1309. template <typename IteratorTy,
  1310. std::enable_if_t<!detail::sort_trivially_copyable<IteratorTy>::value,
  1311. int> = 0>
  1312. inline void sort(IteratorTy Start, IteratorTy End) {
  1313. #ifdef EXPENSIVE_CHECKS
  1314. detail::presortShuffle<IteratorTy>(Start, End);
  1315. #endif
  1316. std::sort(Start, End);
  1317. }
  1318. // Forward trivially copyable types to array_pod_sort. This avoids a large
  1319. // amount of code bloat for a minor performance hit.
  1320. template <typename IteratorTy,
  1321. std::enable_if_t<detail::sort_trivially_copyable<IteratorTy>::value,
  1322. int> = 0>
  1323. inline void sort(IteratorTy Start, IteratorTy End) {
  1324. array_pod_sort(Start, End);
  1325. }
  1326. template <typename Container> inline void sort(Container &&C) {
  1327. llvm::sort(adl_begin(C), adl_end(C));
  1328. }
  1329. template <typename IteratorTy, typename Compare>
  1330. inline void sort(IteratorTy Start, IteratorTy End, Compare Comp) {
  1331. #ifdef EXPENSIVE_CHECKS
  1332. detail::presortShuffle<IteratorTy>(Start, End);
  1333. #endif
  1334. std::sort(Start, End, Comp);
  1335. }
  1336. template <typename Container, typename Compare>
  1337. inline void sort(Container &&C, Compare Comp) {
  1338. llvm::sort(adl_begin(C), adl_end(C), Comp);
  1339. }
  1340. /// Get the size of a range. This is a wrapper function around std::distance
  1341. /// which is only enabled when the operation is O(1).
  1342. template <typename R>
  1343. auto size(R &&Range,
  1344. std::enable_if_t<
  1345. std::is_base_of<std::random_access_iterator_tag,
  1346. typename std::iterator_traits<decltype(
  1347. Range.begin())>::iterator_category>::value,
  1348. void> * = nullptr) {
  1349. return std::distance(Range.begin(), Range.end());
  1350. }
  1351. /// Provide wrappers to std::for_each which take ranges instead of having to
  1352. /// pass begin/end explicitly.
  1353. template <typename R, typename UnaryFunction>
  1354. UnaryFunction for_each(R &&Range, UnaryFunction F) {
  1355. return std::for_each(adl_begin(Range), adl_end(Range), F);
  1356. }
  1357. /// Provide wrappers to std::all_of which take ranges instead of having to pass
  1358. /// begin/end explicitly.
  1359. template <typename R, typename UnaryPredicate>
  1360. bool all_of(R &&Range, UnaryPredicate P) {
  1361. return std::all_of(adl_begin(Range), adl_end(Range), P);
  1362. }
  1363. /// Provide wrappers to std::any_of which take ranges instead of having to pass
  1364. /// begin/end explicitly.
  1365. template <typename R, typename UnaryPredicate>
  1366. bool any_of(R &&Range, UnaryPredicate P) {
  1367. return std::any_of(adl_begin(Range), adl_end(Range), P);
  1368. }
  1369. /// Provide wrappers to std::none_of which take ranges instead of having to pass
  1370. /// begin/end explicitly.
  1371. template <typename R, typename UnaryPredicate>
  1372. bool none_of(R &&Range, UnaryPredicate P) {
  1373. return std::none_of(adl_begin(Range), adl_end(Range), P);
  1374. }
  1375. /// Provide wrappers to std::find which take ranges instead of having to pass
  1376. /// begin/end explicitly.
  1377. template <typename R, typename T> auto find(R &&Range, const T &Val) {
  1378. return std::find(adl_begin(Range), adl_end(Range), Val);
  1379. }
  1380. /// Provide wrappers to std::find_if which take ranges instead of having to pass
  1381. /// begin/end explicitly.
  1382. template <typename R, typename UnaryPredicate>
  1383. auto find_if(R &&Range, UnaryPredicate P) {
  1384. return std::find_if(adl_begin(Range), adl_end(Range), P);
  1385. }
  1386. template <typename R, typename UnaryPredicate>
  1387. auto find_if_not(R &&Range, UnaryPredicate P) {
  1388. return std::find_if_not(adl_begin(Range), adl_end(Range), P);
  1389. }
  1390. /// Provide wrappers to std::remove_if which take ranges instead of having to
  1391. /// pass begin/end explicitly.
  1392. template <typename R, typename UnaryPredicate>
  1393. auto remove_if(R &&Range, UnaryPredicate P) {
  1394. return std::remove_if(adl_begin(Range), adl_end(Range), P);
  1395. }
  1396. /// Provide wrappers to std::copy_if which take ranges instead of having to
  1397. /// pass begin/end explicitly.
  1398. template <typename R, typename OutputIt, typename UnaryPredicate>
  1399. OutputIt copy_if(R &&Range, OutputIt Out, UnaryPredicate P) {
  1400. return std::copy_if(adl_begin(Range), adl_end(Range), Out, P);
  1401. }
  1402. template <typename R, typename OutputIt>
  1403. OutputIt copy(R &&Range, OutputIt Out) {
  1404. return std::copy(adl_begin(Range), adl_end(Range), Out);
  1405. }
  1406. /// Provide wrappers to std::move which take ranges instead of having to
  1407. /// pass begin/end explicitly.
  1408. template <typename R, typename OutputIt>
  1409. OutputIt move(R &&Range, OutputIt Out) {
  1410. return std::move(adl_begin(Range), adl_end(Range), Out);
  1411. }
  1412. /// Wrapper function around std::find to detect if an element exists
  1413. /// in a container.
  1414. template <typename R, typename E>
  1415. bool is_contained(R &&Range, const E &Element) {
  1416. return std::find(adl_begin(Range), adl_end(Range), Element) != adl_end(Range);
  1417. }
  1418. /// Wrapper function around std::is_sorted to check if elements in a range \p R
  1419. /// are sorted with respect to a comparator \p C.
  1420. template <typename R, typename Compare> bool is_sorted(R &&Range, Compare C) {
  1421. return std::is_sorted(adl_begin(Range), adl_end(Range), C);
  1422. }
  1423. /// Wrapper function around std::is_sorted to check if elements in a range \p R
  1424. /// are sorted in non-descending order.
  1425. template <typename R> bool is_sorted(R &&Range) {
  1426. return std::is_sorted(adl_begin(Range), adl_end(Range));
  1427. }
  1428. /// Wrapper function around std::count to count the number of times an element
  1429. /// \p Element occurs in the given range \p Range.
  1430. template <typename R, typename E> auto count(R &&Range, const E &Element) {
  1431. return std::count(adl_begin(Range), adl_end(Range), Element);
  1432. }
  1433. /// Wrapper function around std::count_if to count the number of times an
  1434. /// element satisfying a given predicate occurs in a range.
  1435. template <typename R, typename UnaryPredicate>
  1436. auto count_if(R &&Range, UnaryPredicate P) {
  1437. return std::count_if(adl_begin(Range), adl_end(Range), P);
  1438. }
  1439. /// Wrapper function around std::transform to apply a function to a range and
  1440. /// store the result elsewhere.
  1441. template <typename R, typename OutputIt, typename UnaryFunction>
  1442. OutputIt transform(R &&Range, OutputIt d_first, UnaryFunction F) {
  1443. return std::transform(adl_begin(Range), adl_end(Range), d_first, F);
  1444. }
  1445. /// Provide wrappers to std::partition which take ranges instead of having to
  1446. /// pass begin/end explicitly.
  1447. template <typename R, typename UnaryPredicate>
  1448. auto partition(R &&Range, UnaryPredicate P) {
  1449. return std::partition(adl_begin(Range), adl_end(Range), P);
  1450. }
  1451. /// Provide wrappers to std::lower_bound which take ranges instead of having to
  1452. /// pass begin/end explicitly.
  1453. template <typename R, typename T> auto lower_bound(R &&Range, T &&Value) {
  1454. return std::lower_bound(adl_begin(Range), adl_end(Range),
  1455. std::forward<T>(Value));
  1456. }
  1457. template <typename R, typename T, typename Compare>
  1458. auto lower_bound(R &&Range, T &&Value, Compare C) {
  1459. return std::lower_bound(adl_begin(Range), adl_end(Range),
  1460. std::forward<T>(Value), C);
  1461. }
  1462. /// Provide wrappers to std::upper_bound which take ranges instead of having to
  1463. /// pass begin/end explicitly.
  1464. template <typename R, typename T> auto upper_bound(R &&Range, T &&Value) {
  1465. return std::upper_bound(adl_begin(Range), adl_end(Range),
  1466. std::forward<T>(Value));
  1467. }
  1468. template <typename R, typename T, typename Compare>
  1469. auto upper_bound(R &&Range, T &&Value, Compare C) {
  1470. return std::upper_bound(adl_begin(Range), adl_end(Range),
  1471. std::forward<T>(Value), C);
  1472. }
  1473. template <typename R>
  1474. void stable_sort(R &&Range) {
  1475. std::stable_sort(adl_begin(Range), adl_end(Range));
  1476. }
  1477. template <typename R, typename Compare>
  1478. void stable_sort(R &&Range, Compare C) {
  1479. std::stable_sort(adl_begin(Range), adl_end(Range), C);
  1480. }
  1481. /// Binary search for the first iterator in a range where a predicate is false.
  1482. /// Requires that C is always true below some limit, and always false above it.
  1483. template <typename R, typename Predicate,
  1484. typename Val = decltype(*adl_begin(std::declval<R>()))>
  1485. auto partition_point(R &&Range, Predicate P) {
  1486. return std::partition_point(adl_begin(Range), adl_end(Range), P);
  1487. }
  1488. template<typename Range, typename Predicate>
  1489. auto unique(Range &&R, Predicate P) {
  1490. return std::unique(adl_begin(R), adl_end(R), P);
  1491. }
  1492. /// Wrapper function around std::equal to detect if pair-wise elements between
  1493. /// two ranges are the same.
  1494. template <typename L, typename R> bool equal(L &&LRange, R &&RRange) {
  1495. return std::equal(adl_begin(LRange), adl_end(LRange), adl_begin(RRange),
  1496. adl_end(RRange));
  1497. }
  1498. /// Wrapper function around std::equal to detect if all elements
  1499. /// in a container are same.
  1500. template <typename R>
  1501. bool is_splat(R &&Range) {
  1502. size_t range_size = size(Range);
  1503. return range_size != 0 && (range_size == 1 ||
  1504. std::equal(adl_begin(Range) + 1, adl_end(Range), adl_begin(Range)));
  1505. }
  1506. /// Provide a container algorithm similar to C++ Library Fundamentals v2's
  1507. /// `erase_if` which is equivalent to:
  1508. ///
  1509. /// C.erase(remove_if(C, pred), C.end());
  1510. ///
  1511. /// This version works for any container with an erase method call accepting
  1512. /// two iterators.
  1513. template <typename Container, typename UnaryPredicate>
  1514. void erase_if(Container &C, UnaryPredicate P) {
  1515. C.erase(remove_if(C, P), C.end());
  1516. }
  1517. /// Wrapper function to remove a value from a container:
  1518. ///
  1519. /// C.erase(remove(C.begin(), C.end(), V), C.end());
  1520. template <typename Container, typename ValueType>
  1521. void erase_value(Container &C, ValueType V) {
  1522. C.erase(std::remove(C.begin(), C.end(), V), C.end());
  1523. }
  1524. /// Wrapper function to append a range to a container.
  1525. ///
  1526. /// C.insert(C.end(), R.begin(), R.end());
  1527. template <typename Container, typename Range>
  1528. inline void append_range(Container &C, Range &&R) {
  1529. C.insert(C.end(), R.begin(), R.end());
  1530. }
  1531. /// Given a sequence container Cont, replace the range [ContIt, ContEnd) with
  1532. /// the range [ValIt, ValEnd) (which is not from the same container).
  1533. template<typename Container, typename RandomAccessIterator>
  1534. void replace(Container &Cont, typename Container::iterator ContIt,
  1535. typename Container::iterator ContEnd, RandomAccessIterator ValIt,
  1536. RandomAccessIterator ValEnd) {
  1537. while (true) {
  1538. if (ValIt == ValEnd) {
  1539. Cont.erase(ContIt, ContEnd);
  1540. return;
  1541. } else if (ContIt == ContEnd) {
  1542. Cont.insert(ContIt, ValIt, ValEnd);
  1543. return;
  1544. }
  1545. *ContIt++ = *ValIt++;
  1546. }
  1547. }
  1548. /// Given a sequence container Cont, replace the range [ContIt, ContEnd) with
  1549. /// the range R.
  1550. template<typename Container, typename Range = std::initializer_list<
  1551. typename Container::value_type>>
  1552. void replace(Container &Cont, typename Container::iterator ContIt,
  1553. typename Container::iterator ContEnd, Range R) {
  1554. replace(Cont, ContIt, ContEnd, R.begin(), R.end());
  1555. }
  1556. /// An STL-style algorithm similar to std::for_each that applies a second
  1557. /// functor between every pair of elements.
  1558. ///
  1559. /// This provides the control flow logic to, for example, print a
  1560. /// comma-separated list:
  1561. /// \code
  1562. /// interleave(names.begin(), names.end(),
  1563. /// [&](StringRef name) { os << name; },
  1564. /// [&] { os << ", "; });
  1565. /// \endcode
  1566. template <typename ForwardIterator, typename UnaryFunctor,
  1567. typename NullaryFunctor,
  1568. typename = typename std::enable_if<
  1569. !std::is_constructible<StringRef, UnaryFunctor>::value &&
  1570. !std::is_constructible<StringRef, NullaryFunctor>::value>::type>
  1571. inline void interleave(ForwardIterator begin, ForwardIterator end,
  1572. UnaryFunctor each_fn, NullaryFunctor between_fn) {
  1573. if (begin == end)
  1574. return;
  1575. each_fn(*begin);
  1576. ++begin;
  1577. for (; begin != end; ++begin) {
  1578. between_fn();
  1579. each_fn(*begin);
  1580. }
  1581. }
  1582. template <typename Container, typename UnaryFunctor, typename NullaryFunctor,
  1583. typename = typename std::enable_if<
  1584. !std::is_constructible<StringRef, UnaryFunctor>::value &&
  1585. !std::is_constructible<StringRef, NullaryFunctor>::value>::type>
  1586. inline void interleave(const Container &c, UnaryFunctor each_fn,
  1587. NullaryFunctor between_fn) {
  1588. interleave(c.begin(), c.end(), each_fn, between_fn);
  1589. }
  1590. /// Overload of interleave for the common case of string separator.
  1591. template <typename Container, typename UnaryFunctor, typename StreamT,
  1592. typename T = detail::ValueOfRange<Container>>
  1593. inline void interleave(const Container &c, StreamT &os, UnaryFunctor each_fn,
  1594. const StringRef &separator) {
  1595. interleave(c.begin(), c.end(), each_fn, [&] { os << separator; });
  1596. }
  1597. template <typename Container, typename StreamT,
  1598. typename T = detail::ValueOfRange<Container>>
  1599. inline void interleave(const Container &c, StreamT &os,
  1600. const StringRef &separator) {
  1601. interleave(
  1602. c, os, [&](const T &a) { os << a; }, separator);
  1603. }
  1604. template <typename Container, typename UnaryFunctor, typename StreamT,
  1605. typename T = detail::ValueOfRange<Container>>
  1606. inline void interleaveComma(const Container &c, StreamT &os,
  1607. UnaryFunctor each_fn) {
  1608. interleave(c, os, each_fn, ", ");
  1609. }
  1610. template <typename Container, typename StreamT,
  1611. typename T = detail::ValueOfRange<Container>>
  1612. inline void interleaveComma(const Container &c, StreamT &os) {
  1613. interleaveComma(c, os, [&](const T &a) { os << a; });
  1614. }
  1615. //===----------------------------------------------------------------------===//
  1616. // Extra additions to <memory>
  1617. //===----------------------------------------------------------------------===//
  1618. struct FreeDeleter {
  1619. void operator()(void* v) {
  1620. ::free(v);
  1621. }
  1622. };
  1623. template<typename First, typename Second>
  1624. struct pair_hash {
  1625. size_t operator()(const std::pair<First, Second> &P) const {
  1626. return std::hash<First>()(P.first) * 31 + std::hash<Second>()(P.second);
  1627. }
  1628. };
  1629. /// Binary functor that adapts to any other binary functor after dereferencing
  1630. /// operands.
  1631. template <typename T> struct deref {
  1632. T func;
  1633. // Could be further improved to cope with non-derivable functors and
  1634. // non-binary functors (should be a variadic template member function
  1635. // operator()).
  1636. template <typename A, typename B> auto operator()(A &lhs, B &rhs) const {
  1637. assert(lhs);
  1638. assert(rhs);
  1639. return func(*lhs, *rhs);
  1640. }
  1641. };
  1642. namespace detail {
  1643. template <typename R> class enumerator_iter;
  1644. template <typename R> struct result_pair {
  1645. using value_reference =
  1646. typename std::iterator_traits<IterOfRange<R>>::reference;
  1647. friend class enumerator_iter<R>;
  1648. result_pair() = default;
  1649. result_pair(std::size_t Index, IterOfRange<R> Iter)
  1650. : Index(Index), Iter(Iter) {}
  1651. result_pair(const result_pair<R> &Other)
  1652. : Index(Other.Index), Iter(Other.Iter) {}
  1653. result_pair &operator=(const result_pair &Other) {
  1654. Index = Other.Index;
  1655. Iter = Other.Iter;
  1656. return *this;
  1657. }
  1658. std::size_t index() const { return Index; }
  1659. value_reference value() const { return *Iter; }
  1660. private:
  1661. std::size_t Index = std::numeric_limits<std::size_t>::max();
  1662. IterOfRange<R> Iter;
  1663. };
  1664. template <typename R>
  1665. class enumerator_iter
  1666. : public iterator_facade_base<enumerator_iter<R>, std::forward_iterator_tag,
  1667. const result_pair<R>> {
  1668. using result_type = result_pair<R>;
  1669. public:
  1670. explicit enumerator_iter(IterOfRange<R> EndIter)
  1671. : Result(std::numeric_limits<size_t>::max(), EndIter) {}
  1672. enumerator_iter(std::size_t Index, IterOfRange<R> Iter)
  1673. : Result(Index, Iter) {}
  1674. const result_type &operator*() const { return Result; }
  1675. enumerator_iter &operator++() {
  1676. assert(Result.Index != std::numeric_limits<size_t>::max());
  1677. ++Result.Iter;
  1678. ++Result.Index;
  1679. return *this;
  1680. }
  1681. bool operator==(const enumerator_iter &RHS) const {
  1682. // Don't compare indices here, only iterators. It's possible for an end
  1683. // iterator to have different indices depending on whether it was created
  1684. // by calling std::end() versus incrementing a valid iterator.
  1685. return Result.Iter == RHS.Result.Iter;
  1686. }
  1687. enumerator_iter(const enumerator_iter &Other) : Result(Other.Result) {}
  1688. enumerator_iter &operator=(const enumerator_iter &Other) {
  1689. Result = Other.Result;
  1690. return *this;
  1691. }
  1692. private:
  1693. result_type Result;
  1694. };
  1695. template <typename R> class enumerator {
  1696. public:
  1697. explicit enumerator(R &&Range) : TheRange(std::forward<R>(Range)) {}
  1698. enumerator_iter<R> begin() {
  1699. return enumerator_iter<R>(0, std::begin(TheRange));
  1700. }
  1701. enumerator_iter<R> begin() const {
  1702. return enumerator_iter<R>(0, std::begin(TheRange));
  1703. }
  1704. enumerator_iter<R> end() {
  1705. return enumerator_iter<R>(std::end(TheRange));
  1706. }
  1707. enumerator_iter<R> end() const {
  1708. return enumerator_iter<R>(std::end(TheRange));
  1709. }
  1710. private:
  1711. R TheRange;
  1712. };
  1713. } // end namespace detail
  1714. /// Given an input range, returns a new range whose values are are pair (A,B)
  1715. /// such that A is the 0-based index of the item in the sequence, and B is
  1716. /// the value from the original sequence. Example:
  1717. ///
  1718. /// std::vector<char> Items = {'A', 'B', 'C', 'D'};
  1719. /// for (auto X : enumerate(Items)) {
  1720. /// printf("Item %d - %c\n", X.index(), X.value());
  1721. /// }
  1722. ///
  1723. /// Output:
  1724. /// Item 0 - A
  1725. /// Item 1 - B
  1726. /// Item 2 - C
  1727. /// Item 3 - D
  1728. ///
  1729. template <typename R> detail::enumerator<R> enumerate(R &&TheRange) {
  1730. return detail::enumerator<R>(std::forward<R>(TheRange));
  1731. }
  1732. namespace detail {
  1733. template <typename F, typename Tuple, std::size_t... I>
  1734. decltype(auto) apply_tuple_impl(F &&f, Tuple &&t, std::index_sequence<I...>) {
  1735. return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...);
  1736. }
  1737. } // end namespace detail
  1738. /// Given an input tuple (a1, a2, ..., an), pass the arguments of the
  1739. /// tuple variadically to f as if by calling f(a1, a2, ..., an) and
  1740. /// return the result.
  1741. template <typename F, typename Tuple>
  1742. decltype(auto) apply_tuple(F &&f, Tuple &&t) {
  1743. using Indices = std::make_index_sequence<
  1744. std::tuple_size<typename std::decay<Tuple>::type>::value>;
  1745. return detail::apply_tuple_impl(std::forward<F>(f), std::forward<Tuple>(t),
  1746. Indices{});
  1747. }
  1748. namespace detail {
  1749. template <typename Predicate, typename... Args>
  1750. bool all_of_zip_predicate_first(Predicate &&P, Args &&...args) {
  1751. auto z = zip(args...);
  1752. auto it = z.begin();
  1753. auto end = z.end();
  1754. while (it != end) {
  1755. if (!apply_tuple([&](auto &&...args) { return P(args...); }, *it))
  1756. return false;
  1757. ++it;
  1758. }
  1759. return it.all_equals(end);
  1760. }
  1761. // Just an adaptor to switch the order of argument and have the predicate before
  1762. // the zipped inputs.
  1763. template <typename... ArgsThenPredicate, size_t... InputIndexes>
  1764. bool all_of_zip_predicate_last(
  1765. std::tuple<ArgsThenPredicate...> argsThenPredicate,
  1766. std::index_sequence<InputIndexes...>) {
  1767. auto constexpr OutputIndex =
  1768. std::tuple_size<decltype(argsThenPredicate)>::value - 1;
  1769. return all_of_zip_predicate_first(std::get<OutputIndex>(argsThenPredicate),
  1770. std::get<InputIndexes>(argsThenPredicate)...);
  1771. }
  1772. } // end namespace detail
  1773. /// Compare two zipped ranges using the provided predicate (as last argument).
  1774. /// Return true if all elements satisfy the predicate and false otherwise.
  1775. // Return false if the zipped iterator aren't all at end (size mismatch).
  1776. template <typename... ArgsAndPredicate>
  1777. bool all_of_zip(ArgsAndPredicate &&...argsAndPredicate) {
  1778. return detail::all_of_zip_predicate_last(
  1779. std::forward_as_tuple(argsAndPredicate...),
  1780. std::make_index_sequence<sizeof...(argsAndPredicate) - 1>{});
  1781. }
  1782. /// Return true if the sequence [Begin, End) has exactly N items. Runs in O(N)
  1783. /// time. Not meant for use with random-access iterators.
  1784. /// Can optionally take a predicate to filter lazily some items.
  1785. template <typename IterTy,
  1786. typename Pred = bool (*)(const decltype(*std::declval<IterTy>()) &)>
  1787. bool hasNItems(
  1788. IterTy &&Begin, IterTy &&End, unsigned N,
  1789. Pred &&ShouldBeCounted =
  1790. [](const decltype(*std::declval<IterTy>()) &) { return true; },
  1791. std::enable_if_t<
  1792. !std::is_base_of<std::random_access_iterator_tag,
  1793. typename std::iterator_traits<std::remove_reference_t<
  1794. decltype(Begin)>>::iterator_category>::value,
  1795. void> * = nullptr) {
  1796. for (; N; ++Begin) {
  1797. if (Begin == End)
  1798. return false; // Too few.
  1799. N -= ShouldBeCounted(*Begin);
  1800. }
  1801. for (; Begin != End; ++Begin)
  1802. if (ShouldBeCounted(*Begin))
  1803. return false; // Too many.
  1804. return true;
  1805. }
  1806. /// Return true if the sequence [Begin, End) has N or more items. Runs in O(N)
  1807. /// time. Not meant for use with random-access iterators.
  1808. /// Can optionally take a predicate to lazily filter some items.
  1809. template <typename IterTy,
  1810. typename Pred = bool (*)(const decltype(*std::declval<IterTy>()) &)>
  1811. bool hasNItemsOrMore(
  1812. IterTy &&Begin, IterTy &&End, unsigned N,
  1813. Pred &&ShouldBeCounted =
  1814. [](const decltype(*std::declval<IterTy>()) &) { return true; },
  1815. std::enable_if_t<
  1816. !std::is_base_of<std::random_access_iterator_tag,
  1817. typename std::iterator_traits<std::remove_reference_t<
  1818. decltype(Begin)>>::iterator_category>::value,
  1819. void> * = nullptr) {
  1820. for (; N; ++Begin) {
  1821. if (Begin == End)
  1822. return false; // Too few.
  1823. N -= ShouldBeCounted(*Begin);
  1824. }
  1825. return true;
  1826. }
  1827. /// Returns true if the sequence [Begin, End) has N or less items. Can
  1828. /// optionally take a predicate to lazily filter some items.
  1829. template <typename IterTy,
  1830. typename Pred = bool (*)(const decltype(*std::declval<IterTy>()) &)>
  1831. bool hasNItemsOrLess(
  1832. IterTy &&Begin, IterTy &&End, unsigned N,
  1833. Pred &&ShouldBeCounted = [](const decltype(*std::declval<IterTy>()) &) {
  1834. return true;
  1835. }) {
  1836. assert(N != std::numeric_limits<unsigned>::max());
  1837. return !hasNItemsOrMore(Begin, End, N + 1, ShouldBeCounted);
  1838. }
  1839. /// Returns true if the given container has exactly N items
  1840. template <typename ContainerTy> bool hasNItems(ContainerTy &&C, unsigned N) {
  1841. return hasNItems(std::begin(C), std::end(C), N);
  1842. }
  1843. /// Returns true if the given container has N or more items
  1844. template <typename ContainerTy>
  1845. bool hasNItemsOrMore(ContainerTy &&C, unsigned N) {
  1846. return hasNItemsOrMore(std::begin(C), std::end(C), N);
  1847. }
  1848. /// Returns true if the given container has N or less items
  1849. template <typename ContainerTy>
  1850. bool hasNItemsOrLess(ContainerTy &&C, unsigned N) {
  1851. return hasNItemsOrLess(std::begin(C), std::end(C), N);
  1852. }
  1853. /// Returns a raw pointer that represents the same address as the argument.
  1854. ///
  1855. /// This implementation can be removed once we move to C++20 where it's defined
  1856. /// as std::to_address().
  1857. ///
  1858. /// The std::pointer_traits<>::to_address(p) variations of these overloads has
  1859. /// not been implemented.
  1860. template <class Ptr> auto to_address(const Ptr &P) { return P.operator->(); }
  1861. template <class T> constexpr T *to_address(T *P) { return P; }
  1862. } // end namespace llvm
  1863. #endif // LLVM_ADT_STLEXTRAS_H
  1864. #ifdef __GNUC__
  1865. #pragma GCC diagnostic pop
  1866. #endif