Pavona Software APIs
macros.h
Go to the documentation of this file.
1// Copyright lowRISC contributors (OpenTitan project).
2// Licensed under the Apache License, Version 2.0, see LICENSE for details.
3// SPDX-License-Identifier: Apache-2.0
4
5#ifndef OPENTITAN_SW_DEVICE_LIB_BASE_MACROS_H_
6#define OPENTITAN_SW_DEVICE_LIB_BASE_MACROS_H_
7
8// This file may be used in .S files, in which case standard library includes
9// should be elided.
10#if !defined(__ASSEMBLER__) && !defined(NOSTDINC)
11#include <assert.h>
12#include <stddef.h>
13#include <stdint.h>
14
15#ifdef __cplusplus
16// The <type_traits> header is required for the C++-only `SignConverter` class.
17// See `SignConverter` for an explanation of this `extern "C++"` block.
18extern "C++" {
19#include <type_traits>
20}
21#endif
22#endif
23
24/**
25 * @file
26 * @brief Generic preprocessor macros that don't really fit anywhere else.
27 */
28
29/**
30 * Computes the number of elements in the given array.
31 *
32 * Note that this can only determine the length of *fixed-size* arrays. Due to
33 * limitations of C, it will incorrectly compute the size of an array passed as
34 * a function argument, because those automatically decay into pointers. This
35 * function can only be used correctly with:
36 * - Arrays declared as stack variables.
37 * - Arrays declared at global scope.
38 * - Arrays that are members of a struct or union.
39 *
40 * @param array The array expression to measure.
41 * @return The number of elements in the array, as a `size_t`.
42 */
43// This is a sufficiently well-known macro that we don't really need to bother
44// with a prefix like the others, and a rename will cause churn.
45#define ARRAYSIZE(array) (sizeof(array) / sizeof(array[0]))
46
47/**
48 * An annotation that a switch/case fallthrough is the intended behavior.
49 */
50#define OT_FALLTHROUGH_INTENDED __attribute__((fallthrough))
51
52/**
53 * A directive to force the compiler to inline a function.
54 */
55#define OT_ALWAYS_INLINE __attribute__((always_inline)) inline
56
57/**
58 * The `restrict` keyword is C specific, so we provide a C++-portable wrapper
59 * that uses the GCC name.
60 *
61 * It only needs to be used in headers; .c files can use `restrict` directly.
62 */
63#define OT_RESTRICT __restrict__
64
65/**
66 * An argument stringification macro.
67 */
68#define OT_STRINGIFY(a) OT_STRINGIFY_(a)
69#define OT_STRINGIFY_(a) #a
70
71/**
72 * A variable-argument macro that expands to the number of arguments passed into
73 * it, between 0 and 31 arguments.
74 *
75 * This macro is based off of a well-known preprocessor trick. This
76 * StackOverflow post expains the trick in detail:
77 * https://stackoverflow.com/questions/2308243/macro-returning-the-number-of-arguments-it-is-given-in-c
78 * TODO lowrisc/opentitan#2026: a dummy token is required for this to work
79 * correctly.
80 *
81 * @param dummy a dummy token that is required to be passed for the calculation
82 * to work correctly.
83 * @param ... the variable args list.
84 */
85#define OT_VA_ARGS_COUNT(dummy, ...) \
86 OT_SHIFT_N_VARIABLE_ARGS_(dummy, ##__VA_ARGS__, 31, 30, 29, 28, 27, 26, 25, \
87 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, \
88 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
89
90// Implementation details for `OT_VA_ARGS_COUNT()`.
91#define OT_SHIFT_N_VARIABLE_ARGS_(...) OT_GET_NTH_VARIABLE_ARG_(__VA_ARGS__)
92#define OT_GET_NTH_VARIABLE_ARG_(x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, \
93 x11, x12, x13, x14, x15, x16, x17, x18, x19, \
94 x20, x21, x22, x23, x24, x25, x26, x27, x28, \
95 x29, x30, x31, n, ...) \
96 n
97
98/**
99 * An argument concatenation macro.
100 *
101 * Because the `##` operator inhibits expansion, we use a level of indirection
102 * to create a macro which concatenates without inhibition.
103 */
104#define OT_CAT(a, ...) OT_PRIMITIVE_CAT(a, __VA_ARGS__)
105#define OT_PRIMITIVE_CAT(a, ...) a##__VA_ARGS__
106
107/**
108 * A macro which gets the nth arg from a __VA_LIST__
109 */
110#define OT_GET_ARG(n, ...) OT_CAT(OT_CAT(OT_GET_ARG_, n), _)(__VA_ARGS__)
111
112/**
113 * A macro which gets the last arg from a __VA_LIST__
114 *
115 * Note: we leave out the dummy argument because we want count to
116 * give us the number of args minus one so that the created
117 * OT_GET_ARG_n token will contain the correct integer.
118 */
119#define OT_GET_LAST_ARG(...) \
120 OT_GET_ARG(OT_VA_ARGS_COUNT(__VA_ARGS__), ##__VA_ARGS__)
121
122/**
123 * The following collection of `OT_GET_ARG` macros are used to construct the
124 * generic "get nth arg" macro.
125 */
126#define OT_GET_ARG_0_(x0, ...) x0
127#define OT_GET_ARG_1_(x1, x0, ...) x0
128#define OT_GET_ARG_2_(x2, x1, x0, ...) x0
129#define OT_GET_ARG_3_(x3, x2, x1, x0, ...) x0
130#define OT_GET_ARG_4_(x4, x3, x2, x1, x0, ...) x0
131#define OT_GET_ARG_5_(x5, x4, x3, x2, x1, x0, ...) x0
132#define OT_GET_ARG_6_(x6, x5, x4, x3, x2, x1, x0, ...) x0
133#define OT_GET_ARG_7_(x7, x6, x5, x4, x3, x2, x1, x0, ...) x0
134#define OT_GET_ARG_8_(x8, x7, x6, x5, x4, x3, x2, x1, x0, ...) x0
135#define OT_GET_ARG_9_(x9, x8, x7, x6, x5, x4, x3, x2, x1, x0, ...) x0
136#define OT_GET_ARG_10_(x10, x9, x8, x7, x6, x5, x4, x3, x2, x1, x0, ...) x0
137#define OT_GET_ARG_11_(x11, x10, x9, x8, x7, x6, x5, x4, x3, x2, x1, x0, ...) x0
138#define OT_GET_ARG_12_(x12, x11, x10, x9, x8, x7, x6, x5, x4, x3, x2, x1, x0, \
139 ...) \
140 x0
141#define OT_GET_ARG_13_(x13, x12, x11, x10, x9, x8, x7, x6, x5, x4, x3, x2, x1, \
142 x0, ...) \
143 x0
144#define OT_GET_ARG_14_(x14, x13, x12, x11, x10, x9, x8, x7, x6, x5, x4, x3, \
145 x2, x1, x0, ...) \
146 x0
147#define OT_GET_ARG_15_(x15, x14, x13, x12, x11, x10, x9, x8, x7, x6, x5, x4, \
148 x3, x2, x1, x0, ...) \
149 x0
150#define OT_GET_ARG_16_(x16, x15, x14, x13, x12, x11, x10, x9, x8, x7, x6, x5, \
151 x4, x3, x2, x1, x0, ...) \
152 x0
153#define OT_GET_ARG_17_(x17, x16, x15, x14, x13, x12, x11, x10, x9, x8, x7, x6, \
154 x5, x4, x3, x2, x1, x0, ...) \
155 x0
156#define OT_GET_ARG_18_(x18, x17, x16, x15, x14, x13, x12, x11, x10, x9, x8, \
157 x7, x6, x5, x4, x3, x2, x1, x0, ...) \
158 x0
159#define OT_GET_ARG_19_(x19, x18, x17, x16, x15, x14, x13, x12, x11, x10, x9, \
160 x8, x7, x6, x5, x4, x3, x2, x1, x0, ...) \
161 x0
162#define OT_GET_ARG_20_(x20, x19, x18, x17, x16, x15, x14, x13, x12, x11, x10, \
163 x9, x8, x7, x6, x5, x4, x3, x2, x1, x0, ...) \
164 x0
165#define OT_GET_ARG_21_(x21, x20, x19, x18, x17, x16, x15, x14, x13, x12, x11, \
166 x10, x9, x8, x7, x6, x5, x4, x3, x2, x1, x0, ...) \
167 x0
168#define OT_GET_ARG_22_(x22, x21, x20, x19, x18, x17, x16, x15, x14, x13, x12, \
169 x11, x10, x9, x8, x7, x6, x5, x4, x3, x2, x1, x0, ...) \
170 x0
171#define OT_GET_ARG_23_(x23, x22, x21, x20, x19, x18, x17, x16, x15, x14, x13, \
172 x12, x11, x10, x9, x8, x7, x6, x5, x4, x3, x2, x1, x0, \
173 ...) \
174 x0
175#define OT_GET_ARG_24_(x24, x23, x22, x21, x20, x19, x18, x17, x16, x15, x14, \
176 x13, x12, x11, x10, x9, x8, x7, x6, x5, x4, x3, x2, x1, \
177 x0, ...) \
178 x0
179#define OT_GET_ARG_25_(x25, x24, x23, x22, x21, x20, x19, x18, x17, x16, x15, \
180 x14, x13, x12, x11, x10, x9, x8, x7, x6, x5, x4, x3, \
181 x2, x1, x0, ...) \
182 x0
183#define OT_GET_ARG_26_(x26, x25, x24, x23, x22, x21, x20, x19, x18, x17, x16, \
184 x15, x14, x13, x12, x11, x10, x9, x8, x7, x6, x5, x4, \
185 x3, x2, x1, x0, ...) \
186 x0
187#define OT_GET_ARG_27_(x27, x26, x25, x24, x23, x22, x21, x20, x19, x18, x17, \
188 x16, x15, x14, x13, x12, x11, x10, x9, x8, x7, x6, x5, \
189 x4, x3, x2, x1, x0, ...) \
190 x0
191#define OT_GET_ARG_28_(x28, x27, x26, x25, x24, x23, x22, x21, x20, x19, x18, \
192 x17, x16, x15, x14, x13, x12, x11, x10, x9, x8, x7, x6, \
193 x5, x4, x3, x2, x1, x0, ...) \
194 x0
195#define OT_GET_ARG_29_(x29, x28, x27, x26, x25, x24, x23, x22, x21, x20, x19, \
196 x18, x17, x16, x15, x14, x13, x12, x11, x10, x9, x8, \
197 x7, x6, x5, x4, x3, x2, x1, x0, ...) \
198 x0
199#define OT_GET_ARG_30_(x30, x29, x28, x27, x26, x25, x24, x23, x22, x21, x20, \
200 x19, x18, x17, x16, x15, x14, x13, x12, x11, x10, x9, \
201 x8, x7, x6, x5, x4, x3, x2, x1, x0, ...) \
202 x0
203#define OT_GET_ARG_31_(x31, x30, x29, x28, x27, x26, x25, x24, x23, x22, x21, \
204 x20, x19, x18, x17, x16, x15, x14, x13, x12, x11, x10, \
205 x9, x8, x7, x6, x5, x4, x3, x2, x1, x0, ...) \
206 x0
207
208/**
209 * A macro that expands to an assertion for the offset of a struct member.
210 *
211 * @param type A struct type.
212 * @param member A member of the struct.
213 * @param offset Expected offset of the member.
214 */
215#define OT_ASSERT_MEMBER_OFFSET(type, member, offset) \
216 static_assert(offsetof(type, member) == UINT32_C(offset), \
217 "Unexpected offset for " #type "." #member)
218
219/**
220 * A macro that expands to an assertion for the offset of a struct member.
221 *
222 * @param type A struct type.
223 * @param member A member of the struct.
224 * @param enum_offset Expected offset of the member as an enum constant.
225 */
226#define OT_ASSERT_MEMBER_OFFSET_AS_ENUM(type, member, enum_offset) \
227 static_assert(offsetof(type, member) == enum_offset, \
228 "Unexpected offset for " #type "." #member)
229
230/**
231 * A macro that expands to an assertion for the size of a struct member.
232 *
233 * @param type A struct type.
234 * @param member A member of the struct.
235 * @param size Expected size of the type.
236 */
237#define OT_ASSERT_MEMBER_SIZE(type, member, size) \
238 static_assert(sizeof(((type *)0)->member) == UINT32_C(size), \
239 "Unexpected size for " #type)
240
241/**
242 * A macro that expands to an assertion for the size of a struct member.
243 *
244 * Identical to `OT_ASSERT_MEMBER_SIZE`, except the size parameter is provided
245 * as an enum constant.
246 *
247 * @param type A struct type.
248 * @param member A member of the struct.
249 * @param enum_size Expected size of the type as an enum constant.
250 */
251#define OT_ASSERT_MEMBER_SIZE_AS_ENUM(type, member, enum_size) \
252 static_assert(sizeof(((type *)0)->member) == enum_size, \
253 "Unexpected size for " #type)
254
255/**
256 * A macro that expands to an assertion for the size of a type.
257 *
258 * @param type A type.
259 * @param size Expected size of the type.
260 */
261#define OT_ASSERT_SIZE(type, size) \
262 static_assert(sizeof(type) == UINT32_C(size), "Unexpected size for " #type)
263
264/**
265 * A macro that expands to an assertion for an expected enum value.
266 *
267 * @param var An enum entry.
268 * @param expected_value Expected enum value.
269 */
270#define OT_ASSERT_ENUM_VALUE(var, expected_value) \
271 static_assert(var == expected_value, "Unexpected value for " #var)
272
273/**
274 * A variable-argument macro that expands to the number of arguments passed into
275 * it, between 1 and 32 arguments (1 action and 0-31 others).
276 *
277 * This macro accepts a macro name and a variable list of items, and will then
278 * expand to sequentially call the macro with each provided item in order. This
279 * can be useful for performing compile-time checks on arguments in variadic
280 * functions defined via macros.
281 *
282 * For example, OT_VAR_FOR_EACH(TEST, 5, 19, 32, 1, 4) would expand to be
283 * `do {TEST(5); TEST(19); TEST(32); TEST(1); TEST(4);} while (false)`
284 *
285 * @param action The name of the macro to invoke with each item individually.
286 * @param ... The variable args list to call the macro on.
287 */
288#define OT_VA_FOR_EACH(action, ...) \
289 do { \
290 OT_CAT(OT_CAT(OT_VA_FOR_EACH_, OT_VA_ARGS_COUNT(0, ##__VA_ARGS__)), _) \
291 (action, ##__VA_ARGS__) \
292 } while (false)
293
294/**
295 * The following collection of `OT_VA_FOR_EACH` macros are used to construct
296 * the generic "for each" `OT_VA_FOR_EACH` macro.
297 */
298#define OT_VA_FOR_EACH_0_(action)
299#define OT_VA_FOR_EACH_1_(action, item, ...) \
300 action(item); \
301 OT_VA_FOR_EACH_0_(action, ##__VA_ARGS__)
302#define OT_VA_FOR_EACH_2_(action, item, ...) \
303 action(item); \
304 OT_VA_FOR_EACH_1_(action, ##__VA_ARGS__)
305#define OT_VA_FOR_EACH_3_(action, item, ...) \
306 action(item); \
307 OT_VA_FOR_EACH_2_(action, ##__VA_ARGS__)
308#define OT_VA_FOR_EACH_4_(action, item, ...) \
309 action(item); \
310 OT_VA_FOR_EACH_3_(action, ##__VA_ARGS__)
311#define OT_VA_FOR_EACH_5_(action, item, ...) \
312 action(item); \
313 OT_VA_FOR_EACH_4_(action, ##__VA_ARGS__)
314#define OT_VA_FOR_EACH_6_(action, item, ...) \
315 action(item); \
316 OT_VA_FOR_EACH_5_(action, ##__VA_ARGS__)
317#define OT_VA_FOR_EACH_7_(action, item, ...) \
318 action(item); \
319 OT_VA_FOR_EACH_6_(action, ##__VA_ARGS__)
320#define OT_VA_FOR_EACH_8_(action, item, ...) \
321 action(item); \
322 OT_VA_FOR_EACH_7_(action, ##__VA_ARGS__)
323#define OT_VA_FOR_EACH_9_(action, item, ...) \
324 action(item); \
325 OT_VA_FOR_EACH_8_(action, ##__VA_ARGS__)
326#define OT_VA_FOR_EACH_10_(action, item, ...) \
327 action(item); \
328 OT_VA_FOR_EACH_9_(action, ##__VA_ARGS__)
329#define OT_VA_FOR_EACH_11_(action, item, ...) \
330 action(item); \
331 OT_VA_FOR_EACH_10_(action, ##__VA_ARGS__)
332#define OT_VA_FOR_EACH_12_(action, item, ...) \
333 action(item); \
334 OT_VA_FOR_EACH_11_(action, ##__VA_ARGS__)
335#define OT_VA_FOR_EACH_13_(action, item, ...) \
336 action(item); \
337 OT_VA_FOR_EACH_12_(action, ##__VA_ARGS__)
338#define OT_VA_FOR_EACH_14_(action, item, ...) \
339 action(item); \
340 OT_VA_FOR_EACH_13_(action, ##__VA_ARGS__)
341#define OT_VA_FOR_EACH_15_(action, item, ...) \
342 action(item); \
343 OT_VA_FOR_EACH_14_(action, ##__VA_ARGS__)
344#define OT_VA_FOR_EACH_16_(action, item, ...) \
345 action(item); \
346 OT_VA_FOR_EACH_15_(action, ##__VA_ARGS__)
347#define OT_VA_FOR_EACH_17_(action, item, ...) \
348 action(item); \
349 OT_VA_FOR_EACH_16_(action, ##__VA_ARGS__)
350#define OT_VA_FOR_EACH_18_(action, item, ...) \
351 action(item); \
352 OT_VA_FOR_EACH_17_(action, ##__VA_ARGS__)
353#define OT_VA_FOR_EACH_19_(action, item, ...) \
354 action(item); \
355 OT_VA_FOR_EACH_18_(action, ##__VA_ARGS__)
356#define OT_VA_FOR_EACH_20_(action, item, ...) \
357 action(item); \
358 OT_VA_FOR_EACH_19_(action, ##__VA_ARGS__)
359#define OT_VA_FOR_EACH_21_(action, item, ...) \
360 action(item); \
361 OT_VA_FOR_EACH_20_(action, ##__VA_ARGS__)
362#define OT_VA_FOR_EACH_22_(action, item, ...) \
363 action(item); \
364 OT_VA_FOR_EACH_21_(action, ##__VA_ARGS__)
365#define OT_VA_FOR_EACH_23_(action, item, ...) \
366 action(item); \
367 OT_VA_FOR_EACH_22_(action, ##__VA_ARGS__)
368#define OT_VA_FOR_EACH_24_(action, item, ...) \
369 action(item); \
370 OT_VA_FOR_EACH_23_(action, ##__VA_ARGS__)
371#define OT_VA_FOR_EACH_25_(action, item, ...) \
372 action(item); \
373 OT_VA_FOR_EACH_24_(action, ##__VA_ARGS__)
374#define OT_VA_FOR_EACH_26_(action, item, ...) \
375 action(item); \
376 OT_VA_FOR_EACH_25_(action, ##__VA_ARGS__)
377#define OT_VA_FOR_EACH_27_(action, item, ...) \
378 action(item); \
379 OT_VA_FOR_EACH_26_(action, ##__VA_ARGS__)
380#define OT_VA_FOR_EACH_28_(action, item, ...) \
381 action(item); \
382 OT_VA_FOR_EACH_27_(action, ##__VA_ARGS__)
383#define OT_VA_FOR_EACH_29_(action, item, ...) \
384 action(item); \
385 OT_VA_FOR_EACH_28_(action, ##__VA_ARGS__)
386#define OT_VA_FOR_EACH_30_(action, item, ...) \
387 action(item); \
388 OT_VA_FOR_EACH_29_(action, ##__VA_ARGS__)
389#define OT_VA_FOR_EACH_31_(action, item, ...) \
390 action(item); \
391 OT_VA_FOR_EACH_30_(action, ##__VA_ARGS__)
392
393/**
394 * A macro that checks whether a specified argument is not a standard C integer
395 * type with a width of 64 bits. Useful when assuming that variable arguments
396 * are 32 bits integers.
397 *
398 * @param arg An argument/expression
399 */
400#define OT_CHECK_NOT_INT64(arg) \
401 _Generic((arg), int64_t: false, uint64_t: false, default: true)
402
403/**
404 * A macro that expands to an assertion that wraps the `OT_CHECK_NOT_INT64`
405 * macro, failing with a relevant error message if the provided argument is a
406 * standard C integer type with a width of 64 bits.
407 *
408 * @param arg An argument/expression to check
409 * @param func_name The name of the macro/functionality being invoked, to be
410 * printed in a relevant error if the assertion fails.
411 */
412#define OT_FAIL_IF_64_BIT(arg, func_name) \
413 do { \
414 static_assert(OT_CHECK_NOT_INT64(arg), \
415 "Argument '" #arg "' passed to the " #func_name \
416 " function must be no wider than 32 bits. " \
417 "Hint: maybe cast with '(uint32_t) " #arg "'?"); \
418 } while (0)
419
420/**
421 * A macro representing the OpenTitan execution platform.
422 */
423#if defined(__riscv_xlen) && __riscv_xlen == 32
424#define OT_PLATFORM_RV32 1
425#endif
426
427/**
428 * A macro indicating whether software should assume reduced hardware
429 * support (for the `top_scafi_deprecated` toplevel).
430 */
431#ifdef OT_IS_SCAFI_DEPRECATED_REDUCED_SUPPORT_FOR_INTERNAL_USE_ONLY_
432#define OT_IS_SCAFI_DEPRECATED 1
433#endif
434
435/**
436 * Attribute for functions which return errors that must be acknowledged.
437 *
438 * This attribute must be used to mark all DIFs which return an error value of
439 * some kind, to ensure that callers do not accidentally drop the error on the
440 * ground.
441 *
442 * Normally, the standard way to drop such a value on the ground explicitly is
443 * with the syntax `(void)expr;`, in analogy with the behavior of C++'s
444 * `[[nodiscard]]` attribute.
445 * However, GCC does not implement this, so the idiom `if (expr) {}` should be
446 * used instead, for the time being.
447 * See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509.
448 */
449#define OT_WARN_UNUSED_RESULT __attribute__((warn_unused_result))
450
451/**
452 * Marks all pointer parameters as non-null so the compiler warns (`-Wnonnull`)
453 * when a NULL/0 argument is passed.
454 */
455#define OT_NONNULL __attribute__((nonnull))
456
457/**
458 * Attribute for weak functions that can be overridden, e.g., ISRs.
459 */
460#define OT_WEAK __attribute__((weak))
461
462/**
463 * Attribute to construct functions without prologue/epilogue sequences.
464 *
465 * Only basic asm statements can be safely included in naked functions.
466 *
467 * See https://gcc.gnu.org/onlinedocs/gcc/RISC-V-Function-Attributes.html
468 * #RISC-V-Function-Attributes
469 */
470#define OT_NAKED __attribute__((naked))
471
472/**
473 * Attribute to place symbols into particular sections.
474 *
475 * See https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html
476 * #Common-Function-Attributes
477 */
478#define OT_SECTION(name) __attribute__((section(name)))
479
480/**
481 * Pragma meant to place symbols into a NOBITS section with a specified name.
482 *
483 * This should only be used for zero-initialized globals (including
484 * implicitly zero-initialized ones, when the initializer is missing). The
485 * pragma won't affect variables that do not go into the bss section.
486 *
487 * Example:
488 *
489 * OT_SET_BSS_SECTION(".foo",
490 * uint32_t x; // emitted in section .foo instead of .bss
491 * uint32_t y = 42; // emitted in regular .data section (but don't do this)
492 * )
493 */
494#define OT_SET_BSS_SECTION(name, ...) \
495 OT_SET_BSS_SECTION_(clang section bss = name) \
496 __VA_ARGS__ \
497 _Pragma("clang section bss = \"\"")
498#define OT_SET_BSS_SECTION_(section) _Pragma(#section)
499
500/**
501 * Attribute to suppress the inlining of a function at its call sites.
502 *
503 * See https://clang.llvm.org/docs/AttributeReference.html#noinline.
504 */
505#define OT_NOINLINE __attribute__((noinline))
506
507/**
508 * Returns the address of the current function stack frame.
509 *
510 * See https://gcc.gnu.org/onlinedocs/gcc/Return-Address.html.
511 */
512#define OT_FRAME_ADDR() __builtin_frame_address(0)
513
514/**
515 * Hints to the compiler that some point is not reachable.
516 *
517 * One use case could be a function that never returns.
518 *
519 * Please not that if the control flow reaches the point of the
520 * __builtin_unreachable, the program is undefined.
521 *
522 * See https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html.
523 */
524#define OT_UNREACHABLE() __builtin_unreachable()
525
526/**
527 * Attribute for weak alias that can be overridden, e.g., Mock overrides in
528 * DIFs.
529 */
530#define OT_ALIAS(name) __attribute__((alias(name)))
531
532/**
533 * Defines a local symbol named `kName_` whose address resolves to the
534 * program counter value an inline assembly block at this location would
535 * see.
536 *
537 * The primary intention of this macro is to allow for peripheral tests to be
538 * written that want to assert that a specific program counter reported by the
539 * hardware corresponds to actual code that executed.
540 *
541 * For example, suppose that we're waiting for an interrupt to fire, and want
542 * to verify that it fired in a specific region. We have two volatile globals:
543 * `irq_happened`, which the ISR sets before returning, and `irq_pc`, which
544 * the ISR sets to whatever PC the hardware reports it came from. The
545 * code below tests that the reported PC matches expectations.
546 *
547 * ```
548 * OT_ADDRESSABLE_LABEL(kIrqWaitStart);
549 * enable_interrupts();
550 * while(!irq_happened) {
551 * wait_for_interrupt();
552 * }
553 * OT_ADDRESSABLE_LABEL(kIrqWaitEnd);
554 *
555 * CHECK(irq_pc >= &kIrqWaitStart && irq_pc < &IrqWaitEnd);
556 * ```
557 *
558 * Note that this only works if all functions called between the two labels
559 * are actually inlined; if the interrupt fires inside of one of those two
560 * functions, it will appear to not have the right PC, even though it is
561 * logically inside the pair of labels.
562 *
563 * # Volatile Semantics
564 *
565 * This has the same semantics as a `volatile` inline assembly block: it
566 * may be reordered with respect to all operations except other volatile
567 * operations (i.e. volatile assembly and volatile read/write, such as
568 * MMIO). For example, in the following code, `kBefore` and `kAfter` can
569 * wind up having the same address:
570 *
571 * ```
572 * OT_ADDRESSABLE_LABEL(kBefore);
573 * x += 5;
574 * OT_ADDRESSABLE_LABEL(kAfter);
575 * ```
576 *
577 * Because it can be reordered and the compiler is free to emit whatever
578 * instructions it likes, comparing a program counter value obtained from
579 * the hardware with a symbol emitted by this macro is brittle (and,
580 * ultimately, futile). Instead, it should be used in pairs to create a
581 * range of addresses that a value can be checked for being within.
582 *
583 * For this primitive to work correctly there must be something that counts as
584 * a volatile operation between the two labels. These include:
585 *
586 * - Direct reads or writes to MMIO registers or CSRs.
587 * - A volatile assembly block with at least one instruction.
588 * - Any DIF or driver call that may touch an MMIO register or a CSR.
589 * - `LOG`ging, `printf`ing, or `CHECK`ing.
590 * - `wait_for_interrupt()`.
591 * - `barrier32()`, but NOT `launder32()`.
592 *
593 * This macro should not be used on the host side. It will compile, but will
594 * probably not provide any meaningful values. In the future, it may start
595 * producing a garbage value on the host side.
596 *
597 * # Symbol Access
598 *
599 * The symbol reference `kName_` will only be scoped to the current block
600 * in a function, but it can be redeclared in the same file with
601 *
602 * ```
603 * extern const char kName_[];
604 * ```
605 *
606 * if needed elsewhere (although this should be avoided for readability's sake).
607 * The name of the constant is global to the current `.c` file only.
608 *
609 * # Example Uses
610 */
611#define OT_ADDRESSABLE_LABEL(kName_) \
612 extern const char kName_[]; \
613 asm volatile(".local " #kName_ "; " #kName_ ":;"); \
614 /* Force this to be at function scope. It could go at global scope, but it \
615 * would give a garbage value dependent on the whims of the linker. */ \
616 do { \
617 } while (false)
618
619/**
620 * Evaluates and discards `expr_`.
621 *
622 * This is needed because ‘(void)expr;` does not work for gcc.
623 */
624#define OT_DISCARD(expr_) \
625 if (expr_) { \
626 }
627
628/**
629 * An attribute used for static variables indicating that they should be
630 * retained in the object file, even if they are seemingly unreferenced.
631 */
632#define OT_USED __attribute__((used))
633
634/**
635 * An attribute used to indicate that a character array variable is not intended
636 * to be treated as a null-terminated string.
637 */
638#if defined(__clang__) && __clang_major__ >= 21
639#define OT_NONSTRING __attribute__((nonstring))
640#elif defined(__GNUC__) && !defined(__clang__)
641#define OT_NONSTRING __attribute__((nonstring))
642#else
643#define OT_NONSTRING
644#endif
645
646/**
647 * OT_BUILD_FOR_STATIC_ANALYZER indicates whether we are compiling for the
648 * purpose of static analysis. Currently, this macro only detects
649 * Clang-Analyzer, which is used as a backend by Clang-Tidy.
650 */
651#ifdef __clang_analyzer__
652#define OT_BUILD_FOR_STATIC_ANALYZER 1
653#else
654#define OT_BUILD_FOR_STATIC_ANALYZER 0
655#endif
656
657/**
658 * This macro is used to align an offset to point to a 32b value.
659 */
660#define OT_ALIGN_MEM(x) (uint32_t)(4 + (((uintptr_t)(x) - 1) & ~3u))
661
662#if !defined(__ASSEMBLER__) && !defined(NOSTDINC) && \
663 !defined(RUST_PREPROCESSOR_EMIT)
664#ifndef __cplusplus
666 char err;
667};
668
669/**
670 * This macro converts a given unsigned integer value to its signed counterpart.
671 */
672#define OT_SIGNED(value) \
673 _Generic((value), \
674 unsigned char: (signed char)(value), \
675 unsigned short: (short)(value), \
676 unsigned int: (int)(value), \
677 unsigned long: (long)(value), \
678 unsigned long long: (long long)(value), \
679 default: (struct OtSignConversionUnsupportedType){.err = 1})
680
681/**
682 * This macro converts a given signed integer value to its unsigned counterpart.
683 */
684#define OT_UNSIGNED(value) \
685 _Generic((value), \
686 signed char: (unsigned char)(value), \
687 short: (unsigned short)(value), \
688 int: (unsigned int)(value), \
689 long: (unsigned long)(value), \
690 long long: (unsigned long long)(value), \
691 default: (struct OtSignConversionUnsupportedType){.err = 1})
692#else // __cplusplus
693// Templates require "C++" linkage. Even though this block is only reachable
694// when __cplusplus is defined, it's possible that we are in the middle of an
695// `extern "C"` block. In case that is true, we explicitly set the linkage to
696// "C++" for the coming C++ templates.
697extern "C++" {
698namespace {
699template <typename T>
700class SignConverter {
701 public:
702 using SignedT = typename std::make_signed<T>::type;
703 using UnsignedT = typename std::make_unsigned<T>::type;
704 static constexpr SignedT as_signed(T value) {
705 return static_cast<SignedT>(value);
706 }
707 static constexpr UnsignedT as_unsigned(T value) {
708 return static_cast<UnsignedT>(value);
709 }
710};
711} // namespace
712}
713#define OT_SIGNED(value) (SignConverter<__typeof__(value)>::as_signed((value)))
714#define OT_UNSIGNED(value) \
715 (SignConverter<__typeof__(value)>::as_unsigned((value)))
716#endif // __cplusplus
717#endif // !defined(__ASSEMBLER__) && !defined(NOSTDINC) &&
718 // !defined(RUST_PREPROCESSOR_EMIT)
719
720// This routine makes sure that a condition that can be changed by IRQs
721// is evaluated inside a critical session. It executes a `wfi` between
722// evaluations.
723#define ATOMIC_WAIT_FOR_INTERRUPT(_volatile_condition) \
724 while (true) { \
725 irq_global_ctrl(false); \
726 if ((_volatile_condition)) { \
727 break; \
728 } \
729 wait_for_interrupt(); \
730 irq_global_ctrl(true); \
731 } \
732 irq_global_ctrl(true)
733
734/**
735 * Macros for implementing OT ISRs.
736 */
737#define OT_WORD_SIZE 4
738#define OT_HALF_WORD_SIZE (OT_WORD_SIZE / 2)
739// The ISR context size is 30 words. There are 32 cpu registers; 30 of them
740// need to be saved. The two that do not are `sp` and `gp` (x2 and x3).
741#define OT_CONTEXT_SIZE (OT_WORD_SIZE * 30)
742
743/**
744 * A macro that returns the minimum of two values.
745 *
746 * @param a First value.
747 * @param b Second value.
748 */
749#ifndef MIN
750#define MIN(a, b) \
751 ({ \
752 typeof(a) _a = (a); \
753 typeof(b) _b = (b); \
754 _a < _b ? _a : _b; \
755 })
756#endif
757
758/**
759 * A macro that returns the maximum of two values.
760 *
761 * @param a First value.
762 * @param b Second value.
763 *
764 */
765#ifndef MAX
766#define MAX(a, b) \
767 ({ \
768 typeof(a) _a = (a); \
769 typeof(b) _b = (b); \
770 _a > _b ? _a : _b; \
771 })
772#endif
773
774#endif // OPENTITAN_SW_DEVICE_LIB_BASE_MACROS_H_