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