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