verify.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. /* Compile-time assert-like macros.
  2. Copyright (C) 2005-2006, 2009-2023 Free Software Foundation, Inc.
  3. This file is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Lesser General Public License as
  5. published by the Free Software Foundation; either version 2.1 of the
  6. License, or (at your option) any later version.
  7. This file is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Lesser General Public License for more details.
  11. You should have received a copy of the GNU Lesser General Public License
  12. along with this program. If not, see <https://www.gnu.org/licenses/>. */
  13. /* Written by Paul Eggert, Bruno Haible, and Jim Meyering. */
  14. #ifndef _GL_VERIFY_H
  15. #define _GL_VERIFY_H
  16. /* Define _GL_HAVE__STATIC_ASSERT to 1 if _Static_assert (R, DIAGNOSTIC)
  17. works as per C11. This is supported by GCC 4.6.0+ and by clang 4+.
  18. Define _GL_HAVE__STATIC_ASSERT1 to 1 if _Static_assert (R) works as
  19. per C23. This is supported by GCC 9.1+.
  20. Support compilers claiming conformance to the relevant standard,
  21. and also support GCC when not pedantic. If we were willing to slow
  22. 'configure' down we could also use it with other compilers, but
  23. since this affects only the quality of diagnostics, why bother? */
  24. #ifndef __cplusplus
  25. # if (201112 <= __STDC_VERSION__ \
  26. || (!defined __STRICT_ANSI__ \
  27. && (4 < __GNUC__ + (6 <= __GNUC_MINOR__) || 5 <= __clang_major__)))
  28. # define _GL_HAVE__STATIC_ASSERT 1
  29. # endif
  30. # if (202311 <= __STDC_VERSION__ \
  31. || (!defined __STRICT_ANSI__ && 9 <= __GNUC__))
  32. # define _GL_HAVE__STATIC_ASSERT1 1
  33. # endif
  34. #endif
  35. /* FreeBSD 9.1 <sys/cdefs.h>, included by <stddef.h> and lots of other
  36. system headers, defines a conflicting _Static_assert that is no
  37. better than ours; override it. */
  38. #ifndef _GL_HAVE__STATIC_ASSERT
  39. # include <stddef.h>
  40. # undef _Static_assert
  41. #endif
  42. /* Each of these macros verifies that its argument R is nonzero. To
  43. be portable, R should be an integer constant expression. Unlike
  44. assert (R), there is no run-time overhead.
  45. If _Static_assert works, verify (R) uses it directly. Similarly,
  46. _GL_VERIFY_TRUE works by packaging a _Static_assert inside a struct
  47. that is an operand of sizeof.
  48. The code below uses several ideas for C++ compilers, and for C
  49. compilers that do not support _Static_assert:
  50. * The first step is ((R) ? 1 : -1). Given an expression R, of
  51. integral or boolean or floating-point type, this yields an
  52. expression of integral type, whose value is later verified to be
  53. constant and nonnegative.
  54. * Next this expression W is wrapped in a type
  55. struct _gl_verify_type {
  56. unsigned int _gl_verify_error_if_negative: W;
  57. }.
  58. If W is negative, this yields a compile-time error. No compiler can
  59. deal with a bit-field of negative size.
  60. One might think that an array size check would have the same
  61. effect, that is, that the type struct { unsigned int dummy[W]; }
  62. would work as well. However, inside a function, some compilers
  63. (such as C++ compilers and GNU C) allow local parameters and
  64. variables inside array size expressions. With these compilers,
  65. an array size check would not properly diagnose this misuse of
  66. the verify macro:
  67. void function (int n) { verify (n < 0); }
  68. * For the verify macro, the struct _gl_verify_type will need to
  69. somehow be embedded into a declaration. To be portable, this
  70. declaration must declare an object, a constant, a function, or a
  71. typedef name. If the declared entity uses the type directly,
  72. such as in
  73. struct dummy {...};
  74. typedef struct {...} dummy;
  75. extern struct {...} *dummy;
  76. extern void dummy (struct {...} *);
  77. extern struct {...} *dummy (void);
  78. two uses of the verify macro would yield colliding declarations
  79. if the entity names are not disambiguated. A workaround is to
  80. attach the current line number to the entity name:
  81. #define _GL_CONCAT0(x, y) x##y
  82. #define _GL_CONCAT(x, y) _GL_CONCAT0 (x, y)
  83. extern struct {...} * _GL_CONCAT (dummy, __LINE__);
  84. But this has the problem that two invocations of verify from
  85. within the same macro would collide, since the __LINE__ value
  86. would be the same for both invocations. (The GCC __COUNTER__
  87. macro solves this problem, but is not portable.)
  88. A solution is to use the sizeof operator. It yields a number,
  89. getting rid of the identity of the type. Declarations like
  90. extern int dummy [sizeof (struct {...})];
  91. extern void dummy (int [sizeof (struct {...})]);
  92. extern int (*dummy (void)) [sizeof (struct {...})];
  93. can be repeated.
  94. * Should the implementation use a named struct or an unnamed struct?
  95. Which of the following alternatives can be used?
  96. extern int dummy [sizeof (struct {...})];
  97. extern int dummy [sizeof (struct _gl_verify_type {...})];
  98. extern void dummy (int [sizeof (struct {...})]);
  99. extern void dummy (int [sizeof (struct _gl_verify_type {...})]);
  100. extern int (*dummy (void)) [sizeof (struct {...})];
  101. extern int (*dummy (void)) [sizeof (struct _gl_verify_type {...})];
  102. In the second and sixth case, the struct type is exported to the
  103. outer scope; two such declarations therefore collide. GCC warns
  104. about the first, third, and fourth cases. So the only remaining
  105. possibility is the fifth case:
  106. extern int (*dummy (void)) [sizeof (struct {...})];
  107. * GCC warns about duplicate declarations of the dummy function if
  108. -Wredundant-decls is used. GCC 4.3 and later have a builtin
  109. __COUNTER__ macro that can let us generate unique identifiers for
  110. each dummy function, to suppress this warning.
  111. * This implementation exploits the fact that older versions of GCC,
  112. which do not support _Static_assert, also do not warn about the
  113. last declaration mentioned above.
  114. * GCC warns if -Wnested-externs is enabled and 'verify' is used
  115. within a function body; but inside a function, you can always
  116. arrange to use verify_expr instead.
  117. * In C++, any struct definition inside sizeof is invalid.
  118. Use a template type to work around the problem. */
  119. /* Concatenate two preprocessor tokens. */
  120. #define _GL_CONCAT(x, y) _GL_CONCAT0 (x, y)
  121. #define _GL_CONCAT0(x, y) x##y
  122. /* _GL_COUNTER is an integer, preferably one that changes each time we
  123. use it. Use __COUNTER__ if it works, falling back on __LINE__
  124. otherwise. __LINE__ isn't perfect, but it's better than a
  125. constant. */
  126. #if defined __COUNTER__ && __COUNTER__ != __COUNTER__
  127. # define _GL_COUNTER __COUNTER__
  128. #else
  129. # define _GL_COUNTER __LINE__
  130. #endif
  131. /* Generate a symbol with the given prefix, making it unique if
  132. possible. */
  133. #define _GL_GENSYM(prefix) _GL_CONCAT (prefix, _GL_COUNTER)
  134. /* Verify requirement R at compile-time, as an integer constant expression
  135. that returns 1. If R is false, fail at compile-time, preferably
  136. with a diagnostic that includes the string-literal DIAGNOSTIC. */
  137. #define _GL_VERIFY_TRUE(R, DIAGNOSTIC) \
  138. (!!sizeof (_GL_VERIFY_TYPE (R, DIAGNOSTIC)))
  139. #ifdef __cplusplus
  140. # if !GNULIB_defined_struct__gl_verify_type
  141. template <int w>
  142. struct _gl_verify_type {
  143. unsigned int _gl_verify_error_if_negative: w;
  144. };
  145. # define GNULIB_defined_struct__gl_verify_type 1
  146. # endif
  147. # define _GL_VERIFY_TYPE(R, DIAGNOSTIC) \
  148. _gl_verify_type<(R) ? 1 : -1>
  149. #elif defined _GL_HAVE__STATIC_ASSERT
  150. # define _GL_VERIFY_TYPE(R, DIAGNOSTIC) \
  151. struct { \
  152. _Static_assert (R, DIAGNOSTIC); \
  153. int _gl_dummy; \
  154. }
  155. #else
  156. # define _GL_VERIFY_TYPE(R, DIAGNOSTIC) \
  157. struct { unsigned int _gl_verify_error_if_negative: (R) ? 1 : -1; }
  158. #endif
  159. /* Verify requirement R at compile-time, as a declaration without a
  160. trailing ';'. If R is false, fail at compile-time.
  161. This macro requires three or more arguments but uses at most the first
  162. two, so that the _Static_assert macro optionally defined below supports
  163. both the C11 two-argument syntax and the C23 one-argument syntax.
  164. Unfortunately, unlike C11, this implementation must appear as an
  165. ordinary declaration, and cannot appear inside struct { ... }. */
  166. #if 202311 <= __STDC_VERSION__ || 200410 <= __cpp_static_assert
  167. # define _GL_VERIFY(R, DIAGNOSTIC, ...) static_assert (R, DIAGNOSTIC)
  168. #elif defined _GL_HAVE__STATIC_ASSERT
  169. # define _GL_VERIFY(R, DIAGNOSTIC, ...) _Static_assert (R, DIAGNOSTIC)
  170. #else
  171. # define _GL_VERIFY(R, DIAGNOSTIC, ...) \
  172. extern int (*_GL_GENSYM (_gl_verify_function) (void)) \
  173. [_GL_VERIFY_TRUE (R, DIAGNOSTIC)]
  174. # if 4 < __GNUC__ + (6 <= __GNUC_MINOR__)
  175. # pragma GCC diagnostic ignored "-Wnested-externs"
  176. # endif
  177. #endif
  178. /* _GL_STATIC_ASSERT_H is defined if this code is copied into assert.h. */
  179. #ifdef _GL_STATIC_ASSERT_H
  180. # if !defined _GL_HAVE__STATIC_ASSERT1 && !defined _Static_assert
  181. # if !defined _MSC_VER || defined __clang__
  182. # define _Static_assert(...) \
  183. _GL_VERIFY (__VA_ARGS__, "static assertion failed", -)
  184. # else
  185. /* Work around MSVC preprocessor incompatibility with ISO C; see
  186. <https://stackoverflow.com/questions/5134523/>. */
  187. # define _Static_assert(R, ...) \
  188. _GL_VERIFY ((R), "static assertion failed", -)
  189. # endif
  190. # endif
  191. # if (!defined static_assert \
  192. && __STDC_VERSION__ < 202311 \
  193. && (!defined __cplusplus \
  194. || (__cpp_static_assert < 201411 \
  195. && __GNUG__ < 6 && __clang_major__ < 6)))
  196. # if defined __cplusplus && _MSC_VER >= 1900 && !defined __clang__
  197. /* MSVC 14 in C++ mode supports the two-arguments static_assert but not
  198. the one-argument static_assert, and it does not support _Static_assert.
  199. We have to play preprocessor tricks to distinguish the two cases.
  200. Since the MSVC preprocessor is not ISO C compliant (see above),.
  201. the solution is specific to MSVC. */
  202. # define _GL_EXPAND(x) x
  203. # define _GL_SA1(a1) static_assert ((a1), "static assertion failed")
  204. # define _GL_SA2 static_assert
  205. # define _GL_SA3 static_assert
  206. # define _GL_SA_PICK(x1,x2,x3,x4,...) x4
  207. # define static_assert(...) _GL_EXPAND(_GL_SA_PICK(__VA_ARGS__,_GL_SA3,_GL_SA2,_GL_SA1)) (__VA_ARGS__)
  208. # else
  209. # define static_assert _Static_assert /* C11 requires this #define. */
  210. # endif
  211. # endif
  212. #endif
  213. /* @assert.h omit start@ */
  214. #if defined __clang_major__ && __clang_major__ < 5
  215. # define _GL_HAS_BUILTIN_TRAP 0
  216. #elif 3 < __GNUC__ + (3 < __GNUC_MINOR__ + (4 <= __GNUC_PATCHLEVEL__))
  217. # define _GL_HAS_BUILTIN_TRAP 1
  218. #elif defined __has_builtin
  219. # define _GL_HAS_BUILTIN_TRAP __has_builtin (__builtin_trap)
  220. #else
  221. # define _GL_HAS_BUILTIN_TRAP 0
  222. #endif
  223. #if defined __clang_major__ && __clang_major__ < 5
  224. # define _GL_HAS_BUILTIN_UNREACHABLE 0
  225. #elif 4 < __GNUC__ + (5 <= __GNUC_MINOR__)
  226. # define _GL_HAS_BUILTIN_UNREACHABLE 1
  227. #elif defined __has_builtin
  228. # define _GL_HAS_BUILTIN_UNREACHABLE __has_builtin (__builtin_unreachable)
  229. #else
  230. # define _GL_HAS_BUILTIN_UNREACHABLE 0
  231. #endif
  232. /* Each of these macros verifies that its argument R is nonzero. To
  233. be portable, R should be an integer constant expression. Unlike
  234. assert (R), there is no run-time overhead.
  235. There are two macros, since no single macro can be used in all
  236. contexts in C. verify_expr (R, E) is for scalar contexts, including
  237. integer constant expression contexts. verify (R) is for declaration
  238. contexts, e.g., the top level. */
  239. /* Verify requirement R at compile-time. Return the value of the
  240. expression E. */
  241. #define verify_expr(R, E) \
  242. (_GL_VERIFY_TRUE (R, "verify_expr (" #R ", " #E ")") ? (E) : (E))
  243. /* Verify requirement R at compile-time, as a declaration without a
  244. trailing ';'. verify (R) acts like static_assert (R) except that
  245. it is portable to C11/C++14 and earlier, it can issue better
  246. diagnostics, and its name is shorter and may be more convenient. */
  247. #ifdef __PGI
  248. /* PGI barfs if R is long. */
  249. # define verify(R) _GL_VERIFY (R, "verify (...)", -)
  250. #else
  251. # define verify(R) _GL_VERIFY (R, "verify (" #R ")", -)
  252. #endif
  253. /* Assume that R always holds. Behavior is undefined if R is false,
  254. fails to evaluate, or has side effects.
  255. 'assume (R)' is a directive from the programmer telling the
  256. compiler that R is true so the compiler needn't generate code to
  257. test R. This is why 'assume' is in verify.h: it's related to
  258. static checking (in this case, static checking done by the
  259. programmer), not dynamic checking.
  260. 'assume (R)' can affect compilation of all the code, not just code
  261. that happens to be executed after the assume (R) is "executed".
  262. For example, if the code mistakenly does 'assert (R); assume (R);'
  263. the compiler is entitled to optimize away the 'assert (R)'.
  264. Although assuming R can help a compiler generate better code or
  265. diagnostics, performance can suffer if R uses hard-to-optimize
  266. features such as function calls not inlined by the compiler.
  267. Avoid Clang's __builtin_assume, as it breaks GNU Emacs master
  268. as of 2020-08-23T21:09:49Z!eggert@cs.ucla.edu; see
  269. <https://bugs.gnu.org/43152#71>. It's not known whether this breakage
  270. is a Clang bug or an Emacs bug; play it safe for now. */
  271. #if _GL_HAS_BUILTIN_UNREACHABLE
  272. # define assume(R) ((R) ? (void) 0 : __builtin_unreachable ())
  273. #elif 1200 <= _MSC_VER
  274. # define assume(R) __assume (R)
  275. #elif 202311 <= __STDC_VERSION__
  276. # include <stddef.h>
  277. # define assume(R) ((R) ? (void) 0 : unreachable ())
  278. #elif (defined GCC_LINT || defined lint) && _GL_HAS_BUILTIN_TRAP
  279. /* Doing it this way helps various packages when configured with
  280. --enable-gcc-warnings, which compiles with -Dlint. It's nicer
  281. if 'assume' silences warnings with GCC 3.4 through GCC 4.4.7 (2012). */
  282. # define assume(R) ((R) ? (void) 0 : __builtin_trap ())
  283. #else
  284. /* Some older tools grok NOTREACHED, e.g., Oracle Studio 12.6 (2017). */
  285. # define assume(R) ((R) ? (void) 0 : /*NOTREACHED*/ (void) 0)
  286. #endif
  287. /* @assert.h omit end@ */
  288. #endif