LLVM 24.0.0git
Threading.inc
Go to the documentation of this file.
1//===- Windows/Threading.inc - Win32 Threading Implementation - -*- 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 provides the Win32 specific implementation of Threading functions.
10//
11//===----------------------------------------------------------------------===//
12
14#include "llvm/ADT/Twine.h"
15#include "llvm/Support/thread.h"
16
18#include <process.h>
19
20#include <bitset>
21
22// Windows will at times define MemoryFence.
23#ifdef MemoryFence
24#undef MemoryFence
25#endif
26
27namespace llvm {
28HANDLE
29llvm_execute_on_thread_impl(unsigned(__stdcall *ThreadFunc)(void *), void *Arg,
30 std::optional<unsigned> StackSizeInBytes) {
31 HANDLE hThread =
32 (HANDLE)::_beginthreadex(NULL, StackSizeInBytes.value_or(0), ThreadFunc,
33 Arg, STACK_SIZE_PARAM_IS_A_RESERVATION, NULL);
34
35 if (!hThread)
36 ReportLastErrorFatal("_beginthreadex failed");
37
38 return hThread;
39}
40
41void llvm_thread_join_impl(HANDLE hThread) {
42 if (::WaitForSingleObject(hThread, INFINITE) == WAIT_FAILED)
43 ReportLastErrorFatal("WaitForSingleObject failed");
44 if (::CloseHandle(hThread) == FALSE)
45 ReportLastErrorFatal("CloseHandle failed");
46}
47
48void llvm_thread_detach_impl(HANDLE hThread) {
49 if (::CloseHandle(hThread) == FALSE)
50 ReportLastErrorFatal("CloseHandle failed");
51}
52
53DWORD llvm_thread_get_id_impl(HANDLE hThread) {
54 // AppVerifier (runtime verification tool from Windows SDK) reports an error
55 // when GetThreadId(NULL) is called. Suppress this by manually checking for
56 // NULL. Return 0 as this is what's returned (by documentation) if
57 // GetThreadId() fails.
58 if (!hThread)
59 return 0;
60 return ::GetThreadId(hThread);
61}
62
63DWORD llvm_thread_get_current_id_impl() { return ::GetCurrentThreadId(); }
64
65} // namespace llvm
66
67uint64_t llvm::get_threadid() { return uint64_t(::GetCurrentThreadId()); }
68
70
71#if defined(_MSC_VER)
72static void SetThreadName(DWORD Id, LPCSTR Name) {
73 constexpr DWORD MS_VC_EXCEPTION = 0x406D1388;
74
75#pragma pack(push, 8)
76 struct THREADNAME_INFO {
77 DWORD dwType; // Must be 0x1000.
78 LPCSTR szName; // Pointer to thread name
79 DWORD dwThreadId; // Thread ID (-1 == current thread)
80 DWORD dwFlags; // Reserved. Do not use.
81 };
82#pragma pack(pop)
83
84 THREADNAME_INFO info;
85 info.dwType = 0x1000;
86 info.szName = Name;
87 info.dwThreadId = Id;
88 info.dwFlags = 0;
89
90 __try {
91 ::RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR),
92 (ULONG_PTR *)&info);
93 } __except (EXCEPTION_EXECUTE_HANDLER) {
94 }
95}
96#endif
97
98void llvm::set_thread_name(const Twine &Name) {
99#if defined(_MSC_VER)
100 // Make sure the input is null terminated.
101 SmallString<64> Storage;
102 StringRef NameStr = Name.toNullTerminatedStringRef(Storage);
103 SetThreadName(::GetCurrentThreadId(), NameStr.data());
104#endif
105}
106
107void llvm::get_thread_name(SmallVectorImpl<char> &Name) {
108 // "Name" is not an inherent property of a thread on Windows. In fact, when
109 // you "set" the name, you are only firing a one-time message to a debugger
110 // which it interprets as a program setting its threads' name. We may be
111 // able to get fancy by creating a TLS entry when someone calls
112 // set_thread_name so that subsequent calls to get_thread_name return this
113 // value.
114 Name.clear();
115}
116
118llvm::set_thread_priority(ThreadPriority Priority) {
119#ifdef THREAD_POWER_THROTTLING_CURRENT_VERSION
120 HMODULE kernelM = llvm::sys::windows::loadSystemModuleSecure(L"kernel32.dll");
121 if (kernelM) {
122 // SetThreadInformation is only available on Windows 8 and later. Since we
123 // still support compilation on Windows 7, we load the function dynamically.
124 typedef BOOL(WINAPI * SetThreadInformation_t)(
125 HANDLE hThread, THREAD_INFORMATION_CLASS ThreadInformationClass,
126 _In_reads_bytes_(ThreadInformationSize) PVOID ThreadInformation,
127 ULONG ThreadInformationSize);
128 static const auto pfnSetThreadInformation =
129 (SetThreadInformation_t)(void *)::GetProcAddress(
130 kernelM, "SetThreadInformation");
131 if (pfnSetThreadInformation) {
132 auto setThreadInformation = [](ULONG ControlMaskAndStateMask) {
133 THREAD_POWER_THROTTLING_STATE state{};
134 state.Version = THREAD_POWER_THROTTLING_CURRENT_VERSION;
135 state.ControlMask = ControlMaskAndStateMask;
136 state.StateMask = ControlMaskAndStateMask;
137 return pfnSetThreadInformation(
138 ::GetCurrentThread(), ThreadPowerThrottling, &state, sizeof(state));
139 };
140
141 // Use EcoQoS for ThreadPriority::Background available (running on most
142 // efficent cores at the most efficient cpu frequency):
143 // https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-setthreadinformation
144 // https://learn.microsoft.com/en-us/windows/win32/procthread/quality-of-service
145 setThreadInformation(Priority == ThreadPriority::Background
146 ? THREAD_POWER_THROTTLING_EXECUTION_SPEED
147 : 0);
148 }
149 }
150#endif
151
152 // https://docs.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-setthreadpriority
153 // Begin background processing mode. The system lowers the resource scheduling
154 // priorities of the thread so that it can perform background work without
155 // significantly affecting activity in the foreground.
156 // End background processing mode. The system restores the resource scheduling
157 // priorities of the thread as they were before the thread entered background
158 // processing mode.
159 //
160 // FIXME: consider THREAD_PRIORITY_BELOW_NORMAL for Low
161 return SetThreadPriority(GetCurrentThread(),
162 Priority != ThreadPriority::Default
163 ? THREAD_MODE_BACKGROUND_BEGIN
164 : THREAD_MODE_BACKGROUND_END)
165 ? SetThreadPriorityResult::SUCCESS
166 : SetThreadPriorityResult::FAILURE;
167}
168
169struct ProcessorGroup {
170 unsigned ID;
171 unsigned AllThreads;
172 unsigned UsableThreads;
173 unsigned ThreadsPerCore;
174 uint64_t Affinity;
175
176 unsigned useableCores() const {
177 return std::max(1U, UsableThreads / ThreadsPerCore);
178 }
179};
180
181template <typename F>
182static bool IterateProcInfo(LOGICAL_PROCESSOR_RELATIONSHIP Relationship, F Fn) {
183 DWORD Len = 0;
184 BOOL R = ::GetLogicalProcessorInformationEx(Relationship, NULL, &Len);
185 if (R || GetLastError() != ERROR_INSUFFICIENT_BUFFER)
186 return false;
187
188 auto *Info = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *)calloc(1, Len);
189 R = ::GetLogicalProcessorInformationEx(Relationship, Info, &Len);
190 if (R) {
191 auto *End =
192 (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *)((uint8_t *)Info + Len);
193 for (auto *Curr = Info; Curr < End;
194 Curr = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *)((uint8_t *)Curr +
195 Curr->Size)) {
196 if (Curr->Relationship != Relationship)
197 continue;
198 Fn(Curr);
199 }
200 }
201 free(Info);
202 return true;
203}
204
205static std::optional<std::vector<USHORT>> getActiveGroups() {
206 USHORT Count = 0;
207 if (::GetProcessGroupAffinity(GetCurrentProcess(), &Count, nullptr))
208 return std::nullopt;
209
210 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
211 return std::nullopt;
212
213 std::vector<USHORT> Groups;
214 Groups.resize(Count);
215 if (!::GetProcessGroupAffinity(GetCurrentProcess(), &Count, Groups.data()))
216 return std::nullopt;
217
218 return Groups;
219}
220
221static llvm::ArrayRef<ProcessorGroup> getProcessorGroups() {
222 auto computeGroups = []() {
224
225 auto HandleGroup = [&](SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *ProcInfo) {
226 GROUP_RELATIONSHIP &El = ProcInfo->Group;
227 for (unsigned J = 0; J < El.ActiveGroupCount; ++J) {
228 ProcessorGroup G;
229 G.ID = Groups.size();
230 G.AllThreads = El.GroupInfo[J].MaximumProcessorCount;
231 G.UsableThreads = El.GroupInfo[J].ActiveProcessorCount;
232 assert(G.UsableThreads <= 64);
233 G.Affinity = El.GroupInfo[J].ActiveProcessorMask;
234 Groups.push_back(G);
235 }
236 };
237
238 if (!IterateProcInfo(RelationGroup, HandleGroup))
239 return std::vector<ProcessorGroup>();
240
241 auto HandleProc = [&](SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *ProcInfo) {
242 PROCESSOR_RELATIONSHIP &El = ProcInfo->Processor;
243 assert(El.GroupCount == 1);
244 unsigned NumHyperThreads = 1;
245 // If the flag is set, each core supports more than one hyper-thread.
246 if (El.Flags & LTP_PC_SMT)
247 NumHyperThreads = std::bitset<64>(El.GroupMask[0].Mask).count();
248 unsigned I = El.GroupMask[0].Group;
249 Groups[I].ThreadsPerCore = NumHyperThreads;
250 };
251
252 if (!IterateProcInfo(RelationProcessorCore, HandleProc))
253 return std::vector<ProcessorGroup>();
254
255 auto ActiveGroups = getActiveGroups();
256 if (!ActiveGroups)
257 return std::vector<ProcessorGroup>();
258
259 // If there's an affinity mask set, assume the user wants to constrain the
260 // current process to only a single CPU group. On Windows, it is not
261 // possible for affinity masks to cross CPU group boundaries.
262 DWORD_PTR ProcessAffinityMask = 0, SystemAffinityMask = 0;
263 if (::GetProcessAffinityMask(GetCurrentProcess(), &ProcessAffinityMask,
264 &SystemAffinityMask)) {
265
266 if (ProcessAffinityMask != SystemAffinityMask) {
267 if (llvm::RunningWindows11OrGreater() && ActiveGroups->size() > 1) {
268 // The process affinity mask is spurious, due to an OS bug, ignore it.
269 return std::vector<ProcessorGroup>(Groups.begin(), Groups.end());
270 }
271
272 assert(ActiveGroups->size() == 1 &&
273 "When an affinity mask is set, the process is expected to be "
274 "assigned to a single processor group!");
275
276 unsigned CurrentGroupID = (*ActiveGroups)[0];
277 ProcessorGroup NewG{Groups[CurrentGroupID]};
278 NewG.Affinity = ProcessAffinityMask;
279 NewG.UsableThreads = llvm::popcount(ProcessAffinityMask);
280 Groups.clear();
281 Groups.push_back(NewG);
282 }
283 }
284 return std::vector<ProcessorGroup>(Groups.begin(), Groups.end());
285 };
286 static auto Groups = computeGroups();
288}
289
290template <typename R, typename UnaryPredicate>
291static unsigned aggregate(R &&Range, UnaryPredicate P) {
292 unsigned I{};
293 for (const auto &It : Range)
294 I += P(It);
295 return I;
296}
297
299 static unsigned Cores =
300 aggregate(getProcessorGroups(), [](const ProcessorGroup &G) {
301 return G.UsableThreads / G.ThreadsPerCore;
302 });
303 return Cores;
304}
305
306static int computeHostNumHardwareThreads() {
307 static unsigned Threads =
308 aggregate(getProcessorGroups(),
309 [](const ProcessorGroup &G) { return G.UsableThreads; });
310 return Threads;
311}
312
313// Finds the proper CPU socket where a thread number should go. Returns
314// 'std::nullopt' if the thread shall remain on the actual CPU socket.
315std::optional<unsigned>
316llvm::ThreadPoolStrategy::compute_cpu_socket(unsigned ThreadPoolNum) const {
317 ArrayRef<ProcessorGroup> Groups = getProcessorGroups();
318 // Only one CPU socket in the system or process affinity was set, no need to
319 // move the thread(s) to another CPU socket.
320 if (Groups.size() <= 1)
321 return std::nullopt;
322
323 // We ask for less threads than there are hardware threads per CPU socket, no
324 // need to dispatch threads to other CPU sockets.
325 unsigned MaxThreadsPerSocket =
326 UseHyperThreads ? Groups[0].UsableThreads : Groups[0].useableCores();
327 if (compute_thread_count() <= MaxThreadsPerSocket)
328 return std::nullopt;
329
330 assert(ThreadPoolNum < compute_thread_count() &&
331 "The thread index is not within thread strategy's range!");
332
333 // Assumes the same number of hardware threads per CPU socket.
334 return (ThreadPoolNum * Groups.size()) / compute_thread_count();
335}
336
337// Assign the current thread to a more appropriate CPU socket or CPU group
339 unsigned ThreadPoolNum) const {
340
341 // After Windows 11 and Windows Server 2022, let the OS do the scheduling,
342 // since a process automatically gains access to all processor groups.
344 return;
345
346 std::optional<unsigned> Socket = compute_cpu_socket(ThreadPoolNum);
347 if (!Socket)
348 return;
349 ArrayRef<ProcessorGroup> Groups = getProcessorGroups();
350 GROUP_AFFINITY Affinity{};
351 Affinity.Group = Groups[*Socket].ID;
352 Affinity.Mask = Groups[*Socket].Affinity;
353 SetThreadGroupAffinity(GetCurrentThread(), &Affinity, nullptr);
354}
355
357 GROUP_AFFINITY Affinity{};
358 GetThreadGroupAffinity(GetCurrentThread(), &Affinity);
359
360 static unsigned All =
361 aggregate(getProcessorGroups(),
362 [](const ProcessorGroup &G) { return G.AllThreads; });
363
364 unsigned StartOffset =
365 aggregate(getProcessorGroups(), [&](const ProcessorGroup &G) {
366 return G.ID < Affinity.Group ? G.AllThreads : 0;
367 });
368
370 V.resize(All);
371 for (unsigned I = 0; I < sizeof(KAFFINITY) * 8; ++I) {
372 if ((Affinity.Mask >> I) & 1)
373 V.set(StartOffset + I);
374 }
375 return V;
376}
377
378unsigned llvm::get_cpus() { return getProcessorGroups().size(); }
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
lazy value info
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
#define P(N)
This file defines the SmallString class.
static const X86InstrFMA3Group Groups[]
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
void resize(unsigned N, bool t=false)
Grow or shrink the bitvector.
Definition BitVector.h:356
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
LLVM_ABI void apply_thread_strategy(unsigned ThreadPoolNum) const
Assign the current thread to an ideal hardware CPU or NUMA node.
LLVM_ABI std::optional< unsigned > compute_cpu_socket(unsigned ThreadPoolNum) const
Finds the CPU socket where a thread should go.
LLVM_ABI unsigned compute_thread_count() const
Retrieves the max available threads for the current strategy.
Definition Threading.cpp:43
LLVM_ABI HMODULE loadSystemModuleSecure(LPCWSTR lpModuleName)
Retrieves the handle to a in-memory system module such as ntdll.dll, while ensuring we're not retriev...
This is an optimization pass for GlobalISel generic memory operations.
void ReportLastErrorFatal(const char *Msg)
LLVM_ABI llvm::BitVector get_thread_affinity_mask()
Returns a mask that represents on which hardware thread, core, CPU, NUMA group, the calling thread ca...
Definition Threading.cpp:41
LLVM_ABI uint32_t get_max_thread_name_length()
Get the maximum length of a thread name on this platform.
Definition Threading.cpp:35
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition bit.h:156
LLVM_ABI SetThreadPriorityResult set_thread_priority(ThreadPriority Priority)
LLVM_ABI unsigned get_cpus()
Returns how many physical CPUs or NUMA groups the system has.
LLVM_ABI bool RunningWindows11OrGreater()
Determines if the program is running on Windows 11 or Windows Server 2022.
LLVM_ABI void set_thread_name(const Twine &Name)
Set the name of the current thread.
Definition Threading.cpp:37
SetThreadPriorityResult
Definition Threading.h:285
LLVM_ABI void get_thread_name(SmallVectorImpl< char > &Name)
Get the name of the current thread.
Definition Threading.cpp:39
LLVM_ABI int get_physical_cores()
Returns how many physical cores (as opposed to logical cores returned from thread::hardware_concurren...
Definition Threading.cpp:49
LLVM_ABI uint64_t get_threadid()
Return the current thread id, as used in various OS system calls.
Definition Threading.cpp:33
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
ArrayRef(const T &OneElt) -> ArrayRef< T >
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320