29llvm_execute_on_thread_impl(
unsigned(__stdcall *ThreadFunc)(
void *),
void *Arg,
30 std::optional<unsigned> StackSizeInBytes) {
32 (HANDLE)::_beginthreadex(NULL, StackSizeInBytes.value_or(0), ThreadFunc,
33 Arg, STACK_SIZE_PARAM_IS_A_RESERVATION, NULL);
41void llvm_thread_join_impl(HANDLE hThread) {
42 if (::WaitForSingleObject(hThread, INFINITE) == WAIT_FAILED)
44 if (::CloseHandle(hThread) == FALSE)
48void llvm_thread_detach_impl(HANDLE hThread) {
49 if (::CloseHandle(hThread) == FALSE)
53DWORD llvm_thread_get_id_impl(HANDLE hThread) {
60 return ::GetThreadId(hThread);
63DWORD llvm_thread_get_current_id_impl() { return ::GetCurrentThreadId(); }
72static void SetThreadName(DWORD Id, LPCSTR Name) {
73 constexpr DWORD MS_VC_EXCEPTION = 0x406D1388;
76 struct THREADNAME_INFO {
91 ::RaiseException(MS_VC_EXCEPTION, 0,
sizeof(
info) /
sizeof(ULONG_PTR),
93 } __except (EXCEPTION_EXECUTE_HANDLER) {
101 SmallString<64> Storage;
102 StringRef NameStr =
Name.toNullTerminatedStringRef(Storage);
103 SetThreadName(::GetCurrentThreadId(), NameStr.data());
119#ifdef THREAD_POWER_THROTTLING_CURRENT_VERSION
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));
145 setThreadInformation(Priority == ThreadPriority::Background
146 ? THREAD_POWER_THROTTLING_EXECUTION_SPEED
161 return SetThreadPriority(GetCurrentThread(),
162 Priority != ThreadPriority::Default
163 ? THREAD_MODE_BACKGROUND_BEGIN
164 : THREAD_MODE_BACKGROUND_END)
165 ? SetThreadPriorityResult::SUCCESS
166 : SetThreadPriorityResult::FAILURE;
169struct ProcessorGroup {
172 unsigned UsableThreads;
173 unsigned ThreadsPerCore;
176 unsigned useableCores()
const {
177 return std::max(1U, UsableThreads / ThreadsPerCore);
182static bool IterateProcInfo(LOGICAL_PROCESSOR_RELATIONSHIP Relationship,
F Fn) {
184 BOOL
R = ::GetLogicalProcessorInformationEx(Relationship, NULL, &Len);
185 if (R || GetLastError() != ERROR_INSUFFICIENT_BUFFER)
188 auto *Info = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *)calloc(1, Len);
189 R = ::GetLogicalProcessorInformationEx(Relationship, Info, &Len);
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 +
196 if (Curr->Relationship != Relationship)
205static std::optional<std::vector<USHORT>> getActiveGroups() {
207 if (::GetProcessGroupAffinity(GetCurrentProcess(), &Count,
nullptr))
210 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
213 std::vector<USHORT>
Groups;
215 if (!::GetProcessGroupAffinity(GetCurrentProcess(), &Count,
Groups.data()))
222 auto computeGroups = []() {
225 auto HandleGroup = [&](SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *ProcInfo) {
226 GROUP_RELATIONSHIP &El = ProcInfo->Group;
227 for (
unsigned J = 0; J < El.ActiveGroupCount; ++J) {
230 G.AllThreads = El.GroupInfo[J].MaximumProcessorCount;
231 G.UsableThreads = El.GroupInfo[J].ActiveProcessorCount;
233 G.Affinity = El.GroupInfo[J].ActiveProcessorMask;
238 if (!IterateProcInfo(RelationGroup, HandleGroup))
239 return std::vector<ProcessorGroup>();
241 auto HandleProc = [&](SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *ProcInfo) {
242 PROCESSOR_RELATIONSHIP &El = ProcInfo->Processor;
243 assert(El.GroupCount == 1);
244 unsigned NumHyperThreads = 1;
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;
252 if (!IterateProcInfo(RelationProcessorCore, HandleProc))
253 return std::vector<ProcessorGroup>();
255 auto ActiveGroups = getActiveGroups();
257 return std::vector<ProcessorGroup>();
262 DWORD_PTR ProcessAffinityMask = 0, SystemAffinityMask = 0;
263 if (::GetProcessAffinityMask(GetCurrentProcess(), &ProcessAffinityMask,
264 &SystemAffinityMask)) {
266 if (ProcessAffinityMask != SystemAffinityMask) {
269 return std::vector<ProcessorGroup>(
Groups.begin(),
Groups.end());
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!");
276 unsigned CurrentGroupID = (*ActiveGroups)[0];
277 ProcessorGroup NewG{
Groups[CurrentGroupID]};
278 NewG.Affinity = ProcessAffinityMask;
284 return std::vector<ProcessorGroup>(
Groups.begin(),
Groups.end());
286 static auto Groups = computeGroups();
290template <
typename R,
typename UnaryPredicate>
291static unsigned aggregate(R &&
Range, UnaryPredicate
P) {
293 for (
const auto &It :
Range)
299 static unsigned Cores =
300 aggregate(getProcessorGroups(), [](
const ProcessorGroup &
G) {
301 return G.UsableThreads /
G.ThreadsPerCore;
306static int computeHostNumHardwareThreads() {
307 static unsigned Threads =
308 aggregate(getProcessorGroups(),
309 [](
const ProcessorGroup &
G) {
return G.UsableThreads; });
315std::optional<unsigned>
325 unsigned MaxThreadsPerSocket =
331 "The thread index is not within thread strategy's range!");
339 unsigned ThreadPoolNum)
const {
350 GROUP_AFFINITY Affinity{};
351 Affinity.Group =
Groups[*Socket].ID;
352 Affinity.Mask =
Groups[*Socket].Affinity;
353 SetThreadGroupAffinity(GetCurrentThread(), &Affinity,
nullptr);
357 GROUP_AFFINITY Affinity{};
358 GetThreadGroupAffinity(GetCurrentThread(), &Affinity);
360 static unsigned All =
361 aggregate(getProcessorGroups(),
362 [](
const ProcessorGroup &
G) {
return G.AllThreads; });
364 unsigned StartOffset =
365 aggregate(getProcessorGroups(), [&](
const ProcessorGroup &
G) {
366 return G.ID < Affinity.Group ?
G.AllThreads : 0;
371 for (
unsigned I = 0;
I <
sizeof(KAFFINITY) * 8; ++
I) {
372 if ((Affinity.Mask >>
I) & 1)
373 V.set(StartOffset +
I);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
This file defines the SmallString class.
static const X86InstrFMA3Group Groups[]
Represent a constant reference to an array (0 or more elements consecutively in memory),...
void resize(unsigned N, bool t=false)
Grow or shrink the bitvector.
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.
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...
LLVM_ABI uint32_t get_max_thread_name_length()
Get the maximum length of a thread name on this platform.
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
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.
LLVM_ABI void get_thread_name(SmallVectorImpl< char > &Name)
Get the name of the current thread.
LLVM_ABI int get_physical_cores()
Returns how many physical cores (as opposed to logical cores returned from thread::hardware_concurren...
LLVM_ABI uint64_t get_threadid()
Return the current thread id, as used in various OS system calls.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
ArrayRef(const T &OneElt) -> ArrayRef< T >
@ End
Run the machine verifier once, at the end of the pipeline.