LLVM 24.0.0git
Parallel.cpp
Go to the documentation of this file.
1//===- llvm/Support/Parallel.cpp - 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
10#include "llvm/ADT/ScopeExit.h"
11#include "llvm/Config/llvm-config.h"
16
17#include <atomic>
18#include <future>
19#include <memory>
20#include <mutex>
21#include <thread>
22#include <vector>
23
24using namespace llvm;
25using namespace llvm::parallel;
26
28
29#if LLVM_ENABLE_THREADS
30
31static thread_local unsigned threadIndex = UINT_MAX;
32
33namespace {
34
35/// Runs closures on a thread pool in filo order.
36class ThreadPoolExecutor {
37public:
38 explicit ThreadPoolExecutor(ThreadPoolStrategy S) {
39 if (S.UseJobserver)
40 TheJobserver = JobserverClient::getInstance();
41
43 // Spawn all but one of the threads in another thread as spawning threads
44 // can take a while.
45 Threads.reserve(ThreadCount);
46 Threads.resize(1);
47 std::lock_guard<std::mutex> Lock(Mutex);
48 // Use operator[] before creating the thread to avoid data race in .size()
49 // in 'safe libc++' mode.
50 auto &Thread0 = Threads[0];
51 Thread0 = std::thread([this, S] {
52 for (unsigned I = 1; I < ThreadCount; ++I) {
53 Threads.emplace_back([this, S, I] { work(S, I); });
54 if (Stop)
55 break;
56 }
57 ThreadsCreated.set_value();
58 work(S, 0);
59 });
60 }
61
62 // To make sure the thread pool executor can only be created with a parallel
63 // strategy.
64 ThreadPoolExecutor() = delete;
65
66 void stop() {
67 {
68 std::lock_guard<std::mutex> Lock(Mutex);
69 if (Stop)
70 return;
71 Stop = true;
72 }
73 Cond.notify_all();
74 ThreadsCreated.get_future().wait();
75
76 std::thread::id CurrentThreadId = std::this_thread::get_id();
77 for (std::thread &T : Threads)
78 if (T.get_id() == CurrentThreadId)
79 T.detach();
80 else
81 T.join();
82 }
83
84 ~ThreadPoolExecutor() { stop(); }
85
86 struct Creator {
87 static void *call() { return new ThreadPoolExecutor(strategy); }
88 };
89 struct Deleter {
90 static void call(void *Ptr) { ((ThreadPoolExecutor *)Ptr)->stop(); }
91 };
92
93 struct WorkItem {
94 std::function<void()> F;
95 std::reference_wrapper<parallel::detail::Latch> L;
96 void operator()() {
97 F();
98 L.get().dec();
99 }
100 };
101
102 void add(std::function<void()> F, parallel::detail::Latch &L) {
103 {
104 std::lock_guard<std::mutex> Lock(Mutex);
105 WorkStack.push_back({std::move(F), std::ref(L)});
106 }
107 Cond.notify_one();
108 }
109
110 // Execute tasks from the work queue until the latch reaches zero.
111 // Used by nested TaskGroups (on worker threads) to prevent deadlock:
112 // instead of blocking in sync(), actively help drain the queue.
113 void helpSync(const parallel::detail::Latch &L) {
114 while (L.getCount() != 0) {
115 std::unique_lock<std::mutex> Lock(Mutex);
116 if (Stop || WorkStack.empty())
117 return;
118 popAndRun(Lock);
119 }
120 }
121
122 size_t getThreadCount() const { return ThreadCount; }
123
124private:
125 // Pop one task from the queue and run it. Must be called with Lock held;
126 // releases Lock before executing the task.
127 void popAndRun(std::unique_lock<std::mutex> &Lock) {
128 auto Item = std::move(WorkStack.back());
129 WorkStack.pop_back();
130 Lock.unlock();
131 Item();
132 }
133
134 void work(ThreadPoolStrategy S, unsigned ThreadID) {
135 threadIndex = ThreadID;
136 S.apply_thread_strategy(ThreadID);
137 // Note on jobserver deadlock avoidance:
138 // GNU Make grants each invoked process one implicit job slot. Our
139 // JobserverClient models this by returning an implicit JobSlot on the
140 // first successful tryAcquire() in a process. This guarantees forward
141 // progress without requiring a dedicated "always-on" thread here.
142
143 while (true) {
144 if (TheJobserver) {
145 // Jobserver-mode scheduling:
146 // - Acquire one job slot (with exponential backoff to avoid busy-wait).
147 // - While holding the slot, drain and run tasks from the local queue.
148 // - Release the slot when the queue is empty or when shutting down.
149 // Rationale: Holding a slot amortizes acquire/release overhead over
150 // multiple tasks and avoids requeue/yield churn, while still enforcing
151 // the jobserver’s global concurrency limit. With K available slots,
152 // up to K workers run tasks in parallel; within each worker tasks run
153 // sequentially until the local queue is empty.
154 ExponentialBackoff Backoff(std::chrono::hours(24));
155 JobSlot Slot;
156 do {
157 if (Stop)
158 return;
159 Slot = TheJobserver->tryAcquire();
160 if (Slot.isValid())
161 break;
162 } while (Backoff.waitForNextAttempt());
163
164 llvm::scope_exit SlotReleaser(
165 [&] { TheJobserver->release(std::move(Slot)); });
166
167 while (true) {
168 std::unique_lock<std::mutex> Lock(Mutex);
169 Cond.wait(Lock, [&] { return Stop || !WorkStack.empty(); });
170 if (Stop && WorkStack.empty())
171 return;
172 if (WorkStack.empty())
173 break;
174 popAndRun(Lock);
175 }
176 } else {
177 std::unique_lock<std::mutex> Lock(Mutex);
178 Cond.wait(Lock, [&] { return Stop || !WorkStack.empty(); });
179 if (Stop)
180 break;
181 popAndRun(Lock);
182 }
183 }
184 }
185
186 std::atomic<bool> Stop{false};
187 std::vector<WorkItem> WorkStack;
188 std::mutex Mutex;
189 std::condition_variable Cond;
190 std::promise<void> ThreadsCreated;
191 std::vector<std::thread> Threads;
192 unsigned ThreadCount;
193
194 JobserverClient *TheJobserver = nullptr;
195};
196} // namespace
197
198static ThreadPoolExecutor *getDefaultExecutor() {
199#ifdef _WIN32
200 // The ManagedStatic enables the ThreadPoolExecutor to be stopped via
201 // llvm_shutdown() on Windows. This is important to avoid various race
202 // conditions at process exit that can cause crashes or deadlocks.
203
204 static ManagedStatic<ThreadPoolExecutor, ThreadPoolExecutor::Creator,
205 ThreadPoolExecutor::Deleter>
206 ManagedExec;
207 static std::unique_ptr<ThreadPoolExecutor> Exec(&(*ManagedExec));
208 return Exec.get();
209#else
210 // ManagedStatic is not desired on other platforms. When `Exec` is destroyed
211 // by llvm_shutdown(), worker threads will clean up and invoke TLS
212 // destructors. This can lead to race conditions if other threads attempt to
213 // access TLS objects that have already been destroyed.
214 static ThreadPoolExecutor Exec(strategy);
215 return &Exec;
216#endif
217}
218
220 return getDefaultExecutor()->getThreadCount();
221}
222#endif
223
225 : Parallel(
226#if LLVM_ENABLE_THREADS
227 strategy.ThreadsRequested != 1
228#else
229 false
230#endif
231 ) {
232}
233
235#if LLVM_ENABLE_THREADS
236 // In a nested TaskGroup (threadIndex != -1u), actively help drain the queue.
237 bool IsNested = threadIndex != UINT_MAX;
238 if (Parallel && IsNested)
239 getDefaultExecutor()->helpSync(L);
240#endif
241 L.sync();
242}
243
244void TaskGroup::spawn(std::function<void()> F) {
245#if LLVM_ENABLE_THREADS
246 if (Parallel) {
247 L.inc();
248 getDefaultExecutor()->add(std::move(F), L);
249 return;
250 }
251#endif
252 F();
253}
254
255void llvm::parallelFor(size_t Begin, size_t End,
256 function_ref<void(size_t)> Fn) {
257#if LLVM_ENABLE_THREADS
258 if (strategy.ThreadsRequested != 1) {
259 size_t NumItems = End - Begin;
260 if (NumItems == 0)
261 return;
262 // Distribute work via an atomic counter shared by NumWorkers threads,
263 // keeping the task count (and thus Linux futex calls) at O(ThreadCount)
264 // For lld, per-file work is somewhat uneven, so a multipler > 1 is safer.
265 // While 2 vs 4 vs 8 makes no measurable difference, 4 is used as a
266 // reasonable default.
267 size_t NumWorkers = std::min<size_t>(NumItems, getThreadCount());
268 size_t ChunkSize = std::max(size_t(1), NumItems / (NumWorkers * 4));
269 std::atomic<size_t> Idx{Begin};
270 auto Worker = [&] {
271 while (true) {
272 size_t I = Idx.fetch_add(ChunkSize, std::memory_order_relaxed);
273 if (I >= End)
274 break;
275 size_t IEnd = std::min(I + ChunkSize, End);
276 for (; I < IEnd; ++I)
277 Fn(I);
278 }
279 };
280
281 // Run one worker on the calling thread: starts working immediately and
282 // avoids an idle thread.
283 TaskGroup TG;
284 while (--NumWorkers)
285 TG.spawn(Worker);
286 Worker();
287 return;
288 }
289#endif
290
291 for (; Begin != End; ++Begin)
292 Fn(Begin);
293}
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
if(PassOpts->AAPipeline)
const SmallVectorImpl< MachineOperand > & Cond
This file defines the make_scope_exit function, which executes user-defined cleanup logic at scope ex...
static cl::opt< int > ThreadCount("threads", cl::init(0))
A class to help implement exponential backoff.
LLVM_ABI bool waitForNextAttempt()
Blocks while waiting for the next attempt.
A JobSlot represents a single job slot that can be acquired from or released to a jobserver pool.
Definition Jobserver.h:75
The public interface for a jobserver client.
Definition Jobserver.h:133
static JobserverClient * getInstance()
Returns the singleton instance of the JobserverClient.
ManagedStatic - This transparently changes the behavior of global statics to be lazily constructed on...
This tells how a thread pool will be used.
Definition Threading.h:115
LLVM_ABI void apply_thread_strategy(unsigned ThreadPoolNum) const
Assign the current thread to an ideal hardware CPU or NUMA node.
LLVM_ABI unsigned compute_thread_count() const
Retrieves the max available threads for the current strategy.
Definition Threading.cpp:43
bool UseJobserver
If true, the thread pool will attempt to coordinate with a GNU Make jobserver, acquiring a job slot b...
Definition Threading.h:149
An efficient, type-erasing, non-owning reference to a callable.
LLVM_ABI void spawn(std::function< void()> f)
Definition Parallel.cpp:244
LLVM_ABI ThreadPoolStrategy strategy
Definition Parallel.cpp:27
size_t getThreadCount()
Definition Parallel.h:37
SmartMutex< false > Mutex
Mutex - A standard, always enforced mutex.
Definition Mutex.h:66
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI void parallelFor(size_t Begin, size_t End, function_ref< void(size_t)> Fn)
Definition Parallel.cpp:255