STLExtras.h 85 KB

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