LLVM  9.0.0svn
Threading.h
Go to the documentation of this file.
1 //===-- llvm/Support/Threading.h - Control multithreading mode --*- 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 declares helper functions for running LLVM in a multi-threaded
10 // environment.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_SUPPORT_THREADING_H
15 #define LLVM_SUPPORT_THREADING_H
16 
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/Config/llvm-config.h" // for LLVM_ON_UNIX
19 #include "llvm/Support/Compiler.h"
20 #include <ciso646> // So we can check the C++ standard lib macros.
21 #include <functional>
22 
23 #if defined(_MSC_VER)
24 // MSVC's call_once implementation worked since VS 2015, which is the minimum
25 // supported version as of this writing.
26 #define LLVM_THREADING_USE_STD_CALL_ONCE 1
27 #elif defined(LLVM_ON_UNIX) && \
28  (defined(_LIBCPP_VERSION) || \
29  !(defined(__NetBSD__) || defined(__OpenBSD__) || \
30  (defined(__ppc__) || defined(__PPC__))))
31 // std::call_once from libc++ is used on all Unix platforms. Other
32 // implementations like libstdc++ are known to have problems on NetBSD,
33 // OpenBSD and PowerPC.
34 #define LLVM_THREADING_USE_STD_CALL_ONCE 1
35 #elif defined(LLVM_ON_UNIX) && \
36  ((defined(__ppc__) || defined(__PPC__)) && defined(__LITTLE_ENDIAN__))
37 #define LLVM_THREADING_USE_STD_CALL_ONCE 1
38 #else
39 #define LLVM_THREADING_USE_STD_CALL_ONCE 0
40 #endif
41 
42 #if LLVM_THREADING_USE_STD_CALL_ONCE
43 #include <mutex>
44 #else
45 #include "llvm/Support/Atomic.h"
46 #endif
47 
48 namespace llvm {
49 class Twine;
50 
51 /// Returns true if LLVM is compiled with support for multi-threading, and
52 /// false otherwise.
54 
55 /// llvm_execute_on_thread - Execute the given \p UserFn on a separate
56 /// thread, passing it the provided \p UserData and waits for thread
57 /// completion.
58 ///
59 /// This function does not guarantee that the code will actually be executed
60 /// on a separate thread or honoring the requested stack size, but tries to do
61 /// so where system support is available.
62 ///
63 /// \param UserFn - The callback to execute.
64 /// \param UserData - An argument to pass to the callback function.
65 /// \param RequestedStackSize - If non-zero, a requested size (in bytes) for
66 /// the thread stack.
67 void llvm_execute_on_thread(void (*UserFn)(void *), void *UserData,
68  unsigned RequestedStackSize = 0);
69 
70 #if LLVM_THREADING_USE_STD_CALL_ONCE
71 
73 
74 #else
75 
76  enum InitStatus { Uninitialized = 0, Wait = 1, Done = 2 };
77 
78  /// The llvm::once_flag structure
79  ///
80  /// This type is modeled after std::once_flag to use with llvm::call_once.
81  /// This structure must be used as an opaque object. It is a struct to force
82  /// autoinitialization and behave like std::once_flag.
83  struct once_flag {
84  volatile sys::cas_flag status = Uninitialized;
85  };
86 
87 #endif
88 
89  /// Execute the function specified as a parameter once.
90  ///
91  /// Typical usage:
92  /// \code
93  /// void foo() {...};
94  /// ...
95  /// static once_flag flag;
96  /// call_once(flag, foo);
97  /// \endcode
98  ///
99  /// \param flag Flag used for tracking whether or not this has run.
100  /// \param F Function to call once.
101  template <typename Function, typename... Args>
102  void call_once(once_flag &flag, Function &&F, Args &&... ArgList) {
103 #if LLVM_THREADING_USE_STD_CALL_ONCE
104  std::call_once(flag, std::forward<Function>(F),
105  std::forward<Args>(ArgList)...);
106 #else
107  // For other platforms we use a generic (if brittle) version based on our
108  // atomics.
109  sys::cas_flag old_val = sys::CompareAndSwap(&flag.status, Wait, Uninitialized);
110  if (old_val == Uninitialized) {
111  std::forward<Function>(F)(std::forward<Args>(ArgList)...);
114  TsanHappensBefore(&flag.status);
115  flag.status = Done;
117  } else {
118  // Wait until any thread doing the call has finished.
119  sys::cas_flag tmp = flag.status;
121  while (tmp != Done) {
122  tmp = flag.status;
124  }
125  }
126  TsanHappensAfter(&flag.status);
127 #endif
128  }
129 
130  /// Get the amount of currency to use for tasks requiring significant
131  /// memory or other resources. Currently based on physical cores, if
132  /// available for the host system, otherwise falls back to
133  /// thread::hardware_concurrency().
134  /// Returns 1 when LLVM is configured with LLVM_ENABLE_THREADS=OFF
136 
137  /// Get the number of threads that the current program can execute
138  /// concurrently. On some systems std::thread::hardware_concurrency() returns
139  /// the total number of cores, without taking affinity into consideration.
140  /// Returns 1 when LLVM is configured with LLVM_ENABLE_THREADS=OFF.
141  /// Fallback to std::thread::hardware_concurrency() if sched_getaffinity is
142  /// not available.
143  unsigned hardware_concurrency();
144 
145  /// Return the current thread id, as used in various OS system calls.
146  /// Note that not all platforms guarantee that the value returned will be
147  /// unique across the entire system, so portable code should not assume
148  /// this.
149  uint64_t get_threadid();
150 
151  /// Get the maximum length of a thread name on this platform.
152  /// A value of 0 means there is no limit.
154 
155  /// Set the name of the current thread. Setting a thread's name can
156  /// be helpful for enabling useful diagnostics under a debugger or when
157  /// logging. The level of support for setting a thread's name varies
158  /// wildly across operating systems, and we only make a best effort to
159  /// perform the operation on supported platforms. No indication of success
160  /// or failure is returned.
161  void set_thread_name(const Twine &Name);
162 
163  /// Get the name of the current thread. The level of support for
164  /// getting a thread's name varies wildly across operating systems, and it
165  /// is not even guaranteed that if you can successfully set a thread's name
166  /// that you can later get it back. This function is intended for diagnostic
167  /// purposes, and as with setting a thread's name no indication of whether
168  /// the operation succeeded or failed is returned.
170 
171  enum class ThreadPriority {
172  Background = 0,
173  Default = 1,
174  };
175  /// If priority is Background tries to lower current threads priority such
176  /// that it does not affect foreground tasks significantly. Can be used for
177  /// long-running, latency-insensitive tasks to make sure cpu is not hogged by
178  /// this task.
179  /// If the priority is default tries to restore current threads priority to
180  /// default scheduling priority.
183 }
184 
185 #endif
void set_thread_name(const Twine &Name)
Set the name of the current thread.
This class represents lattice values for constants.
Definition: AllocatorList.h:23
unsigned heavyweight_hardware_concurrency()
Get the amount of currency to use for tasks requiring significant memory or other resources...
Definition: Threading.cpp:62
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
F(f)
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:80
uint32_t get_max_thread_name_length()
Get the maximum length of a thread name on this platform.
void get_thread_name(SmallVectorImpl< char > &Name)
Get the name of the current thread.
void call_once(once_flag &flag, Function &&F, Args &&... ArgList)
Execute the function specified as a parameter once.
Definition: Threading.h:102
std::error_code status(const Twine &path, file_status &result, bool follow=true)
Get file status as if by POSIX stat().
#define TsanHappensAfter(cv)
Definition: Compiler.h:453
SetThreadPriorityResult
If priority is Background tries to lower current threads priority such that it does not affect foregr...
Definition: Threading.h:181
bool llvm_is_multithreaded()
Returns true if LLVM is compiled with support for multi-threading, and false otherwise.
Definition: Threading.cpp:30
#define TsanHappensBefore(cv)
Definition: Compiler.h:452
cas_flag CompareAndSwap(volatile cas_flag *ptr, cas_flag new_value, cas_flag old_value)
Definition: Atomic.cpp:44
std::once_flag once_flag
Definition: Threading.h:72
void MemoryFence()
Definition: Atomic.cpp:30
uint64_t get_threadid()
Return the current thread id, as used in various OS system calls.
void llvm_execute_on_thread(void(*UserFn)(void *), void *UserData, unsigned RequestedStackSize=0)
llvm_execute_on_thread - Execute the given UserFn on a separate thread, passing it the provided UserD...
#define TsanIgnoreWritesBegin()
Definition: Compiler.h:454
#define TsanIgnoreWritesEnd()
Definition: Compiler.h:455
SetThreadPriorityResult set_thread_priority(ThreadPriority Priority)
ProcessInfo Wait(const ProcessInfo &PI, unsigned SecondsToWait, bool WaitUntilTerminates, std::string *ErrMsg=nullptr)
This function waits for the process specified by PI to finish.
ThreadPriority
Definition: Threading.h:171
unsigned hardware_concurrency()
Get the number of threads that the current program can execute concurrently.
Definition: Threading.cpp:75
constexpr char Args[]
Key for Kernel::Metadata::mArgs.