Parallel.h 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/Support/Parallel.h - Parallel algorithms ----------------------===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #ifndef LLVM_SUPPORT_PARALLEL_H
  14. #define LLVM_SUPPORT_PARALLEL_H
  15. #include "llvm/ADT/STLExtras.h"
  16. #include "llvm/Config/llvm-config.h"
  17. #include "llvm/Support/Error.h"
  18. #include "llvm/Support/MathExtras.h"
  19. #include "llvm/Support/Threading.h"
  20. #include <algorithm>
  21. #include <condition_variable>
  22. #include <functional>
  23. #include <mutex>
  24. namespace llvm {
  25. namespace parallel {
  26. // Strategy for the default executor used by the parallel routines provided by
  27. // this file. It defaults to using all hardware threads and should be
  28. // initialized before the first use of parallel routines.
  29. extern ThreadPoolStrategy strategy;
  30. namespace detail {
  31. #if LLVM_ENABLE_THREADS
  32. class Latch {
  33. uint32_t Count;
  34. mutable std::mutex Mutex;
  35. mutable std::condition_variable Cond;
  36. public:
  37. explicit Latch(uint32_t Count = 0) : Count(Count) {}
  38. ~Latch() {
  39. // Ensure at least that sync() was called.
  40. assert(Count == 0);
  41. }
  42. void inc() {
  43. std::lock_guard<std::mutex> lock(Mutex);
  44. ++Count;
  45. }
  46. void dec() {
  47. std::lock_guard<std::mutex> lock(Mutex);
  48. if (--Count == 0)
  49. Cond.notify_all();
  50. }
  51. void sync() const {
  52. std::unique_lock<std::mutex> lock(Mutex);
  53. Cond.wait(lock, [&] { return Count == 0; });
  54. }
  55. };
  56. class TaskGroup {
  57. Latch L;
  58. bool Parallel;
  59. public:
  60. TaskGroup();
  61. ~TaskGroup();
  62. void spawn(std::function<void()> f);
  63. void sync() const { L.sync(); }
  64. };
  65. const ptrdiff_t MinParallelSize = 1024;
  66. /// Inclusive median.
  67. template <class RandomAccessIterator, class Comparator>
  68. RandomAccessIterator medianOf3(RandomAccessIterator Start,
  69. RandomAccessIterator End,
  70. const Comparator &Comp) {
  71. RandomAccessIterator Mid = Start + (std::distance(Start, End) / 2);
  72. return Comp(*Start, *(End - 1))
  73. ? (Comp(*Mid, *(End - 1)) ? (Comp(*Start, *Mid) ? Mid : Start)
  74. : End - 1)
  75. : (Comp(*Mid, *Start) ? (Comp(*(End - 1), *Mid) ? Mid : End - 1)
  76. : Start);
  77. }
  78. template <class RandomAccessIterator, class Comparator>
  79. void parallel_quick_sort(RandomAccessIterator Start, RandomAccessIterator End,
  80. const Comparator &Comp, TaskGroup &TG, size_t Depth) {
  81. // Do a sequential sort for small inputs.
  82. if (std::distance(Start, End) < detail::MinParallelSize || Depth == 0) {
  83. llvm::sort(Start, End, Comp);
  84. return;
  85. }
  86. // Partition.
  87. auto Pivot = medianOf3(Start, End, Comp);
  88. // Move Pivot to End.
  89. std::swap(*(End - 1), *Pivot);
  90. Pivot = std::partition(Start, End - 1, [&Comp, End](decltype(*Start) V) {
  91. return Comp(V, *(End - 1));
  92. });
  93. // Move Pivot to middle of partition.
  94. std::swap(*Pivot, *(End - 1));
  95. // Recurse.
  96. TG.spawn([=, &Comp, &TG] {
  97. parallel_quick_sort(Start, Pivot, Comp, TG, Depth - 1);
  98. });
  99. parallel_quick_sort(Pivot + 1, End, Comp, TG, Depth - 1);
  100. }
  101. template <class RandomAccessIterator, class Comparator>
  102. void parallel_sort(RandomAccessIterator Start, RandomAccessIterator End,
  103. const Comparator &Comp) {
  104. TaskGroup TG;
  105. parallel_quick_sort(Start, End, Comp, TG,
  106. llvm::Log2_64(std::distance(Start, End)) + 1);
  107. }
  108. // TaskGroup has a relatively high overhead, so we want to reduce
  109. // the number of spawn() calls. We'll create up to 1024 tasks here.
  110. // (Note that 1024 is an arbitrary number. This code probably needs
  111. // improving to take the number of available cores into account.)
  112. enum { MaxTasksPerGroup = 1024 };
  113. template <class IterTy, class ResultTy, class ReduceFuncTy,
  114. class TransformFuncTy>
  115. ResultTy parallel_transform_reduce(IterTy Begin, IterTy End, ResultTy Init,
  116. ReduceFuncTy Reduce,
  117. TransformFuncTy Transform) {
  118. // Limit the number of tasks to MaxTasksPerGroup to limit job scheduling
  119. // overhead on large inputs.
  120. size_t NumInputs = std::distance(Begin, End);
  121. if (NumInputs == 0)
  122. return std::move(Init);
  123. size_t NumTasks = std::min(static_cast<size_t>(MaxTasksPerGroup), NumInputs);
  124. std::vector<ResultTy> Results(NumTasks, Init);
  125. {
  126. // Each task processes either TaskSize or TaskSize+1 inputs. Any inputs
  127. // remaining after dividing them equally amongst tasks are distributed as
  128. // one extra input over the first tasks.
  129. TaskGroup TG;
  130. size_t TaskSize = NumInputs / NumTasks;
  131. size_t RemainingInputs = NumInputs % NumTasks;
  132. IterTy TBegin = Begin;
  133. for (size_t TaskId = 0; TaskId < NumTasks; ++TaskId) {
  134. IterTy TEnd = TBegin + TaskSize + (TaskId < RemainingInputs ? 1 : 0);
  135. TG.spawn([=, &Transform, &Reduce, &Results] {
  136. // Reduce the result of transformation eagerly within each task.
  137. ResultTy R = Init;
  138. for (IterTy It = TBegin; It != TEnd; ++It)
  139. R = Reduce(R, Transform(*It));
  140. Results[TaskId] = R;
  141. });
  142. TBegin = TEnd;
  143. }
  144. assert(TBegin == End);
  145. }
  146. // Do a final reduction. There are at most 1024 tasks, so this only adds
  147. // constant single-threaded overhead for large inputs. Hopefully most
  148. // reductions are cheaper than the transformation.
  149. ResultTy FinalResult = std::move(Results.front());
  150. for (ResultTy &PartialResult :
  151. makeMutableArrayRef(Results.data() + 1, Results.size() - 1))
  152. FinalResult = Reduce(FinalResult, std::move(PartialResult));
  153. return std::move(FinalResult);
  154. }
  155. #endif
  156. } // namespace detail
  157. } // namespace parallel
  158. template <class RandomAccessIterator,
  159. class Comparator = std::less<
  160. typename std::iterator_traits<RandomAccessIterator>::value_type>>
  161. void parallelSort(RandomAccessIterator Start, RandomAccessIterator End,
  162. const Comparator &Comp = Comparator()) {
  163. #if LLVM_ENABLE_THREADS
  164. if (parallel::strategy.ThreadsRequested != 1) {
  165. parallel::detail::parallel_sort(Start, End, Comp);
  166. return;
  167. }
  168. #endif
  169. llvm::sort(Start, End, Comp);
  170. }
  171. void parallelForEachN(size_t Begin, size_t End, function_ref<void(size_t)> Fn);
  172. template <class IterTy, class FuncTy>
  173. void parallelForEach(IterTy Begin, IterTy End, FuncTy Fn) {
  174. parallelForEachN(0, End - Begin, [&](size_t I) { Fn(Begin[I]); });
  175. }
  176. template <class IterTy, class ResultTy, class ReduceFuncTy,
  177. class TransformFuncTy>
  178. ResultTy parallelTransformReduce(IterTy Begin, IterTy End, ResultTy Init,
  179. ReduceFuncTy Reduce,
  180. TransformFuncTy Transform) {
  181. #if LLVM_ENABLE_THREADS
  182. if (parallel::strategy.ThreadsRequested != 1) {
  183. return parallel::detail::parallel_transform_reduce(Begin, End, Init, Reduce,
  184. Transform);
  185. }
  186. #endif
  187. for (IterTy I = Begin; I != End; ++I)
  188. Init = Reduce(std::move(Init), Transform(*I));
  189. return std::move(Init);
  190. }
  191. // Range wrappers.
  192. template <class RangeTy,
  193. class Comparator = std::less<decltype(*std::begin(RangeTy()))>>
  194. void parallelSort(RangeTy &&R, const Comparator &Comp = Comparator()) {
  195. parallelSort(std::begin(R), std::end(R), Comp);
  196. }
  197. template <class RangeTy, class FuncTy>
  198. void parallelForEach(RangeTy &&R, FuncTy Fn) {
  199. parallelForEach(std::begin(R), std::end(R), Fn);
  200. }
  201. template <class RangeTy, class ResultTy, class ReduceFuncTy,
  202. class TransformFuncTy>
  203. ResultTy parallelTransformReduce(RangeTy &&R, ResultTy Init,
  204. ReduceFuncTy Reduce,
  205. TransformFuncTy Transform) {
  206. return parallelTransformReduce(std::begin(R), std::end(R), Init, Reduce,
  207. Transform);
  208. }
  209. // Parallel for-each, but with error handling.
  210. template <class RangeTy, class FuncTy>
  211. Error parallelForEachError(RangeTy &&R, FuncTy Fn) {
  212. // The transform_reduce algorithm requires that the initial value be copyable.
  213. // Error objects are uncopyable. We only need to copy initial success values,
  214. // so work around this mismatch via the C API. The C API represents success
  215. // values with a null pointer. The joinErrors discards null values and joins
  216. // multiple errors into an ErrorList.
  217. return unwrap(parallelTransformReduce(
  218. std::begin(R), std::end(R), wrap(Error::success()),
  219. [](LLVMErrorRef Lhs, LLVMErrorRef Rhs) {
  220. return wrap(joinErrors(unwrap(Lhs), unwrap(Rhs)));
  221. },
  222. [&Fn](auto &&V) { return wrap(Fn(V)); }));
  223. }
  224. } // namespace llvm
  225. #endif // LLVM_SUPPORT_PARALLEL_H
  226. #ifdef __GNUC__
  227. #pragma GCC diagnostic pop
  228. #endif