• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright © 2014 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  */
23 
24 #ifndef UTIL_MACROS_H
25 #define UTIL_MACROS_H
26 
27 #include <assert.h>
28 #if defined(__HAIKU__)  && !defined(__cplusplus)
29 #define static_assert _Static_assert
30 #endif
31 #include <stddef.h>
32 #include <stdint.h>
33 #include <stdio.h>
34 
35 #ifdef _GAMING_XBOX
36 #define strdup _strdup
37 #define stricmp _stricmp
38 #define unlink _unlink
39 #define access(a, b) _access(a, b)
40 #endif
41 
42 /* Compute the size of an array */
43 #ifndef ARRAY_SIZE
44 #  define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
45 #endif
46 
47 /* For compatibility with Clang's __has_builtin() */
48 #ifndef __has_builtin
49 #  define __has_builtin(x) 0
50 #endif
51 
52 #ifndef __has_attribute
53 #  define __has_attribute(x) 0
54 #endif
55 
56 /**
57  * __builtin_expect macros
58  */
59 #if !defined(HAVE___BUILTIN_EXPECT)
60 #  define __builtin_expect(x, y) (x)
61 #endif
62 
63 #ifndef likely
64 #  ifdef HAVE___BUILTIN_EXPECT
65 #    define likely(x)   __builtin_expect(!!(x), 1)
66 #    define unlikely(x) __builtin_expect(!!(x), 0)
67 #  else
68 #    define likely(x)   (x)
69 #    define unlikely(x) (x)
70 #  endif
71 #endif
72 
73 /**
74  * __builtin_types_compatible_p compat
75  */
76 #if defined(__cplusplus) || !defined(HAVE___BUILTIN_TYPES_COMPATIBLE_P)
77 #  define __builtin_types_compatible_p(type1, type2) (1)
78 #endif
79 
80 /* This should match linux gcc cdecl semantics everywhere, so that we
81  * just codegen one calling convention on all platforms.
82  */
83 #ifdef _MSC_VER
84 #define UTIL_CDECL __cdecl
85 #else
86 #define UTIL_CDECL
87 #endif
88 
89 /**
90  * Static (compile-time) assertion.
91  */
92 #define STATIC_ASSERT(cond) do { \
93    static_assert(cond, #cond); \
94 } while (0)
95 
96 /**
97  * container_of - cast a member of a structure out to the containing structure
98  * @ptr:        the pointer to the member.
99  * @type:       the type of the container struct this is embedded in.
100  * @member:     the name of the member within the struct.
101  */
102 #ifndef __GNUC__
103    /* a grown-up compiler is required for the extra type checking: */
104 #  define container_of(ptr, type, member)                               \
105       (type*)((uint8_t *)ptr - offsetof(type, member))
106 #else
107 #  define __same_type(a, b) \
108       __builtin_types_compatible_p(__typeof__(a), __typeof__(b))
109 #  define container_of(ptr, type, member) ({                            \
110          uint8_t *__mptr = (uint8_t *)(ptr);                            \
111          static_assert(__same_type(*(ptr), ((type *)0)->member) ||      \
112                        __same_type(*(ptr), void),                       \
113                        "pointer type mismatch in container_of()");      \
114          ((type *)(__mptr - offsetof(type, member)));                   \
115       })
116 #endif
117 
118 /**
119  * Unreachable macro. Useful for suppressing "control reaches end of non-void
120  * function" warnings.
121  */
122 #if defined(HAVE___BUILTIN_UNREACHABLE) || __has_builtin(__builtin_unreachable)
123 #define unreachable(str)    \
124 do {                        \
125    assert(!"" str);         \
126    __builtin_unreachable(); \
127 } while (0)
128 #elif defined (_MSC_VER)
129 #define unreachable(str)    \
130 do {                        \
131    assert(!"" str);         \
132    __assume(0);             \
133 } while (0)
134 #else
135 #define unreachable(str) assert(!"" str)
136 #endif
137 
138 /**
139  * Assume macro. Useful for expressing our assumptions to the compiler,
140  * typically for purposes of silencing warnings.
141  */
142 #if __has_builtin(__builtin_assume)
143 #define assume(expr)       \
144 do {                       \
145    assert(expr);           \
146    __builtin_assume(expr); \
147 } while (0)
148 #elif defined HAVE___BUILTIN_UNREACHABLE
149 #define assume(expr) ((expr) ? ((void) 0) \
150                              : (assert(!"assumption failed"), \
151                                 __builtin_unreachable()))
152 #elif defined (_MSC_VER)
153 #define assume(expr) __assume(expr)
154 #else
155 #define assume(expr) assert(expr)
156 #endif
157 
158 /* Attribute const is used for functions that have no effects other than their
159  * return value, and only rely on the argument values to compute the return
160  * value.  As a result, calls to it can be CSEed.  Note that using memory
161  * pointed to by the arguments is not allowed for const functions.
162  */
163 #if !defined(__clang__) && defined(HAVE_FUNC_ATTRIBUTE_CONST)
164 #define ATTRIBUTE_CONST __attribute__((__const__))
165 #else
166 #define ATTRIBUTE_CONST
167 #endif
168 
169 #ifdef HAVE_FUNC_ATTRIBUTE_FLATTEN
170 #define FLATTEN __attribute__((__flatten__))
171 #else
172 #define FLATTEN
173 #endif
174 
175 #ifdef HAVE_FUNC_ATTRIBUTE_FORMAT
176 #if defined (__MINGW_PRINTF_FORMAT)
177 # define PRINTFLIKE(f, a) __attribute__ ((format(__MINGW_PRINTF_FORMAT, f, a)))
178 #else
179 # define PRINTFLIKE(f, a) __attribute__ ((format(__printf__, f, a)))
180 #endif
181 #else
182 #define PRINTFLIKE(f, a)
183 #endif
184 
185 #ifdef HAVE_FUNC_ATTRIBUTE_MALLOC
186 #define MALLOCLIKE __attribute__((__malloc__))
187 #else
188 #define MALLOCLIKE
189 #endif
190 
191 /* Forced function inlining */
192 /* Note: Clang also sets __GNUC__ (see other cases below) */
193 #ifndef ALWAYS_INLINE
194 #  if defined(__GNUC__)
195 #    define ALWAYS_INLINE inline __attribute__((always_inline))
196 #  elif defined(_MSC_VER)
197 #    define ALWAYS_INLINE __forceinline
198 #  else
199 #    define ALWAYS_INLINE inline
200 #  endif
201 #endif
202 
203 /* Used to optionally mark structures with misaligned elements or size as
204  * packed, to trade off performance for space.
205  */
206 #ifdef HAVE_FUNC_ATTRIBUTE_PACKED
207 #  if defined(__MINGW32__) || defined(__MINGW64__)
208 #    define PACKED __attribute__((gcc_struct,__packed__))
209 #  else
210 #    define PACKED __attribute__((__packed__))
211 #  endif
212 #  define ENUM_PACKED __attribute__((packed))
213 #else
214 #define PACKED
215 #define ENUM_PACKED
216 #endif
217 
218 /* Attribute pure is used for functions that have no effects other than their
219  * return value.  As a result, calls to it can be dead code eliminated.
220  */
221 #ifdef HAVE_FUNC_ATTRIBUTE_PURE
222 #define ATTRIBUTE_PURE __attribute__((__pure__))
223 #else
224 #define ATTRIBUTE_PURE
225 #endif
226 
227 #ifdef HAVE_FUNC_ATTRIBUTE_RETURNS_NONNULL
228 #define ATTRIBUTE_RETURNS_NONNULL __attribute__((__returns_nonnull__))
229 #else
230 #define ATTRIBUTE_RETURNS_NONNULL
231 #endif
232 
233 #ifndef NORETURN
234 #  ifdef _MSC_VER
235 #    define NORETURN __declspec(noreturn)
236 #  elif defined HAVE_FUNC_ATTRIBUTE_NORETURN
237 #    define NORETURN __attribute__((__noreturn__))
238 #  else
239 #    define NORETURN
240 #  endif
241 #endif
242 
243 #ifdef __cplusplus
244 /**
245  * Macro function that evaluates to true if T is a trivially
246  * destructible type -- that is, if its (non-virtual) destructor
247  * performs no action and all member variables and base classes are
248  * trivially destructible themselves.
249  */
250 #   if defined(__clang__)
251 #      if __has_builtin(__is_trivially_destructible)
252 #         define HAS_TRIVIAL_DESTRUCTOR(T) __is_trivially_destructible(T)
253 #      elif (defined(__has_feature) && __has_feature(has_trivial_destructor))
254 #         define HAS_TRIVIAL_DESTRUCTOR(T) __has_trivial_destructor(T)
255 #      endif
256 #   elif defined(__GNUC__)
257 #      if ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 3)))
258 #         define HAS_TRIVIAL_DESTRUCTOR(T) __has_trivial_destructor(T)
259 #      endif
260 #   elif defined(_MSC_VER) && !defined(__INTEL_COMPILER)
261 #      define HAS_TRIVIAL_DESTRUCTOR(T) __has_trivial_destructor(T)
262 #   endif
263 #   ifndef HAS_TRIVIAL_DESTRUCTOR
264        /* It's always safe (if inefficient) to assume that a
265         * destructor is non-trivial.
266         */
267 #      define HAS_TRIVIAL_DESTRUCTOR(T) (false)
268 #   endif
269 #endif
270 
271 /**
272  * PUBLIC/USED macros
273  *
274  * If we build the library with gcc's -fvisibility=hidden flag, we'll
275  * use the PUBLIC macro to mark functions that are to be exported.
276  *
277  * We also need to define a USED attribute, so the optimizer doesn't
278  * inline a static function that we later use in an alias. - ajax
279  */
280 #ifndef PUBLIC
281 #  if defined(_WIN32)
282 #    define PUBLIC __declspec(dllexport)
283 #    define USED
284 #  elif defined(__GNUC__)
285 #    define PUBLIC __attribute__((visibility("default")))
286 #    define USED __attribute__((used))
287 #  else
288 #    define PUBLIC
289 #    define USED
290 #  endif
291 #endif
292 
293 /**
294  * UNUSED marks variables (or sometimes functions) that have to be defined,
295  * but are sometimes (or always) unused beyond that. A common case is for
296  * a function parameter to be used in some build configurations but not others.
297  * Another case is fallback vfuncs that don't do anything with their params.
298  *
299  * Note that this should not be used for identifiers used in `assert()`;
300  * see ASSERTED below.
301  */
302 #ifdef HAVE_FUNC_ATTRIBUTE_UNUSED
303 #define UNUSED __attribute__((unused))
304 #elif defined (_MSC_VER)
305 #define UNUSED __pragma(warning(suppress:4100 4101 4189))
306 #else
307 #define UNUSED
308 #endif
309 
310 /**
311  * Use ASSERTED to indicate that an identifier is unused outside of an `assert()`,
312  * so that assert-free builds don't get "unused variable" warnings.
313  */
314 #ifdef NDEBUG
315 #define ASSERTED UNUSED
316 #else
317 #define ASSERTED
318 #endif
319 
320 #ifdef HAVE_FUNC_ATTRIBUTE_NONNULL
321 #define NONNULL __attribute__((__nonnull__))
322 #else
323 #define NONNULL
324 #endif
325 
326 #ifdef HAVE_FUNC_ATTRIBUTE_WARN_UNUSED_RESULT
327 #define MUST_CHECK __attribute__((warn_unused_result))
328 #else
329 #define MUST_CHECK
330 #endif
331 
332 #if defined(__GNUC__)
333 #define ATTRIBUTE_NOINLINE __attribute__((noinline))
334 #elif defined(_MSC_VER)
335 #define ATTRIBUTE_NOINLINE __declspec(noinline)
336 #else
337 #define ATTRIBUTE_NOINLINE
338 #endif
339 
340 /**
341  * Check that STRUCT::FIELD can hold MAXVAL.  We use a lot of bitfields
342  * in Mesa/gallium.  We have to be sure they're of sufficient size to
343  * hold the largest expected value.
344  * Note that with MSVC, enums are signed and enum bitfields need one extra
345  * high bit (always zero) to ensure the max value is handled correctly.
346  * This macro will detect that with MSVC, but not GCC.
347  */
348 #define ASSERT_BITFIELD_SIZE(STRUCT, FIELD, MAXVAL) \
349    do { \
350       ASSERTED STRUCT s; \
351       s.FIELD = (MAXVAL); \
352       assert((int) s.FIELD == (MAXVAL) && "Insufficient bitfield size!"); \
353    } while (0)
354 
355 
356 /** Compute ceiling of integer quotient of A divided by B. */
357 #define DIV_ROUND_UP( A, B )  ( ((A) + (B) - 1) / (B) )
358 
359 /** Clamp X to [MIN,MAX].  Turn NaN into MIN, arbitrarily. */
360 #define CLAMP( X, MIN, MAX )  ( (X)>(MIN) ? ((X)>(MAX) ? (MAX) : (X)) : (MIN) )
361 
362 /* Syntax sugar occuring frequently in graphics code */
363 #define SATURATE( X ) CLAMP(X, 0.0f, 1.0f)
364 
365 /** Minimum of two values: */
366 #define MIN2( A, B )   ( (A)<(B) ? (A) : (B) )
367 
368 /** Maximum of two values: */
369 #define MAX2( A, B )   ( (A)>(B) ? (A) : (B) )
370 
371 /** Minimum and maximum of three values: */
372 #define MIN3( A, B, C ) ((A) < (B) ? MIN2(A, C) : MIN2(B, C))
373 #define MAX3( A, B, C ) ((A) > (B) ? MAX2(A, C) : MAX2(B, C))
374 
375 /** Align a value to a power of two */
376 #define ALIGN_POT(x, pot_align) (((x) + (pot_align) - 1) & ~((pot_align) - 1))
377 
378 /** Checks is a value is a power of two. Does not handle zero. */
379 #define IS_POT(v) (((v) & ((v) - 1)) == 0)
380 
381 /** Set a single bit */
382 #define BITFIELD_BIT(b)      (1u << (b))
383 /** Set all bits up to excluding bit b */
384 #define BITFIELD_MASK(b)      \
385    ((b) == 32 ? (~0u) : BITFIELD_BIT((b) % 32) - 1)
386 /** Set count bits starting from bit b  */
387 #define BITFIELD_RANGE(b, count) \
388    (BITFIELD_MASK((b) + (count)) & ~BITFIELD_MASK(b))
389 
390 /** Set a single bit */
391 #define BITFIELD64_BIT(b)      (1ull << (b))
392 /** Set all bits up to excluding bit b */
393 #define BITFIELD64_MASK(b)      \
394    ((b) == 64 ? (~0ull) : BITFIELD64_BIT(b) - 1)
395 /** Set count bits starting from bit b  */
396 #define BITFIELD64_RANGE(b, count) \
397    (BITFIELD64_MASK((b) + (count)) & ~BITFIELD64_MASK(b))
398 
399 static inline int64_t
u_intN_max(unsigned bit_size)400 u_intN_max(unsigned bit_size)
401 {
402    assert(bit_size <= 64 && bit_size > 0);
403    return INT64_MAX >> (64 - bit_size);
404 }
405 
406 static inline int64_t
u_intN_min(unsigned bit_size)407 u_intN_min(unsigned bit_size)
408 {
409    /* On 2's compliment platforms, which is every platform Mesa is likely to
410     * every worry about, stdint.h generally calculated INT##_MIN in this
411     * manner.
412     */
413    return (-u_intN_max(bit_size)) - 1;
414 }
415 
416 static inline uint64_t
u_uintN_max(unsigned bit_size)417 u_uintN_max(unsigned bit_size)
418 {
419    assert(bit_size <= 64 && bit_size > 0);
420    return UINT64_MAX >> (64 - bit_size);
421 }
422 
423 /* alignas usage
424  * For struct or union, use alignas(align_size) on any member
425  * of it will make it aligned to align_size.
426  * See https://en.cppreference.com/w/c/language/_Alignas for
427  * details. We can use static_assert and alignof to check if
428  * the alignment result of alignas(align_size) on struct or
429  * union is valid.
430  * For example:
431  *   static_assert(alignof(struct tgsi_exec_machine) == 16, "")
432  * Also, we can use special code to see the size of the aligned
433  * struct or union at the compile time with GCC, Clang or MSVC.
434  * So we can see if the size of union or struct are as expected
435  * when using alignas(align_size) on its member.
436  * For example:
437  *   char (*__kaboom)[sizeof(struct tgsi_exec_machine)] = 1;
438  * can show us the size of struct tgsi_exec_machine at compile
439  * time.
440  */
441 #ifndef __cplusplus
442 #ifdef _MSC_VER
443 #define alignof _Alignof
444 #define alignas _Alignas
445 #else
446 #include <stdalign.h>
447 #endif
448 #endif
449 
450 /* Macros for static type-safety checking.
451  *
452  * https://clang.llvm.org/docs/ThreadSafetyAnalysis.html
453  */
454 
455 #if __has_attribute(capability)
456 typedef int __attribute__((capability("mutex"))) lock_cap_t;
457 
458 #define guarded_by(l) __attribute__((guarded_by(l)))
459 #define acquire_cap(l) __attribute((acquire_capability(l), no_thread_safety_analysis))
460 #define release_cap(l) __attribute((release_capability(l), no_thread_safety_analysis))
461 #define assert_cap(l) __attribute((assert_capability(l), no_thread_safety_analysis))
462 #define requires_cap(l) __attribute((requires_capability(l)))
463 #define disable_thread_safety_analysis __attribute((no_thread_safety_analysis))
464 
465 #else
466 
467 typedef int lock_cap_t;
468 
469 #define guarded_by(l)
470 #define acquire_cap(l)
471 #define release_cap(l)
472 #define assert_cap(l)
473 #define requires_cap(l)
474 #define disable_thread_safety_analysis
475 
476 #endif
477 
478 #define DO_PRAGMA(X) _Pragma (#X)
479 
480 #if defined(__clang__)
481 #define PRAGMA_DIAGNOSTIC_PUSH       _Pragma("clang diagnostic push")
482 #define PRAGMA_DIAGNOSTIC_POP        _Pragma("clang diagnostic pop")
483 #define PRAGMA_DIAGNOSTIC_ERROR(X)   DO_PRAGMA( clang diagnostic error #X )
484 #define PRAGMA_DIAGNOSTIC_WARNING(X) DO_PRAGMA( clang diagnostic warning #X )
485 #define PRAGMA_DIAGNOSTIC_IGNORED(X) DO_PRAGMA( clang diagnostic ignored #X )
486 #elif defined(__GNUC__)
487 #define PRAGMA_DIAGNOSTIC_PUSH       _Pragma("GCC diagnostic push")
488 #define PRAGMA_DIAGNOSTIC_POP        _Pragma("GCC diagnostic pop")
489 #define PRAGMA_DIAGNOSTIC_ERROR(X)   DO_PRAGMA( GCC diagnostic error #X )
490 #define PRAGMA_DIAGNOSTIC_WARNING(X) DO_PRAGMA( GCC diagnostic warning #X )
491 #define PRAGMA_DIAGNOSTIC_IGNORED(X) DO_PRAGMA( GCC diagnostic ignored #X )
492 #else
493 #define PRAGMA_DIAGNOSTIC_PUSH
494 #define PRAGMA_DIAGNOSTIC_POP
495 #define PRAGMA_DIAGNOSTIC_ERROR(X)
496 #define PRAGMA_DIAGNOSTIC_WARNING(X)
497 #define PRAGMA_DIAGNOSTIC_IGNORED(X)
498 #endif
499 
500 #define PASTE2(a, b) a ## b
501 #define PASTE3(a, b, c) a ## b ## c
502 #define PASTE4(a, b, c, d) a ## b ## c ## d
503 
504 #define CONCAT2(a, b) PASTE2(a, b)
505 #define CONCAT3(a, b, c) PASTE3(a, b, c)
506 #define CONCAT4(a, b, c, d) PASTE4(a, b, c, d)
507 
508 #if defined(__GNUC__)
509 #define PRAGMA_POISON(X) DO_PRAGMA( GCC poison X )
510 #elif defined(__clang__)
511 #define PRAGMA_POISON(X) DO_PRAGMA( clang poison X )
512 #else
513 #define PRAGMA_POISON
514 #endif
515 
516 #endif /* UTIL_MACROS_H */
517