xref: /openbmc/qemu/include/qemu/compiler.h (revision bb153e7960b24fb31b36b4230e4d1d008ae2f129)
1 /* compiler.h: macros to abstract away compiler specifics
2  *
3  * This work is licensed under the terms of the GNU GPL, version 2 or later.
4  * See the COPYING file in the top-level directory.
5  */
6 
7 #ifndef COMPILER_H
8 #define COMPILER_H
9 
10 #define HOST_BIG_ENDIAN (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)
11 
12 /* HOST_LONG_BITS is the size of a native pointer in bits. */
13 #define HOST_LONG_BITS (__SIZEOF_POINTER__ * 8)
14 
15 #if defined __clang_analyzer__ || defined __COVERITY__
16 #define QEMU_STATIC_ANALYSIS 1
17 #endif
18 
19 #ifdef __cplusplus
20 #define QEMU_EXTERN_C extern "C"
21 #else
22 #define QEMU_EXTERN_C extern
23 #endif
24 
25 #define QEMU_PACKED __attribute__((packed))
26 #define QEMU_ALIGNED(X) __attribute__((aligned(X)))
27 
28 #ifndef glue
29 #define xglue(x, y) x ## y
30 #define glue(x, y) xglue(x, y)
31 #define stringify(s) tostring(s)
32 #define tostring(s) #s
33 #endif
34 
35 /* Expands into an identifier stemN, where N is another number each time */
36 #define MAKE_IDENTIFIER(stem) glue(stem, __COUNTER__)
37 
38 #ifndef likely
39 #define likely(x)   __builtin_expect(!!(x), 1)
40 #define unlikely(x)   __builtin_expect(!!(x), 0)
41 #endif
42 
43 #ifndef container_of
44 #define container_of(ptr, type, member) ({                      \
45         const typeof(((type *) 0)->member) *__mptr = (ptr);     \
46         (type *) ((char *) __mptr - offsetof(type, member));})
47 #endif
48 
49 #define sizeof_field(type, field) sizeof(((type *)0)->field)
50 
51 /*
52  * Calculate the number of bytes up to and including the given 'field' of
53  * 'container'.
54  */
55 #define endof(container, field) \
56     (offsetof(container, field) + sizeof_field(container, field))
57 
58 /* Convert from a base type to a parent type, with compile time checking.  */
59 #define DO_UPCAST(type, field, dev) ( __extension__ ( { \
60     char __attribute__((unused)) offset_must_be_zero[ \
61         -offsetof(type, field)]; \
62     container_of(dev, type, field);}))
63 
64 #define typeof_field(type, field) typeof(((type *)0)->field)
65 #define type_check(t1,t2) ((t1*)0 - (t2*)0)
66 
67 #define QEMU_BUILD_BUG_ON_STRUCT(x) \
68     struct { \
69         int:(x) ? -1 : 1; \
70     }
71 
72 #define QEMU_BUILD_BUG_MSG(x, msg) _Static_assert(!(x), msg)
73 
74 #define QEMU_BUILD_BUG_ON(x) QEMU_BUILD_BUG_MSG(x, "not expecting: " #x)
75 
76 #define QEMU_BUILD_BUG_ON_ZERO(x) (sizeof(QEMU_BUILD_BUG_ON_STRUCT(x)) - \
77                                    sizeof(QEMU_BUILD_BUG_ON_STRUCT(x)))
78 
79 #if !defined(__clang__) && defined(_WIN32)
80 /*
81  * Map __printf__ to __gnu_printf__ because we want standard format strings even
82  * when MinGW or GLib include files use __printf__.
83  */
84 # define __printf__ __gnu_printf__
85 #endif
86 
87 #ifndef __has_warning
88 #define __has_warning(x) 0 /* compatibility with non-clang compilers */
89 #endif
90 
91 #ifndef __has_feature
92 #define __has_feature(x) 0 /* compatibility with non-clang compilers */
93 #endif
94 
95 #ifndef __has_builtin
96 #define __has_builtin(x) 0 /* compatibility with non-clang compilers */
97 #endif
98 
99 #if __has_builtin(__builtin_assume_aligned) || !defined(__clang__)
100 #define HAS_ASSUME_ALIGNED
101 #endif
102 
103 #ifndef __has_attribute
104 #define __has_attribute(x) 0 /* compatibility with older GCC */
105 #endif
106 
107 #if defined(__SANITIZE_ADDRESS__) || __has_feature(address_sanitizer)
108 # define QEMU_SANITIZE_ADDRESS 1
109 #endif
110 
111 #if defined(__SANITIZE_THREAD__) || __has_feature(thread_sanitizer)
112 # define QEMU_SANITIZE_THREAD 1
113 #endif
114 
115 /*
116  * GCC doesn't provide __has_attribute() until GCC 5, but we know all the GCC
117  * versions we support have the "flatten" attribute. Clang may not have the
118  * "flatten" attribute but always has __has_attribute() to check for it.
119  */
120 #if __has_attribute(flatten) || !defined(__clang__)
121 # define QEMU_FLATTEN __attribute__((flatten))
122 #else
123 # define QEMU_FLATTEN
124 #endif
125 
126 /*
127  * If __attribute__((error)) is present, use it to produce an error at
128  * compile time.  Otherwise, one must wait for the linker to diagnose
129  * the missing symbol.
130  */
131 #if __has_attribute(error)
132 # define QEMU_ERROR(X) __attribute__((error(X)))
133 #else
134 # define QEMU_ERROR(X)
135 #endif
136 
137 /*
138  * The nonstring variable attribute specifies that an object or member
139  * declaration with type array of char or pointer to char is intended
140  * to store character arrays that do not necessarily contain a terminating
141  * NUL character. This is useful in detecting uses of such arrays or pointers
142  * with functions that expect NUL-terminated strings, and to avoid warnings
143  * when such an array or pointer is used as an argument to a bounded string
144  * manipulation function such as strncpy.
145  */
146 #if __has_attribute(nonstring)
147 # define QEMU_NONSTRING __attribute__((nonstring))
148 #else
149 # define QEMU_NONSTRING
150 #endif
151 
152 /*
153  * Forced inlining may be desired to encourage constant propagation
154  * of function parameters.  However, it can also make debugging harder,
155  * so disable it for a non-optimizing build.
156  */
157 #if defined(__OPTIMIZE__)
158 #define QEMU_ALWAYS_INLINE  __attribute__((always_inline))
159 #else
160 #define QEMU_ALWAYS_INLINE
161 #endif
162 
163 /**
164  * In most cases, normal "fallthrough" comments are good enough for
165  * switch-case statements, but sometimes the compiler has problems
166  * with those. In that case you can use QEMU_FALLTHROUGH instead.
167  */
168 #if __has_attribute(fallthrough)
169 # define QEMU_FALLTHROUGH __attribute__((fallthrough))
170 #else
171 # define QEMU_FALLTHROUGH do {} while (0) /* fallthrough */
172 #endif
173 
174 #ifdef CONFIG_CFI
175 /*
176  * If CFI is enabled, use an attribute to disable cfi-icall on the following
177  * function
178  */
179 #define QEMU_DISABLE_CFI __attribute__((no_sanitize("cfi-icall")))
180 #else
181 /* If CFI is not enabled, use an empty define to not change the behavior */
182 #define QEMU_DISABLE_CFI
183 #endif
184 
185 #if __has_attribute(annotate)
186 #define QEMU_ANNOTATE(x) __attribute__((annotate(x)))
187 #else
188 #define QEMU_ANNOTATE(x)
189 #endif
190 
191 #if __has_attribute(used)
192 # define QEMU_USED __attribute__((used))
193 #else
194 # define QEMU_USED
195 #endif
196 
197 /*
198  * Disable -ftrivial-auto-var-init on a local variable.
199  *
200  * Use this in cases where there a method in the device I/O path (or other
201  * important hot paths), that has large variables on the stack. A rule of
202  * thumb is that "large" means a method with 4kb data in the local stack
203  * frame. Any variables which are KB in size, should be annotated with this
204  * attribute, to pre-emptively eliminate any potential overhead from the
205  * compiler's implicit zero'ing of memory.
206  *
207  * Given that this turns off a security hardening feature, when using this
208  * to flag variables, it is important that the code is double-checked to
209  * ensure there is no possible use of uninitialized data in the method.
210  */
211 #if __has_attribute(uninitialized)
212 # define QEMU_UNINITIALIZED __attribute__((uninitialized))
213 #else
214 # define QEMU_UNINITIALIZED
215 #endif
216 
217 /*
218  * http://clang.llvm.org/docs/ThreadSafetyAnalysis.html
219  *
220  * TSA is available since clang 3.6-ish.
221  */
222 #ifdef __clang__
223 #  define TSA(x)   __attribute__((x))
224 #else
225 #  define TSA(x)   /* No TSA, make TSA attributes no-ops. */
226 #endif
227 
228 /*
229  * TSA_CAPABILITY() is used to annotate typedefs:
230  *
231  * typedef pthread_mutex_t TSA_CAPABILITY("mutex") tsa_mutex;
232  */
233 #define TSA_CAPABILITY(x) TSA(capability(x))
234 
235 /*
236  * TSA_GUARDED_BY() is used to annotate global variables,
237  * the data is guarded:
238  *
239  * Foo foo TSA_GUARDED_BY(mutex);
240  */
241 #define TSA_GUARDED_BY(x) TSA(guarded_by(x))
242 
243 /*
244  * TSA_PT_GUARDED_BY() is used to annotate global pointers, the data
245  * behind the pointer is guarded.
246  *
247  * Foo* ptr TSA_PT_GUARDED_BY(mutex);
248  */
249 #define TSA_PT_GUARDED_BY(x) TSA(pt_guarded_by(x))
250 
251 /*
252  * The TSA_REQUIRES() is used to annotate functions: the caller of the
253  * function MUST hold the resource, the function will NOT release it.
254  *
255  * More than one mutex may be specified, comma-separated.
256  *
257  * void Foo(void) TSA_REQUIRES(mutex);
258  */
259 #define TSA_REQUIRES(...) TSA(requires_capability(__VA_ARGS__))
260 #define TSA_REQUIRES_SHARED(...) TSA(requires_shared_capability(__VA_ARGS__))
261 
262 /*
263  * TSA_EXCLUDES() is used to annotate functions: the caller of the
264  * function MUST NOT hold resource, the function first acquires the
265  * resource, and then releases it.
266  *
267  * More than one mutex may be specified, comma-separated.
268  *
269  * void Foo(void) TSA_EXCLUDES(mutex);
270  */
271 #define TSA_EXCLUDES(...) TSA(locks_excluded(__VA_ARGS__))
272 
273 /*
274  * TSA_ACQUIRE() is used to annotate functions: the caller of the
275  * function MUST NOT hold the resource, the function will acquire the
276  * resource, but NOT release it.
277  *
278  * More than one mutex may be specified, comma-separated.
279  *
280  * void Foo(void) TSA_ACQUIRE(mutex);
281  */
282 #define TSA_ACQUIRE(...) TSA(acquire_capability(__VA_ARGS__))
283 #define TSA_ACQUIRE_SHARED(...) TSA(acquire_shared_capability(__VA_ARGS__))
284 
285 /*
286  * TSA_RELEASE() is used to annotate functions: the caller of the
287  * function MUST hold the resource, but the function will then release it.
288  *
289  * More than one mutex may be specified, comma-separated.
290  *
291  * void Foo(void) TSA_RELEASE(mutex);
292  */
293 #define TSA_RELEASE(...) TSA(release_capability(__VA_ARGS__))
294 #define TSA_RELEASE_SHARED(...) TSA(release_shared_capability(__VA_ARGS__))
295 
296 /*
297  * TSA_NO_TSA is used to annotate functions.  Use only when you need to.
298  *
299  * void Foo(void) TSA_NO_TSA;
300  */
301 #define TSA_NO_TSA TSA(no_thread_safety_analysis)
302 
303 /*
304  * TSA_ASSERT() is used to annotate functions: This function will assert that
305  * the lock is held. When it returns, the caller of the function is assumed to
306  * already hold the resource.
307  *
308  * More than one mutex may be specified, comma-separated.
309  */
310 #define TSA_ASSERT(...) TSA(assert_capability(__VA_ARGS__))
311 #define TSA_ASSERT_SHARED(...) TSA(assert_shared_capability(__VA_ARGS__))
312 
313 /*
314  * Ugly CPP trick that is like "defined FOO", but also works in C
315  * code.  Useful to replace #ifdef with "if" statements; assumes
316  * the symbol was defined with Meson's "config.set()", so it is empty
317  * if defined.
318  */
319 #define IS_ENABLED(x)                  IS_EMPTY(x)
320 
321 #define IS_EMPTY_JUNK_                 junk,
322 #define IS_EMPTY(value)                IS_EMPTY_(IS_EMPTY_JUNK_##value)
323 
324 /* Expands to either SECOND_ARG(junk, 1, 0) or SECOND_ARG(IS_EMPTY_JUNK_CONFIG_FOO 1, 0)  */
325 #define SECOND_ARG(first, second, ...) second
326 #define IS_EMPTY_(junk_maybecomma)     SECOND_ARG(junk_maybecomma 1, 0)
327 
328 #ifndef __cplusplus
329 /*
330  * Useful in macros that need to declare temporary variables.  For example,
331  * the variable that receives the old value of an atomically-accessed
332  * variable must be non-qualified, because atomic builtins return values
333  * through a pointer-type argument as in __atomic_load(&var, &old, MODEL).
334  *
335  * This macro has to handle types smaller than int manually, because of
336  * implicit promotion.  int and larger types, as well as pointers, can be
337  * converted to a non-qualified type just by applying a binary operator.
338  */
339 #define typeof_strip_qual(expr)                                                    \
340   typeof(                                                                          \
341     __builtin_choose_expr(                                                         \
342       __builtin_types_compatible_p(typeof(expr), bool) ||                          \
343         __builtin_types_compatible_p(typeof(expr), const bool) ||                  \
344         __builtin_types_compatible_p(typeof(expr), volatile bool) ||               \
345         __builtin_types_compatible_p(typeof(expr), const volatile bool),           \
346         (bool)1,                                                                   \
347     __builtin_choose_expr(                                                         \
348       __builtin_types_compatible_p(typeof(expr), signed char) ||                   \
349         __builtin_types_compatible_p(typeof(expr), const signed char) ||           \
350         __builtin_types_compatible_p(typeof(expr), volatile signed char) ||        \
351         __builtin_types_compatible_p(typeof(expr), const volatile signed char),    \
352         (signed char)1,                                                            \
353     __builtin_choose_expr(                                                         \
354       __builtin_types_compatible_p(typeof(expr), unsigned char) ||                 \
355         __builtin_types_compatible_p(typeof(expr), const unsigned char) ||         \
356         __builtin_types_compatible_p(typeof(expr), volatile unsigned char) ||      \
357         __builtin_types_compatible_p(typeof(expr), const volatile unsigned char),  \
358         (unsigned char)1,                                                          \
359     __builtin_choose_expr(                                                         \
360       __builtin_types_compatible_p(typeof(expr), signed short) ||                  \
361         __builtin_types_compatible_p(typeof(expr), const signed short) ||          \
362         __builtin_types_compatible_p(typeof(expr), volatile signed short) ||       \
363         __builtin_types_compatible_p(typeof(expr), const volatile signed short),   \
364         (signed short)1,                                                           \
365     __builtin_choose_expr(                                                         \
366       __builtin_types_compatible_p(typeof(expr), unsigned short) ||                \
367         __builtin_types_compatible_p(typeof(expr), const unsigned short) ||        \
368         __builtin_types_compatible_p(typeof(expr), volatile unsigned short) ||     \
369         __builtin_types_compatible_p(typeof(expr), const volatile unsigned short), \
370         (unsigned short)1,                                                         \
371       (expr)+0))))))
372 #endif
373 
374 #endif /* COMPILER_H */
375