]> git.ipfire.org Git - thirdparty/gcc.git/blob - gcc/doc/gcc/extensions-to-the-c-language-family/declaring-attributes-of-functions/common-function-attributes.rst
sphinx: add missing trailing newline
[thirdparty/gcc.git] / gcc / doc / gcc / extensions-to-the-c-language-family / declaring-attributes-of-functions / common-function-attributes.rst
1 ..
2 Copyright 1988-2022 Free Software Foundation, Inc.
3 This is part of the GCC manual.
4 For copying conditions, see the copyright.rst file.
5
6 .. _common-function-attributes:
7
8 Common Function Attributes
9 ^^^^^^^^^^^^^^^^^^^^^^^^^^
10
11 The following attributes are supported on most targets.
12
13 .. Keep this table alphabetized by attribute name. Treat _ as space.
14
15 .. fn-attr:: access (access-mode, ref-index), access (access-mode, ref-index, size-index)
16
17 The :fn-attr:`access` attribute enables the detection of invalid or unsafe
18 accesses by functions to which they apply or their callers, as well as
19 write-only accesses to objects that are never read from. Such accesses
20 may be diagnosed by warnings such as :option:`-Wstringop-overflow`,
21 :option:`-Wuninitialized`, :option:`-Wunused`, and others.
22
23 The :fn-attr:`access` attribute specifies that a function to whose by-reference
24 arguments the attribute applies accesses the referenced object according to
25 :samp:`{access-mode}`. The :samp:`{access-mode}` argument is required and must be
26 one of four names: ``read_only``, ``read_write``, ``write_only``,
27 or ``none``. The remaining two are positional arguments.
28
29 The required :samp:`{ref-index}` positional argument denotes a function
30 argument of pointer (or in C++, reference) type that is subject to
31 the access. The same pointer argument can be referenced by at most one
32 distinct :fn-attr:`access` attribute.
33
34 The optional :samp:`{size-index}` positional argument denotes a function
35 argument of integer type that specifies the maximum size of the access.
36 The size is the number of elements of the type referenced by :samp:`{ref-index}`,
37 or the number of bytes when the pointer type is ``void*``. When no
38 :samp:`{size-index}` argument is specified, the pointer argument must be either
39 null or point to a space that is suitably aligned and large for at least one
40 object of the referenced type (this implies that a past-the-end pointer is
41 not a valid argument). The actual size of the access may be less but it
42 must not be more.
43
44 The ``read_only`` access mode specifies that the pointer to which it
45 applies is used to read the referenced object but not write to it. Unless
46 the argument specifying the size of the access denoted by :samp:`{size-index}`
47 is zero, the referenced object must be initialized. The mode implies
48 a stronger guarantee than the ``const`` qualifier which, when cast away
49 from a pointer, does not prevent the pointed-to object from being modified.
50 Examples of the use of the ``read_only`` access mode is the argument to
51 the ``puts`` function, or the second and third arguments to
52 the ``memcpy`` function.
53
54 .. code-block:: c++
55
56 __attribute__ ((access (read_only, 1))) int puts (const char*);
57 __attribute__ ((access (read_only, 2, 3))) void* memcpy (void*, const void*, size_t);
58
59 The ``read_write`` access mode applies to arguments of pointer types
60 without the ``const`` qualifier. It specifies that the pointer to which
61 it applies is used to both read and write the referenced object. Unless
62 the argument specifying the size of the access denoted by :samp:`{size-index}`
63 is zero, the object referenced by the pointer must be initialized. An example
64 of the use of the ``read_write`` access mode is the first argument to
65 the ``strcat`` function.
66
67 .. code-block:: c++
68
69 __attribute__ ((access (read_write, 1), access (read_only, 2))) char* strcat (char*, const char*);
70
71 The ``write_only`` access mode applies to arguments of pointer types
72 without the ``const`` qualifier. It specifies that the pointer to which
73 it applies is used to write to the referenced object but not read from it.
74 The object referenced by the pointer need not be initialized. An example
75 of the use of the ``write_only`` access mode is the first argument to
76 the ``strcpy`` function, or the first two arguments to the ``fgets``
77 function.
78
79 .. code-block:: c++
80
81 __attribute__ ((access (write_only, 1), access (read_only, 2))) char* strcpy (char*, const char*);
82 __attribute__ ((access (write_only, 1, 2), access (read_write, 3))) int fgets (char*, int, FILE*);
83
84 The access mode ``none`` specifies that the pointer to which it applies
85 is not used to access the referenced object at all. Unless the pointer is
86 null the pointed-to object must exist and have at least the size as denoted
87 by the :samp:`{size-index}` argument. When the optional :samp:`{size-index}`
88 argument is omitted for an argument of ``void*`` type the actual pointer
89 agument is ignored. The referenced object need not be initialized.
90 The mode is intended to be used as a means to help validate the expected
91 object size, for example in functions that call ``__builtin_object_size``.
92 See :ref:`object-size-checking`.
93
94 Note that the ``access`` attribute merely specifies how an object
95 referenced by the pointer argument can be accessed; it does not imply that
96 an access **will** happen. Also, the ``access`` attribute does not
97 imply the attribute :fn-attr:`nonnull` ; it may be appropriate to add both attributes
98 at the declaration of a function that unconditionally manipulates a buffer via
99 a pointer argument. See the :fn-attr:`nonnull` attribute for more information and
100 caveats.
101
102 .. index:: alias function attribute
103
104 .. fn-attr:: alias ("target")
105
106 The ``alias`` attribute causes the declaration to be emitted as an alias
107 for another symbol, which must have been previously declared with the same
108 type, and for variables, also the same size and alignment. Declaring an alias
109 with a different type than the target is undefined and may be diagnosed. As
110 an example, the following declarations:
111
112 .. code-block:: c++
113
114 void __f () { /* Do something. */; }
115 void f () __attribute__ ((weak, alias ("__f")));
116
117 define :samp:`f` to be a weak alias for :samp:`__f`. In C++, the mangled name
118 for the target must be used. It is an error if :samp:`__f` is not defined in
119 the same translation unit.
120
121 This attribute requires assembler and object file support,
122 and may not be available on all targets.
123
124 .. index:: aligned function attribute
125
126 .. fn-attr:: aligned, aligned (alignment)
127
128 The :fn-attr:`aligned` attribute specifies a minimum alignment for
129 the first instruction of the function, measured in bytes. When specified,
130 :samp:`{alignment}` must be an integer constant power of 2. Specifying no
131 :samp:`{alignment}` argument implies the ideal alignment for the target.
132 The ``__alignof__`` operator can be used to determine what that is
133 (see :ref:`alignment`). The attribute has no effect when a definition for
134 the function is not provided in the same translation unit.
135
136 The attribute cannot be used to decrease the alignment of a function
137 previously declared with a more restrictive alignment; only to increase
138 it. Attempts to do otherwise are diagnosed. Some targets specify
139 a minimum default alignment for functions that is greater than 1. On
140 such targets, specifying a less restrictive alignment is silently ignored.
141 Using the attribute overrides the effect of the :option:`-falign-functions`
142 (see :ref:`optimize-options`) option for this function.
143
144 Note that the effectiveness of :fn-attr:`aligned` attributes may be
145 limited by inherent limitations in the system linker
146 and/or object file format. On some systems, the
147 linker is only able to arrange for functions to be aligned up to a
148 certain maximum alignment. (For some linkers, the maximum supported
149 alignment may be very very small.) See your linker documentation for
150 further information.
151
152 The :fn-attr:`aligned` attribute can also be used for variables and fields
153 (see :ref:`variable-attributes`.)
154
155 .. index:: alloc_align function attribute
156
157 .. fn-attr:: alloc_align (position)
158
159 The ``alloc_align`` attribute may be applied to a function that
160 returns a pointer and takes at least one argument of an integer or
161 enumerated type.
162 It indicates that the returned pointer is aligned on a boundary given
163 by the function argument at :samp:`{position}`. Meaningful alignments are
164 powers of 2 greater than one. GCC uses this information to improve
165 pointer alignment analysis.
166
167 The function parameter denoting the allocated alignment is specified by
168 one constant integer argument whose number is the argument of the attribute.
169 Argument numbering starts at one.
170
171 For instance,
172
173 .. code-block:: c++
174
175 void* my_memalign (size_t, size_t) __attribute__ ((alloc_align (1)));
176
177 declares that ``my_memalign`` returns memory with minimum alignment
178 given by parameter 1.
179
180 .. index:: alloc_size function attribute
181
182 .. fn-attr:: alloc_size (position), alloc_size (position-1, position-2)
183
184 The ``alloc_size`` attribute may be applied to a function that
185 returns a pointer and takes at least one argument of an integer or
186 enumerated type.
187 It indicates that the returned pointer points to memory whose size is
188 given by the function argument at :samp:`{position-1}`, or by the product
189 of the arguments at :samp:`{position-1}` and :samp:`{position-2}`. Meaningful
190 sizes are positive values less than ``PTRDIFF_MAX``. GCC uses this
191 information to improve the results of ``__builtin_object_size``.
192
193 The function parameter(s) denoting the allocated size are specified by
194 one or two integer arguments supplied to the attribute. The allocated size
195 is either the value of the single function argument specified or the product
196 of the two function arguments specified. Argument numbering starts at
197 one for ordinary functions, and at two for C++ non-static member functions.
198
199 For instance,
200
201 .. code-block:: c++
202
203 void* my_calloc (size_t, size_t) __attribute__ ((alloc_size (1, 2)));
204 void* my_realloc (void*, size_t) __attribute__ ((alloc_size (2)));
205
206 declares that ``my_calloc`` returns memory of the size given by
207 the product of parameter 1 and 2 and that ``my_realloc`` returns memory
208 of the size given by parameter 2.
209
210 .. index:: always_inline function attribute
211
212 .. fn-attr:: always_inline
213
214 Generally, functions are not inlined unless optimization is specified.
215 For functions declared inline, this attribute inlines the function
216 independent of any restrictions that otherwise apply to inlining.
217 Failure to inline such a function is diagnosed as an error.
218 Note that if such a function is called indirectly the compiler may
219 or may not inline it depending on optimization level and a failure
220 to inline an indirect call may or may not be diagnosed.
221
222 .. index:: artificial function attribute
223
224 .. fn-attr:: artificial
225
226 This attribute is useful for small inline wrappers that if possible
227 should appear during debugging as a unit. Depending on the debug
228 info format it either means marking the function as artificial
229 or using the caller location for all instructions within the inlined
230 body.
231
232 .. index:: assume_aligned function attribute
233
234 .. fn-attr:: assume_aligned (alignment), assume_aligned (alignment, offset)
235
236 The ``assume_aligned`` attribute may be applied to a function that
237 returns a pointer. It indicates that the returned pointer is aligned
238 on a boundary given by :samp:`{alignment}`. If the attribute has two
239 arguments, the second argument is misalignment :samp:`{offset}`. Meaningful
240 values of :samp:`{alignment}` are powers of 2 greater than one. Meaningful
241 values of :samp:`{offset}` are greater than zero and less than :samp:`{alignment}`.
242
243 For instance
244
245 .. code-block:: c++
246
247 void* my_alloc1 (size_t) __attribute__((assume_aligned (16)));
248 void* my_alloc2 (size_t) __attribute__((assume_aligned (32, 8)));
249
250 declares that ``my_alloc1`` returns 16-byte aligned pointers and
251 that ``my_alloc2`` returns a pointer whose value modulo 32 is equal
252 to 8.
253
254 .. index:: cold function attribute
255
256 .. fn-attr:: cold
257
258 The :fn-attr:`cold` attribute on functions is used to inform the compiler that
259 the function is unlikely to be executed. The function is optimized for
260 size rather than speed and on many targets it is placed into a special
261 subsection of the text section so all cold functions appear close together,
262 improving code locality of non-cold parts of program. The paths leading
263 to calls of cold functions within code are marked as unlikely by the branch
264 prediction mechanism. It is thus useful to mark functions used to handle
265 unlikely conditions, such as ``perror``, as cold to improve optimization
266 of hot functions that do call marked functions in rare occasions.
267
268 When profile feedback is available, via :option:`-fprofile-use`, cold functions
269 are automatically detected and this attribute is ignored.
270
271 .. index:: const function attribute, functions that have no side effects
272
273 .. fn-attr:: const
274
275 Calls to functions whose return value is not affected by changes to
276 the observable state of the program and that have no observable effects
277 on such state other than to return a value may lend themselves to
278 optimizations such as common subexpression elimination. Declaring such
279 functions with the :option:`const` attribute allows GCC to avoid emitting
280 some calls in repeated invocations of the function with the same argument
281 values.
282
283 For example,
284
285 .. code-block:: c++
286
287 int square (int) __attribute__ ((const));
288
289 tells GCC that subsequent calls to function ``square`` with the same
290 argument value can be replaced by the result of the first call regardless
291 of the statements in between.
292
293 The :option:`const` attribute prohibits a function from reading objects
294 that affect its return value between successive invocations. However,
295 functions declared with the attribute can safely read objects that do
296 not change their return value, such as non-volatile constants.
297
298 The :fn-attr:`const` attribute imposes greater restrictions on a function's
299 definition than the similar :fn-attr:`pure` attribute. Declaring the same
300 function with both the :fn-attr:`const` and the :fn-attr:`pure` attribute is
301 diagnosed. Because a const function cannot have any observable side
302 effects it does not make sense for it to return ``void``. Declaring
303 such a function is diagnosed.
304
305 .. index:: pointer arguments
306
307 Note that a function that has pointer arguments and examines the data
308 pointed to must *not* be declared :option:`const` if the pointed-to
309 data might change between successive invocations of the function. In
310 general, since a function cannot distinguish data that might change
311 from data that cannot, const functions should never take pointer or,
312 in C++, reference arguments. Likewise, a function that calls a non-const
313 function usually must not be const itself.
314
315 .. index:: constructor function attribute, destructor function attribute
316
317 .. fn-attr:: constructor, destructor, constructor (priority), destructor (priority)
318
319 The :fn-attr:`constructor` attribute causes the function to be called
320 automatically before execution enters ``main ()``. Similarly, the
321 ``destructor`` attribute causes the function to be called
322 automatically after ``main ()`` completes or ``exit ()`` is
323 called. Functions with these attributes are useful for
324 initializing data that is used implicitly during the execution of
325 the program.
326
327 On some targets the attributes also accept an integer argument to
328 specify a priority to control the order in which constructor and
329 destructor functions are run. A constructor
330 with a smaller priority number runs before a constructor with a larger
331 priority number; the opposite relationship holds for destructors. Note
332 that priorities 0-100 are reserved. So, if you have a constructor that
333 allocates a resource and a destructor that deallocates the same
334 resource, both functions typically have the same priority. The
335 priorities for constructor and destructor functions are the same as
336 those specified for namespace-scope C++ objects (see :ref:`c++-attributes`).
337 However, at present, the order in which constructors for C++ objects
338 with static storage duration and functions decorated with attribute
339 :fn-attr:`constructor` are invoked is unspecified. In mixed declarations,
340 attribute ``init_priority`` can be used to impose a specific ordering.
341
342 Using the argument forms of the :fn-attr:`constructor` and ``destructor``
343 attributes on targets where the feature is not supported is rejected with
344 an error.
345
346 .. index:: copy function attribute
347
348 .. fn-attr:: copy, copy (function)
349
350 The :fn-attr:`copy` attribute applies the set of attributes with which
351 :samp:`{function}` has been declared to the declaration of the function
352 to which the attribute is applied. The attribute is designed for
353 libraries that define aliases or function resolvers that are expected
354 to specify the same set of attributes as their targets. The :fn-attr:`copy`
355 attribute can be used with functions, variables, or types. However,
356 the kind of symbol to which the attribute is applied (either function
357 or variable) must match the kind of symbol to which the argument refers.
358 The :fn-attr:`copy` attribute copies only syntactic and semantic attributes
359 but not attributes that affect a symbol's linkage or visibility such as
360 ``alias``, :fn-attr:`visibility`, or :fn-attr:`weak`. The :fn-attr:`deprecated`
361 and ``target_clones`` attribute are also not copied.
362 See :ref:`common-type-attributes`.
363 See :ref:`common-variable-attributes`.
364
365 For example, the :samp:`{StrongAlias}` macro below makes use of the ``alias``
366 and :fn-attr:`copy` attributes to define an alias named :samp:`{alloc}` for function
367 :samp:`{allocate}` declared with attributes :samp:`{alloc_size}`, :samp:`{malloc}`, and
368 :samp:`{nothrow}`. Thanks to the ``__typeof__`` operator the alias has
369 the same type as the target function. As a result of the :fn-attr:`copy`
370 attribute the alias also shares the same attributes as the target.
371
372 .. code-block:: c++
373
374 #define StrongAlias(TargetFunc, AliasDecl) \
375 extern __typeof__ (TargetFunc) AliasDecl \
376 __attribute__ ((alias (#TargetFunc), copy (TargetFunc)));
377
378 extern __attribute__ ((alloc_size (1), malloc, nothrow))
379 void* allocate (size_t);
380 StrongAlias (allocate, alloc);
381
382 .. index:: deprecated function attribute
383
384 .. fn-attr:: deprecated, deprecated (msg)
385
386 The :fn-attr:`deprecated` attribute results in a warning if the function
387 is used anywhere in the source file. This is useful when identifying
388 functions that are expected to be removed in a future version of a
389 program. The warning also includes the location of the declaration
390 of the deprecated function, to enable users to easily find further
391 information about why the function is deprecated, or what they should
392 do instead. Note that the warnings only occurs for uses:
393
394 .. code-block:: c++
395
396 int old_fn () __attribute__ ((deprecated));
397 int old_fn ();
398 int (*fn_ptr)() = old_fn;
399
400 results in a warning on line 3 but not line 2. The optional :samp:`{msg}`
401 argument, which must be a string, is printed in the warning if
402 present.
403
404 The :fn-attr:`deprecated` attribute can also be used for variables and
405 types (see :ref:`variable-attributes`, see :ref:`type-attributes`.)
406
407 The message attached to the attribute is affected by the setting of
408 the :option:`-fmessage-length` option.
409
410 .. index:: unavailable function attribute
411
412 .. fn-attr:: unavailable, unavailable (msg)
413
414 The :fn-attr:`unavailable` attribute results in an error if the function
415 is used anywhere in the source file. This is useful when identifying
416 functions that have been removed from a particular variation of an
417 interface. Other than emitting an error rather than a warning, the
418 :fn-attr:`unavailable` attribute behaves in the same manner as
419 :fn-attr:`deprecated`.
420
421 The :fn-attr:`unavailable` attribute can also be used for variables and
422 types (see :ref:`variable-attributes`, see :ref:`type-attributes`.)
423
424 .. index:: error function attribute, warning function attribute
425
426 .. fn-attr:: error ("message"), warning ("message")
427
428 If the ``error`` or ``warning`` attribute
429 is used on a function declaration and a call to such a function
430 is not eliminated through dead code elimination or other optimizations,
431 an error or warning (respectively) that includes :samp:`{message}` is diagnosed.
432 This is useful
433 for compile-time checking, especially together with ``__builtin_constant_p``
434 and inline functions where checking the inline function arguments is not
435 possible through ``extern char [(condition) ? 1 : -1];`` tricks.
436
437 While it is possible to leave the function undefined and thus invoke
438 a link failure (to define the function with
439 a message in ``.gnu.warning*`` section),
440 when using these attributes the problem is diagnosed
441 earlier and with exact location of the call even in presence of inline
442 functions or when not emitting debugging information.
443
444 .. index:: externally_visible function attribute
445
446 .. fn-attr:: externally_visible
447
448 This attribute, attached to a global variable or function, nullifies
449 the effect of the :option:`-fwhole-program` command-line option, so the
450 object remains visible outside the current compilation unit.
451
452 If :option:`-fwhole-program` is used together with :option:`-flto` and
453 :command:`gold` is used as the linker plugin,
454 :fn-attr:`externally_visible` attributes are automatically added to functions
455 (not variable yet due to a current :command:`gold` issue)
456 that are accessed outside of LTO objects according to resolution file
457 produced by :command:`gold`.
458 For other linkers that cannot generate resolution file,
459 explicit :fn-attr:`externally_visible` attributes are still necessary.
460
461 .. index:: fd_arg function attribute
462
463 .. fn-attr:: fd_arg, fd_arg (N)
464
465 The :fn-attr:`fd_arg` attribute may be applied to a function that takes an open
466 file descriptor at referenced argument :samp:`{N}`.
467
468 It indicates that the passed filedescriptor must not have been closed.
469 Therefore, when the analyzer is enabled with :option:`-fanalyzer`, the
470 analyzer may emit a :option:`-Wanalyzer-fd-use-after-close` diagnostic
471 if it detects a code path in which a function with this attribute is
472 called with a closed file descriptor.
473
474 The attribute also indicates that the file descriptor must have been checked for
475 validity before usage. Therefore, analyzer may emit
476 :option:`-Wanalyzer-fd-use-without-check` diagnostic if it detects a code path in
477 which a function with this attribute is called with a file descriptor that has
478 not been checked for validity.
479
480 .. index:: fd_arg_read function attribute
481
482 .. fn-attr:: fd_arg_read, fd_arg_read (N)
483
484 The :fn-attr:`fd_arg_read` is identical to :fn-attr:`fd_arg`, but with the additional
485 requirement that it might read from the file descriptor, and thus, the file
486 descriptor must not have been opened as write-only.
487
488 The analyzer may emit a :option:`-Wanalyzer-access-mode-mismatch`
489 diagnostic if it detects a code path in which a function with this
490 attribute is called on a file descriptor opened with ``O_WRONLY``.
491
492 .. index:: fd_arg_write function attribute
493
494 .. fn-attr:: fd_arg_write, fd_arg_write (N)
495
496 The :fn-attr:`fd_arg_write` is identical to :fn-attr:`fd_arg_read` except that the
497 analyzer may emit a :option:`-Wanalyzer-access-mode-mismatch` diagnostic if
498 it detects a code path in which a function with this attribute is called on a
499 file descriptor opened with ``O_RDONLY``.
500
501 .. index:: flatten function attribute
502
503 .. fn-attr:: flatten
504
505 Generally, inlining into a function is limited. For a function marked with
506 this attribute, every call inside this function is inlined, if possible.
507 Functions declared with attribute :fn-attr:`noinline` and similar are not
508 inlined. Whether the function itself is considered for inlining depends
509 on its size and the current inlining parameters.
510
511 .. index:: format function attribute, functions with printf, scanf, strftime or strfmon style arguments
512
513 .. option:: format (archetype, string-index, first-to-check)
514
515 The ``format`` attribute specifies that a function takes ``printf``,
516 ``scanf``, ``strftime`` or ``strfmon`` style arguments that
517 should be type-checked against a format string. For example, the
518 declaration:
519
520 .. code-block:: c++
521
522 extern int
523 my_printf (void *my_object, const char *my_format, ...)
524 __attribute__ ((format (printf, 2, 3)));
525
526 causes the compiler to check the arguments in calls to ``my_printf``
527 for consistency with the ``printf`` style format string argument
528 ``my_format``.
529
530 The parameter :samp:`{archetype}` determines how the format string is
531 interpreted, and should be ``printf``, ``scanf``, ``strftime``,
532 ``gnu_printf``, ``gnu_scanf``, ``gnu_strftime`` or
533 ``strfmon``. (You can also use ``__printf__``,
534 ``__scanf__``, ``__strftime__`` or ``__strfmon__``.) On
535 MinGW targets, ``ms_printf``, ``ms_scanf``, and
536 ``ms_strftime`` are also present.
537 :samp:`{archetype}` values such as ``printf`` refer to the formats accepted
538 by the system's C runtime library,
539 while values prefixed with :samp:`gnu_` always refer
540 to the formats accepted by the GNU C Library. On Microsoft Windows
541 targets, values prefixed with :samp:`ms_` refer to the formats accepted by the
542 :samp:`msvcrt.dll` library.
543 The parameter :samp:`{string-index}`
544 specifies which argument is the format string argument (starting
545 from 1), while :samp:`{first-to-check}` is the number of the first
546 argument to check against the format string. For functions
547 where the arguments are not available to be checked (such as
548 ``vprintf``), specify the third parameter as zero. In this case the
549 compiler only checks the format string for consistency. For
550 ``strftime`` formats, the third parameter is required to be zero.
551 Since non-static C++ methods have an implicit ``this`` argument, the
552 arguments of such methods should be counted from two, not one, when
553 giving values for :samp:`{string-index}` and :samp:`{first-to-check}`.
554
555 In the example above, the format string (``my_format``) is the second
556 argument of the function ``my_print``, and the arguments to check
557 start with the third argument, so the correct parameters for the format
558 attribute are 2 and 3.
559
560 The ``format`` attribute allows you to identify your own functions
561 that take format strings as arguments, so that GCC can check the
562 calls to these functions for errors. The compiler always (unless
563 :option:`-ffreestanding` or :option:`-fno-builtin` is used) checks formats
564 for the standard library functions ``printf``, ``fprintf``,
565 ``sprintf``, ``scanf``, ``fscanf``, ``sscanf``, ``strftime``,
566 ``vprintf``, ``vfprintf`` and ``vsprintf`` whenever such
567 warnings are requested (using :option:`-Wformat`), so there is no need to
568 modify the header file :samp:`stdio.h`. In C99 mode, the functions
569 ``snprintf``, ``vsnprintf``, ``vscanf``, ``vfscanf`` and
570 ``vsscanf`` are also checked. Except in strictly conforming C
571 standard modes, the X/Open function ``strfmon`` is also checked as
572 are ``printf_unlocked`` and ``fprintf_unlocked``.
573 See :ref:`c-dialect-options`.
574
575 For Objective-C dialects, ``NSString`` (or ``__NSString__``) is
576 recognized in the same context. Declarations including these format attributes
577 are parsed for correct syntax, however the result of checking of such format
578 strings is not yet defined, and is not carried out by this version of the
579 compiler.
580
581 The target may also provide additional types of format checks.
582 See :ref:`target-format-checks`.
583
584 .. index:: format_arg function attribute
585
586 .. option:: format_arg (string-index)
587
588 The ``format_arg`` attribute specifies that a function takes one or
589 more format strings for a ``printf``, ``scanf``, ``strftime`` or
590 ``strfmon`` style function and modifies it (for example, to translate
591 it into another language), so the result can be passed to a
592 ``printf``, ``scanf``, ``strftime`` or ``strfmon`` style
593 function (with the remaining arguments to the format function the same
594 as they would have been for the unmodified string). Multiple
595 ``format_arg`` attributes may be applied to the same function, each
596 designating a distinct parameter as a format string. For example, the
597 declaration:
598
599 .. code-block:: c++
600
601 extern char *
602 my_dgettext (char *my_domain, const char *my_format)
603 __attribute__ ((format_arg (2)));
604
605 causes the compiler to check the arguments in calls to a ``printf``,
606 ``scanf``, ``strftime`` or ``strfmon`` type function, whose
607 format string argument is a call to the ``my_dgettext`` function, for
608 consistency with the format string argument ``my_format``. If the
609 ``format_arg`` attribute had not been specified, all the compiler
610 could tell in such calls to format functions would be that the format
611 string argument is not constant; this would generate a warning when
612 :option:`-Wformat-nonliteral` is used, but the calls could not be checked
613 without the attribute.
614
615 In calls to a function declared with more than one ``format_arg``
616 attribute, each with a distinct argument value, the corresponding
617 actual function arguments are checked against all format strings
618 designated by the attributes. This capability is designed to support
619 the GNU ``ngettext`` family of functions.
620
621 The parameter :samp:`{string-index}` specifies which argument is the format
622 string argument (starting from one). Since non-static C++ methods have
623 an implicit ``this`` argument, the arguments of such methods should
624 be counted from two.
625
626 The ``format_arg`` attribute allows you to identify your own
627 functions that modify format strings, so that GCC can check the
628 calls to ``printf``, ``scanf``, ``strftime`` or ``strfmon``
629 type function whose operands are a call to one of your own function.
630 The compiler always treats ``gettext``, ``dgettext``, and
631 ``dcgettext`` in this manner except when strict ISO C support is
632 requested by :option:`-ansi` or an appropriate :option:`-std` option, or
633 :option:`-ffreestanding` or :option:`-fno-builtin`
634 is used. See :ref:`c-dialect-options`.
635
636 For Objective-C dialects, the ``format-arg`` attribute may refer to an
637 ``NSString`` reference for compatibility with the ``format`` attribute
638 above.
639
640 The target may also allow additional types in ``format-arg`` attributes.
641 See :ref:`target-format-checks`.
642
643 .. index:: gnu_inline function attribute
644
645 .. fn-attr:: gnu_inline
646
647 This attribute should be used with a function that is also declared
648 with the ``inline`` keyword. It directs GCC to treat the function
649 as if it were defined in gnu90 mode even when compiling in C99 or
650 gnu99 mode.
651
652 If the function is declared ``extern``, then this definition of the
653 function is used only for inlining. In no case is the function
654 compiled as a standalone function, not even if you take its address
655 explicitly. Such an address becomes an external reference, as if you
656 had only declared the function, and had not defined it. This has
657 almost the effect of a macro. The way to use this is to put a
658 function definition in a header file with this attribute, and put
659 another copy of the function, without ``extern``, in a library
660 file. The definition in the header file causes most calls to the
661 function to be inlined. If any uses of the function remain, they
662 refer to the single copy in the library. Note that the two
663 definitions of the functions need not be precisely the same, although
664 if they do not have the same effect your program may behave oddly.
665
666 In C, if the function is neither ``extern`` nor ``static``, then
667 the function is compiled as a standalone function, as well as being
668 inlined where possible.
669
670 This is how GCC traditionally handled functions declared
671 ``inline``. Since ISO C99 specifies a different semantics for
672 ``inline``, this function attribute is provided as a transition
673 measure and as a useful feature in its own right. This attribute is
674 available in GCC 4.1.3 and later. It is available if either of the
675 preprocessor macros ``__GNUC_GNU_INLINE__`` or
676 ``__GNUC_STDC_INLINE__`` are defined. See :ref:`inline`.
677
678 In C++, this attribute does not depend on ``extern`` in any way,
679 but it still requires the ``inline`` keyword to enable its special
680 behavior.
681
682 .. index:: hot function attribute
683
684 .. fn-attr:: hot
685
686 The :fn-attr:`hot` attribute on a function is used to inform the compiler that
687 the function is a hot spot of the compiled program. The function is
688 optimized more aggressively and on many targets it is placed into a special
689 subsection of the text section so all hot functions appear close together,
690 improving locality.
691
692 When profile feedback is available, via :option:`-fprofile-use`, hot functions
693 are automatically detected and this attribute is ignored.
694
695 .. index:: ifunc function attribute, indirect functions, functions that are dynamically resolved
696
697 .. fn-attr:: ifunc ("resolver")
698
699 The ``ifunc`` attribute is used to mark a function as an indirect
700 function using the STT_GNU_IFUNC symbol type extension to the ELF
701 standard. This allows the resolution of the symbol value to be
702 determined dynamically at load time, and an optimized version of the
703 routine to be selected for the particular processor or other system
704 characteristics determined then. To use this attribute, first define
705 the implementation functions available, and a resolver function that
706 returns a pointer to the selected implementation function. The
707 implementation functions' declarations must match the API of the
708 function being implemented. The resolver should be declared to
709 be a function taking no arguments and returning a pointer to
710 a function of the same type as the implementation. For example:
711
712 .. code-block:: c++
713
714 void *my_memcpy (void *dst, const void *src, size_t len)
715 {
716 ...
717 return dst;
718 }
719
720 static void * (*resolve_memcpy (void))(void *, const void *, size_t)
721 {
722 return my_memcpy; // we will just always select this routine
723 }
724
725 The exported header file declaring the function the user calls would
726 contain:
727
728 .. code-block:: c++
729
730 extern void *memcpy (void *, const void *, size_t);
731
732 allowing the user to call ``memcpy`` as a regular function, unaware of
733 the actual implementation. Finally, the indirect function needs to be
734 defined in the same translation unit as the resolver function:
735
736 .. code-block:: c++
737
738 void *memcpy (void *, const void *, size_t)
739 __attribute__ ((ifunc ("resolve_memcpy")));
740
741 In C++, the ``ifunc`` attribute takes a string that is the mangled name
742 of the resolver function. A C++ resolver for a non-static member function
743 of class ``C`` should be declared to return a pointer to a non-member
744 function taking pointer to ``C`` as the first argument, followed by
745 the same arguments as of the implementation function. G++ checks
746 the signatures of the two functions and issues
747 a :option:`-Wattribute-alias` warning for mismatches. To suppress a warning
748 for the necessary cast from a pointer to the implementation member function
749 to the type of the corresponding non-member function use
750 the :option:`-Wno-pmf-conversions` option. For example:
751
752 .. code-block:: c++
753
754 class S
755 {
756 private:
757 int debug_impl (int);
758 int optimized_impl (int);
759
760 typedef int Func (S*, int);
761
762 static Func* resolver ();
763 public:
764
765 int interface (int);
766 };
767
768 int S::debug_impl (int) { /* ... */ }
769 int S::optimized_impl (int) { /* ... */ }
770
771 S::Func* S::resolver ()
772 {
773 int (S::*pimpl) (int)
774 = getenv ("DEBUG") ? &S::debug_impl : &S::optimized_impl;
775
776 // Cast triggers -Wno-pmf-conversions.
777 return reinterpret_cast<Func*>(pimpl);
778 }
779
780 int S::interface (int) __attribute__ ((ifunc ("_ZN1S8resolverEv")));
781
782 Indirect functions cannot be weak. Binutils version 2.20.1 or higher
783 and GNU C Library version 2.11.1 are required to use this feature.
784
785 .. fn-attr:: interrupt, interrupt_handler
786
787 Many GCC back ends support attributes to indicate that a function is
788 an interrupt handler, which tells the compiler to generate function
789 entry and exit sequences that differ from those from regular
790 functions. The exact syntax and behavior are target-specific;
791 refer to the following subsections for details.
792
793 .. index:: leaf function attribute
794
795 .. fn-attr:: leaf
796
797 Calls to external functions with this attribute must return to the
798 current compilation unit only by return or by exception handling. In
799 particular, a leaf function is not allowed to invoke callback functions
800 passed to it from the current compilation unit, directly call functions
801 exported by the unit, or ``longjmp`` into the unit. Leaf functions
802 might still call functions from other compilation units and thus they
803 are not necessarily leaf in the sense that they contain no function
804 calls at all.
805
806 The attribute is intended for library functions to improve dataflow
807 analysis. The compiler takes the hint that any data not escaping the
808 current compilation unit cannot be used or modified by the leaf
809 function. For example, the ``sin`` function is a leaf function, but
810 ``qsort`` is not.
811
812 Note that leaf functions might indirectly run a signal handler defined
813 in the current compilation unit that uses static variables. Similarly,
814 when lazy symbol resolution is in effect, leaf functions might invoke
815 indirect functions whose resolver function or implementation function is
816 defined in the current compilation unit and uses static variables. There
817 is no standard-compliant way to write such a signal handler, resolver
818 function, or implementation function, and the best that you can do is to
819 remove the :fn-attr:`leaf` attribute or mark all such static variables
820 ``volatile``. Lastly, for ELF-based systems that support symbol
821 interposition, care should be taken that functions defined in the
822 current compilation unit do not unexpectedly interpose other symbols
823 based on the defined standards mode and defined feature test macros;
824 otherwise an inadvertent callback would be added.
825
826 The attribute has no effect on functions defined within the current
827 compilation unit. This is to allow easy merging of multiple compilation
828 units into one, for example, by using the link-time optimization. For
829 this reason the attribute is not allowed on types to annotate indirect
830 calls.
831
832 .. index:: malloc function attribute, functions that behave like malloc
833
834 .. fn-attr:: malloc, malloc (deallocator), malloc (deallocator, ptr-index)
835
836 Attribute ``malloc`` indicates that a function is ``malloc`` -like,
837 i.e., that the pointer :samp:`{P}` returned by the function cannot alias any
838 other pointer valid when the function returns, and moreover no
839 pointers to valid objects occur in any storage addressed by :samp:`{P}`. In
840 addition, the GCC predicts that a function with the attribute returns
841 non-null in most cases.
842
843 Independently, the form of the attribute with one or two arguments
844 associates ``deallocator`` as a suitable deallocation function for
845 pointers returned from the ``malloc`` -like function. :samp:`{ptr-index}`
846 denotes the positional argument to which when the pointer is passed in
847 calls to ``deallocator`` has the effect of deallocating it.
848
849 Using the attribute with no arguments is designed to improve optimization
850 by relying on the aliasing property it implies. Functions like ``malloc``
851 and ``calloc`` have this property because they return a pointer to
852 uninitialized or zeroed-out, newly obtained storage. However, functions
853 like ``realloc`` do not have this property, as they may return pointers
854 to storage containing pointers to existing objects. Additionally, since
855 all such functions are assumed to return null only infrequently, callers
856 can be optimized based on that assumption.
857
858 Associating a function with a :samp:`{deallocator}` helps detect calls to
859 mismatched allocation and deallocation functions and diagnose them under
860 the control of options such as :option:`-Wmismatched-dealloc`. It also
861 makes it possible to diagnose attempts to deallocate objects that were not
862 allocated dynamically, by :option:`-Wfree-nonheap-object`. To indicate
863 that an allocation function both satisifies the nonaliasing property and
864 has a deallocator associated with it, both the plain form of the attribute
865 and the one with the :samp:`{deallocator}` argument must be used. The same
866 function can be both an allocator and a deallocator. Since inlining one
867 of the associated functions but not the other could result in apparent
868 mismatches, this form of attribute ``malloc`` is not accepted on inline
869 functions. For the same reason, using the attribute prevents both
870 the allocation and deallocation functions from being expanded inline.
871
872 For example, besides stating that the functions return pointers that do
873 not alias any others, the following declarations make ``fclose``
874 a suitable deallocator for pointers returned from all functions except
875 ``popen``, and ``pclose`` as the only suitable deallocator for
876 pointers returned from ``popen``. The deallocator functions must
877 be declared before they can be referenced in the attribute.
878
879 .. code-block:: c++
880
881 int fclose (FILE*);
882 int pclose (FILE*);
883
884 __attribute__ ((malloc, malloc (fclose, 1)))
885 FILE* fdopen (int, const char*);
886 __attribute__ ((malloc, malloc (fclose, 1)))
887 FILE* fopen (const char*, const char*);
888 __attribute__ ((malloc, malloc (fclose, 1)))
889 FILE* fmemopen(void *, size_t, const char *);
890 __attribute__ ((malloc, malloc (pclose, 1)))
891 FILE* popen (const char*, const char*);
892 __attribute__ ((malloc, malloc (fclose, 1)))
893 FILE* tmpfile (void);
894
895 The warnings guarded by :option:`-fanalyzer` respect allocation and
896 deallocation pairs marked with the ``malloc``. In particular:
897
898 * The analyzer will emit a :option:`-Wanalyzer-mismatching-deallocation`
899 diagnostic if there is an execution path in which the result of an
900 allocation call is passed to a different deallocator.
901
902 * The analyzer will emit a :option:`-Wanalyzer-double-free`
903 diagnostic if there is an execution path in which a value is passed
904 more than once to a deallocation call.
905
906 * The analyzer will consider the possibility that an allocation function
907 could fail and return NULL. It will emit
908 :option:`-Wanalyzer-possible-null-dereference` and
909 :option:`-Wanalyzer-possible-null-argument` diagnostics if there are
910 execution paths in which an unchecked result of an allocation call is
911 dereferenced or passed to a function requiring a non-null argument.
912 If the allocator always returns non-null, use
913 ``__attribute__ ((returns_nonnull))`` to suppress these warnings.
914 For example:
915
916 .. code-block:: c++
917
918 char *xstrdup (const char *)
919 __attribute__((malloc (free), returns_nonnull));
920
921 * The analyzer will emit a :option:`-Wanalyzer-use-after-free`
922 diagnostic if there is an execution path in which the memory passed
923 by pointer to a deallocation call is used after the deallocation.
924
925 * The analyzer will emit a :option:`-Wanalyzer-malloc-leak` diagnostic if
926 there is an execution path in which the result of an allocation call
927 is leaked (without being passed to the deallocation function).
928
929 * The analyzer will emit a :option:`-Wanalyzer-free-of-non-heap` diagnostic
930 if a deallocation function is used on a global or on-stack variable.
931
932 The analyzer assumes that deallocators can gracefully handle the ``NULL``
933 pointer. If this is not the case, the deallocator can be marked with
934 ``__attribute__((nonnull))`` so that :option:`-fanalyzer` can emit
935 a :option:`-Wanalyzer-possible-null-argument` diagnostic for code paths
936 in which the deallocator is called with NULL.
937
938 .. index:: no_icf function attribute
939
940 .. fn-attr:: no_icf
941
942 This function attribute prevents a functions from being merged with another
943 semantically equivalent function.
944
945 .. index:: no_instrument_function function attribute
946
947 .. option:: no_instrument_function
948
949 If any of :option:`-finstrument-functions`, :option:`-p`, or :option:`-pg` are
950 given, profiling function calls are
951 generated at entry and exit of most user-compiled functions.
952 Functions with this attribute are not so instrumented.
953
954 .. index:: no_profile_instrument_function function attribute
955
956 .. fn-attr:: no_profile_instrument_function
957
958 The :fn-attr:`no_profile_instrument_function` attribute on functions is used
959 to inform the compiler that it should not process any profile feedback based
960 optimization code instrumentation.
961
962 .. index:: no_reorder function attribute
963
964 .. fn-attr:: no_reorder
965
966 Do not reorder functions or variables marked :fn-attr:`no_reorder`
967 against each other or top level assembler statements the executable.
968 The actual order in the program will depend on the linker command
969 line. Static variables marked like this are also not removed.
970 This has a similar effect
971 as the :option:`-fno-toplevel-reorder` option, but only applies to the
972 marked symbols.
973
974 .. index:: no_sanitize function attribute
975
976 .. fn-attr:: no_sanitize ("sanitize_option")
977
978 The ``no_sanitize`` attribute on functions is used
979 to inform the compiler that it should not do sanitization of any option
980 mentioned in :samp:`{sanitize_option}`. A list of values acceptable by
981 the :option:`-fsanitize` option can be provided.
982
983 .. code-block:: c++
984
985 void __attribute__ ((no_sanitize ("alignment", "object-size")))
986 f () { /* Do something. */; }
987 void __attribute__ ((no_sanitize ("alignment,object-size")))
988 g () { /* Do something. */; }
989
990 .. index:: no_sanitize_address function attribute
991
992 .. fn-attr:: no_sanitize_address, no_address_safety_analysis
993
994 The :fn-attr:`no_sanitize_address` attribute on functions is used
995 to inform the compiler that it should not instrument memory accesses
996 in the function when compiling with the :option:`-fsanitize=address` option.
997 The ``no_address_safety_analysis`` is a deprecated alias of the
998 :fn-attr:`no_sanitize_address` attribute, new code should use
999 :fn-attr:`no_sanitize_address`.
1000
1001 .. index:: no_sanitize_thread function attribute
1002
1003 .. fn-attr:: no_sanitize_thread
1004
1005 The :fn-attr:`no_sanitize_thread` attribute on functions is used
1006 to inform the compiler that it should not instrument memory accesses
1007 in the function when compiling with the :option:`-fsanitize=thread` option.
1008
1009 .. index:: no_sanitize_undefined function attribute
1010
1011 .. fn-attr:: no_sanitize_undefined
1012
1013 The :fn-attr:`no_sanitize_undefined` attribute on functions is used
1014 to inform the compiler that it should not check for undefined behavior
1015 in the function when compiling with the :option:`-fsanitize=undefined` option.
1016
1017 .. index:: no_sanitize_coverage function attribute
1018
1019 .. fn-attr:: no_sanitize_coverage
1020
1021 The :fn-attr:`no_sanitize_coverage` attribute on functions is used
1022 to inform the compiler that it should not do coverage-guided
1023 fuzzing code instrumentation (:option:`-fsanitize-coverage`).
1024
1025 .. index:: no_split_stack function attribute
1026
1027 .. option:: no_split_stack
1028
1029 If :option:`-fsplit-stack` is given, functions have a small
1030 prologue which decides whether to split the stack. Functions with the
1031 ``no_split_stack`` attribute do not have that prologue, and thus
1032 may run with only a small amount of stack space available.
1033
1034 .. index:: no_stack_limit function attribute
1035
1036 .. fn-attr:: no_stack_limit
1037
1038 This attribute locally overrides the :option:`-fstack-limit-register`
1039 and :option:`-fstack-limit-symbol` command-line options; it has the effect
1040 of disabling stack limit checking in the function it applies to.
1041
1042 .. index:: noclone function attribute
1043
1044 .. fn-attr:: noclone
1045
1046 This function attribute prevents a function from being considered for
1047 cloning---a mechanism that produces specialized copies of functions
1048 and which is (currently) performed by interprocedural constant
1049 propagation.
1050
1051 .. index:: noinline function attribute
1052
1053 .. fn-attr:: noinline
1054
1055 This function attribute prevents a function from being considered for
1056 inlining.
1057
1058 .. Don't enumerate the optimizations by name here; we try to be
1059
1060 .. future-compatible with this mechanism.
1061
1062 If the function does not have side effects, there are optimizations
1063 other than inlining that cause function calls to be optimized away,
1064 although the function call is live. To keep such calls from being
1065 optimized away, put
1066
1067 .. code-block:: c++
1068
1069 asm ("");
1070
1071 (see :ref:`extended-asm`) in the called function, to serve as a special
1072 side effect.
1073
1074 .. index:: noipa function attribute
1075
1076 .. fn-attr:: noipa
1077
1078 Disable interprocedural optimizations between the function with this
1079 attribute and its callers, as if the body of the function is not available
1080 when optimizing callers and the callers are unavailable when optimizing
1081 the body. This attribute implies :fn-attr:`noinline`, :fn-attr:`noclone` and
1082 :fn-attr:`no_icf` attributes. However, this attribute is not equivalent
1083 to a combination of other attributes, because its purpose is to suppress
1084 existing and future optimizations employing interprocedural analysis,
1085 including those that do not have an attribute suitable for disabling
1086 them individually. This attribute is supported mainly for the purpose
1087 of testing the compiler.
1088
1089 .. index:: nonnull function attribute, functions with non-null pointer arguments
1090
1091 .. fn-attr:: nonnull, nonnull (arg-index, ...)
1092
1093 The :fn-attr:`nonnull` attribute may be applied to a function that takes at
1094 least one argument of a pointer type. It indicates that the referenced
1095 arguments must be non-null pointers. For instance, the declaration:
1096
1097 .. code-block:: c++
1098
1099 extern void *
1100 my_memcpy (void *dest, const void *src, size_t len)
1101 __attribute__((nonnull (1, 2)));
1102
1103 informs the compiler that, in calls to ``my_memcpy``, arguments
1104 :samp:`{dest}` and :samp:`{src}` must be non-null.
1105
1106 The attribute has an effect both on functions calls and function definitions.
1107
1108 For function calls:
1109
1110 * If the compiler determines that a null pointer is
1111 passed in an argument slot marked as non-null, and the
1112 :option:`-Wnonnull` option is enabled, a warning is issued.
1113 See :ref:`warning-options`.
1114
1115 * The :option:`-fisolate-erroneous-paths-attribute` option can be
1116 specified to have GCC transform calls with null arguments to non-null
1117 functions into traps. See :ref:`optimize-options`.
1118
1119 * The compiler may also perform optimizations based on the
1120 knowledge that certain function arguments cannot be null. These
1121 optimizations can be disabled by the
1122 :option:`-fno-delete-null-pointer-checks` option. See :ref:`optimize-options`.
1123
1124 For function definitions:
1125
1126 * If the compiler determines that a function parameter that is
1127 marked with nonnull is compared with null, and
1128 :option:`-Wnonnull-compare` option is enabled, a warning is issued.
1129 See :ref:`warning-options`.
1130
1131 * The compiler may also perform optimizations based on the
1132 knowledge that ``nonnul`` parameters cannot be null. This can
1133 currently not be disabled other than by removing the nonnull
1134 attribute.
1135
1136 If no :samp:`{arg-index}` is given to the :fn-attr:`nonnull` attribute,
1137 all pointer arguments are marked as non-null. To illustrate, the
1138 following declaration is equivalent to the previous example:
1139
1140 .. code-block:: c++
1141
1142 extern void *
1143 my_memcpy (void *dest, const void *src, size_t len)
1144 __attribute__((nonnull));
1145
1146 .. index:: noplt function attribute
1147
1148 .. fn-attr:: noplt
1149
1150 The :fn-attr:`noplt` attribute is the counterpart to option :option:`-fno-plt`.
1151 Calls to functions marked with this attribute in position-independent code
1152 do not use the PLT.
1153
1154 .. code-block:: c++
1155
1156 /* Externally defined function foo. */
1157 int foo () __attribute__ ((noplt));
1158
1159 int
1160 main (/* ... */)
1161 {
1162 /* ... */
1163 foo ();
1164 /* ... */
1165 }
1166
1167 The :fn-attr:`noplt` attribute on function ``foo``
1168 tells the compiler to assume that
1169 the function ``foo`` is externally defined and that the call to
1170 ``foo`` must avoid the PLT
1171 in position-independent code.
1172
1173 In position-dependent code, a few targets also convert calls to
1174 functions that are marked to not use the PLT to use the GOT instead.
1175
1176 .. index:: noreturn function attribute, functions that never return
1177
1178 .. fn-attr:: noreturn
1179
1180 A few standard library functions, such as ``abort`` and ``exit``,
1181 cannot return. GCC knows this automatically. Some programs define
1182 their own functions that never return. You can declare them
1183 :fn-attr:`noreturn` to tell the compiler this fact. For example,
1184
1185 .. code-block:: c++
1186
1187 void fatal () __attribute__ ((noreturn));
1188
1189 void
1190 fatal (/* ... */)
1191 {
1192 /* ... */ /* Print error message. */ /* ... */
1193 exit (1);
1194 }
1195
1196 The :fn-attr:`noreturn` keyword tells the compiler to assume that
1197 ``fatal`` cannot return. It can then optimize without regard to what
1198 would happen if ``fatal`` ever did return. This makes slightly
1199 better code. More importantly, it helps avoid spurious warnings of
1200 uninitialized variables.
1201
1202 The :fn-attr:`noreturn` keyword does not affect the exceptional path when that
1203 applies: a :fn-attr:`noreturn` -marked function may still return to the caller
1204 by throwing an exception or calling ``longjmp``.
1205
1206 In order to preserve backtraces, GCC will never turn calls to
1207 :fn-attr:`noreturn` functions into tail calls.
1208
1209 Do not assume that registers saved by the calling function are
1210 restored before calling the :fn-attr:`noreturn` function.
1211
1212 It does not make sense for a :fn-attr:`noreturn` function to have a return
1213 type other than ``void``.
1214
1215 .. index:: nothrow function attribute
1216
1217 .. fn-attr:: nothrow
1218
1219 The :fn-attr:`nothrow` attribute is used to inform the compiler that a
1220 function cannot throw an exception. For example, most functions in
1221 the standard C library can be guaranteed not to throw an exception
1222 with the notable exceptions of ``qsort`` and ``bsearch`` that
1223 take function pointer arguments.
1224
1225 .. index:: optimize function attribute
1226
1227 .. fn-attr:: optimize (level, ...), optimize (string, ...)
1228
1229 .. fn-attr:: optimize (string, ...)
1230
1231 The ``optimize`` attribute is used to specify that a function is to
1232 be compiled with different optimization options than specified on the
1233 command line. The optimize attribute arguments of a function behave
1234 behave as if appended to the command-line.
1235
1236 Valid arguments are constant non-negative integers and
1237 strings. Each numeric argument specifies an optimization :samp:`{level}`.
1238 Each :samp:`{string}` argument consists of one or more comma-separated
1239 substrings. Each substring that begins with the letter ``O`` refers
1240 to an optimization option such as :option:`-O0` or :option:`-Os`. Other
1241 substrings are taken as suffixes to the ``-f`` prefix jointly
1242 forming the name of an optimization option. See :ref:`optimize-options`.
1243
1244 :samp:`#pragma GCC optimize` can be used to set optimization options
1245 for more than one function. See :ref:`function-specific-option-pragmas`,
1246 for details about the pragma.
1247
1248 Providing multiple strings as arguments separated by commas to specify
1249 multiple options is equivalent to separating the option suffixes with
1250 a comma (:samp:`,`) within a single string. Spaces are not permitted
1251 within the strings.
1252
1253 Not every optimization option that starts with the :samp:`{-f}` prefix
1254 specified by the attribute necessarily has an effect on the function.
1255 The ``optimize`` attribute should be used for debugging purposes only.
1256 It is not suitable in production code.
1257
1258 .. index:: patchable_function_entry function attribute, extra NOP instructions at the function entry point
1259
1260 .. fn-attr:: patchable_function_entry
1261
1262 In case the target's text segment can be made writable at run time by
1263 any means, padding the function entry with a number of NOPs can be
1264 used to provide a universal tool for instrumentation.
1265
1266 The :fn-attr:`patchable_function_entry` function attribute can be used to
1267 change the number of NOPs to any desired value. The two-value syntax
1268 is the same as for the command-line switch
1269 :option:`-fpatchable-function-entry=N,M`, generating :samp:`{N}` NOPs, with
1270 the function entry point before the :samp:`{M}` th NOP instruction.
1271 :samp:`{M}` defaults to 0 if omitted e.g. function entry point is before
1272 the first NOP.
1273
1274 If patchable function entries are enabled globally using the command-line
1275 option :option:`-fpatchable-function-entry=N,M`, then you must disable
1276 instrumentation on all functions that are part of the instrumentation
1277 framework with the attribute ``patchable_function_entry (0)``
1278 to prevent recursion.
1279
1280 .. index:: pure function attribute, functions that have no side effects
1281
1282 .. fn-attr:: pure
1283
1284 Calls to functions that have no observable effects on the state of
1285 the program other than to return a value may lend themselves to optimizations
1286 such as common subexpression elimination. Declaring such functions with
1287 the :fn-attr:`pure` attribute allows GCC to avoid emitting some calls in repeated
1288 invocations of the function with the same argument values.
1289
1290 The :fn-attr:`pure` attribute prohibits a function from modifying the state
1291 of the program that is observable by means other than inspecting
1292 the function's return value. However, functions declared with the :fn-attr:`pure`
1293 attribute can safely read any non-volatile objects, and modify the value of
1294 objects in a way that does not affect their return value or the observable
1295 state of the program.
1296
1297 For example,
1298
1299 .. code-block:: c++
1300
1301 int hash (char *) __attribute__ ((pure));
1302
1303 tells GCC that subsequent calls to the function ``hash`` with the same
1304 string can be replaced by the result of the first call provided the state
1305 of the program observable by ``hash``, including the contents of the array
1306 itself, does not change in between. Even though ``hash`` takes a non-const
1307 pointer argument it must not modify the array it points to, or any other object
1308 whose value the rest of the program may depend on. However, the caller may
1309 safely change the contents of the array between successive calls to
1310 the function (doing so disables the optimization). The restriction also
1311 applies to member objects referenced by the ``this`` pointer in C++
1312 non-static member functions.
1313
1314 Some common examples of pure functions are ``strlen`` or ``memcmp``.
1315 Interesting non-pure functions are functions with infinite loops or those
1316 depending on volatile memory or other system resource, that may change between
1317 consecutive calls (such as the standard C ``feof`` function in
1318 a multithreading environment).
1319
1320 The :fn-attr:`pure` attribute imposes similar but looser restrictions on
1321 a function's definition than the :fn-attr:`const` attribute: :fn-attr:`pure`
1322 allows the function to read any non-volatile memory, even if it changes
1323 in between successive invocations of the function. Declaring the same
1324 function with both the :fn-attr:`pure` and the :fn-attr:`const` attribute is
1325 diagnosed. Because a pure function cannot have any observable side
1326 effects it does not make sense for such a function to return ``void``.
1327 Declaring such a function is diagnosed.
1328
1329 .. index:: returns_nonnull function attribute
1330
1331 .. fn-attr:: returns_nonnull
1332
1333 The :fn-attr:`returns_nonnull` attribute specifies that the function
1334 return value should be a non-null pointer. For instance, the declaration:
1335
1336 .. code-block:: c++
1337
1338 extern void *
1339 mymalloc (size_t len) __attribute__((returns_nonnull));
1340
1341 lets the compiler optimize callers based on the knowledge
1342 that the return value will never be null.
1343
1344 .. index:: returns_twice function attribute, functions that return more than once
1345
1346 .. fn-attr:: returns_twice
1347
1348 The :fn-attr:`returns_twice` attribute tells the compiler that a function may
1349 return more than one time. The compiler ensures that all registers
1350 are dead before calling such a function and emits a warning about
1351 the variables that may be clobbered after the second return from the
1352 function. Examples of such functions are ``setjmp`` and ``vfork``.
1353 The ``longjmp`` -like counterpart of such function, if any, might need
1354 to be marked with the :fn-attr:`noreturn` attribute.
1355
1356 .. index:: section function attribute, functions in arbitrary sections
1357
1358 .. fn-attr:: section ("section-name")
1359
1360 Normally, the compiler places the code it generates in the ``text`` section.
1361 Sometimes, however, you need additional sections, or you need certain
1362 particular functions to appear in special sections. The ``section``
1363 attribute specifies that a function lives in a particular section.
1364 For example, the declaration:
1365
1366 .. code-block:: c++
1367
1368 extern void foobar (void) __attribute__ ((section ("bar")));
1369
1370 puts the function ``foobar`` in the ``bar`` section.
1371
1372 Some file formats do not support arbitrary sections so the ``section``
1373 attribute is not available on all platforms.
1374 If you need to map the entire contents of a module to a particular
1375 section, consider using the facilities of the linker instead.
1376
1377 .. index:: sentinel function attribute
1378
1379 .. fn-attr:: sentinel, sentinel (position)
1380
1381 This function attribute indicates that an argument in a call to the function
1382 is expected to be an explicit ``NULL``. The attribute is only valid on
1383 variadic functions. By default, the sentinel is expected to be the last
1384 argument of the function call. If the optional :samp:`{position}` argument
1385 is specified to the attribute, the sentinel must be located at
1386 :samp:`{position}` counting backwards from the end of the argument list.
1387
1388 .. code-block:: c++
1389
1390 __attribute__ ((sentinel))
1391 is equivalent to
1392 __attribute__ ((sentinel(0)))
1393
1394 The attribute is automatically set with a position of 0 for the built-in
1395 functions ``execl`` and ``execlp``. The built-in function
1396 ``execle`` has the attribute set with a position of 1.
1397
1398 A valid ``NULL`` in this context is defined as zero with any object
1399 pointer type. If your system defines the ``NULL`` macro with
1400 an integer type then you need to add an explicit cast. During
1401 installation GCC replaces the system ``<stddef.h>`` header with
1402 a copy that redefines NULL appropriately.
1403
1404 The warnings for missing or incorrect sentinels are enabled with
1405 :option:`-Wformat`.
1406
1407 .. index:: simd function attribute
1408
1409 .. fn-attr:: simd, simd("mask")
1410
1411 This attribute enables creation of one or more function versions that
1412 can process multiple arguments using SIMD instructions from a
1413 single invocation. Specifying this attribute allows compiler to
1414 assume that such versions are available at link time (provided
1415 in the same or another translation unit). Generated versions are
1416 target-dependent and described in the corresponding Vector ABI document. For
1417 x86_64 target this document can be found
1418 `here <https://sourceware.org/glibc/wiki/libmvec?action=AttachFile&do=view&target=VectorABI.txt>`_.
1419
1420 The optional argument :samp:`{mask}` may have the value
1421 ``notinbranch`` or ``inbranch``,
1422 and instructs the compiler to generate non-masked or masked
1423 clones correspondingly. By default, all clones are generated.
1424
1425 If the attribute is specified and ``#pragma omp declare simd`` is
1426 present on a declaration and the :option:`-fopenmp` or :option:`-fopenmp-simd`
1427 switch is specified, then the attribute is ignored.
1428
1429 .. index:: stack_protect function attribute
1430
1431 .. fn-attr:: stack_protect
1432
1433 This attribute adds stack protection code to the function if
1434 flags :option:`-fstack-protector`, :option:`-fstack-protector-strong`
1435 or :option:`-fstack-protector-explicit` are set.
1436
1437 .. index:: no_stack_protector function attribute
1438
1439 .. fn-attr:: no_stack_protector
1440
1441 This attribute prevents stack protection code for the function.
1442
1443 .. index:: target function attribute
1444
1445 .. fn-attr:: target (string, ...)
1446
1447 Multiple target back ends implement the ``target`` attribute
1448 to specify that a function is to
1449 be compiled with different target options than specified on the
1450 command line. The original target command-line options are ignored.
1451 One or more strings can be provided as arguments.
1452 Each string consists of one or more comma-separated suffixes to
1453 the ``-m`` prefix jointly forming the name of a machine-dependent
1454 option. See :ref:`submodel-options`.
1455
1456 The ``target`` attribute can be used for instance to have a function
1457 compiled with a different ISA (instruction set architecture) than the
1458 default. :samp:`#pragma GCC target` can be used to specify target-specific
1459 options for more than one function. See :ref:`function-specific-option-pragmas`,
1460 for details about the pragma.
1461
1462 For instance, on an x86, you could declare one function with the
1463 ``target("sse4.1,arch=core2")`` attribute and another with
1464 ``target("sse4a,arch=amdfam10")``. This is equivalent to
1465 compiling the first function with :option:`-msse4.1` and
1466 :option:`-march=core2` options, and the second function with
1467 :option:`-msse4a` and :option:`-march=amdfam10` options. It is up to you
1468 to make sure that a function is only invoked on a machine that
1469 supports the particular ISA it is compiled for (for example by using
1470 ``cpuid`` on x86 to determine what feature bits and architecture
1471 family are used).
1472
1473 .. code-block:: c++
1474
1475 int core2_func (void) __attribute__ ((__target__ ("arch=core2")));
1476 int sse3_func (void) __attribute__ ((__target__ ("sse3")));
1477
1478 Providing multiple strings as arguments separated by commas to specify
1479 multiple options is equivalent to separating the option suffixes with
1480 a comma (:samp:`,`) within a single string. Spaces are not permitted
1481 within the strings.
1482
1483 The options supported are specific to each target; refer to :ref:`x86-function-attributes`, :ref:`powerpc-function-attributes`,
1484 :ref:`arm-function-attributes`, :ref:`aarch64-function-attributes`,
1485 :ref:`nios-ii-function-attributes`, and :ref:`s-390-function-attributes`
1486 for details.
1487
1488 .. index:: symver function attribute
1489
1490 .. fn-attr:: symver ("name2@nodename")
1491
1492 On ELF targets this attribute creates a symbol version. The :samp:`{name2}` part
1493 of the parameter is the actual name of the symbol by which it will be
1494 externally referenced. The ``nodename`` portion should be the name of a
1495 node specified in the version script supplied to the linker when building a
1496 shared library. Versioned symbol must be defined and must be exported with
1497 default visibility.
1498
1499 .. code-block:: c++
1500
1501 __attribute__ ((__symver__ ("foo@VERS_1"))) int
1502 foo_v1 (void)
1503 {
1504 }
1505
1506 Will produce a ``.symver foo_v1, foo@VERS_1`` directive in the assembler
1507 output.
1508
1509 One can also define multiple version for a given symbol
1510 (starting from binutils 2.35).
1511
1512 .. code-block:: c++
1513
1514 __attribute__ ((__symver__ ("foo@VERS_2"), __symver__ ("foo@VERS_3")))
1515 int symver_foo_v1 (void)
1516 {
1517 }
1518
1519 This example creates a symbol name ``symver_foo_v1``
1520 which will be version ``VERS_2`` and ``VERS_3`` of ``foo``.
1521
1522 If you have an older release of binutils, then symbol alias needs to
1523 be used:
1524
1525 .. code-block:: c++
1526
1527 __attribute__ ((__symver__ ("foo@VERS_2")))
1528 int foo_v1 (void)
1529 {
1530 return 0;
1531 }
1532
1533 __attribute__ ((__symver__ ("foo@VERS_3")))
1534 __attribute__ ((alias ("foo_v1")))
1535 int symver_foo_v1 (void);
1536
1537 Finally if the parameter is ``"name2@@nodename"`` then in
1538 addition to creating a symbol version (as if
1539 ``"name2@nodename"`` was used) the version will be also used
1540 to resolve :samp:`{name2}` by the linker.
1541
1542 .. index:: tainted_args function attribute
1543
1544 .. fn-attr:: tainted_args
1545
1546 The :fn-attr:`tainted_args` attribute is used to specify that a function is called
1547 in a way that requires sanitization of its arguments, such as a system
1548 call in an operating system kernel. Such a function can be considered part
1549 of the 'attack surface' of the program. The attribute can be used both
1550 on function declarations, and on field declarations containing function
1551 pointers. In the latter case, any function used as an initializer of
1552 such a callback field will be treated as being called with tainted
1553 arguments.
1554
1555 The analyzer will pay particular attention to such functions when both
1556 :option:`-fanalyzer` and :option:`-fanalyzer-checker=taint` are supplied,
1557 potentially issuing warnings guarded by
1558 :option:`-Wanalyzer-tainted-allocation-size`,
1559 :option:`-Wanalyzer-tainted-array-index`,
1560 :option:`-Wanalyzer-tainted-divisor`,
1561 :option:`-Wanalyzer-tainted-offset`,
1562 and :option:`-Wanalyzer-tainted-size`.
1563
1564 .. index:: target_clones function attribute
1565
1566 .. fn-attr:: target_clones (options)
1567
1568 The ``target_clones`` attribute is used to specify that a function
1569 be cloned into multiple versions compiled with different target options
1570 than specified on the command line. The supported options and restrictions
1571 are the same as for ``target`` attribute.
1572
1573 For instance, on an x86, you could compile a function with
1574 ``target_clones("sse4.1,avx")``. GCC creates two function clones,
1575 one compiled with :option:`-msse4.1` and another with :option:`-mavx`.
1576
1577 On a PowerPC, you can compile a function with
1578 ``target_clones("cpu=power9,default")``. GCC will create two
1579 function clones, one compiled with :option:`-mcpu=power9` and another
1580 with the default options. GCC must be configured to use GLIBC 2.23 or
1581 newer in order to use the ``target_clones`` attribute.
1582
1583 It also creates a resolver function (see
1584 the ``ifunc`` attribute above) that dynamically selects a clone
1585 suitable for current architecture. The resolver is created only if there
1586 is a usage of a function with ``target_clones`` attribute.
1587
1588 Note that any subsequent call of a function without ``target_clone``
1589 from a ``target_clone`` caller will not lead to copying
1590 (target clone) of the called function.
1591 If you want to enforce such behaviour,
1592 we recommend declaring the calling function with the :fn-attr:`flatten` attribute?
1593
1594 .. index:: unused function attribute
1595
1596 .. fn-attr:: unused
1597
1598 This attribute, attached to a function, means that the function is meant
1599 to be possibly unused. GCC does not produce a warning for this
1600 function.
1601
1602 .. index:: used function attribute
1603
1604 .. fn-attr:: used
1605
1606 This attribute, attached to a function, means that code must be emitted
1607 for the function even if it appears that the function is not referenced.
1608 This is useful, for example, when the function is referenced only in
1609 inline assembly.
1610
1611 When applied to a member function of a C++ class template, the
1612 attribute also means that the function is instantiated if the
1613 class itself is instantiated.
1614
1615 .. index:: retain function attribute
1616
1617 .. fn-attr:: retain
1618
1619 For ELF targets that support the GNU or FreeBSD OSABIs, this attribute
1620 will save the function from linker garbage collection. To support
1621 this behavior, functions that have not been placed in specific sections
1622 (e.g. by the ``section`` attribute, or the ``-ffunction-sections``
1623 option), will be placed in new, unique sections.
1624
1625 This additional functionality requires Binutils version 2.36 or later.
1626
1627 .. index:: visibility function attribute
1628
1629 .. fn-attr:: visibility ("visibility_type")
1630
1631 This attribute affects the linkage of the declaration to which it is attached.
1632 It can be applied to variables (see :ref:`common-variable-attributes`) and types
1633 (see :ref:`common-type-attributes`) as well as functions.
1634
1635 There are four supported :samp:`{visibility_type}` values: default,
1636 hidden, protected or internal visibility.
1637
1638 .. code-block:: c++
1639
1640 void __attribute__ ((visibility ("protected")))
1641 f () { /* Do something. */; }
1642 int i __attribute__ ((visibility ("hidden")));
1643
1644 The possible values of :samp:`{visibility_type}` correspond to the
1645 visibility settings in the ELF gABI.
1646
1647 .. keep this list of visibilities in alphabetical order.
1648
1649 ``default``
1650 Default visibility is the normal case for the object file format.
1651 This value is available for the visibility attribute to override other
1652 options that may change the assumed visibility of entities.
1653
1654 On ELF, default visibility means that the declaration is visible to other
1655 modules and, in shared libraries, means that the declared entity may be
1656 overridden.
1657
1658 On Darwin, default visibility means that the declaration is visible to
1659 other modules.
1660
1661 Default visibility corresponds to 'external linkage' in the language.
1662
1663 ``hidden``
1664 Hidden visibility indicates that the entity declared has a new
1665 form of linkage, which we call 'hidden linkage'. Two
1666 declarations of an object with hidden linkage refer to the same object
1667 if they are in the same shared object.
1668
1669 ``internal``
1670 Internal visibility is like hidden visibility, but with additional
1671 processor specific semantics. Unless otherwise specified by the
1672 psABI, GCC defines internal visibility to mean that a function is
1673 *never* called from another module. Compare this with hidden
1674 functions which, while they cannot be referenced directly by other
1675 modules, can be referenced indirectly via function pointers. By
1676 indicating that a function cannot be called from outside the module,
1677 GCC may for instance omit the load of a PIC register since it is known
1678 that the calling function loaded the correct value.
1679
1680 ``protected``
1681 Protected visibility is like default visibility except that it
1682 indicates that references within the defining module bind to the
1683 definition in that module. That is, the declared entity cannot be
1684 overridden by another module.
1685
1686 All visibilities are supported on many, but not all, ELF targets
1687 (supported when the assembler supports the :samp:`.visibility`
1688 pseudo-op). Default visibility is supported everywhere. Hidden
1689 visibility is supported on Darwin targets.
1690
1691 The visibility attribute should be applied only to declarations that
1692 would otherwise have external linkage. The attribute should be applied
1693 consistently, so that the same entity should not be declared with
1694 different settings of the attribute.
1695
1696 In C++, the visibility attribute applies to types as well as functions
1697 and objects, because in C++ types have linkage. A class must not have
1698 greater visibility than its non-static data member types and bases,
1699 and class members default to the visibility of their class. Also, a
1700 declaration without explicit visibility is limited to the visibility
1701 of its type.
1702
1703 In C++, you can mark member functions and static member variables of a
1704 class with the visibility attribute. This is useful if you know a
1705 particular method or static member variable should only be used from
1706 one shared object; then you can mark it hidden while the rest of the
1707 class has default visibility. Care must be taken to avoid breaking
1708 the One Definition Rule; for example, it is usually not useful to mark
1709 an inline method as hidden without marking the whole class as hidden.
1710
1711 A C++ namespace declaration can also have the visibility attribute.
1712
1713 .. code-block:: c++
1714
1715 namespace nspace1 __attribute__ ((visibility ("protected")))
1716 { /* Do something. */; }
1717
1718 This attribute applies only to the particular namespace body, not to
1719 other definitions of the same namespace; it is equivalent to using
1720 :samp:`#pragma GCC visibility` before and after the namespace
1721 definition (see :ref:`visibility-pragmas`).
1722
1723 In C++, if a template argument has limited visibility, this
1724 restriction is implicitly propagated to the template instantiation.
1725 Otherwise, template instantiations and specializations default to the
1726 visibility of their template.
1727
1728 If both the template and enclosing class have explicit visibility, the
1729 visibility from the template is used.
1730
1731 .. index:: warn_unused_result function attribute
1732
1733 .. fn-attr:: warn_unused_result
1734
1735 The :fn-attr:`warn_unused_result` attribute causes a warning to be emitted
1736 if a caller of the function with this attribute does not use its
1737 return value. This is useful for functions where not checking
1738 the result is either a security problem or always a bug, such as
1739 ``realloc``.
1740
1741 .. code-block:: c++
1742
1743 int fn () __attribute__ ((warn_unused_result));
1744 int foo ()
1745 {
1746 if (fn () < 0) return -1;
1747 fn ();
1748 return 0;
1749 }
1750
1751 results in warning on line 5.
1752
1753 .. index:: weak function attribute
1754
1755 .. fn-attr:: weak
1756
1757 The :fn-attr:`weak` attribute causes a declaration of an external symbol
1758 to be emitted as a weak symbol rather than a global. This is primarily
1759 useful in defining library functions that can be overridden in user code,
1760 though it can also be used with non-function declarations. The overriding
1761 symbol must have the same type as the weak symbol. In addition, if it
1762 designates a variable it must also have the same size and alignment as
1763 the weak symbol. Weak symbols are supported for ELF targets, and also
1764 for a.out targets when using the GNU assembler and linker.
1765
1766 .. index:: weakref function attribute
1767
1768 .. fn-attr:: weakref, weakref ("target")
1769
1770 The :fn-attr:`weakref` attribute marks a declaration as a weak reference.
1771 Without arguments, it should be accompanied by an ``alias`` attribute
1772 naming the target symbol. Alternatively, :samp:`{target}` may be given as
1773 an argument to :fn-attr:`weakref` itself, naming the target definition of
1774 the alias. The :samp:`{target}` must have the same type as the declaration.
1775 In addition, if it designates a variable it must also have the same size
1776 and alignment as the declaration. In either form of the declaration
1777 :fn-attr:`weakref` implicitly marks the declared symbol as :fn-attr:`weak`. Without
1778 a :samp:`{target}` given as an argument to :fn-attr:`weakref` or to ``alias``,
1779 :fn-attr:`weakref` is equivalent to :fn-attr:`weak` (in that case the declaration
1780 may be ``extern``).
1781
1782 .. code-block:: c++
1783
1784 /* Given the declaration: */
1785 extern int y (void);
1786
1787 /* the following... */
1788 static int x (void) __attribute__ ((weakref ("y")));
1789
1790 /* is equivalent to... */
1791 static int x (void) __attribute__ ((weakref, alias ("y")));
1792
1793 /* or, alternatively, to... */
1794 static int x (void) __attribute__ ((weakref));
1795 static int x (void) __attribute__ ((alias ("y")));
1796
1797 A weak reference is an alias that does not by itself require a
1798 definition to be given for the target symbol. If the target symbol is
1799 only referenced through weak references, then it becomes a :fn-attr:`weak`
1800 undefined symbol. If it is directly referenced, however, then such
1801 strong references prevail, and a definition is required for the
1802 symbol, not necessarily in the same translation unit.
1803
1804 The effect is equivalent to moving all references to the alias to a
1805 separate translation unit, renaming the alias to the aliased symbol,
1806 declaring it as weak, compiling the two separate translation units and
1807 performing a link with relocatable output (i.e. ``ld -r``) on them.
1808
1809 A declaration to which :fn-attr:`weakref` is attached and that is associated
1810 with a named ``target`` must be ``static``.
1811
1812 .. index:: zero_call_used_regs function attribute
1813
1814 .. fn-attr:: zero_call_used_regs ("choice")
1815
1816 The ``zero_call_used_regs`` attribute causes the compiler to zero
1817 a subset of all call-used registers ([#f1]_) at function return.
1818 This is used to increase program security by either mitigating
1819 Return-Oriented Programming (ROP) attacks or preventing information leakage
1820 through registers.
1821
1822 In order to satisfy users with different security needs and control the
1823 run-time overhead at the same time, the :samp:`{choice}` parameter provides a
1824 flexible way to choose the subset of the call-used registers to be zeroed.
1825 The three basic values of :samp:`{choice}` are:
1826
1827 * :samp:`skip` doesn't zero any call-used registers.
1828
1829 * :samp:`used` only zeros call-used registers that are used in the function.
1830 A 'used' register is one whose content has been set or referenced in
1831 the function.
1832
1833 * :samp:`all` zeros all call-used registers.
1834
1835 In addition to these three basic choices, it is possible to modify
1836 :samp:`used` or :samp:`all` as follows:
1837
1838 * Adding :samp:`-gpr` restricts the zeroing to general-purpose registers.
1839
1840 * Adding :samp:`-arg` restricts the zeroing to registers that can sometimes
1841 be used to pass function arguments. This includes all argument registers
1842 defined by the platform's calling conversion, regardless of whether the
1843 function uses those registers for function arguments or not.
1844
1845 The modifiers can be used individually or together. If they are used
1846 together, they must appear in the order above.
1847
1848 The full list of :samp:`{choice}` s is therefore:
1849
1850 ``skip``
1851 doesn't zero any call-used register.
1852
1853 ``used``
1854 only zeros call-used registers that are used in the function.
1855
1856 ``used-gpr``
1857 only zeros call-used general purpose registers that are used in the function.
1858
1859 ``used-arg``
1860 only zeros call-used registers that are used in the function and pass arguments.
1861
1862 ``used-gpr-arg``
1863 only zeros call-used general purpose registers that are used in the function
1864 and pass arguments.
1865
1866 ``all``
1867 zeros all call-used registers.
1868
1869 ``all-gpr``
1870 zeros all call-used general purpose registers.
1871
1872 ``all-arg``
1873 zeros all call-used registers that pass arguments.
1874
1875 ``all-gpr-arg``
1876 zeros all call-used general purpose registers that pass
1877 arguments.
1878
1879 Of this list, :samp:`used-arg`, :samp:`used-gpr-arg`, :samp:`all-arg`,
1880 and :samp:`all-gpr-arg` are mainly used for ROP mitigation.
1881
1882 The default for the attribute is controlled by :option:`-fzero-call-used-regs`.
1883
1884 .. This is the end of the target-independent attribute table
1885
1886 .. [#f1] A 'call-used' register
1887 is a register whose contents can be changed by a function call;
1888 therefore, a caller cannot assume that the register has the same contents
1889 on return from the function as it had before calling the function. Such
1890 registers are also called 'call-clobbered', 'caller-saved', or
1891 'volatile'.