1 //===- llvm/ADT/STLExtras.h - Useful STL related functions ------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 /// 9 /// \file 10 /// This file contains some templates that are useful if you are working with 11 /// the STL at all. 12 /// 13 /// No library is required when using these functions. 14 /// 15 //===----------------------------------------------------------------------===// 16 17 #ifndef LLVM_ADT_STLEXTRAS_H 18 #define LLVM_ADT_STLEXTRAS_H 19 20 #include "llvm/ADT/ADL.h" 21 #include "llvm/ADT/Hashing.h" 22 #include "llvm/ADT/STLForwardCompat.h" 23 #include "llvm/ADT/STLFunctionalExtras.h" 24 #include "llvm/ADT/iterator.h" 25 #include "llvm/ADT/iterator_range.h" 26 #include "llvm/Config/abi-breaking.h" 27 #include "llvm/Support/ErrorHandling.h" 28 #include <algorithm> 29 #include <cassert> 30 #include <cstddef> 31 #include <cstdint> 32 #include <cstdlib> 33 #include <functional> 34 #include <initializer_list> 35 #include <iterator> 36 #include <limits> 37 #include <memory> 38 #include <optional> 39 #include <tuple> 40 #include <type_traits> 41 #include <utility> 42 43 #ifdef EXPENSIVE_CHECKS 44 #include <random> // for std::mt19937 45 #endif 46 47 namespace llvm { 48 49 //===----------------------------------------------------------------------===// 50 // Extra additions to <type_traits> 51 //===----------------------------------------------------------------------===// 52 53 template <typename T> struct make_const_ptr { 54 using type = std::add_pointer_t<std::add_const_t<T>>; 55 }; 56 57 template <typename T> struct make_const_ref { 58 using type = std::add_lvalue_reference_t<std::add_const_t<T>>; 59 }; 60 61 namespace detail { 62 template <class, template <class...> class Op, class... Args> struct detector { 63 using value_t = std::false_type; 64 }; 65 template <template <class...> class Op, class... Args> 66 struct detector<std::void_t<Op<Args...>>, Op, Args...> { 67 using value_t = std::true_type; 68 }; 69 } // end namespace detail 70 71 /// Detects if a given trait holds for some set of arguments 'Args'. 72 /// For example, the given trait could be used to detect if a given type 73 /// has a copy assignment operator: 74 /// template<class T> 75 /// using has_copy_assign_t = decltype(std::declval<T&>() 76 /// = std::declval<const T&>()); 77 /// bool fooHasCopyAssign = is_detected<has_copy_assign_t, FooClass>::value; 78 template <template <class...> class Op, class... Args> 79 using is_detected = typename detail::detector<void, Op, Args...>::value_t; 80 81 /// This class provides various trait information about a callable object. 82 /// * To access the number of arguments: Traits::num_args 83 /// * To access the type of an argument: Traits::arg_t<Index> 84 /// * To access the type of the result: Traits::result_t 85 template <typename T, bool isClass = std::is_class<T>::value> 86 struct function_traits : public function_traits<decltype(&T::operator())> {}; 87 88 /// Overload for class function types. 89 template <typename ClassType, typename ReturnType, typename... Args> 90 struct function_traits<ReturnType (ClassType::*)(Args...) const, false> { 91 /// The number of arguments to this function. 92 enum { num_args = sizeof...(Args) }; 93 94 /// The result type of this function. 95 using result_t = ReturnType; 96 97 /// The type of an argument to this function. 98 template <size_t Index> 99 using arg_t = std::tuple_element_t<Index, std::tuple<Args...>>; 100 }; 101 /// Overload for class function types. 102 template <typename ClassType, typename ReturnType, typename... Args> 103 struct function_traits<ReturnType (ClassType::*)(Args...), false> 104 : public function_traits<ReturnType (ClassType::*)(Args...) const> {}; 105 /// Overload for non-class function types. 106 template <typename ReturnType, typename... Args> 107 struct function_traits<ReturnType (*)(Args...), false> { 108 /// The number of arguments to this function. 109 enum { num_args = sizeof...(Args) }; 110 111 /// The result type of this function. 112 using result_t = ReturnType; 113 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 126 /// traits class for checking whether type T is one of any of the given 127 /// types in the variadic list. 128 template <typename T, typename... Ts> 129 using is_one_of = std::disjunction<std::is_same<T, Ts>...>; 130 131 /// traits class for checking whether type T is a base class for all 132 /// the given types in the variadic list. 133 template <typename T, typename... Ts> 134 using are_base_of = std::conjunction<std::is_base_of<T, Ts>...>; 135 136 namespace detail { 137 template <typename T, typename... Us> struct TypesAreDistinct; 138 template <typename T, typename... Us> 139 struct TypesAreDistinct 140 : std::integral_constant<bool, !is_one_of<T, Us...>::value && 141 TypesAreDistinct<Us...>::value> {}; 142 template <typename T> struct TypesAreDistinct<T> : std::true_type {}; 143 } // namespace detail 144 145 /// Determine if all types in Ts are distinct. 146 /// 147 /// Useful to statically assert when Ts is intended to describe a non-multi set 148 /// of types. 149 /// 150 /// Expensive (currently quadratic in sizeof(Ts...)), and so should only be 151 /// asserted once per instantiation of a type which requires it. 152 template <typename... Ts> struct TypesAreDistinct; 153 template <> struct TypesAreDistinct<> : std::true_type {}; 154 template <typename... Ts> 155 struct TypesAreDistinct 156 : std::integral_constant<bool, detail::TypesAreDistinct<Ts...>::value> {}; 157 158 /// Find the first index where a type appears in a list of types. 159 /// 160 /// FirstIndexOfType<T, Us...>::value is the first index of T in Us. 161 /// 162 /// Typically only meaningful when it is otherwise statically known that the 163 /// type pack has no duplicate types. This should be guaranteed explicitly with 164 /// static_assert(TypesAreDistinct<Us...>::value). 165 /// 166 /// It is a compile-time error to instantiate when T is not present in Us, i.e. 167 /// if is_one_of<T, Us...>::value is false. 168 template <typename T, typename... Us> struct FirstIndexOfType; 169 template <typename T, typename U, typename... Us> 170 struct FirstIndexOfType<T, U, Us...> 171 : std::integral_constant<size_t, 1 + FirstIndexOfType<T, Us...>::value> {}; 172 template <typename T, typename... Us> 173 struct FirstIndexOfType<T, T, Us...> : std::integral_constant<size_t, 0> {}; 174 175 /// Find the type at a given index in a list of types. 176 /// 177 /// TypeAtIndex<I, Ts...> is the type at index I in Ts. 178 template <size_t I, typename... Ts> 179 using TypeAtIndex = std::tuple_element_t<I, std::tuple<Ts...>>; 180 181 /// Helper which adds two underlying types of enumeration type. 182 /// Implicit conversion to a common type is accepted. 183 template <typename EnumTy1, typename EnumTy2, 184 typename UT1 = std::enable_if_t<std::is_enum<EnumTy1>::value, 185 std::underlying_type_t<EnumTy1>>, 186 typename UT2 = std::enable_if_t<std::is_enum<EnumTy2>::value, 187 std::underlying_type_t<EnumTy2>>> 188 constexpr auto addEnumValues(EnumTy1 LHS, EnumTy2 RHS) { 189 return static_cast<UT1>(LHS) + static_cast<UT2>(RHS); 190 } 191 192 //===----------------------------------------------------------------------===// 193 // Extra additions to <iterator> 194 //===----------------------------------------------------------------------===// 195 196 namespace callable_detail { 197 198 /// Templated storage wrapper for a callable. 199 /// 200 /// This class is consistently default constructible, copy / move 201 /// constructible / assignable. 202 /// 203 /// Supported callable types: 204 /// - Function pointer 205 /// - Function reference 206 /// - Lambda 207 /// - Function object 208 template <typename T, 209 bool = std::is_function_v<std::remove_pointer_t<remove_cvref_t<T>>>> 210 class Callable { 211 using value_type = std::remove_reference_t<T>; 212 using reference = value_type &; 213 using const_reference = value_type const &; 214 215 std::optional<value_type> Obj; 216 217 static_assert(!std::is_pointer_v<value_type>, 218 "Pointers to non-functions are not callable."); 219 220 public: 221 Callable() = default; 222 Callable(T const &O) : Obj(std::in_place, O) {} 223 224 Callable(Callable const &Other) = default; 225 Callable(Callable &&Other) = default; 226 227 Callable &operator=(Callable const &Other) { 228 Obj = std::nullopt; 229 if (Other.Obj) 230 Obj.emplace(*Other.Obj); 231 return *this; 232 } 233 234 Callable &operator=(Callable &&Other) { 235 Obj = std::nullopt; 236 if (Other.Obj) 237 Obj.emplace(std::move(*Other.Obj)); 238 return *this; 239 } 240 241 template <typename... Pn, 242 std::enable_if_t<std::is_invocable_v<T, Pn...>, int> = 0> 243 decltype(auto) operator()(Pn &&...Params) { 244 return (*Obj)(std::forward<Pn>(Params)...); 245 } 246 247 template <typename... Pn, 248 std::enable_if_t<std::is_invocable_v<T const, Pn...>, int> = 0> 249 decltype(auto) operator()(Pn &&...Params) const { 250 return (*Obj)(std::forward<Pn>(Params)...); 251 } 252 253 bool valid() const { return Obj != std::nullopt; } 254 bool reset() { return Obj = std::nullopt; } 255 256 operator reference() { return *Obj; } 257 operator const_reference() const { return *Obj; } 258 }; 259 260 // Function specialization. No need to waste extra space wrapping with a 261 // std::optional. 262 template <typename T> class Callable<T, true> { 263 static constexpr bool IsPtr = std::is_pointer_v<remove_cvref_t<T>>; 264 265 using StorageT = std::conditional_t<IsPtr, T, std::remove_reference_t<T> *>; 266 using CastT = std::conditional_t<IsPtr, T, T &>; 267 268 private: 269 StorageT Func = nullptr; 270 271 private: 272 template <typename In> static constexpr auto convertIn(In &&I) { 273 if constexpr (IsPtr) { 274 // Pointer... just echo it back. 275 return I; 276 } else { 277 // Must be a function reference. Return its address. 278 return &I; 279 } 280 } 281 282 public: 283 Callable() = default; 284 285 // Construct from a function pointer or reference. 286 // 287 // Disable this constructor for references to 'Callable' so we don't violate 288 // the rule of 0. 289 template < // clang-format off 290 typename FnPtrOrRef, 291 std::enable_if_t< 292 !std::is_same_v<remove_cvref_t<FnPtrOrRef>, Callable>, int 293 > = 0 294 > // clang-format on 295 Callable(FnPtrOrRef &&F) : Func(convertIn(F)) {} 296 297 template <typename... Pn, 298 std::enable_if_t<std::is_invocable_v<T, Pn...>, int> = 0> 299 decltype(auto) operator()(Pn &&...Params) const { 300 return Func(std::forward<Pn>(Params)...); 301 } 302 303 bool valid() const { return Func != nullptr; } 304 void reset() { Func = nullptr; } 305 306 operator T const &() const { 307 if constexpr (IsPtr) { 308 // T is a pointer... just echo it back. 309 return Func; 310 } else { 311 static_assert(std::is_reference_v<T>, 312 "Expected a reference to a function."); 313 // T is a function reference... dereference the stored pointer. 314 return *Func; 315 } 316 } 317 }; 318 319 } // namespace callable_detail 320 321 /// Returns true if the given container only contains a single element. 322 template <typename ContainerTy> bool hasSingleElement(ContainerTy &&C) { 323 auto B = adl_begin(C); 324 auto E = adl_end(C); 325 return B != E && std::next(B) == E; 326 } 327 328 /// Asserts that the given container has a single element and returns that 329 /// element. 330 template <typename ContainerTy> 331 decltype(auto) getSingleElement(ContainerTy &&C) { 332 assert(hasSingleElement(C) && "expected container with single element"); 333 return *adl_begin(C); 334 } 335 336 /// Return a range covering \p RangeOrContainer with the first N elements 337 /// excluded. 338 template <typename T> auto drop_begin(T &&RangeOrContainer, size_t N = 1) { 339 return make_range(std::next(adl_begin(RangeOrContainer), N), 340 adl_end(RangeOrContainer)); 341 } 342 343 /// Return a range covering \p RangeOrContainer with the last N elements 344 /// excluded. 345 template <typename T> auto drop_end(T &&RangeOrContainer, size_t N = 1) { 346 return make_range(adl_begin(RangeOrContainer), 347 std::prev(adl_end(RangeOrContainer), N)); 348 } 349 350 // mapped_iterator - This is a simple iterator adapter that causes a function to 351 // be applied whenever operator* is invoked on the iterator. 352 353 template <typename ItTy, typename FuncTy, 354 typename ReferenceTy = 355 decltype(std::declval<FuncTy>()(*std::declval<ItTy>()))> 356 class mapped_iterator 357 : public iterator_adaptor_base< 358 mapped_iterator<ItTy, FuncTy>, ItTy, 359 typename std::iterator_traits<ItTy>::iterator_category, 360 std::remove_reference_t<ReferenceTy>, 361 typename std::iterator_traits<ItTy>::difference_type, 362 std::remove_reference_t<ReferenceTy> *, ReferenceTy> { 363 public: 364 mapped_iterator() = default; 365 mapped_iterator(ItTy U, FuncTy F) 366 : mapped_iterator::iterator_adaptor_base(std::move(U)), F(std::move(F)) {} 367 368 ItTy getCurrent() { return this->I; } 369 370 const FuncTy &getFunction() const { return F; } 371 372 ReferenceTy operator*() const { return F(*this->I); } 373 374 private: 375 callable_detail::Callable<FuncTy> F{}; 376 }; 377 378 // map_iterator - Provide a convenient way to create mapped_iterators, just like 379 // make_pair is useful for creating pairs... 380 template <class ItTy, class FuncTy> 381 inline mapped_iterator<ItTy, FuncTy> map_iterator(ItTy I, FuncTy F) { 382 return mapped_iterator<ItTy, FuncTy>(std::move(I), std::move(F)); 383 } 384 385 template <class ContainerTy, class FuncTy> 386 auto map_range(ContainerTy &&C, FuncTy F) { 387 return make_range(map_iterator(adl_begin(C), F), map_iterator(adl_end(C), F)); 388 } 389 390 /// A base type of mapped iterator, that is useful for building derived 391 /// iterators that do not need/want to store the map function (as in 392 /// mapped_iterator). These iterators must simply provide a `mapElement` method 393 /// that defines how to map a value of the iterator to the provided reference 394 /// type. 395 template <typename DerivedT, typename ItTy, typename ReferenceTy> 396 class mapped_iterator_base 397 : public iterator_adaptor_base< 398 DerivedT, ItTy, 399 typename std::iterator_traits<ItTy>::iterator_category, 400 std::remove_reference_t<ReferenceTy>, 401 typename std::iterator_traits<ItTy>::difference_type, 402 std::remove_reference_t<ReferenceTy> *, ReferenceTy> { 403 public: 404 using BaseT = mapped_iterator_base; 405 406 mapped_iterator_base(ItTy U) 407 : mapped_iterator_base::iterator_adaptor_base(std::move(U)) {} 408 409 ItTy getCurrent() { return this->I; } 410 411 ReferenceTy operator*() const { 412 return static_cast<const DerivedT &>(*this).mapElement(*this->I); 413 } 414 }; 415 416 namespace detail { 417 template <typename Range> 418 using check_has_free_function_rbegin = 419 decltype(adl_rbegin(std::declval<Range &>())); 420 421 template <typename Range> 422 static constexpr bool HasFreeFunctionRBegin = 423 is_detected<check_has_free_function_rbegin, Range>::value; 424 } // namespace detail 425 426 // Returns an iterator_range over the given container which iterates in reverse. 427 // Does not mutate the container. 428 template <typename ContainerTy> [[nodiscard]] auto reverse(ContainerTy &&C) { 429 if constexpr (detail::HasFreeFunctionRBegin<ContainerTy>) 430 return make_range(adl_rbegin(C), adl_rend(C)); 431 else 432 return make_range(std::make_reverse_iterator(adl_end(C)), 433 std::make_reverse_iterator(adl_begin(C))); 434 } 435 436 /// An iterator adaptor that filters the elements of given inner iterators. 437 /// 438 /// The predicate parameter should be a callable object that accepts the wrapped 439 /// iterator's reference type and returns a bool. When incrementing or 440 /// decrementing the iterator, it will call the predicate on each element and 441 /// skip any where it returns false. 442 /// 443 /// \code 444 /// int A[] = { 1, 2, 3, 4 }; 445 /// auto R = make_filter_range(A, [](int N) { return N % 2 == 1; }); 446 /// // R contains { 1, 3 }. 447 /// \endcode 448 /// 449 /// Note: filter_iterator_base implements support for forward iteration. 450 /// filter_iterator_impl exists to provide support for bidirectional iteration, 451 /// conditional on whether the wrapped iterator supports it. 452 template <typename WrappedIteratorT, typename PredicateT, typename IterTag> 453 class filter_iterator_base 454 : public iterator_adaptor_base< 455 filter_iterator_base<WrappedIteratorT, PredicateT, IterTag>, 456 WrappedIteratorT, 457 std::common_type_t<IterTag, 458 typename std::iterator_traits< 459 WrappedIteratorT>::iterator_category>> { 460 using BaseT = typename filter_iterator_base::iterator_adaptor_base; 461 462 protected: 463 WrappedIteratorT End; 464 PredicateT Pred; 465 466 void findNextValid() { 467 while (this->I != End && !Pred(*this->I)) 468 BaseT::operator++(); 469 } 470 471 filter_iterator_base() = default; 472 473 // Construct the iterator. The begin iterator needs to know where the end 474 // is, so that it can properly stop when it gets there. The end iterator only 475 // needs the predicate to support bidirectional iteration. 476 filter_iterator_base(WrappedIteratorT Begin, WrappedIteratorT End, 477 PredicateT Pred) 478 : BaseT(Begin), End(End), Pred(Pred) { 479 findNextValid(); 480 } 481 482 public: 483 using BaseT::operator++; 484 485 filter_iterator_base &operator++() { 486 BaseT::operator++(); 487 findNextValid(); 488 return *this; 489 } 490 491 decltype(auto) operator*() const { 492 assert(BaseT::wrapped() != End && "Cannot dereference end iterator!"); 493 return BaseT::operator*(); 494 } 495 496 decltype(auto) operator->() const { 497 assert(BaseT::wrapped() != End && "Cannot dereference end iterator!"); 498 return BaseT::operator->(); 499 } 500 }; 501 502 /// Specialization of filter_iterator_base for forward iteration only. 503 template <typename WrappedIteratorT, typename PredicateT, 504 typename IterTag = std::forward_iterator_tag> 505 class filter_iterator_impl 506 : public filter_iterator_base<WrappedIteratorT, PredicateT, IterTag> { 507 public: 508 filter_iterator_impl() = default; 509 510 filter_iterator_impl(WrappedIteratorT Begin, WrappedIteratorT End, 511 PredicateT Pred) 512 : filter_iterator_impl::filter_iterator_base(Begin, End, Pred) {} 513 }; 514 515 /// Specialization of filter_iterator_base for bidirectional iteration. 516 template <typename WrappedIteratorT, typename PredicateT> 517 class filter_iterator_impl<WrappedIteratorT, PredicateT, 518 std::bidirectional_iterator_tag> 519 : public filter_iterator_base<WrappedIteratorT, PredicateT, 520 std::bidirectional_iterator_tag> { 521 using BaseT = typename filter_iterator_impl::filter_iterator_base; 522 523 void findPrevValid() { 524 while (!this->Pred(*this->I)) 525 BaseT::operator--(); 526 } 527 528 public: 529 using BaseT::operator--; 530 531 filter_iterator_impl() = default; 532 533 filter_iterator_impl(WrappedIteratorT Begin, WrappedIteratorT End, 534 PredicateT Pred) 535 : BaseT(Begin, End, Pred) {} 536 537 filter_iterator_impl &operator--() { 538 BaseT::operator--(); 539 findPrevValid(); 540 return *this; 541 } 542 }; 543 544 namespace detail { 545 546 template <bool is_bidirectional> struct fwd_or_bidi_tag_impl { 547 using type = std::forward_iterator_tag; 548 }; 549 550 template <> struct fwd_or_bidi_tag_impl<true> { 551 using type = std::bidirectional_iterator_tag; 552 }; 553 554 /// Helper which sets its type member to forward_iterator_tag if the category 555 /// of \p IterT does not derive from bidirectional_iterator_tag, and to 556 /// bidirectional_iterator_tag otherwise. 557 template <typename IterT> struct fwd_or_bidi_tag { 558 using type = typename fwd_or_bidi_tag_impl<std::is_base_of< 559 std::bidirectional_iterator_tag, 560 typename std::iterator_traits<IterT>::iterator_category>::value>::type; 561 }; 562 563 } // namespace detail 564 565 /// Defines filter_iterator to a suitable specialization of 566 /// filter_iterator_impl, based on the underlying iterator's category. 567 template <typename WrappedIteratorT, typename PredicateT> 568 using filter_iterator = filter_iterator_impl< 569 WrappedIteratorT, PredicateT, 570 typename detail::fwd_or_bidi_tag<WrappedIteratorT>::type>; 571 572 /// Convenience function that takes a range of elements and a predicate, 573 /// and return a new filter_iterator range. 574 /// 575 /// FIXME: Currently if RangeT && is a rvalue reference to a temporary, the 576 /// lifetime of that temporary is not kept by the returned range object, and the 577 /// temporary is going to be dropped on the floor after the make_iterator_range 578 /// full expression that contains this function call. 579 template <typename RangeT, typename PredicateT> 580 iterator_range<filter_iterator<detail::IterOfRange<RangeT>, PredicateT>> 581 make_filter_range(RangeT &&Range, PredicateT Pred) { 582 using FilterIteratorT = 583 filter_iterator<detail::IterOfRange<RangeT>, PredicateT>; 584 auto B = adl_begin(Range); 585 auto E = adl_end(Range); 586 return make_range(FilterIteratorT(B, E, Pred), FilterIteratorT(E, E, Pred)); 587 } 588 589 /// A pseudo-iterator adaptor that is designed to implement "early increment" 590 /// style loops. 591 /// 592 /// This is *not a normal iterator* and should almost never be used directly. It 593 /// is intended primarily to be used with range based for loops and some range 594 /// algorithms. 595 /// 596 /// The iterator isn't quite an `OutputIterator` or an `InputIterator` but 597 /// somewhere between them. The constraints of these iterators are: 598 /// 599 /// - On construction or after being incremented, it is comparable and 600 /// dereferencable. It is *not* incrementable. 601 /// - After being dereferenced, it is neither comparable nor dereferencable, it 602 /// is only incrementable. 603 /// 604 /// This means you can only dereference the iterator once, and you can only 605 /// increment it once between dereferences. 606 template <typename WrappedIteratorT> 607 class early_inc_iterator_impl 608 : public iterator_adaptor_base<early_inc_iterator_impl<WrappedIteratorT>, 609 WrappedIteratorT, std::input_iterator_tag> { 610 using BaseT = typename early_inc_iterator_impl::iterator_adaptor_base; 611 612 using PointerT = typename std::iterator_traits<WrappedIteratorT>::pointer; 613 614 protected: 615 #if LLVM_ENABLE_ABI_BREAKING_CHECKS 616 bool IsEarlyIncremented = false; 617 #endif 618 619 public: 620 early_inc_iterator_impl(WrappedIteratorT I) : BaseT(I) {} 621 622 using BaseT::operator*; 623 decltype(*std::declval<WrappedIteratorT>()) operator*() { 624 #if LLVM_ENABLE_ABI_BREAKING_CHECKS 625 assert(!IsEarlyIncremented && "Cannot dereference twice!"); 626 IsEarlyIncremented = true; 627 #endif 628 return *(this->I)++; 629 } 630 631 using BaseT::operator++; 632 early_inc_iterator_impl &operator++() { 633 #if LLVM_ENABLE_ABI_BREAKING_CHECKS 634 assert(IsEarlyIncremented && "Cannot increment before dereferencing!"); 635 IsEarlyIncremented = false; 636 #endif 637 return *this; 638 } 639 640 friend bool operator==(const early_inc_iterator_impl &LHS, 641 const early_inc_iterator_impl &RHS) { 642 #if LLVM_ENABLE_ABI_BREAKING_CHECKS 643 assert(!LHS.IsEarlyIncremented && "Cannot compare after dereferencing!"); 644 #endif 645 return (const BaseT &)LHS == (const BaseT &)RHS; 646 } 647 }; 648 649 /// Make a range that does early increment to allow mutation of the underlying 650 /// range without disrupting iteration. 651 /// 652 /// The underlying iterator will be incremented immediately after it is 653 /// dereferenced, allowing deletion of the current node or insertion of nodes to 654 /// not disrupt iteration provided they do not invalidate the *next* iterator -- 655 /// the current iterator can be invalidated. 656 /// 657 /// This requires a very exact pattern of use that is only really suitable to 658 /// range based for loops and other range algorithms that explicitly guarantee 659 /// to dereference exactly once each element, and to increment exactly once each 660 /// element. 661 template <typename RangeT> 662 iterator_range<early_inc_iterator_impl<detail::IterOfRange<RangeT>>> 663 make_early_inc_range(RangeT &&Range) { 664 using EarlyIncIteratorT = 665 early_inc_iterator_impl<detail::IterOfRange<RangeT>>; 666 return make_range(EarlyIncIteratorT(adl_begin(Range)), 667 EarlyIncIteratorT(adl_end(Range))); 668 } 669 670 // Forward declarations required by zip_shortest/zip_equal/zip_first/zip_longest 671 template <typename R, typename UnaryPredicate> 672 bool all_of(R &&range, UnaryPredicate P); 673 674 template <typename R, typename UnaryPredicate> 675 bool any_of(R &&range, UnaryPredicate P); 676 677 template <typename T> bool all_equal(std::initializer_list<T> Values); 678 679 template <typename R> constexpr size_t range_size(R &&Range); 680 681 namespace detail { 682 683 using std::declval; 684 685 // We have to alias this since inlining the actual type at the usage site 686 // in the parameter list of iterator_facade_base<> below ICEs MSVC 2017. 687 template<typename... Iters> struct ZipTupleType { 688 using type = std::tuple<decltype(*declval<Iters>())...>; 689 }; 690 691 template <typename ZipType, typename ReferenceTupleType, typename... Iters> 692 using zip_traits = iterator_facade_base< 693 ZipType, 694 std::common_type_t< 695 std::bidirectional_iterator_tag, 696 typename std::iterator_traits<Iters>::iterator_category...>, 697 // ^ TODO: Implement random access methods. 698 ReferenceTupleType, 699 typename std::iterator_traits< 700 std::tuple_element_t<0, std::tuple<Iters...>>>::difference_type, 701 // ^ FIXME: This follows boost::make_zip_iterator's assumption that all 702 // inner iterators have the same difference_type. It would fail if, for 703 // instance, the second field's difference_type were non-numeric while the 704 // first is. 705 ReferenceTupleType *, ReferenceTupleType>; 706 707 template <typename ZipType, typename ReferenceTupleType, typename... Iters> 708 struct zip_common : public zip_traits<ZipType, ReferenceTupleType, Iters...> { 709 using Base = zip_traits<ZipType, ReferenceTupleType, Iters...>; 710 using IndexSequence = std::index_sequence_for<Iters...>; 711 using value_type = typename Base::value_type; 712 713 std::tuple<Iters...> iterators; 714 715 protected: 716 template <size_t... Ns> value_type deref(std::index_sequence<Ns...>) const { 717 return value_type(*std::get<Ns>(iterators)...); 718 } 719 720 template <size_t... Ns> void tup_inc(std::index_sequence<Ns...>) { 721 (++std::get<Ns>(iterators), ...); 722 } 723 724 template <size_t... Ns> void tup_dec(std::index_sequence<Ns...>) { 725 (--std::get<Ns>(iterators), ...); 726 } 727 728 template <size_t... Ns> 729 bool test_all_equals(const zip_common &other, 730 std::index_sequence<Ns...>) const { 731 return ((std::get<Ns>(this->iterators) == std::get<Ns>(other.iterators)) && 732 ...); 733 } 734 735 public: 736 zip_common(Iters &&... ts) : iterators(std::forward<Iters>(ts)...) {} 737 738 value_type operator*() const { return deref(IndexSequence{}); } 739 740 ZipType &operator++() { 741 tup_inc(IndexSequence{}); 742 return static_cast<ZipType &>(*this); 743 } 744 745 ZipType &operator--() { 746 static_assert(Base::IsBidirectional, 747 "All inner iterators must be at least bidirectional."); 748 tup_dec(IndexSequence{}); 749 return static_cast<ZipType &>(*this); 750 } 751 752 /// Return true if all the iterator are matching `other`'s iterators. 753 bool all_equals(zip_common &other) { 754 return test_all_equals(other, IndexSequence{}); 755 } 756 }; 757 758 template <typename... Iters> 759 struct zip_first : zip_common<zip_first<Iters...>, 760 typename ZipTupleType<Iters...>::type, Iters...> { 761 using zip_common<zip_first, typename ZipTupleType<Iters...>::type, 762 Iters...>::zip_common; 763 764 bool operator==(const zip_first &other) const { 765 return std::get<0>(this->iterators) == std::get<0>(other.iterators); 766 } 767 }; 768 769 template <typename... Iters> 770 struct zip_shortest 771 : zip_common<zip_shortest<Iters...>, typename ZipTupleType<Iters...>::type, 772 Iters...> { 773 using zip_common<zip_shortest, typename ZipTupleType<Iters...>::type, 774 Iters...>::zip_common; 775 776 bool operator==(const zip_shortest &other) const { 777 return any_iterator_equals(other, std::index_sequence_for<Iters...>{}); 778 } 779 780 private: 781 template <size_t... Ns> 782 bool any_iterator_equals(const zip_shortest &other, 783 std::index_sequence<Ns...>) const { 784 return ((std::get<Ns>(this->iterators) == std::get<Ns>(other.iterators)) || 785 ...); 786 } 787 }; 788 789 /// Helper to obtain the iterator types for the tuple storage within `zippy`. 790 template <template <typename...> class ItType, typename TupleStorageType, 791 typename IndexSequence> 792 struct ZippyIteratorTuple; 793 794 /// Partial specialization for non-const tuple storage. 795 template <template <typename...> class ItType, typename... Args, 796 std::size_t... Ns> 797 struct ZippyIteratorTuple<ItType, std::tuple<Args...>, 798 std::index_sequence<Ns...>> { 799 using type = ItType<decltype(adl_begin( 800 std::get<Ns>(declval<std::tuple<Args...> &>())))...>; 801 }; 802 803 /// Partial specialization for const tuple storage. 804 template <template <typename...> class ItType, typename... Args, 805 std::size_t... Ns> 806 struct ZippyIteratorTuple<ItType, const std::tuple<Args...>, 807 std::index_sequence<Ns...>> { 808 using type = ItType<decltype(adl_begin( 809 std::get<Ns>(declval<const std::tuple<Args...> &>())))...>; 810 }; 811 812 template <template <typename...> class ItType, typename... Args> class zippy { 813 private: 814 std::tuple<Args...> storage; 815 using IndexSequence = std::index_sequence_for<Args...>; 816 817 public: 818 using iterator = typename ZippyIteratorTuple<ItType, decltype(storage), 819 IndexSequence>::type; 820 using const_iterator = 821 typename ZippyIteratorTuple<ItType, const decltype(storage), 822 IndexSequence>::type; 823 using iterator_category = typename iterator::iterator_category; 824 using value_type = typename iterator::value_type; 825 using difference_type = typename iterator::difference_type; 826 using pointer = typename iterator::pointer; 827 using reference = typename iterator::reference; 828 using const_reference = typename const_iterator::reference; 829 830 zippy(Args &&...args) : storage(std::forward<Args>(args)...) {} 831 832 const_iterator begin() const { return begin_impl(IndexSequence{}); } 833 iterator begin() { return begin_impl(IndexSequence{}); } 834 const_iterator end() const { return end_impl(IndexSequence{}); } 835 iterator end() { return end_impl(IndexSequence{}); } 836 837 private: 838 template <size_t... Ns> 839 const_iterator begin_impl(std::index_sequence<Ns...>) const { 840 return const_iterator(adl_begin(std::get<Ns>(storage))...); 841 } 842 template <size_t... Ns> iterator begin_impl(std::index_sequence<Ns...>) { 843 return iterator(adl_begin(std::get<Ns>(storage))...); 844 } 845 846 template <size_t... Ns> 847 const_iterator end_impl(std::index_sequence<Ns...>) const { 848 return const_iterator(adl_end(std::get<Ns>(storage))...); 849 } 850 template <size_t... Ns> iterator end_impl(std::index_sequence<Ns...>) { 851 return iterator(adl_end(std::get<Ns>(storage))...); 852 } 853 }; 854 855 } // end namespace detail 856 857 /// zip iterator for two or more iteratable types. Iteration continues until the 858 /// end of the *shortest* iteratee is reached. 859 template <typename T, typename U, typename... Args> 860 detail::zippy<detail::zip_shortest, T, U, Args...> zip(T &&t, U &&u, 861 Args &&...args) { 862 return detail::zippy<detail::zip_shortest, T, U, Args...>( 863 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...); 864 } 865 866 /// zip iterator that assumes that all iteratees have the same length. 867 /// In builds with assertions on, this assumption is checked before the 868 /// iteration starts. 869 template <typename T, typename U, typename... Args> 870 detail::zippy<detail::zip_first, T, U, Args...> zip_equal(T &&t, U &&u, 871 Args &&...args) { 872 assert(all_equal({range_size(t), range_size(u), range_size(args)...}) && 873 "Iteratees do not have equal length"); 874 return detail::zippy<detail::zip_first, T, U, Args...>( 875 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...); 876 } 877 878 /// zip iterator that, for the sake of efficiency, assumes the first iteratee to 879 /// be the shortest. Iteration continues until the end of the first iteratee is 880 /// reached. In builds with assertions on, we check that the assumption about 881 /// the first iteratee being the shortest holds. 882 template <typename T, typename U, typename... Args> 883 detail::zippy<detail::zip_first, T, U, Args...> zip_first(T &&t, U &&u, 884 Args &&...args) { 885 assert(range_size(t) <= std::min({range_size(u), range_size(args)...}) && 886 "First iteratee is not the shortest"); 887 888 return detail::zippy<detail::zip_first, T, U, Args...>( 889 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...); 890 } 891 892 namespace detail { 893 template <typename Iter> 894 Iter next_or_end(const Iter &I, const Iter &End) { 895 if (I == End) 896 return End; 897 return std::next(I); 898 } 899 900 template <typename Iter> 901 auto deref_or_none(const Iter &I, const Iter &End) -> std::optional< 902 std::remove_const_t<std::remove_reference_t<decltype(*I)>>> { 903 if (I == End) 904 return std::nullopt; 905 return *I; 906 } 907 908 template <typename Iter> struct ZipLongestItemType { 909 using type = std::optional<std::remove_const_t< 910 std::remove_reference_t<decltype(*std::declval<Iter>())>>>; 911 }; 912 913 template <typename... Iters> struct ZipLongestTupleType { 914 using type = std::tuple<typename ZipLongestItemType<Iters>::type...>; 915 }; 916 917 template <typename... Iters> 918 class zip_longest_iterator 919 : public iterator_facade_base< 920 zip_longest_iterator<Iters...>, 921 std::common_type_t< 922 std::forward_iterator_tag, 923 typename std::iterator_traits<Iters>::iterator_category...>, 924 typename ZipLongestTupleType<Iters...>::type, 925 typename std::iterator_traits< 926 std::tuple_element_t<0, std::tuple<Iters...>>>::difference_type, 927 typename ZipLongestTupleType<Iters...>::type *, 928 typename ZipLongestTupleType<Iters...>::type> { 929 public: 930 using value_type = typename ZipLongestTupleType<Iters...>::type; 931 932 private: 933 std::tuple<Iters...> iterators; 934 std::tuple<Iters...> end_iterators; 935 936 template <size_t... Ns> 937 bool test(const zip_longest_iterator<Iters...> &other, 938 std::index_sequence<Ns...>) const { 939 return ((std::get<Ns>(this->iterators) != std::get<Ns>(other.iterators)) || 940 ...); 941 } 942 943 template <size_t... Ns> value_type deref(std::index_sequence<Ns...>) const { 944 return value_type( 945 deref_or_none(std::get<Ns>(iterators), std::get<Ns>(end_iterators))...); 946 } 947 948 template <size_t... Ns> 949 decltype(iterators) tup_inc(std::index_sequence<Ns...>) const { 950 return std::tuple<Iters...>( 951 next_or_end(std::get<Ns>(iterators), std::get<Ns>(end_iterators))...); 952 } 953 954 public: 955 zip_longest_iterator(std::pair<Iters &&, Iters &&>... ts) 956 : iterators(std::forward<Iters>(ts.first)...), 957 end_iterators(std::forward<Iters>(ts.second)...) {} 958 959 value_type operator*() const { 960 return deref(std::index_sequence_for<Iters...>{}); 961 } 962 963 zip_longest_iterator<Iters...> &operator++() { 964 iterators = tup_inc(std::index_sequence_for<Iters...>{}); 965 return *this; 966 } 967 968 bool operator==(const zip_longest_iterator<Iters...> &other) const { 969 return !test(other, std::index_sequence_for<Iters...>{}); 970 } 971 }; 972 973 template <typename... Args> class zip_longest_range { 974 public: 975 using iterator = 976 zip_longest_iterator<decltype(adl_begin(std::declval<Args>()))...>; 977 using iterator_category = typename iterator::iterator_category; 978 using value_type = typename iterator::value_type; 979 using difference_type = typename iterator::difference_type; 980 using pointer = typename iterator::pointer; 981 using reference = typename iterator::reference; 982 983 private: 984 std::tuple<Args...> ts; 985 986 template <size_t... Ns> 987 iterator begin_impl(std::index_sequence<Ns...>) const { 988 return iterator(std::make_pair(adl_begin(std::get<Ns>(ts)), 989 adl_end(std::get<Ns>(ts)))...); 990 } 991 992 template <size_t... Ns> iterator end_impl(std::index_sequence<Ns...>) const { 993 return iterator(std::make_pair(adl_end(std::get<Ns>(ts)), 994 adl_end(std::get<Ns>(ts)))...); 995 } 996 997 public: 998 zip_longest_range(Args &&... ts_) : ts(std::forward<Args>(ts_)...) {} 999 1000 iterator begin() const { 1001 return begin_impl(std::index_sequence_for<Args...>{}); 1002 } 1003 iterator end() const { return end_impl(std::index_sequence_for<Args...>{}); } 1004 }; 1005 } // namespace detail 1006 1007 /// Iterate over two or more iterators at the same time. Iteration continues 1008 /// until all iterators reach the end. The std::optional only contains a value 1009 /// if the iterator has not reached the end. 1010 template <typename T, typename U, typename... Args> 1011 detail::zip_longest_range<T, U, Args...> zip_longest(T &&t, U &&u, 1012 Args &&... args) { 1013 return detail::zip_longest_range<T, U, Args...>( 1014 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...); 1015 } 1016 1017 /// Iterator wrapper that concatenates sequences together. 1018 /// 1019 /// This can concatenate different iterators, even with different types, into 1020 /// a single iterator provided the value types of all the concatenated 1021 /// iterators expose `reference` and `pointer` types that can be converted to 1022 /// `ValueT &` and `ValueT *` respectively. It doesn't support more 1023 /// interesting/customized pointer or reference types. 1024 /// 1025 /// Currently this only supports forward or higher iterator categories as 1026 /// inputs and always exposes a forward iterator interface. 1027 template <typename ValueT, typename... IterTs> 1028 class concat_iterator 1029 : public iterator_facade_base<concat_iterator<ValueT, IterTs...>, 1030 std::forward_iterator_tag, ValueT> { 1031 using BaseT = typename concat_iterator::iterator_facade_base; 1032 1033 static constexpr bool ReturnsByValue = 1034 !(std::is_reference_v<decltype(*std::declval<IterTs>())> && ...); 1035 1036 using reference_type = 1037 typename std::conditional_t<ReturnsByValue, ValueT, ValueT &>; 1038 1039 using handle_type = 1040 typename std::conditional_t<ReturnsByValue, std::optional<ValueT>, 1041 ValueT *>; 1042 1043 /// We store both the current and end iterators for each concatenated 1044 /// sequence in a tuple of pairs. 1045 /// 1046 /// Note that something like iterator_range seems nice at first here, but the 1047 /// range properties are of little benefit and end up getting in the way 1048 /// because we need to do mutation on the current iterators. 1049 std::tuple<IterTs...> Begins; 1050 std::tuple<IterTs...> Ends; 1051 1052 /// Attempts to increment a specific iterator. 1053 /// 1054 /// Returns true if it was able to increment the iterator. Returns false if 1055 /// the iterator is already at the end iterator. 1056 template <size_t Index> bool incrementHelper() { 1057 auto &Begin = std::get<Index>(Begins); 1058 auto &End = std::get<Index>(Ends); 1059 if (Begin == End) 1060 return false; 1061 1062 ++Begin; 1063 return true; 1064 } 1065 1066 /// Increments the first non-end iterator. 1067 /// 1068 /// It is an error to call this with all iterators at the end. 1069 template <size_t... Ns> void increment(std::index_sequence<Ns...>) { 1070 // Build a sequence of functions to increment each iterator if possible. 1071 bool (concat_iterator::*IncrementHelperFns[])() = { 1072 &concat_iterator::incrementHelper<Ns>...}; 1073 1074 // Loop over them, and stop as soon as we succeed at incrementing one. 1075 for (auto &IncrementHelperFn : IncrementHelperFns) 1076 if ((this->*IncrementHelperFn)()) 1077 return; 1078 1079 llvm_unreachable("Attempted to increment an end concat iterator!"); 1080 } 1081 1082 /// Returns null if the specified iterator is at the end. Otherwise, 1083 /// dereferences the iterator and returns the address of the resulting 1084 /// reference. 1085 template <size_t Index> handle_type getHelper() const { 1086 auto &Begin = std::get<Index>(Begins); 1087 auto &End = std::get<Index>(Ends); 1088 if (Begin == End) 1089 return {}; 1090 1091 if constexpr (ReturnsByValue) 1092 return *Begin; 1093 else 1094 return &*Begin; 1095 } 1096 1097 /// Finds the first non-end iterator, dereferences, and returns the resulting 1098 /// reference. 1099 /// 1100 /// It is an error to call this with all iterators at the end. 1101 template <size_t... Ns> reference_type get(std::index_sequence<Ns...>) const { 1102 // Build a sequence of functions to get from iterator if possible. 1103 handle_type (concat_iterator::*GetHelperFns[])() 1104 const = {&concat_iterator::getHelper<Ns>...}; 1105 1106 // Loop over them, and return the first result we find. 1107 for (auto &GetHelperFn : GetHelperFns) 1108 if (auto P = (this->*GetHelperFn)()) 1109 return *P; 1110 1111 llvm_unreachable("Attempted to get a pointer from an end concat iterator!"); 1112 } 1113 1114 public: 1115 /// Constructs an iterator from a sequence of ranges. 1116 /// 1117 /// We need the full range to know how to switch between each of the 1118 /// iterators. 1119 template <typename... RangeTs> 1120 explicit concat_iterator(RangeTs &&...Ranges) 1121 : Begins(adl_begin(Ranges)...), Ends(adl_end(Ranges)...) {} 1122 1123 using BaseT::operator++; 1124 1125 concat_iterator &operator++() { 1126 increment(std::index_sequence_for<IterTs...>()); 1127 return *this; 1128 } 1129 1130 reference_type operator*() const { 1131 return get(std::index_sequence_for<IterTs...>()); 1132 } 1133 1134 bool operator==(const concat_iterator &RHS) const { 1135 return Begins == RHS.Begins && Ends == RHS.Ends; 1136 } 1137 }; 1138 1139 namespace detail { 1140 1141 /// Helper to store a sequence of ranges being concatenated and access them. 1142 /// 1143 /// This is designed to facilitate providing actual storage when temporaries 1144 /// are passed into the constructor such that we can use it as part of range 1145 /// based for loops. 1146 template <typename ValueT, typename... RangeTs> class concat_range { 1147 public: 1148 using iterator = 1149 concat_iterator<ValueT, 1150 decltype(adl_begin(std::declval<RangeTs &>()))...>; 1151 1152 private: 1153 std::tuple<RangeTs...> Ranges; 1154 1155 template <size_t... Ns> iterator begin_impl(std::index_sequence<Ns...>) { 1156 return iterator(std::get<Ns>(Ranges)...); 1157 } 1158 template <size_t... Ns> 1159 iterator begin_impl(std::index_sequence<Ns...>) const { 1160 return iterator(std::get<Ns>(Ranges)...); 1161 } 1162 template <size_t... Ns> iterator end_impl(std::index_sequence<Ns...>) { 1163 return iterator(make_range(adl_end(std::get<Ns>(Ranges)), 1164 adl_end(std::get<Ns>(Ranges)))...); 1165 } 1166 template <size_t... Ns> iterator end_impl(std::index_sequence<Ns...>) const { 1167 return iterator(make_range(adl_end(std::get<Ns>(Ranges)), 1168 adl_end(std::get<Ns>(Ranges)))...); 1169 } 1170 1171 public: 1172 concat_range(RangeTs &&... Ranges) 1173 : Ranges(std::forward<RangeTs>(Ranges)...) {} 1174 1175 iterator begin() { 1176 return begin_impl(std::index_sequence_for<RangeTs...>{}); 1177 } 1178 iterator begin() const { 1179 return begin_impl(std::index_sequence_for<RangeTs...>{}); 1180 } 1181 iterator end() { 1182 return end_impl(std::index_sequence_for<RangeTs...>{}); 1183 } 1184 iterator end() const { 1185 return end_impl(std::index_sequence_for<RangeTs...>{}); 1186 } 1187 }; 1188 1189 } // end namespace detail 1190 1191 /// Returns a concatenated range across two or more ranges. Does not modify the 1192 /// ranges. 1193 /// 1194 /// The desired value type must be explicitly specified. 1195 template <typename ValueT, typename... RangeTs> 1196 [[nodiscard]] detail::concat_range<ValueT, RangeTs...> 1197 concat(RangeTs &&...Ranges) { 1198 static_assert(sizeof...(RangeTs) > 1, 1199 "Need more than one range to concatenate!"); 1200 return detail::concat_range<ValueT, RangeTs...>( 1201 std::forward<RangeTs>(Ranges)...); 1202 } 1203 1204 /// A utility class used to implement an iterator that contains some base object 1205 /// and an index. The iterator moves the index but keeps the base constant. 1206 template <typename DerivedT, typename BaseT, typename T, 1207 typename PointerT = T *, typename ReferenceT = T &> 1208 class indexed_accessor_iterator 1209 : public llvm::iterator_facade_base<DerivedT, 1210 std::random_access_iterator_tag, T, 1211 std::ptrdiff_t, PointerT, ReferenceT> { 1212 public: 1213 ptrdiff_t operator-(const indexed_accessor_iterator &rhs) const { 1214 assert(base == rhs.base && "incompatible iterators"); 1215 return index - rhs.index; 1216 } 1217 bool operator==(const indexed_accessor_iterator &rhs) const { 1218 assert(base == rhs.base && "incompatible iterators"); 1219 return index == rhs.index; 1220 } 1221 bool operator<(const indexed_accessor_iterator &rhs) const { 1222 assert(base == rhs.base && "incompatible iterators"); 1223 return index < rhs.index; 1224 } 1225 1226 DerivedT &operator+=(ptrdiff_t offset) { 1227 this->index += offset; 1228 return static_cast<DerivedT &>(*this); 1229 } 1230 DerivedT &operator-=(ptrdiff_t offset) { 1231 this->index -= offset; 1232 return static_cast<DerivedT &>(*this); 1233 } 1234 1235 /// Returns the current index of the iterator. 1236 ptrdiff_t getIndex() const { return index; } 1237 1238 /// Returns the current base of the iterator. 1239 const BaseT &getBase() const { return base; } 1240 1241 protected: 1242 indexed_accessor_iterator(BaseT base, ptrdiff_t index) 1243 : base(base), index(index) {} 1244 BaseT base; 1245 ptrdiff_t index; 1246 }; 1247 1248 namespace detail { 1249 /// The class represents the base of a range of indexed_accessor_iterators. It 1250 /// provides support for many different range functionalities, e.g. 1251 /// drop_front/slice/etc.. Derived range classes must implement the following 1252 /// static methods: 1253 /// * ReferenceT dereference_iterator(const BaseT &base, ptrdiff_t index) 1254 /// - Dereference an iterator pointing to the base object at the given 1255 /// index. 1256 /// * BaseT offset_base(const BaseT &base, ptrdiff_t index) 1257 /// - Return a new base that is offset from the provide base by 'index' 1258 /// elements. 1259 template <typename DerivedT, typename BaseT, typename T, 1260 typename PointerT = T *, typename ReferenceT = T &> 1261 class indexed_accessor_range_base { 1262 public: 1263 using RangeBaseT = indexed_accessor_range_base; 1264 1265 /// An iterator element of this range. 1266 class iterator : public indexed_accessor_iterator<iterator, BaseT, T, 1267 PointerT, ReferenceT> { 1268 public: 1269 // Index into this iterator, invoking a static method on the derived type. 1270 ReferenceT operator*() const { 1271 return DerivedT::dereference_iterator(this->getBase(), this->getIndex()); 1272 } 1273 1274 private: 1275 iterator(BaseT owner, ptrdiff_t curIndex) 1276 : iterator::indexed_accessor_iterator(owner, curIndex) {} 1277 1278 /// Allow access to the constructor. 1279 friend indexed_accessor_range_base<DerivedT, BaseT, T, PointerT, 1280 ReferenceT>; 1281 }; 1282 1283 indexed_accessor_range_base(iterator begin, iterator end) 1284 : base(offset_base(begin.getBase(), begin.getIndex())), 1285 count(end.getIndex() - begin.getIndex()) {} 1286 indexed_accessor_range_base(const iterator_range<iterator> &range) 1287 : indexed_accessor_range_base(range.begin(), range.end()) {} 1288 indexed_accessor_range_base(BaseT base, ptrdiff_t count) 1289 : base(base), count(count) {} 1290 1291 iterator begin() const { return iterator(base, 0); } 1292 iterator end() const { return iterator(base, count); } 1293 ReferenceT operator[](size_t Index) const { 1294 assert(Index < size() && "invalid index for value range"); 1295 return DerivedT::dereference_iterator(base, static_cast<ptrdiff_t>(Index)); 1296 } 1297 ReferenceT front() const { 1298 assert(!empty() && "expected non-empty range"); 1299 return (*this)[0]; 1300 } 1301 ReferenceT back() const { 1302 assert(!empty() && "expected non-empty range"); 1303 return (*this)[size() - 1]; 1304 } 1305 1306 /// Return the size of this range. 1307 size_t size() const { return count; } 1308 1309 /// Return if the range is empty. 1310 bool empty() const { return size() == 0; } 1311 1312 /// Drop the first N elements, and keep M elements. 1313 DerivedT slice(size_t n, size_t m) const { 1314 assert(n + m <= size() && "invalid size specifiers"); 1315 return DerivedT(offset_base(base, n), m); 1316 } 1317 1318 /// Drop the first n elements. 1319 DerivedT drop_front(size_t n = 1) const { 1320 assert(size() >= n && "Dropping more elements than exist"); 1321 return slice(n, size() - n); 1322 } 1323 /// Drop the last n elements. 1324 DerivedT drop_back(size_t n = 1) const { 1325 assert(size() >= n && "Dropping more elements than exist"); 1326 return DerivedT(base, size() - n); 1327 } 1328 1329 /// Take the first n elements. 1330 DerivedT take_front(size_t n = 1) const { 1331 return n < size() ? drop_back(size() - n) 1332 : static_cast<const DerivedT &>(*this); 1333 } 1334 1335 /// Take the last n elements. 1336 DerivedT take_back(size_t n = 1) const { 1337 return n < size() ? drop_front(size() - n) 1338 : static_cast<const DerivedT &>(*this); 1339 } 1340 1341 /// Allow conversion to any type accepting an iterator_range. 1342 template <typename RangeT, typename = std::enable_if_t<std::is_constructible< 1343 RangeT, iterator_range<iterator>>::value>> 1344 operator RangeT() const { 1345 return RangeT(iterator_range<iterator>(*this)); 1346 } 1347 1348 /// Returns the base of this range. 1349 const BaseT &getBase() const { return base; } 1350 1351 private: 1352 /// Offset the given base by the given amount. 1353 static BaseT offset_base(const BaseT &base, size_t n) { 1354 return n == 0 ? base : DerivedT::offset_base(base, n); 1355 } 1356 1357 protected: 1358 indexed_accessor_range_base(const indexed_accessor_range_base &) = default; 1359 indexed_accessor_range_base(indexed_accessor_range_base &&) = default; 1360 indexed_accessor_range_base & 1361 operator=(const indexed_accessor_range_base &) = default; 1362 1363 /// The base that owns the provided range of values. 1364 BaseT base; 1365 /// The size from the owning range. 1366 ptrdiff_t count; 1367 }; 1368 /// Compare this range with another. 1369 /// FIXME: Make me a member function instead of friend when it works in C++20. 1370 template <typename OtherT, typename DerivedT, typename BaseT, typename T, 1371 typename PointerT, typename ReferenceT> 1372 bool operator==(const indexed_accessor_range_base<DerivedT, BaseT, T, PointerT, 1373 ReferenceT> &lhs, 1374 const OtherT &rhs) { 1375 return std::equal(lhs.begin(), lhs.end(), rhs.begin(), rhs.end()); 1376 } 1377 1378 template <typename OtherT, typename DerivedT, typename BaseT, typename T, 1379 typename PointerT, typename ReferenceT> 1380 bool operator!=(const indexed_accessor_range_base<DerivedT, BaseT, T, PointerT, 1381 ReferenceT> &lhs, 1382 const OtherT &rhs) { 1383 return !(lhs == rhs); 1384 } 1385 } // end namespace detail 1386 1387 /// This class provides an implementation of a range of 1388 /// indexed_accessor_iterators where the base is not indexable. Ranges with 1389 /// bases that are offsetable should derive from indexed_accessor_range_base 1390 /// instead. Derived range classes are expected to implement the following 1391 /// static method: 1392 /// * ReferenceT dereference(const BaseT &base, ptrdiff_t index) 1393 /// - Dereference an iterator pointing to a parent base at the given index. 1394 template <typename DerivedT, typename BaseT, typename T, 1395 typename PointerT = T *, typename ReferenceT = T &> 1396 class indexed_accessor_range 1397 : public detail::indexed_accessor_range_base< 1398 DerivedT, std::pair<BaseT, ptrdiff_t>, T, PointerT, ReferenceT> { 1399 public: 1400 indexed_accessor_range(BaseT base, ptrdiff_t startIndex, ptrdiff_t count) 1401 : detail::indexed_accessor_range_base< 1402 DerivedT, std::pair<BaseT, ptrdiff_t>, T, PointerT, ReferenceT>( 1403 std::make_pair(base, startIndex), count) {} 1404 using detail::indexed_accessor_range_base< 1405 DerivedT, std::pair<BaseT, ptrdiff_t>, T, PointerT, 1406 ReferenceT>::indexed_accessor_range_base; 1407 1408 /// Returns the current base of the range. 1409 const BaseT &getBase() const { return this->base.first; } 1410 1411 /// Returns the current start index of the range. 1412 ptrdiff_t getStartIndex() const { return this->base.second; } 1413 1414 /// See `detail::indexed_accessor_range_base` for details. 1415 static std::pair<BaseT, ptrdiff_t> 1416 offset_base(const std::pair<BaseT, ptrdiff_t> &base, ptrdiff_t index) { 1417 // We encode the internal base as a pair of the derived base and a start 1418 // index into the derived base. 1419 return std::make_pair(base.first, base.second + index); 1420 } 1421 /// See `detail::indexed_accessor_range_base` for details. 1422 static ReferenceT 1423 dereference_iterator(const std::pair<BaseT, ptrdiff_t> &base, 1424 ptrdiff_t index) { 1425 return DerivedT::dereference(base.first, base.second + index); 1426 } 1427 }; 1428 1429 namespace detail { 1430 /// Return a reference to the first or second member of a reference. Otherwise, 1431 /// return a copy of the member of a temporary. 1432 /// 1433 /// When passing a range whose iterators return values instead of references, 1434 /// the reference must be dropped from `decltype((elt.first))`, which will 1435 /// always be a reference, to avoid returning a reference to a temporary. 1436 template <typename EltTy, typename FirstTy> class first_or_second_type { 1437 public: 1438 using type = std::conditional_t<std::is_reference<EltTy>::value, FirstTy, 1439 std::remove_reference_t<FirstTy>>; 1440 }; 1441 } // end namespace detail 1442 1443 /// Given a container of pairs, return a range over the first elements. 1444 template <typename ContainerTy> auto make_first_range(ContainerTy &&c) { 1445 using EltTy = decltype(*adl_begin(c)); 1446 return llvm::map_range(std::forward<ContainerTy>(c), 1447 [](EltTy elt) -> typename detail::first_or_second_type< 1448 EltTy, decltype((elt.first))>::type { 1449 return elt.first; 1450 }); 1451 } 1452 1453 /// Given a container of pairs, return a range over the second elements. 1454 template <typename ContainerTy> auto make_second_range(ContainerTy &&c) { 1455 using EltTy = decltype(*adl_begin(c)); 1456 return llvm::map_range( 1457 std::forward<ContainerTy>(c), 1458 [](EltTy elt) -> 1459 typename detail::first_or_second_type<EltTy, 1460 decltype((elt.second))>::type { 1461 return elt.second; 1462 }); 1463 } 1464 1465 //===----------------------------------------------------------------------===// 1466 // Extra additions to <utility> 1467 //===----------------------------------------------------------------------===// 1468 1469 /// Function object to check whether the first component of a container 1470 /// supported by std::get (like std::pair and std::tuple) compares less than the 1471 /// first component of another container. 1472 struct less_first { 1473 template <typename T> bool operator()(const T &lhs, const T &rhs) const { 1474 return std::less<>()(std::get<0>(lhs), std::get<0>(rhs)); 1475 } 1476 }; 1477 1478 /// Function object to check whether the second component of a container 1479 /// supported by std::get (like std::pair and std::tuple) compares less than the 1480 /// second component of another container. 1481 struct less_second { 1482 template <typename T> bool operator()(const T &lhs, const T &rhs) const { 1483 return std::less<>()(std::get<1>(lhs), std::get<1>(rhs)); 1484 } 1485 }; 1486 1487 /// \brief Function object to apply a binary function to the first component of 1488 /// a std::pair. 1489 template<typename FuncTy> 1490 struct on_first { 1491 FuncTy func; 1492 1493 template <typename T> 1494 decltype(auto) operator()(const T &lhs, const T &rhs) const { 1495 return func(lhs.first, rhs.first); 1496 } 1497 }; 1498 1499 /// Utility type to build an inheritance chain that makes it easy to rank 1500 /// overload candidates. 1501 template <int N> struct rank : rank<N - 1> {}; 1502 template <> struct rank<0> {}; 1503 1504 namespace detail { 1505 template <typename... Ts> struct Visitor; 1506 1507 template <typename HeadT, typename... TailTs> 1508 struct Visitor<HeadT, TailTs...> : remove_cvref_t<HeadT>, Visitor<TailTs...> { 1509 explicit constexpr Visitor(HeadT &&Head, TailTs &&...Tail) 1510 : remove_cvref_t<HeadT>(std::forward<HeadT>(Head)), 1511 Visitor<TailTs...>(std::forward<TailTs>(Tail)...) {} 1512 using remove_cvref_t<HeadT>::operator(); 1513 using Visitor<TailTs...>::operator(); 1514 }; 1515 1516 template <typename HeadT> struct Visitor<HeadT> : remove_cvref_t<HeadT> { 1517 explicit constexpr Visitor(HeadT &&Head) 1518 : remove_cvref_t<HeadT>(std::forward<HeadT>(Head)) {} 1519 using remove_cvref_t<HeadT>::operator(); 1520 }; 1521 } // namespace detail 1522 1523 /// Returns an opaquely-typed Callable object whose operator() overload set is 1524 /// the sum of the operator() overload sets of each CallableT in CallableTs. 1525 /// 1526 /// The type of the returned object derives from each CallableT in CallableTs. 1527 /// The returned object is constructed by invoking the appropriate copy or move 1528 /// constructor of each CallableT, as selected by overload resolution on the 1529 /// corresponding argument to makeVisitor. 1530 /// 1531 /// Example: 1532 /// 1533 /// \code 1534 /// auto visitor = makeVisitor([](auto) { return "unhandled type"; }, 1535 /// [](int i) { return "int"; }, 1536 /// [](std::string s) { return "str"; }); 1537 /// auto a = visitor(42); // `a` is now "int". 1538 /// auto b = visitor("foo"); // `b` is now "str". 1539 /// auto c = visitor(3.14f); // `c` is now "unhandled type". 1540 /// \endcode 1541 /// 1542 /// Example of making a visitor with a lambda which captures a move-only type: 1543 /// 1544 /// \code 1545 /// std::unique_ptr<FooHandler> FH = /* ... */; 1546 /// auto visitor = makeVisitor( 1547 /// [FH{std::move(FH)}](Foo F) { return FH->handle(F); }, 1548 /// [](int i) { return i; }, 1549 /// [](std::string s) { return atoi(s); }); 1550 /// \endcode 1551 template <typename... CallableTs> 1552 constexpr decltype(auto) makeVisitor(CallableTs &&...Callables) { 1553 return detail::Visitor<CallableTs...>(std::forward<CallableTs>(Callables)...); 1554 } 1555 1556 //===----------------------------------------------------------------------===// 1557 // Extra additions to <algorithm> 1558 //===----------------------------------------------------------------------===// 1559 1560 // We have a copy here so that LLVM behaves the same when using different 1561 // standard libraries. 1562 template <class Iterator, class RNG> 1563 void shuffle(Iterator first, Iterator last, RNG &&g) { 1564 // It would be better to use a std::uniform_int_distribution, 1565 // but that would be stdlib dependent. 1566 typedef 1567 typename std::iterator_traits<Iterator>::difference_type difference_type; 1568 for (auto size = last - first; size > 1; ++first, (void)--size) { 1569 difference_type offset = g() % size; 1570 // Avoid self-assignment due to incorrect assertions in libstdc++ 1571 // containers (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85828). 1572 if (offset != difference_type(0)) 1573 std::iter_swap(first, first + offset); 1574 } 1575 } 1576 1577 /// Adapt std::less<T> for array_pod_sort. 1578 template<typename T> 1579 inline int array_pod_sort_comparator(const void *P1, const void *P2) { 1580 if (std::less<T>()(*reinterpret_cast<const T*>(P1), 1581 *reinterpret_cast<const T*>(P2))) 1582 return -1; 1583 if (std::less<T>()(*reinterpret_cast<const T*>(P2), 1584 *reinterpret_cast<const T*>(P1))) 1585 return 1; 1586 return 0; 1587 } 1588 1589 /// get_array_pod_sort_comparator - This is an internal helper function used to 1590 /// get type deduction of T right. 1591 template<typename T> 1592 inline int (*get_array_pod_sort_comparator(const T &)) 1593 (const void*, const void*) { 1594 return array_pod_sort_comparator<T>; 1595 } 1596 1597 #ifdef EXPENSIVE_CHECKS 1598 namespace detail { 1599 1600 inline unsigned presortShuffleEntropy() { 1601 static unsigned Result(std::random_device{}()); 1602 return Result; 1603 } 1604 1605 template <class IteratorTy> 1606 inline void presortShuffle(IteratorTy Start, IteratorTy End) { 1607 std::mt19937 Generator(presortShuffleEntropy()); 1608 llvm::shuffle(Start, End, Generator); 1609 } 1610 1611 } // end namespace detail 1612 #endif 1613 1614 /// array_pod_sort - This sorts an array with the specified start and end 1615 /// extent. This is just like std::sort, except that it calls qsort instead of 1616 /// using an inlined template. qsort is slightly slower than std::sort, but 1617 /// most sorts are not performance critical in LLVM and std::sort has to be 1618 /// template instantiated for each type, leading to significant measured code 1619 /// bloat. This function should generally be used instead of std::sort where 1620 /// possible. 1621 /// 1622 /// This function assumes that you have simple POD-like types that can be 1623 /// compared with std::less and can be moved with memcpy. If this isn't true, 1624 /// you should use std::sort. 1625 /// 1626 /// NOTE: If qsort_r were portable, we could allow a custom comparator and 1627 /// default to std::less. 1628 template<class IteratorTy> 1629 inline void array_pod_sort(IteratorTy Start, IteratorTy End) { 1630 // Don't inefficiently call qsort with one element or trigger undefined 1631 // behavior with an empty sequence. 1632 auto NElts = End - Start; 1633 if (NElts <= 1) return; 1634 #ifdef EXPENSIVE_CHECKS 1635 detail::presortShuffle<IteratorTy>(Start, End); 1636 #endif 1637 qsort(&*Start, NElts, sizeof(*Start), get_array_pod_sort_comparator(*Start)); 1638 } 1639 1640 template <class IteratorTy> 1641 inline void array_pod_sort( 1642 IteratorTy Start, IteratorTy End, 1643 int (*Compare)( 1644 const typename std::iterator_traits<IteratorTy>::value_type *, 1645 const typename std::iterator_traits<IteratorTy>::value_type *)) { 1646 // Don't inefficiently call qsort with one element or trigger undefined 1647 // behavior with an empty sequence. 1648 auto NElts = End - Start; 1649 if (NElts <= 1) return; 1650 #ifdef EXPENSIVE_CHECKS 1651 detail::presortShuffle<IteratorTy>(Start, End); 1652 #endif 1653 qsort(&*Start, NElts, sizeof(*Start), 1654 reinterpret_cast<int (*)(const void *, const void *)>(Compare)); 1655 } 1656 1657 namespace detail { 1658 template <typename T> 1659 // We can use qsort if the iterator type is a pointer and the underlying value 1660 // is trivially copyable. 1661 using sort_trivially_copyable = std::conjunction< 1662 std::is_pointer<T>, 1663 std::is_trivially_copyable<typename std::iterator_traits<T>::value_type>>; 1664 } // namespace detail 1665 1666 // Provide wrappers to std::sort which shuffle the elements before sorting 1667 // to help uncover non-deterministic behavior (PR35135). 1668 template <typename IteratorTy> 1669 inline void sort(IteratorTy Start, IteratorTy End) { 1670 if constexpr (detail::sort_trivially_copyable<IteratorTy>::value) { 1671 // Forward trivially copyable types to array_pod_sort. This avoids a large 1672 // amount of code bloat for a minor performance hit. 1673 array_pod_sort(Start, End); 1674 } else { 1675 #ifdef EXPENSIVE_CHECKS 1676 detail::presortShuffle<IteratorTy>(Start, End); 1677 #endif 1678 std::sort(Start, End); 1679 } 1680 } 1681 1682 template <typename Container> inline void sort(Container &&C) { 1683 llvm::sort(adl_begin(C), adl_end(C)); 1684 } 1685 1686 template <typename IteratorTy, typename Compare> 1687 inline void sort(IteratorTy Start, IteratorTy End, Compare Comp) { 1688 #ifdef EXPENSIVE_CHECKS 1689 detail::presortShuffle<IteratorTy>(Start, End); 1690 #endif 1691 std::sort(Start, End, Comp); 1692 } 1693 1694 template <typename Container, typename Compare> 1695 inline void sort(Container &&C, Compare Comp) { 1696 llvm::sort(adl_begin(C), adl_end(C), Comp); 1697 } 1698 1699 /// Get the size of a range. This is a wrapper function around std::distance 1700 /// which is only enabled when the operation is O(1). 1701 template <typename R> 1702 auto size(R &&Range, 1703 std::enable_if_t< 1704 std::is_base_of<std::random_access_iterator_tag, 1705 typename std::iterator_traits<decltype( 1706 Range.begin())>::iterator_category>::value, 1707 void> * = nullptr) { 1708 return std::distance(Range.begin(), Range.end()); 1709 } 1710 1711 namespace detail { 1712 template <typename Range> 1713 using check_has_free_function_size = 1714 decltype(adl_size(std::declval<Range &>())); 1715 1716 template <typename Range> 1717 static constexpr bool HasFreeFunctionSize = 1718 is_detected<check_has_free_function_size, Range>::value; 1719 } // namespace detail 1720 1721 /// Returns the size of the \p Range, i.e., the number of elements. This 1722 /// implementation takes inspiration from `std::ranges::size` from C++20 and 1723 /// delegates the size check to `adl_size` or `std::distance`, in this order of 1724 /// preference. Unlike `llvm::size`, this function does *not* guarantee O(1) 1725 /// running time, and is intended to be used in generic code that does not know 1726 /// the exact range type. 1727 template <typename R> constexpr size_t range_size(R &&Range) { 1728 if constexpr (detail::HasFreeFunctionSize<R>) 1729 return adl_size(Range); 1730 else 1731 return static_cast<size_t>(std::distance(adl_begin(Range), adl_end(Range))); 1732 } 1733 1734 /// Provide wrappers to std::for_each which take ranges instead of having to 1735 /// pass begin/end explicitly. 1736 template <typename R, typename UnaryFunction> 1737 UnaryFunction for_each(R &&Range, UnaryFunction F) { 1738 return std::for_each(adl_begin(Range), adl_end(Range), F); 1739 } 1740 1741 /// Provide wrappers to std::all_of which take ranges instead of having to pass 1742 /// begin/end explicitly. 1743 template <typename R, typename UnaryPredicate> 1744 bool all_of(R &&Range, UnaryPredicate P) { 1745 return std::all_of(adl_begin(Range), adl_end(Range), P); 1746 } 1747 1748 /// Provide wrappers to std::any_of which take ranges instead of having to pass 1749 /// begin/end explicitly. 1750 template <typename R, typename UnaryPredicate> 1751 bool any_of(R &&Range, UnaryPredicate P) { 1752 return std::any_of(adl_begin(Range), adl_end(Range), P); 1753 } 1754 1755 /// Provide wrappers to std::none_of which take ranges instead of having to pass 1756 /// begin/end explicitly. 1757 template <typename R, typename UnaryPredicate> 1758 bool none_of(R &&Range, UnaryPredicate P) { 1759 return std::none_of(adl_begin(Range), adl_end(Range), P); 1760 } 1761 1762 /// Provide wrappers to std::fill which take ranges instead of having to pass 1763 /// begin/end explicitly. 1764 template <typename R, typename T> void fill(R &&Range, T &&Value) { 1765 std::fill(adl_begin(Range), adl_end(Range), std::forward<T>(Value)); 1766 } 1767 1768 /// Provide wrappers to std::find which take ranges instead of having to pass 1769 /// begin/end explicitly. 1770 template <typename R, typename T> auto find(R &&Range, const T &Val) { 1771 return std::find(adl_begin(Range), adl_end(Range), Val); 1772 } 1773 1774 /// Provide wrappers to std::find_if which take ranges instead of having to pass 1775 /// begin/end explicitly. 1776 template <typename R, typename UnaryPredicate> 1777 auto find_if(R &&Range, UnaryPredicate P) { 1778 return std::find_if(adl_begin(Range), adl_end(Range), P); 1779 } 1780 1781 template <typename R, typename UnaryPredicate> 1782 auto find_if_not(R &&Range, UnaryPredicate P) { 1783 return std::find_if_not(adl_begin(Range), adl_end(Range), P); 1784 } 1785 1786 /// Provide wrappers to std::remove_if which take ranges instead of having to 1787 /// pass begin/end explicitly. 1788 template <typename R, typename UnaryPredicate> 1789 auto remove_if(R &&Range, UnaryPredicate P) { 1790 return std::remove_if(adl_begin(Range), adl_end(Range), P); 1791 } 1792 1793 /// Provide wrappers to std::copy_if which take ranges instead of having to 1794 /// pass begin/end explicitly. 1795 template <typename R, typename OutputIt, typename UnaryPredicate> 1796 OutputIt copy_if(R &&Range, OutputIt Out, UnaryPredicate P) { 1797 return std::copy_if(adl_begin(Range), adl_end(Range), Out, P); 1798 } 1799 1800 /// Return the single value in \p Range that satisfies 1801 /// \p P(<member of \p Range> *, AllowRepeats)->T * returning nullptr 1802 /// when no values or multiple values were found. 1803 /// When \p AllowRepeats is true, multiple values that compare equal 1804 /// are allowed. 1805 template <typename T, typename R, typename Predicate> 1806 T *find_singleton(R &&Range, Predicate P, bool AllowRepeats = false) { 1807 T *RC = nullptr; 1808 for (auto &&A : Range) { 1809 if (T *PRC = P(A, AllowRepeats)) { 1810 if (RC) { 1811 if (!AllowRepeats || PRC != RC) 1812 return nullptr; 1813 } else { 1814 RC = PRC; 1815 } 1816 } 1817 } 1818 return RC; 1819 } 1820 1821 /// Return a pair consisting of the single value in \p Range that satisfies 1822 /// \p P(<member of \p Range> *, AllowRepeats)->std::pair<T*, bool> returning 1823 /// nullptr when no values or multiple values were found, and a bool indicating 1824 /// whether multiple values were found to cause the nullptr. 1825 /// When \p AllowRepeats is true, multiple values that compare equal are 1826 /// allowed. The predicate \p P returns a pair<T *, bool> where T is the 1827 /// singleton while the bool indicates whether multiples have already been 1828 /// found. It is expected that first will be nullptr when second is true. 1829 /// This allows using find_singleton_nested within the predicate \P. 1830 template <typename T, typename R, typename Predicate> 1831 std::pair<T *, bool> find_singleton_nested(R &&Range, Predicate P, 1832 bool AllowRepeats = false) { 1833 T *RC = nullptr; 1834 for (auto *A : Range) { 1835 std::pair<T *, bool> PRC = P(A, AllowRepeats); 1836 if (PRC.second) { 1837 assert(PRC.first == nullptr && 1838 "Inconsistent return values in find_singleton_nested."); 1839 return PRC; 1840 } 1841 if (PRC.first) { 1842 if (RC) { 1843 if (!AllowRepeats || PRC.first != RC) 1844 return {nullptr, true}; 1845 } else { 1846 RC = PRC.first; 1847 } 1848 } 1849 } 1850 return {RC, false}; 1851 } 1852 1853 template <typename R, typename OutputIt> 1854 OutputIt copy(R &&Range, OutputIt Out) { 1855 return std::copy(adl_begin(Range), adl_end(Range), Out); 1856 } 1857 1858 /// Provide wrappers to std::replace_copy_if which take ranges instead of having 1859 /// to pass begin/end explicitly. 1860 template <typename R, typename OutputIt, typename UnaryPredicate, typename T> 1861 OutputIt replace_copy_if(R &&Range, OutputIt Out, UnaryPredicate P, 1862 const T &NewValue) { 1863 return std::replace_copy_if(adl_begin(Range), adl_end(Range), Out, P, 1864 NewValue); 1865 } 1866 1867 /// Provide wrappers to std::replace_copy which take ranges instead of having to 1868 /// pass begin/end explicitly. 1869 template <typename R, typename OutputIt, typename T> 1870 OutputIt replace_copy(R &&Range, OutputIt Out, const T &OldValue, 1871 const T &NewValue) { 1872 return std::replace_copy(adl_begin(Range), adl_end(Range), Out, OldValue, 1873 NewValue); 1874 } 1875 1876 /// Provide wrappers to std::replace which take ranges instead of having to pass 1877 /// begin/end explicitly. 1878 template <typename R, typename T> 1879 void replace(R &&Range, const T &OldValue, const T &NewValue) { 1880 std::replace(adl_begin(Range), adl_end(Range), OldValue, NewValue); 1881 } 1882 1883 /// Provide wrappers to std::move which take ranges instead of having to 1884 /// pass begin/end explicitly. 1885 template <typename R, typename OutputIt> 1886 OutputIt move(R &&Range, OutputIt Out) { 1887 return std::move(adl_begin(Range), adl_end(Range), Out); 1888 } 1889 1890 namespace detail { 1891 template <typename Range, typename Element> 1892 using check_has_member_contains_t = 1893 decltype(std::declval<Range &>().contains(std::declval<const Element &>())); 1894 1895 template <typename Range, typename Element> 1896 static constexpr bool HasMemberContains = 1897 is_detected<check_has_member_contains_t, Range, Element>::value; 1898 1899 template <typename Range, typename Element> 1900 using check_has_member_find_t = 1901 decltype(std::declval<Range &>().find(std::declval<const Element &>()) != 1902 std::declval<Range &>().end()); 1903 1904 template <typename Range, typename Element> 1905 static constexpr bool HasMemberFind = 1906 is_detected<check_has_member_find_t, Range, Element>::value; 1907 1908 } // namespace detail 1909 1910 /// Returns true if \p Element is found in \p Range. Delegates the check to 1911 /// either `.contains(Element)`, `.find(Element)`, or `std::find`, in this 1912 /// order of preference. This is intended as the canonical way to check if an 1913 /// element exists in a range in generic code or range type that does not 1914 /// expose a `.contains(Element)` member. 1915 template <typename R, typename E> 1916 bool is_contained(R &&Range, const E &Element) { 1917 if constexpr (detail::HasMemberContains<R, E>) 1918 return Range.contains(Element); 1919 else if constexpr (detail::HasMemberFind<R, E>) 1920 return Range.find(Element) != Range.end(); 1921 else 1922 return std::find(adl_begin(Range), adl_end(Range), Element) != 1923 adl_end(Range); 1924 } 1925 1926 /// Returns true iff \p Element exists in \p Set. This overload takes \p Set as 1927 /// an initializer list and is `constexpr`-friendly. 1928 template <typename T, typename E> 1929 constexpr bool is_contained(std::initializer_list<T> Set, const E &Element) { 1930 // TODO: Use std::find when we switch to C++20. 1931 for (const T &V : Set) 1932 if (V == Element) 1933 return true; 1934 return false; 1935 } 1936 1937 /// Wrapper function around std::is_sorted to check if elements in a range \p R 1938 /// are sorted with respect to a comparator \p C. 1939 template <typename R, typename Compare> bool is_sorted(R &&Range, Compare C) { 1940 return std::is_sorted(adl_begin(Range), adl_end(Range), C); 1941 } 1942 1943 /// Wrapper function around std::is_sorted to check if elements in a range \p R 1944 /// are sorted in non-descending order. 1945 template <typename R> bool is_sorted(R &&Range) { 1946 return std::is_sorted(adl_begin(Range), adl_end(Range)); 1947 } 1948 1949 /// Provide wrappers to std::includes which take ranges instead of having to 1950 /// pass begin/end explicitly. 1951 /// This function checks if the sorted range \p R2 is a subsequence of the 1952 /// sorted range \p R1. The ranges must be sorted in non-descending order. 1953 template <typename R1, typename R2> bool includes(R1 &&Range1, R2 &&Range2) { 1954 assert(is_sorted(Range1) && "Range1 must be sorted in non-descending order"); 1955 assert(is_sorted(Range2) && "Range2 must be sorted in non-descending order"); 1956 return std::includes(adl_begin(Range1), adl_end(Range1), adl_begin(Range2), 1957 adl_end(Range2)); 1958 } 1959 1960 /// This function checks if the sorted range \p R2 is a subsequence of the 1961 /// sorted range \p R1. The ranges must be sorted with respect to a comparator 1962 /// \p C. 1963 template <typename R1, typename R2, typename Compare> 1964 bool includes(R1 &&Range1, R2 &&Range2, Compare &&C) { 1965 assert(is_sorted(Range1, C) && "Range1 must be sorted with respect to C"); 1966 assert(is_sorted(Range2, C) && "Range2 must be sorted with respect to C"); 1967 return std::includes(adl_begin(Range1), adl_end(Range1), adl_begin(Range2), 1968 adl_end(Range2), std::forward<Compare>(C)); 1969 } 1970 1971 /// Wrapper function around std::count to count the number of times an element 1972 /// \p Element occurs in the given range \p Range. 1973 template <typename R, typename E> auto count(R &&Range, const E &Element) { 1974 return std::count(adl_begin(Range), adl_end(Range), Element); 1975 } 1976 1977 /// Wrapper function around std::count_if to count the number of times an 1978 /// element satisfying a given predicate occurs in a range. 1979 template <typename R, typename UnaryPredicate> 1980 auto count_if(R &&Range, UnaryPredicate P) { 1981 return std::count_if(adl_begin(Range), adl_end(Range), P); 1982 } 1983 1984 /// Wrapper function around std::transform to apply a function to a range and 1985 /// store the result elsewhere. 1986 template <typename R, typename OutputIt, typename UnaryFunction> 1987 OutputIt transform(R &&Range, OutputIt d_first, UnaryFunction F) { 1988 return std::transform(adl_begin(Range), adl_end(Range), d_first, F); 1989 } 1990 1991 /// Provide wrappers to std::partition which take ranges instead of having to 1992 /// pass begin/end explicitly. 1993 template <typename R, typename UnaryPredicate> 1994 auto partition(R &&Range, UnaryPredicate P) { 1995 return std::partition(adl_begin(Range), adl_end(Range), P); 1996 } 1997 1998 /// Provide wrappers to std::binary_search which take ranges instead of having 1999 /// to pass begin/end explicitly. 2000 template <typename R, typename T> auto binary_search(R &&Range, T &&Value) { 2001 return std::binary_search(adl_begin(Range), adl_end(Range), 2002 std::forward<T>(Value)); 2003 } 2004 2005 template <typename R, typename T, typename Compare> 2006 auto binary_search(R &&Range, T &&Value, Compare C) { 2007 return std::binary_search(adl_begin(Range), adl_end(Range), 2008 std::forward<T>(Value), C); 2009 } 2010 2011 /// Provide wrappers to std::lower_bound which take ranges instead of having to 2012 /// pass begin/end explicitly. 2013 template <typename R, typename T> auto lower_bound(R &&Range, T &&Value) { 2014 return std::lower_bound(adl_begin(Range), adl_end(Range), 2015 std::forward<T>(Value)); 2016 } 2017 2018 template <typename R, typename T, typename Compare> 2019 auto lower_bound(R &&Range, T &&Value, Compare C) { 2020 return std::lower_bound(adl_begin(Range), adl_end(Range), 2021 std::forward<T>(Value), C); 2022 } 2023 2024 /// Provide wrappers to std::upper_bound which take ranges instead of having to 2025 /// pass begin/end explicitly. 2026 template <typename R, typename T> auto upper_bound(R &&Range, T &&Value) { 2027 return std::upper_bound(adl_begin(Range), adl_end(Range), 2028 std::forward<T>(Value)); 2029 } 2030 2031 template <typename R, typename T, typename Compare> 2032 auto upper_bound(R &&Range, T &&Value, Compare C) { 2033 return std::upper_bound(adl_begin(Range), adl_end(Range), 2034 std::forward<T>(Value), C); 2035 } 2036 2037 /// Provide wrappers to std::min_element which take ranges instead of having to 2038 /// pass begin/end explicitly. 2039 template <typename R> auto min_element(R &&Range) { 2040 return std::min_element(adl_begin(Range), adl_end(Range)); 2041 } 2042 2043 template <typename R, typename Compare> auto min_element(R &&Range, Compare C) { 2044 return std::min_element(adl_begin(Range), adl_end(Range), C); 2045 } 2046 2047 /// Provide wrappers to std::max_element which take ranges instead of having to 2048 /// pass begin/end explicitly. 2049 template <typename R> auto max_element(R &&Range) { 2050 return std::max_element(adl_begin(Range), adl_end(Range)); 2051 } 2052 2053 template <typename R, typename Compare> auto max_element(R &&Range, Compare C) { 2054 return std::max_element(adl_begin(Range), adl_end(Range), C); 2055 } 2056 2057 /// Provide wrappers to std::mismatch which take ranges instead of having to 2058 /// pass begin/end explicitly. 2059 /// This function returns a pair of iterators for the first mismatching elements 2060 /// from `R1` and `R2`. As an example, if: 2061 /// 2062 /// R1 = [0, 1, 4, 6], R2 = [0, 1, 5, 6] 2063 /// 2064 /// this function will return a pair of iterators, first pointing to R1[2] and 2065 /// second pointing to R2[2]. 2066 template <typename R1, typename R2> auto mismatch(R1 &&Range1, R2 &&Range2) { 2067 return std::mismatch(adl_begin(Range1), adl_end(Range1), adl_begin(Range2), 2068 adl_end(Range2)); 2069 } 2070 2071 template <typename R, typename IterTy> 2072 auto uninitialized_copy(R &&Src, IterTy Dst) { 2073 return std::uninitialized_copy(adl_begin(Src), adl_end(Src), Dst); 2074 } 2075 2076 template <typename R> 2077 void stable_sort(R &&Range) { 2078 std::stable_sort(adl_begin(Range), adl_end(Range)); 2079 } 2080 2081 template <typename R, typename Compare> 2082 void stable_sort(R &&Range, Compare C) { 2083 std::stable_sort(adl_begin(Range), adl_end(Range), C); 2084 } 2085 2086 /// Binary search for the first iterator in a range where a predicate is false. 2087 /// Requires that C is always true below some limit, and always false above it. 2088 template <typename R, typename Predicate, 2089 typename Val = decltype(*adl_begin(std::declval<R>()))> 2090 auto partition_point(R &&Range, Predicate P) { 2091 return std::partition_point(adl_begin(Range), adl_end(Range), P); 2092 } 2093 2094 template<typename Range, typename Predicate> 2095 auto unique(Range &&R, Predicate P) { 2096 return std::unique(adl_begin(R), adl_end(R), P); 2097 } 2098 2099 /// Wrapper function around std::unique to allow calling unique on a 2100 /// container without having to specify the begin/end iterators. 2101 template <typename Range> auto unique(Range &&R) { 2102 return std::unique(adl_begin(R), adl_end(R)); 2103 } 2104 2105 /// Wrapper function around std::equal to detect if pair-wise elements between 2106 /// two ranges are the same. 2107 template <typename L, typename R> bool equal(L &&LRange, R &&RRange) { 2108 return std::equal(adl_begin(LRange), adl_end(LRange), adl_begin(RRange), 2109 adl_end(RRange)); 2110 } 2111 2112 template <typename L, typename R, typename BinaryPredicate> 2113 bool equal(L &&LRange, R &&RRange, BinaryPredicate P) { 2114 return std::equal(adl_begin(LRange), adl_end(LRange), adl_begin(RRange), 2115 adl_end(RRange), P); 2116 } 2117 2118 /// Returns true if all elements in Range are equal or when the Range is empty. 2119 template <typename R> bool all_equal(R &&Range) { 2120 auto Begin = adl_begin(Range); 2121 auto End = adl_end(Range); 2122 return Begin == End || std::equal(std::next(Begin), End, Begin); 2123 } 2124 2125 /// Returns true if all Values in the initializer lists are equal or the list 2126 // is empty. 2127 template <typename T> bool all_equal(std::initializer_list<T> Values) { 2128 return all_equal<std::initializer_list<T>>(std::move(Values)); 2129 } 2130 2131 /// Provide a container algorithm similar to C++ Library Fundamentals v2's 2132 /// `erase_if` which is equivalent to: 2133 /// 2134 /// C.erase(remove_if(C, pred), C.end()); 2135 /// 2136 /// This version works for any container with an erase method call accepting 2137 /// two iterators. 2138 template <typename Container, typename UnaryPredicate> 2139 void erase_if(Container &C, UnaryPredicate P) { 2140 C.erase(remove_if(C, P), C.end()); 2141 } 2142 2143 /// Wrapper function to remove a value from a container: 2144 /// 2145 /// C.erase(remove(C.begin(), C.end(), V), C.end()); 2146 template <typename Container, typename ValueType> 2147 void erase(Container &C, ValueType V) { 2148 C.erase(std::remove(C.begin(), C.end(), V), C.end()); 2149 } 2150 2151 /// Wrapper function to append range `R` to container `C`. 2152 /// 2153 /// C.insert(C.end(), R.begin(), R.end()); 2154 template <typename Container, typename Range> 2155 void append_range(Container &C, Range &&R) { 2156 C.insert(C.end(), adl_begin(R), adl_end(R)); 2157 } 2158 2159 /// Appends all `Values` to container `C`. 2160 template <typename Container, typename... Args> 2161 void append_values(Container &C, Args &&...Values) { 2162 C.reserve(range_size(C) + sizeof...(Args)); 2163 // Append all values one by one. 2164 ((void)C.insert(C.end(), std::forward<Args>(Values)), ...); 2165 } 2166 2167 /// Given a sequence container Cont, replace the range [ContIt, ContEnd) with 2168 /// the range [ValIt, ValEnd) (which is not from the same container). 2169 template <typename Container, typename RandomAccessIterator> 2170 void replace(Container &Cont, typename Container::iterator ContIt, 2171 typename Container::iterator ContEnd, RandomAccessIterator ValIt, 2172 RandomAccessIterator ValEnd) { 2173 while (true) { 2174 if (ValIt == ValEnd) { 2175 Cont.erase(ContIt, ContEnd); 2176 return; 2177 } 2178 if (ContIt == ContEnd) { 2179 Cont.insert(ContIt, ValIt, ValEnd); 2180 return; 2181 } 2182 *ContIt = *ValIt; 2183 ++ContIt; 2184 ++ValIt; 2185 } 2186 } 2187 2188 /// Given a sequence container Cont, replace the range [ContIt, ContEnd) with 2189 /// the range R. 2190 template <typename Container, typename Range = std::initializer_list< 2191 typename Container::value_type>> 2192 void replace(Container &Cont, typename Container::iterator ContIt, 2193 typename Container::iterator ContEnd, Range &&R) { 2194 replace(Cont, ContIt, ContEnd, adl_begin(R), adl_end(R)); 2195 } 2196 2197 /// An STL-style algorithm similar to std::for_each that applies a second 2198 /// functor between every pair of elements. 2199 /// 2200 /// This provides the control flow logic to, for example, print a 2201 /// comma-separated list: 2202 /// \code 2203 /// interleave(names.begin(), names.end(), 2204 /// [&](StringRef name) { os << name; }, 2205 /// [&] { os << ", "; }); 2206 /// \endcode 2207 template <typename ForwardIterator, typename UnaryFunctor, 2208 typename NullaryFunctor, 2209 typename = std::enable_if_t< 2210 !std::is_constructible<StringRef, UnaryFunctor>::value && 2211 !std::is_constructible<StringRef, NullaryFunctor>::value>> 2212 inline void interleave(ForwardIterator begin, ForwardIterator end, 2213 UnaryFunctor each_fn, NullaryFunctor between_fn) { 2214 if (begin == end) 2215 return; 2216 each_fn(*begin); 2217 ++begin; 2218 for (; begin != end; ++begin) { 2219 between_fn(); 2220 each_fn(*begin); 2221 } 2222 } 2223 2224 template <typename Container, typename UnaryFunctor, typename NullaryFunctor, 2225 typename = std::enable_if_t< 2226 !std::is_constructible<StringRef, UnaryFunctor>::value && 2227 !std::is_constructible<StringRef, NullaryFunctor>::value>> 2228 inline void interleave(const Container &c, UnaryFunctor each_fn, 2229 NullaryFunctor between_fn) { 2230 interleave(adl_begin(c), adl_end(c), each_fn, between_fn); 2231 } 2232 2233 /// Overload of interleave for the common case of string separator. 2234 template <typename Container, typename UnaryFunctor, typename StreamT, 2235 typename T = detail::ValueOfRange<Container>> 2236 inline void interleave(const Container &c, StreamT &os, UnaryFunctor each_fn, 2237 const StringRef &separator) { 2238 interleave(adl_begin(c), adl_end(c), each_fn, [&] { os << separator; }); 2239 } 2240 template <typename Container, typename StreamT, 2241 typename T = detail::ValueOfRange<Container>> 2242 inline void interleave(const Container &c, StreamT &os, 2243 const StringRef &separator) { 2244 interleave( 2245 c, os, [&](const T &a) { os << a; }, separator); 2246 } 2247 2248 template <typename Container, typename UnaryFunctor, typename StreamT, 2249 typename T = detail::ValueOfRange<Container>> 2250 inline void interleaveComma(const Container &c, StreamT &os, 2251 UnaryFunctor each_fn) { 2252 interleave(c, os, each_fn, ", "); 2253 } 2254 template <typename Container, typename StreamT, 2255 typename T = detail::ValueOfRange<Container>> 2256 inline void interleaveComma(const Container &c, StreamT &os) { 2257 interleaveComma(c, os, [&](const T &a) { os << a; }); 2258 } 2259 2260 //===----------------------------------------------------------------------===// 2261 // Extra additions to <memory> 2262 //===----------------------------------------------------------------------===// 2263 2264 struct FreeDeleter { 2265 void operator()(void* v) { 2266 ::free(v); 2267 } 2268 }; 2269 2270 template<typename First, typename Second> 2271 struct pair_hash { 2272 size_t operator()(const std::pair<First, Second> &P) const { 2273 return std::hash<First>()(P.first) * 31 + std::hash<Second>()(P.second); 2274 } 2275 }; 2276 2277 /// Binary functor that adapts to any other binary functor after dereferencing 2278 /// operands. 2279 template <typename T> struct deref { 2280 T func; 2281 2282 // Could be further improved to cope with non-derivable functors and 2283 // non-binary functors (should be a variadic template member function 2284 // operator()). 2285 template <typename A, typename B> auto operator()(A &lhs, B &rhs) const { 2286 assert(lhs); 2287 assert(rhs); 2288 return func(*lhs, *rhs); 2289 } 2290 }; 2291 2292 namespace detail { 2293 2294 /// Tuple-like type for `zip_enumerator` dereference. 2295 template <typename... Refs> struct enumerator_result; 2296 2297 template <typename... Iters> 2298 using EnumeratorTupleType = enumerator_result<decltype(*declval<Iters>())...>; 2299 2300 /// Zippy iterator that uses the second iterator for comparisons. For the 2301 /// increment to be safe, the second range has to be the shortest. 2302 /// Returns `enumerator_result` on dereference to provide `.index()` and 2303 /// `.value()` member functions. 2304 /// Note: Because the dereference operator returns `enumerator_result` as a 2305 /// value instead of a reference and does not strictly conform to the C++17's 2306 /// definition of forward iterator. However, it satisfies all the 2307 /// forward_iterator requirements that the `zip_common` and `zippy` depend on 2308 /// and fully conforms to the C++20 definition of forward iterator. 2309 /// This is similar to `std::vector<bool>::iterator` that returns bit reference 2310 /// wrappers on dereference. 2311 template <typename... Iters> 2312 struct zip_enumerator : zip_common<zip_enumerator<Iters...>, 2313 EnumeratorTupleType<Iters...>, Iters...> { 2314 static_assert(sizeof...(Iters) >= 2, "Expected at least two iteratees"); 2315 using zip_common<zip_enumerator<Iters...>, EnumeratorTupleType<Iters...>, 2316 Iters...>::zip_common; 2317 2318 bool operator==(const zip_enumerator &Other) const { 2319 return std::get<1>(this->iterators) == std::get<1>(Other.iterators); 2320 } 2321 }; 2322 2323 template <typename... Refs> struct enumerator_result<std::size_t, Refs...> { 2324 static constexpr std::size_t NumRefs = sizeof...(Refs); 2325 static_assert(NumRefs != 0); 2326 // `NumValues` includes the index. 2327 static constexpr std::size_t NumValues = NumRefs + 1; 2328 2329 // Tuple type whose element types are references for each `Ref`. 2330 using range_reference_tuple = std::tuple<Refs...>; 2331 // Tuple type who elements are references to all values, including both 2332 // the index and `Refs` reference types. 2333 using value_reference_tuple = std::tuple<std::size_t, Refs...>; 2334 2335 enumerator_result(std::size_t Index, Refs &&...Rs) 2336 : Idx(Index), Storage(std::forward<Refs>(Rs)...) {} 2337 2338 /// Returns the 0-based index of the current position within the original 2339 /// input range(s). 2340 std::size_t index() const { return Idx; } 2341 2342 /// Returns the value(s) for the current iterator. This does not include the 2343 /// index. 2344 decltype(auto) value() const { 2345 if constexpr (NumRefs == 1) 2346 return std::get<0>(Storage); 2347 else 2348 return Storage; 2349 } 2350 2351 /// Returns the value at index `I`. This case covers the index. 2352 template <std::size_t I, typename = std::enable_if_t<I == 0>> 2353 friend std::size_t get(const enumerator_result &Result) { 2354 return Result.Idx; 2355 } 2356 2357 /// Returns the value at index `I`. This case covers references to the 2358 /// iteratees. 2359 template <std::size_t I, typename = std::enable_if_t<I != 0>> 2360 friend decltype(auto) get(const enumerator_result &Result) { 2361 // Note: This is a separate function from the other `get`, instead of an 2362 // `if constexpr` case, to work around an MSVC 19.31.31XXX compiler 2363 // (Visual Studio 2022 17.1) return type deduction bug. 2364 return std::get<I - 1>(Result.Storage); 2365 } 2366 2367 template <typename... Ts> 2368 friend bool operator==(const enumerator_result &Result, 2369 const std::tuple<std::size_t, Ts...> &Other) { 2370 static_assert(NumRefs == sizeof...(Ts), "Size mismatch"); 2371 if (Result.Idx != std::get<0>(Other)) 2372 return false; 2373 return Result.is_value_equal(Other, std::make_index_sequence<NumRefs>{}); 2374 } 2375 2376 private: 2377 template <typename Tuple, std::size_t... Idx> 2378 bool is_value_equal(const Tuple &Other, std::index_sequence<Idx...>) const { 2379 return ((std::get<Idx>(Storage) == std::get<Idx + 1>(Other)) && ...); 2380 } 2381 2382 std::size_t Idx; 2383 // Make this tuple mutable to avoid casts that obfuscate const-correctness 2384 // issues. Const-correctness of references is taken care of by `zippy` that 2385 // defines const-non and const iterator types that will propagate down to 2386 // `enumerator_result`'s `Refs`. 2387 // Note that unlike the results of `zip*` functions, `enumerate`'s result are 2388 // supposed to be modifiable even when defined as 2389 // `const`. 2390 mutable range_reference_tuple Storage; 2391 }; 2392 2393 struct index_iterator 2394 : llvm::iterator_facade_base<index_iterator, 2395 std::random_access_iterator_tag, std::size_t> { 2396 index_iterator(std::size_t Index) : Index(Index) {} 2397 2398 index_iterator &operator+=(std::ptrdiff_t N) { 2399 Index += N; 2400 return *this; 2401 } 2402 2403 index_iterator &operator-=(std::ptrdiff_t N) { 2404 Index -= N; 2405 return *this; 2406 } 2407 2408 std::ptrdiff_t operator-(const index_iterator &R) const { 2409 return Index - R.Index; 2410 } 2411 2412 // Note: This dereference operator returns a value instead of a reference 2413 // and does not strictly conform to the C++17's definition of forward 2414 // iterator. However, it satisfies all the forward_iterator requirements 2415 // that the `zip_common` depends on and fully conforms to the C++20 2416 // definition of forward iterator. 2417 std::size_t operator*() const { return Index; } 2418 2419 friend bool operator==(const index_iterator &Lhs, const index_iterator &Rhs) { 2420 return Lhs.Index == Rhs.Index; 2421 } 2422 2423 friend bool operator<(const index_iterator &Lhs, const index_iterator &Rhs) { 2424 return Lhs.Index < Rhs.Index; 2425 } 2426 2427 private: 2428 std::size_t Index; 2429 }; 2430 2431 /// Infinite stream of increasing 0-based `size_t` indices. 2432 struct index_stream { 2433 index_iterator begin() const { return {0}; } 2434 index_iterator end() const { 2435 // We approximate 'infinity' with the max size_t value, which should be good 2436 // enough to index over any container. 2437 return index_iterator{std::numeric_limits<std::size_t>::max()}; 2438 } 2439 }; 2440 2441 } // end namespace detail 2442 2443 /// Increasing range of `size_t` indices. 2444 class index_range { 2445 std::size_t Begin; 2446 std::size_t End; 2447 2448 public: 2449 index_range(std::size_t Begin, std::size_t End) : Begin(Begin), End(End) {} 2450 detail::index_iterator begin() const { return {Begin}; } 2451 detail::index_iterator end() const { return {End}; } 2452 }; 2453 2454 /// Given two or more input ranges, returns a new range whose values are 2455 /// tuples (A, B, C, ...), such that A is the 0-based index of the item in the 2456 /// sequence, and B, C, ..., are the values from the original input ranges. All 2457 /// input ranges are required to have equal lengths. Note that the returned 2458 /// iterator allows for the values (B, C, ...) to be modified. Example: 2459 /// 2460 /// ```c++ 2461 /// std::vector<char> Letters = {'A', 'B', 'C', 'D'}; 2462 /// std::vector<int> Vals = {10, 11, 12, 13}; 2463 /// 2464 /// for (auto [Index, Letter, Value] : enumerate(Letters, Vals)) { 2465 /// printf("Item %zu - %c: %d\n", Index, Letter, Value); 2466 /// Value -= 10; 2467 /// } 2468 /// ``` 2469 /// 2470 /// Output: 2471 /// Item 0 - A: 10 2472 /// Item 1 - B: 11 2473 /// Item 2 - C: 12 2474 /// Item 3 - D: 13 2475 /// 2476 /// or using an iterator: 2477 /// ```c++ 2478 /// for (auto it : enumerate(Vals)) { 2479 /// it.value() += 10; 2480 /// printf("Item %zu: %d\n", it.index(), it.value()); 2481 /// } 2482 /// ``` 2483 /// 2484 /// Output: 2485 /// Item 0: 20 2486 /// Item 1: 21 2487 /// Item 2: 22 2488 /// Item 3: 23 2489 /// 2490 template <typename FirstRange, typename... RestRanges> 2491 auto enumerate(FirstRange &&First, RestRanges &&...Rest) { 2492 if constexpr (sizeof...(Rest) != 0) { 2493 #ifndef NDEBUG 2494 // Note: Create an array instead of an initializer list to work around an 2495 // Apple clang 14 compiler bug. 2496 size_t sizes[] = {range_size(First), range_size(Rest)...}; 2497 assert(all_equal(sizes) && "Ranges have different length"); 2498 #endif 2499 } 2500 using enumerator = detail::zippy<detail::zip_enumerator, detail::index_stream, 2501 FirstRange, RestRanges...>; 2502 return enumerator(detail::index_stream{}, std::forward<FirstRange>(First), 2503 std::forward<RestRanges>(Rest)...); 2504 } 2505 2506 namespace detail { 2507 2508 template <typename Predicate, typename... Args> 2509 bool all_of_zip_predicate_first(Predicate &&P, Args &&...args) { 2510 auto z = zip(args...); 2511 auto it = z.begin(); 2512 auto end = z.end(); 2513 while (it != end) { 2514 if (!std::apply([&](auto &&...args) { return P(args...); }, *it)) 2515 return false; 2516 ++it; 2517 } 2518 return it.all_equals(end); 2519 } 2520 2521 // Just an adaptor to switch the order of argument and have the predicate before 2522 // the zipped inputs. 2523 template <typename... ArgsThenPredicate, size_t... InputIndexes> 2524 bool all_of_zip_predicate_last( 2525 std::tuple<ArgsThenPredicate...> argsThenPredicate, 2526 std::index_sequence<InputIndexes...>) { 2527 auto constexpr OutputIndex = 2528 std::tuple_size<decltype(argsThenPredicate)>::value - 1; 2529 return all_of_zip_predicate_first(std::get<OutputIndex>(argsThenPredicate), 2530 std::get<InputIndexes>(argsThenPredicate)...); 2531 } 2532 2533 } // end namespace detail 2534 2535 /// Compare two zipped ranges using the provided predicate (as last argument). 2536 /// Return true if all elements satisfy the predicate and false otherwise. 2537 // Return false if the zipped iterator aren't all at end (size mismatch). 2538 template <typename... ArgsAndPredicate> 2539 bool all_of_zip(ArgsAndPredicate &&...argsAndPredicate) { 2540 return detail::all_of_zip_predicate_last( 2541 std::forward_as_tuple(argsAndPredicate...), 2542 std::make_index_sequence<sizeof...(argsAndPredicate) - 1>{}); 2543 } 2544 2545 /// Return true if the sequence [Begin, End) has exactly N items. Runs in O(N) 2546 /// time. Not meant for use with random-access iterators. 2547 /// Can optionally take a predicate to filter lazily some items. 2548 template <typename IterTy, 2549 typename Pred = bool (*)(const decltype(*std::declval<IterTy>()) &)> 2550 bool hasNItems( 2551 IterTy &&Begin, IterTy &&End, unsigned N, 2552 Pred &&ShouldBeCounted = 2553 [](const decltype(*std::declval<IterTy>()) &) { return true; }, 2554 std::enable_if_t< 2555 !std::is_base_of<std::random_access_iterator_tag, 2556 typename std::iterator_traits<std::remove_reference_t< 2557 decltype(Begin)>>::iterator_category>::value, 2558 void> * = nullptr) { 2559 for (; N; ++Begin) { 2560 if (Begin == End) 2561 return false; // Too few. 2562 N -= ShouldBeCounted(*Begin); 2563 } 2564 for (; Begin != End; ++Begin) 2565 if (ShouldBeCounted(*Begin)) 2566 return false; // Too many. 2567 return true; 2568 } 2569 2570 /// Return true if the sequence [Begin, End) has N or more items. Runs in O(N) 2571 /// time. Not meant for use with random-access iterators. 2572 /// Can optionally take a predicate to lazily filter some items. 2573 template <typename IterTy, 2574 typename Pred = bool (*)(const decltype(*std::declval<IterTy>()) &)> 2575 bool hasNItemsOrMore( 2576 IterTy &&Begin, IterTy &&End, unsigned N, 2577 Pred &&ShouldBeCounted = 2578 [](const decltype(*std::declval<IterTy>()) &) { return true; }, 2579 std::enable_if_t< 2580 !std::is_base_of<std::random_access_iterator_tag, 2581 typename std::iterator_traits<std::remove_reference_t< 2582 decltype(Begin)>>::iterator_category>::value, 2583 void> * = nullptr) { 2584 for (; N; ++Begin) { 2585 if (Begin == End) 2586 return false; // Too few. 2587 N -= ShouldBeCounted(*Begin); 2588 } 2589 return true; 2590 } 2591 2592 /// Returns true if the sequence [Begin, End) has N or less items. Can 2593 /// optionally take a predicate to lazily filter some items. 2594 template <typename IterTy, 2595 typename Pred = bool (*)(const decltype(*std::declval<IterTy>()) &)> 2596 bool hasNItemsOrLess( 2597 IterTy &&Begin, IterTy &&End, unsigned N, 2598 Pred &&ShouldBeCounted = [](const decltype(*std::declval<IterTy>()) &) { 2599 return true; 2600 }) { 2601 assert(N != std::numeric_limits<unsigned>::max()); 2602 return !hasNItemsOrMore(Begin, End, N + 1, ShouldBeCounted); 2603 } 2604 2605 /// Returns true if the given container has exactly N items 2606 template <typename ContainerTy> bool hasNItems(ContainerTy &&C, unsigned N) { 2607 return hasNItems(adl_begin(C), adl_end(C), N); 2608 } 2609 2610 /// Returns true if the given container has N or more items 2611 template <typename ContainerTy> 2612 bool hasNItemsOrMore(ContainerTy &&C, unsigned N) { 2613 return hasNItemsOrMore(adl_begin(C), adl_end(C), N); 2614 } 2615 2616 /// Returns true if the given container has N or less items 2617 template <typename ContainerTy> 2618 bool hasNItemsOrLess(ContainerTy &&C, unsigned N) { 2619 return hasNItemsOrLess(adl_begin(C), adl_end(C), N); 2620 } 2621 2622 /// Returns a raw pointer that represents the same address as the argument. 2623 /// 2624 /// This implementation can be removed once we move to C++20 where it's defined 2625 /// as std::to_address(). 2626 /// 2627 /// The std::pointer_traits<>::to_address(p) variations of these overloads has 2628 /// not been implemented. 2629 template <class Ptr> auto to_address(const Ptr &P) { return P.operator->(); } 2630 template <class T> constexpr T *to_address(T *P) { return P; } 2631 2632 // Detect incomplete types, relying on the fact that their size is unknown. 2633 namespace detail { 2634 template <typename T> using has_sizeof = decltype(sizeof(T)); 2635 } // namespace detail 2636 2637 /// Detects when type `T` is incomplete. This is true for forward declarations 2638 /// and false for types with a full definition. 2639 template <typename T> 2640 constexpr bool is_incomplete_v = !is_detected<detail::has_sizeof, T>::value; 2641 2642 } // end namespace llvm 2643 2644 namespace std { 2645 template <typename... Refs> 2646 struct tuple_size<llvm::detail::enumerator_result<Refs...>> 2647 : std::integral_constant<std::size_t, sizeof...(Refs)> {}; 2648 2649 template <std::size_t I, typename... Refs> 2650 struct tuple_element<I, llvm::detail::enumerator_result<Refs...>> 2651 : std::tuple_element<I, std::tuple<Refs...>> {}; 2652 2653 template <std::size_t I, typename... Refs> 2654 struct tuple_element<I, const llvm::detail::enumerator_result<Refs...>> 2655 : std::tuple_element<I, std::tuple<Refs...>> {}; 2656 2657 } // namespace std 2658 2659 #endif // LLVM_ADT_STLEXTRAS_H 2660