1 //===- llvm/Support/Parallel.h - Parallel algorithms ----------------------===//
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 #ifndef LLVM_SUPPORT_PARALLEL_H
10 #define LLVM_SUPPORT_PARALLEL_H
11
12 #include "llvm/ADT/STLExtras.h"
13 #include "llvm/Config/llvm-config.h"
14 #include "llvm/Support/Compiler.h"
15 #include "llvm/Support/Error.h"
16 #include "llvm/Support/MathExtras.h"
17 #include "llvm/Support/Threading.h"
18
19 #include <algorithm>
20 #include <condition_variable>
21 #include <functional>
22 #include <mutex>
23
24 namespace llvm {
25
26 namespace parallel {
27
28 // Strategy for the default executor used by the parallel routines provided by
29 // this file. It defaults to using all hardware threads and should be
30 // initialized before the first use of parallel routines.
31 LLVM_ABI extern ThreadPoolStrategy strategy;
32
33 #if LLVM_ENABLE_THREADS
34 #define GET_THREAD_INDEX_IMPL \
35 if (parallel::strategy.ThreadsRequested == 1) \
36 return 0; \
37 assert((threadIndex != UINT_MAX) && \
38 "getThreadIndex() must be called from a thread created by " \
39 "ThreadPoolExecutor"); \
40 return threadIndex;
41
42 #ifdef _WIN32
43 // Direct access to thread_local variables from a different DLL isn't
44 // possible with Windows Native TLS.
45 LLVM_ABI unsigned getThreadIndex();
46 #else
47 // Don't access this directly, use the getThreadIndex wrapper.
48 LLVM_ABI extern thread_local unsigned threadIndex;
49
getThreadIndex()50 inline unsigned getThreadIndex() { GET_THREAD_INDEX_IMPL; }
51 #endif
52
53 LLVM_ABI size_t getThreadCount();
54 #else
getThreadIndex()55 inline unsigned getThreadIndex() { return 0; }
getThreadCount()56 inline size_t getThreadCount() { return 1; }
57 #endif
58
59 namespace detail {
60 class Latch {
61 uint32_t Count;
62 mutable std::mutex Mutex;
63 mutable std::condition_variable Cond;
64
65 public:
Count(Count)66 explicit Latch(uint32_t Count = 0) : Count(Count) {}
~Latch()67 ~Latch() {
68 // Ensure at least that sync() was called.
69 assert(Count == 0);
70 }
71
inc()72 void inc() {
73 std::lock_guard<std::mutex> lock(Mutex);
74 ++Count;
75 }
76
dec()77 void dec() {
78 std::lock_guard<std::mutex> lock(Mutex);
79 if (--Count == 0)
80 Cond.notify_all();
81 }
82
sync()83 void sync() const {
84 std::unique_lock<std::mutex> lock(Mutex);
85 Cond.wait(lock, [&] { return Count == 0; });
86 }
87 };
88 } // namespace detail
89
90 class TaskGroup {
91 detail::Latch L;
92 bool Parallel;
93
94 public:
95 LLVM_ABI TaskGroup();
96 LLVM_ABI ~TaskGroup();
97
98 // Spawn a task, but does not wait for it to finish.
99 // Tasks marked with \p Sequential will be executed
100 // exactly in the order which they were spawned.
101 LLVM_ABI void spawn(std::function<void()> f);
102
sync()103 void sync() const { L.sync(); }
104
isParallel()105 bool isParallel() const { return Parallel; }
106 };
107
108 namespace detail {
109
110 #if LLVM_ENABLE_THREADS
111 const ptrdiff_t MinParallelSize = 1024;
112
113 /// Inclusive median.
114 template <class RandomAccessIterator, class Comparator>
medianOf3(RandomAccessIterator Start,RandomAccessIterator End,const Comparator & Comp)115 RandomAccessIterator medianOf3(RandomAccessIterator Start,
116 RandomAccessIterator End,
117 const Comparator &Comp) {
118 RandomAccessIterator Mid = Start + (std::distance(Start, End) / 2);
119 return Comp(*Start, *(End - 1))
120 ? (Comp(*Mid, *(End - 1)) ? (Comp(*Start, *Mid) ? Mid : Start)
121 : End - 1)
122 : (Comp(*Mid, *Start) ? (Comp(*(End - 1), *Mid) ? Mid : End - 1)
123 : Start);
124 }
125
126 template <class RandomAccessIterator, class Comparator>
parallel_quick_sort(RandomAccessIterator Start,RandomAccessIterator End,const Comparator & Comp,TaskGroup & TG,size_t Depth)127 void parallel_quick_sort(RandomAccessIterator Start, RandomAccessIterator End,
128 const Comparator &Comp, TaskGroup &TG, size_t Depth) {
129 // Do a sequential sort for small inputs.
130 if (std::distance(Start, End) < detail::MinParallelSize || Depth == 0) {
131 llvm::sort(Start, End, Comp);
132 return;
133 }
134
135 // Partition.
136 auto Pivot = medianOf3(Start, End, Comp);
137 // Move Pivot to End.
138 std::swap(*(End - 1), *Pivot);
139 Pivot = std::partition(Start, End - 1, [&Comp, End](decltype(*Start) V) {
140 return Comp(V, *(End - 1));
141 });
142 // Move Pivot to middle of partition.
143 std::swap(*Pivot, *(End - 1));
144
145 // Recurse.
146 TG.spawn([=, &Comp, &TG] {
147 parallel_quick_sort(Start, Pivot, Comp, TG, Depth - 1);
148 });
149 parallel_quick_sort(Pivot + 1, End, Comp, TG, Depth - 1);
150 }
151
152 template <class RandomAccessIterator, class Comparator>
parallel_sort(RandomAccessIterator Start,RandomAccessIterator End,const Comparator & Comp)153 void parallel_sort(RandomAccessIterator Start, RandomAccessIterator End,
154 const Comparator &Comp) {
155 TaskGroup TG;
156 parallel_quick_sort(Start, End, Comp, TG,
157 llvm::Log2_64(std::distance(Start, End)) + 1);
158 }
159
160 // TaskGroup has a relatively high overhead, so we want to reduce
161 // the number of spawn() calls. We'll create up to 1024 tasks here.
162 // (Note that 1024 is an arbitrary number. This code probably needs
163 // improving to take the number of available cores into account.)
164 enum { MaxTasksPerGroup = 1024 };
165
166 template <class IterTy, class ResultTy, class ReduceFuncTy,
167 class TransformFuncTy>
parallel_transform_reduce(IterTy Begin,IterTy End,ResultTy Init,ReduceFuncTy Reduce,TransformFuncTy Transform)168 ResultTy parallel_transform_reduce(IterTy Begin, IterTy End, ResultTy Init,
169 ReduceFuncTy Reduce,
170 TransformFuncTy Transform) {
171 // Limit the number of tasks to MaxTasksPerGroup to limit job scheduling
172 // overhead on large inputs.
173 size_t NumInputs = std::distance(Begin, End);
174 if (NumInputs == 0)
175 return std::move(Init);
176 size_t NumTasks = std::min(static_cast<size_t>(MaxTasksPerGroup), NumInputs);
177 std::vector<ResultTy> Results(NumTasks, Init);
178 {
179 // Each task processes either TaskSize or TaskSize+1 inputs. Any inputs
180 // remaining after dividing them equally amongst tasks are distributed as
181 // one extra input over the first tasks.
182 TaskGroup TG;
183 size_t TaskSize = NumInputs / NumTasks;
184 size_t RemainingInputs = NumInputs % NumTasks;
185 IterTy TBegin = Begin;
186 for (size_t TaskId = 0; TaskId < NumTasks; ++TaskId) {
187 IterTy TEnd = TBegin + TaskSize + (TaskId < RemainingInputs ? 1 : 0);
188 TG.spawn([=, &Transform, &Reduce, &Results] {
189 // Reduce the result of transformation eagerly within each task.
190 ResultTy R = Init;
191 for (IterTy It = TBegin; It != TEnd; ++It)
192 R = Reduce(R, Transform(*It));
193 Results[TaskId] = R;
194 });
195 TBegin = TEnd;
196 }
197 assert(TBegin == End);
198 }
199
200 // Do a final reduction. There are at most 1024 tasks, so this only adds
201 // constant single-threaded overhead for large inputs. Hopefully most
202 // reductions are cheaper than the transformation.
203 ResultTy FinalResult = std::move(Results.front());
204 for (ResultTy &PartialResult :
205 MutableArrayRef(Results.data() + 1, Results.size() - 1))
206 FinalResult = Reduce(FinalResult, std::move(PartialResult));
207 return std::move(FinalResult);
208 }
209
210 #endif
211
212 } // namespace detail
213 } // namespace parallel
214
215 template <class RandomAccessIterator,
216 class Comparator = std::less<
217 typename std::iterator_traits<RandomAccessIterator>::value_type>>
218 void parallelSort(RandomAccessIterator Start, RandomAccessIterator End,
219 const Comparator &Comp = Comparator()) {
220 #if LLVM_ENABLE_THREADS
221 if (parallel::strategy.ThreadsRequested != 1) {
222 parallel::detail::parallel_sort(Start, End, Comp);
223 return;
224 }
225 #endif
226 llvm::sort(Start, End, Comp);
227 }
228
229 LLVM_ABI void parallelFor(size_t Begin, size_t End,
230 function_ref<void(size_t)> Fn);
231
232 template <class IterTy, class FuncTy>
parallelForEach(IterTy Begin,IterTy End,FuncTy Fn)233 void parallelForEach(IterTy Begin, IterTy End, FuncTy Fn) {
234 parallelFor(0, End - Begin, [&](size_t I) { Fn(Begin[I]); });
235 }
236
237 template <class IterTy, class ResultTy, class ReduceFuncTy,
238 class TransformFuncTy>
parallelTransformReduce(IterTy Begin,IterTy End,ResultTy Init,ReduceFuncTy Reduce,TransformFuncTy Transform)239 ResultTy parallelTransformReduce(IterTy Begin, IterTy End, ResultTy Init,
240 ReduceFuncTy Reduce,
241 TransformFuncTy Transform) {
242 #if LLVM_ENABLE_THREADS
243 if (parallel::strategy.ThreadsRequested != 1) {
244 return parallel::detail::parallel_transform_reduce(Begin, End, Init, Reduce,
245 Transform);
246 }
247 #endif
248 for (IterTy I = Begin; I != End; ++I)
249 Init = Reduce(std::move(Init), Transform(*I));
250 return std::move(Init);
251 }
252
253 // Range wrappers.
254 template <class RangeTy,
255 class Comparator = std::less<decltype(*std::begin(RangeTy()))>>
256 void parallelSort(RangeTy &&R, const Comparator &Comp = Comparator()) {
257 parallelSort(std::begin(R), std::end(R), Comp);
258 }
259
260 template <class RangeTy, class FuncTy>
parallelForEach(RangeTy && R,FuncTy Fn)261 void parallelForEach(RangeTy &&R, FuncTy Fn) {
262 parallelForEach(std::begin(R), std::end(R), Fn);
263 }
264
265 template <class RangeTy, class ResultTy, class ReduceFuncTy,
266 class TransformFuncTy>
parallelTransformReduce(RangeTy && R,ResultTy Init,ReduceFuncTy Reduce,TransformFuncTy Transform)267 ResultTy parallelTransformReduce(RangeTy &&R, ResultTy Init,
268 ReduceFuncTy Reduce,
269 TransformFuncTy Transform) {
270 return parallelTransformReduce(std::begin(R), std::end(R), Init, Reduce,
271 Transform);
272 }
273
274 // Parallel for-each, but with error handling.
275 template <class RangeTy, class FuncTy>
parallelForEachError(RangeTy && R,FuncTy Fn)276 Error parallelForEachError(RangeTy &&R, FuncTy Fn) {
277 // The transform_reduce algorithm requires that the initial value be copyable.
278 // Error objects are uncopyable. We only need to copy initial success values,
279 // so work around this mismatch via the C API. The C API represents success
280 // values with a null pointer. The joinErrors discards null values and joins
281 // multiple errors into an ErrorList.
282 return unwrap(parallelTransformReduce(
283 std::begin(R), std::end(R), wrap(Error::success()),
284 [](LLVMErrorRef Lhs, LLVMErrorRef Rhs) {
285 return wrap(joinErrors(unwrap(Lhs), unwrap(Rhs)));
286 },
287 [&Fn](auto &&V) { return wrap(Fn(V)); }));
288 }
289
290 } // namespace llvm
291
292 #endif // LLVM_SUPPORT_PARALLEL_H
293