1 /*! \file */
2 /*
3  * kmp.h -- KPTS runtime header file.
4  */
5 
6 //===----------------------------------------------------------------------===//
7 //
8 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
9 // See https://llvm.org/LICENSE.txt for license information.
10 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef KMP_H
15 #define KMP_H
16 
17 #include "kmp_config.h"
18 
19 /* #define BUILD_PARALLEL_ORDERED 1 */
20 
21 /* This fix replaces gettimeofday with clock_gettime for better scalability on
22    the Altix.  Requires user code to be linked with -lrt. */
23 //#define FIX_SGI_CLOCK
24 
25 /* Defines for OpenMP 3.0 tasking and auto scheduling */
26 
27 #ifndef KMP_STATIC_STEAL_ENABLED
28 #define KMP_STATIC_STEAL_ENABLED 1
29 #endif
30 #define KMP_WEIGHTED_ITERATIONS_SUPPORTED                                      \
31   (KMP_AFFINITY_SUPPORTED && KMP_STATIC_STEAL_ENABLED &&                       \
32    (KMP_ARCH_X86 || KMP_ARCH_X86_64))
33 
34 #define TASK_CURRENT_NOT_QUEUED 0
35 #define TASK_CURRENT_QUEUED 1
36 
37 #ifdef BUILD_TIED_TASK_STACK
38 #define TASK_STACK_EMPTY 0 // entries when the stack is empty
39 #define TASK_STACK_BLOCK_BITS 5 // Used in TASK_STACK_SIZE and TASK_STACK_MASK
40 // Number of entries in each task stack array
41 #define TASK_STACK_BLOCK_SIZE (1 << TASK_STACK_BLOCK_BITS)
42 // Mask for determining index into stack block
43 #define TASK_STACK_INDEX_MASK (TASK_STACK_BLOCK_SIZE - 1)
44 #endif // BUILD_TIED_TASK_STACK
45 
46 #define TASK_NOT_PUSHED 1
47 #define TASK_SUCCESSFULLY_PUSHED 0
48 #define TASK_TIED 1
49 #define TASK_UNTIED 0
50 #define TASK_EXPLICIT 1
51 #define TASK_IMPLICIT 0
52 #define TASK_PROXY 1
53 #define TASK_FULL 0
54 #define TASK_DETACHABLE 1
55 #define TASK_UNDETACHABLE 0
56 
57 #define KMP_CANCEL_THREADS
58 #define KMP_THREAD_ATTR
59 
60 // Android does not have pthread_cancel.  Undefine KMP_CANCEL_THREADS if being
61 // built on Android
62 #if defined(__ANDROID__)
63 #undef KMP_CANCEL_THREADS
64 #endif
65 
66 // Some WASI targets (e.g., wasm32-wasi-threads) do not support thread
67 // cancellation.
68 #if KMP_OS_WASI
69 #undef KMP_CANCEL_THREADS
70 #endif
71 
72 #if !KMP_OS_WASI
73 #include <signal.h>
74 #endif
75 #include <stdarg.h>
76 #include <stddef.h>
77 #include <stdio.h>
78 #include <stdlib.h>
79 #include <string.h>
80 #include <limits>
81 #include <type_traits>
82 /* include <ctype.h> don't use; problems with /MD on Windows* OS NT due to bad
83    Microsoft library. Some macros provided below to replace these functions  */
84 #ifndef __ABSOFT_WIN
85 #include <sys/types.h>
86 #endif
87 #include <limits.h>
88 #include <time.h>
89 
90 #include <errno.h>
91 
92 #include "kmp_os.h"
93 
94 #include "kmp_safe_c_api.h"
95 
96 #if KMP_STATS_ENABLED
97 class kmp_stats_list;
98 #endif
99 
100 #if KMP_USE_HIER_SCHED
101 // Only include hierarchical scheduling if affinity is supported
102 #undef KMP_USE_HIER_SCHED
103 #define KMP_USE_HIER_SCHED KMP_AFFINITY_SUPPORTED
104 #endif
105 
106 #if KMP_USE_HWLOC && KMP_AFFINITY_SUPPORTED
107 #include "hwloc.h"
108 #ifndef HWLOC_OBJ_NUMANODE
109 #define HWLOC_OBJ_NUMANODE HWLOC_OBJ_NODE
110 #endif
111 #ifndef HWLOC_OBJ_PACKAGE
112 #define HWLOC_OBJ_PACKAGE HWLOC_OBJ_SOCKET
113 #endif
114 #endif
115 
116 #if KMP_ARCH_X86 || KMP_ARCH_X86_64
117 #include <xmmintrin.h>
118 #endif
119 
120 // The below has to be defined before including "kmp_barrier.h".
121 #define KMP_INTERNAL_MALLOC(sz) malloc(sz)
122 #define KMP_INTERNAL_FREE(p) free(p)
123 #define KMP_INTERNAL_REALLOC(p, sz) realloc((p), (sz))
124 #define KMP_INTERNAL_CALLOC(n, sz) calloc((n), (sz))
125 
126 #include "kmp_debug.h"
127 #include "kmp_lock.h"
128 #include "kmp_version.h"
129 #include "kmp_barrier.h"
130 #if USE_DEBUGGER
131 #include "kmp_debugger.h"
132 #endif
133 #include "kmp_i18n.h"
134 
135 #define KMP_HANDLE_SIGNALS ((KMP_OS_UNIX && !KMP_OS_WASI) || KMP_OS_WINDOWS)
136 
137 #include "kmp_wrapper_malloc.h"
138 #if KMP_OS_UNIX
139 #include <unistd.h>
140 #if !defined NSIG && defined _NSIG
141 #define NSIG _NSIG
142 #endif
143 #endif
144 
145 #if KMP_OS_LINUX
146 #pragma weak clock_gettime
147 #endif
148 
149 #if OMPT_SUPPORT
150 #include "ompt-internal.h"
151 #endif
152 
153 #if OMPD_SUPPORT
154 #include "ompd-specific.h"
155 #endif
156 
157 #ifndef UNLIKELY
158 #define UNLIKELY(x) (x)
159 #endif
160 
161 // Affinity format function
162 #include "kmp_str.h"
163 
164 // 0 - no fast memory allocation, alignment: 8-byte on x86, 16-byte on x64.
165 // 3 - fast allocation using sync, non-sync free lists of any size, non-self
166 // free lists of limited size.
167 #ifndef USE_FAST_MEMORY
168 #define USE_FAST_MEMORY 3
169 #endif
170 
171 #ifndef KMP_NESTED_HOT_TEAMS
172 #define KMP_NESTED_HOT_TEAMS 0
173 #define USE_NESTED_HOT_ARG(x)
174 #else
175 #if KMP_NESTED_HOT_TEAMS
176 #define USE_NESTED_HOT_ARG(x) , x
177 #else
178 #define USE_NESTED_HOT_ARG(x)
179 #endif
180 #endif
181 
182 // Assume using BGET compare_exchange instruction instead of lock by default.
183 #ifndef USE_CMP_XCHG_FOR_BGET
184 #define USE_CMP_XCHG_FOR_BGET 1
185 #endif
186 
187 // Test to see if queuing lock is better than bootstrap lock for bget
188 // #ifndef USE_QUEUING_LOCK_FOR_BGET
189 // #define USE_QUEUING_LOCK_FOR_BGET
190 // #endif
191 
192 #define KMP_NSEC_PER_SEC 1000000000L
193 #define KMP_USEC_PER_SEC 1000000L
194 #define KMP_NSEC_PER_USEC 1000L
195 
196 /*!
197 @ingroup BASIC_TYPES
198 @{
199 */
200 
201 /*!
202 Values for bit flags used in the ident_t to describe the fields.
203 */
204 enum {
205   /*! Use trampoline for internal microtasks */
206   KMP_IDENT_IMB = 0x01,
207   /*! Use c-style ident structure */
208   KMP_IDENT_KMPC = 0x02,
209   /* 0x04 is no longer used */
210   /*! Entry point generated by auto-parallelization */
211   KMP_IDENT_AUTOPAR = 0x08,
212   /*! Compiler generates atomic reduction option for kmpc_reduce* */
213   KMP_IDENT_ATOMIC_REDUCE = 0x10,
214   /*! To mark a 'barrier' directive in user code */
215   KMP_IDENT_BARRIER_EXPL = 0x20,
216   /*! To Mark implicit barriers. */
217   KMP_IDENT_BARRIER_IMPL = 0x0040,
218   KMP_IDENT_BARRIER_IMPL_MASK = 0x01C0,
219   KMP_IDENT_BARRIER_IMPL_FOR = 0x0040,
220   KMP_IDENT_BARRIER_IMPL_SECTIONS = 0x00C0,
221 
222   KMP_IDENT_BARRIER_IMPL_SINGLE = 0x0140,
223   KMP_IDENT_BARRIER_IMPL_WORKSHARE = 0x01C0,
224 
225   /*! To mark a static loop in OMPT callbacks */
226   KMP_IDENT_WORK_LOOP = 0x200,
227   /*! To mark a sections directive in OMPT callbacks */
228   KMP_IDENT_WORK_SECTIONS = 0x400,
229   /*! To mark a distribute construct in OMPT callbacks */
230   KMP_IDENT_WORK_DISTRIBUTE = 0x800,
231   /*! Atomic hint; bottom four bits as omp_sync_hint_t. Top four reserved and
232       not currently used. If one day we need more bits, then we can use
233       an invalid combination of hints to mean that another, larger field
234       should be used in a different flag. */
235   KMP_IDENT_ATOMIC_HINT_MASK = 0xFF0000,
236   KMP_IDENT_ATOMIC_HINT_UNCONTENDED = 0x010000,
237   KMP_IDENT_ATOMIC_HINT_CONTENDED = 0x020000,
238   KMP_IDENT_ATOMIC_HINT_NONSPECULATIVE = 0x040000,
239   KMP_IDENT_ATOMIC_HINT_SPECULATIVE = 0x080000,
240   KMP_IDENT_OPENMP_SPEC_VERSION_MASK = 0xFF000000
241 };
242 
243 /*!
244  * The ident structure that describes a source location.
245  */
246 typedef struct ident {
247   kmp_int32 reserved_1; /**<  might be used in Fortran; see above  */
248   kmp_int32 flags; /**<  also f.flags; KMP_IDENT_xxx flags; KMP_IDENT_KMPC
249                       identifies this union member  */
250   kmp_int32 reserved_2; /**<  not really used in Fortran any more; see above */
251 #if USE_ITT_BUILD
252 /*  but currently used for storing region-specific ITT */
253 /*  contextual information. */
254 #endif /* USE_ITT_BUILD */
255   kmp_int32 reserved_3; /**< source[4] in Fortran, do not use for C++  */
256   char const *psource; /**< String describing the source location.
257                        The string is composed of semi-colon separated fields
258                        which describe the source file, the function and a pair
259                        of line numbers that delimit the construct. */
260   // Returns the OpenMP version in form major*10+minor (e.g., 50 for 5.0)
get_openmp_versionident261   kmp_int32 get_openmp_version() {
262     return (((flags & KMP_IDENT_OPENMP_SPEC_VERSION_MASK) >> 24) & 0xFF);
263   }
264 } ident_t;
265 /*!
266 @}
267 */
268 
269 // Some forward declarations.
270 typedef union kmp_team kmp_team_t;
271 typedef struct kmp_taskdata kmp_taskdata_t;
272 typedef union kmp_task_team kmp_task_team_t;
273 typedef union kmp_team kmp_team_p;
274 typedef union kmp_info kmp_info_p;
275 typedef union kmp_root kmp_root_p;
276 
277 template <bool C = false, bool S = true> class kmp_flag_32;
278 template <bool C = false, bool S = true> class kmp_flag_64;
279 template <bool C = false, bool S = true> class kmp_atomic_flag_64;
280 class kmp_flag_oncore;
281 
282 #ifdef __cplusplus
283 extern "C" {
284 #endif
285 
286 /* ------------------------------------------------------------------------ */
287 
288 /* Pack two 32-bit signed integers into a 64-bit signed integer */
289 /* ToDo: Fix word ordering for big-endian machines. */
290 #define KMP_PACK_64(HIGH_32, LOW_32)                                           \
291   ((kmp_int64)((((kmp_uint64)(HIGH_32)) << 32) | (kmp_uint64)(LOW_32)))
292 
293 // Generic string manipulation macros. Assume that _x is of type char *
294 #define SKIP_WS(_x)                                                            \
295   {                                                                            \
296     while (*(_x) == ' ' || *(_x) == '\t')                                      \
297       (_x)++;                                                                  \
298   }
299 #define SKIP_DIGITS(_x)                                                        \
300   {                                                                            \
301     while (*(_x) >= '0' && *(_x) <= '9')                                       \
302       (_x)++;                                                                  \
303   }
304 #define SKIP_TOKEN(_x)                                                         \
305   {                                                                            \
306     while ((*(_x) >= '0' && *(_x) <= '9') || (*(_x) >= 'a' && *(_x) <= 'z') || \
307            (*(_x) >= 'A' && *(_x) <= 'Z') || *(_x) == '_')                     \
308       (_x)++;                                                                  \
309   }
310 #define SKIP_TO(_x, _c)                                                        \
311   {                                                                            \
312     while (*(_x) != '\0' && *(_x) != (_c))                                     \
313       (_x)++;                                                                  \
314   }
315 
316 /* ------------------------------------------------------------------------ */
317 
318 #define KMP_MAX(x, y) ((x) > (y) ? (x) : (y))
319 #define KMP_MIN(x, y) ((x) < (y) ? (x) : (y))
320 
321 /* ------------------------------------------------------------------------ */
322 /* Enumeration types */
323 
324 enum kmp_state_timer {
325   ts_stop,
326   ts_start,
327   ts_pause,
328 
329   ts_last_state
330 };
331 
332 enum dynamic_mode {
333   dynamic_default,
334 #ifdef USE_LOAD_BALANCE
335   dynamic_load_balance,
336 #endif /* USE_LOAD_BALANCE */
337   dynamic_random,
338   dynamic_thread_limit,
339   dynamic_max
340 };
341 
342 /* external schedule constants, duplicate enum omp_sched in omp.h in order to
343  * not include it here */
344 #ifndef KMP_SCHED_TYPE_DEFINED
345 #define KMP_SCHED_TYPE_DEFINED
346 typedef enum kmp_sched {
347   kmp_sched_lower = 0, // lower and upper bounds are for routine parameter check
348   // Note: need to adjust __kmp_sch_map global array in case enum is changed
349   kmp_sched_static = 1, // mapped to kmp_sch_static_chunked           (33)
350   kmp_sched_dynamic = 2, // mapped to kmp_sch_dynamic_chunked          (35)
351   kmp_sched_guided = 3, // mapped to kmp_sch_guided_chunked           (36)
352   kmp_sched_auto = 4, // mapped to kmp_sch_auto                     (38)
353   kmp_sched_upper_std = 5, // upper bound for standard schedules
354   kmp_sched_lower_ext = 100, // lower bound of Intel extension schedules
355   kmp_sched_trapezoidal = 101, // mapped to kmp_sch_trapezoidal (39)
356 #if KMP_STATIC_STEAL_ENABLED
357   kmp_sched_static_steal = 102, // mapped to kmp_sch_static_steal (44)
358 #endif
359   kmp_sched_upper,
360   kmp_sched_default = kmp_sched_static, // default scheduling
361   kmp_sched_monotonic = 0x80000000
362 } kmp_sched_t;
363 #endif
364 
365 /*!
366  @ingroup WORK_SHARING
367  * Describes the loop schedule to be used for a parallel for loop.
368  */
369 enum sched_type : kmp_int32 {
370   kmp_sch_lower = 32, /**< lower bound for unordered values */
371   kmp_sch_static_chunked = 33,
372   kmp_sch_static = 34, /**< static unspecialized */
373   kmp_sch_dynamic_chunked = 35,
374   kmp_sch_guided_chunked = 36, /**< guided unspecialized */
375   kmp_sch_runtime = 37,
376   kmp_sch_auto = 38, /**< auto */
377   kmp_sch_trapezoidal = 39,
378 
379   /* accessible only through KMP_SCHEDULE environment variable */
380   kmp_sch_static_greedy = 40,
381   kmp_sch_static_balanced = 41,
382   /* accessible only through KMP_SCHEDULE environment variable */
383   kmp_sch_guided_iterative_chunked = 42,
384   kmp_sch_guided_analytical_chunked = 43,
385   /* accessible only through KMP_SCHEDULE environment variable */
386   kmp_sch_static_steal = 44,
387 
388   /* static with chunk adjustment (e.g., simd) */
389   kmp_sch_static_balanced_chunked = 45,
390   kmp_sch_guided_simd = 46, /**< guided with chunk adjustment */
391   kmp_sch_runtime_simd = 47, /**< runtime with chunk adjustment */
392 
393   /* accessible only through KMP_SCHEDULE environment variable */
394   kmp_sch_upper, /**< upper bound for unordered values */
395 
396   kmp_ord_lower = 64, /**< lower bound for ordered values, must be power of 2 */
397   kmp_ord_static_chunked = 65,
398   kmp_ord_static = 66, /**< ordered static unspecialized */
399   kmp_ord_dynamic_chunked = 67,
400   kmp_ord_guided_chunked = 68,
401   kmp_ord_runtime = 69,
402   kmp_ord_auto = 70, /**< ordered auto */
403   kmp_ord_trapezoidal = 71,
404   kmp_ord_upper, /**< upper bound for ordered values */
405 
406   /* Schedules for Distribute construct */
407   kmp_distribute_static_chunked = 91, /**< distribute static chunked */
408   kmp_distribute_static = 92, /**< distribute static unspecialized */
409 
410   /* For the "nomerge" versions, kmp_dispatch_next*() will always return a
411      single iteration/chunk, even if the loop is serialized. For the schedule
412      types listed above, the entire iteration vector is returned if the loop is
413      serialized. This doesn't work for gcc/gcomp sections. */
414   kmp_nm_lower = 160, /**< lower bound for nomerge values */
415 
416   kmp_nm_static_chunked =
417       (kmp_sch_static_chunked - kmp_sch_lower + kmp_nm_lower),
418   kmp_nm_static = 162, /**< static unspecialized */
419   kmp_nm_dynamic_chunked = 163,
420   kmp_nm_guided_chunked = 164, /**< guided unspecialized */
421   kmp_nm_runtime = 165,
422   kmp_nm_auto = 166, /**< auto */
423   kmp_nm_trapezoidal = 167,
424 
425   /* accessible only through KMP_SCHEDULE environment variable */
426   kmp_nm_static_greedy = 168,
427   kmp_nm_static_balanced = 169,
428   /* accessible only through KMP_SCHEDULE environment variable */
429   kmp_nm_guided_iterative_chunked = 170,
430   kmp_nm_guided_analytical_chunked = 171,
431   kmp_nm_static_steal =
432       172, /* accessible only through OMP_SCHEDULE environment variable */
433 
434   kmp_nm_ord_static_chunked = 193,
435   kmp_nm_ord_static = 194, /**< ordered static unspecialized */
436   kmp_nm_ord_dynamic_chunked = 195,
437   kmp_nm_ord_guided_chunked = 196,
438   kmp_nm_ord_runtime = 197,
439   kmp_nm_ord_auto = 198, /**< auto */
440   kmp_nm_ord_trapezoidal = 199,
441   kmp_nm_upper, /**< upper bound for nomerge values */
442 
443   /* Support for OpenMP 4.5 monotonic and nonmonotonic schedule modifiers. Since
444      we need to distinguish the three possible cases (no modifier, monotonic
445      modifier, nonmonotonic modifier), we need separate bits for each modifier.
446      The absence of monotonic does not imply nonmonotonic, especially since 4.5
447      says that the behaviour of the "no modifier" case is implementation defined
448      in 4.5, but will become "nonmonotonic" in 5.0.
449 
450      Since we're passing a full 32 bit value, we can use a couple of high bits
451      for these flags; out of paranoia we avoid the sign bit.
452 
453      These modifiers can be or-ed into non-static schedules by the compiler to
454      pass the additional information. They will be stripped early in the
455      processing in __kmp_dispatch_init when setting up schedules, so most of the
456      code won't ever see schedules with these bits set.  */
457   kmp_sch_modifier_monotonic =
458       (1 << 29), /**< Set if the monotonic schedule modifier was present */
459   kmp_sch_modifier_nonmonotonic =
460       (1 << 30), /**< Set if the nonmonotonic schedule modifier was present */
461 
462 #define SCHEDULE_WITHOUT_MODIFIERS(s)                                          \
463   (enum sched_type)(                                                           \
464       (s) & ~(kmp_sch_modifier_nonmonotonic | kmp_sch_modifier_monotonic))
465 #define SCHEDULE_HAS_MONOTONIC(s) (((s)&kmp_sch_modifier_monotonic) != 0)
466 #define SCHEDULE_HAS_NONMONOTONIC(s) (((s)&kmp_sch_modifier_nonmonotonic) != 0)
467 #define SCHEDULE_HAS_NO_MODIFIERS(s)                                           \
468   (((s) & (kmp_sch_modifier_nonmonotonic | kmp_sch_modifier_monotonic)) == 0)
469 #define SCHEDULE_GET_MODIFIERS(s)                                              \
470   ((enum sched_type)(                                                          \
471       (s) & (kmp_sch_modifier_nonmonotonic | kmp_sch_modifier_monotonic)))
472 #define SCHEDULE_SET_MODIFIERS(s, m)                                           \
473   (s = (enum sched_type)((kmp_int32)s | (kmp_int32)m))
474 #define SCHEDULE_NONMONOTONIC 0
475 #define SCHEDULE_MONOTONIC 1
476 
477   kmp_sch_default = kmp_sch_static /**< default scheduling algorithm */
478 };
479 
480 // Apply modifiers on internal kind to standard kind
481 static inline void
__kmp_sched_apply_mods_stdkind(kmp_sched_t * kind,enum sched_type internal_kind)482 __kmp_sched_apply_mods_stdkind(kmp_sched_t *kind,
483                                enum sched_type internal_kind) {
484   if (SCHEDULE_HAS_MONOTONIC(internal_kind)) {
485     *kind = (kmp_sched_t)((int)*kind | (int)kmp_sched_monotonic);
486   }
487 }
488 
489 // Apply modifiers on standard kind to internal kind
490 static inline void
__kmp_sched_apply_mods_intkind(kmp_sched_t kind,enum sched_type * internal_kind)491 __kmp_sched_apply_mods_intkind(kmp_sched_t kind,
492                                enum sched_type *internal_kind) {
493   if ((int)kind & (int)kmp_sched_monotonic) {
494     *internal_kind = (enum sched_type)((int)*internal_kind |
495                                        (int)kmp_sch_modifier_monotonic);
496   }
497 }
498 
499 // Get standard schedule without modifiers
__kmp_sched_without_mods(kmp_sched_t kind)500 static inline kmp_sched_t __kmp_sched_without_mods(kmp_sched_t kind) {
501   return (kmp_sched_t)((int)kind & ~((int)kmp_sched_monotonic));
502 }
503 
504 /* Type to keep runtime schedule set via OMP_SCHEDULE or omp_set_schedule() */
505 typedef union kmp_r_sched {
506   struct {
507     enum sched_type r_sched_type;
508     int chunk;
509   };
510   kmp_int64 sched;
511 } kmp_r_sched_t;
512 
513 extern enum sched_type __kmp_sch_map[]; // map OMP 3.0 schedule types with our
514 // internal schedule types
515 
516 enum library_type {
517   library_none,
518   library_serial,
519   library_turnaround,
520   library_throughput
521 };
522 
523 #if KMP_OS_LINUX
524 enum clock_function_type {
525   clock_function_gettimeofday,
526   clock_function_clock_gettime
527 };
528 #endif /* KMP_OS_LINUX */
529 
530 #if KMP_MIC_SUPPORTED
531 enum mic_type { non_mic, mic1, mic2, mic3, dummy };
532 #endif
533 
534 /* -- fast reduction stuff ------------------------------------------------ */
535 
536 #undef KMP_FAST_REDUCTION_BARRIER
537 #define KMP_FAST_REDUCTION_BARRIER 1
538 
539 #undef KMP_FAST_REDUCTION_CORE_DUO
540 #if KMP_ARCH_X86 || KMP_ARCH_X86_64
541 #define KMP_FAST_REDUCTION_CORE_DUO 1
542 #endif
543 
544 enum _reduction_method {
545   reduction_method_not_defined = 0,
546   critical_reduce_block = (1 << 8),
547   atomic_reduce_block = (2 << 8),
548   tree_reduce_block = (3 << 8),
549   empty_reduce_block = (4 << 8)
550 };
551 
552 // Description of the packed_reduction_method variable:
553 // The packed_reduction_method variable consists of two enum types variables
554 // that are packed together into 0-th byte and 1-st byte:
555 // 0: (packed_reduction_method & 0x000000FF) is a 'enum barrier_type' value of
556 // barrier that will be used in fast reduction: bs_plain_barrier or
557 // bs_reduction_barrier
558 // 1: (packed_reduction_method & 0x0000FF00) is a reduction method that will
559 // be used in fast reduction;
560 // Reduction method is of 'enum _reduction_method' type and it's defined the way
561 // so that the bits of 0-th byte are empty, so no need to execute a shift
562 // instruction while packing/unpacking
563 
564 #if KMP_FAST_REDUCTION_BARRIER
565 #define PACK_REDUCTION_METHOD_AND_BARRIER(reduction_method, barrier_type)      \
566   ((reduction_method) | (barrier_type))
567 
568 #define UNPACK_REDUCTION_METHOD(packed_reduction_method)                       \
569   ((enum _reduction_method)((packed_reduction_method) & (0x0000FF00)))
570 
571 #define UNPACK_REDUCTION_BARRIER(packed_reduction_method)                      \
572   ((enum barrier_type)((packed_reduction_method) & (0x000000FF)))
573 #else
574 #define PACK_REDUCTION_METHOD_AND_BARRIER(reduction_method, barrier_type)      \
575   (reduction_method)
576 
577 #define UNPACK_REDUCTION_METHOD(packed_reduction_method)                       \
578   (packed_reduction_method)
579 
580 #define UNPACK_REDUCTION_BARRIER(packed_reduction_method) (bs_plain_barrier)
581 #endif
582 
583 #define TEST_REDUCTION_METHOD(packed_reduction_method, which_reduction_block)  \
584   ((UNPACK_REDUCTION_METHOD(packed_reduction_method)) ==                       \
585    (which_reduction_block))
586 
587 #if KMP_FAST_REDUCTION_BARRIER
588 #define TREE_REDUCE_BLOCK_WITH_REDUCTION_BARRIER                               \
589   (PACK_REDUCTION_METHOD_AND_BARRIER(tree_reduce_block, bs_reduction_barrier))
590 
591 #define TREE_REDUCE_BLOCK_WITH_PLAIN_BARRIER                                   \
592   (PACK_REDUCTION_METHOD_AND_BARRIER(tree_reduce_block, bs_plain_barrier))
593 #endif
594 
595 typedef int PACKED_REDUCTION_METHOD_T;
596 
597 /* -- end of fast reduction stuff ----------------------------------------- */
598 
599 #if KMP_OS_WINDOWS
600 #define USE_CBLKDATA
601 #if KMP_MSVC_COMPAT
602 #pragma warning(push)
603 #pragma warning(disable : 271 310)
604 #endif
605 #include <windows.h>
606 #if KMP_MSVC_COMPAT
607 #pragma warning(pop)
608 #endif
609 #endif
610 
611 #if KMP_OS_UNIX
612 #if !KMP_OS_WASI
613 #include <dlfcn.h>
614 #endif
615 #include <pthread.h>
616 #endif
617 
618 enum kmp_hw_t : int {
619   KMP_HW_UNKNOWN = -1,
620   KMP_HW_SOCKET = 0,
621   KMP_HW_PROC_GROUP,
622   KMP_HW_NUMA,
623   KMP_HW_DIE,
624   KMP_HW_LLC,
625   KMP_HW_L3,
626   KMP_HW_TILE,
627   KMP_HW_MODULE,
628   KMP_HW_L2,
629   KMP_HW_L1,
630   KMP_HW_CORE,
631   KMP_HW_THREAD,
632   KMP_HW_LAST
633 };
634 
635 typedef enum kmp_hw_core_type_t {
636   KMP_HW_CORE_TYPE_UNKNOWN = 0x0,
637 #if KMP_ARCH_X86 || KMP_ARCH_X86_64
638   KMP_HW_CORE_TYPE_ATOM = 0x20,
639   KMP_HW_CORE_TYPE_CORE = 0x40,
640   KMP_HW_MAX_NUM_CORE_TYPES = 3,
641 #else
642   KMP_HW_MAX_NUM_CORE_TYPES = 1,
643 #endif
644 } kmp_hw_core_type_t;
645 
646 #define KMP_HW_MAX_NUM_CORE_EFFS 8
647 
648 #define KMP_DEBUG_ASSERT_VALID_HW_TYPE(type)                                   \
649   KMP_DEBUG_ASSERT(type >= (kmp_hw_t)0 && type < KMP_HW_LAST)
650 #define KMP_ASSERT_VALID_HW_TYPE(type)                                         \
651   KMP_ASSERT(type >= (kmp_hw_t)0 && type < KMP_HW_LAST)
652 
653 #define KMP_FOREACH_HW_TYPE(type)                                              \
654   for (kmp_hw_t type = (kmp_hw_t)0; type < KMP_HW_LAST;                        \
655        type = (kmp_hw_t)((int)type + 1))
656 
657 const char *__kmp_hw_get_keyword(kmp_hw_t type, bool plural = false);
658 const char *__kmp_hw_get_catalog_string(kmp_hw_t type, bool plural = false);
659 const char *__kmp_hw_get_core_type_string(kmp_hw_core_type_t type);
660 
661 /* Only Linux* OS and Windows* OS support thread affinity. */
662 #if KMP_AFFINITY_SUPPORTED
663 
664 // GROUP_AFFINITY is already defined for _MSC_VER>=1600 (VS2010 and later).
665 #if KMP_OS_WINDOWS
666 #if _MSC_VER < 1600 && KMP_MSVC_COMPAT
667 typedef struct GROUP_AFFINITY {
668   KAFFINITY Mask;
669   WORD Group;
670   WORD Reserved[3];
671 } GROUP_AFFINITY;
672 #endif /* _MSC_VER < 1600 */
673 #if KMP_GROUP_AFFINITY
674 extern int __kmp_num_proc_groups;
675 #else
676 static const int __kmp_num_proc_groups = 1;
677 #endif /* KMP_GROUP_AFFINITY */
678 typedef DWORD (*kmp_GetActiveProcessorCount_t)(WORD);
679 extern kmp_GetActiveProcessorCount_t __kmp_GetActiveProcessorCount;
680 
681 typedef WORD (*kmp_GetActiveProcessorGroupCount_t)(void);
682 extern kmp_GetActiveProcessorGroupCount_t __kmp_GetActiveProcessorGroupCount;
683 
684 typedef BOOL (*kmp_GetThreadGroupAffinity_t)(HANDLE, GROUP_AFFINITY *);
685 extern kmp_GetThreadGroupAffinity_t __kmp_GetThreadGroupAffinity;
686 
687 typedef BOOL (*kmp_SetThreadGroupAffinity_t)(HANDLE, const GROUP_AFFINITY *,
688                                              GROUP_AFFINITY *);
689 extern kmp_SetThreadGroupAffinity_t __kmp_SetThreadGroupAffinity;
690 #endif /* KMP_OS_WINDOWS */
691 
692 #if KMP_USE_HWLOC
693 extern hwloc_topology_t __kmp_hwloc_topology;
694 extern int __kmp_hwloc_error;
695 #endif
696 
697 extern size_t __kmp_affin_mask_size;
698 #define KMP_AFFINITY_CAPABLE() (__kmp_affin_mask_size > 0)
699 #define KMP_AFFINITY_DISABLE() (__kmp_affin_mask_size = 0)
700 #define KMP_AFFINITY_ENABLE(mask_size) (__kmp_affin_mask_size = mask_size)
701 #define KMP_CPU_SET_ITERATE(i, mask)                                           \
702   for (i = (mask)->begin(); (int)i != (mask)->end(); i = (mask)->next(i))
703 #define KMP_CPU_SET(i, mask) (mask)->set(i)
704 #define KMP_CPU_ISSET(i, mask) (mask)->is_set(i)
705 #define KMP_CPU_CLR(i, mask) (mask)->clear(i)
706 #define KMP_CPU_ZERO(mask) (mask)->zero()
707 #define KMP_CPU_ISEMPTY(mask) (mask)->empty()
708 #define KMP_CPU_COPY(dest, src) (dest)->copy(src)
709 #define KMP_CPU_AND(dest, src) (dest)->bitwise_and(src)
710 #define KMP_CPU_COMPLEMENT(max_bit_number, mask) (mask)->bitwise_not()
711 #define KMP_CPU_UNION(dest, src) (dest)->bitwise_or(src)
712 #define KMP_CPU_EQUAL(dest, src) (dest)->is_equal(src)
713 #define KMP_CPU_ALLOC(ptr) (ptr = __kmp_affinity_dispatch->allocate_mask())
714 #define KMP_CPU_FREE(ptr) __kmp_affinity_dispatch->deallocate_mask(ptr)
715 #define KMP_CPU_ALLOC_ON_STACK(ptr) KMP_CPU_ALLOC(ptr)
716 #define KMP_CPU_FREE_FROM_STACK(ptr) KMP_CPU_FREE(ptr)
717 #define KMP_CPU_INTERNAL_ALLOC(ptr) KMP_CPU_ALLOC(ptr)
718 #define KMP_CPU_INTERNAL_FREE(ptr) KMP_CPU_FREE(ptr)
719 #define KMP_CPU_INDEX(arr, i) __kmp_affinity_dispatch->index_mask_array(arr, i)
720 #define KMP_CPU_ALLOC_ARRAY(arr, n)                                            \
721   (arr = __kmp_affinity_dispatch->allocate_mask_array(n))
722 #define KMP_CPU_FREE_ARRAY(arr, n)                                             \
723   __kmp_affinity_dispatch->deallocate_mask_array(arr)
724 #define KMP_CPU_INTERNAL_ALLOC_ARRAY(arr, n) KMP_CPU_ALLOC_ARRAY(arr, n)
725 #define KMP_CPU_INTERNAL_FREE_ARRAY(arr, n) KMP_CPU_FREE_ARRAY(arr, n)
726 #define __kmp_get_system_affinity(mask, abort_bool)                            \
727   (mask)->get_system_affinity(abort_bool)
728 #define __kmp_set_system_affinity(mask, abort_bool)                            \
729   (mask)->set_system_affinity(abort_bool)
730 #define __kmp_get_proc_group(mask) (mask)->get_proc_group()
731 
732 class KMPAffinity {
733 public:
734   class Mask {
735   public:
736     void *operator new(size_t n);
737     void operator delete(void *p);
738     void *operator new[](size_t n);
739     void operator delete[](void *p);
~Mask()740     virtual ~Mask() {}
741     // Set bit i to 1
set(int i)742     virtual void set(int i) {}
743     // Return bit i
is_set(int i)744     virtual bool is_set(int i) const { return false; }
745     // Set bit i to 0
clear(int i)746     virtual void clear(int i) {}
747     // Zero out entire mask
zero()748     virtual void zero() {}
749     // Check whether mask is empty
empty()750     virtual bool empty() const { return true; }
751     // Copy src into this mask
copy(const Mask * src)752     virtual void copy(const Mask *src) {}
753     // this &= rhs
bitwise_and(const Mask * rhs)754     virtual void bitwise_and(const Mask *rhs) {}
755     // this |= rhs
bitwise_or(const Mask * rhs)756     virtual void bitwise_or(const Mask *rhs) {}
757     // this = ~this
bitwise_not()758     virtual void bitwise_not() {}
759     // this == rhs
is_equal(const Mask * rhs)760     virtual bool is_equal(const Mask *rhs) const { return false; }
761     // API for iterating over an affinity mask
762     // for (int i = mask->begin(); i != mask->end(); i = mask->next(i))
begin()763     virtual int begin() const { return 0; }
end()764     virtual int end() const { return 0; }
next(int previous)765     virtual int next(int previous) const { return 0; }
766 #if KMP_OS_WINDOWS
set_process_affinity(bool abort_on_error)767     virtual int set_process_affinity(bool abort_on_error) const { return -1; }
768 #endif
769     // Set the system's affinity to this affinity mask's value
set_system_affinity(bool abort_on_error)770     virtual int set_system_affinity(bool abort_on_error) const { return -1; }
771     // Set this affinity mask to the current system affinity
get_system_affinity(bool abort_on_error)772     virtual int get_system_affinity(bool abort_on_error) { return -1; }
773     // Only 1 DWORD in the mask should have any procs set.
774     // Return the appropriate index, or -1 for an invalid mask.
get_proc_group()775     virtual int get_proc_group() const { return -1; }
get_max_cpu()776     int get_max_cpu() const {
777       int cpu;
778       int max_cpu = -1;
779       KMP_CPU_SET_ITERATE(cpu, this) {
780         if (cpu > max_cpu)
781           max_cpu = cpu;
782       }
783       return max_cpu;
784     }
785   };
786   void *operator new(size_t n);
787   void operator delete(void *p);
788   // Need virtual destructor
789   virtual ~KMPAffinity() = default;
790   // Determine if affinity is capable
determine_capable(const char * env_var)791   virtual void determine_capable(const char *env_var) {}
792   // Bind the current thread to os proc
bind_thread(int proc)793   virtual void bind_thread(int proc) {}
794   // Factory functions to allocate/deallocate a mask
allocate_mask()795   virtual Mask *allocate_mask() { return nullptr; }
deallocate_mask(Mask * m)796   virtual void deallocate_mask(Mask *m) {}
allocate_mask_array(int num)797   virtual Mask *allocate_mask_array(int num) { return nullptr; }
deallocate_mask_array(Mask * m)798   virtual void deallocate_mask_array(Mask *m) {}
index_mask_array(Mask * m,int index)799   virtual Mask *index_mask_array(Mask *m, int index) { return nullptr; }
800   static void pick_api();
801   static void destroy_api();
802   enum api_type {
803     NATIVE_OS
804 #if KMP_USE_HWLOC
805     ,
806     HWLOC
807 #endif
808   };
get_api_type()809   virtual api_type get_api_type() const {
810     KMP_ASSERT(0);
811     return NATIVE_OS;
812   }
813 
814 private:
815   static bool picked_api;
816 };
817 
818 typedef KMPAffinity::Mask kmp_affin_mask_t;
819 extern KMPAffinity *__kmp_affinity_dispatch;
820 
821 #ifndef KMP_OS_AIX
822 class kmp_affinity_raii_t {
823   kmp_affin_mask_t *mask;
824   bool restored;
825 
826 public:
827   kmp_affinity_raii_t(const kmp_affin_mask_t *new_mask = nullptr)
restored(false)828       : restored(false) {
829     if (KMP_AFFINITY_CAPABLE()) {
830       KMP_CPU_ALLOC(mask);
831       KMP_ASSERT(mask != NULL);
832       __kmp_get_system_affinity(mask, /*abort_on_error=*/true);
833       if (new_mask)
834         __kmp_set_system_affinity(new_mask, /*abort_on_error=*/true);
835     }
836   }
restore()837   void restore() {
838     if (!restored && KMP_AFFINITY_CAPABLE()) {
839       __kmp_set_system_affinity(mask, /*abort_on_error=*/true);
840       KMP_CPU_FREE(mask);
841     }
842     restored = true;
843   }
~kmp_affinity_raii_t()844   ~kmp_affinity_raii_t() { restore(); }
845 };
846 #endif // !KMP_OS_AIX
847 
848 // Declare local char buffers with this size for printing debug and info
849 // messages, using __kmp_affinity_print_mask().
850 #define KMP_AFFIN_MASK_PRINT_LEN 1024
851 
852 enum affinity_type {
853   affinity_none = 0,
854   affinity_physical,
855   affinity_logical,
856   affinity_compact,
857   affinity_scatter,
858   affinity_explicit,
859   affinity_balanced,
860   affinity_disabled, // not used outsize the env var parser
861   affinity_default
862 };
863 
864 enum affinity_top_method {
865   affinity_top_method_all = 0, // try all (supported) methods, in order
866 #if KMP_ARCH_X86 || KMP_ARCH_X86_64
867   affinity_top_method_apicid,
868   affinity_top_method_x2apicid,
869   affinity_top_method_x2apicid_1f,
870 #endif /* KMP_ARCH_X86 || KMP_ARCH_X86_64 */
871   affinity_top_method_cpuinfo, // KMP_CPUINFO_FILE is usable on Windows* OS, too
872 #if KMP_GROUP_AFFINITY
873   affinity_top_method_group,
874 #endif /* KMP_GROUP_AFFINITY */
875   affinity_top_method_flat,
876 #if KMP_USE_HWLOC
877   affinity_top_method_hwloc,
878 #endif
879   affinity_top_method_default
880 };
881 
882 #define affinity_respect_mask_default (2)
883 
884 typedef struct kmp_affinity_flags_t {
885   unsigned dups : 1;
886   unsigned verbose : 1;
887   unsigned warnings : 1;
888   unsigned respect : 2;
889   unsigned reset : 1;
890   unsigned initialized : 1;
891   unsigned core_types_gran : 1;
892   unsigned core_effs_gran : 1;
893   unsigned omp_places : 1;
894   unsigned reserved : 22;
895 } kmp_affinity_flags_t;
896 KMP_BUILD_ASSERT(sizeof(kmp_affinity_flags_t) == 4);
897 
898 typedef struct kmp_affinity_ids_t {
899   int os_id;
900   int ids[KMP_HW_LAST];
901 } kmp_affinity_ids_t;
902 
903 typedef struct kmp_affinity_attrs_t {
904   int core_type : 8;
905   int core_eff : 8;
906   unsigned valid : 1;
907   unsigned reserved : 15;
908 } kmp_affinity_attrs_t;
909 #define KMP_AFFINITY_ATTRS_UNKNOWN                                             \
910   { KMP_HW_CORE_TYPE_UNKNOWN, kmp_hw_attr_t::UNKNOWN_CORE_EFF, 0, 0 }
911 
912 typedef struct kmp_affinity_t {
913   char *proclist;
914   enum affinity_type type;
915   kmp_hw_t gran;
916   int gran_levels;
917   kmp_affinity_attrs_t core_attr_gran;
918   int compact;
919   int offset;
920   kmp_affinity_flags_t flags;
921   unsigned num_masks;
922   kmp_affin_mask_t *masks;
923   kmp_affinity_ids_t *ids;
924   kmp_affinity_attrs_t *attrs;
925   unsigned num_os_id_masks;
926   kmp_affin_mask_t *os_id_masks;
927   const char *env_var;
928 } kmp_affinity_t;
929 
930 #define KMP_AFFINITY_INIT(env)                                                 \
931   {                                                                            \
932     nullptr, affinity_default, KMP_HW_UNKNOWN, -1, KMP_AFFINITY_ATTRS_UNKNOWN, \
933         0, 0,                                                                  \
934         {TRUE,  FALSE, TRUE, affinity_respect_mask_default, FALSE, FALSE,      \
935          FALSE, FALSE, FALSE},                                                 \
936         0, nullptr, nullptr, nullptr, 0, nullptr, env                          \
937   }
938 
939 extern enum affinity_top_method __kmp_affinity_top_method;
940 extern kmp_affinity_t __kmp_affinity;
941 extern kmp_affinity_t __kmp_hh_affinity;
942 extern kmp_affinity_t *__kmp_affinities[2];
943 
944 extern void __kmp_affinity_bind_thread(int which);
945 
946 extern kmp_affin_mask_t *__kmp_affin_fullMask;
947 extern kmp_affin_mask_t *__kmp_affin_origMask;
948 extern char *__kmp_cpuinfo_file;
949 
950 #if KMP_WEIGHTED_ITERATIONS_SUPPORTED
951 extern int __kmp_first_osid_with_ecore;
952 #endif
953 
954 #endif /* KMP_AFFINITY_SUPPORTED */
955 
956 // This needs to be kept in sync with the values in omp.h !!!
957 typedef enum kmp_proc_bind_t {
958   proc_bind_false = 0,
959   proc_bind_true,
960   proc_bind_primary,
961   proc_bind_close,
962   proc_bind_spread,
963   proc_bind_intel, // use KMP_AFFINITY interface
964   proc_bind_default
965 } kmp_proc_bind_t;
966 
967 typedef struct kmp_nested_proc_bind_t {
968   kmp_proc_bind_t *bind_types;
969   int size;
970   int used;
971 } kmp_nested_proc_bind_t;
972 
973 extern kmp_nested_proc_bind_t __kmp_nested_proc_bind;
974 extern kmp_proc_bind_t __kmp_teams_proc_bind;
975 
976 extern int __kmp_display_affinity;
977 extern char *__kmp_affinity_format;
978 static const size_t KMP_AFFINITY_FORMAT_SIZE = 512;
979 #if OMPT_SUPPORT
980 extern int __kmp_tool;
981 extern char *__kmp_tool_libraries;
982 #endif // OMPT_SUPPORT
983 
984 #if KMP_AFFINITY_SUPPORTED
985 #define KMP_PLACE_ALL (-1)
986 #define KMP_PLACE_UNDEFINED (-2)
987 // Is KMP_AFFINITY is being used instead of OMP_PROC_BIND/OMP_PLACES?
988 #define KMP_AFFINITY_NON_PROC_BIND                                             \
989   ((__kmp_nested_proc_bind.bind_types[0] == proc_bind_false ||                 \
990     __kmp_nested_proc_bind.bind_types[0] == proc_bind_intel) &&                \
991    (__kmp_affinity.num_masks > 0 || __kmp_affinity.type == affinity_balanced))
992 #endif /* KMP_AFFINITY_SUPPORTED */
993 
994 extern int __kmp_affinity_num_places;
995 
996 typedef enum kmp_cancel_kind_t {
997   cancel_noreq = 0,
998   cancel_parallel = 1,
999   cancel_loop = 2,
1000   cancel_sections = 3,
1001   cancel_taskgroup = 4
1002 } kmp_cancel_kind_t;
1003 
1004 // KMP_HW_SUBSET support:
1005 typedef struct kmp_hws_item {
1006   int num;
1007   int offset;
1008 } kmp_hws_item_t;
1009 
1010 extern kmp_hws_item_t __kmp_hws_socket;
1011 extern kmp_hws_item_t __kmp_hws_die;
1012 extern kmp_hws_item_t __kmp_hws_node;
1013 extern kmp_hws_item_t __kmp_hws_tile;
1014 extern kmp_hws_item_t __kmp_hws_core;
1015 extern kmp_hws_item_t __kmp_hws_proc;
1016 extern int __kmp_hws_requested;
1017 extern int __kmp_hws_abs_flag; // absolute or per-item number requested
1018 
1019 /* ------------------------------------------------------------------------ */
1020 
1021 #define KMP_PAD(type, sz)                                                      \
1022   (sizeof(type) + (sz - ((sizeof(type) - 1) % (sz)) - 1))
1023 
1024 // We need to avoid using -1 as a GTID as +1 is added to the gtid
1025 // when storing it in a lock, and the value 0 is reserved.
1026 #define KMP_GTID_DNE (-2) /* Does not exist */
1027 #define KMP_GTID_SHUTDOWN (-3) /* Library is shutting down */
1028 #define KMP_GTID_MONITOR (-4) /* Monitor thread ID */
1029 #define KMP_GTID_UNKNOWN (-5) /* Is not known */
1030 #define KMP_GTID_MIN (-6) /* Minimal gtid for low bound check in DEBUG */
1031 
1032 /* OpenMP 5.0 Memory Management support */
1033 
1034 #ifndef __OMP_H
1035 // Duplicate type definitions from omp.h
1036 typedef uintptr_t omp_uintptr_t;
1037 
1038 typedef enum {
1039   omp_atk_sync_hint = 1,
1040   omp_atk_alignment = 2,
1041   omp_atk_access = 3,
1042   omp_atk_pool_size = 4,
1043   omp_atk_fallback = 5,
1044   omp_atk_fb_data = 6,
1045   omp_atk_pinned = 7,
1046   omp_atk_partition = 8
1047 } omp_alloctrait_key_t;
1048 
1049 typedef enum {
1050   omp_atv_false = 0,
1051   omp_atv_true = 1,
1052   omp_atv_contended = 3,
1053   omp_atv_uncontended = 4,
1054   omp_atv_serialized = 5,
1055   omp_atv_sequential = omp_atv_serialized, // (deprecated)
1056   omp_atv_private = 6,
1057   omp_atv_all = 7,
1058   omp_atv_thread = 8,
1059   omp_atv_pteam = 9,
1060   omp_atv_cgroup = 10,
1061   omp_atv_default_mem_fb = 11,
1062   omp_atv_null_fb = 12,
1063   omp_atv_abort_fb = 13,
1064   omp_atv_allocator_fb = 14,
1065   omp_atv_environment = 15,
1066   omp_atv_nearest = 16,
1067   omp_atv_blocked = 17,
1068   omp_atv_interleaved = 18
1069 } omp_alloctrait_value_t;
1070 #define omp_atv_default ((omp_uintptr_t)-1)
1071 
1072 typedef void *omp_memspace_handle_t;
1073 extern omp_memspace_handle_t const omp_default_mem_space;
1074 extern omp_memspace_handle_t const omp_large_cap_mem_space;
1075 extern omp_memspace_handle_t const omp_const_mem_space;
1076 extern omp_memspace_handle_t const omp_high_bw_mem_space;
1077 extern omp_memspace_handle_t const omp_low_lat_mem_space;
1078 extern omp_memspace_handle_t const llvm_omp_target_host_mem_space;
1079 extern omp_memspace_handle_t const llvm_omp_target_shared_mem_space;
1080 extern omp_memspace_handle_t const llvm_omp_target_device_mem_space;
1081 
1082 typedef struct {
1083   omp_alloctrait_key_t key;
1084   omp_uintptr_t value;
1085 } omp_alloctrait_t;
1086 
1087 typedef void *omp_allocator_handle_t;
1088 extern omp_allocator_handle_t const omp_null_allocator;
1089 extern omp_allocator_handle_t const omp_default_mem_alloc;
1090 extern omp_allocator_handle_t const omp_large_cap_mem_alloc;
1091 extern omp_allocator_handle_t const omp_const_mem_alloc;
1092 extern omp_allocator_handle_t const omp_high_bw_mem_alloc;
1093 extern omp_allocator_handle_t const omp_low_lat_mem_alloc;
1094 extern omp_allocator_handle_t const omp_cgroup_mem_alloc;
1095 extern omp_allocator_handle_t const omp_pteam_mem_alloc;
1096 extern omp_allocator_handle_t const omp_thread_mem_alloc;
1097 extern omp_allocator_handle_t const llvm_omp_target_host_mem_alloc;
1098 extern omp_allocator_handle_t const llvm_omp_target_shared_mem_alloc;
1099 extern omp_allocator_handle_t const llvm_omp_target_device_mem_alloc;
1100 extern omp_allocator_handle_t const kmp_max_mem_alloc;
1101 extern omp_allocator_handle_t __kmp_def_allocator;
1102 
1103 // end of duplicate type definitions from omp.h
1104 #endif
1105 
1106 extern int __kmp_memkind_available;
1107 
1108 typedef omp_memspace_handle_t kmp_memspace_t; // placeholder
1109 
1110 typedef struct kmp_allocator_t {
1111   omp_memspace_handle_t memspace;
1112   void **memkind; // pointer to memkind
1113   size_t alignment;
1114   omp_alloctrait_value_t fb;
1115   kmp_allocator_t *fb_data;
1116   kmp_uint64 pool_size;
1117   kmp_uint64 pool_used;
1118   bool pinned;
1119 } kmp_allocator_t;
1120 
1121 extern omp_allocator_handle_t __kmpc_init_allocator(int gtid,
1122                                                     omp_memspace_handle_t,
1123                                                     int ntraits,
1124                                                     omp_alloctrait_t traits[]);
1125 extern void __kmpc_destroy_allocator(int gtid, omp_allocator_handle_t al);
1126 extern void __kmpc_set_default_allocator(int gtid, omp_allocator_handle_t al);
1127 extern omp_allocator_handle_t __kmpc_get_default_allocator(int gtid);
1128 // external interfaces, may be used by compiler
1129 extern void *__kmpc_alloc(int gtid, size_t sz, omp_allocator_handle_t al);
1130 extern void *__kmpc_aligned_alloc(int gtid, size_t align, size_t sz,
1131                                   omp_allocator_handle_t al);
1132 extern void *__kmpc_calloc(int gtid, size_t nmemb, size_t sz,
1133                            omp_allocator_handle_t al);
1134 extern void *__kmpc_realloc(int gtid, void *ptr, size_t sz,
1135                             omp_allocator_handle_t al,
1136                             omp_allocator_handle_t free_al);
1137 extern void __kmpc_free(int gtid, void *ptr, omp_allocator_handle_t al);
1138 // internal interfaces, contain real implementation
1139 extern void *__kmp_alloc(int gtid, size_t align, size_t sz,
1140                          omp_allocator_handle_t al);
1141 extern void *__kmp_calloc(int gtid, size_t align, size_t nmemb, size_t sz,
1142                           omp_allocator_handle_t al);
1143 extern void *__kmp_realloc(int gtid, void *ptr, size_t sz,
1144                            omp_allocator_handle_t al,
1145                            omp_allocator_handle_t free_al);
1146 extern void ___kmpc_free(int gtid, void *ptr, omp_allocator_handle_t al);
1147 
1148 extern void __kmp_init_memkind();
1149 extern void __kmp_fini_memkind();
1150 extern void __kmp_init_target_mem();
1151 
1152 /* ------------------------------------------------------------------------ */
1153 
1154 #if ENABLE_LIBOMPTARGET
1155 extern void __kmp_init_target_task();
1156 #endif
1157 
1158 /* ------------------------------------------------------------------------ */
1159 
1160 #define KMP_UINT64_MAX                                                         \
1161   (~((kmp_uint64)1 << ((sizeof(kmp_uint64) * (1 << 3)) - 1)))
1162 
1163 #define KMP_MIN_NTH 1
1164 
1165 #ifndef KMP_MAX_NTH
1166 #if defined(PTHREAD_THREADS_MAX) && PTHREAD_THREADS_MAX < INT_MAX
1167 #define KMP_MAX_NTH PTHREAD_THREADS_MAX
1168 #else
1169 #ifdef __ve__
1170 // VE's pthread supports only up to 64 threads per a VE process.
1171 // Please check p. 14 of following documentation for more details.
1172 // https://sxauroratsubasa.sakura.ne.jp/documents/veos/en/VEOS_high_level_design.pdf
1173 #define KMP_MAX_NTH 64
1174 #else
1175 #define KMP_MAX_NTH INT_MAX
1176 #endif
1177 #endif
1178 #endif /* KMP_MAX_NTH */
1179 
1180 #ifdef PTHREAD_STACK_MIN
1181 #define KMP_MIN_STKSIZE ((size_t)PTHREAD_STACK_MIN)
1182 #else
1183 #define KMP_MIN_STKSIZE ((size_t)(32 * 1024))
1184 #endif
1185 
1186 #if KMP_OS_AIX && KMP_ARCH_PPC
1187 #define KMP_MAX_STKSIZE 0x10000000 /* 256Mb max size on 32-bit AIX */
1188 #else
1189 #define KMP_MAX_STKSIZE (~((size_t)1 << ((sizeof(size_t) * (1 << 3)) - 1)))
1190 #endif
1191 
1192 #if KMP_ARCH_X86
1193 #define KMP_DEFAULT_STKSIZE ((size_t)(2 * 1024 * 1024))
1194 #elif KMP_ARCH_X86_64
1195 #define KMP_DEFAULT_STKSIZE ((size_t)(4 * 1024 * 1024))
1196 #define KMP_BACKUP_STKSIZE ((size_t)(2 * 1024 * 1024))
1197 #elif KMP_ARCH_VE
1198 // Minimum stack size for pthread for VE is 4MB.
1199 //   https://www.hpc.nec/documents/veos/en/glibc/Difference_Points_glibc.htm
1200 #define KMP_DEFAULT_STKSIZE ((size_t)(4 * 1024 * 1024))
1201 #elif KMP_OS_AIX
1202 // The default stack size for worker threads on AIX is 4MB.
1203 #define KMP_DEFAULT_STKSIZE ((size_t)(4 * 1024 * 1024))
1204 #else
1205 #define KMP_DEFAULT_STKSIZE ((size_t)(1024 * 1024))
1206 #endif
1207 
1208 #define KMP_DEFAULT_MALLOC_POOL_INCR ((size_t)(1024 * 1024))
1209 #define KMP_MIN_MALLOC_POOL_INCR ((size_t)(4 * 1024))
1210 #define KMP_MAX_MALLOC_POOL_INCR                                               \
1211   (~((size_t)1 << ((sizeof(size_t) * (1 << 3)) - 1)))
1212 
1213 #define KMP_MIN_STKOFFSET (0)
1214 #define KMP_MAX_STKOFFSET KMP_MAX_STKSIZE
1215 #if KMP_OS_DARWIN
1216 #define KMP_DEFAULT_STKOFFSET KMP_MIN_STKOFFSET
1217 #else
1218 #define KMP_DEFAULT_STKOFFSET CACHE_LINE
1219 #endif
1220 
1221 #define KMP_MIN_STKPADDING (0)
1222 #define KMP_MAX_STKPADDING (2 * 1024 * 1024)
1223 
1224 #define KMP_BLOCKTIME_MULTIPLIER                                               \
1225   (1000000) /* number of blocktime units per second */
1226 #define KMP_MIN_BLOCKTIME (0)
1227 #define KMP_MAX_BLOCKTIME                                                      \
1228   (INT_MAX) /* Must be this for "infinite" setting the work */
1229 
1230 /* __kmp_blocktime is in microseconds */
1231 #define KMP_DEFAULT_BLOCKTIME (__kmp_is_hybrid_cpu() ? (0) : (200000))
1232 
1233 #if KMP_USE_MONITOR
1234 #define KMP_DEFAULT_MONITOR_STKSIZE ((size_t)(64 * 1024))
1235 #define KMP_MIN_MONITOR_WAKEUPS (1) // min times monitor wakes up per second
1236 #define KMP_MAX_MONITOR_WAKEUPS (1000) // max times monitor can wake up per sec
1237 
1238 /* Calculate new number of monitor wakeups for a specific block time based on
1239    previous monitor_wakeups. Only allow increasing number of wakeups */
1240 #define KMP_WAKEUPS_FROM_BLOCKTIME(blocktime, monitor_wakeups)                 \
1241   (((blocktime) == KMP_MAX_BLOCKTIME)   ? (monitor_wakeups)                    \
1242    : ((blocktime) == KMP_MIN_BLOCKTIME) ? KMP_MAX_MONITOR_WAKEUPS              \
1243    : ((monitor_wakeups) > (KMP_BLOCKTIME_MULTIPLIER / (blocktime)))            \
1244        ? (monitor_wakeups)                                                     \
1245        : (KMP_BLOCKTIME_MULTIPLIER) / (blocktime))
1246 
1247 /* Calculate number of intervals for a specific block time based on
1248    monitor_wakeups */
1249 #define KMP_INTERVALS_FROM_BLOCKTIME(blocktime, monitor_wakeups)               \
1250   (((blocktime) + (KMP_BLOCKTIME_MULTIPLIER / (monitor_wakeups)) - 1) /        \
1251    (KMP_BLOCKTIME_MULTIPLIER / (monitor_wakeups)))
1252 #else
1253 #define KMP_BLOCKTIME(team, tid)                                               \
1254   (get__bt_set(team, tid) ? get__blocktime(team, tid) : __kmp_dflt_blocktime)
1255 #if KMP_OS_UNIX && (KMP_ARCH_X86 || KMP_ARCH_X86_64)
1256 // HW TSC is used to reduce overhead (clock tick instead of nanosecond).
1257 extern kmp_uint64 __kmp_ticks_per_msec;
1258 extern kmp_uint64 __kmp_ticks_per_usec;
1259 #if KMP_COMPILER_ICC || KMP_COMPILER_ICX
1260 #define KMP_NOW() ((kmp_uint64)_rdtsc())
1261 #else
1262 #define KMP_NOW() __kmp_hardware_timestamp()
1263 #endif
1264 #define KMP_BLOCKTIME_INTERVAL(team, tid)                                      \
1265   ((kmp_uint64)KMP_BLOCKTIME(team, tid) * __kmp_ticks_per_usec)
1266 #define KMP_BLOCKING(goal, count) ((goal) > KMP_NOW())
1267 #else
1268 // System time is retrieved sporadically while blocking.
1269 extern kmp_uint64 __kmp_now_nsec();
1270 #define KMP_NOW() __kmp_now_nsec()
1271 #define KMP_BLOCKTIME_INTERVAL(team, tid)                                      \
1272   ((kmp_uint64)KMP_BLOCKTIME(team, tid) * (kmp_uint64)KMP_NSEC_PER_USEC)
1273 #define KMP_BLOCKING(goal, count) ((count) % 1000 != 0 || (goal) > KMP_NOW())
1274 #endif
1275 #endif // KMP_USE_MONITOR
1276 
1277 #define KMP_MIN_STATSCOLS 40
1278 #define KMP_MAX_STATSCOLS 4096
1279 #define KMP_DEFAULT_STATSCOLS 80
1280 
1281 #define KMP_MIN_INTERVAL 0
1282 #define KMP_MAX_INTERVAL (INT_MAX - 1)
1283 #define KMP_DEFAULT_INTERVAL 0
1284 
1285 #define KMP_MIN_CHUNK 1
1286 #define KMP_MAX_CHUNK (INT_MAX - 1)
1287 #define KMP_DEFAULT_CHUNK 1
1288 
1289 #define KMP_MIN_DISP_NUM_BUFF 1
1290 #define KMP_DFLT_DISP_NUM_BUFF 7
1291 #define KMP_MAX_DISP_NUM_BUFF 4096
1292 
1293 #define KMP_MAX_ORDERED 8
1294 
1295 #define KMP_MAX_FIELDS 32
1296 
1297 #define KMP_MAX_BRANCH_BITS 31
1298 
1299 #define KMP_MAX_ACTIVE_LEVELS_LIMIT INT_MAX
1300 
1301 #define KMP_MAX_DEFAULT_DEVICE_LIMIT INT_MAX
1302 
1303 #define KMP_MAX_TASK_PRIORITY_LIMIT INT_MAX
1304 
1305 /* Minimum number of threads before switch to TLS gtid (experimentally
1306    determined) */
1307 /* josh TODO: what about OS X* tuning? */
1308 #if KMP_ARCH_X86 || KMP_ARCH_X86_64
1309 #define KMP_TLS_GTID_MIN 5
1310 #else
1311 #define KMP_TLS_GTID_MIN INT_MAX
1312 #endif
1313 
1314 #define KMP_MASTER_TID(tid) (0 == (tid))
1315 #define KMP_WORKER_TID(tid) (0 != (tid))
1316 
1317 #define KMP_MASTER_GTID(gtid) (0 == __kmp_tid_from_gtid((gtid)))
1318 #define KMP_WORKER_GTID(gtid) (0 != __kmp_tid_from_gtid((gtid)))
1319 #define KMP_INITIAL_GTID(gtid) (0 == (gtid))
1320 
1321 #ifndef TRUE
1322 #define FALSE 0
1323 #define TRUE (!FALSE)
1324 #endif
1325 
1326 /* NOTE: all of the following constants must be even */
1327 
1328 #if KMP_OS_WINDOWS
1329 #define KMP_INIT_WAIT 64U /* initial number of spin-tests   */
1330 #define KMP_NEXT_WAIT 32U /* susequent number of spin-tests */
1331 #elif KMP_OS_LINUX
1332 #define KMP_INIT_WAIT 1024U /* initial number of spin-tests   */
1333 #define KMP_NEXT_WAIT 512U /* susequent number of spin-tests */
1334 #elif KMP_OS_DARWIN
1335 /* TODO: tune for KMP_OS_DARWIN */
1336 #define KMP_INIT_WAIT 1024U /* initial number of spin-tests   */
1337 #define KMP_NEXT_WAIT 512U /* susequent number of spin-tests */
1338 #elif KMP_OS_DRAGONFLY
1339 /* TODO: tune for KMP_OS_DRAGONFLY */
1340 #define KMP_INIT_WAIT 1024U /* initial number of spin-tests   */
1341 #define KMP_NEXT_WAIT 512U /* susequent number of spin-tests */
1342 #elif KMP_OS_FREEBSD
1343 /* TODO: tune for KMP_OS_FREEBSD */
1344 #define KMP_INIT_WAIT 1024U /* initial number of spin-tests   */
1345 #define KMP_NEXT_WAIT 512U /* susequent number of spin-tests */
1346 #elif KMP_OS_NETBSD
1347 /* TODO: tune for KMP_OS_NETBSD */
1348 #define KMP_INIT_WAIT 1024U /* initial number of spin-tests   */
1349 #define KMP_NEXT_WAIT 512U /* susequent number of spin-tests */
1350 #elif KMP_OS_OPENBSD
1351 /* TODO: tune for KMP_OS_OPENBSD */
1352 #define KMP_INIT_WAIT 1024U /* initial number of spin-tests   */
1353 #define KMP_NEXT_WAIT 512U /* susequent number of spin-tests */
1354 #elif KMP_OS_HURD
1355 /* TODO: tune for KMP_OS_HURD */
1356 #define KMP_INIT_WAIT 1024U /* initial number of spin-tests   */
1357 #define KMP_NEXT_WAIT 512U /* susequent number of spin-tests */
1358 #elif KMP_OS_SOLARIS
1359 /* TODO: tune for KMP_OS_SOLARIS */
1360 #define KMP_INIT_WAIT 1024U /* initial number of spin-tests   */
1361 #define KMP_NEXT_WAIT 512U /* susequent number of spin-tests */
1362 #elif KMP_OS_WASI
1363 /* TODO: tune for KMP_OS_WASI */
1364 #define KMP_INIT_WAIT 1024U /* initial number of spin-tests   */
1365 #define KMP_NEXT_WAIT 512U /* susequent number of spin-tests */
1366 #elif KMP_OS_AIX
1367 /* TODO: tune for KMP_OS_AIX */
1368 #define KMP_INIT_WAIT 1024U /* initial number of spin-tests   */
1369 #define KMP_NEXT_WAIT 512U /* susequent number of spin-tests */
1370 #endif
1371 
1372 #if KMP_ARCH_X86 || KMP_ARCH_X86_64
1373 typedef struct kmp_cpuid {
1374   kmp_uint32 eax;
1375   kmp_uint32 ebx;
1376   kmp_uint32 ecx;
1377   kmp_uint32 edx;
1378 } kmp_cpuid_t;
1379 
1380 typedef struct kmp_cpuinfo_flags_t {
1381   unsigned sse2 : 1; // 0 if SSE2 instructions are not supported, 1 otherwise.
1382   unsigned rtm : 1; // 0 if RTM instructions are not supported, 1 otherwise.
1383   unsigned hybrid : 1;
1384   unsigned reserved : 29; // Ensure size of 32 bits
1385 } kmp_cpuinfo_flags_t;
1386 
1387 typedef struct kmp_cpuinfo {
1388   int initialized; // If 0, other fields are not initialized.
1389   int signature; // CPUID(1).EAX
1390   int family; // CPUID(1).EAX[27:20]+CPUID(1).EAX[11:8] (Extended Family+Family)
1391   int model; // ( CPUID(1).EAX[19:16] << 4 ) + CPUID(1).EAX[7:4] ( ( Extended
1392   // Model << 4 ) + Model)
1393   int stepping; // CPUID(1).EAX[3:0] ( Stepping )
1394   kmp_cpuinfo_flags_t flags;
1395   int apic_id;
1396   int physical_id;
1397   int logical_id;
1398   kmp_uint64 frequency; // Nominal CPU frequency in Hz.
1399   char name[3 * sizeof(kmp_cpuid_t)]; // CPUID(0x80000002,0x80000003,0x80000004)
1400 } kmp_cpuinfo_t;
1401 
1402 extern void __kmp_query_cpuid(kmp_cpuinfo_t *p);
1403 
1404 #if KMP_OS_UNIX
1405 // subleaf is only needed for cache and topology discovery and can be set to
1406 // zero in most cases
__kmp_x86_cpuid(int leaf,int subleaf,struct kmp_cpuid * p)1407 static inline void __kmp_x86_cpuid(int leaf, int subleaf, struct kmp_cpuid *p) {
1408   __asm__ __volatile__("cpuid"
1409                        : "=a"(p->eax), "=b"(p->ebx), "=c"(p->ecx), "=d"(p->edx)
1410                        : "a"(leaf), "c"(subleaf));
1411 }
1412 // Load p into FPU control word
__kmp_load_x87_fpu_control_word(const kmp_int16 * p)1413 static inline void __kmp_load_x87_fpu_control_word(const kmp_int16 *p) {
1414   __asm__ __volatile__("fldcw %0" : : "m"(*p));
1415 }
1416 // Store FPU control word into p
__kmp_store_x87_fpu_control_word(kmp_int16 * p)1417 static inline void __kmp_store_x87_fpu_control_word(kmp_int16 *p) {
1418   __asm__ __volatile__("fstcw %0" : "=m"(*p));
1419 }
__kmp_clear_x87_fpu_status_word()1420 static inline void __kmp_clear_x87_fpu_status_word() {
1421 #if KMP_MIC
1422   // 32-bit protected mode x87 FPU state
1423   struct x87_fpu_state {
1424     unsigned cw;
1425     unsigned sw;
1426     unsigned tw;
1427     unsigned fip;
1428     unsigned fips;
1429     unsigned fdp;
1430     unsigned fds;
1431   };
1432   struct x87_fpu_state fpu_state = {0, 0, 0, 0, 0, 0, 0};
1433   __asm__ __volatile__("fstenv %0\n\t" // store FP env
1434                        "andw $0x7f00, %1\n\t" // clear 0-7,15 bits of FP SW
1435                        "fldenv %0\n\t" // load FP env back
1436                        : "+m"(fpu_state), "+m"(fpu_state.sw));
1437 #else
1438   __asm__ __volatile__("fnclex");
1439 #endif // KMP_MIC
1440 }
1441 #if __SSE__
__kmp_load_mxcsr(const kmp_uint32 * p)1442 static inline void __kmp_load_mxcsr(const kmp_uint32 *p) { _mm_setcsr(*p); }
__kmp_store_mxcsr(kmp_uint32 * p)1443 static inline void __kmp_store_mxcsr(kmp_uint32 *p) { *p = _mm_getcsr(); }
1444 #else
__kmp_load_mxcsr(const kmp_uint32 * p)1445 static inline void __kmp_load_mxcsr(const kmp_uint32 *p) {}
__kmp_store_mxcsr(kmp_uint32 * p)1446 static inline void __kmp_store_mxcsr(kmp_uint32 *p) { *p = 0; }
1447 #endif
1448 #else
1449 // Windows still has these as external functions in assembly file
1450 extern void __kmp_x86_cpuid(int mode, int mode2, struct kmp_cpuid *p);
1451 extern void __kmp_load_x87_fpu_control_word(const kmp_int16 *p);
1452 extern void __kmp_store_x87_fpu_control_word(kmp_int16 *p);
1453 extern void __kmp_clear_x87_fpu_status_word();
__kmp_load_mxcsr(const kmp_uint32 * p)1454 static inline void __kmp_load_mxcsr(const kmp_uint32 *p) { _mm_setcsr(*p); }
__kmp_store_mxcsr(kmp_uint32 * p)1455 static inline void __kmp_store_mxcsr(kmp_uint32 *p) { *p = _mm_getcsr(); }
1456 #endif // KMP_OS_UNIX
1457 
1458 #define KMP_X86_MXCSR_MASK 0xffffffc0 /* ignore status flags (6 lsb) */
1459 
1460 // User-level Monitor/Mwait
1461 #if KMP_HAVE_UMWAIT
1462 // We always try for UMWAIT first
1463 #if KMP_HAVE_WAITPKG_INTRINSICS
1464 #if KMP_HAVE_IMMINTRIN_H
1465 #include <immintrin.h>
1466 #elif KMP_HAVE_INTRIN_H
1467 #include <intrin.h>
1468 #endif
1469 #endif // KMP_HAVE_WAITPKG_INTRINSICS
1470 
1471 KMP_ATTRIBUTE_TARGET_WAITPKG
__kmp_tpause(uint32_t hint,uint64_t counter)1472 static inline int __kmp_tpause(uint32_t hint, uint64_t counter) {
1473 #if !KMP_HAVE_WAITPKG_INTRINSICS
1474   uint32_t timeHi = uint32_t(counter >> 32);
1475   uint32_t timeLo = uint32_t(counter & 0xffffffff);
1476   char flag;
1477   __asm__ volatile("#tpause\n.byte 0x66, 0x0F, 0xAE, 0xF1\n"
1478                    "setb   %0"
1479                    // The "=q" restraint means any register accessible as rl
1480                    //   in 32-bit mode: a, b, c, and d;
1481                    //   in 64-bit mode: any integer register
1482                    : "=q"(flag)
1483                    : "a"(timeLo), "d"(timeHi), "c"(hint)
1484                    :);
1485   return flag;
1486 #else
1487   return _tpause(hint, counter);
1488 #endif
1489 }
1490 KMP_ATTRIBUTE_TARGET_WAITPKG
__kmp_umonitor(void * cacheline)1491 static inline void __kmp_umonitor(void *cacheline) {
1492 #if !KMP_HAVE_WAITPKG_INTRINSICS
1493   __asm__ volatile("# umonitor\n.byte 0xF3, 0x0F, 0xAE, 0x01 "
1494                    :
1495                    : "a"(cacheline)
1496                    :);
1497 #else
1498   _umonitor(cacheline);
1499 #endif
1500 }
1501 KMP_ATTRIBUTE_TARGET_WAITPKG
__kmp_umwait(uint32_t hint,uint64_t counter)1502 static inline int __kmp_umwait(uint32_t hint, uint64_t counter) {
1503 #if !KMP_HAVE_WAITPKG_INTRINSICS
1504   uint32_t timeHi = uint32_t(counter >> 32);
1505   uint32_t timeLo = uint32_t(counter & 0xffffffff);
1506   char flag;
1507   __asm__ volatile("#umwait\n.byte 0xF2, 0x0F, 0xAE, 0xF1\n"
1508                    "setb   %0"
1509                    // The "=q" restraint means any register accessible as rl
1510                    //   in 32-bit mode: a, b, c, and d;
1511                    //   in 64-bit mode: any integer register
1512                    : "=q"(flag)
1513                    : "a"(timeLo), "d"(timeHi), "c"(hint)
1514                    :);
1515   return flag;
1516 #else
1517   return _umwait(hint, counter);
1518 #endif
1519 }
1520 #elif KMP_HAVE_MWAIT
1521 #if KMP_OS_UNIX
1522 #include <pmmintrin.h>
1523 #else
1524 #include <intrin.h>
1525 #endif
1526 #if KMP_OS_UNIX
1527 __attribute__((target("sse3")))
1528 #endif
1529 static inline void
__kmp_mm_monitor(void * cacheline,unsigned extensions,unsigned hints)1530 __kmp_mm_monitor(void *cacheline, unsigned extensions, unsigned hints) {
1531   _mm_monitor(cacheline, extensions, hints);
1532 }
1533 #if KMP_OS_UNIX
1534 __attribute__((target("sse3")))
1535 #endif
1536 static inline void
__kmp_mm_mwait(unsigned extensions,unsigned hints)1537 __kmp_mm_mwait(unsigned extensions, unsigned hints) {
1538   _mm_mwait(extensions, hints);
1539 }
1540 #endif // KMP_HAVE_UMWAIT
1541 
1542 #if KMP_ARCH_X86
1543 extern void __kmp_x86_pause(void);
1544 #elif KMP_MIC
1545 // Performance testing on KNC (C0QS-7120 P/A/X/D, 61-core, 16 GB Memory) showed
1546 // regression after removal of extra PAUSE from spin loops. Changing
1547 // the delay from 100 to 300 showed even better performance than double PAUSE
1548 // on Spec OMP2001 and LCPC tasking tests, no regressions on EPCC.
__kmp_x86_pause(void)1549 static inline void __kmp_x86_pause(void) { _mm_delay_32(300); }
1550 #else
__kmp_x86_pause(void)1551 static inline void __kmp_x86_pause(void) { _mm_pause(); }
1552 #endif
1553 #define KMP_CPU_PAUSE() __kmp_x86_pause()
1554 #elif KMP_ARCH_PPC64
1555 #define KMP_PPC64_PRI_LOW() __asm__ volatile("or 1, 1, 1")
1556 #define KMP_PPC64_PRI_MED() __asm__ volatile("or 2, 2, 2")
1557 #define KMP_PPC64_PRI_LOC_MB() __asm__ volatile("" : : : "memory")
1558 #define KMP_CPU_PAUSE()                                                        \
1559   do {                                                                         \
1560     KMP_PPC64_PRI_LOW();                                                       \
1561     KMP_PPC64_PRI_MED();                                                       \
1562     KMP_PPC64_PRI_LOC_MB();                                                    \
1563   } while (0)
1564 #else
1565 #define KMP_CPU_PAUSE() /* nothing to do */
1566 #endif
1567 
1568 #define KMP_INIT_YIELD(count)                                                  \
1569   { (count) = __kmp_yield_init; }
1570 
1571 #define KMP_INIT_BACKOFF(time)                                                 \
1572   { (time) = __kmp_pause_init; }
1573 
1574 #define KMP_OVERSUBSCRIBED                                                     \
1575   (TCR_4(__kmp_nth) > (__kmp_avail_proc ? __kmp_avail_proc : __kmp_xproc))
1576 
1577 #define KMP_TRY_YIELD                                                          \
1578   ((__kmp_use_yield == 1) || (__kmp_use_yield == 2 && (KMP_OVERSUBSCRIBED)))
1579 
1580 #define KMP_TRY_YIELD_OVERSUB                                                  \
1581   ((__kmp_use_yield == 1 || __kmp_use_yield == 2) && (KMP_OVERSUBSCRIBED))
1582 
1583 #define KMP_YIELD(cond)                                                        \
1584   {                                                                            \
1585     KMP_CPU_PAUSE();                                                           \
1586     if ((cond) && (KMP_TRY_YIELD))                                             \
1587       __kmp_yield();                                                           \
1588   }
1589 
1590 #define KMP_YIELD_OVERSUB()                                                    \
1591   {                                                                            \
1592     KMP_CPU_PAUSE();                                                           \
1593     if ((KMP_TRY_YIELD_OVERSUB))                                               \
1594       __kmp_yield();                                                           \
1595   }
1596 
1597 // Note the decrement of 2 in the following Macros. With KMP_LIBRARY=turnaround,
1598 // there should be no yielding since initial value from KMP_INIT_YIELD() is odd.
1599 #define KMP_YIELD_SPIN(count)                                                  \
1600   {                                                                            \
1601     KMP_CPU_PAUSE();                                                           \
1602     if (KMP_TRY_YIELD) {                                                       \
1603       (count) -= 2;                                                            \
1604       if (!(count)) {                                                          \
1605         __kmp_yield();                                                         \
1606         (count) = __kmp_yield_next;                                            \
1607       }                                                                        \
1608     }                                                                          \
1609   }
1610 
1611 // If TPAUSE is available & enabled, use it. If oversubscribed, use the slower
1612 // (C0.2) state, which improves performance of other SMT threads on the same
1613 // core, otherwise, use the fast (C0.1) default state, or whatever the user has
1614 // requested. Uses a timed TPAUSE, and exponential backoff. If TPAUSE isn't
1615 // available, fall back to the regular CPU pause and yield combination.
1616 #if KMP_HAVE_UMWAIT
1617 #define KMP_TPAUSE_MAX_MASK ((kmp_uint64)0xFFFF)
1618 #define KMP_YIELD_OVERSUB_ELSE_SPIN(count, time)                               \
1619   {                                                                            \
1620     if (__kmp_tpause_enabled) {                                                \
1621       if (KMP_OVERSUBSCRIBED) {                                                \
1622         __kmp_tpause(0, (time));                                               \
1623       } else {                                                                 \
1624         __kmp_tpause(__kmp_tpause_hint, (time));                               \
1625       }                                                                        \
1626       (time) = (time << 1 | 1) & KMP_TPAUSE_MAX_MASK;                          \
1627     } else {                                                                   \
1628       KMP_CPU_PAUSE();                                                         \
1629       if ((KMP_TRY_YIELD_OVERSUB)) {                                           \
1630         __kmp_yield();                                                         \
1631       } else if (__kmp_use_yield == 1) {                                       \
1632         (count) -= 2;                                                          \
1633         if (!(count)) {                                                        \
1634           __kmp_yield();                                                       \
1635           (count) = __kmp_yield_next;                                          \
1636         }                                                                      \
1637       }                                                                        \
1638     }                                                                          \
1639   }
1640 #else
1641 #define KMP_YIELD_OVERSUB_ELSE_SPIN(count, time)                               \
1642   {                                                                            \
1643     KMP_CPU_PAUSE();                                                           \
1644     if ((KMP_TRY_YIELD_OVERSUB))                                               \
1645       __kmp_yield();                                                           \
1646     else if (__kmp_use_yield == 1) {                                           \
1647       (count) -= 2;                                                            \
1648       if (!(count)) {                                                          \
1649         __kmp_yield();                                                         \
1650         (count) = __kmp_yield_next;                                            \
1651       }                                                                        \
1652     }                                                                          \
1653   }
1654 #endif // KMP_HAVE_UMWAIT
1655 
1656 /* ------------------------------------------------------------------------ */
1657 /* Support datatypes for the orphaned construct nesting checks.             */
1658 /* ------------------------------------------------------------------------ */
1659 
1660 /* When adding to this enum, add its corresponding string in cons_text_c[]
1661  * array in kmp_error.cpp */
1662 enum cons_type {
1663   ct_none,
1664   ct_parallel,
1665   ct_pdo,
1666   ct_pdo_ordered,
1667   ct_psections,
1668   ct_psingle,
1669   ct_critical,
1670   ct_ordered_in_parallel,
1671   ct_ordered_in_pdo,
1672   ct_master,
1673   ct_reduce,
1674   ct_barrier,
1675   ct_masked
1676 };
1677 
1678 #define IS_CONS_TYPE_ORDERED(ct) ((ct) == ct_pdo_ordered)
1679 
1680 struct cons_data {
1681   ident_t const *ident;
1682   enum cons_type type;
1683   int prev;
1684   kmp_user_lock_p
1685       name; /* address exclusively for critical section name comparison */
1686 };
1687 
1688 struct cons_header {
1689   int p_top, w_top, s_top;
1690   int stack_size, stack_top;
1691   struct cons_data *stack_data;
1692 };
1693 
1694 struct kmp_region_info {
1695   char *text;
1696   int offset[KMP_MAX_FIELDS];
1697   int length[KMP_MAX_FIELDS];
1698 };
1699 
1700 /* ---------------------------------------------------------------------- */
1701 /* ---------------------------------------------------------------------- */
1702 
1703 #if KMP_OS_WINDOWS
1704 typedef HANDLE kmp_thread_t;
1705 typedef DWORD kmp_key_t;
1706 #endif /* KMP_OS_WINDOWS */
1707 
1708 #if KMP_OS_UNIX
1709 typedef pthread_t kmp_thread_t;
1710 typedef pthread_key_t kmp_key_t;
1711 #endif
1712 
1713 extern kmp_key_t __kmp_gtid_threadprivate_key;
1714 
1715 typedef struct kmp_sys_info {
1716   long maxrss; /* the maximum resident set size utilized (in kilobytes)     */
1717   long minflt; /* the number of page faults serviced without any I/O        */
1718   long majflt; /* the number of page faults serviced that required I/O      */
1719   long nswap; /* the number of times a process was "swapped" out of memory */
1720   long inblock; /* the number of times the file system had to perform input  */
1721   long oublock; /* the number of times the file system had to perform output */
1722   long nvcsw; /* the number of times a context switch was voluntarily      */
1723   long nivcsw; /* the number of times a context switch was forced           */
1724 } kmp_sys_info_t;
1725 
1726 #if USE_ITT_BUILD
1727 // We cannot include "kmp_itt.h" due to circular dependency. Declare the only
1728 // required type here. Later we will check the type meets requirements.
1729 typedef int kmp_itt_mark_t;
1730 #define KMP_ITT_DEBUG 0
1731 #endif /* USE_ITT_BUILD */
1732 
1733 typedef kmp_int32 kmp_critical_name[8];
1734 
1735 /*!
1736 @ingroup PARALLEL
1737 The type for a microtask which gets passed to @ref __kmpc_fork_call().
1738 The arguments to the outlined function are
1739 @param global_tid the global thread identity of the thread executing the
1740 function.
1741 @param bound_tid  the local identity of the thread executing the function
1742 @param ... pointers to shared variables accessed by the function.
1743 */
1744 typedef void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid, ...);
1745 typedef void (*kmpc_micro_bound)(kmp_int32 *bound_tid, kmp_int32 *bound_nth,
1746                                  ...);
1747 
1748 /*!
1749 @ingroup THREADPRIVATE
1750 @{
1751 */
1752 /* ---------------------------------------------------------------------------
1753  */
1754 /* Threadprivate initialization/finalization function declarations */
1755 
1756 /*  for non-array objects:  __kmpc_threadprivate_register()  */
1757 
1758 /*!
1759  Pointer to the constructor function.
1760  The first argument is the <tt>this</tt> pointer
1761 */
1762 typedef void *(*kmpc_ctor)(void *);
1763 
1764 /*!
1765  Pointer to the destructor function.
1766  The first argument is the <tt>this</tt> pointer
1767 */
1768 typedef void (*kmpc_dtor)(
1769     void * /*, size_t */); /* 2nd arg: magic number for KCC unused by Intel
1770                               compiler */
1771 /*!
1772  Pointer to an alternate constructor.
1773  The first argument is the <tt>this</tt> pointer.
1774 */
1775 typedef void *(*kmpc_cctor)(void *, void *);
1776 
1777 /* for array objects: __kmpc_threadprivate_register_vec() */
1778 /* First arg: "this" pointer */
1779 /* Last arg: number of array elements */
1780 /*!
1781  Array constructor.
1782  First argument is the <tt>this</tt> pointer
1783  Second argument the number of array elements.
1784 */
1785 typedef void *(*kmpc_ctor_vec)(void *, size_t);
1786 /*!
1787  Pointer to the array destructor function.
1788  The first argument is the <tt>this</tt> pointer
1789  Second argument the number of array elements.
1790 */
1791 typedef void (*kmpc_dtor_vec)(void *, size_t);
1792 /*!
1793  Array constructor.
1794  First argument is the <tt>this</tt> pointer
1795  Third argument the number of array elements.
1796 */
1797 typedef void *(*kmpc_cctor_vec)(void *, void *,
1798                                 size_t); /* function unused by compiler */
1799 
1800 /*!
1801 @}
1802 */
1803 
1804 /* keeps tracked of threadprivate cache allocations for cleanup later */
1805 typedef struct kmp_cached_addr {
1806   void **addr; /* address of allocated cache */
1807   void ***compiler_cache; /* pointer to compiler's cache */
1808   void *data; /* pointer to global data */
1809   struct kmp_cached_addr *next; /* pointer to next cached address */
1810 } kmp_cached_addr_t;
1811 
1812 struct private_data {
1813   struct private_data *next; /* The next descriptor in the list      */
1814   void *data; /* The data buffer for this descriptor  */
1815   int more; /* The repeat count for this descriptor */
1816   size_t size; /* The data size for this descriptor    */
1817 };
1818 
1819 struct private_common {
1820   struct private_common *next;
1821   struct private_common *link;
1822   void *gbl_addr;
1823   void *par_addr; /* par_addr == gbl_addr for PRIMARY thread */
1824   size_t cmn_size;
1825 };
1826 
1827 struct shared_common {
1828   struct shared_common *next;
1829   struct private_data *pod_init;
1830   void *obj_init;
1831   void *gbl_addr;
1832   union {
1833     kmpc_ctor ctor;
1834     kmpc_ctor_vec ctorv;
1835   } ct;
1836   union {
1837     kmpc_cctor cctor;
1838     kmpc_cctor_vec cctorv;
1839   } cct;
1840   union {
1841     kmpc_dtor dtor;
1842     kmpc_dtor_vec dtorv;
1843   } dt;
1844   size_t vec_len;
1845   int is_vec;
1846   size_t cmn_size;
1847 };
1848 
1849 #define KMP_HASH_TABLE_LOG2 9 /* log2 of the hash table size */
1850 #define KMP_HASH_TABLE_SIZE                                                    \
1851   (1 << KMP_HASH_TABLE_LOG2) /* size of the hash table */
1852 #define KMP_HASH_SHIFT 3 /* throw away this many low bits from the address */
1853 #define KMP_HASH(x)                                                            \
1854   ((((kmp_uintptr_t)x) >> KMP_HASH_SHIFT) & (KMP_HASH_TABLE_SIZE - 1))
1855 
1856 struct common_table {
1857   struct private_common *data[KMP_HASH_TABLE_SIZE];
1858 };
1859 
1860 struct shared_table {
1861   struct shared_common *data[KMP_HASH_TABLE_SIZE];
1862 };
1863 
1864 /* ------------------------------------------------------------------------ */
1865 
1866 #if KMP_USE_HIER_SCHED
1867 // Shared barrier data that exists inside a single unit of the scheduling
1868 // hierarchy
1869 typedef struct kmp_hier_private_bdata_t {
1870   kmp_int32 num_active;
1871   kmp_uint64 index;
1872   kmp_uint64 wait_val[2];
1873 } kmp_hier_private_bdata_t;
1874 #endif
1875 
1876 typedef struct kmp_sched_flags {
1877   unsigned ordered : 1;
1878   unsigned nomerge : 1;
1879   unsigned contains_last : 1;
1880   unsigned use_hier : 1; // Used in KMP_USE_HIER_SCHED code
1881   unsigned use_hybrid : 1; // Used in KMP_WEIGHTED_ITERATIONS_SUPPORTED code
1882   unsigned unused : 27;
1883 } kmp_sched_flags_t;
1884 
1885 KMP_BUILD_ASSERT(sizeof(kmp_sched_flags_t) == 4);
1886 
1887 #if KMP_STATIC_STEAL_ENABLED
1888 typedef struct KMP_ALIGN_CACHE dispatch_private_info32 {
1889   kmp_int32 count;
1890   kmp_int32 ub;
1891   /* Adding KMP_ALIGN_CACHE here doesn't help / can hurt performance */
1892   kmp_int32 lb;
1893   kmp_int32 st;
1894   kmp_int32 tc;
1895   kmp_lock_t *steal_lock; // lock used for chunk stealing
1896 
1897   kmp_uint32 ordered_lower;
1898   kmp_uint32 ordered_upper;
1899 
1900   // KMP_ALIGN(32) ensures (if the KMP_ALIGN macro is turned on)
1901   //    a) parm3 is properly aligned and
1902   //    b) all parm1-4 are on the same cache line.
1903   // Because of parm1-4 are used together, performance seems to be better
1904   // if they are on the same cache line (not measured though).
1905 
1906   struct KMP_ALIGN(32) {
1907     kmp_int32 parm1;
1908     kmp_int32 parm2;
1909     kmp_int32 parm3;
1910     kmp_int32 parm4;
1911   };
1912 
1913 #if KMP_WEIGHTED_ITERATIONS_SUPPORTED
1914   kmp_uint32 pchunks;
1915   kmp_uint32 num_procs_with_pcore;
1916   kmp_int32 first_thread_with_ecore;
1917 #endif
1918 #if KMP_OS_WINDOWS
1919   kmp_int32 last_upper;
1920 #endif /* KMP_OS_WINDOWS */
1921 } dispatch_private_info32_t;
1922 
1923 #if CACHE_LINE <= 128
1924 KMP_BUILD_ASSERT(sizeof(dispatch_private_info32_t) <= 128);
1925 #endif
1926 
1927 typedef struct KMP_ALIGN_CACHE dispatch_private_info64 {
1928   kmp_int64 count; // current chunk number for static & static-steal scheduling
1929   kmp_int64 ub; /* upper-bound */
1930   /* Adding KMP_ALIGN_CACHE here doesn't help / can hurt performance */
1931   kmp_int64 lb; /* lower-bound */
1932   kmp_int64 st; /* stride */
1933   kmp_int64 tc; /* trip count (number of iterations) */
1934   kmp_lock_t *steal_lock; // lock used for chunk stealing
1935 
1936   kmp_uint64 ordered_lower;
1937   kmp_uint64 ordered_upper;
1938   /* parm[1-4] are used in different ways by different scheduling algorithms */
1939 
1940   // KMP_ALIGN(32) ensures ( if the KMP_ALIGN macro is turned on )
1941   //    a) parm3 is properly aligned and
1942   //    b) all parm1-4 are in the same cache line.
1943   // Because of parm1-4 are used together, performance seems to be better
1944   // if they are in the same line (not measured though).
1945   struct KMP_ALIGN(32) {
1946     kmp_int64 parm1;
1947     kmp_int64 parm2;
1948     kmp_int64 parm3;
1949     kmp_int64 parm4;
1950   };
1951 
1952 #if KMP_WEIGHTED_ITERATIONS_SUPPORTED
1953   kmp_uint64 pchunks;
1954   kmp_uint64 num_procs_with_pcore;
1955   kmp_int64 first_thread_with_ecore;
1956 #endif
1957 
1958 #if KMP_OS_WINDOWS
1959   kmp_int64 last_upper;
1960 #endif /* KMP_OS_WINDOWS */
1961 } dispatch_private_info64_t;
1962 
1963 #if CACHE_LINE <= 128
1964 KMP_BUILD_ASSERT(sizeof(dispatch_private_info64_t) <= 128);
1965 #endif
1966 
1967 #else /* KMP_STATIC_STEAL_ENABLED */
1968 typedef struct KMP_ALIGN_CACHE dispatch_private_info32 {
1969   kmp_int32 lb;
1970   kmp_int32 ub;
1971   kmp_int32 st;
1972   kmp_int32 tc;
1973 
1974   kmp_int32 parm1;
1975   kmp_int32 parm2;
1976   kmp_int32 parm3;
1977   kmp_int32 parm4;
1978 
1979   kmp_int32 count;
1980 
1981   kmp_uint32 ordered_lower;
1982   kmp_uint32 ordered_upper;
1983 #if KMP_OS_WINDOWS
1984   kmp_int32 last_upper;
1985 #endif /* KMP_OS_WINDOWS */
1986 } dispatch_private_info32_t;
1987 
1988 typedef struct KMP_ALIGN_CACHE dispatch_private_info64 {
1989   kmp_int64 lb; /* lower-bound */
1990   kmp_int64 ub; /* upper-bound */
1991   kmp_int64 st; /* stride */
1992   kmp_int64 tc; /* trip count (number of iterations) */
1993 
1994   /* parm[1-4] are used in different ways by different scheduling algorithms */
1995   kmp_int64 parm1;
1996   kmp_int64 parm2;
1997   kmp_int64 parm3;
1998   kmp_int64 parm4;
1999 
2000   kmp_int64 count; /* current chunk number for static scheduling */
2001 
2002   kmp_uint64 ordered_lower;
2003   kmp_uint64 ordered_upper;
2004 #if KMP_OS_WINDOWS
2005   kmp_int64 last_upper;
2006 #endif /* KMP_OS_WINDOWS */
2007 } dispatch_private_info64_t;
2008 #endif /* KMP_STATIC_STEAL_ENABLED */
2009 
2010 typedef struct KMP_ALIGN_CACHE dispatch_private_info {
2011   union private_info {
2012     dispatch_private_info32_t p32;
2013     dispatch_private_info64_t p64;
2014   } u;
2015   enum sched_type schedule; /* scheduling algorithm */
2016   kmp_sched_flags_t flags; /* flags (e.g., ordered, nomerge, etc.) */
2017   std::atomic<kmp_uint32> steal_flag; // static_steal only, state of a buffer
2018   kmp_int32 ordered_bumped;
2019   // Stack of buffers for nest of serial regions
2020   struct dispatch_private_info *next;
2021   kmp_int32 type_size; /* the size of types in private_info */
2022 #if KMP_USE_HIER_SCHED
2023   kmp_int32 hier_id;
2024   void *parent; /* hierarchical scheduling parent pointer */
2025 #endif
2026   enum cons_type pushed_ws;
2027 } dispatch_private_info_t;
2028 
2029 typedef struct dispatch_shared_info32 {
2030   /* chunk index under dynamic, number of idle threads under static-steal;
2031      iteration index otherwise */
2032   volatile kmp_uint32 iteration;
2033   volatile kmp_int32 num_done;
2034   volatile kmp_uint32 ordered_iteration;
2035   // Dummy to retain the structure size after making ordered_iteration scalar
2036   kmp_int32 ordered_dummy[KMP_MAX_ORDERED - 1];
2037 } dispatch_shared_info32_t;
2038 
2039 typedef struct dispatch_shared_info64 {
2040   /* chunk index under dynamic, number of idle threads under static-steal;
2041      iteration index otherwise */
2042   volatile kmp_uint64 iteration;
2043   volatile kmp_int64 num_done;
2044   volatile kmp_uint64 ordered_iteration;
2045   // Dummy to retain the structure size after making ordered_iteration scalar
2046   kmp_int64 ordered_dummy[KMP_MAX_ORDERED - 3];
2047 } dispatch_shared_info64_t;
2048 
2049 typedef struct dispatch_shared_info {
2050   union shared_info {
2051     dispatch_shared_info32_t s32;
2052     dispatch_shared_info64_t s64;
2053   } u;
2054   volatile kmp_uint32 buffer_index;
2055   volatile kmp_int32 doacross_buf_idx; // teamwise index
2056   volatile kmp_uint32 *doacross_flags; // shared array of iteration flags (0/1)
2057   kmp_int32 doacross_num_done; // count finished threads
2058 #if KMP_USE_HIER_SCHED
2059   void *hier;
2060 #endif
2061 #if KMP_USE_HWLOC
2062   // When linking with libhwloc, the ORDERED EPCC test slows down on big
2063   // machines (> 48 cores). Performance analysis showed that a cache thrash
2064   // was occurring and this padding helps alleviate the problem.
2065   char padding[64];
2066 #endif
2067 } dispatch_shared_info_t;
2068 
2069 typedef struct kmp_disp {
2070   /* Vector for ORDERED SECTION */
2071   void (*th_deo_fcn)(int *gtid, int *cid, ident_t *);
2072   /* Vector for END ORDERED SECTION */
2073   void (*th_dxo_fcn)(int *gtid, int *cid, ident_t *);
2074 
2075   dispatch_shared_info_t *th_dispatch_sh_current;
2076   dispatch_private_info_t *th_dispatch_pr_current;
2077 
2078   dispatch_private_info_t *th_disp_buffer;
2079   kmp_uint32 th_disp_index;
2080   kmp_int32 th_doacross_buf_idx; // thread's doacross buffer index
2081   volatile kmp_uint32 *th_doacross_flags; // pointer to shared array of flags
2082   kmp_int64 *th_doacross_info; // info on loop bounds
2083 #if KMP_USE_INTERNODE_ALIGNMENT
2084   char more_padding[INTERNODE_CACHE_LINE];
2085 #endif
2086 } kmp_disp_t;
2087 
2088 /* ------------------------------------------------------------------------ */
2089 /* Barrier stuff */
2090 
2091 /* constants for barrier state update */
2092 #define KMP_INIT_BARRIER_STATE 0 /* should probably start from zero */
2093 #define KMP_BARRIER_SLEEP_BIT 0 /* bit used for suspend/sleep part of state */
2094 #define KMP_BARRIER_UNUSED_BIT 1 // bit that must never be set for valid state
2095 #define KMP_BARRIER_BUMP_BIT 2 /* lsb used for bump of go/arrived state */
2096 
2097 #define KMP_BARRIER_SLEEP_STATE (1 << KMP_BARRIER_SLEEP_BIT)
2098 #define KMP_BARRIER_UNUSED_STATE (1 << KMP_BARRIER_UNUSED_BIT)
2099 #define KMP_BARRIER_STATE_BUMP (1 << KMP_BARRIER_BUMP_BIT)
2100 
2101 #if (KMP_BARRIER_SLEEP_BIT >= KMP_BARRIER_BUMP_BIT)
2102 #error "Barrier sleep bit must be smaller than barrier bump bit"
2103 #endif
2104 #if (KMP_BARRIER_UNUSED_BIT >= KMP_BARRIER_BUMP_BIT)
2105 #error "Barrier unused bit must be smaller than barrier bump bit"
2106 #endif
2107 
2108 // Constants for release barrier wait state: currently, hierarchical only
2109 #define KMP_BARRIER_NOT_WAITING 0 // Normal state; worker not in wait_sleep
2110 #define KMP_BARRIER_OWN_FLAG                                                   \
2111   1 // Normal state; worker waiting on own b_go flag in release
2112 #define KMP_BARRIER_PARENT_FLAG                                                \
2113   2 // Special state; worker waiting on parent's b_go flag in release
2114 #define KMP_BARRIER_SWITCH_TO_OWN_FLAG                                         \
2115   3 // Special state; tells worker to shift from parent to own b_go
2116 #define KMP_BARRIER_SWITCHING                                                  \
2117   4 // Special state; worker resets appropriate flag on wake-up
2118 
2119 #define KMP_NOT_SAFE_TO_REAP                                                   \
2120   0 // Thread th_reap_state: not safe to reap (tasking)
2121 #define KMP_SAFE_TO_REAP 1 // Thread th_reap_state: safe to reap (not tasking)
2122 
2123 // The flag_type describes the storage used for the flag.
2124 enum flag_type {
2125   flag32, /**< atomic 32 bit flags */
2126   flag64, /**< 64 bit flags */
2127   atomic_flag64, /**< atomic 64 bit flags */
2128   flag_oncore, /**< special 64-bit flag for on-core barrier (hierarchical) */
2129   flag_unset
2130 };
2131 
2132 enum barrier_type {
2133   bs_plain_barrier = 0, /* 0, All non-fork/join barriers (except reduction
2134                            barriers if enabled) */
2135   bs_forkjoin_barrier, /* 1, All fork/join (parallel region) barriers */
2136 #if KMP_FAST_REDUCTION_BARRIER
2137   bs_reduction_barrier, /* 2, All barriers that are used in reduction */
2138 #endif // KMP_FAST_REDUCTION_BARRIER
2139   bs_last_barrier /* Just a placeholder to mark the end */
2140 };
2141 
2142 // to work with reduction barriers just like with plain barriers
2143 #if !KMP_FAST_REDUCTION_BARRIER
2144 #define bs_reduction_barrier bs_plain_barrier
2145 #endif // KMP_FAST_REDUCTION_BARRIER
2146 
2147 typedef enum kmp_bar_pat { /* Barrier communication patterns */
2148                            bp_linear_bar =
2149                                0, /* Single level (degenerate) tree */
2150                            bp_tree_bar =
2151                                1, /* Balanced tree with branching factor 2^n */
2152                            bp_hyper_bar = 2, /* Hypercube-embedded tree with min
2153                                                 branching factor 2^n */
2154                            bp_hierarchical_bar = 3, /* Machine hierarchy tree */
2155                            bp_dist_bar = 4, /* Distributed barrier */
2156                            bp_last_bar /* Placeholder to mark the end */
2157 } kmp_bar_pat_e;
2158 
2159 #define KMP_BARRIER_ICV_PUSH 1
2160 
2161 /* Record for holding the values of the internal controls stack records */
2162 typedef struct kmp_internal_control {
2163   int serial_nesting_level; /* corresponds to the value of the
2164                                th_team_serialized field */
2165   kmp_int8 dynamic; /* internal control for dynamic adjustment of threads (per
2166                        thread) */
2167   kmp_int8
2168       bt_set; /* internal control for whether blocktime is explicitly set */
2169   int blocktime; /* internal control for blocktime */
2170 #if KMP_USE_MONITOR
2171   int bt_intervals; /* internal control for blocktime intervals */
2172 #endif
2173   int nproc; /* internal control for #threads for next parallel region (per
2174                 thread) */
2175   int thread_limit; /* internal control for thread-limit-var */
2176   int task_thread_limit; /* internal control for thread-limit-var of a task*/
2177   int max_active_levels; /* internal control for max_active_levels */
2178   kmp_r_sched_t
2179       sched; /* internal control for runtime schedule {sched,chunk} pair */
2180   kmp_proc_bind_t proc_bind; /* internal control for affinity  */
2181   kmp_int32 default_device; /* internal control for default device */
2182   struct kmp_internal_control *next;
2183 } kmp_internal_control_t;
2184 
copy_icvs(kmp_internal_control_t * dst,kmp_internal_control_t * src)2185 static inline void copy_icvs(kmp_internal_control_t *dst,
2186                              kmp_internal_control_t *src) {
2187   *dst = *src;
2188 }
2189 
2190 /* Thread barrier needs volatile barrier fields */
2191 typedef struct KMP_ALIGN_CACHE kmp_bstate {
2192   // th_fixed_icvs is aligned by virtue of kmp_bstate being aligned (and all
2193   // uses of it). It is not explicitly aligned below, because we *don't* want
2194   // it to be padded -- instead, we fit b_go into the same cache line with
2195   // th_fixed_icvs, enabling NGO cache lines stores in the hierarchical barrier.
2196   kmp_internal_control_t th_fixed_icvs; // Initial ICVs for the thread
2197   // Tuck b_go into end of th_fixed_icvs cache line, so it can be stored with
2198   // same NGO store
2199   volatile kmp_uint64 b_go; // STATE => task should proceed (hierarchical)
2200   KMP_ALIGN_CACHE volatile kmp_uint64
2201       b_arrived; // STATE => task reached synch point.
2202   kmp_uint32 *skip_per_level;
2203   kmp_uint32 my_level;
2204   kmp_int32 parent_tid;
2205   kmp_int32 old_tid;
2206   kmp_uint32 depth;
2207   struct kmp_bstate *parent_bar;
2208   kmp_team_t *team;
2209   kmp_uint64 leaf_state;
2210   kmp_uint32 nproc;
2211   kmp_uint8 base_leaf_kids;
2212   kmp_uint8 leaf_kids;
2213   kmp_uint8 offset;
2214   kmp_uint8 wait_flag;
2215   kmp_uint8 use_oncore_barrier;
2216 #if USE_DEBUGGER
2217   // The following field is intended for the debugger solely. Only the worker
2218   // thread itself accesses this field: the worker increases it by 1 when it
2219   // arrives to a barrier.
2220   KMP_ALIGN_CACHE kmp_uint b_worker_arrived;
2221 #endif /* USE_DEBUGGER */
2222 } kmp_bstate_t;
2223 
2224 union KMP_ALIGN_CACHE kmp_barrier_union {
2225   double b_align; /* use worst case alignment */
2226   char b_pad[KMP_PAD(kmp_bstate_t, CACHE_LINE)];
2227   kmp_bstate_t bb;
2228 };
2229 
2230 typedef union kmp_barrier_union kmp_balign_t;
2231 
2232 /* Team barrier needs only non-volatile arrived counter */
2233 union KMP_ALIGN_CACHE kmp_barrier_team_union {
2234   double b_align; /* use worst case alignment */
2235   char b_pad[CACHE_LINE];
2236   struct {
2237     kmp_uint64 b_arrived; /* STATE => task reached synch point. */
2238 #if USE_DEBUGGER
2239     // The following two fields are indended for the debugger solely. Only
2240     // primary thread of the team accesses these fields: the first one is
2241     // increased by 1 when the primary thread arrives to a barrier, the second
2242     // one is increased by one when all the threads arrived.
2243     kmp_uint b_master_arrived;
2244     kmp_uint b_team_arrived;
2245 #endif
2246   };
2247 };
2248 
2249 typedef union kmp_barrier_team_union kmp_balign_team_t;
2250 
2251 /* Padding for Linux* OS pthreads condition variables and mutexes used to signal
2252    threads when a condition changes.  This is to workaround an NPTL bug where
2253    padding was added to pthread_cond_t which caused the initialization routine
2254    to write outside of the structure if compiled on pre-NPTL threads.  */
2255 #if KMP_OS_WINDOWS
2256 typedef struct kmp_win32_mutex {
2257   /* The Lock */
2258   CRITICAL_SECTION cs;
2259 } kmp_win32_mutex_t;
2260 
2261 typedef struct kmp_win32_cond {
2262   /* Count of the number of waiters. */
2263   int waiters_count_;
2264 
2265   /* Serialize access to <waiters_count_> */
2266   kmp_win32_mutex_t waiters_count_lock_;
2267 
2268   /* Number of threads to release via a <cond_broadcast> or a <cond_signal> */
2269   int release_count_;
2270 
2271   /* Keeps track of the current "generation" so that we don't allow */
2272   /* one thread to steal all the "releases" from the broadcast. */
2273   int wait_generation_count_;
2274 
2275   /* A manual-reset event that's used to block and release waiting threads. */
2276   HANDLE event_;
2277 } kmp_win32_cond_t;
2278 #endif
2279 
2280 #if KMP_OS_UNIX
2281 
2282 union KMP_ALIGN_CACHE kmp_cond_union {
2283   double c_align;
2284   char c_pad[CACHE_LINE];
2285   pthread_cond_t c_cond;
2286 };
2287 
2288 typedef union kmp_cond_union kmp_cond_align_t;
2289 
2290 union KMP_ALIGN_CACHE kmp_mutex_union {
2291   double m_align;
2292   char m_pad[CACHE_LINE];
2293   pthread_mutex_t m_mutex;
2294 };
2295 
2296 typedef union kmp_mutex_union kmp_mutex_align_t;
2297 
2298 #endif /* KMP_OS_UNIX */
2299 
2300 typedef struct kmp_desc_base {
2301   void *ds_stackbase;
2302   size_t ds_stacksize;
2303   int ds_stackgrow;
2304   kmp_thread_t ds_thread;
2305   volatile int ds_tid;
2306   int ds_gtid;
2307 #if KMP_OS_WINDOWS
2308   volatile int ds_alive;
2309   DWORD ds_thread_id;
2310 /* ds_thread keeps thread handle on Windows* OS. It is enough for RTL purposes.
2311    However, debugger support (libomp_db) cannot work with handles, because they
2312    uncomparable. For example, debugger requests info about thread with handle h.
2313    h is valid within debugger process, and meaningless within debugee process.
2314    Even if h is duped by call to DuplicateHandle(), so the result h' is valid
2315    within debugee process, but it is a *new* handle which does *not* equal to
2316    any other handle in debugee... The only way to compare handles is convert
2317    them to system-wide ids. GetThreadId() function is available only in
2318    Longhorn and Server 2003. :-( In contrast, GetCurrentThreadId() is available
2319    on all Windows* OS flavours (including Windows* 95). Thus, we have to get
2320    thread id by call to GetCurrentThreadId() from within the thread and save it
2321    to let libomp_db identify threads.  */
2322 #endif /* KMP_OS_WINDOWS */
2323 } kmp_desc_base_t;
2324 
2325 typedef union KMP_ALIGN_CACHE kmp_desc {
2326   double ds_align; /* use worst case alignment */
2327   char ds_pad[KMP_PAD(kmp_desc_base_t, CACHE_LINE)];
2328   kmp_desc_base_t ds;
2329 } kmp_desc_t;
2330 
2331 typedef struct kmp_local {
2332   volatile int this_construct; /* count of single's encountered by thread */
2333   void *reduce_data;
2334 #if KMP_USE_BGET
2335   void *bget_data;
2336   void *bget_list;
2337 #if !USE_CMP_XCHG_FOR_BGET
2338 #ifdef USE_QUEUING_LOCK_FOR_BGET
2339   kmp_lock_t bget_lock; /* Lock for accessing bget free list */
2340 #else
2341   kmp_bootstrap_lock_t bget_lock; // Lock for accessing bget free list. Must be
2342 // bootstrap lock so we can use it at library
2343 // shutdown.
2344 #endif /* USE_LOCK_FOR_BGET */
2345 #endif /* ! USE_CMP_XCHG_FOR_BGET */
2346 #endif /* KMP_USE_BGET */
2347 
2348   PACKED_REDUCTION_METHOD_T
2349   packed_reduction_method; /* stored by __kmpc_reduce*(), used by
2350                               __kmpc_end_reduce*() */
2351 
2352 } kmp_local_t;
2353 
2354 #define KMP_CHECK_UPDATE(a, b)                                                 \
2355   if ((a) != (b))                                                              \
2356   (a) = (b)
2357 #define KMP_CHECK_UPDATE_SYNC(a, b)                                            \
2358   if ((a) != (b))                                                              \
2359   TCW_SYNC_PTR((a), (b))
2360 
2361 #define get__blocktime(xteam, xtid)                                            \
2362   ((xteam)->t.t_threads[(xtid)]->th.th_current_task->td_icvs.blocktime)
2363 #define get__bt_set(xteam, xtid)                                               \
2364   ((xteam)->t.t_threads[(xtid)]->th.th_current_task->td_icvs.bt_set)
2365 #if KMP_USE_MONITOR
2366 #define get__bt_intervals(xteam, xtid)                                         \
2367   ((xteam)->t.t_threads[(xtid)]->th.th_current_task->td_icvs.bt_intervals)
2368 #endif
2369 
2370 #define get__dynamic_2(xteam, xtid)                                            \
2371   ((xteam)->t.t_threads[(xtid)]->th.th_current_task->td_icvs.dynamic)
2372 #define get__nproc_2(xteam, xtid)                                              \
2373   ((xteam)->t.t_threads[(xtid)]->th.th_current_task->td_icvs.nproc)
2374 #define get__sched_2(xteam, xtid)                                              \
2375   ((xteam)->t.t_threads[(xtid)]->th.th_current_task->td_icvs.sched)
2376 
2377 #define set__blocktime_team(xteam, xtid, xval)                                 \
2378   (((xteam)->t.t_threads[(xtid)]->th.th_current_task->td_icvs.blocktime) =     \
2379        (xval))
2380 
2381 #if KMP_USE_MONITOR
2382 #define set__bt_intervals_team(xteam, xtid, xval)                              \
2383   (((xteam)->t.t_threads[(xtid)]->th.th_current_task->td_icvs.bt_intervals) =  \
2384        (xval))
2385 #endif
2386 
2387 #define set__bt_set_team(xteam, xtid, xval)                                    \
2388   (((xteam)->t.t_threads[(xtid)]->th.th_current_task->td_icvs.bt_set) = (xval))
2389 
2390 #define set__dynamic(xthread, xval)                                            \
2391   (((xthread)->th.th_current_task->td_icvs.dynamic) = (xval))
2392 #define get__dynamic(xthread)                                                  \
2393   (((xthread)->th.th_current_task->td_icvs.dynamic) ? (FTN_TRUE) : (FTN_FALSE))
2394 
2395 #define set__nproc(xthread, xval)                                              \
2396   (((xthread)->th.th_current_task->td_icvs.nproc) = (xval))
2397 
2398 #define set__thread_limit(xthread, xval)                                       \
2399   (((xthread)->th.th_current_task->td_icvs.thread_limit) = (xval))
2400 
2401 #define set__max_active_levels(xthread, xval)                                  \
2402   (((xthread)->th.th_current_task->td_icvs.max_active_levels) = (xval))
2403 
2404 #define get__max_active_levels(xthread)                                        \
2405   ((xthread)->th.th_current_task->td_icvs.max_active_levels)
2406 
2407 #define set__sched(xthread, xval)                                              \
2408   (((xthread)->th.th_current_task->td_icvs.sched) = (xval))
2409 
2410 #define set__proc_bind(xthread, xval)                                          \
2411   (((xthread)->th.th_current_task->td_icvs.proc_bind) = (xval))
2412 #define get__proc_bind(xthread)                                                \
2413   ((xthread)->th.th_current_task->td_icvs.proc_bind)
2414 
2415 // OpenMP tasking data structures
2416 
2417 typedef enum kmp_tasking_mode {
2418   tskm_immediate_exec = 0,
2419   tskm_extra_barrier = 1,
2420   tskm_task_teams = 2,
2421   tskm_max = 2
2422 } kmp_tasking_mode_t;
2423 
2424 extern kmp_tasking_mode_t
2425     __kmp_tasking_mode; /* determines how/when to execute tasks */
2426 extern int __kmp_task_stealing_constraint;
2427 extern int __kmp_enable_task_throttling;
2428 extern kmp_int32 __kmp_default_device; // Set via OMP_DEFAULT_DEVICE if
2429 // specified, defaults to 0 otherwise
2430 // Set via OMP_MAX_TASK_PRIORITY if specified, defaults to 0 otherwise
2431 extern kmp_int32 __kmp_max_task_priority;
2432 // Set via KMP_TASKLOOP_MIN_TASKS if specified, defaults to 0 otherwise
2433 extern kmp_uint64 __kmp_taskloop_min_tasks;
2434 
2435 /* NOTE: kmp_taskdata_t and kmp_task_t structures allocated in single block with
2436    taskdata first */
2437 #define KMP_TASK_TO_TASKDATA(task) (((kmp_taskdata_t *)task) - 1)
2438 #define KMP_TASKDATA_TO_TASK(taskdata) (kmp_task_t *)(taskdata + 1)
2439 
2440 // The tt_found_tasks flag is a signal to all threads in the team that tasks
2441 // were spawned and queued since the previous barrier release.
2442 #define KMP_TASKING_ENABLED(task_team)                                         \
2443   (TRUE == TCR_SYNC_4((task_team)->tt.tt_found_tasks))
2444 /*!
2445 @ingroup BASIC_TYPES
2446 @{
2447 */
2448 
2449 /*!
2450  */
2451 typedef kmp_int32 (*kmp_routine_entry_t)(kmp_int32, void *);
2452 
2453 typedef union kmp_cmplrdata {
2454   kmp_int32 priority; /**< priority specified by user for the task */
2455   kmp_routine_entry_t
2456       destructors; /* pointer to function to invoke deconstructors of
2457                       firstprivate C++ objects */
2458   /* future data */
2459 } kmp_cmplrdata_t;
2460 
2461 /*  sizeof_kmp_task_t passed as arg to kmpc_omp_task call  */
2462 /*!
2463  */
2464 typedef struct kmp_task { /* GEH: Shouldn't this be aligned somehow? */
2465   void *shareds; /**< pointer to block of pointers to shared vars   */
2466   kmp_routine_entry_t
2467       routine; /**< pointer to routine to call for executing task */
2468   kmp_int32 part_id; /**< part id for the task                          */
2469   kmp_cmplrdata_t
2470       data1; /* Two known optional additions: destructors and priority */
2471   kmp_cmplrdata_t data2; /* Process destructors first, priority second */
2472   /* future data */
2473   /*  private vars  */
2474 } kmp_task_t;
2475 
2476 /*!
2477 @}
2478 */
2479 
2480 typedef struct kmp_taskgroup {
2481   std::atomic<kmp_int32> count; // number of allocated and incomplete tasks
2482   std::atomic<kmp_int32>
2483       cancel_request; // request for cancellation of this taskgroup
2484   struct kmp_taskgroup *parent; // parent taskgroup
2485   // Block of data to perform task reduction
2486   void *reduce_data; // reduction related info
2487   kmp_int32 reduce_num_data; // number of data items to reduce
2488   uintptr_t *gomp_data; // gomp reduction data
2489 } kmp_taskgroup_t;
2490 
2491 // forward declarations
2492 typedef union kmp_depnode kmp_depnode_t;
2493 typedef struct kmp_depnode_list kmp_depnode_list_t;
2494 typedef struct kmp_dephash_entry kmp_dephash_entry_t;
2495 
2496 // macros for checking dep flag as an integer
2497 #define KMP_DEP_IN 0x1
2498 #define KMP_DEP_OUT 0x2
2499 #define KMP_DEP_INOUT 0x3
2500 #define KMP_DEP_MTX 0x4
2501 #define KMP_DEP_SET 0x8
2502 #define KMP_DEP_ALL 0x80
2503 // Compiler sends us this info. Note: some test cases contain an explicit copy
2504 // of this struct and should be in sync with any changes here.
2505 typedef struct kmp_depend_info {
2506   kmp_intptr_t base_addr;
2507   size_t len;
2508   union {
2509     kmp_uint8 flag; // flag as an unsigned char
2510     struct { // flag as a set of 8 bits
2511 #if defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)
2512       /* Same fields as in the #else branch, but in reverse order */
2513       unsigned all : 1;
2514       unsigned unused : 3;
2515       unsigned set : 1;
2516       unsigned mtx : 1;
2517       unsigned out : 1;
2518       unsigned in : 1;
2519 #else
2520       unsigned in : 1;
2521       unsigned out : 1;
2522       unsigned mtx : 1;
2523       unsigned set : 1;
2524       unsigned unused : 3;
2525       unsigned all : 1;
2526 #endif
2527     } flags;
2528   };
2529 } kmp_depend_info_t;
2530 
2531 // Internal structures to work with task dependencies:
2532 struct kmp_depnode_list {
2533   kmp_depnode_t *node;
2534   kmp_depnode_list_t *next;
2535 };
2536 
2537 // Max number of mutexinoutset dependencies per node
2538 #define MAX_MTX_DEPS 4
2539 
2540 typedef struct kmp_base_depnode {
2541   kmp_depnode_list_t *successors; /* used under lock */
2542   kmp_task_t *task; /* non-NULL if depnode is active, used under lock */
2543   kmp_lock_t *mtx_locks[MAX_MTX_DEPS]; /* lock mutexinoutset dependent tasks */
2544   kmp_int32 mtx_num_locks; /* number of locks in mtx_locks array */
2545   kmp_lock_t lock; /* guards shared fields: task, successors */
2546 #if KMP_SUPPORT_GRAPH_OUTPUT
2547   kmp_uint32 id;
2548 #endif
2549   std::atomic<kmp_int32> npredecessors;
2550   std::atomic<kmp_int32> nrefs;
2551 } kmp_base_depnode_t;
2552 
2553 union KMP_ALIGN_CACHE kmp_depnode {
2554   double dn_align; /* use worst case alignment */
2555   char dn_pad[KMP_PAD(kmp_base_depnode_t, CACHE_LINE)];
2556   kmp_base_depnode_t dn;
2557 };
2558 
2559 struct kmp_dephash_entry {
2560   kmp_intptr_t addr;
2561   kmp_depnode_t *last_out;
2562   kmp_depnode_list_t *last_set;
2563   kmp_depnode_list_t *prev_set;
2564   kmp_uint8 last_flag;
2565   kmp_lock_t *mtx_lock; /* is referenced by depnodes w/mutexinoutset dep */
2566   kmp_dephash_entry_t *next_in_bucket;
2567 };
2568 
2569 typedef struct kmp_dephash {
2570   kmp_dephash_entry_t **buckets;
2571   size_t size;
2572   kmp_depnode_t *last_all;
2573   size_t generation;
2574   kmp_uint32 nelements;
2575   kmp_uint32 nconflicts;
2576 } kmp_dephash_t;
2577 
2578 typedef struct kmp_task_affinity_info {
2579   kmp_intptr_t base_addr;
2580   size_t len;
2581   struct {
2582     bool flag1 : 1;
2583     bool flag2 : 1;
2584     kmp_int32 reserved : 30;
2585   } flags;
2586 } kmp_task_affinity_info_t;
2587 
2588 typedef enum kmp_event_type_t {
2589   KMP_EVENT_UNINITIALIZED = 0,
2590   KMP_EVENT_ALLOW_COMPLETION = 1
2591 } kmp_event_type_t;
2592 
2593 typedef struct {
2594   kmp_event_type_t type;
2595   kmp_tas_lock_t lock;
2596   union {
2597     kmp_task_t *task;
2598   } ed;
2599 } kmp_event_t;
2600 
2601 #if OMPX_TASKGRAPH
2602 // Initial number of allocated nodes while recording
2603 #define INIT_MAPSIZE 50
2604 
2605 typedef struct kmp_taskgraph_flags { /*This needs to be exactly 32 bits */
2606   unsigned nowait : 1;
2607   unsigned re_record : 1;
2608   unsigned reserved : 30;
2609 } kmp_taskgraph_flags_t;
2610 
2611 /// Represents a TDG node
2612 typedef struct kmp_node_info {
2613   kmp_task_t *task; // Pointer to the actual task
2614   kmp_int32 *successors; // Array of the succesors ids
2615   kmp_int32 nsuccessors; // Number of succesors of the node
2616   std::atomic<kmp_int32>
2617       npredecessors_counter; // Number of predessors on the fly
2618   kmp_int32 npredecessors; // Total number of predecessors
2619   kmp_int32 successors_size; // Number of allocated succesors ids
2620   kmp_taskdata_t *parent_task; // Parent implicit task
2621 } kmp_node_info_t;
2622 
2623 /// Represent a TDG's current status
2624 typedef enum kmp_tdg_status {
2625   KMP_TDG_NONE = 0,
2626   KMP_TDG_RECORDING = 1,
2627   KMP_TDG_READY = 2
2628 } kmp_tdg_status_t;
2629 
2630 /// Structure that contains a TDG
2631 typedef struct kmp_tdg_info {
2632   kmp_int32 tdg_id; // Unique idenfifier of the TDG
2633   kmp_taskgraph_flags_t tdg_flags; // Flags related to a TDG
2634   kmp_int32 map_size; // Number of allocated TDG nodes
2635   kmp_int32 num_roots; // Number of roots tasks int the TDG
2636   kmp_int32 *root_tasks; // Array of tasks identifiers that are roots
2637   kmp_node_info_t *record_map; // Array of TDG nodes
2638   kmp_tdg_status_t tdg_status =
2639       KMP_TDG_NONE; // Status of the TDG (recording, ready...)
2640   std::atomic<kmp_int32> num_tasks; // Number of TDG nodes
2641   kmp_bootstrap_lock_t
2642       graph_lock; // Protect graph attributes when updated via taskloop_recur
2643   // Taskloop reduction related
2644   void *rec_taskred_data; // Data to pass to __kmpc_task_reduction_init or
2645                           // __kmpc_taskred_init
2646   kmp_int32 rec_num_taskred;
2647 } kmp_tdg_info_t;
2648 
2649 extern int __kmp_tdg_dot;
2650 extern kmp_int32 __kmp_max_tdgs;
2651 extern kmp_tdg_info_t **__kmp_global_tdgs;
2652 extern kmp_int32 __kmp_curr_tdg_idx;
2653 extern kmp_int32 __kmp_successors_size;
2654 extern std::atomic<kmp_int32> __kmp_tdg_task_id;
2655 extern kmp_int32 __kmp_num_tdg;
2656 #endif
2657 
2658 #ifdef BUILD_TIED_TASK_STACK
2659 
2660 /* Tied Task stack definitions */
2661 typedef struct kmp_stack_block {
2662   kmp_taskdata_t *sb_block[TASK_STACK_BLOCK_SIZE];
2663   struct kmp_stack_block *sb_next;
2664   struct kmp_stack_block *sb_prev;
2665 } kmp_stack_block_t;
2666 
2667 typedef struct kmp_task_stack {
2668   kmp_stack_block_t ts_first_block; // first block of stack entries
2669   kmp_taskdata_t **ts_top; // pointer to the top of stack
2670   kmp_int32 ts_entries; // number of entries on the stack
2671 } kmp_task_stack_t;
2672 
2673 #endif // BUILD_TIED_TASK_STACK
2674 
2675 typedef struct kmp_tasking_flags { /* Total struct must be exactly 32 bits */
2676 #if defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)
2677   /* Same fields as in the #else branch, but in reverse order */
2678 #if OMPX_TASKGRAPH
2679   unsigned reserved31 : 6;
2680   unsigned onced : 1;
2681 #else
2682   unsigned reserved31 : 7;
2683 #endif
2684   unsigned native : 1;
2685   unsigned freed : 1;
2686   unsigned complete : 1;
2687   unsigned executing : 1;
2688   unsigned started : 1;
2689   unsigned team_serial : 1;
2690   unsigned tasking_ser : 1;
2691   unsigned task_serial : 1;
2692   unsigned tasktype : 1;
2693   unsigned reserved : 8;
2694   unsigned hidden_helper : 1;
2695   unsigned detachable : 1;
2696   unsigned priority_specified : 1;
2697   unsigned proxy : 1;
2698   unsigned destructors_thunk : 1;
2699   unsigned merged_if0 : 1;
2700   unsigned final : 1;
2701   unsigned tiedness : 1;
2702 #else
2703   /* Compiler flags */ /* Total compiler flags must be 16 bits */
2704   unsigned tiedness : 1; /* task is either tied (1) or untied (0) */
2705   unsigned final : 1; /* task is final(1) so execute immediately */
2706   unsigned merged_if0 : 1; /* no __kmpc_task_{begin/complete}_if0 calls in if0
2707                               code path */
2708   unsigned destructors_thunk : 1; /* set if the compiler creates a thunk to
2709                                      invoke destructors from the runtime */
2710   unsigned proxy : 1; /* task is a proxy task (it will be executed outside the
2711                          context of the RTL) */
2712   unsigned priority_specified : 1; /* set if the compiler provides priority
2713                                       setting for the task */
2714   unsigned detachable : 1; /* 1 == can detach */
2715   unsigned hidden_helper : 1; /* 1 == hidden helper task */
2716   unsigned reserved : 8; /* reserved for compiler use */
2717 
2718   /* Library flags */ /* Total library flags must be 16 bits */
2719   unsigned tasktype : 1; /* task is either explicit(1) or implicit (0) */
2720   unsigned task_serial : 1; // task is executed immediately (1) or deferred (0)
2721   unsigned tasking_ser : 1; // all tasks in team are either executed immediately
2722   // (1) or may be deferred (0)
2723   unsigned team_serial : 1; // entire team is serial (1) [1 thread] or parallel
2724   // (0) [>= 2 threads]
2725   /* If either team_serial or tasking_ser is set, task team may be NULL */
2726   /* Task State Flags: */
2727   unsigned started : 1; /* 1==started, 0==not started     */
2728   unsigned executing : 1; /* 1==executing, 0==not executing */
2729   unsigned complete : 1; /* 1==complete, 0==not complete   */
2730   unsigned freed : 1; /* 1==freed, 0==allocated        */
2731   unsigned native : 1; /* 1==gcc-compiled task, 0==intel */
2732 #if OMPX_TASKGRAPH
2733   unsigned onced : 1; /* 1==ran once already, 0==never ran, record & replay purposes */
2734   unsigned reserved31 : 6; /* reserved for library use */
2735 #else
2736   unsigned reserved31 : 7; /* reserved for library use */
2737 #endif
2738 #endif
2739 } kmp_tasking_flags_t;
2740 
2741 typedef struct kmp_target_data {
2742   void *async_handle; // libomptarget async handle for task completion query
2743 } kmp_target_data_t;
2744 
2745 struct kmp_taskdata { /* aligned during dynamic allocation       */
2746   kmp_int32 td_task_id; /* id, assigned by debugger                */
2747   kmp_tasking_flags_t td_flags; /* task flags                              */
2748   kmp_team_t *td_team; /* team for this task                      */
2749   kmp_info_p *td_alloc_thread; /* thread that allocated data structures   */
2750   /* Currently not used except for perhaps IDB */
2751   kmp_taskdata_t *td_parent; /* parent task                             */
2752   kmp_int32 td_level; /* task nesting level                      */
2753   std::atomic<kmp_int32> td_untied_count; // untied task active parts counter
2754   ident_t *td_ident; /* task identifier                         */
2755   // Taskwait data.
2756   ident_t *td_taskwait_ident;
2757   kmp_uint32 td_taskwait_counter;
2758   kmp_int32 td_taskwait_thread; /* gtid + 1 of thread encountered taskwait */
2759   KMP_ALIGN_CACHE kmp_internal_control_t
2760       td_icvs; /* Internal control variables for the task */
2761   KMP_ALIGN_CACHE std::atomic<kmp_int32>
2762       td_allocated_child_tasks; /* Child tasks (+ current task) not yet
2763                                    deallocated */
2764   std::atomic<kmp_int32>
2765       td_incomplete_child_tasks; /* Child tasks not yet complete */
2766   kmp_taskgroup_t
2767       *td_taskgroup; // Each task keeps pointer to its current taskgroup
2768   kmp_dephash_t
2769       *td_dephash; // Dependencies for children tasks are tracked from here
2770   kmp_depnode_t
2771       *td_depnode; // Pointer to graph node if this task has dependencies
2772   kmp_task_team_t *td_task_team;
2773   size_t td_size_alloc; // Size of task structure, including shareds etc.
2774 #if defined(KMP_GOMP_COMPAT)
2775   // 4 or 8 byte integers for the loop bounds in GOMP_taskloop
2776   kmp_int32 td_size_loop_bounds;
2777 #endif
2778   kmp_taskdata_t *td_last_tied; // keep tied task for task scheduling constraint
2779 #if defined(KMP_GOMP_COMPAT)
2780   // GOMP sends in a copy function for copy constructors
2781   void (*td_copy_func)(void *, void *);
2782 #endif
2783   kmp_event_t td_allow_completion_event;
2784 #if OMPT_SUPPORT
2785   ompt_task_info_t ompt_task_info;
2786 #endif
2787 #if OMPX_TASKGRAPH
2788   bool is_taskgraph = 0; // whether the task is within a TDG
2789   kmp_tdg_info_t *tdg; // used to associate task with a TDG
2790 #endif
2791   kmp_target_data_t td_target_data;
2792 }; // struct kmp_taskdata
2793 
2794 // Make sure padding above worked
2795 KMP_BUILD_ASSERT(sizeof(kmp_taskdata_t) % sizeof(void *) == 0);
2796 
2797 // Data for task team but per thread
2798 typedef struct kmp_base_thread_data {
2799   kmp_info_p *td_thr; // Pointer back to thread info
2800   // Used only in __kmp_execute_tasks_template, maybe not avail until task is
2801   // queued?
2802   kmp_bootstrap_lock_t td_deque_lock; // Lock for accessing deque
2803   kmp_taskdata_t *
2804       *td_deque; // Deque of tasks encountered by td_thr, dynamically allocated
2805   kmp_int32 td_deque_size; // Size of deck
2806   kmp_uint32 td_deque_head; // Head of deque (will wrap)
2807   kmp_uint32 td_deque_tail; // Tail of deque (will wrap)
2808   kmp_int32 td_deque_ntasks; // Number of tasks in deque
2809   // GEH: shouldn't this be volatile since used in while-spin?
2810   kmp_int32 td_deque_last_stolen; // Thread number of last successful steal
2811 #ifdef BUILD_TIED_TASK_STACK
2812   kmp_task_stack_t td_susp_tied_tasks; // Stack of suspended tied tasks for task
2813 // scheduling constraint
2814 #endif // BUILD_TIED_TASK_STACK
2815 } kmp_base_thread_data_t;
2816 
2817 #define TASK_DEQUE_BITS 8 // Used solely to define INITIAL_TASK_DEQUE_SIZE
2818 #define INITIAL_TASK_DEQUE_SIZE (1 << TASK_DEQUE_BITS)
2819 
2820 #define TASK_DEQUE_SIZE(td) ((td).td_deque_size)
2821 #define TASK_DEQUE_MASK(td) ((td).td_deque_size - 1)
2822 
2823 typedef union KMP_ALIGN_CACHE kmp_thread_data {
2824   kmp_base_thread_data_t td;
2825   double td_align; /* use worst case alignment */
2826   char td_pad[KMP_PAD(kmp_base_thread_data_t, CACHE_LINE)];
2827 } kmp_thread_data_t;
2828 
2829 typedef struct kmp_task_pri {
2830   kmp_thread_data_t td;
2831   kmp_int32 priority;
2832   kmp_task_pri *next;
2833 } kmp_task_pri_t;
2834 
2835 // Data for task teams which are used when tasking is enabled for the team
2836 typedef struct kmp_base_task_team {
2837   kmp_bootstrap_lock_t
2838       tt_threads_lock; /* Lock used to allocate per-thread part of task team */
2839   /* must be bootstrap lock since used at library shutdown*/
2840 
2841   // TODO: check performance vs kmp_tas_lock_t
2842   kmp_bootstrap_lock_t tt_task_pri_lock; /* Lock to access priority tasks */
2843   kmp_task_pri_t *tt_task_pri_list;
2844 
2845   kmp_task_team_t *tt_next; /* For linking the task team free list */
2846   kmp_thread_data_t
2847       *tt_threads_data; /* Array of per-thread structures for task team */
2848   /* Data survives task team deallocation */
2849   kmp_int32 tt_found_tasks; /* Have we found tasks and queued them while
2850                                executing this team? */
2851   /* TRUE means tt_threads_data is set up and initialized */
2852   kmp_int32 tt_nproc; /* #threads in team           */
2853   kmp_int32 tt_max_threads; // # entries allocated for threads_data array
2854   kmp_int32 tt_found_proxy_tasks; // found proxy tasks since last barrier
2855   kmp_int32 tt_untied_task_encountered;
2856   std::atomic<kmp_int32> tt_num_task_pri; // number of priority tasks enqueued
2857   // There is hidden helper thread encountered in this task team so that we must
2858   // wait when waiting on task team
2859   kmp_int32 tt_hidden_helper_task_encountered;
2860 
2861   KMP_ALIGN_CACHE
2862   std::atomic<kmp_int32> tt_unfinished_threads; /* #threads still active */
2863 
2864   KMP_ALIGN_CACHE
2865   volatile kmp_uint32
2866       tt_active; /* is the team still actively executing tasks */
2867 } kmp_base_task_team_t;
2868 
2869 union KMP_ALIGN_CACHE kmp_task_team {
2870   kmp_base_task_team_t tt;
2871   double tt_align; /* use worst case alignment */
2872   char tt_pad[KMP_PAD(kmp_base_task_team_t, CACHE_LINE)];
2873 };
2874 
2875 #if (USE_FAST_MEMORY == 3) || (USE_FAST_MEMORY == 5)
2876 // Free lists keep same-size free memory slots for fast memory allocation
2877 // routines
2878 typedef struct kmp_free_list {
2879   void *th_free_list_self; // Self-allocated tasks free list
2880   void *th_free_list_sync; // Self-allocated tasks stolen/returned by other
2881   // threads
2882   void *th_free_list_other; // Non-self free list (to be returned to owner's
2883   // sync list)
2884 } kmp_free_list_t;
2885 #endif
2886 #if KMP_NESTED_HOT_TEAMS
2887 // Hot teams array keeps hot teams and their sizes for given thread. Hot teams
2888 // are not put in teams pool, and they don't put threads in threads pool.
2889 typedef struct kmp_hot_team_ptr {
2890   kmp_team_p *hot_team; // pointer to hot_team of given nesting level
2891   kmp_int32 hot_team_nth; // number of threads allocated for the hot_team
2892 } kmp_hot_team_ptr_t;
2893 #endif
2894 typedef struct kmp_teams_size {
2895   kmp_int32 nteams; // number of teams in a league
2896   kmp_int32 nth; // number of threads in each team of the league
2897 } kmp_teams_size_t;
2898 
2899 // This struct stores a thread that acts as a "root" for a contention
2900 // group. Contention groups are rooted at kmp_root threads, but also at
2901 // each primary thread of each team created in the teams construct.
2902 // This struct therefore also stores a thread_limit associated with
2903 // that contention group, and a counter to track the number of threads
2904 // active in that contention group. Each thread has a list of these: CG
2905 // root threads have an entry in their list in which cg_root refers to
2906 // the thread itself, whereas other workers in the CG will have a
2907 // single entry where cg_root is same as the entry containing their CG
2908 // root. When a thread encounters a teams construct, it will add a new
2909 // entry to the front of its list, because it now roots a new CG.
2910 typedef struct kmp_cg_root {
2911   kmp_info_p *cg_root; // "root" thread for a contention group
2912   // The CG root's limit comes from OMP_THREAD_LIMIT for root threads, or
2913   // thread_limit clause for teams primary threads
2914   kmp_int32 cg_thread_limit;
2915   kmp_int32 cg_nthreads; // Count of active threads in CG rooted at cg_root
2916   struct kmp_cg_root *up; // pointer to higher level CG root in list
2917 } kmp_cg_root_t;
2918 
2919 // OpenMP thread data structures
2920 
2921 typedef struct KMP_ALIGN_CACHE kmp_base_info {
2922   /* Start with the readonly data which is cache aligned and padded. This is
2923      written before the thread starts working by the primary thread. Uber
2924      masters may update themselves later. Usage does not consider serialized
2925      regions.  */
2926   kmp_desc_t th_info;
2927   kmp_team_p *th_team; /* team we belong to */
2928   kmp_root_p *th_root; /* pointer to root of task hierarchy */
2929   kmp_info_p *th_next_pool; /* next available thread in the pool */
2930   kmp_disp_t *th_dispatch; /* thread's dispatch data */
2931   int th_in_pool; /* in thread pool (32 bits for TCR/TCW) */
2932 
2933   /* The following are cached from the team info structure */
2934   /* TODO use these in more places as determined to be needed via profiling */
2935   int th_team_nproc; /* number of threads in a team */
2936   kmp_info_p *th_team_master; /* the team's primary thread */
2937   int th_team_serialized; /* team is serialized */
2938   microtask_t th_teams_microtask; /* save entry address for teams construct */
2939   int th_teams_level; /* save initial level of teams construct */
2940 /* it is 0 on device but may be any on host */
2941 
2942 /* The blocktime info is copied from the team struct to the thread struct */
2943 /* at the start of a barrier, and the values stored in the team are used  */
2944 /* at points in the code where the team struct is no longer guaranteed    */
2945 /* to exist (from the POV of worker threads).                             */
2946 #if KMP_USE_MONITOR
2947   int th_team_bt_intervals;
2948   int th_team_bt_set;
2949 #else
2950   kmp_uint64 th_team_bt_intervals;
2951 #endif
2952 
2953 #if KMP_AFFINITY_SUPPORTED
2954   kmp_affin_mask_t *th_affin_mask; /* thread's current affinity mask */
2955   kmp_affinity_ids_t th_topology_ids; /* thread's current topology ids */
2956   kmp_affinity_attrs_t th_topology_attrs; /* thread's current topology attrs */
2957 #endif
2958   omp_allocator_handle_t th_def_allocator; /* default allocator */
2959   /* The data set by the primary thread at reinit, then R/W by the worker */
2960   KMP_ALIGN_CACHE int
2961       th_set_nproc; /* if > 0, then only use this request for the next fork */
2962 #if KMP_NESTED_HOT_TEAMS
2963   kmp_hot_team_ptr_t *th_hot_teams; /* array of hot teams */
2964 #endif
2965   kmp_proc_bind_t
2966       th_set_proc_bind; /* if != proc_bind_default, use request for next fork */
2967   kmp_teams_size_t
2968       th_teams_size; /* number of teams/threads in teams construct */
2969 #if KMP_AFFINITY_SUPPORTED
2970   int th_current_place; /* place currently bound to */
2971   int th_new_place; /* place to bind to in par reg */
2972   int th_first_place; /* first place in partition */
2973   int th_last_place; /* last place in partition */
2974 #endif
2975   int th_prev_level; /* previous level for affinity format */
2976   int th_prev_num_threads; /* previous num_threads for affinity format */
2977 #if USE_ITT_BUILD
2978   kmp_uint64 th_bar_arrive_time; /* arrival to barrier timestamp */
2979   kmp_uint64 th_bar_min_time; /* minimum arrival time at the barrier */
2980   kmp_uint64 th_frame_time; /* frame timestamp */
2981 #endif /* USE_ITT_BUILD */
2982   kmp_local_t th_local;
2983   struct private_common *th_pri_head;
2984 
2985   /* Now the data only used by the worker (after initial allocation) */
2986   /* TODO the first serial team should actually be stored in the info_t
2987      structure.  this will help reduce initial allocation overhead */
2988   KMP_ALIGN_CACHE kmp_team_p
2989       *th_serial_team; /*serialized team held in reserve*/
2990 
2991 #if OMPT_SUPPORT
2992   ompt_thread_info_t ompt_thread_info;
2993 #endif
2994 
2995   /* The following are also read by the primary thread during reinit */
2996   struct common_table *th_pri_common;
2997 
2998   volatile kmp_uint32 th_spin_here; /* thread-local location for spinning */
2999   /* while awaiting queuing lock acquire */
3000 
3001   volatile void *th_sleep_loc; // this points at a kmp_flag<T>
3002   flag_type th_sleep_loc_type; // enum type of flag stored in th_sleep_loc
3003 
3004   ident_t *th_ident;
3005   unsigned th_x; // Random number generator data
3006   unsigned th_a; // Random number generator data
3007 
3008   /* Tasking-related data for the thread */
3009   kmp_task_team_t *th_task_team; // Task team struct
3010   kmp_taskdata_t *th_current_task; // Innermost Task being executed
3011   kmp_uint8 th_task_state; // alternating 0/1 for task team identification
3012   kmp_uint8 *th_task_state_memo_stack; // Stack holding memos of th_task_state
3013   // at nested levels
3014   kmp_uint32 th_task_state_top; // Top element of th_task_state_memo_stack
3015   kmp_uint32 th_task_state_stack_sz; // Size of th_task_state_memo_stack
3016   kmp_uint32 th_reap_state; // Non-zero indicates thread is not
3017   // tasking, thus safe to reap
3018 
3019   /* More stuff for keeping track of active/sleeping threads (this part is
3020      written by the worker thread) */
3021   kmp_uint8 th_active_in_pool; // included in count of #active threads in pool
3022   int th_active; // ! sleeping; 32 bits for TCR/TCW
3023   std::atomic<kmp_uint32> th_used_in_team; // Flag indicating use in team
3024   // 0 = not used in team; 1 = used in team;
3025   // 2 = transitioning to not used in team; 3 = transitioning to used in team
3026   struct cons_header *th_cons; // used for consistency check
3027 #if KMP_USE_HIER_SCHED
3028   // used for hierarchical scheduling
3029   kmp_hier_private_bdata_t *th_hier_bar_data;
3030 #endif
3031 
3032   /* Add the syncronizing data which is cache aligned and padded. */
3033   KMP_ALIGN_CACHE kmp_balign_t th_bar[bs_last_barrier];
3034 
3035   KMP_ALIGN_CACHE volatile kmp_int32
3036       th_next_waiting; /* gtid+1 of next thread on lock wait queue, 0 if none */
3037 
3038 #if (USE_FAST_MEMORY == 3) || (USE_FAST_MEMORY == 5)
3039 #define NUM_LISTS 4
3040   kmp_free_list_t th_free_lists[NUM_LISTS]; // Free lists for fast memory
3041 // allocation routines
3042 #endif
3043 
3044 #if KMP_OS_WINDOWS
3045   kmp_win32_cond_t th_suspend_cv;
3046   kmp_win32_mutex_t th_suspend_mx;
3047   std::atomic<int> th_suspend_init;
3048 #endif
3049 #if KMP_OS_UNIX
3050   kmp_cond_align_t th_suspend_cv;
3051   kmp_mutex_align_t th_suspend_mx;
3052   std::atomic<int> th_suspend_init_count;
3053 #endif
3054 
3055 #if USE_ITT_BUILD
3056   kmp_itt_mark_t th_itt_mark_single;
3057 // alignment ???
3058 #endif /* USE_ITT_BUILD */
3059 #if KMP_STATS_ENABLED
3060   kmp_stats_list *th_stats;
3061 #endif
3062 #if KMP_OS_UNIX
3063   std::atomic<bool> th_blocking;
3064 #endif
3065   kmp_cg_root_t *th_cg_roots; // list of cg_roots associated with this thread
3066 } kmp_base_info_t;
3067 
3068 typedef union KMP_ALIGN_CACHE kmp_info {
3069   double th_align; /* use worst case alignment */
3070   char th_pad[KMP_PAD(kmp_base_info_t, CACHE_LINE)];
3071   kmp_base_info_t th;
3072 } kmp_info_t;
3073 
3074 // OpenMP thread team data structures
3075 
3076 typedef struct kmp_base_data {
3077   volatile kmp_uint32 t_value;
3078 } kmp_base_data_t;
3079 
3080 typedef union KMP_ALIGN_CACHE kmp_sleep_team {
3081   double dt_align; /* use worst case alignment */
3082   char dt_pad[KMP_PAD(kmp_base_data_t, CACHE_LINE)];
3083   kmp_base_data_t dt;
3084 } kmp_sleep_team_t;
3085 
3086 typedef union KMP_ALIGN_CACHE kmp_ordered_team {
3087   double dt_align; /* use worst case alignment */
3088   char dt_pad[KMP_PAD(kmp_base_data_t, CACHE_LINE)];
3089   kmp_base_data_t dt;
3090 } kmp_ordered_team_t;
3091 
3092 typedef int (*launch_t)(int gtid);
3093 
3094 /* Minimum number of ARGV entries to malloc if necessary */
3095 #define KMP_MIN_MALLOC_ARGV_ENTRIES 100
3096 
3097 // Set up how many argv pointers will fit in cache lines containing
3098 // t_inline_argv. Historically, we have supported at least 96 bytes. Using a
3099 // larger value for more space between the primary write/worker read section and
3100 // read/write by all section seems to buy more performance on EPCC PARALLEL.
3101 #if KMP_ARCH_X86 || KMP_ARCH_X86_64
3102 #define KMP_INLINE_ARGV_BYTES                                                  \
3103   (4 * CACHE_LINE -                                                            \
3104    ((3 * KMP_PTR_SKIP + 2 * sizeof(int) + 2 * sizeof(kmp_int8) +               \
3105      sizeof(kmp_int16) + sizeof(kmp_uint32)) %                                 \
3106     CACHE_LINE))
3107 #else
3108 #define KMP_INLINE_ARGV_BYTES                                                  \
3109   (2 * CACHE_LINE - ((3 * KMP_PTR_SKIP + 2 * sizeof(int)) % CACHE_LINE))
3110 #endif
3111 #define KMP_INLINE_ARGV_ENTRIES (int)(KMP_INLINE_ARGV_BYTES / KMP_PTR_SKIP)
3112 
3113 typedef struct KMP_ALIGN_CACHE kmp_base_team {
3114   // Synchronization Data
3115   // ---------------------------------------------------------------------------
3116   KMP_ALIGN_CACHE kmp_ordered_team_t t_ordered;
3117   kmp_balign_team_t t_bar[bs_last_barrier];
3118   std::atomic<int> t_construct; // count of single directive encountered by team
3119   char pad[sizeof(kmp_lock_t)]; // padding to maintain performance on big iron
3120 
3121   // [0] - parallel / [1] - worksharing task reduction data shared by taskgroups
3122   std::atomic<void *> t_tg_reduce_data[2]; // to support task modifier
3123   std::atomic<int> t_tg_fini_counter[2]; // sync end of task reductions
3124 
3125   // Primary thread only
3126   // ---------------------------------------------------------------------------
3127   KMP_ALIGN_CACHE int t_master_tid; // tid of primary thread in parent team
3128   int t_master_this_cons; // "this_construct" single counter of primary thread
3129   // in parent team
3130   ident_t *t_ident; // if volatile, have to change too much other crud to
3131   // volatile too
3132   kmp_team_p *t_parent; // parent team
3133   kmp_team_p *t_next_pool; // next free team in the team pool
3134   kmp_disp_t *t_dispatch; // thread's dispatch data
3135   kmp_task_team_t *t_task_team[2]; // Task team struct; switch between 2
3136   kmp_proc_bind_t t_proc_bind; // bind type for par region
3137 #if USE_ITT_BUILD
3138   kmp_uint64 t_region_time; // region begin timestamp
3139 #endif /* USE_ITT_BUILD */
3140 
3141   // Primary thread write, workers read
3142   // --------------------------------------------------------------------------
3143   KMP_ALIGN_CACHE void **t_argv;
3144   int t_argc;
3145   int t_nproc; // number of threads in team
3146   microtask_t t_pkfn;
3147   launch_t t_invoke; // procedure to launch the microtask
3148 
3149 #if OMPT_SUPPORT
3150   ompt_team_info_t ompt_team_info;
3151   ompt_lw_taskteam_t *ompt_serialized_team_info;
3152 #endif
3153 
3154 #if KMP_ARCH_X86 || KMP_ARCH_X86_64
3155   kmp_int8 t_fp_control_saved;
3156   kmp_int8 t_pad2b;
3157   kmp_int16 t_x87_fpu_control_word; // FP control regs
3158   kmp_uint32 t_mxcsr;
3159 #endif /* KMP_ARCH_X86 || KMP_ARCH_X86_64 */
3160 
3161   void *t_inline_argv[KMP_INLINE_ARGV_ENTRIES];
3162 
3163   KMP_ALIGN_CACHE kmp_info_t **t_threads;
3164   kmp_taskdata_t
3165       *t_implicit_task_taskdata; // Taskdata for the thread's implicit task
3166   int t_level; // nested parallel level
3167 
3168   KMP_ALIGN_CACHE int t_max_argc;
3169   int t_max_nproc; // max threads this team can handle (dynamically expandable)
3170   int t_serialized; // levels deep of serialized teams
3171   dispatch_shared_info_t *t_disp_buffer; // buffers for dispatch system
3172   int t_id; // team's id, assigned by debugger.
3173   int t_active_level; // nested active parallel level
3174   kmp_r_sched_t t_sched; // run-time schedule for the team
3175 #if KMP_AFFINITY_SUPPORTED
3176   int t_first_place; // first & last place in parent thread's partition.
3177   int t_last_place; // Restore these values to primary thread after par region.
3178 #endif // KMP_AFFINITY_SUPPORTED
3179   int t_display_affinity;
3180   int t_size_changed; // team size was changed?: 0: no, 1: yes, -1: changed via
3181   // omp_set_num_threads() call
3182   omp_allocator_handle_t t_def_allocator; /* default allocator */
3183 
3184 // Read/write by workers as well
3185 #if (KMP_ARCH_X86 || KMP_ARCH_X86_64)
3186   // Using CACHE_LINE=64 reduces memory footprint, but causes a big perf
3187   // regression of epcc 'parallel' and 'barrier' on fxe256lin01. This extra
3188   // padding serves to fix the performance of epcc 'parallel' and 'barrier' when
3189   // CACHE_LINE=64. TODO: investigate more and get rid if this padding.
3190   char dummy_padding[1024];
3191 #endif
3192   // Internal control stack for additional nested teams.
3193   KMP_ALIGN_CACHE kmp_internal_control_t *t_control_stack_top;
3194   // for SERIALIZED teams nested 2 or more levels deep
3195   // typed flag to store request state of cancellation
3196   std::atomic<kmp_int32> t_cancel_request;
3197   int t_master_active; // save on fork, restore on join
3198   void *t_copypriv_data; // team specific pointer to copyprivate data array
3199 #if KMP_OS_WINDOWS
3200   std::atomic<kmp_uint32> t_copyin_counter;
3201 #endif
3202 #if USE_ITT_BUILD
3203   void *t_stack_id; // team specific stack stitching id (for ittnotify)
3204 #endif /* USE_ITT_BUILD */
3205   distributedBarrier *b; // Distributed barrier data associated with team
3206 } kmp_base_team_t;
3207 
3208 union KMP_ALIGN_CACHE kmp_team {
3209   kmp_base_team_t t;
3210   double t_align; /* use worst case alignment */
3211   char t_pad[KMP_PAD(kmp_base_team_t, CACHE_LINE)];
3212 };
3213 
3214 typedef union KMP_ALIGN_CACHE kmp_time_global {
3215   double dt_align; /* use worst case alignment */
3216   char dt_pad[KMP_PAD(kmp_base_data_t, CACHE_LINE)];
3217   kmp_base_data_t dt;
3218 } kmp_time_global_t;
3219 
3220 typedef struct kmp_base_global {
3221   /* cache-aligned */
3222   kmp_time_global_t g_time;
3223 
3224   /* non cache-aligned */
3225   volatile int g_abort;
3226   volatile int g_done;
3227 
3228   int g_dynamic;
3229   enum dynamic_mode g_dynamic_mode;
3230 } kmp_base_global_t;
3231 
3232 typedef union KMP_ALIGN_CACHE kmp_global {
3233   kmp_base_global_t g;
3234   double g_align; /* use worst case alignment */
3235   char g_pad[KMP_PAD(kmp_base_global_t, CACHE_LINE)];
3236 } kmp_global_t;
3237 
3238 typedef struct kmp_base_root {
3239   // TODO: GEH - combine r_active with r_in_parallel then r_active ==
3240   // (r_in_parallel>= 0)
3241   // TODO: GEH - then replace r_active with t_active_levels if we can to reduce
3242   // the synch overhead or keeping r_active
3243   volatile int r_active; /* TRUE if some region in a nest has > 1 thread */
3244   // keeps a count of active parallel regions per root
3245   std::atomic<int> r_in_parallel;
3246   // GEH: This is misnamed, should be r_active_levels
3247   kmp_team_t *r_root_team;
3248   kmp_team_t *r_hot_team;
3249   kmp_info_t *r_uber_thread;
3250   kmp_lock_t r_begin_lock;
3251   volatile int r_begin;
3252   int r_blocktime; /* blocktime for this root and descendants */
3253 #if KMP_AFFINITY_SUPPORTED
3254   int r_affinity_assigned;
3255 #endif // KMP_AFFINITY_SUPPORTED
3256 } kmp_base_root_t;
3257 
3258 typedef union KMP_ALIGN_CACHE kmp_root {
3259   kmp_base_root_t r;
3260   double r_align; /* use worst case alignment */
3261   char r_pad[KMP_PAD(kmp_base_root_t, CACHE_LINE)];
3262 } kmp_root_t;
3263 
3264 struct fortran_inx_info {
3265   kmp_int32 data;
3266 };
3267 
3268 // This list type exists to hold old __kmp_threads arrays so that
3269 // old references to them may complete while reallocation takes place when
3270 // expanding the array. The items in this list are kept alive until library
3271 // shutdown.
3272 typedef struct kmp_old_threads_list_t {
3273   kmp_info_t **threads;
3274   struct kmp_old_threads_list_t *next;
3275 } kmp_old_threads_list_t;
3276 
3277 /* ------------------------------------------------------------------------ */
3278 
3279 extern int __kmp_settings;
3280 extern int __kmp_duplicate_library_ok;
3281 #if USE_ITT_BUILD
3282 extern int __kmp_forkjoin_frames;
3283 extern int __kmp_forkjoin_frames_mode;
3284 #endif
3285 extern PACKED_REDUCTION_METHOD_T __kmp_force_reduction_method;
3286 extern int __kmp_determ_red;
3287 
3288 #ifdef KMP_DEBUG
3289 extern int kmp_a_debug;
3290 extern int kmp_b_debug;
3291 extern int kmp_c_debug;
3292 extern int kmp_d_debug;
3293 extern int kmp_e_debug;
3294 extern int kmp_f_debug;
3295 #endif /* KMP_DEBUG */
3296 
3297 /* For debug information logging using rotating buffer */
3298 #define KMP_DEBUG_BUF_LINES_INIT 512
3299 #define KMP_DEBUG_BUF_LINES_MIN 1
3300 
3301 #define KMP_DEBUG_BUF_CHARS_INIT 128
3302 #define KMP_DEBUG_BUF_CHARS_MIN 2
3303 
3304 extern int
3305     __kmp_debug_buf; /* TRUE means use buffer, FALSE means print to stderr */
3306 extern int __kmp_debug_buf_lines; /* How many lines of debug stored in buffer */
3307 extern int
3308     __kmp_debug_buf_chars; /* How many characters allowed per line in buffer */
3309 extern int __kmp_debug_buf_atomic; /* TRUE means use atomic update of buffer
3310                                       entry pointer */
3311 
3312 extern char *__kmp_debug_buffer; /* Debug buffer itself */
3313 extern std::atomic<int> __kmp_debug_count; /* Counter for number of lines
3314                                               printed in buffer so far */
3315 extern int __kmp_debug_buf_warn_chars; /* Keep track of char increase
3316                                           recommended in warnings */
3317 /* end rotating debug buffer */
3318 
3319 #ifdef KMP_DEBUG
3320 extern int __kmp_par_range; /* +1 => only go par for constructs in range */
3321 
3322 #define KMP_PAR_RANGE_ROUTINE_LEN 1024
3323 extern char __kmp_par_range_routine[KMP_PAR_RANGE_ROUTINE_LEN];
3324 #define KMP_PAR_RANGE_FILENAME_LEN 1024
3325 extern char __kmp_par_range_filename[KMP_PAR_RANGE_FILENAME_LEN];
3326 extern int __kmp_par_range_lb;
3327 extern int __kmp_par_range_ub;
3328 #endif
3329 
3330 /* For printing out dynamic storage map for threads and teams */
3331 extern int
3332     __kmp_storage_map; /* True means print storage map for threads and teams */
3333 extern int __kmp_storage_map_verbose; /* True means storage map includes
3334                                          placement info */
3335 extern int __kmp_storage_map_verbose_specified;
3336 
3337 #if KMP_ARCH_X86 || KMP_ARCH_X86_64
3338 extern kmp_cpuinfo_t __kmp_cpuinfo;
__kmp_is_hybrid_cpu()3339 static inline bool __kmp_is_hybrid_cpu() { return __kmp_cpuinfo.flags.hybrid; }
3340 #elif KMP_OS_DARWIN && KMP_ARCH_AARCH64
__kmp_is_hybrid_cpu()3341 static inline bool __kmp_is_hybrid_cpu() { return true; }
3342 #else
__kmp_is_hybrid_cpu()3343 static inline bool __kmp_is_hybrid_cpu() { return false; }
3344 #endif
3345 
3346 extern volatile int __kmp_init_serial;
3347 extern volatile int __kmp_init_gtid;
3348 extern volatile int __kmp_init_common;
3349 extern volatile int __kmp_need_register_serial;
3350 extern volatile int __kmp_init_middle;
3351 extern volatile int __kmp_init_parallel;
3352 #if KMP_USE_MONITOR
3353 extern volatile int __kmp_init_monitor;
3354 #endif
3355 extern volatile int __kmp_init_user_locks;
3356 extern volatile int __kmp_init_hidden_helper_threads;
3357 extern int __kmp_init_counter;
3358 extern int __kmp_root_counter;
3359 extern int __kmp_version;
3360 
3361 /* list of address of allocated caches for commons */
3362 extern kmp_cached_addr_t *__kmp_threadpriv_cache_list;
3363 
3364 /* Barrier algorithm types and options */
3365 extern kmp_uint32 __kmp_barrier_gather_bb_dflt;
3366 extern kmp_uint32 __kmp_barrier_release_bb_dflt;
3367 extern kmp_bar_pat_e __kmp_barrier_gather_pat_dflt;
3368 extern kmp_bar_pat_e __kmp_barrier_release_pat_dflt;
3369 extern kmp_uint32 __kmp_barrier_gather_branch_bits[bs_last_barrier];
3370 extern kmp_uint32 __kmp_barrier_release_branch_bits[bs_last_barrier];
3371 extern kmp_bar_pat_e __kmp_barrier_gather_pattern[bs_last_barrier];
3372 extern kmp_bar_pat_e __kmp_barrier_release_pattern[bs_last_barrier];
3373 extern char const *__kmp_barrier_branch_bit_env_name[bs_last_barrier];
3374 extern char const *__kmp_barrier_pattern_env_name[bs_last_barrier];
3375 extern char const *__kmp_barrier_type_name[bs_last_barrier];
3376 extern char const *__kmp_barrier_pattern_name[bp_last_bar];
3377 
3378 /* Global Locks */
3379 extern kmp_bootstrap_lock_t __kmp_initz_lock; /* control initialization */
3380 extern kmp_bootstrap_lock_t __kmp_forkjoin_lock; /* control fork/join access */
3381 extern kmp_bootstrap_lock_t __kmp_task_team_lock;
3382 extern kmp_bootstrap_lock_t
3383     __kmp_exit_lock; /* exit() is not always thread-safe */
3384 #if KMP_USE_MONITOR
3385 extern kmp_bootstrap_lock_t
3386     __kmp_monitor_lock; /* control monitor thread creation */
3387 #endif
3388 extern kmp_bootstrap_lock_t
3389     __kmp_tp_cached_lock; /* used for the hack to allow threadprivate cache and
3390                              __kmp_threads expansion to co-exist */
3391 
3392 extern kmp_lock_t __kmp_global_lock; /* control OS/global access  */
3393 extern kmp_queuing_lock_t __kmp_dispatch_lock; /* control dispatch access  */
3394 extern kmp_lock_t __kmp_debug_lock; /* control I/O access for KMP_DEBUG */
3395 
3396 extern enum library_type __kmp_library;
3397 
3398 extern enum sched_type __kmp_sched; /* default runtime scheduling */
3399 extern enum sched_type __kmp_static; /* default static scheduling method */
3400 extern enum sched_type __kmp_guided; /* default guided scheduling method */
3401 extern enum sched_type __kmp_auto; /* default auto scheduling method */
3402 extern int __kmp_chunk; /* default runtime chunk size */
3403 extern int __kmp_force_monotonic; /* whether monotonic scheduling forced */
3404 
3405 extern size_t __kmp_stksize; /* stack size per thread         */
3406 #if KMP_USE_MONITOR
3407 extern size_t __kmp_monitor_stksize; /* stack size for monitor thread */
3408 #endif
3409 extern size_t __kmp_stkoffset; /* stack offset per thread       */
3410 extern int __kmp_stkpadding; /* Should we pad root thread(s) stack */
3411 
3412 extern size_t
3413     __kmp_malloc_pool_incr; /* incremental size of pool for kmp_malloc() */
3414 extern int __kmp_env_stksize; /* was KMP_STACKSIZE specified? */
3415 extern int __kmp_env_blocktime; /* was KMP_BLOCKTIME specified? */
3416 extern int __kmp_env_checks; /* was KMP_CHECKS specified?    */
3417 extern int __kmp_env_consistency_check; // was KMP_CONSISTENCY_CHECK specified?
3418 extern int __kmp_generate_warnings; /* should we issue warnings? */
3419 extern int __kmp_reserve_warn; /* have we issued reserve_threads warning? */
3420 
3421 #ifdef DEBUG_SUSPEND
3422 extern int __kmp_suspend_count; /* count inside __kmp_suspend_template() */
3423 #endif
3424 
3425 extern kmp_int32 __kmp_use_yield;
3426 extern kmp_int32 __kmp_use_yield_exp_set;
3427 extern kmp_uint32 __kmp_yield_init;
3428 extern kmp_uint32 __kmp_yield_next;
3429 extern kmp_uint64 __kmp_pause_init;
3430 
3431 /* ------------------------------------------------------------------------- */
3432 extern int __kmp_allThreadsSpecified;
3433 
3434 extern size_t __kmp_align_alloc;
3435 /* following data protected by initialization routines */
3436 extern int __kmp_xproc; /* number of processors in the system */
3437 extern int __kmp_avail_proc; /* number of processors available to the process */
3438 extern size_t __kmp_sys_min_stksize; /* system-defined minimum stack size */
3439 extern int __kmp_sys_max_nth; /* system-imposed maximum number of threads */
3440 // maximum total number of concurrently-existing threads on device
3441 extern int __kmp_max_nth;
3442 // maximum total number of concurrently-existing threads in a contention group
3443 extern int __kmp_cg_max_nth;
3444 extern int __kmp_task_max_nth; // max threads used in a task
3445 extern int __kmp_teams_max_nth; // max threads used in a teams construct
3446 extern int __kmp_threads_capacity; /* capacity of the arrays __kmp_threads and
3447                                       __kmp_root */
3448 extern int __kmp_dflt_team_nth; /* default number of threads in a parallel
3449                                    region a la OMP_NUM_THREADS */
3450 extern int __kmp_dflt_team_nth_ub; /* upper bound on "" determined at serial
3451                                       initialization */
3452 extern int __kmp_tp_capacity; /* capacity of __kmp_threads if threadprivate is
3453                                  used (fixed) */
3454 extern int __kmp_tp_cached; /* whether threadprivate cache has been created
3455                                (__kmpc_threadprivate_cached()) */
3456 extern int __kmp_dflt_blocktime; /* number of microseconds to wait before
3457                                     blocking (env setting) */
3458 extern char __kmp_blocktime_units; /* 'm' or 'u' to note units specified */
3459 extern bool __kmp_wpolicy_passive; /* explicitly set passive wait policy */
3460 
3461 // Convert raw blocktime from ms to us if needed.
__kmp_aux_convert_blocktime(int * bt)3462 static inline void __kmp_aux_convert_blocktime(int *bt) {
3463   if (__kmp_blocktime_units == 'm') {
3464     if (*bt > INT_MAX / 1000) {
3465       *bt = INT_MAX / 1000;
3466       KMP_INFORM(MaxValueUsing, "kmp_set_blocktime(ms)", bt);
3467     }
3468     *bt = *bt * 1000;
3469   }
3470 }
3471 
3472 #if KMP_USE_MONITOR
3473 extern int
3474     __kmp_monitor_wakeups; /* number of times monitor wakes up per second */
3475 extern int __kmp_bt_intervals; /* number of monitor timestamp intervals before
3476                                   blocking */
3477 #endif
3478 #ifdef KMP_ADJUST_BLOCKTIME
3479 extern int __kmp_zero_bt; /* whether blocktime has been forced to zero */
3480 #endif /* KMP_ADJUST_BLOCKTIME */
3481 #ifdef KMP_DFLT_NTH_CORES
3482 extern int __kmp_ncores; /* Total number of cores for threads placement */
3483 #endif
3484 /* Number of millisecs to delay on abort for Intel(R) VTune(TM) tools */
3485 extern int __kmp_abort_delay;
3486 
3487 extern int __kmp_need_register_atfork_specified;
3488 extern int __kmp_need_register_atfork; /* At initialization, call pthread_atfork
3489                                           to install fork handler */
3490 extern int __kmp_gtid_mode; /* Method of getting gtid, values:
3491                                0 - not set, will be set at runtime
3492                                1 - using stack search
3493                                2 - dynamic TLS (pthread_getspecific(Linux* OS/OS
3494                                    X*) or TlsGetValue(Windows* OS))
3495                                3 - static TLS (__declspec(thread) __kmp_gtid),
3496                                    Linux* OS .so only.  */
3497 extern int
3498     __kmp_adjust_gtid_mode; /* If true, adjust method based on #threads */
3499 #ifdef KMP_TDATA_GTID
3500 extern KMP_THREAD_LOCAL int __kmp_gtid;
3501 #endif
3502 extern int __kmp_tls_gtid_min; /* #threads below which use sp search for gtid */
3503 extern int __kmp_foreign_tp; // If true, separate TP var for each foreign thread
3504 #if KMP_ARCH_X86 || KMP_ARCH_X86_64
3505 extern int __kmp_inherit_fp_control; // copy fp creg(s) parent->workers at fork
3506 extern kmp_int16 __kmp_init_x87_fpu_control_word; // init thread's FP ctrl reg
3507 extern kmp_uint32 __kmp_init_mxcsr; /* init thread's mxscr */
3508 #endif /* KMP_ARCH_X86 || KMP_ARCH_X86_64 */
3509 
3510 // max_active_levels for nested parallelism enabled by default via
3511 // OMP_MAX_ACTIVE_LEVELS, OMP_NESTED, OMP_NUM_THREADS, and OMP_PROC_BIND
3512 extern int __kmp_dflt_max_active_levels;
3513 // Indicates whether value of __kmp_dflt_max_active_levels was already
3514 // explicitly set by OMP_MAX_ACTIVE_LEVELS or OMP_NESTED=false
3515 extern bool __kmp_dflt_max_active_levels_set;
3516 extern int __kmp_dispatch_num_buffers; /* max possible dynamic loops in
3517                                           concurrent execution per team */
3518 #if KMP_NESTED_HOT_TEAMS
3519 extern int __kmp_hot_teams_mode;
3520 extern int __kmp_hot_teams_max_level;
3521 #endif
3522 
3523 #if KMP_OS_LINUX
3524 extern enum clock_function_type __kmp_clock_function;
3525 extern int __kmp_clock_function_param;
3526 #endif /* KMP_OS_LINUX */
3527 
3528 #if KMP_MIC_SUPPORTED
3529 extern enum mic_type __kmp_mic_type;
3530 #endif
3531 
3532 #ifdef USE_LOAD_BALANCE
3533 extern double __kmp_load_balance_interval; // load balance algorithm interval
3534 #endif /* USE_LOAD_BALANCE */
3535 
3536 // OpenMP 3.1 - Nested num threads array
3537 typedef struct kmp_nested_nthreads_t {
3538   int *nth;
3539   int size;
3540   int used;
3541 } kmp_nested_nthreads_t;
3542 
3543 extern kmp_nested_nthreads_t __kmp_nested_nth;
3544 
3545 #if KMP_USE_ADAPTIVE_LOCKS
3546 
3547 // Parameters for the speculative lock backoff system.
3548 struct kmp_adaptive_backoff_params_t {
3549   // Number of soft retries before it counts as a hard retry.
3550   kmp_uint32 max_soft_retries;
3551   // Badness is a bit mask : 0,1,3,7,15,... on each hard failure we move one to
3552   // the right
3553   kmp_uint32 max_badness;
3554 };
3555 
3556 extern kmp_adaptive_backoff_params_t __kmp_adaptive_backoff_params;
3557 
3558 #if KMP_DEBUG_ADAPTIVE_LOCKS
3559 extern const char *__kmp_speculative_statsfile;
3560 #endif
3561 
3562 #endif // KMP_USE_ADAPTIVE_LOCKS
3563 
3564 extern int __kmp_display_env; /* TRUE or FALSE */
3565 extern int __kmp_display_env_verbose; /* TRUE if OMP_DISPLAY_ENV=VERBOSE */
3566 extern int __kmp_omp_cancellation; /* TRUE or FALSE */
3567 extern int __kmp_nteams;
3568 extern int __kmp_teams_thread_limit;
3569 
3570 /* ------------------------------------------------------------------------- */
3571 
3572 /* the following are protected by the fork/join lock */
3573 /* write: lock  read: anytime */
3574 extern kmp_info_t **__kmp_threads; /* Descriptors for the threads */
3575 /* Holds old arrays of __kmp_threads until library shutdown */
3576 extern kmp_old_threads_list_t *__kmp_old_threads_list;
3577 /* read/write: lock */
3578 extern volatile kmp_team_t *__kmp_team_pool;
3579 extern volatile kmp_info_t *__kmp_thread_pool;
3580 extern kmp_info_t *__kmp_thread_pool_insert_pt;
3581 
3582 // total num threads reachable from some root thread including all root threads
3583 extern volatile int __kmp_nth;
3584 /* total number of threads reachable from some root thread including all root
3585    threads, and those in the thread pool */
3586 extern volatile int __kmp_all_nth;
3587 extern std::atomic<int> __kmp_thread_pool_active_nth;
3588 
3589 extern kmp_root_t **__kmp_root; /* root of thread hierarchy */
3590 /* end data protected by fork/join lock */
3591 /* ------------------------------------------------------------------------- */
3592 
3593 #define __kmp_get_gtid() __kmp_get_global_thread_id()
3594 #define __kmp_entry_gtid() __kmp_get_global_thread_id_reg()
3595 #define __kmp_get_tid() (__kmp_tid_from_gtid(__kmp_get_gtid()))
3596 #define __kmp_get_team() (__kmp_threads[(__kmp_get_gtid())]->th.th_team)
3597 #define __kmp_get_thread() (__kmp_thread_from_gtid(__kmp_get_gtid()))
3598 
3599 // AT: Which way is correct?
3600 // AT: 1. nproc = __kmp_threads[ ( gtid ) ] -> th.th_team -> t.t_nproc;
3601 // AT: 2. nproc = __kmp_threads[ ( gtid ) ] -> th.th_team_nproc;
3602 #define __kmp_get_team_num_threads(gtid)                                       \
3603   (__kmp_threads[(gtid)]->th.th_team->t.t_nproc)
3604 
KMP_UBER_GTID(int gtid)3605 static inline bool KMP_UBER_GTID(int gtid) {
3606   KMP_DEBUG_ASSERT(gtid >= KMP_GTID_MIN);
3607   KMP_DEBUG_ASSERT(gtid < __kmp_threads_capacity);
3608   return (gtid >= 0 && __kmp_root[gtid] && __kmp_threads[gtid] &&
3609           __kmp_threads[gtid] == __kmp_root[gtid]->r.r_uber_thread);
3610 }
3611 
__kmp_tid_from_gtid(int gtid)3612 static inline int __kmp_tid_from_gtid(int gtid) {
3613   KMP_DEBUG_ASSERT(gtid >= 0);
3614   return __kmp_threads[gtid]->th.th_info.ds.ds_tid;
3615 }
3616 
__kmp_gtid_from_tid(int tid,const kmp_team_t * team)3617 static inline int __kmp_gtid_from_tid(int tid, const kmp_team_t *team) {
3618   KMP_DEBUG_ASSERT(tid >= 0 && team);
3619   return team->t.t_threads[tid]->th.th_info.ds.ds_gtid;
3620 }
3621 
__kmp_gtid_from_thread(const kmp_info_t * thr)3622 static inline int __kmp_gtid_from_thread(const kmp_info_t *thr) {
3623   KMP_DEBUG_ASSERT(thr);
3624   return thr->th.th_info.ds.ds_gtid;
3625 }
3626 
__kmp_thread_from_gtid(int gtid)3627 static inline kmp_info_t *__kmp_thread_from_gtid(int gtid) {
3628   KMP_DEBUG_ASSERT(gtid >= 0);
3629   return __kmp_threads[gtid];
3630 }
3631 
__kmp_team_from_gtid(int gtid)3632 static inline kmp_team_t *__kmp_team_from_gtid(int gtid) {
3633   KMP_DEBUG_ASSERT(gtid >= 0);
3634   return __kmp_threads[gtid]->th.th_team;
3635 }
3636 
__kmp_assert_valid_gtid(kmp_int32 gtid)3637 static inline void __kmp_assert_valid_gtid(kmp_int32 gtid) {
3638   if (UNLIKELY(gtid < 0 || gtid >= __kmp_threads_capacity))
3639     KMP_FATAL(ThreadIdentInvalid);
3640 }
3641 
3642 #if KMP_HAVE_MWAIT || KMP_HAVE_UMWAIT
3643 extern int __kmp_user_level_mwait; // TRUE or FALSE; from KMP_USER_LEVEL_MWAIT
3644 extern int __kmp_umwait_enabled; // Runtime check if user-level mwait enabled
3645 extern int __kmp_mwait_enabled; // Runtime check if ring3 mwait is enabled
3646 extern int __kmp_mwait_hints; // Hints to pass in to mwait
3647 #endif
3648 
3649 #if KMP_HAVE_UMWAIT
3650 extern int __kmp_waitpkg_enabled; // Runtime check if waitpkg exists
3651 extern int __kmp_tpause_state; // 0 (default), 1=C0.1, 2=C0.2; from KMP_TPAUSE
3652 extern int __kmp_tpause_hint; // 1=C0.1 (default), 0=C0.2; from KMP_TPAUSE
3653 extern int __kmp_tpause_enabled; // 0 (default), 1 (KMP_TPAUSE is non-zero)
3654 #endif
3655 
3656 /* ------------------------------------------------------------------------- */
3657 
3658 extern kmp_global_t __kmp_global; /* global status */
3659 
3660 extern kmp_info_t __kmp_monitor;
3661 // For Debugging Support Library
3662 extern std::atomic<kmp_int32> __kmp_team_counter;
3663 // For Debugging Support Library
3664 extern std::atomic<kmp_int32> __kmp_task_counter;
3665 
3666 #if USE_DEBUGGER
3667 #define _KMP_GEN_ID(counter)                                                   \
3668   (__kmp_debugging ? KMP_ATOMIC_INC(&counter) + 1 : ~0)
3669 #else
3670 #define _KMP_GEN_ID(counter) (~0)
3671 #endif /* USE_DEBUGGER */
3672 
3673 #define KMP_GEN_TASK_ID() _KMP_GEN_ID(__kmp_task_counter)
3674 #define KMP_GEN_TEAM_ID() _KMP_GEN_ID(__kmp_team_counter)
3675 
3676 /* ------------------------------------------------------------------------ */
3677 
3678 extern void __kmp_print_storage_map_gtid(int gtid, void *p1, void *p2,
3679                                          size_t size, char const *format, ...);
3680 
3681 extern void __kmp_serial_initialize(void);
3682 extern void __kmp_middle_initialize(void);
3683 extern void __kmp_parallel_initialize(void);
3684 
3685 extern void __kmp_internal_begin(void);
3686 extern void __kmp_internal_end_library(int gtid);
3687 extern void __kmp_internal_end_thread(int gtid);
3688 extern void __kmp_internal_end_atexit(void);
3689 extern void __kmp_internal_end_dtor(void);
3690 extern void __kmp_internal_end_dest(void *);
3691 
3692 extern int __kmp_register_root(int initial_thread);
3693 extern void __kmp_unregister_root(int gtid);
3694 extern void __kmp_unregister_library(void); // called by __kmp_internal_end()
3695 
3696 extern int __kmp_ignore_mppbeg(void);
3697 extern int __kmp_ignore_mppend(void);
3698 
3699 extern int __kmp_enter_single(int gtid, ident_t *id_ref, int push_ws);
3700 extern void __kmp_exit_single(int gtid);
3701 
3702 extern void __kmp_parallel_deo(int *gtid_ref, int *cid_ref, ident_t *loc_ref);
3703 extern void __kmp_parallel_dxo(int *gtid_ref, int *cid_ref, ident_t *loc_ref);
3704 
3705 #ifdef USE_LOAD_BALANCE
3706 extern int __kmp_get_load_balance(int);
3707 #endif
3708 
3709 extern int __kmp_get_global_thread_id(void);
3710 extern int __kmp_get_global_thread_id_reg(void);
3711 extern void __kmp_exit_thread(int exit_status);
3712 extern void __kmp_abort(char const *format, ...);
3713 extern void __kmp_abort_thread(void);
3714 KMP_NORETURN extern void __kmp_abort_process(void);
3715 extern void __kmp_warn(char const *format, ...);
3716 
3717 extern void __kmp_set_num_threads(int new_nth, int gtid);
3718 
3719 extern bool __kmp_detect_shm();
3720 extern bool __kmp_detect_tmp();
3721 
3722 // Returns current thread (pointer to kmp_info_t). Current thread *must* be
3723 // registered.
__kmp_entry_thread()3724 static inline kmp_info_t *__kmp_entry_thread() {
3725   int gtid = __kmp_entry_gtid();
3726 
3727   return __kmp_threads[gtid];
3728 }
3729 
3730 extern void __kmp_set_max_active_levels(int gtid, int new_max_active_levels);
3731 extern int __kmp_get_max_active_levels(int gtid);
3732 extern int __kmp_get_ancestor_thread_num(int gtid, int level);
3733 extern int __kmp_get_team_size(int gtid, int level);
3734 extern void __kmp_set_schedule(int gtid, kmp_sched_t new_sched, int chunk);
3735 extern void __kmp_get_schedule(int gtid, kmp_sched_t *sched, int *chunk);
3736 
3737 extern unsigned short __kmp_get_random(kmp_info_t *thread);
3738 extern void __kmp_init_random(kmp_info_t *thread);
3739 
3740 extern kmp_r_sched_t __kmp_get_schedule_global(void);
3741 extern void __kmp_adjust_num_threads(int new_nproc);
3742 extern void __kmp_check_stksize(size_t *val);
3743 
3744 extern void *___kmp_allocate(size_t size KMP_SRC_LOC_DECL);
3745 extern void *___kmp_page_allocate(size_t size KMP_SRC_LOC_DECL);
3746 extern void ___kmp_free(void *ptr KMP_SRC_LOC_DECL);
3747 #define __kmp_allocate(size) ___kmp_allocate((size)KMP_SRC_LOC_CURR)
3748 #define __kmp_page_allocate(size) ___kmp_page_allocate((size)KMP_SRC_LOC_CURR)
3749 #define __kmp_free(ptr) ___kmp_free((ptr)KMP_SRC_LOC_CURR)
3750 
3751 #if USE_FAST_MEMORY
3752 extern void *___kmp_fast_allocate(kmp_info_t *this_thr,
3753                                   size_t size KMP_SRC_LOC_DECL);
3754 extern void ___kmp_fast_free(kmp_info_t *this_thr, void *ptr KMP_SRC_LOC_DECL);
3755 extern void __kmp_free_fast_memory(kmp_info_t *this_thr);
3756 extern void __kmp_initialize_fast_memory(kmp_info_t *this_thr);
3757 #define __kmp_fast_allocate(this_thr, size)                                    \
3758   ___kmp_fast_allocate((this_thr), (size)KMP_SRC_LOC_CURR)
3759 #define __kmp_fast_free(this_thr, ptr)                                         \
3760   ___kmp_fast_free((this_thr), (ptr)KMP_SRC_LOC_CURR)
3761 #endif
3762 
3763 extern void *___kmp_thread_malloc(kmp_info_t *th, size_t size KMP_SRC_LOC_DECL);
3764 extern void *___kmp_thread_calloc(kmp_info_t *th, size_t nelem,
3765                                   size_t elsize KMP_SRC_LOC_DECL);
3766 extern void *___kmp_thread_realloc(kmp_info_t *th, void *ptr,
3767                                    size_t size KMP_SRC_LOC_DECL);
3768 extern void ___kmp_thread_free(kmp_info_t *th, void *ptr KMP_SRC_LOC_DECL);
3769 #define __kmp_thread_malloc(th, size)                                          \
3770   ___kmp_thread_malloc((th), (size)KMP_SRC_LOC_CURR)
3771 #define __kmp_thread_calloc(th, nelem, elsize)                                 \
3772   ___kmp_thread_calloc((th), (nelem), (elsize)KMP_SRC_LOC_CURR)
3773 #define __kmp_thread_realloc(th, ptr, size)                                    \
3774   ___kmp_thread_realloc((th), (ptr), (size)KMP_SRC_LOC_CURR)
3775 #define __kmp_thread_free(th, ptr)                                             \
3776   ___kmp_thread_free((th), (ptr)KMP_SRC_LOC_CURR)
3777 
3778 extern void __kmp_push_num_threads(ident_t *loc, int gtid, int num_threads);
3779 
3780 extern void __kmp_push_proc_bind(ident_t *loc, int gtid,
3781                                  kmp_proc_bind_t proc_bind);
3782 extern void __kmp_push_num_teams(ident_t *loc, int gtid, int num_teams,
3783                                  int num_threads);
3784 extern void __kmp_push_num_teams_51(ident_t *loc, int gtid, int num_teams_lb,
3785                                     int num_teams_ub, int num_threads);
3786 
3787 extern void __kmp_yield();
3788 
3789 extern void __kmpc_dispatch_init_4(ident_t *loc, kmp_int32 gtid,
3790                                    enum sched_type schedule, kmp_int32 lb,
3791                                    kmp_int32 ub, kmp_int32 st, kmp_int32 chunk);
3792 extern void __kmpc_dispatch_init_4u(ident_t *loc, kmp_int32 gtid,
3793                                     enum sched_type schedule, kmp_uint32 lb,
3794                                     kmp_uint32 ub, kmp_int32 st,
3795                                     kmp_int32 chunk);
3796 extern void __kmpc_dispatch_init_8(ident_t *loc, kmp_int32 gtid,
3797                                    enum sched_type schedule, kmp_int64 lb,
3798                                    kmp_int64 ub, kmp_int64 st, kmp_int64 chunk);
3799 extern void __kmpc_dispatch_init_8u(ident_t *loc, kmp_int32 gtid,
3800                                     enum sched_type schedule, kmp_uint64 lb,
3801                                     kmp_uint64 ub, kmp_int64 st,
3802                                     kmp_int64 chunk);
3803 
3804 extern int __kmpc_dispatch_next_4(ident_t *loc, kmp_int32 gtid,
3805                                   kmp_int32 *p_last, kmp_int32 *p_lb,
3806                                   kmp_int32 *p_ub, kmp_int32 *p_st);
3807 extern int __kmpc_dispatch_next_4u(ident_t *loc, kmp_int32 gtid,
3808                                    kmp_int32 *p_last, kmp_uint32 *p_lb,
3809                                    kmp_uint32 *p_ub, kmp_int32 *p_st);
3810 extern int __kmpc_dispatch_next_8(ident_t *loc, kmp_int32 gtid,
3811                                   kmp_int32 *p_last, kmp_int64 *p_lb,
3812                                   kmp_int64 *p_ub, kmp_int64 *p_st);
3813 extern int __kmpc_dispatch_next_8u(ident_t *loc, kmp_int32 gtid,
3814                                    kmp_int32 *p_last, kmp_uint64 *p_lb,
3815                                    kmp_uint64 *p_ub, kmp_int64 *p_st);
3816 
3817 extern void __kmpc_dispatch_fini_4(ident_t *loc, kmp_int32 gtid);
3818 extern void __kmpc_dispatch_fini_8(ident_t *loc, kmp_int32 gtid);
3819 extern void __kmpc_dispatch_fini_4u(ident_t *loc, kmp_int32 gtid);
3820 extern void __kmpc_dispatch_fini_8u(ident_t *loc, kmp_int32 gtid);
3821 
3822 #ifdef KMP_GOMP_COMPAT
3823 
3824 extern void __kmp_aux_dispatch_init_4(ident_t *loc, kmp_int32 gtid,
3825                                       enum sched_type schedule, kmp_int32 lb,
3826                                       kmp_int32 ub, kmp_int32 st,
3827                                       kmp_int32 chunk, int push_ws);
3828 extern void __kmp_aux_dispatch_init_4u(ident_t *loc, kmp_int32 gtid,
3829                                        enum sched_type schedule, kmp_uint32 lb,
3830                                        kmp_uint32 ub, kmp_int32 st,
3831                                        kmp_int32 chunk, int push_ws);
3832 extern void __kmp_aux_dispatch_init_8(ident_t *loc, kmp_int32 gtid,
3833                                       enum sched_type schedule, kmp_int64 lb,
3834                                       kmp_int64 ub, kmp_int64 st,
3835                                       kmp_int64 chunk, int push_ws);
3836 extern void __kmp_aux_dispatch_init_8u(ident_t *loc, kmp_int32 gtid,
3837                                        enum sched_type schedule, kmp_uint64 lb,
3838                                        kmp_uint64 ub, kmp_int64 st,
3839                                        kmp_int64 chunk, int push_ws);
3840 extern void __kmp_aux_dispatch_fini_chunk_4(ident_t *loc, kmp_int32 gtid);
3841 extern void __kmp_aux_dispatch_fini_chunk_8(ident_t *loc, kmp_int32 gtid);
3842 extern void __kmp_aux_dispatch_fini_chunk_4u(ident_t *loc, kmp_int32 gtid);
3843 extern void __kmp_aux_dispatch_fini_chunk_8u(ident_t *loc, kmp_int32 gtid);
3844 
3845 #endif /* KMP_GOMP_COMPAT */
3846 
3847 extern kmp_uint32 __kmp_eq_4(kmp_uint32 value, kmp_uint32 checker);
3848 extern kmp_uint32 __kmp_neq_4(kmp_uint32 value, kmp_uint32 checker);
3849 extern kmp_uint32 __kmp_lt_4(kmp_uint32 value, kmp_uint32 checker);
3850 extern kmp_uint32 __kmp_ge_4(kmp_uint32 value, kmp_uint32 checker);
3851 extern kmp_uint32 __kmp_le_4(kmp_uint32 value, kmp_uint32 checker);
3852 extern kmp_uint32 __kmp_wait_4(kmp_uint32 volatile *spinner, kmp_uint32 checker,
3853                                kmp_uint32 (*pred)(kmp_uint32, kmp_uint32),
3854                                void *obj);
3855 extern void __kmp_wait_4_ptr(void *spinner, kmp_uint32 checker,
3856                              kmp_uint32 (*pred)(void *, kmp_uint32), void *obj);
3857 
3858 extern void __kmp_wait_64(kmp_info_t *this_thr, kmp_flag_64<> *flag,
3859                           int final_spin
3860 #if USE_ITT_BUILD
3861                           ,
3862                           void *itt_sync_obj
3863 #endif
3864 );
3865 extern void __kmp_release_64(kmp_flag_64<> *flag);
3866 
3867 extern void __kmp_infinite_loop(void);
3868 
3869 extern void __kmp_cleanup(void);
3870 
3871 #if KMP_HANDLE_SIGNALS
3872 extern int __kmp_handle_signals;
3873 extern void __kmp_install_signals(int parallel_init);
3874 extern void __kmp_remove_signals(void);
3875 #endif
3876 
3877 extern void __kmp_clear_system_time(void);
3878 extern void __kmp_read_system_time(double *delta);
3879 
3880 extern void __kmp_check_stack_overlap(kmp_info_t *thr);
3881 
3882 extern void __kmp_expand_host_name(char *buffer, size_t size);
3883 extern void __kmp_expand_file_name(char *result, size_t rlen, char *pattern);
3884 
3885 #if KMP_ARCH_X86 || KMP_ARCH_X86_64 || (KMP_OS_WINDOWS && (KMP_ARCH_AARCH64 || KMP_ARCH_ARM))
3886 extern void
3887 __kmp_initialize_system_tick(void); /* Initialize timer tick value */
3888 #endif
3889 
3890 extern void
3891 __kmp_runtime_initialize(void); /* machine specific initialization */
3892 extern void __kmp_runtime_destroy(void);
3893 
3894 #if KMP_AFFINITY_SUPPORTED
3895 extern char *__kmp_affinity_print_mask(char *buf, int buf_len,
3896                                        kmp_affin_mask_t *mask);
3897 extern kmp_str_buf_t *__kmp_affinity_str_buf_mask(kmp_str_buf_t *buf,
3898                                                   kmp_affin_mask_t *mask);
3899 extern void __kmp_affinity_initialize(kmp_affinity_t &affinity);
3900 extern void __kmp_affinity_uninitialize(void);
3901 extern void __kmp_affinity_set_init_mask(
3902     int gtid, int isa_root); /* set affinity according to KMP_AFFINITY */
3903 void __kmp_affinity_bind_init_mask(int gtid);
3904 extern void __kmp_affinity_bind_place(int gtid);
3905 extern void __kmp_affinity_determine_capable(const char *env_var);
3906 extern int __kmp_aux_set_affinity(void **mask);
3907 extern int __kmp_aux_get_affinity(void **mask);
3908 extern int __kmp_aux_get_affinity_max_proc();
3909 extern int __kmp_aux_set_affinity_mask_proc(int proc, void **mask);
3910 extern int __kmp_aux_unset_affinity_mask_proc(int proc, void **mask);
3911 extern int __kmp_aux_get_affinity_mask_proc(int proc, void **mask);
3912 extern void __kmp_balanced_affinity(kmp_info_t *th, int team_size);
3913 #if KMP_WEIGHTED_ITERATIONS_SUPPORTED
3914 extern int __kmp_get_first_osid_with_ecore(void);
3915 #endif
3916 #if KMP_OS_LINUX || KMP_OS_FREEBSD || KMP_OS_AIX
3917 extern int kmp_set_thread_affinity_mask_initial(void);
3918 #endif
__kmp_assign_root_init_mask()3919 static inline void __kmp_assign_root_init_mask() {
3920   int gtid = __kmp_entry_gtid();
3921   kmp_root_t *r = __kmp_threads[gtid]->th.th_root;
3922   if (r->r.r_uber_thread == __kmp_threads[gtid] && !r->r.r_affinity_assigned) {
3923     __kmp_affinity_set_init_mask(gtid, /*isa_root=*/TRUE);
3924     __kmp_affinity_bind_init_mask(gtid);
3925     r->r.r_affinity_assigned = TRUE;
3926   }
3927 }
__kmp_reset_root_init_mask(int gtid)3928 static inline void __kmp_reset_root_init_mask(int gtid) {
3929   if (!KMP_AFFINITY_CAPABLE())
3930     return;
3931   kmp_info_t *th = __kmp_threads[gtid];
3932   kmp_root_t *r = th->th.th_root;
3933   if (r->r.r_uber_thread == th && r->r.r_affinity_assigned) {
3934     __kmp_set_system_affinity(__kmp_affin_origMask, FALSE);
3935     KMP_CPU_COPY(th->th.th_affin_mask, __kmp_affin_origMask);
3936     r->r.r_affinity_assigned = FALSE;
3937   }
3938 }
3939 #else /* KMP_AFFINITY_SUPPORTED */
3940 #define __kmp_assign_root_init_mask() /* Nothing */
__kmp_reset_root_init_mask(int gtid)3941 static inline void __kmp_reset_root_init_mask(int gtid) {}
3942 #endif /* KMP_AFFINITY_SUPPORTED */
3943 // No need for KMP_AFFINITY_SUPPORTED guard as only one field in the
3944 // format string is for affinity, so platforms that do not support
3945 // affinity can still use the other fields, e.g., %n for num_threads
3946 extern size_t __kmp_aux_capture_affinity(int gtid, const char *format,
3947                                          kmp_str_buf_t *buffer);
3948 extern void __kmp_aux_display_affinity(int gtid, const char *format);
3949 
3950 extern void __kmp_cleanup_hierarchy();
3951 extern void __kmp_get_hierarchy(kmp_uint32 nproc, kmp_bstate_t *thr_bar);
3952 
3953 #if KMP_USE_FUTEX
3954 
3955 extern int __kmp_futex_determine_capable(void);
3956 
3957 #endif // KMP_USE_FUTEX
3958 
3959 extern void __kmp_gtid_set_specific(int gtid);
3960 extern int __kmp_gtid_get_specific(void);
3961 
3962 extern double __kmp_read_cpu_time(void);
3963 
3964 extern int __kmp_read_system_info(struct kmp_sys_info *info);
3965 
3966 #if KMP_USE_MONITOR
3967 extern void __kmp_create_monitor(kmp_info_t *th);
3968 #endif
3969 
3970 extern void *__kmp_launch_thread(kmp_info_t *thr);
3971 
3972 extern void __kmp_create_worker(int gtid, kmp_info_t *th, size_t stack_size);
3973 
3974 #if KMP_OS_WINDOWS
3975 extern int __kmp_still_running(kmp_info_t *th);
3976 extern int __kmp_is_thread_alive(kmp_info_t *th, DWORD *exit_val);
3977 extern void __kmp_free_handle(kmp_thread_t tHandle);
3978 #endif
3979 
3980 #if KMP_USE_MONITOR
3981 extern void __kmp_reap_monitor(kmp_info_t *th);
3982 #endif
3983 extern void __kmp_reap_worker(kmp_info_t *th);
3984 extern void __kmp_terminate_thread(int gtid);
3985 
3986 extern int __kmp_try_suspend_mx(kmp_info_t *th);
3987 extern void __kmp_lock_suspend_mx(kmp_info_t *th);
3988 extern void __kmp_unlock_suspend_mx(kmp_info_t *th);
3989 
3990 extern void __kmp_elapsed(double *);
3991 extern void __kmp_elapsed_tick(double *);
3992 
3993 extern void __kmp_enable(int old_state);
3994 extern void __kmp_disable(int *old_state);
3995 
3996 extern void __kmp_thread_sleep(int millis);
3997 
3998 extern void __kmp_common_initialize(void);
3999 extern void __kmp_common_destroy(void);
4000 extern void __kmp_common_destroy_gtid(int gtid);
4001 
4002 #if KMP_OS_UNIX
4003 extern void __kmp_register_atfork(void);
4004 #endif
4005 extern void __kmp_suspend_initialize(void);
4006 extern void __kmp_suspend_initialize_thread(kmp_info_t *th);
4007 extern void __kmp_suspend_uninitialize_thread(kmp_info_t *th);
4008 
4009 extern kmp_info_t *__kmp_allocate_thread(kmp_root_t *root, kmp_team_t *team,
4010                                          int tid);
4011 extern kmp_team_t *
4012 __kmp_allocate_team(kmp_root_t *root, int new_nproc, int max_nproc,
4013 #if OMPT_SUPPORT
4014                     ompt_data_t ompt_parallel_data,
4015 #endif
4016                     kmp_proc_bind_t proc_bind, kmp_internal_control_t *new_icvs,
4017                     int argc USE_NESTED_HOT_ARG(kmp_info_t *thr));
4018 extern void __kmp_free_thread(kmp_info_t *);
4019 extern void __kmp_free_team(kmp_root_t *,
4020                             kmp_team_t *USE_NESTED_HOT_ARG(kmp_info_t *));
4021 extern kmp_team_t *__kmp_reap_team(kmp_team_t *);
4022 
4023 /* ------------------------------------------------------------------------ */
4024 
4025 extern void __kmp_initialize_bget(kmp_info_t *th);
4026 extern void __kmp_finalize_bget(kmp_info_t *th);
4027 
4028 KMP_EXPORT void *kmpc_malloc(size_t size);
4029 KMP_EXPORT void *kmpc_aligned_malloc(size_t size, size_t alignment);
4030 KMP_EXPORT void *kmpc_calloc(size_t nelem, size_t elsize);
4031 KMP_EXPORT void *kmpc_realloc(void *ptr, size_t size);
4032 KMP_EXPORT void kmpc_free(void *ptr);
4033 
4034 /* declarations for internal use */
4035 
4036 extern int __kmp_barrier(enum barrier_type bt, int gtid, int is_split,
4037                          size_t reduce_size, void *reduce_data,
4038                          void (*reduce)(void *, void *));
4039 extern void __kmp_end_split_barrier(enum barrier_type bt, int gtid);
4040 extern int __kmp_barrier_gomp_cancel(int gtid);
4041 
4042 /*!
4043  * Tell the fork call which compiler generated the fork call, and therefore how
4044  * to deal with the call.
4045  */
4046 enum fork_context_e {
4047   fork_context_gnu, /**< Called from GNU generated code, so must not invoke the
4048                        microtask internally. */
4049   fork_context_intel, /**< Called from Intel generated code.  */
4050   fork_context_last
4051 };
4052 extern int __kmp_fork_call(ident_t *loc, int gtid,
4053                            enum fork_context_e fork_context, kmp_int32 argc,
4054                            microtask_t microtask, launch_t invoker,
4055                            kmp_va_list ap);
4056 
4057 extern void __kmp_join_call(ident_t *loc, int gtid
4058 #if OMPT_SUPPORT
4059                             ,
4060                             enum fork_context_e fork_context
4061 #endif
4062                             ,
4063                             int exit_teams = 0);
4064 
4065 extern void __kmp_serialized_parallel(ident_t *id, kmp_int32 gtid);
4066 extern void __kmp_internal_fork(ident_t *id, int gtid, kmp_team_t *team);
4067 extern void __kmp_internal_join(ident_t *id, int gtid, kmp_team_t *team);
4068 extern int __kmp_invoke_task_func(int gtid);
4069 extern void __kmp_run_before_invoked_task(int gtid, int tid,
4070                                           kmp_info_t *this_thr,
4071                                           kmp_team_t *team);
4072 extern void __kmp_run_after_invoked_task(int gtid, int tid,
4073                                          kmp_info_t *this_thr,
4074                                          kmp_team_t *team);
4075 
4076 // should never have been exported
4077 KMP_EXPORT int __kmpc_invoke_task_func(int gtid);
4078 extern int __kmp_invoke_teams_master(int gtid);
4079 extern void __kmp_teams_master(int gtid);
4080 extern int __kmp_aux_get_team_num();
4081 extern int __kmp_aux_get_num_teams();
4082 extern void __kmp_save_internal_controls(kmp_info_t *thread);
4083 extern void __kmp_user_set_library(enum library_type arg);
4084 extern void __kmp_aux_set_library(enum library_type arg);
4085 extern void __kmp_aux_set_stacksize(size_t arg);
4086 extern void __kmp_aux_set_blocktime(int arg, kmp_info_t *thread, int tid);
4087 extern void __kmp_aux_set_defaults(char const *str, size_t len);
4088 
4089 /* Functions called from __kmp_aux_env_initialize() in kmp_settings.cpp */
4090 void kmpc_set_blocktime(int arg);
4091 void ompc_set_nested(int flag);
4092 void ompc_set_dynamic(int flag);
4093 void ompc_set_num_threads(int arg);
4094 
4095 extern void __kmp_push_current_task_to_thread(kmp_info_t *this_thr,
4096                                               kmp_team_t *team, int tid);
4097 extern void __kmp_pop_current_task_from_thread(kmp_info_t *this_thr);
4098 extern kmp_task_t *__kmp_task_alloc(ident_t *loc_ref, kmp_int32 gtid,
4099                                     kmp_tasking_flags_t *flags,
4100                                     size_t sizeof_kmp_task_t,
4101                                     size_t sizeof_shareds,
4102                                     kmp_routine_entry_t task_entry);
4103 extern void __kmp_init_implicit_task(ident_t *loc_ref, kmp_info_t *this_thr,
4104                                      kmp_team_t *team, int tid,
4105                                      int set_curr_task);
4106 extern void __kmp_finish_implicit_task(kmp_info_t *this_thr);
4107 extern void __kmp_free_implicit_task(kmp_info_t *this_thr);
4108 
4109 extern kmp_event_t *__kmpc_task_allow_completion_event(ident_t *loc_ref,
4110                                                        int gtid,
4111                                                        kmp_task_t *task);
4112 extern void __kmp_fulfill_event(kmp_event_t *event);
4113 
4114 extern void __kmp_free_task_team(kmp_info_t *thread,
4115                                  kmp_task_team_t *task_team);
4116 extern void __kmp_reap_task_teams(void);
4117 extern void __kmp_wait_to_unref_task_teams(void);
4118 extern void __kmp_task_team_setup(kmp_info_t *this_thr, kmp_team_t *team,
4119                                   int always);
4120 extern void __kmp_task_team_sync(kmp_info_t *this_thr, kmp_team_t *team);
4121 extern void __kmp_task_team_wait(kmp_info_t *this_thr, kmp_team_t *team
4122 #if USE_ITT_BUILD
4123                                  ,
4124                                  void *itt_sync_obj
4125 #endif /* USE_ITT_BUILD */
4126                                  ,
4127                                  int wait = 1);
4128 extern void __kmp_tasking_barrier(kmp_team_t *team, kmp_info_t *thread,
4129                                   int gtid);
4130 
4131 extern int __kmp_is_address_mapped(void *addr);
4132 extern kmp_uint64 __kmp_hardware_timestamp(void);
4133 
4134 #if KMP_OS_UNIX
4135 extern int __kmp_read_from_file(char const *path, char const *format, ...);
4136 #endif
4137 
4138 /* ------------------------------------------------------------------------ */
4139 //
4140 // Assembly routines that have no compiler intrinsic replacement
4141 //
4142 
4143 extern int __kmp_invoke_microtask(microtask_t pkfn, int gtid, int npr, int argc,
4144                                   void *argv[]
4145 #if OMPT_SUPPORT
4146                                   ,
4147                                   void **exit_frame_ptr
4148 #endif
4149 );
4150 
4151 /* ------------------------------------------------------------------------ */
4152 
4153 KMP_EXPORT void __kmpc_begin(ident_t *, kmp_int32 flags);
4154 KMP_EXPORT void __kmpc_end(ident_t *);
4155 
4156 KMP_EXPORT void __kmpc_threadprivate_register_vec(ident_t *, void *data,
4157                                                   kmpc_ctor_vec ctor,
4158                                                   kmpc_cctor_vec cctor,
4159                                                   kmpc_dtor_vec dtor,
4160                                                   size_t vector_length);
4161 KMP_EXPORT void __kmpc_threadprivate_register(ident_t *, void *data,
4162                                               kmpc_ctor ctor, kmpc_cctor cctor,
4163                                               kmpc_dtor dtor);
4164 KMP_EXPORT void *__kmpc_threadprivate(ident_t *, kmp_int32 global_tid,
4165                                       void *data, size_t size);
4166 
4167 KMP_EXPORT kmp_int32 __kmpc_global_thread_num(ident_t *);
4168 KMP_EXPORT kmp_int32 __kmpc_global_num_threads(ident_t *);
4169 KMP_EXPORT kmp_int32 __kmpc_bound_thread_num(ident_t *);
4170 KMP_EXPORT kmp_int32 __kmpc_bound_num_threads(ident_t *);
4171 
4172 KMP_EXPORT kmp_int32 __kmpc_ok_to_fork(ident_t *);
4173 KMP_EXPORT void __kmpc_fork_call(ident_t *, kmp_int32 nargs,
4174                                  kmpc_micro microtask, ...);
4175 KMP_EXPORT void __kmpc_fork_call_if(ident_t *loc, kmp_int32 nargs,
4176                                     kmpc_micro microtask, kmp_int32 cond,
4177                                     void *args);
4178 
4179 KMP_EXPORT void __kmpc_serialized_parallel(ident_t *, kmp_int32 global_tid);
4180 KMP_EXPORT void __kmpc_end_serialized_parallel(ident_t *, kmp_int32 global_tid);
4181 
4182 KMP_EXPORT void __kmpc_flush(ident_t *);
4183 KMP_EXPORT void __kmpc_barrier(ident_t *, kmp_int32 global_tid);
4184 KMP_EXPORT kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid);
4185 KMP_EXPORT void __kmpc_end_master(ident_t *, kmp_int32 global_tid);
4186 KMP_EXPORT kmp_int32 __kmpc_masked(ident_t *, kmp_int32 global_tid,
4187                                    kmp_int32 filter);
4188 KMP_EXPORT void __kmpc_end_masked(ident_t *, kmp_int32 global_tid);
4189 KMP_EXPORT void __kmpc_ordered(ident_t *, kmp_int32 global_tid);
4190 KMP_EXPORT void __kmpc_end_ordered(ident_t *, kmp_int32 global_tid);
4191 KMP_EXPORT void __kmpc_critical(ident_t *, kmp_int32 global_tid,
4192                                 kmp_critical_name *);
4193 KMP_EXPORT void __kmpc_end_critical(ident_t *, kmp_int32 global_tid,
4194                                     kmp_critical_name *);
4195 KMP_EXPORT void __kmpc_critical_with_hint(ident_t *, kmp_int32 global_tid,
4196                                           kmp_critical_name *, uint32_t hint);
4197 
4198 KMP_EXPORT kmp_int32 __kmpc_barrier_master(ident_t *, kmp_int32 global_tid);
4199 KMP_EXPORT void __kmpc_end_barrier_master(ident_t *, kmp_int32 global_tid);
4200 
4201 KMP_EXPORT kmp_int32 __kmpc_barrier_master_nowait(ident_t *,
4202                                                   kmp_int32 global_tid);
4203 
4204 KMP_EXPORT kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid);
4205 KMP_EXPORT void __kmpc_end_single(ident_t *, kmp_int32 global_tid);
4206 
4207 KMP_EXPORT kmp_int32 __kmpc_sections_init(ident_t *loc, kmp_int32 global_tid);
4208 KMP_EXPORT kmp_int32 __kmpc_next_section(ident_t *loc, kmp_int32 global_tid,
4209                                          kmp_int32 numberOfSections);
4210 KMP_EXPORT void __kmpc_end_sections(ident_t *loc, kmp_int32 global_tid);
4211 
4212 KMP_EXPORT void KMPC_FOR_STATIC_INIT(ident_t *loc, kmp_int32 global_tid,
4213                                      kmp_int32 schedtype, kmp_int32 *plastiter,
4214                                      kmp_int *plower, kmp_int *pupper,
4215                                      kmp_int *pstride, kmp_int incr,
4216                                      kmp_int chunk);
4217 
4218 KMP_EXPORT void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
4219 
4220 KMP_EXPORT void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
4221                                    size_t cpy_size, void *cpy_data,
4222                                    void (*cpy_func)(void *, void *),
4223                                    kmp_int32 didit);
4224 
4225 KMP_EXPORT void *__kmpc_copyprivate_light(ident_t *loc, kmp_int32 gtid,
4226                                           void *cpy_data);
4227 
4228 extern void KMPC_SET_NUM_THREADS(int arg);
4229 extern void KMPC_SET_DYNAMIC(int flag);
4230 extern void KMPC_SET_NESTED(int flag);
4231 
4232 /* OMP 3.0 tasking interface routines */
4233 KMP_EXPORT kmp_int32 __kmpc_omp_task(ident_t *loc_ref, kmp_int32 gtid,
4234                                      kmp_task_t *new_task);
4235 KMP_EXPORT kmp_task_t *__kmpc_omp_task_alloc(ident_t *loc_ref, kmp_int32 gtid,
4236                                              kmp_int32 flags,
4237                                              size_t sizeof_kmp_task_t,
4238                                              size_t sizeof_shareds,
4239                                              kmp_routine_entry_t task_entry);
4240 KMP_EXPORT kmp_task_t *__kmpc_omp_target_task_alloc(
4241     ident_t *loc_ref, kmp_int32 gtid, kmp_int32 flags, size_t sizeof_kmp_task_t,
4242     size_t sizeof_shareds, kmp_routine_entry_t task_entry, kmp_int64 device_id);
4243 KMP_EXPORT void __kmpc_omp_task_begin_if0(ident_t *loc_ref, kmp_int32 gtid,
4244                                           kmp_task_t *task);
4245 KMP_EXPORT void __kmpc_omp_task_complete_if0(ident_t *loc_ref, kmp_int32 gtid,
4246                                              kmp_task_t *task);
4247 KMP_EXPORT kmp_int32 __kmpc_omp_task_parts(ident_t *loc_ref, kmp_int32 gtid,
4248                                            kmp_task_t *new_task);
4249 KMP_EXPORT kmp_int32 __kmpc_omp_taskwait(ident_t *loc_ref, kmp_int32 gtid);
4250 KMP_EXPORT kmp_int32 __kmpc_omp_taskyield(ident_t *loc_ref, kmp_int32 gtid,
4251                                           int end_part);
4252 
4253 #if TASK_UNUSED
4254 void __kmpc_omp_task_begin(ident_t *loc_ref, kmp_int32 gtid, kmp_task_t *task);
4255 void __kmpc_omp_task_complete(ident_t *loc_ref, kmp_int32 gtid,
4256                               kmp_task_t *task);
4257 #endif // TASK_UNUSED
4258 
4259 /* ------------------------------------------------------------------------ */
4260 
4261 KMP_EXPORT void __kmpc_taskgroup(ident_t *loc, int gtid);
4262 KMP_EXPORT void __kmpc_end_taskgroup(ident_t *loc, int gtid);
4263 
4264 KMP_EXPORT kmp_int32 __kmpc_omp_task_with_deps(
4265     ident_t *loc_ref, kmp_int32 gtid, kmp_task_t *new_task, kmp_int32 ndeps,
4266     kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
4267     kmp_depend_info_t *noalias_dep_list);
4268 
4269 KMP_EXPORT kmp_base_depnode_t *__kmpc_task_get_depnode(kmp_task_t *task);
4270 
4271 KMP_EXPORT kmp_depnode_list_t *__kmpc_task_get_successors(kmp_task_t *task);
4272 
4273 KMP_EXPORT void __kmpc_omp_wait_deps(ident_t *loc_ref, kmp_int32 gtid,
4274                                      kmp_int32 ndeps,
4275                                      kmp_depend_info_t *dep_list,
4276                                      kmp_int32 ndeps_noalias,
4277                                      kmp_depend_info_t *noalias_dep_list);
4278 /* __kmpc_omp_taskwait_deps_51 : Function for OpenMP 5.1 nowait clause.
4279  *                               Placeholder for taskwait with nowait clause.*/
4280 KMP_EXPORT void __kmpc_omp_taskwait_deps_51(ident_t *loc_ref, kmp_int32 gtid,
4281                                             kmp_int32 ndeps,
4282                                             kmp_depend_info_t *dep_list,
4283                                             kmp_int32 ndeps_noalias,
4284                                             kmp_depend_info_t *noalias_dep_list,
4285                                             kmp_int32 has_no_wait);
4286 
4287 extern kmp_int32 __kmp_omp_task(kmp_int32 gtid, kmp_task_t *new_task,
4288                                 bool serialize_immediate);
4289 
4290 KMP_EXPORT kmp_int32 __kmpc_cancel(ident_t *loc_ref, kmp_int32 gtid,
4291                                    kmp_int32 cncl_kind);
4292 KMP_EXPORT kmp_int32 __kmpc_cancellationpoint(ident_t *loc_ref, kmp_int32 gtid,
4293                                               kmp_int32 cncl_kind);
4294 KMP_EXPORT kmp_int32 __kmpc_cancel_barrier(ident_t *loc_ref, kmp_int32 gtid);
4295 KMP_EXPORT int __kmp_get_cancellation_status(int cancel_kind);
4296 
4297 KMP_EXPORT void __kmpc_proxy_task_completed(kmp_int32 gtid, kmp_task_t *ptask);
4298 KMP_EXPORT void __kmpc_proxy_task_completed_ooo(kmp_task_t *ptask);
4299 KMP_EXPORT void __kmpc_taskloop(ident_t *loc, kmp_int32 gtid, kmp_task_t *task,
4300                                 kmp_int32 if_val, kmp_uint64 *lb,
4301                                 kmp_uint64 *ub, kmp_int64 st, kmp_int32 nogroup,
4302                                 kmp_int32 sched, kmp_uint64 grainsize,
4303                                 void *task_dup);
4304 KMP_EXPORT void __kmpc_taskloop_5(ident_t *loc, kmp_int32 gtid,
4305                                   kmp_task_t *task, kmp_int32 if_val,
4306                                   kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st,
4307                                   kmp_int32 nogroup, kmp_int32 sched,
4308                                   kmp_uint64 grainsize, kmp_int32 modifier,
4309                                   void *task_dup);
4310 KMP_EXPORT void *__kmpc_task_reduction_init(int gtid, int num_data, void *data);
4311 KMP_EXPORT void *__kmpc_taskred_init(int gtid, int num_data, void *data);
4312 KMP_EXPORT void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void *d);
4313 KMP_EXPORT void *__kmpc_task_reduction_modifier_init(ident_t *loc, int gtid,
4314                                                      int is_ws, int num,
4315                                                      void *data);
4316 KMP_EXPORT void *__kmpc_taskred_modifier_init(ident_t *loc, int gtid, int is_ws,
4317                                               int num, void *data);
4318 KMP_EXPORT void __kmpc_task_reduction_modifier_fini(ident_t *loc, int gtid,
4319                                                     int is_ws);
4320 KMP_EXPORT kmp_int32 __kmpc_omp_reg_task_with_affinity(
4321     ident_t *loc_ref, kmp_int32 gtid, kmp_task_t *new_task, kmp_int32 naffins,
4322     kmp_task_affinity_info_t *affin_list);
4323 KMP_EXPORT void __kmp_set_num_teams(int num_teams);
4324 KMP_EXPORT int __kmp_get_max_teams(void);
4325 KMP_EXPORT void __kmp_set_teams_thread_limit(int limit);
4326 KMP_EXPORT int __kmp_get_teams_thread_limit(void);
4327 
4328 /* Interface target task integration */
4329 KMP_EXPORT void **__kmpc_omp_get_target_async_handle_ptr(kmp_int32 gtid);
4330 KMP_EXPORT bool __kmpc_omp_has_task_team(kmp_int32 gtid);
4331 
4332 /* Lock interface routines (fast versions with gtid passed in) */
4333 KMP_EXPORT void __kmpc_init_lock(ident_t *loc, kmp_int32 gtid,
4334                                  void **user_lock);
4335 KMP_EXPORT void __kmpc_init_nest_lock(ident_t *loc, kmp_int32 gtid,
4336                                       void **user_lock);
4337 KMP_EXPORT void __kmpc_destroy_lock(ident_t *loc, kmp_int32 gtid,
4338                                     void **user_lock);
4339 KMP_EXPORT void __kmpc_destroy_nest_lock(ident_t *loc, kmp_int32 gtid,
4340                                          void **user_lock);
4341 KMP_EXPORT void __kmpc_set_lock(ident_t *loc, kmp_int32 gtid, void **user_lock);
4342 KMP_EXPORT void __kmpc_set_nest_lock(ident_t *loc, kmp_int32 gtid,
4343                                      void **user_lock);
4344 KMP_EXPORT void __kmpc_unset_lock(ident_t *loc, kmp_int32 gtid,
4345                                   void **user_lock);
4346 KMP_EXPORT void __kmpc_unset_nest_lock(ident_t *loc, kmp_int32 gtid,
4347                                        void **user_lock);
4348 KMP_EXPORT int __kmpc_test_lock(ident_t *loc, kmp_int32 gtid, void **user_lock);
4349 KMP_EXPORT int __kmpc_test_nest_lock(ident_t *loc, kmp_int32 gtid,
4350                                      void **user_lock);
4351 
4352 KMP_EXPORT void __kmpc_init_lock_with_hint(ident_t *loc, kmp_int32 gtid,
4353                                            void **user_lock, uintptr_t hint);
4354 KMP_EXPORT void __kmpc_init_nest_lock_with_hint(ident_t *loc, kmp_int32 gtid,
4355                                                 void **user_lock,
4356                                                 uintptr_t hint);
4357 
4358 #if OMPX_TASKGRAPH
4359 // Taskgraph's Record & Replay mechanism
4360 // __kmp_tdg_is_recording: check whether a given TDG is recording
4361 // status: the tdg's current status
__kmp_tdg_is_recording(kmp_tdg_status_t status)4362 static inline bool __kmp_tdg_is_recording(kmp_tdg_status_t status) {
4363   return status == KMP_TDG_RECORDING;
4364 }
4365 
4366 KMP_EXPORT kmp_int32 __kmpc_start_record_task(ident_t *loc, kmp_int32 gtid,
4367                                               kmp_int32 input_flags,
4368                                               kmp_int32 tdg_id);
4369 KMP_EXPORT void __kmpc_end_record_task(ident_t *loc, kmp_int32 gtid,
4370                                        kmp_int32 input_flags, kmp_int32 tdg_id);
4371 #endif
4372 /* Interface to fast scalable reduce methods routines */
4373 
4374 KMP_EXPORT kmp_int32 __kmpc_reduce_nowait(
4375     ident_t *loc, kmp_int32 global_tid, kmp_int32 num_vars, size_t reduce_size,
4376     void *reduce_data, void (*reduce_func)(void *lhs_data, void *rhs_data),
4377     kmp_critical_name *lck);
4378 KMP_EXPORT void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
4379                                          kmp_critical_name *lck);
4380 KMP_EXPORT kmp_int32 __kmpc_reduce(
4381     ident_t *loc, kmp_int32 global_tid, kmp_int32 num_vars, size_t reduce_size,
4382     void *reduce_data, void (*reduce_func)(void *lhs_data, void *rhs_data),
4383     kmp_critical_name *lck);
4384 KMP_EXPORT void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
4385                                   kmp_critical_name *lck);
4386 
4387 /* Internal fast reduction routines */
4388 
4389 extern PACKED_REDUCTION_METHOD_T __kmp_determine_reduction_method(
4390     ident_t *loc, kmp_int32 global_tid, kmp_int32 num_vars, size_t reduce_size,
4391     void *reduce_data, void (*reduce_func)(void *lhs_data, void *rhs_data),
4392     kmp_critical_name *lck);
4393 
4394 // this function is for testing set/get/determine reduce method
4395 KMP_EXPORT kmp_int32 __kmp_get_reduce_method(void);
4396 
4397 KMP_EXPORT kmp_uint64 __kmpc_get_taskid();
4398 KMP_EXPORT kmp_uint64 __kmpc_get_parent_taskid();
4399 
4400 // C++ port
4401 // missing 'extern "C"' declarations
4402 
4403 KMP_EXPORT kmp_int32 __kmpc_in_parallel(ident_t *loc);
4404 KMP_EXPORT void __kmpc_pop_num_threads(ident_t *loc, kmp_int32 global_tid);
4405 KMP_EXPORT void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
4406                                         kmp_int32 num_threads);
4407 
4408 KMP_EXPORT void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
4409                                       int proc_bind);
4410 KMP_EXPORT void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid,
4411                                       kmp_int32 num_teams,
4412                                       kmp_int32 num_threads);
4413 KMP_EXPORT void __kmpc_set_thread_limit(ident_t *loc, kmp_int32 global_tid,
4414                                         kmp_int32 thread_limit);
4415 /* Function for OpenMP 5.1 num_teams clause */
4416 KMP_EXPORT void __kmpc_push_num_teams_51(ident_t *loc, kmp_int32 global_tid,
4417                                          kmp_int32 num_teams_lb,
4418                                          kmp_int32 num_teams_ub,
4419                                          kmp_int32 num_threads);
4420 KMP_EXPORT void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc,
4421                                   kmpc_micro microtask, ...);
4422 struct kmp_dim { // loop bounds info casted to kmp_int64
4423   kmp_int64 lo; // lower
4424   kmp_int64 up; // upper
4425   kmp_int64 st; // stride
4426 };
4427 KMP_EXPORT void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
4428                                      kmp_int32 num_dims,
4429                                      const struct kmp_dim *dims);
4430 KMP_EXPORT void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid,
4431                                      const kmp_int64 *vec);
4432 KMP_EXPORT void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid,
4433                                      const kmp_int64 *vec);
4434 KMP_EXPORT void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
4435 
4436 KMP_EXPORT void *__kmpc_threadprivate_cached(ident_t *loc, kmp_int32 global_tid,
4437                                              void *data, size_t size,
4438                                              void ***cache);
4439 
4440 // The routines below are not exported.
4441 // Consider making them 'static' in corresponding source files.
4442 void kmp_threadprivate_insert_private_data(int gtid, void *pc_addr,
4443                                            void *data_addr, size_t pc_size);
4444 struct private_common *kmp_threadprivate_insert(int gtid, void *pc_addr,
4445                                                 void *data_addr,
4446                                                 size_t pc_size);
4447 void __kmp_threadprivate_resize_cache(int newCapacity);
4448 void __kmp_cleanup_threadprivate_caches();
4449 
4450 // ompc_, kmpc_ entries moved from omp.h.
4451 #if KMP_OS_WINDOWS
4452 #define KMPC_CONVENTION __cdecl
4453 #else
4454 #define KMPC_CONVENTION
4455 #endif
4456 
4457 #ifndef __OMP_H
4458 typedef enum omp_sched_t {
4459   omp_sched_static = 1,
4460   omp_sched_dynamic = 2,
4461   omp_sched_guided = 3,
4462   omp_sched_auto = 4
4463 } omp_sched_t;
4464 typedef void *kmp_affinity_mask_t;
4465 #endif
4466 
4467 KMP_EXPORT void KMPC_CONVENTION ompc_set_max_active_levels(int);
4468 KMP_EXPORT void KMPC_CONVENTION ompc_set_schedule(omp_sched_t, int);
4469 KMP_EXPORT int KMPC_CONVENTION ompc_get_ancestor_thread_num(int);
4470 KMP_EXPORT int KMPC_CONVENTION ompc_get_team_size(int);
4471 KMP_EXPORT int KMPC_CONVENTION
4472 kmpc_set_affinity_mask_proc(int, kmp_affinity_mask_t *);
4473 KMP_EXPORT int KMPC_CONVENTION
4474 kmpc_unset_affinity_mask_proc(int, kmp_affinity_mask_t *);
4475 KMP_EXPORT int KMPC_CONVENTION
4476 kmpc_get_affinity_mask_proc(int, kmp_affinity_mask_t *);
4477 
4478 KMP_EXPORT void KMPC_CONVENTION kmpc_set_stacksize(int);
4479 KMP_EXPORT void KMPC_CONVENTION kmpc_set_stacksize_s(size_t);
4480 KMP_EXPORT void KMPC_CONVENTION kmpc_set_library(int);
4481 KMP_EXPORT void KMPC_CONVENTION kmpc_set_defaults(char const *);
4482 KMP_EXPORT void KMPC_CONVENTION kmpc_set_disp_num_buffers(int);
4483 void KMP_EXPAND_NAME(ompc_set_affinity_format)(char const *format);
4484 size_t KMP_EXPAND_NAME(ompc_get_affinity_format)(char *buffer, size_t size);
4485 void KMP_EXPAND_NAME(ompc_display_affinity)(char const *format);
4486 size_t KMP_EXPAND_NAME(ompc_capture_affinity)(char *buffer, size_t buf_size,
4487                                               char const *format);
4488 
4489 enum kmp_target_offload_kind {
4490   tgt_disabled = 0,
4491   tgt_default = 1,
4492   tgt_mandatory = 2
4493 };
4494 typedef enum kmp_target_offload_kind kmp_target_offload_kind_t;
4495 // Set via OMP_TARGET_OFFLOAD if specified, defaults to tgt_default otherwise
4496 extern kmp_target_offload_kind_t __kmp_target_offload;
4497 extern int __kmpc_get_target_offload();
4498 
4499 // Constants used in libomptarget
4500 #define KMP_DEVICE_DEFAULT -1 // This is libomptarget's default device.
4501 #define KMP_DEVICE_ALL -11 // This is libomptarget's "all devices".
4502 
4503 // OMP Pause Resource
4504 
4505 // The following enum is used both to set the status in __kmp_pause_status, and
4506 // as the internal equivalent of the externally-visible omp_pause_resource_t.
4507 typedef enum kmp_pause_status_t {
4508   kmp_not_paused = 0, // status is not paused, or, requesting resume
4509   kmp_soft_paused = 1, // status is soft-paused, or, requesting soft pause
4510   kmp_hard_paused = 2 // status is hard-paused, or, requesting hard pause
4511 } kmp_pause_status_t;
4512 
4513 // This stores the pause state of the runtime
4514 extern kmp_pause_status_t __kmp_pause_status;
4515 extern int __kmpc_pause_resource(kmp_pause_status_t level);
4516 extern int __kmp_pause_resource(kmp_pause_status_t level);
4517 // Soft resume sets __kmp_pause_status, and wakes up all threads.
4518 extern void __kmp_resume_if_soft_paused();
4519 // Hard resume simply resets the status to not paused. Library will appear to
4520 // be uninitialized after hard pause. Let OMP constructs trigger required
4521 // initializations.
__kmp_resume_if_hard_paused()4522 static inline void __kmp_resume_if_hard_paused() {
4523   if (__kmp_pause_status == kmp_hard_paused) {
4524     __kmp_pause_status = kmp_not_paused;
4525   }
4526 }
4527 
4528 extern void __kmp_omp_display_env(int verbose);
4529 
4530 // 1: it is initializing hidden helper team
4531 extern volatile int __kmp_init_hidden_helper;
4532 // 1: the hidden helper team is done
4533 extern volatile int __kmp_hidden_helper_team_done;
4534 // 1: enable hidden helper task
4535 extern kmp_int32 __kmp_enable_hidden_helper;
4536 // Main thread of hidden helper team
4537 extern kmp_info_t *__kmp_hidden_helper_main_thread;
4538 // Descriptors for the hidden helper threads
4539 extern kmp_info_t **__kmp_hidden_helper_threads;
4540 // Number of hidden helper threads
4541 extern kmp_int32 __kmp_hidden_helper_threads_num;
4542 // Number of hidden helper tasks that have not been executed yet
4543 extern std::atomic<kmp_int32> __kmp_unexecuted_hidden_helper_tasks;
4544 
4545 extern void __kmp_hidden_helper_initialize();
4546 extern void __kmp_hidden_helper_threads_initz_routine();
4547 extern void __kmp_do_initialize_hidden_helper_threads();
4548 extern void __kmp_hidden_helper_threads_initz_wait();
4549 extern void __kmp_hidden_helper_initz_release();
4550 extern void __kmp_hidden_helper_threads_deinitz_wait();
4551 extern void __kmp_hidden_helper_threads_deinitz_release();
4552 extern void __kmp_hidden_helper_main_thread_wait();
4553 extern void __kmp_hidden_helper_worker_thread_wait();
4554 extern void __kmp_hidden_helper_worker_thread_signal();
4555 extern void __kmp_hidden_helper_main_thread_release();
4556 
4557 // Check whether a given thread is a hidden helper thread
4558 #define KMP_HIDDEN_HELPER_THREAD(gtid)                                         \
4559   ((gtid) >= 1 && (gtid) <= __kmp_hidden_helper_threads_num)
4560 
4561 #define KMP_HIDDEN_HELPER_WORKER_THREAD(gtid)                                  \
4562   ((gtid) > 1 && (gtid) <= __kmp_hidden_helper_threads_num)
4563 
4564 #define KMP_HIDDEN_HELPER_MAIN_THREAD(gtid)                                    \
4565   ((gtid) == 1 && (gtid) <= __kmp_hidden_helper_threads_num)
4566 
4567 #define KMP_HIDDEN_HELPER_TEAM(team)                                           \
4568   (team->t.t_threads[0] == __kmp_hidden_helper_main_thread)
4569 
4570 // Map a gtid to a hidden helper thread. The first hidden helper thread, a.k.a
4571 // main thread, is skipped.
4572 #define KMP_GTID_TO_SHADOW_GTID(gtid)                                          \
4573   ((gtid) % (__kmp_hidden_helper_threads_num - 1) + 2)
4574 
4575 // Return the adjusted gtid value by subtracting from gtid the number
4576 // of hidden helper threads. This adjusted value is the gtid the thread would
4577 // have received if there were no hidden helper threads.
__kmp_adjust_gtid_for_hidden_helpers(int gtid)4578 static inline int __kmp_adjust_gtid_for_hidden_helpers(int gtid) {
4579   int adjusted_gtid = gtid;
4580   if (__kmp_hidden_helper_threads_num > 0 && gtid > 0 &&
4581       gtid - __kmp_hidden_helper_threads_num >= 0) {
4582     adjusted_gtid -= __kmp_hidden_helper_threads_num;
4583   }
4584   return adjusted_gtid;
4585 }
4586 
4587 // Support for error directive
4588 typedef enum kmp_severity_t {
4589   severity_warning = 1,
4590   severity_fatal = 2
4591 } kmp_severity_t;
4592 extern void __kmpc_error(ident_t *loc, int severity, const char *message);
4593 
4594 // Support for scope directive
4595 KMP_EXPORT void __kmpc_scope(ident_t *loc, kmp_int32 gtid, void *reserved);
4596 KMP_EXPORT void __kmpc_end_scope(ident_t *loc, kmp_int32 gtid, void *reserved);
4597 
4598 #ifdef __cplusplus
4599 }
4600 #endif
4601 
4602 template <bool C, bool S>
4603 extern void __kmp_suspend_32(int th_gtid, kmp_flag_32<C, S> *flag);
4604 template <bool C, bool S>
4605 extern void __kmp_suspend_64(int th_gtid, kmp_flag_64<C, S> *flag);
4606 template <bool C, bool S>
4607 extern void __kmp_atomic_suspend_64(int th_gtid,
4608                                     kmp_atomic_flag_64<C, S> *flag);
4609 extern void __kmp_suspend_oncore(int th_gtid, kmp_flag_oncore *flag);
4610 #if KMP_HAVE_MWAIT || KMP_HAVE_UMWAIT
4611 template <bool C, bool S>
4612 extern void __kmp_mwait_32(int th_gtid, kmp_flag_32<C, S> *flag);
4613 template <bool C, bool S>
4614 extern void __kmp_mwait_64(int th_gtid, kmp_flag_64<C, S> *flag);
4615 template <bool C, bool S>
4616 extern void __kmp_atomic_mwait_64(int th_gtid, kmp_atomic_flag_64<C, S> *flag);
4617 extern void __kmp_mwait_oncore(int th_gtid, kmp_flag_oncore *flag);
4618 #endif
4619 template <bool C, bool S>
4620 extern void __kmp_resume_32(int target_gtid, kmp_flag_32<C, S> *flag);
4621 template <bool C, bool S>
4622 extern void __kmp_resume_64(int target_gtid, kmp_flag_64<C, S> *flag);
4623 template <bool C, bool S>
4624 extern void __kmp_atomic_resume_64(int target_gtid,
4625                                    kmp_atomic_flag_64<C, S> *flag);
4626 extern void __kmp_resume_oncore(int target_gtid, kmp_flag_oncore *flag);
4627 
4628 template <bool C, bool S>
4629 int __kmp_execute_tasks_32(kmp_info_t *thread, kmp_int32 gtid,
4630                            kmp_flag_32<C, S> *flag, int final_spin,
4631                            int *thread_finished,
4632 #if USE_ITT_BUILD
4633                            void *itt_sync_obj,
4634 #endif /* USE_ITT_BUILD */
4635                            kmp_int32 is_constrained);
4636 template <bool C, bool S>
4637 int __kmp_execute_tasks_64(kmp_info_t *thread, kmp_int32 gtid,
4638                            kmp_flag_64<C, S> *flag, int final_spin,
4639                            int *thread_finished,
4640 #if USE_ITT_BUILD
4641                            void *itt_sync_obj,
4642 #endif /* USE_ITT_BUILD */
4643                            kmp_int32 is_constrained);
4644 template <bool C, bool S>
4645 int __kmp_atomic_execute_tasks_64(kmp_info_t *thread, kmp_int32 gtid,
4646                                   kmp_atomic_flag_64<C, S> *flag,
4647                                   int final_spin, int *thread_finished,
4648 #if USE_ITT_BUILD
4649                                   void *itt_sync_obj,
4650 #endif /* USE_ITT_BUILD */
4651                                   kmp_int32 is_constrained);
4652 int __kmp_execute_tasks_oncore(kmp_info_t *thread, kmp_int32 gtid,
4653                                kmp_flag_oncore *flag, int final_spin,
4654                                int *thread_finished,
4655 #if USE_ITT_BUILD
4656                                void *itt_sync_obj,
4657 #endif /* USE_ITT_BUILD */
4658                                kmp_int32 is_constrained);
4659 
4660 extern int __kmp_nesting_mode;
4661 extern int __kmp_nesting_mode_nlevels;
4662 extern int *__kmp_nesting_nth_level;
4663 extern void __kmp_init_nesting_mode();
4664 extern void __kmp_set_nesting_mode_threads();
4665 
4666 /// This class safely opens and closes a C-style FILE* object using RAII
4667 /// semantics. There are also methods which allow using stdout or stderr as
4668 /// the underlying FILE* object. With the implicit conversion operator to
4669 /// FILE*, an object with this type can be used in any function which takes
4670 /// a FILE* object e.g., fprintf().
4671 /// No close method is needed at use sites.
4672 class kmp_safe_raii_file_t {
4673   FILE *f;
4674 
close()4675   void close() {
4676     if (f && f != stdout && f != stderr) {
4677       fclose(f);
4678       f = nullptr;
4679     }
4680   }
4681 
4682 public:
kmp_safe_raii_file_t()4683   kmp_safe_raii_file_t() : f(nullptr) {}
4684   kmp_safe_raii_file_t(const char *filename, const char *mode,
4685                        const char *env_var = nullptr)
f(nullptr)4686       : f(nullptr) {
4687     open(filename, mode, env_var);
4688   }
~kmp_safe_raii_file_t()4689   ~kmp_safe_raii_file_t() { close(); }
4690 
4691   /// Open filename using mode. This is automatically closed in the destructor.
4692   /// The env_var parameter indicates the environment variable the filename
4693   /// came from if != nullptr.
4694   void open(const char *filename, const char *mode,
4695             const char *env_var = nullptr) {
4696     KMP_ASSERT(!f);
4697     f = fopen(filename, mode);
4698     if (!f) {
4699       int code = errno;
4700       if (env_var) {
4701         __kmp_fatal(KMP_MSG(CantOpenFileForReading, filename), KMP_ERR(code),
4702                     KMP_HNT(CheckEnvVar, env_var, filename), __kmp_msg_null);
4703       } else {
4704         __kmp_fatal(KMP_MSG(CantOpenFileForReading, filename), KMP_ERR(code),
4705                     __kmp_msg_null);
4706       }
4707     }
4708   }
4709   /// Instead of erroring out, return non-zero when
4710   /// unsuccessful fopen() for any reason
try_open(const char * filename,const char * mode)4711   int try_open(const char *filename, const char *mode) {
4712     KMP_ASSERT(!f);
4713     f = fopen(filename, mode);
4714     if (!f)
4715       return errno;
4716     return 0;
4717   }
4718   /// Set the FILE* object to stdout and output there
4719   /// No open call should happen before this call.
set_stdout()4720   void set_stdout() {
4721     KMP_ASSERT(!f);
4722     f = stdout;
4723   }
4724   /// Set the FILE* object to stderr and output there
4725   /// No open call should happen before this call.
set_stderr()4726   void set_stderr() {
4727     KMP_ASSERT(!f);
4728     f = stderr;
4729   }
4730   operator bool() { return bool(f); }
4731   operator FILE *() { return f; }
4732 };
4733 
4734 template <typename SourceType, typename TargetType,
4735           bool isSourceSmaller = (sizeof(SourceType) < sizeof(TargetType)),
4736           bool isSourceEqual = (sizeof(SourceType) == sizeof(TargetType)),
4737           bool isSourceSigned = std::is_signed<SourceType>::value,
4738           bool isTargetSigned = std::is_signed<TargetType>::value>
4739 struct kmp_convert {};
4740 
4741 // Both types are signed; Source smaller
4742 template <typename SourceType, typename TargetType>
4743 struct kmp_convert<SourceType, TargetType, true, false, true, true> {
4744   static TargetType to(SourceType src) { return (TargetType)src; }
4745 };
4746 // Source equal
4747 template <typename SourceType, typename TargetType>
4748 struct kmp_convert<SourceType, TargetType, false, true, true, true> {
4749   static TargetType to(SourceType src) { return src; }
4750 };
4751 // Source bigger
4752 template <typename SourceType, typename TargetType>
4753 struct kmp_convert<SourceType, TargetType, false, false, true, true> {
4754   static TargetType to(SourceType src) {
4755     KMP_ASSERT(src <= static_cast<SourceType>(
4756                           (std::numeric_limits<TargetType>::max)()));
4757     KMP_ASSERT(src >= static_cast<SourceType>(
4758                           (std::numeric_limits<TargetType>::min)()));
4759     return (TargetType)src;
4760   }
4761 };
4762 
4763 // Source signed, Target unsigned
4764 // Source smaller
4765 template <typename SourceType, typename TargetType>
4766 struct kmp_convert<SourceType, TargetType, true, false, true, false> {
4767   static TargetType to(SourceType src) {
4768     KMP_ASSERT(src >= 0);
4769     return (TargetType)src;
4770   }
4771 };
4772 // Source equal
4773 template <typename SourceType, typename TargetType>
4774 struct kmp_convert<SourceType, TargetType, false, true, true, false> {
4775   static TargetType to(SourceType src) {
4776     KMP_ASSERT(src >= 0);
4777     return (TargetType)src;
4778   }
4779 };
4780 // Source bigger
4781 template <typename SourceType, typename TargetType>
4782 struct kmp_convert<SourceType, TargetType, false, false, true, false> {
4783   static TargetType to(SourceType src) {
4784     KMP_ASSERT(src >= 0);
4785     KMP_ASSERT(src <= static_cast<SourceType>(
4786                           (std::numeric_limits<TargetType>::max)()));
4787     return (TargetType)src;
4788   }
4789 };
4790 
4791 // Source unsigned, Target signed
4792 // Source smaller
4793 template <typename SourceType, typename TargetType>
4794 struct kmp_convert<SourceType, TargetType, true, false, false, true> {
4795   static TargetType to(SourceType src) { return (TargetType)src; }
4796 };
4797 // Source equal
4798 template <typename SourceType, typename TargetType>
4799 struct kmp_convert<SourceType, TargetType, false, true, false, true> {
4800   static TargetType to(SourceType src) {
4801     KMP_ASSERT(src <= static_cast<SourceType>(
4802                           (std::numeric_limits<TargetType>::max)()));
4803     return (TargetType)src;
4804   }
4805 };
4806 // Source bigger
4807 template <typename SourceType, typename TargetType>
4808 struct kmp_convert<SourceType, TargetType, false, false, false, true> {
4809   static TargetType to(SourceType src) {
4810     KMP_ASSERT(src <= static_cast<SourceType>(
4811                           (std::numeric_limits<TargetType>::max)()));
4812     return (TargetType)src;
4813   }
4814 };
4815 
4816 // Source unsigned, Target unsigned
4817 // Source smaller
4818 template <typename SourceType, typename TargetType>
4819 struct kmp_convert<SourceType, TargetType, true, false, false, false> {
4820   static TargetType to(SourceType src) { return (TargetType)src; }
4821 };
4822 // Source equal
4823 template <typename SourceType, typename TargetType>
4824 struct kmp_convert<SourceType, TargetType, false, true, false, false> {
4825   static TargetType to(SourceType src) { return src; }
4826 };
4827 // Source bigger
4828 template <typename SourceType, typename TargetType>
4829 struct kmp_convert<SourceType, TargetType, false, false, false, false> {
4830   static TargetType to(SourceType src) {
4831     KMP_ASSERT(src <= static_cast<SourceType>(
4832                           (std::numeric_limits<TargetType>::max)()));
4833     return (TargetType)src;
4834   }
4835 };
4836 
4837 template <typename T1, typename T2>
4838 static inline void __kmp_type_convert(T1 src, T2 *dest) {
4839   *dest = kmp_convert<T1, T2>::to(src);
4840 }
4841 
4842 #endif /* KMP_H */
4843