git: 9735d993c225 - stable/12 - Merge commit d989ffd10 from llvm git (by Dimitry Andric):

From: Dimitry Andric <dim_at_FreeBSD.org>
Date: Wed, 22 Dec 2021 10:06:27 UTC
The branch stable/12 has been updated by dim:

URL: https://cgit.FreeBSD.org/src/commit/?id=9735d993c225faa0e1f96015a5b0edf9dc1c2c5b

commit 9735d993c225faa0e1f96015a5b0edf9dc1c2c5b
Author:     Dimitry Andric <dim@FreeBSD.org>
AuthorDate: 2020-12-03 19:29:18 +0000
Commit:     Dimitry Andric <dim@FreeBSD.org>
CommitDate: 2021-12-22 10:01:24 +0000

    Merge commit d989ffd10 from llvm git (by Dimitry Andric):
    
      Implement computeHostNumHardwareThreads() for FreeBSD
    
      This retrieves CPU affinity via FreeBSD's cpuset(2) API, and makes
      LLVM respect affinity settings configured by the user via the
      cpuset(1) command.
    
      In particular, this allows to reduce the number of threads used on
      machines with high core counts, which can interact badly with
      parallelized build systems. This is particularly noticable with lld,
      which spawns lots of threads even for linking e.g. hello_world!
    
      This fix is related to PR48193, but does not adress the more
      fundamental problem, which is that LLVM by default grabs as many CPUs
      and/or threads as possible.
    
      Reviewed By: MaskRay
    
      Differential Revision: https://reviews.llvm.org/D92271
    
    Originally by:  mjg
    MFC after:      1 week
    
    (cherry picked from commit c3f7be36e8ad24c31a3c56851681803704a4b0b2)
---
 contrib/llvm-project/llvm/lib/Support/Unix/Threading.inc | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)

diff --git a/contrib/llvm-project/llvm/lib/Support/Unix/Threading.inc b/contrib/llvm-project/llvm/lib/Support/Unix/Threading.inc
index 2d0aacabf092..667d023fc134 100644
--- a/contrib/llvm-project/llvm/lib/Support/Unix/Threading.inc
+++ b/contrib/llvm-project/llvm/lib/Support/Unix/Threading.inc
@@ -28,6 +28,7 @@
 
 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
 #include <errno.h>
+#include <sys/cpuset.h>
 #include <sys/sysctl.h>
 #include <sys/user.h>
 #include <unistd.h>
@@ -282,7 +283,13 @@ SetThreadPriorityResult llvm::set_thread_priority(ThreadPriority Priority) {
 #include <thread>
 
 int computeHostNumHardwareThreads() {
-#ifdef __linux__
+#if defined(__FreeBSD__)
+  cpuset_t mask;
+  CPU_ZERO(&mask);
+  if (cpuset_getaffinity(CPU_LEVEL_WHICH, CPU_WHICH_TID, -1, sizeof(mask),
+                         &mask) == 0)
+    return CPU_COUNT(&mask);
+#elif defined(__linux__)
   cpu_set_t Set;
   if (sched_getaffinity(0, sizeof(Set), &Set) == 0)
     return CPU_COUNT(&Set);