LLVM 22.0.0git
Parallel.h
Go to the documentation of this file.
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"
15#include "llvm/Support/Error.h"
18
19#include <algorithm>
20#include <condition_variable>
21#include <functional>
22#include <mutex>
23
24namespace llvm {
25
26namespace 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.
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.
45LLVM_ABI unsigned getThreadIndex();
46#else
47// Don't access this directly, use the getThreadIndex wrapper.
48LLVM_ABI extern thread_local unsigned threadIndex;
49
50inline unsigned getThreadIndex() { GET_THREAD_INDEX_IMPL; }
51#endif
52
54#else
55inline unsigned getThreadIndex() { return 0; }
56inline size_t getThreadCount() { return 1; }
57#endif
58
59namespace detail {
60class Latch {
61 uint32_t Count;
62 mutable std::mutex Mutex;
63 mutable std::condition_variable Cond;
64
65public:
66 explicit Latch(uint32_t Count = 0) : Count(Count) {}
68 // Ensure at least that sync() was called.
69 assert(Count == 0);
70 }
71
72 void inc() {
73 std::lock_guard<std::mutex> lock(Mutex);
74 ++Count;
75 }
76
77 void dec() {
78 std::lock_guard<std::mutex> lock(Mutex);
79 if (--Count == 0)
80 Cond.notify_all();
81 }
82
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
90class TaskGroup {
92 bool Parallel;
93
94public:
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
103 void sync() const { L.sync(); }
104
105 bool isParallel() const { return Parallel; }
106};
107
108namespace detail {
109
110#if LLVM_ENABLE_THREADS
111const ptrdiff_t MinParallelSize = 1024;
112
113/// Inclusive median.
114template <class RandomAccessIterator, class Comparator>
115RandomAccessIterator 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
126template <class RandomAccessIterator, class Comparator>
127void 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
152template <class RandomAccessIterator, class Comparator>
153void 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.)
164enum { MaxTasksPerGroup = 1024 };
165
166template <class IterTy, class ResultTy, class ReduceFuncTy,
167 class TransformFuncTy>
168ResultTy 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
215template <class RandomAccessIterator,
216 class Comparator = std::less<
217 typename std::iterator_traits<RandomAccessIterator>::value_type>>
218void 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
229LLVM_ABI void parallelFor(size_t Begin, size_t End,
230 function_ref<void(size_t)> Fn);
231
232template <class IterTy, class FuncTy>
233void parallelForEach(IterTy Begin, IterTy End, FuncTy Fn) {
234 parallelFor(0, End - Begin, [&](size_t I) { Fn(Begin[I]); });
235}
236
237template <class IterTy, class ResultTy, class ReduceFuncTy,
238 class TransformFuncTy>
239ResultTy 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.
254template <class RangeTy,
255 class Comparator = std::less<decltype(*std::begin(RangeTy()))>>
256void parallelSort(RangeTy &&R, const Comparator &Comp = Comparator()) {
257 parallelSort(std::begin(R), std::end(R), Comp);
258}
259
260template <class RangeTy, class FuncTy>
261void parallelForEach(RangeTy &&R, FuncTy Fn) {
262 parallelForEach(std::begin(R), std::end(R), Fn);
263}
264
265template <class RangeTy, class ResultTy, class ReduceFuncTy,
266 class TransformFuncTy>
267ResultTy 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.
275template <class RangeTy, class FuncTy>
276Error 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.
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
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Function Alias Analysis Results
#define LLVM_ABI
Definition: Compiler.h:213
bool End
Definition: ELF_riscv.cpp:480
#define I(x, y, z)
Definition: MD5.cpp:58
const SmallVectorImpl< MachineOperand > & Cond
This file contains some templates that are useful if you are working with the STL at all.
Lightweight error class with error context and mandatory checking.
Definition: Error.h:159
static ErrorSuccess success()
Create a success value.
Definition: Error.h:336
This tells how a thread pool will be used.
Definition: Threading.h:115
LLVM_ABI void spawn(std::function< void()> f)
Definition: Parallel.cpp:194
bool isParallel() const
Definition: Parallel.h:105
Latch(uint32_t Count=0)
Definition: Parallel.h:66
struct LLVMOpaqueError * LLVMErrorRef
Opaque reference to an error instance.
Definition: Error.h:34
LLVM_ABI ThreadPoolStrategy strategy
Definition: Parallel.cpp:19
unsigned getThreadIndex()
Definition: Parallel.h:55
size_t getThreadCount()
Definition: Parallel.h:56
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
unsigned Log2_64(uint64_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition: MathExtras.h:342
void parallelSort(RandomAccessIterator Start, RandomAccessIterator End, const Comparator &Comp=Comparator())
Definition: Parallel.h:218
Error joinErrors(Error E1, Error E2)
Concatenate errors.
Definition: Error.h:442
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1669
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
Attribute unwrap(LLVMAttributeRef Attr)
Definition: Attributes.h:351
LLVMAttributeRef wrap(Attribute Attr)
Definition: Attributes.h:346
LLVM_ABI void parallelFor(size_t Begin, size_t End, function_ref< void(size_t)> Fn)
Definition: Parallel.cpp:211
ResultTy parallelTransformReduce(IterTy Begin, IterTy End, ResultTy Init, ReduceFuncTy Reduce, TransformFuncTy Transform)
Definition: Parallel.h:239
void parallelForEach(IterTy Begin, IterTy End, FuncTy Fn)
Definition: Parallel.h:233
Error parallelForEachError(RangeTy &&R, FuncTy Fn)
Definition: Parallel.h:276
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:858