1/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\
2|* *|
3|* Clang attribute documentation *|
4|* *|
5|* Automatically generated file, do not edit! *|
6|* From: Attr.td *|
7|* *|
8\*===----------------------------------------------------------------------===*/
9
10
11static const char AttrDoc_AArch64SVEPcs[] = R"reST(On AArch64 targets, this attribute changes the calling convention of a
12function to preserve additional Scalable Vector registers and Scalable
13Predicate registers relative to the default calling convention used for
14AArch64.
15
16This means it is more efficient to call such functions from code that performs
17extensive scalable vector and scalable predicate calculations, because fewer
18live SVE registers need to be saved. This property makes it well-suited for SVE
19math library functions, which are typically leaf functions that require a small
20number of registers.
21
22However, using this attribute also means that it is more expensive to call
23a function that adheres to the default calling convention from within such
24a function. Therefore, it is recommended that this attribute is only used
25for leaf functions.
26
27For more information, see the documentation for `aarch64_sve_pcs` in the
28ARM C Language Extension (ACLE) documentation.
29
30.. _`aarch64_sve_pcs`: https://github.com/ARM-software/acle/blob/main/main/acle.md#scalable-vector-extension-procedure-call-standard-attribute)reST";
31
32static const char AttrDoc_AArch64VectorPcs[] = R"reST(On AArch64 targets, this attribute changes the calling convention of a
33function to preserve additional floating-point and Advanced SIMD registers
34relative to the default calling convention used for AArch64.
35
36This means it is more efficient to call such functions from code that performs
37extensive floating-point and vector calculations, because fewer live SIMD and FP
38registers need to be saved. This property makes it well-suited for e.g.
39floating-point or vector math library functions, which are typically leaf
40functions that require a small number of registers.
41
42However, using this attribute also means that it is more expensive to call
43a function that adheres to the default calling convention from within such
44a function. Therefore, it is recommended that this attribute is only used
45for leaf functions.
46
47For more information, see the documentation for `aarch64_vector_pcs`_ on
48the Arm Developer website.
49
50.. _`aarch64_vector_pcs`: https://developer.arm.com/products/software-development-tools/hpc/arm-compiler-for-hpc/vector-function-abi)reST";
51
52static const char AttrDoc_AMDGPUFlatWorkGroupSize[] = R"reST(The flat work-group size is the number of work-items in the work-group size
53specified when the kernel is dispatched. It is the product of the sizes of the
54x, y, and z dimension of the work-group.
55
56Clang supports the
57``__attribute__((amdgpu_flat_work_group_size(<min>, <max>)))`` attribute for the
58AMDGPU target. This attribute may be attached to a kernel function definition
59and is an optimization hint.
60
61``<min>`` parameter specifies the minimum flat work-group size, and ``<max>``
62parameter specifies the maximum flat work-group size (must be greater than
63``<min>``) to which all dispatches of the kernel will conform. Passing ``0, 0``
64as ``<min>, <max>`` implies the default behavior (``128, 256``).
65
66If specified, the AMDGPU target backend might be able to produce better machine
67code for barriers and perform scratch promotion by estimating available group
68segment size.
69
70An error will be given if:
71 - Specified values violate subtarget specifications;
72 - Specified values are not compatible with values provided through other
73 attributes.)reST";
74
75static const char AttrDoc_AMDGPUMaxNumWorkGroups[] = R"reST(This attribute specifies the max number of work groups when the kernel
76is dispatched.
77
78Clang supports the
79``__attribute__((amdgpu_max_num_work_groups(<x>, <y>, <z>)))`` or
80``[[clang::amdgpu_max_num_work_groups(<x>, <y>, <z>)]]`` attribute for the
81AMDGPU target. This attribute may be attached to HIP or OpenCL kernel function
82definitions and is an optimization hint.
83
84The ``<x>`` parameter specifies the maximum number of work groups in the x dimension.
85Similarly ``<y>`` and ``<z>`` are for the y and z dimensions respectively.
86Each of the three values must be greater than 0 when provided. The ``<x>`` parameter
87is required, while ``<y>`` and ``<z>`` are optional with default value of 1.
88
89If specified, the AMDGPU target backend might be able to produce better machine
90code.
91
92An error will be given if:
93 - Specified values violate subtarget specifications;
94 - Specified values are not compatible with values provided through other
95 attributes.)reST";
96
97static const char AttrDoc_AMDGPUNumSGPR[] = R"reST(Clang supports the ``__attribute__((amdgpu_num_sgpr(<num_sgpr>)))`` and
98``__attribute__((amdgpu_num_vgpr(<num_vgpr>)))`` attributes for the AMDGPU
99target. These attributes may be attached to a kernel function definition and are
100an optimization hint.
101
102If these attributes are specified, then the AMDGPU target backend will attempt
103to limit the number of SGPRs and/or VGPRs used to the specified value(s). The
104number of used SGPRs and/or VGPRs may further be rounded up to satisfy the
105allocation requirements or constraints of the subtarget. Passing ``0`` as
106``num_sgpr`` and/or ``num_vgpr`` implies the default behavior (no limits).
107
108These attributes can be used to test the AMDGPU target backend. It is
109recommended that the ``amdgpu_waves_per_eu`` attribute be used to control
110resources such as SGPRs and VGPRs since it is aware of the limits for different
111subtargets.
112
113An error will be given if:
114 - Specified values violate subtarget specifications;
115 - Specified values are not compatible with values provided through other
116 attributes;
117 - The AMDGPU target backend is unable to create machine code that can meet the
118 request.)reST";
119
120static const char AttrDoc_AMDGPUNumVGPR[] = R"reST(Clang supports the ``__attribute__((amdgpu_num_sgpr(<num_sgpr>)))`` and
121``__attribute__((amdgpu_num_vgpr(<num_vgpr>)))`` attributes for the AMDGPU
122target. These attributes may be attached to a kernel function definition and are
123an optimization hint.
124
125If these attributes are specified, then the AMDGPU target backend will attempt
126to limit the number of SGPRs and/or VGPRs used to the specified value(s). The
127number of used SGPRs and/or VGPRs may further be rounded up to satisfy the
128allocation requirements or constraints of the subtarget. Passing ``0`` as
129``num_sgpr`` and/or ``num_vgpr`` implies the default behavior (no limits).
130
131These attributes can be used to test the AMDGPU target backend. It is
132recommended that the ``amdgpu_waves_per_eu`` attribute be used to control
133resources such as SGPRs and VGPRs since it is aware of the limits for different
134subtargets.
135
136An error will be given if:
137 - Specified values violate subtarget specifications;
138 - Specified values are not compatible with values provided through other
139 attributes;
140 - The AMDGPU target backend is unable to create machine code that can meet the
141 request.)reST";
142
143static const char AttrDoc_AMDGPUWavesPerEU[] = R"reST(A compute unit (CU) is responsible for executing the wavefronts of a work-group.
144It is composed of one or more execution units (EU), which are responsible for
145executing the wavefronts. An EU can have enough resources to maintain the state
146of more than one executing wavefront. This allows an EU to hide latency by
147switching between wavefronts in a similar way to symmetric multithreading on a
148CPU. In order to allow the state for multiple wavefronts to fit on an EU, the
149resources used by a single wavefront have to be limited. For example, the number
150of SGPRs and VGPRs. Limiting such resources can allow greater latency hiding,
151but can result in having to spill some register state to memory.
152
153Clang supports the ``__attribute__((amdgpu_waves_per_eu(<min>[, <max>])))``
154attribute for the AMDGPU target. This attribute may be attached to a kernel
155function definition and is an optimization hint.
156
157``<min>`` parameter specifies the requested minimum number of waves per EU, and
158*optional* ``<max>`` parameter specifies the requested maximum number of waves
159per EU (must be greater than ``<min>`` if specified). If ``<max>`` is omitted,
160then there is no restriction on the maximum number of waves per EU other than
161the one dictated by the hardware for which the kernel is compiled. Passing
162``0, 0`` as ``<min>, <max>`` implies the default behavior (no limits).
163
164If specified, this attribute allows an advanced developer to tune the number of
165wavefronts that are capable of fitting within the resources of an EU. The AMDGPU
166target backend can use this information to limit resources, such as number of
167SGPRs, number of VGPRs, size of available group and private memory segments, in
168such a way that guarantees that at least ``<min>`` wavefronts and at most
169``<max>`` wavefronts are able to fit within the resources of an EU. Requesting
170more wavefronts can hide memory latency but limits available registers which
171can result in spilling. Requesting fewer wavefronts can help reduce cache
172thrashing, but can reduce memory latency hiding.
173
174This attribute controls the machine code generated by the AMDGPU target backend
175to ensure it is capable of meeting the requested values. However, when the
176kernel is executed, there may be other reasons that prevent meeting the request,
177for example, there may be wavefronts from other kernels executing on the EU.
178
179An error will be given if:
180 - Specified values violate subtarget specifications;
181 - Specified values are not compatible with values provided through other
182 attributes;
183
184The AMDGPU target backend will emit a warning whenever it is unable to
185create machine code that meets the request.)reST";
186
187static const char AttrDoc_ARMInterrupt[] = R"reST(Clang supports the GNU style ``__attribute__((interrupt("TYPE")))`` attribute on
188ARM targets. This attribute may be attached to a function definition and
189instructs the backend to generate appropriate function entry/exit code so that
190it can be used directly as an interrupt service routine.
191
192The parameter passed to the interrupt attribute is optional, but if
193provided it must be a string literal with one of the following values: "IRQ",
194"FIQ", "SWI", "ABORT", "UNDEF".
195
196The semantics are as follows:
197
198- If the function is AAPCS, Clang instructs the backend to realign the stack to
199 8 bytes on entry. This is a general requirement of the AAPCS at public
200 interfaces, but may not hold when an exception is taken. Doing this allows
201 other AAPCS functions to be called.
202- If the CPU is M-class this is all that needs to be done since the architecture
203 itself is designed in such a way that functions obeying the normal AAPCS ABI
204 constraints are valid exception handlers.
205- If the CPU is not M-class, the prologue and epilogue are modified to save all
206 non-banked registers that are used, so that upon return the user-mode state
207 will not be corrupted. Note that to avoid unnecessary overhead, only
208 general-purpose (integer) registers are saved in this way. If VFP operations
209 are needed, that state must be saved manually.
210
211 Specifically, interrupt kinds other than "FIQ" will save all core registers
212 except "lr" and "sp". "FIQ" interrupts will save r0-r7.
213- If the CPU is not M-class, the return instruction is changed to one of the
214 canonical sequences permitted by the architecture for exception return. Where
215 possible the function itself will make the necessary "lr" adjustments so that
216 the "preferred return address" is selected.
217
218 Unfortunately the compiler is unable to make this guarantee for an "UNDEF"
219 handler, where the offset from "lr" to the preferred return address depends on
220 the execution state of the code which generated the exception. In this case
221 a sequence equivalent to "movs pc, lr" will be used.)reST";
222
223static const char AttrDoc_ARMInterruptSaveFP[] = R"reST(Clang supports the GNU style ``__attribute__((interrupt_save_fp("TYPE")))``
224on ARM targets. This attribute behaves the same way as the ARM interrupt
225attribute, except the general purpose floating point registers are also saved,
226along with FPEXC and FPSCR. Note, even on M-class CPUs, where the floating
227point context can be automatically saved depending on the FPCCR, the general
228purpose floating point registers will be saved.)reST";
229
230static const char AttrDoc_ARMSaveFP[] = R"reST()reST";
231
232static const char AttrDoc_AVRInterrupt[] = R"reST(Clang supports the GNU style ``__attribute__((interrupt))`` attribute on
233AVR targets. This attribute may be attached to a function definition and instructs
234the backend to generate appropriate function entry/exit code so that it can be used
235directly as an interrupt service routine.
236
237On the AVR, the hardware globally disables interrupts when an interrupt is executed.
238The first instruction of an interrupt handler declared with this attribute is a SEI
239instruction to re-enable interrupts. See also the signal attribute that
240does not insert a SEI instruction.)reST";
241
242static const char AttrDoc_AVRSignal[] = R"reST(Clang supports the GNU style ``__attribute__((signal))`` attribute on
243AVR targets. This attribute may be attached to a function definition and instructs
244the backend to generate appropriate function entry/exit code so that it can be used
245directly as an interrupt service routine.
246
247Interrupt handler functions defined with the signal attribute do not re-enable interrupts.)reST";
248
249static const char AttrDoc_AbiTag[] = R"reST(The ``abi_tag`` attribute can be applied to a function, variable, class or
250inline namespace declaration to modify the mangled name of the entity. It gives
251the ability to distinguish between different versions of the same entity but
252with different ABI versions supported. For example, a newer version of a class
253could have a different set of data members and thus have a different size. Using
254the ``abi_tag`` attribute, it is possible to have different mangled names for
255a global variable of the class type. Therefore, the old code could keep using
256the old mangled name and the new code will use the new mangled name with tags.)reST";
257
258static const char AttrDoc_AcquireCapability[] = R"reST(Marks a function as acquiring a capability.)reST";
259
260static const char AttrDoc_AcquireHandle[] = R"reST(If this annotation is on a function or a function type it is assumed to return
261a new handle. In case this annotation is on an output parameter,
262the function is assumed to fill the corresponding argument with a new
263handle. The attribute requires a string literal argument which used to
264identify the handle with later uses of ``use_handle`` or
265``release_handle``.
266
267.. code-block:: c++
268
269 // Output arguments from Zircon.
270 zx_status_t zx_socket_create(uint32_t options,
271 zx_handle_t __attribute__((acquire_handle("zircon"))) * out0,
272 zx_handle_t* out1 [[clang::acquire_handle("zircon")]]);
273
274
275 // Returned handle.
276 [[clang::acquire_handle("tag")]] int open(const char *path, int oflag, ... );
277 int open(const char *path, int oflag, ... ) __attribute__((acquire_handle("tag")));)reST";
278
279static const char AttrDoc_AcquiredAfter[] = R"reST(No documentation.)reST";
280
281static const char AttrDoc_AcquiredBefore[] = R"reST(No documentation.)reST";
282
283static const char AttrDoc_AddressSpace[] = R"reST(No documentation.)reST";
284
285static const char AttrDoc_Alias[] = R"reST(No documentation.)reST";
286
287static const char AttrDoc_AlignMac68k[] = R"reST()reST";
288
289static const char AttrDoc_AlignNatural[] = R"reST()reST";
290
291static const char AttrDoc_AlignValue[] = R"reST(The align_value attribute can be added to the typedef of a pointer type or the
292declaration of a variable of pointer or reference type. It specifies that the
293pointer will point to, or the reference will bind to, only objects with at
294least the provided alignment. This alignment value must be some positive power
295of 2.
296
297 .. code-block:: c
298
299 typedef double * aligned_double_ptr __attribute__((align_value(64)));
300 void foo(double & x __attribute__((align_value(128)),
301 aligned_double_ptr y) { ... }
302
303If the pointer value does not have the specified alignment at runtime, the
304behavior of the program is undefined.)reST";
305
306static const char AttrDoc_Aligned[] = R"reST(No documentation.)reST";
307
308static const char AttrDoc_AllocAlign[] = R"reST(Use ``__attribute__((alloc_align(<alignment>))`` on a function
309declaration to specify that the return value of the function (which must be a
310pointer type) is at least as aligned as the value of the indicated parameter. The
311parameter is given by its index in the list of formal parameters; the first
312parameter has index 1 unless the function is a C++ non-static member function,
313in which case the first parameter has index 2 to account for the implicit ``this``
314parameter.
315
316.. code-block:: c++
317
318 // The returned pointer has the alignment specified by the first parameter.
319 void *a(size_t align) __attribute__((alloc_align(1)));
320
321 // The returned pointer has the alignment specified by the second parameter.
322 void *b(void *v, size_t align) __attribute__((alloc_align(2)));
323
324 // The returned pointer has the alignment specified by the second visible
325 // parameter, however it must be adjusted for the implicit 'this' parameter.
326 void *Foo::b(void *v, size_t align) __attribute__((alloc_align(3)));
327
328Note that this attribute merely informs the compiler that a function always
329returns a sufficiently aligned pointer. It does not cause the compiler to
330emit code to enforce that alignment. The behavior is undefined if the returned
331pointer is not sufficiently aligned.)reST";
332
333static const char AttrDoc_AllocSize[] = R"reST(The ``alloc_size`` attribute can be placed on functions that return pointers in
334order to hint to the compiler how many bytes of memory will be available at the
335returned pointer. ``alloc_size`` takes one or two arguments.
336
337- ``alloc_size(N)`` implies that argument number N equals the number of
338 available bytes at the returned pointer.
339- ``alloc_size(N, M)`` implies that the product of argument number N and
340 argument number M equals the number of available bytes at the returned
341 pointer.
342
343Argument numbers are 1-based.
344
345An example of how to use ``alloc_size``
346
347.. code-block:: c
348
349 void *my_malloc(int a) __attribute__((alloc_size(1)));
350 void *my_calloc(int a, int b) __attribute__((alloc_size(1, 2)));
351
352 int main() {
353 void *const p = my_malloc(100);
354 assert(__builtin_object_size(p, 0) == 100);
355 void *const a = my_calloc(20, 5);
356 assert(__builtin_object_size(a, 0) == 100);
357 }
358
359.. Note:: This attribute works differently in clang than it does in GCC.
360 Specifically, clang will only trace ``const`` pointers (as above); we give up
361 on pointers that are not marked as ``const``. In the vast majority of cases,
362 this is unimportant, because LLVM has support for the ``alloc_size``
363 attribute. However, this may cause mildly unintuitive behavior when used with
364 other attributes, such as ``enable_if``.)reST";
365
366static const char AttrDoc_Allocating[] = R"reST(Declares that a function potentially allocates heap memory, and prevents any potential inference
367of ``nonallocating`` by the compiler.)reST";
368
369static const char AttrDoc_AlwaysDestroy[] = R"reST(The ``always_destroy`` attribute specifies that a variable with static or thread
370storage duration should have its exit-time destructor run. This attribute is the
371default unless clang was invoked with -fno-c++-static-destructors.
372
373If a variable is explicitly declared with this attribute, Clang will silence
374otherwise applicable ``-Wexit-time-destructors`` warnings.)reST";
375
376static const char AttrDoc_AlwaysInline[] = R"reST(Inlining heuristics are disabled and inlining is always attempted regardless of
377optimization level.
378
379``[[clang::always_inline]]`` spelling can be used as a statement attribute; other
380spellings of the attribute are not supported on statements. If a statement is
381marked ``[[clang::always_inline]]`` and contains calls, the compiler attempts
382to inline those calls.
383
384.. code-block:: c
385
386 int example(void) {
387 int i;
388 [[clang::always_inline]] foo(); // attempts to inline foo
389 [[clang::always_inline]] i = bar(); // attempts to inline bar
390 [[clang::always_inline]] return f(42, baz(bar())); // attempts to inline everything
391 }
392
393A declaration statement, which is a statement, is not a statement that can have an
394attribute associated with it (the attribute applies to the declaration, not the
395statement in that case). So this use case will not work:
396
397.. code-block:: c
398
399 int example(void) {
400 [[clang::always_inline]] int i = bar();
401 return i;
402 }
403
404This attribute does not guarantee that inline substitution actually occurs.
405
406<ins>Note: applying this attribute to a coroutine at the `-O0` optimization level
407has no effect; other optimization levels may only partially inline and result in a
408diagnostic.</ins>
409
410See also `the Microsoft Docs on Inline Functions`_, `the GCC Common Function
411Attribute docs`_, and `the GCC Inline docs`_.
412
413.. _the Microsoft Docs on Inline Functions: https://docs.microsoft.com/en-us/cpp/cpp/inline-functions-cpp
414.. _the GCC Common Function Attribute docs: https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html
415.. _the GCC Inline docs: https://gcc.gnu.org/onlinedocs/gcc/Inline.html)reST";
416
417static const char AttrDoc_AnalyzerNoReturn[] = R"reST(No documentation.)reST";
418
419static const char AttrDoc_Annotate[] = R"reST(No documentation.)reST";
420
421static const char AttrDoc_AnnotateType[] = R"reST(This attribute is used to add annotations to types, typically for use by static
422analysis tools that are not integrated into the core Clang compiler (e.g.,
423Clang-Tidy checks or out-of-tree Clang-based tools). It is a counterpart to the
424`annotate` attribute, which serves the same purpose, but for declarations.
425
426The attribute takes a mandatory string literal argument specifying the
427annotation category and an arbitrary number of optional arguments that provide
428additional information specific to the annotation category. The optional
429arguments must be constant expressions of arbitrary type.
430
431For example:
432
433.. code-block:: c++
434
435 int* [[clang::annotate_type("category1", "foo", 1)]] f(int[[clang::annotate_type("category2")]] *);
436
437The attribute does not have any effect on the semantics of the type system,
438neither type checking rules, nor runtime semantics. In particular:
439
440- ``std::is_same<T, T [[clang::annotate_type("foo")]]>`` is true for all types
441 ``T``.
442
443- It is not permissible for overloaded functions or template specializations
444 to differ merely by an ``annotate_type`` attribute.
445
446- The presence of an ``annotate_type`` attribute will not affect name
447 mangling.)reST";
448
449static const char AttrDoc_AnyX86Interrupt[] = R"reST(Clang supports the GNU style ``__attribute__((interrupt))`` attribute on X86
450targets. This attribute may be attached to a function definition and instructs
451the backend to generate appropriate function entry/exit code so that it can be
452used directly as an interrupt service routine.
453
454Interrupt handlers have access to the stack frame pushed onto the stack by the processor,
455and return using the ``IRET`` instruction. All registers in an interrupt handler are callee-saved.
456Exception handlers also have access to the error code pushed onto the stack by the processor,
457when applicable.
458
459An interrupt handler must take the following arguments:
460
461 .. code-block:: c
462
463 __attribute__ ((interrupt))
464 void f (struct stack_frame *frame) {
465 ...
466 }
467
468 Where ``struct stack_frame`` is a suitable struct matching the stack frame pushed by the
469 processor.
470
471An exception handler must take the following arguments:
472
473 .. code-block:: c
474
475 __attribute__ ((interrupt))
476 void g (struct stack_frame *frame, unsigned long code) {
477 ...
478 }
479
480 On 32-bit targets, the ``code`` argument should be of type ``unsigned int``.
481
482Exception handlers should only be used when an error code is pushed by the processor.
483Using the incorrect handler type will crash the system.
484
485Interrupt and exception handlers cannot be called by other functions and must have return type ``void``.
486
487Interrupt and exception handlers should only call functions with the 'no_caller_saved_registers'
488attribute, or should be compiled with the '-mgeneral-regs-only' flag to avoid saving unused
489non-GPR registers.)reST";
490
491static const char AttrDoc_AnyX86NoCallerSavedRegisters[] = R"reST(Use this attribute to indicate that the specified function has no
492caller-saved registers. That is, all registers are callee-saved except for
493registers used for passing parameters to the function or returning parameters
494from the function.
495The compiler saves and restores any modified registers that were not used for
496passing or returning arguments to the function.
497
498The user can call functions specified with the 'no_caller_saved_registers'
499attribute from an interrupt handler without saving and restoring all
500call-clobbered registers.
501
502Functions specified with the 'no_caller_saved_registers' attribute should only
503call other functions with the 'no_caller_saved_registers' attribute, or should be
504compiled with the '-mgeneral-regs-only' flag to avoid saving unused non-GPR registers.
505
506Note that 'no_caller_saved_registers' attribute is not a calling convention.
507In fact, it only overrides the decision of which registers should be saved by
508the caller, but not how the parameters are passed from the caller to the callee.
509
510For example:
511
512 .. code-block:: c
513
514 __attribute__ ((no_caller_saved_registers, fastcall))
515 void f (int arg1, int arg2) {
516 ...
517 }
518
519 In this case parameters 'arg1' and 'arg2' will be passed in registers.
520 In this case, on 32-bit x86 targets, the function 'f' will use ECX and EDX as
521 register parameters. However, it will not assume any scratch registers and
522 should save and restore any modified registers except for ECX and EDX.)reST";
523
524static const char AttrDoc_AnyX86NoCfCheck[] = R"reST(Jump Oriented Programming attacks rely on tampering with addresses used by
525indirect call / jmp, e.g. redirect control-flow to non-programmer
526intended bytes in the binary.
527X86 Supports Indirect Branch Tracking (IBT) as part of Control-Flow
528Enforcement Technology (CET). IBT instruments ENDBR instructions used to
529specify valid targets of indirect call / jmp.
530The ``nocf_check`` attribute has two roles:
5311. Appertains to a function - do not add ENDBR instruction at the beginning of
532the function.
5332. Appertains to a function pointer - do not track the target function of this
534pointer (by adding nocf_check prefix to the indirect-call instruction).)reST";
535
536static const char AttrDoc_ArcWeakrefUnavailable[] = R"reST(No documentation.)reST";
537
538static const char AttrDoc_ArgumentWithTypeTag[] = R"reST(Use ``__attribute__((argument_with_type_tag(arg_kind, arg_idx,
539type_tag_idx)))`` on a function declaration to specify that the function
540accepts a type tag that determines the type of some other argument.
541
542This attribute is primarily useful for checking arguments of variadic functions
543(``pointer_with_type_tag`` can be used in most non-variadic cases).
544
545In the attribute prototype above:
546 * ``arg_kind`` is an identifier that should be used when annotating all
547 applicable type tags.
548 * ``arg_idx`` provides the position of a function argument. The expected type of
549 this function argument will be determined by the function argument specified
550 by ``type_tag_idx``. In the code example below, "3" means that the type of the
551 function's third argument will be determined by ``type_tag_idx``.
552 * ``type_tag_idx`` provides the position of a function argument. This function
553 argument will be a type tag. The type tag will determine the expected type of
554 the argument specified by ``arg_idx``. In the code example below, "2" means
555 that the type tag associated with the function's second argument should agree
556 with the type of the argument specified by ``arg_idx``.
557
558For example:
559
560.. code-block:: c++
561
562 int fcntl(int fd, int cmd, ...)
563 __attribute__(( argument_with_type_tag(fcntl,3,2) ));
564 // The function's second argument will be a type tag; this type tag will
565 // determine the expected type of the function's third argument.)reST";
566
567static const char AttrDoc_ArmAgnostic[] = R"reST(The ``__arm_agnostic`` keyword applies to prototyped function types and
568affects the function's calling convention for a given state S. This
569attribute allows the user to describe a function that preserves S, without
570requiring the function to share S with its callers and without making
571the assumption that S exists.
572
573If a function has the ``__arm_agnostic(S)`` attribute and calls a function
574without this attribute, then the function's object code will contain code
575to preserve state S. Otherwise, the function's object code will be the same
576as if it did not have the attribute.
577
578The attribute takes string arguments to describe state S. The supported
579states are:
580
581* ``"sme_za_state"`` for state enabled by PSTATE.ZA, such as ZA and ZT0.
582
583The attribute ``__arm_agnostic("sme_za_state")`` cannot be used in conjunction
584with ``__arm_in(S)``, ``__arm_out(S)``, ``__arm_inout(S)`` or
585``__arm_preserves(S)`` where state S describes state enabled by PSTATE.ZA,
586such as "za" or "zt0".)reST";
587
588static const char AttrDoc_ArmBuiltinAlias[] = R"reST(This attribute is used in the implementation of the ACLE intrinsics.
589It allows the intrinsic functions to
590be declared using the names defined in ACLE, and still be recognized
591as clang builtins equivalent to the underlying name. For example,
592``arm_mve.h`` declares the function ``vaddq_u32`` with
593``__attribute__((__clang_arm_mve_alias(__builtin_arm_mve_vaddq_u32)))``,
594and similarly, one of the type-overloaded declarations of ``vaddq``
595will have the same attribute. This ensures that both functions are
596recognized as that clang builtin, and in the latter case, the choice
597of which builtin to identify the function as can be deferred until
598after overload resolution.
599
600This attribute can only be used to set up the aliases for certain Arm
601intrinsic functions; it is intended for use only inside ``arm_*.h``
602and is not a general mechanism for declaring arbitrary aliases for
603clang builtin functions.
604
605In order to avoid duplicating the attribute definitions for similar
606purpose for other architecture, there is a general form for the
607attribute `clang_builtin_alias`.)reST";
608
609static const char AttrDoc_ArmIn[] = R"reST(The ``__arm_in`` keyword applies to prototyped function types and specifies
610that the function shares a given state S with its caller. For ``__arm_in``, the
611function takes the state S as input and returns with the state S unchanged.
612
613The attribute takes string arguments to instruct the compiler which state
614is shared. The supported states for S are:
615
616* ``"za"`` for Matrix Storage (requires SME)
617
618The attributes ``__arm_in(S)``, ``__arm_out(S)``, ``__arm_inout(S)`` and
619``__arm_preserves(S)`` are all mutually exclusive for the same state S.)reST";
620
621static const char AttrDoc_ArmInOut[] = R"reST(The ``__arm_inout`` keyword applies to prototyped function types and specifies
622that the function shares a given state S with its caller. For ``__arm_inout``,
623the function takes the state S as input and returns new state for S.
624
625The attribute takes string arguments to instruct the compiler which state
626is shared. The supported states for S are:
627
628* ``"za"`` for Matrix Storage (requires SME)
629
630The attributes ``__arm_in(S)``, ``__arm_out(S)``, ``__arm_inout(S)`` and
631``__arm_preserves(S)`` are all mutually exclusive for the same state S.)reST";
632
633static const char AttrDoc_ArmLocallyStreaming[] = R"reST(The ``__arm_locally_streaming`` keyword applies to function declarations
634and specifies that all the statements in the function are executed in
635streaming mode. This means that:
636
637* the function requires that the target processor implements the Scalable Matrix
638 Extension (SME).
639
640* the program automatically puts the machine into streaming mode before
641 executing the statements and automatically restores the previous mode
642 afterwards.
643
644Clang manages PSTATE.SM automatically; it is not the source code's
645responsibility to do this. For example, Clang will emit code to enable
646streaming mode at the start of the function, and disable streaming mode
647at the end of the function.)reST";
648
649static const char AttrDoc_ArmMveStrictPolymorphism[] = R"reST(This attribute is used in the implementation of the ACLE intrinsics for the Arm
650MVE instruction set. It is used to define the vector types used by the MVE
651intrinsics.
652
653Its effect is to modify the behavior of a vector type with respect to function
654overloading. If a candidate function for overload resolution has a parameter
655type with this attribute, then the selection of that candidate function will be
656disallowed if the actual argument can only be converted via a lax vector
657conversion. The aim is to prevent spurious ambiguity in ARM MVE polymorphic
658intrinsics.
659
660.. code-block:: c++
661
662 void overloaded(uint16x8_t vector, uint16_t scalar);
663 void overloaded(int32x4_t vector, int32_t scalar);
664 uint16x8_t myVector;
665 uint16_t myScalar;
666
667 // myScalar is promoted to int32_t as a side effect of the addition,
668 // so if lax vector conversions are considered for myVector, then
669 // the two overloads are equally good (one argument conversion
670 // each). But if the vector has the __clang_arm_mve_strict_polymorphism
671 // attribute, only the uint16x8_t,uint16_t overload will match.
672 overloaded(myVector, myScalar + 1);
673
674However, this attribute does not prohibit lax vector conversions in contexts
675other than overloading.
676
677.. code-block:: c++
678
679 uint16x8_t function();
680
681 // This is still permitted with lax vector conversion enabled, even
682 // if the vector types have __clang_arm_mve_strict_polymorphism
683 int32x4_t result = function();)reST";
684
685static const char AttrDoc_ArmNew[] = R"reST(The ``__arm_new`` keyword applies to function declarations and specifies
686that the function will create a new scope for state S.
687
688The attribute takes string arguments to instruct the compiler for which state
689to create new scope. The supported states for S are:
690
691* ``"za"`` for Matrix Storage (requires SME)
692
693For state ``"za"``, this means that:
694
695* the function requires that the target processor implements the Scalable Matrix
696 Extension (SME).
697
698* the function will commit any lazily saved ZA data.
699
700* the function will create a new ZA context and enable PSTATE.ZA.
701
702* the function will disable PSTATE.ZA (by setting it to 0) before returning.
703
704For ``__arm_new("za")`` functions Clang will set up the ZA context automatically
705on entry to the function and disable it before returning. For example, if ZA is
706in a dormant state Clang will generate the code to commit a lazy-save and set up
707a new ZA state before executing user code.)reST";
708
709static const char AttrDoc_ArmOut[] = R"reST(The ``__arm_out`` keyword applies to prototyped function types and specifies
710that the function shares a given state S with its caller. For ``__arm_out``,
711the function ignores the incoming state for S and returns new state for S.
712
713The attribute takes string arguments to instruct the compiler which state
714is shared. The supported states for S are:
715
716* ``"za"`` for Matrix Storage (requires SME)
717
718The attributes ``__arm_in(S)``, ``__arm_out(S)``, ``__arm_inout(S)`` and
719``__arm_preserves(S)`` are all mutually exclusive for the same state S.)reST";
720
721static const char AttrDoc_ArmPreserves[] = R"reST(The ``__arm_preserves`` keyword applies to prototyped function types and
722specifies that the function does not read a given state S and returns
723with state S unchanged.
724
725The attribute takes string arguments to instruct the compiler which state
726is shared. The supported states for S are:
727
728* ``"za"`` for Matrix Storage (requires SME)
729
730The attributes ``__arm_in(S)``, ``__arm_out(S)``, ``__arm_inout(S)`` and
731``__arm_preserves(S)`` are all mutually exclusive for the same state S.)reST";
732
733static const char AttrDoc_ArmStreaming[] = R"reST(The ``__arm_streaming`` keyword applies to prototyped function types and specifies
734that the function has a "streaming interface". This means that:
735
736* the function requires that the processor implements the Scalable Matrix
737 Extension (SME).
738
739* the function must be entered in streaming mode (that is, with PSTATE.SM
740 set to 1)
741
742* the function must return in streaming mode
743
744Clang manages PSTATE.SM automatically; it is not the source code's
745responsibility to do this. For example, if a non-streaming
746function calls an ``__arm_streaming`` function, Clang generates code
747that switches into streaming mode before calling the function and
748switches back to non-streaming mode on return.)reST";
749
750static const char AttrDoc_ArmStreamingCompatible[] = R"reST(The ``__arm_streaming_compatible`` keyword applies to prototyped function types and
751specifies that the function has a "streaming compatible interface". This
752means that:
753
754* the function may be entered in either non-streaming mode (PSTATE.SM=0) or
755 in streaming mode (PSTATE.SM=1).
756
757* the function must return in the same mode as it was entered.
758
759* the code executed in the function is compatible with either mode.
760
761Clang manages PSTATE.SM automatically; it is not the source code's
762responsibility to do this. Clang will ensure that the generated code in
763streaming-compatible functions is valid in either mode (PSTATE.SM=0 or
764PSTATE.SM=1). For example, if an ``__arm_streaming_compatible`` function calls a
765non-streaming function, Clang generates code to temporarily switch out of streaming
766mode before calling the function and switch back to streaming-mode on return if
767``PSTATE.SM`` is ``1`` on entry of the caller. If ``PSTATE.SM`` is ``0`` on
768entry to the ``__arm_streaming_compatible`` function, the call will be executed
769without changing modes.)reST";
770
771static const char AttrDoc_Artificial[] = R"reST(The ``artificial`` attribute can be applied to an inline function. If such a
772function is inlined, the attribute indicates that debuggers should associate
773the resulting instructions with the call site, rather than with the
774corresponding line within the inlined callee.)reST";
775
776static const char AttrDoc_AsmLabel[] = R"reST(This attribute can be used on a function or variable to specify its symbol name.
777
778On some targets, all C symbols are prefixed by default with a single character,
779typically ``_``. This was done historically to distinguish them from symbols
780used by other languages. (This prefix is also added to the standard Itanium
781C++ ABI prefix on "mangled" symbol names, so that e.g. on such targets the true
782symbol name for a C++ variable declared as ``int cppvar;`` would be
783``__Z6cppvar``; note the two underscores.) This prefix is *not* added to the
784symbol names specified by the ``asm`` attribute; programmers wishing to match a
785C symbol name must compensate for this.
786
787For example, consider the following C code:
788
789.. code-block:: c
790
791 int var1 asm("altvar") = 1; // "altvar" in symbol table.
792 int var2 = 1; // "_var2" in symbol table.
793
794 void func1(void) asm("altfunc");
795 void func1(void) {} // "altfunc" in symbol table.
796 void func2(void) {} // "_func2" in symbol table.
797
798Clang's implementation of this attribute is compatible with GCC's, `documented here <https://gcc.gnu.org/onlinedocs/gcc/Asm-Labels.html>`_.
799
800While it is possible to use this attribute to name a special symbol used
801internally by the compiler, such as an LLVM intrinsic, this is neither
802recommended nor supported and may cause the compiler to crash or miscompile.
803Users who wish to gain access to intrinsic behavior are strongly encouraged to
804request new builtin functions.)reST";
805
806static const char AttrDoc_AssertCapability[] = R"reST(Marks a function that dynamically tests whether a capability is held, and halts
807the program if it is not held.)reST";
808
809static const char AttrDoc_AssumeAligned[] = R"reST(Use ``__attribute__((assume_aligned(<alignment>[,<offset>]))`` on a function
810declaration to specify that the return value of the function (which must be a
811pointer type) has the specified offset, in bytes, from an address with the
812specified alignment. The offset is taken to be zero if omitted.
813
814.. code-block:: c++
815
816 // The returned pointer value has 32-byte alignment.
817 void *a() __attribute__((assume_aligned (32)));
818
819 // The returned pointer value is 4 bytes greater than an address having
820 // 32-byte alignment.
821 void *b() __attribute__((assume_aligned (32, 4)));
822
823Note that this attribute provides information to the compiler regarding a
824condition that the code already ensures is true. It does not cause the compiler
825to enforce the provided alignment assumption.)reST";
826
827static const char AttrDoc_Atomic[] = R"reST(The ``atomic`` attribute can be applied to *compound statements* to override or
828further specify the default atomic code-generation behavior, especially on
829targets such as AMDGPU. You can annotate compound statements with options
830to modify how atomic instructions inside that statement are emitted at the IR
831level.
832
833For details, see the documentation for `@atomic
834<http://clang.llvm.org/docs/LanguageExtensions.html#extensions-for-controlling-atomic-code-generation>`_)reST";
835
836static const char AttrDoc_Availability[] = R"reST(The ``availability`` attribute can be placed on declarations to describe the
837lifecycle of that declaration relative to operating system versions. Consider
838the function declaration for a hypothetical function ``f``:
839
840.. code-block:: c++
841
842 void f(void) __attribute__((availability(macos,introduced=10.4,deprecated=10.6,obsoleted=10.7)));
843
844The availability attribute states that ``f`` was introduced in macOS 10.4,
845deprecated in macOS 10.6, and obsoleted in macOS 10.7. This information
846is used by Clang to determine when it is safe to use ``f``: for example, if
847Clang is instructed to compile code for macOS 10.5, a call to ``f()``
848succeeds. If Clang is instructed to compile code for macOS 10.6, the call
849succeeds but Clang emits a warning specifying that the function is deprecated.
850Finally, if Clang is instructed to compile code for macOS 10.7, the call
851fails because ``f()`` is no longer available.
852
853Clang is instructed to compile code for a minimum deployment version using
854the ``-target`` or ``-mtargetos`` command line arguments. For example,
855macOS 10.7 would be specified as ``-target x86_64-apple-macos10.7`` or
856``-mtargetos=macos10.7``. Variants like Mac Catalyst are specified as
857``-target arm64-apple-ios15.0-macabi`` or ``-mtargetos=ios15.0-macabi``
858
859The availability attribute is a comma-separated list starting with the
860platform name and then including clauses specifying important milestones in the
861declaration's lifetime (in any order) along with additional information. Those
862clauses can be:
863
864introduced=\ *version*
865 The first version in which this declaration was introduced.
866
867deprecated=\ *version*
868 The first version in which this declaration was deprecated, meaning that
869 users should migrate away from this API.
870
871obsoleted=\ *version*
872 The first version in which this declaration was obsoleted, meaning that it
873 was removed completely and can no longer be used.
874
875unavailable
876 This declaration is never available on this platform.
877
878message=\ *string-literal*
879 Additional message text that Clang will provide when emitting a warning or
880 error about use of a deprecated or obsoleted declaration. Useful to direct
881 users to replacement APIs.
882
883replacement=\ *string-literal*
884 Additional message text that Clang will use to provide Fix-It when emitting
885 a warning about use of a deprecated declaration. The Fix-It will replace
886 the deprecated declaration with the new declaration specified.
887
888environment=\ *identifier*
889 Target environment in which this declaration is available. If present,
890 the availability attribute applies only to targets with the same platform
891 and environment. The parameter is currently supported only in HLSL.
892
893Multiple availability attributes can be placed on a declaration, which may
894correspond to different platforms. For most platforms, the availability
895attribute with the platform corresponding to the target platform will be used;
896any others will be ignored. However, the availability for ``watchOS`` and
897``tvOS`` can be implicitly inferred from an ``iOS`` availability attribute.
898Any explicit availability attributes for those platforms are still preferred over
899the implicitly inferred availability attributes. If no availability attribute
900specifies availability for the current target platform, the availability
901attributes are ignored. Supported platforms are:
902
903``iOS``
904``macOS``
905``tvOS``
906``watchOS``
907``iOSApplicationExtension``
908``macOSApplicationExtension``
909``tvOSApplicationExtension``
910``watchOSApplicationExtension``
911``macCatalyst``
912``macCatalystApplicationExtension``
913``visionOS``
914``visionOSApplicationExtension``
915``driverkit``
916``swift``
917``android``
918``fuchsia``
919``ohos``
920``zos``
921``ShaderModel``
922
923Some platforms have alias names:
924
925``ios``
926``macos``
927``macosx (deprecated)``
928``tvos``
929``watchos``
930``ios_app_extension``
931``macos_app_extension``
932``macosx_app_extension (deprecated)``
933``tvos_app_extension``
934``watchos_app_extension``
935``maccatalyst``
936``maccatalyst_app_extension``
937``visionos``
938``visionos_app_extension``
939``shadermodel``
940
941Supported environment names for the ShaderModel platform:
942
943``pixel``
944``vertex``
945``geometry``
946``hull``
947``domain``
948``compute``
949``raygeneration``
950``intersection``
951``anyhit``
952``closesthit``
953``miss``
954``callable``
955``mesh``
956``amplification``
957``library``
958
959A declaration can typically be used even when deploying back to a platform
960version prior to when the declaration was introduced. When this happens, the
961declaration is `weakly linked
962<https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPFrameworks/Concepts/WeakLinking.html>`_,
963as if the ``weak_import`` attribute were added to the declaration. A
964weakly-linked declaration may or may not be present a run-time, and a program
965can determine whether the declaration is present by checking whether the
966address of that declaration is non-NULL.
967
968The flag ``strict`` disallows using API when deploying back to a
969platform version prior to when the declaration was introduced. An
970attempt to use such API before its introduction causes a hard error.
971Weakly-linking is almost always a better API choice, since it allows
972users to query availability at runtime.
973
974If there are multiple declarations of the same entity, the availability
975attributes must either match on a per-platform basis or later
976declarations must not have availability attributes for that
977platform. For example:
978
979.. code-block:: c
980
981 void g(void) __attribute__((availability(macos,introduced=10.4)));
982 void g(void) __attribute__((availability(macos,introduced=10.4))); // okay, matches
983 void g(void) __attribute__((availability(ios,introduced=4.0))); // okay, adds a new platform
984 void g(void); // okay, inherits both macos and ios availability from above.
985 void g(void) __attribute__((availability(macos,introduced=10.5))); // error: mismatch
986
987When one method overrides another, the overriding method can be more widely available than the overridden method, e.g.,:
988
989.. code-block:: objc
990
991 @interface A
992 - (id)method __attribute__((availability(macos,introduced=10.4)));
993 - (id)method2 __attribute__((availability(macos,introduced=10.4)));
994 @end
995
996 @interface B : A
997 - (id)method __attribute__((availability(macos,introduced=10.3))); // okay: method moved into base class later
998 - (id)method __attribute__((availability(macos,introduced=10.5))); // error: this method was available via the base class in 10.4
999 @end
1000
1001Starting with the macOS 10.12 SDK, the ``API_AVAILABLE`` macro from
1002``<os/availability.h>`` can simplify the spelling:
1003
1004.. code-block:: objc
1005
1006 @interface A
1007 - (id)method API_AVAILABLE(macos(10.11)));
1008 - (id)otherMethod API_AVAILABLE(macos(10.11), ios(11.0));
1009 @end
1010
1011Availability attributes can also be applied using a ``#pragma clang attribute``.
1012Any explicit availability attribute whose platform corresponds to the target
1013platform is applied to a declaration regardless of the availability attributes
1014specified in the pragma. For example, in the code below,
1015``hasExplicitAvailabilityAttribute`` will use the ``macOS`` availability
1016attribute that is specified with the declaration, whereas
1017``getsThePragmaAvailabilityAttribute`` will use the ``macOS`` availability
1018attribute that is applied by the pragma.
1019
1020.. code-block:: c
1021
1022 #pragma clang attribute push (__attribute__((availability(macOS, introduced=10.12))), apply_to=function)
1023 void getsThePragmaAvailabilityAttribute(void);
1024 void hasExplicitAvailabilityAttribute(void) __attribute__((availability(macos,introduced=10.4)));
1025 #pragma clang attribute pop
1026
1027For platforms like ``watchOS`` and ``tvOS``, whose availability attributes can
1028be implicitly inferred from an ``iOS`` availability attribute, the logic is
1029slightly more complex. The explicit and the pragma-applied availability
1030attributes whose platform corresponds to the target platform are applied as
1031described in the previous paragraph. However, the implicitly inferred attributes
1032are applied to a declaration only when there is no explicit or pragma-applied
1033availability attribute whose platform corresponds to the target platform. For
1034example, the function below will receive the ``tvOS`` availability from the
1035pragma rather than using the inferred ``iOS`` availability from the declaration:
1036
1037.. code-block:: c
1038
1039 #pragma clang attribute push (__attribute__((availability(tvOS, introduced=12.0))), apply_to=function)
1040 void getsThePragmaTVOSAvailabilityAttribute(void) __attribute__((availability(iOS,introduced=11.0)));
1041 #pragma clang attribute pop
1042
1043The compiler is also able to apply implicitly inferred attributes from a pragma
1044as well. For example, when targeting ``tvOS``, the function below will receive
1045a ``tvOS`` availability attribute that is implicitly inferred from the ``iOS``
1046availability attribute applied by the pragma:
1047
1048.. code-block:: c
1049
1050 #pragma clang attribute push (__attribute__((availability(iOS, introduced=12.0))), apply_to=function)
1051 void infersTVOSAvailabilityFromPragma(void);
1052 #pragma clang attribute pop
1053
1054The implicit attributes that are inferred from explicitly specified attributes
1055whose platform corresponds to the target platform are applied to the declaration
1056even if there is an availability attribute that can be inferred from a pragma.
1057For example, the function below will receive the ``tvOS, introduced=11.0``
1058availability that is inferred from the attribute on the declaration rather than
1059inferring availability from the pragma:
1060
1061.. code-block:: c
1062
1063 #pragma clang attribute push (__attribute__((availability(iOS, unavailable))), apply_to=function)
1064 void infersTVOSAvailabilityFromAttributeNextToDeclaration(void)
1065 __attribute__((availability(iOS,introduced=11.0)));
1066 #pragma clang attribute pop
1067
1068Also see the documentation for `@available
1069<http://clang.llvm.org/docs/LanguageExtensions.html#objective-c-available>`_)reST";
1070
1071static const char AttrDoc_AvailableOnlyInDefaultEvalMethod[] = R"reST(No documentation.)reST";
1072
1073static const char AttrDoc_BPFFastCall[] = R"reST(Functions annotated with this attribute are likely to be inlined by BPF JIT.
1074It is assumed that inlined implementation uses less caller saved registers,
1075than a regular function.
1076Specifically, the following registers are likely to be preserved:
1077- ``R0`` if function return value is ``void``;
1078- ``R2-R5` if function takes 1 argument;
1079- ``R3-R5` if function takes 2 arguments;
1080- ``R4-R5` if function takes 3 arguments;
1081- ``R5`` if function takes 4 arguments;
1082
1083For such functions Clang generates code pattern that allows BPF JIT
1084to recognize and remove unnecessary spills and fills of the preserved
1085registers.)reST";
1086
1087static const char AttrDoc_BPFPreserveAccessIndex[] = R"reST(Clang supports the ``__attribute__((preserve_access_index))``
1088attribute for the BPF target. This attribute may be attached to a
1089struct or union declaration, where if -g is specified, it enables
1090preserving struct or union member access debuginfo indices of this
1091struct or union, similar to clang ``__builtin_preserve_access_index()``.)reST";
1092
1093static const char AttrDoc_BPFPreserveStaticOffset[] = R"reST(Clang supports the ``__attribute__((preserve_static_offset))``
1094attribute for the BPF target. This attribute may be attached to a
1095struct or union declaration. Reading or writing fields of types having
1096such annotation is guaranteed to generate LDX/ST/STX instruction with
1097offset corresponding to the field.
1098
1099For example:
1100
1101.. code-block:: c
1102
1103 struct foo {
1104 int a;
1105 int b;
1106 };
1107
1108 struct bar {
1109 int a;
1110 struct foo b;
1111 } __attribute__((preserve_static_offset));
1112
1113 void buz(struct bar *g) {
1114 g->b.a = 42;
1115 }
1116
1117The assignment to ``g``'s field would produce an ST instruction with
1118offset 8: ``*(u32)(r1 + 8) = 42;``.
1119
1120Without this attribute generated instructions might be different,
1121depending on optimizations behavior. E.g. the example above could be
1122rewritten as ``r1 += 8; *(u32)(r1 + 0) = 42;``.)reST";
1123
1124static const char AttrDoc_BTFDeclTag[] = R"reST(Clang supports the ``__attribute__((btf_decl_tag("ARGUMENT")))`` attribute for
1125all targets. This attribute may be attached to a struct/union, struct/union
1126field, function, function parameter, variable or typedef declaration. If -g is
1127specified, the ``ARGUMENT`` info will be preserved in IR and be emitted to
1128dwarf. For BPF targets, the ``ARGUMENT`` info will be emitted to .BTF ELF
1129section too.)reST";
1130
1131static const char AttrDoc_BTFTypeTag[] = R"reST(Clang supports the ``__attribute__((btf_type_tag("ARGUMENT")))`` attribute for
1132all targets. It only has effect when ``-g`` is specified on the command line and
1133is currently silently ignored when not applied to a pointer type (note: this
1134scenario may be diagnosed in the future).
1135
1136The ``ARGUMENT`` string will be preserved in IR and emitted to DWARF for the
1137types used in variable declarations, function declarations, or typedef
1138declarations.
1139
1140For BPF targets, the ``ARGUMENT`` string will also be emitted to .BTF ELF
1141section.)reST";
1142
1143static const char AttrDoc_Blocking[] = R"reST(Declares that a function potentially blocks, and prevents any potential inference of ``nonblocking``
1144by the compiler.)reST";
1145
1146static const char AttrDoc_Blocks[] = R"reST(No documentation.)reST";
1147
1148static const char AttrDoc_Builtin[] = R"reST()reST";
1149
1150static const char AttrDoc_BuiltinAlias[] = R"reST(This attribute is used in the implementation of the C intrinsics.
1151It allows the C intrinsic functions to be declared using the names defined
1152in target builtins, and still be recognized as clang builtins equivalent to the
1153underlying name. For example, ``riscv_vector.h`` declares the function ``vadd``
1154with ``__attribute__((clang_builtin_alias(__builtin_rvv_vadd_vv_i8m1)))``.
1155This ensures that both functions are recognized as that clang builtin,
1156and in the latter case, the choice of which builtin to identify the
1157function as can be deferred until after overload resolution.
1158
1159This attribute can only be used to set up the aliases for certain ARM/RISC-V
1160C intrinsic functions; it is intended for use only inside ``arm_*.h`` and
1161``riscv_*.h`` and is not a general mechanism for declaring arbitrary aliases
1162for clang builtin functions.)reST";
1163
1164static const char AttrDoc_C11NoReturn[] = R"reST(A function declared as ``_Noreturn`` shall not return to its caller. The
1165compiler will generate a diagnostic for a function declared as ``_Noreturn``
1166that appears to be capable of returning to its caller. Despite being a type
1167specifier, the ``_Noreturn`` attribute cannot be specified on a function
1168pointer type.)reST";
1169
1170static const char AttrDoc_CDecl[] = R"reST(No documentation.)reST";
1171
1172static const char AttrDoc_CFAuditedTransfer[] = R"reST(No documentation.)reST";
1173
1174static const char AttrDoc_CFConsumed[] = R"reST(The behavior of a function with respect to reference counting for Foundation
1175(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
1176convention (e.g. functions starting with "get" are assumed to return at
1177``+0``).
1178
1179It can be overridden using a family of the following attributes. In
1180Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
1181a function communicates that the object is returned at ``+1``, and the caller
1182is responsible for freeing it.
1183Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
1184specifies that the object is returned at ``+0`` and the ownership remains with
1185the callee.
1186The annotation ``__attribute__((ns_consumes_self))`` specifies that
1187the Objective-C method call consumes the reference to ``self``, e.g. by
1188attaching it to a supplied parameter.
1189Additionally, parameters can have an annotation
1190``__attribute__((ns_consumed))``, which specifies that passing an owned object
1191as that parameter effectively transfers the ownership, and the caller is no
1192longer responsible for it.
1193These attributes affect code generation when interacting with ARC code, and
1194they are used by the Clang Static Analyzer.
1195
1196In C programs using CoreFoundation, a similar set of attributes:
1197``__attribute__((cf_returns_not_retained))``,
1198``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
1199have the same respective semantics when applied to CoreFoundation objects.
1200These attributes affect code generation when interacting with ARC code, and
1201they are used by the Clang Static Analyzer.
1202
1203Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
1204the same attribute family is present:
1205``__attribute__((os_returns_not_retained))``,
1206``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
1207with the same respective semantics.
1208Similar to ``__attribute__((ns_consumes_self))``,
1209``__attribute__((os_consumes_this))`` specifies that the method call consumes
1210the reference to "this" (e.g., when attaching it to a different object supplied
1211as a parameter).
1212Out parameters (parameters the function is meant to write into,
1213either via pointers-to-pointers or references-to-pointers)
1214may be annotated with ``__attribute__((os_returns_retained))``
1215or ``__attribute__((os_returns_not_retained))`` which specifies that the object
1216written into the out parameter should (or respectively should not) be released
1217after use.
1218Since often out parameters may or may not be written depending on the exit
1219code of the function,
1220annotations ``__attribute__((os_returns_retained_on_zero))``
1221and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
1222an out parameter at ``+1`` is written if and only if the function returns a zero
1223(respectively non-zero) error code.
1224Observe that return-code-dependent out parameter annotations are only
1225available for retained out parameters, as non-retained object do not have to be
1226released by the callee.
1227These attributes are only used by the Clang Static Analyzer.
1228
1229The family of attributes ``X_returns_X_retained`` can be added to functions,
1230C++ methods, and Objective-C methods and properties.
1231Attributes ``X_consumed`` can be added to parameters of methods, functions,
1232and Objective-C methods.)reST";
1233
1234static const char AttrDoc_CFGuard[] = R"reST(Code can indicate CFG checks are not wanted with the ``__declspec(guard(nocf))``
1235attribute. This directs the compiler to not insert any CFG checks for the entire
1236function. This approach is typically used only sparingly in specific situations
1237where the programmer has manually inserted "CFG-equivalent" protection. The
1238programmer knows that they are calling through some read-only function table
1239whose address is obtained through read-only memory references and for which the
1240index is masked to the function table limit. This approach may also be applied
1241to small wrapper functions that are not inlined and that do nothing more than
1242make a call through a function pointer. Since incorrect usage of this directive
1243can compromise the security of CFG, the programmer must be very careful using
1244the directive. Typically, this usage is limited to very small functions that
1245only call one function.
1246
1247`Control Flow Guard documentation <https://docs.microsoft.com/en-us/windows/win32/secbp/pe-metadata>`)reST";
1248
1249static const char AttrDoc_CFICanonicalJumpTable[] = R"reST(Use ``__attribute__((cfi_canonical_jump_table))`` on a function declaration to
1250make the function's CFI jump table canonical. See :ref:`the CFI documentation
1251<cfi-canonical-jump-tables>` for more details.)reST";
1252
1253static const char AttrDoc_CFIUncheckedCallee[] = R"reST(``cfi_unchecked_callee`` is a function type attribute which prevents the compiler from instrumenting
1254`Control Flow Integrity <https://clang.llvm.org/docs/ControlFlowIntegrity.html>`_ checks on indirect
1255function calls. Specifically, the attribute has the following semantics:
1256
12571. Indirect calls to a function type with this attribute will not be instrumented with CFI. That is,
1258 the indirect call will not be checked. Note that this only changes the behavior for indirect calls
1259 on pointers to function types having this attribute. It does not prevent all indirect function calls
1260 for a given type from being checked.
12612. All direct references to a function whose type has this attribute will always reference the
1262 function definition rather than an entry in the CFI jump table.
12633. When a pointer to a function with this attribute is implicitly cast to a pointer to a function
1264 without this attribute, the compiler will give a warning saying this attribute is discarded. This
1265 warning can be silenced with an explicit cast. Note an explicit cast just disables the warning, so
1266 direct references to a function with a ``cfi_unchecked_callee`` attribute will still reference the
1267 function definition rather than the CFI jump table.
1268
1269.. code-block:: c
1270
1271 #define CFI_UNCHECKED_CALLEE __attribute__((cfi_unchecked_callee))
1272
1273 void no_cfi() CFI_UNCHECKED_CALLEE {}
1274
1275 void (*with_cfi)() = no_cfi; // warning: implicit conversion discards `cfi_unchecked_callee` attribute.
1276 // `with_cfi` also points to the actual definition of `no_cfi` rather than
1277 // its jump table entry.
1278
1279 void invoke(void (CFI_UNCHECKED_CALLEE *func)()) {
1280 func(); // CFI will not instrument this indirect call.
1281
1282 void (*func2)() = func; // warning: implicit conversion discards `cfi_unchecked_callee` attribute.
1283
1284 func2(); // CFI will instrument this indirect call. Users should be careful however because if this
1285 // references a function with type `cfi_unchecked_callee`, then the CFI check may incorrectly
1286 // fail because the reference will be to the function definition rather than the CFI jump
1287 // table entry.
1288 }
1289
1290This attribute can only be applied on functions or member functions. This attribute can be a good
1291alternative to ``no_sanitize("cfi")`` if you only want to disable innstrumentation for specific indirect
1292calls rather than applying ``no_sanitize("cfi")`` on the whole function containing indirect call. Note
1293that ``cfi_unchecked_attribute`` is a type attribute doesn't disable CFI instrumentation on a function
1294body.)reST";
1295
1296static const char AttrDoc_CFReturnsNotRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
1297(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
1298convention (e.g. functions starting with "get" are assumed to return at
1299``+0``).
1300
1301It can be overridden using a family of the following attributes. In
1302Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
1303a function communicates that the object is returned at ``+1``, and the caller
1304is responsible for freeing it.
1305Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
1306specifies that the object is returned at ``+0`` and the ownership remains with
1307the callee.
1308The annotation ``__attribute__((ns_consumes_self))`` specifies that
1309the Objective-C method call consumes the reference to ``self``, e.g. by
1310attaching it to a supplied parameter.
1311Additionally, parameters can have an annotation
1312``__attribute__((ns_consumed))``, which specifies that passing an owned object
1313as that parameter effectively transfers the ownership, and the caller is no
1314longer responsible for it.
1315These attributes affect code generation when interacting with ARC code, and
1316they are used by the Clang Static Analyzer.
1317
1318In C programs using CoreFoundation, a similar set of attributes:
1319``__attribute__((cf_returns_not_retained))``,
1320``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
1321have the same respective semantics when applied to CoreFoundation objects.
1322These attributes affect code generation when interacting with ARC code, and
1323they are used by the Clang Static Analyzer.
1324
1325Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
1326the same attribute family is present:
1327``__attribute__((os_returns_not_retained))``,
1328``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
1329with the same respective semantics.
1330Similar to ``__attribute__((ns_consumes_self))``,
1331``__attribute__((os_consumes_this))`` specifies that the method call consumes
1332the reference to "this" (e.g., when attaching it to a different object supplied
1333as a parameter).
1334Out parameters (parameters the function is meant to write into,
1335either via pointers-to-pointers or references-to-pointers)
1336may be annotated with ``__attribute__((os_returns_retained))``
1337or ``__attribute__((os_returns_not_retained))`` which specifies that the object
1338written into the out parameter should (or respectively should not) be released
1339after use.
1340Since often out parameters may or may not be written depending on the exit
1341code of the function,
1342annotations ``__attribute__((os_returns_retained_on_zero))``
1343and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
1344an out parameter at ``+1`` is written if and only if the function returns a zero
1345(respectively non-zero) error code.
1346Observe that return-code-dependent out parameter annotations are only
1347available for retained out parameters, as non-retained object do not have to be
1348released by the callee.
1349These attributes are only used by the Clang Static Analyzer.
1350
1351The family of attributes ``X_returns_X_retained`` can be added to functions,
1352C++ methods, and Objective-C methods and properties.
1353Attributes ``X_consumed`` can be added to parameters of methods, functions,
1354and Objective-C methods.)reST";
1355
1356static const char AttrDoc_CFReturnsRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
1357(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
1358convention (e.g. functions starting with "get" are assumed to return at
1359``+0``).
1360
1361It can be overridden using a family of the following attributes. In
1362Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
1363a function communicates that the object is returned at ``+1``, and the caller
1364is responsible for freeing it.
1365Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
1366specifies that the object is returned at ``+0`` and the ownership remains with
1367the callee.
1368The annotation ``__attribute__((ns_consumes_self))`` specifies that
1369the Objective-C method call consumes the reference to ``self``, e.g. by
1370attaching it to a supplied parameter.
1371Additionally, parameters can have an annotation
1372``__attribute__((ns_consumed))``, which specifies that passing an owned object
1373as that parameter effectively transfers the ownership, and the caller is no
1374longer responsible for it.
1375These attributes affect code generation when interacting with ARC code, and
1376they are used by the Clang Static Analyzer.
1377
1378In C programs using CoreFoundation, a similar set of attributes:
1379``__attribute__((cf_returns_not_retained))``,
1380``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
1381have the same respective semantics when applied to CoreFoundation objects.
1382These attributes affect code generation when interacting with ARC code, and
1383they are used by the Clang Static Analyzer.
1384
1385Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
1386the same attribute family is present:
1387``__attribute__((os_returns_not_retained))``,
1388``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
1389with the same respective semantics.
1390Similar to ``__attribute__((ns_consumes_self))``,
1391``__attribute__((os_consumes_this))`` specifies that the method call consumes
1392the reference to "this" (e.g., when attaching it to a different object supplied
1393as a parameter).
1394Out parameters (parameters the function is meant to write into,
1395either via pointers-to-pointers or references-to-pointers)
1396may be annotated with ``__attribute__((os_returns_retained))``
1397or ``__attribute__((os_returns_not_retained))`` which specifies that the object
1398written into the out parameter should (or respectively should not) be released
1399after use.
1400Since often out parameters may or may not be written depending on the exit
1401code of the function,
1402annotations ``__attribute__((os_returns_retained_on_zero))``
1403and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
1404an out parameter at ``+1`` is written if and only if the function returns a zero
1405(respectively non-zero) error code.
1406Observe that return-code-dependent out parameter annotations are only
1407available for retained out parameters, as non-retained object do not have to be
1408released by the callee.
1409These attributes are only used by the Clang Static Analyzer.
1410
1411The family of attributes ``X_returns_X_retained`` can be added to functions,
1412C++ methods, and Objective-C methods and properties.
1413Attributes ``X_consumed`` can be added to parameters of methods, functions,
1414and Objective-C methods.)reST";
1415
1416static const char AttrDoc_CFUnknownTransfer[] = R"reST(No documentation.)reST";
1417
1418static const char AttrDoc_CPUDispatch[] = R"reST(The ``cpu_specific`` and ``cpu_dispatch`` attributes are used to define and
1419resolve multiversioned functions. This form of multiversioning provides a
1420mechanism for declaring versions across translation units and manually
1421specifying the resolved function list. A specified CPU defines a set of minimum
1422features that are required for the function to be called. The result of this is
1423that future processors execute the most restrictive version of the function the
1424new processor can execute.
1425
1426In addition, unlike the ICC implementation of this feature, the selection of the
1427version does not consider the manufacturer or microarchitecture of the processor.
1428It tests solely the list of features that are both supported by the specified
1429processor and present in the compiler-rt library. This can be surprising at times,
1430as the runtime processor may be from a completely different manufacturer, as long
1431as it supports the same feature set.
1432
1433This can additionally be surprising, as some processors are indistringuishable from
1434others based on the list of testable features. When this happens, the variant
1435is selected in an unspecified manner.
1436
1437Function versions are defined with ``cpu_specific``, which takes one or more CPU
1438names as a parameter. For example:
1439
1440.. code-block:: c
1441
1442 // Declares and defines the ivybridge version of single_cpu.
1443 __attribute__((cpu_specific(ivybridge)))
1444 void single_cpu(void){}
1445
1446 // Declares and defines the atom version of single_cpu.
1447 __attribute__((cpu_specific(atom)))
1448 void single_cpu(void){}
1449
1450 // Declares and defines both the ivybridge and atom version of multi_cpu.
1451 __attribute__((cpu_specific(ivybridge, atom)))
1452 void multi_cpu(void){}
1453
1454A dispatching (or resolving) function can be declared anywhere in a project's
1455source code with ``cpu_dispatch``. This attribute takes one or more CPU names
1456as a parameter (like ``cpu_specific``). Functions marked with ``cpu_dispatch``
1457are not expected to be defined, only declared. If such a marked function has a
1458definition, any side effects of the function are ignored; trivial function
1459bodies are permissible for ICC compatibility.
1460
1461.. code-block:: c
1462
1463 // Creates a resolver for single_cpu above.
1464 __attribute__((cpu_dispatch(ivybridge, atom)))
1465 void single_cpu(void){}
1466
1467 // Creates a resolver for multi_cpu, but adds a 3rd version defined in another
1468 // translation unit.
1469 __attribute__((cpu_dispatch(ivybridge, atom, sandybridge)))
1470 void multi_cpu(void){}
1471
1472Note that it is possible to have a resolving function that dispatches based on
1473more or fewer options than are present in the program. Specifying fewer will
1474result in the omitted options not being considered during resolution. Specifying
1475a version for resolution that isn't defined in the program will result in a
1476linking failure.
1477
1478It is also possible to specify a CPU name of ``generic`` which will be resolved
1479if the executing processor doesn't satisfy the features required in the CPU
1480name. The behavior of a program executing on a processor that doesn't satisfy
1481any option of a multiversioned function is undefined.)reST";
1482
1483static const char AttrDoc_CPUSpecific[] = R"reST(The ``cpu_specific`` and ``cpu_dispatch`` attributes are used to define and
1484resolve multiversioned functions. This form of multiversioning provides a
1485mechanism for declaring versions across translation units and manually
1486specifying the resolved function list. A specified CPU defines a set of minimum
1487features that are required for the function to be called. The result of this is
1488that future processors execute the most restrictive version of the function the
1489new processor can execute.
1490
1491In addition, unlike the ICC implementation of this feature, the selection of the
1492version does not consider the manufacturer or microarchitecture of the processor.
1493It tests solely the list of features that are both supported by the specified
1494processor and present in the compiler-rt library. This can be surprising at times,
1495as the runtime processor may be from a completely different manufacturer, as long
1496as it supports the same feature set.
1497
1498This can additionally be surprising, as some processors are indistringuishable from
1499others based on the list of testable features. When this happens, the variant
1500is selected in an unspecified manner.
1501
1502Function versions are defined with ``cpu_specific``, which takes one or more CPU
1503names as a parameter. For example:
1504
1505.. code-block:: c
1506
1507 // Declares and defines the ivybridge version of single_cpu.
1508 __attribute__((cpu_specific(ivybridge)))
1509 void single_cpu(void){}
1510
1511 // Declares and defines the atom version of single_cpu.
1512 __attribute__((cpu_specific(atom)))
1513 void single_cpu(void){}
1514
1515 // Declares and defines both the ivybridge and atom version of multi_cpu.
1516 __attribute__((cpu_specific(ivybridge, atom)))
1517 void multi_cpu(void){}
1518
1519A dispatching (or resolving) function can be declared anywhere in a project's
1520source code with ``cpu_dispatch``. This attribute takes one or more CPU names
1521as a parameter (like ``cpu_specific``). Functions marked with ``cpu_dispatch``
1522are not expected to be defined, only declared. If such a marked function has a
1523definition, any side effects of the function are ignored; trivial function
1524bodies are permissible for ICC compatibility.
1525
1526.. code-block:: c
1527
1528 // Creates a resolver for single_cpu above.
1529 __attribute__((cpu_dispatch(ivybridge, atom)))
1530 void single_cpu(void){}
1531
1532 // Creates a resolver for multi_cpu, but adds a 3rd version defined in another
1533 // translation unit.
1534 __attribute__((cpu_dispatch(ivybridge, atom, sandybridge)))
1535 void multi_cpu(void){}
1536
1537Note that it is possible to have a resolving function that dispatches based on
1538more or fewer options than are present in the program. Specifying fewer will
1539result in the omitted options not being considered during resolution. Specifying
1540a version for resolution that isn't defined in the program will result in a
1541linking failure.
1542
1543It is also possible to specify a CPU name of ``generic`` which will be resolved
1544if the executing processor doesn't satisfy the features required in the CPU
1545name. The behavior of a program executing on a processor that doesn't satisfy
1546any option of a multiversioned function is undefined.)reST";
1547
1548static const char AttrDoc_CUDAConstant[] = R"reST(No documentation.)reST";
1549
1550static const char AttrDoc_CUDADevice[] = R"reST(No documentation.)reST";
1551
1552static const char AttrDoc_CUDADeviceBuiltinSurfaceType[] = R"reST(The ``device_builtin_surface_type`` attribute can be applied to a class
1553template when declaring the surface reference. A surface reference variable
1554could be accessed on the host side and, on the device side, might be translated
1555into an internal surface object, which is established through surface bind and
1556unbind runtime APIs.)reST";
1557
1558static const char AttrDoc_CUDADeviceBuiltinTextureType[] = R"reST(The ``device_builtin_texture_type`` attribute can be applied to a class
1559template when declaring the texture reference. A texture reference variable
1560could be accessed on the host side and, on the device side, might be translated
1561into an internal texture object, which is established through texture bind and
1562unbind runtime APIs.)reST";
1563
1564static const char AttrDoc_CUDAGlobal[] = R"reST(No documentation.)reST";
1565
1566static const char AttrDoc_CUDAGridConstant[] = R"reST(The ``__grid_constant__`` attribute can be applied to a ``const``-qualified kernel
1567function argument and allows compiler to take the address of that argument without
1568making a copy. The argument applies to sm_70 or newer GPUs, during compilation
1569with CUDA-11.7(PTX 7.7) or newer, and is ignored otherwise.)reST";
1570
1571static const char AttrDoc_CUDAHost[] = R"reST(No documentation.)reST";
1572
1573static const char AttrDoc_CUDAInvalidTarget[] = R"reST()reST";
1574
1575static const char AttrDoc_CUDALaunchBounds[] = R"reST(No documentation.)reST";
1576
1577static const char AttrDoc_CUDAShared[] = R"reST(No documentation.)reST";
1578
1579static const char AttrDoc_CXX11NoReturn[] = R"reST(A function declared as ``[[noreturn]]`` shall not return to its caller. The
1580compiler will generate a diagnostic for a function declared as ``[[noreturn]]``
1581that appears to be capable of returning to its caller.
1582
1583The ``[[_Noreturn]]`` spelling is deprecated and only exists to ease code
1584migration for code using ``[[noreturn]]`` after including ``<stdnoreturn.h>``.)reST";
1585
1586static const char AttrDoc_CXXAssume[] = R"reST(The ``assume`` attribute is used to indicate to the optimizer that a
1587certain condition is assumed to be true at a certain point in the
1588program. If this condition is violated at runtime, the behavior is
1589undefined. ``assume`` can only be applied to a null statement.
1590
1591Different optimisers are likely to react differently to the presence of
1592this attribute; in some cases, adding ``assume`` may affect performance
1593negatively. It should be used with parsimony and care.
1594
1595Example:
1596
1597.. code-block:: c++
1598
1599 int f(int x, int y) {
1600 [[assume(x == 27)]];
1601 [[assume(x == y)]];
1602 return y + 1; // May be optimised to `return 28`.
1603 })reST";
1604
1605static const char AttrDoc_CallableWhen[] = R"reST(Use ``__attribute__((callable_when(...)))`` to indicate what states a method
1606may be called in. Valid states are unconsumed, consumed, or unknown. Each
1607argument to this attribute must be a quoted string. E.g.:
1608
1609``__attribute__((callable_when("unconsumed", "unknown")))``)reST";
1610
1611static const char AttrDoc_Callback[] = R"reST(The ``callback`` attribute specifies that the annotated function may invoke the
1612specified callback zero or more times. The callback, as well as the passed
1613arguments, are identified by their parameter name or position (starting with
16141!) in the annotated function. The first position in the attribute identifies
1615the callback callee, the following positions declare describe its arguments.
1616The callback callee is required to be callable with the number, and order, of
1617the specified arguments. The index ``0``, or the identifier ``this``, is used to
1618represent an implicit "this" pointer in class methods. If there is no implicit
1619"this" pointer it shall not be referenced. The index '-1', or the name "__",
1620represents an unknown callback callee argument. This can be a value which is
1621not present in the declared parameter list, or one that is, but is potentially
1622inspected, captured, or modified. Parameter names and indices can be mixed in
1623the callback attribute.
1624
1625The ``callback`` attribute, which is directly translated to ``callback``
1626metadata <http://llvm.org/docs/LangRef.html#callback-metadata>, make the
1627connection between the call to the annotated function and the callback callee.
1628This can enable interprocedural optimizations which were otherwise impossible.
1629If a function parameter is mentioned in the ``callback`` attribute, through its
1630position, it is undefined if that parameter is used for anything other than the
1631actual callback. Inspected, captured, or modified parameters shall not be
1632listed in the ``callback`` metadata.
1633
1634Example encodings for the callback performed by ``pthread_create`` are shown
1635below. The explicit attribute annotation indicates that the third parameter
1636(``start_routine``) is called zero or more times by the ``pthread_create`` function,
1637and that the fourth parameter (``arg``) is passed along. Note that the callback
1638behavior of ``pthread_create`` is automatically recognized by Clang. In addition,
1639the declarations of ``__kmpc_fork_teams`` and ``__kmpc_fork_call``, generated for
1640``#pragma omp target teams`` and ``#pragma omp parallel``, respectively, are also
1641automatically recognized as broker functions. Further functions might be added
1642in the future.
1643
1644 .. code-block:: c
1645
1646 __attribute__((callback (start_routine, arg)))
1647 int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
1648 void *(*start_routine) (void *), void *arg);
1649
1650 __attribute__((callback (3, 4)))
1651 int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
1652 void *(*start_routine) (void *), void *arg);)reST";
1653
1654static const char AttrDoc_CalledOnce[] = R"reST(The ``called_once`` attribute specifies that the annotated function or method
1655parameter is invoked exactly once on all execution paths. It only applies
1656to parameters with function-like types, i.e. function pointers or blocks. This
1657concept is particularly useful for asynchronous programs.
1658
1659Clang implements a check for ``called_once`` parameters,
1660``-Wcalled-once-parameter``. It is on by default and finds the following
1661violations:
1662
1663* Parameter is not called at all.
1664
1665* Parameter is called more than once.
1666
1667* Parameter is not called on one of the execution paths.
1668
1669In the latter case, Clang pinpoints the path where parameter is not invoked
1670by showing the control-flow statement where the path diverges.
1671
1672.. code-block:: objc
1673
1674 void fooWithCallback(void (^callback)(void) __attribute__((called_once))) {
1675 if (somePredicate()) {
1676 ...
1677 callback();
1678 } else {
1679 callback(); // OK: callback is called on every path
1680 }
1681 }
1682
1683 void barWithCallback(void (^callback)(void) __attribute__((called_once))) {
1684 if (somePredicate()) {
1685 ...
1686 callback(); // note: previous call is here
1687 }
1688 callback(); // warning: callback is called twice
1689 }
1690
1691 void foobarWithCallback(void (^callback)(void) __attribute__((called_once))) {
1692 if (somePredicate()) { // warning: callback is not called when condition is false
1693 ...
1694 callback();
1695 }
1696 }
1697
1698This attribute is useful for API developers who want to double-check if they
1699implemented their method correctly.)reST";
1700
1701static const char AttrDoc_Capability[] = R"reST(No documentation.)reST";
1702
1703static const char AttrDoc_CapturedRecord[] = R"reST()reST";
1704
1705static const char AttrDoc_CarriesDependency[] = R"reST(The ``carries_dependency`` attribute specifies dependency propagation into and
1706out of functions.
1707
1708When specified on a function or Objective-C method, the ``carries_dependency``
1709attribute means that the return value carries a dependency out of the function,
1710so that the implementation need not constrain ordering upon return from that
1711function. Implementations of the function and its caller may choose to preserve
1712dependencies instead of emitting memory ordering instructions such as fences.
1713
1714Note, this attribute does not change the meaning of the program, but may result
1715in generation of more efficient code.)reST";
1716
1717static const char AttrDoc_Cleanup[] = R"reST(This attribute allows a function to be run when a local variable goes out of
1718scope. The attribute takes the identifier of a function with a parameter type
1719that is a pointer to the type with the attribute.
1720
1721.. code-block:: c
1722
1723 static void foo (int *) { ... }
1724 static void bar (int *) { ... }
1725 void baz (void) {
1726 int x __attribute__((cleanup(foo)));
1727 {
1728 int y __attribute__((cleanup(bar)));
1729 }
1730 }
1731
1732The above example will result in a call to ``bar`` being passed the address of
1733``y`` when ``y`` goes out of scope, then a call to ``foo`` being passed the
1734address of ``x`` when ``x`` goes out of scope. If two or more variables share
1735the same scope, their ``cleanup`` callbacks are invoked in the reverse order
1736the variables were declared in. It is not possible to check the return value
1737(if any) of these ``cleanup`` callback functions.)reST";
1738
1739static const char AttrDoc_ClspvLibclcBuiltin[] = R"reST(Attribute used by `clspv`_ (OpenCL-C to Vulkan SPIR-V compiler) to identify functions coming from `libclc`_ (OpenCL-C builtin library).
1740
1741.. code-block:: c
1742
1743 void __attribute__((clspv_libclc_builtin)) libclc_builtin() {}
1744
1745.. _`clspv`: https://github.com/google/clspv
1746.. _`libclc`: https://libclc.llvm.org)reST";
1747
1748static const char AttrDoc_CmseNSCall[] = R"reST(This attribute declares a non-secure function type. When compiling for secure
1749state, a call to such a function would switch from secure to non-secure state.
1750All non-secure function calls must happen only through a function pointer, and
1751a non-secure function type should only be used as a base type of a pointer.
1752See `ARMv8-M Security Extensions: Requirements on Development
1753Tools - Engineering Specification Documentation
1754<https://developer.arm.com/docs/ecm0359818/latest/>`_ for more information.)reST";
1755
1756static const char AttrDoc_CmseNSEntry[] = R"reST(This attribute declares a function that can be called from non-secure state, or
1757from secure state. Entering from and returning to non-secure state would switch
1758to and from secure state, respectively, and prevent flow of information
1759to non-secure state, except via return values. See `ARMv8-M Security Extensions:
1760Requirements on Development Tools - Engineering Specification Documentation
1761<https://developer.arm.com/docs/ecm0359818/latest/>`_ for more information.)reST";
1762
1763static const char AttrDoc_CodeAlign[] = R"reST(The ``clang::code_align(N)`` attribute applies to a loop and specifies the byte
1764alignment for a loop. The attribute accepts a positive integer constant
1765initialization expression indicating the number of bytes for the minimum
1766alignment boundary. Its value must be a power of 2, between 1 and 4096
1767(inclusive).
1768
1769.. code-block:: c++
1770
1771 void foo() {
1772 int var = 0;
1773 [[clang::code_align(16)]] for (int i = 0; i < 10; ++i) var++;
1774 }
1775
1776 void Array(int *array, size_t n) {
1777 [[clang::code_align(64)]] for (int i = 0; i < n; ++i) array[i] = 0;
1778 }
1779
1780 void count () {
1781 int a1[10], int i = 0;
1782 [[clang::code_align(32)]] while (i < 10) { a1[i] += 3; }
1783 }
1784
1785 void check() {
1786 int a = 10;
1787 [[clang::code_align(8)]] do {
1788 a = a + 1;
1789 } while (a < 20);
1790 }
1791
1792 template<int A>
1793 void func() {
1794 [[clang::code_align(A)]] for(;;) { }
1795 })reST";
1796
1797static const char AttrDoc_CodeModel[] = R"reST(The ``model`` attribute allows overriding the translation unit's
1798code model (specified by ``-mcmodel``) for a specific global variable.
1799
1800On LoongArch, allowed values are "normal", "medium", "extreme".
1801
1802On x86-64, allowed values are ``"small"`` and ``"large"``. ``"small"`` is
1803roughly equivalent to ``-mcmodel=small``, meaning the global is considered
1804"small" placed closer to the ``.text`` section relative to "large" globals, and
1805to prefer using 32-bit relocations to access the global. ``"large"`` is roughly
1806equivalent to ``-mcmodel=large``, meaning the global is considered "large" and
1807placed further from the ``.text`` section relative to "small" globals, and
180864-bit relocations must be used to access the global.)reST";
1809
1810static const char AttrDoc_CodeSeg[] = R"reST(The ``__declspec(code_seg)`` attribute enables the placement of code into separate
1811named segments that can be paged or locked in memory individually. This attribute
1812is used to control the placement of instantiated templates and compiler-generated
1813code. See the documentation for `__declspec(code_seg)`_ on MSDN.
1814
1815.. _`__declspec(code_seg)`: http://msdn.microsoft.com/en-us/library/dn636922.aspx)reST";
1816
1817static const char AttrDoc_Cold[] = R"reST(``__attribute__((cold))`` marks a function as cold, as a manual alternative to PGO hotness data.
1818If PGO data is available, the profile count based hotness overrides the ``__attribute__((cold))`` annotation (unlike ``__attribute__((hot))``).)reST";
1819
1820static const char AttrDoc_Common[] = R"reST(No documentation.)reST";
1821
1822static const char AttrDoc_Const[] = R"reST(No documentation.)reST";
1823
1824static const char AttrDoc_ConstInit[] = R"reST(This attribute specifies that the variable to which it is attached is intended
1825to have a `constant initializer <http://en.cppreference.com/w/cpp/language/constant_initialization>`_
1826according to the rules of [basic.start.static]. The variable is required to
1827have static or thread storage duration. If the initialization of the variable
1828is not a constant initializer an error will be produced. This attribute may
1829only be used in C++; the ``constinit`` spelling is only accepted in C++20
1830onwards.
1831
1832Note that in C++03 strict constant expression checking is not done. Instead
1833the attribute reports if Clang can emit the variable as a constant, even if it's
1834not technically a 'constant initializer'. This behavior is non-portable.
1835
1836Static storage duration variables with constant initializers avoid hard-to-find
1837bugs caused by the indeterminate order of dynamic initialization. They can also
1838be safely used during dynamic initialization across translation units.
1839
1840This attribute acts as a compile time assertion that the requirements
1841for constant initialization have been met. Since these requirements change
1842between dialects and have subtle pitfalls it's important to fail fast instead
1843of silently falling back on dynamic initialization.
1844
1845The first use of the attribute on a variable must be part of, or precede, the
1846initializing declaration of the variable. C++20 requires the ``constinit``
1847spelling of the attribute to be present on the initializing declaration if it
1848is used anywhere. The other spellings can be specified on a forward declaration
1849and omitted on a later initializing declaration.
1850
1851.. code-block:: c++
1852
1853 // -std=c++14
1854 #define SAFE_STATIC [[clang::require_constant_initialization]]
1855 struct T {
1856 constexpr T(int) {}
1857 ~T(); // non-trivial
1858 };
1859 SAFE_STATIC T x = {42}; // Initialization OK. Doesn't check destructor.
1860 SAFE_STATIC T y = 42; // error: variable does not have a constant initializer
1861 // copy initialization is not a constant expression on a non-literal type.)reST";
1862
1863static const char AttrDoc_Constructor[] = R"reST(The ``constructor`` attribute causes the function to be called before entering
1864``main()``, and the ``destructor`` attribute causes the function to be called
1865after returning from ``main()`` or when the ``exit()`` function has been
1866called. Note, ``quick_exit()``, ``_Exit()``, and ``abort()`` prevent a function
1867marked ``destructor`` from being called.
1868
1869The constructor or destructor function should not accept any arguments and its
1870return type should be ``void``.
1871
1872The attributes accept an optional argument used to specify the priority order
1873in which to execute constructor and destructor functions. The priority is
1874given as an integer constant expression between 101 and 65535 (inclusive).
1875Priorities outside of that range are reserved for use by the implementation. A
1876lower value indicates a higher priority of initialization. Note that only the
1877relative ordering of values is important. For example:
1878
1879.. code-block:: c++
1880
1881 __attribute__((constructor(200))) void foo(void);
1882 __attribute__((constructor(101))) void bar(void);
1883
1884``bar()`` will be called before ``foo()``, and both will be called before
1885``main()``. If no argument is given to the ``constructor`` or ``destructor``
1886attribute, they default to the value ``65535``.)reST";
1887
1888static const char AttrDoc_Consumable[] = R"reST(Each ``class`` that uses any of the typestate annotations must first be marked
1889using the ``consumable`` attribute. Failure to do so will result in a warning.
1890
1891This attribute accepts a single parameter that must be one of the following:
1892``unknown``, ``consumed``, or ``unconsumed``.)reST";
1893
1894static const char AttrDoc_ConsumableAutoCast[] = R"reST(No documentation.)reST";
1895
1896static const char AttrDoc_ConsumableSetOnRead[] = R"reST(No documentation.)reST";
1897
1898static const char AttrDoc_Convergent[] = R"reST(The ``convergent`` attribute can be placed on a function declaration. It is
1899translated into the LLVM ``convergent`` attribute, which indicates that the call
1900instructions of a function with this attribute cannot be made control-dependent
1901on any additional values.
1902
1903This attribute is different from ``noduplicate`` because it allows duplicating
1904function calls if it can be proved that the duplicated function calls are
1905not made control-dependent on any additional values, e.g., unrolling a loop
1906executed by all work items.
1907
1908Sample usage:
1909
1910.. code-block:: c
1911
1912 void convfunc(void) __attribute__((convergent));
1913 // Setting it as a C++11 attribute is also valid in a C++ program.
1914 // void convfunc(void) [[clang::convergent]];)reST";
1915
1916static const char AttrDoc_CoroAwaitElidable[] = R"reST(The ``[[clang::coro_await_elidable]]`` is a class attribute which can be
1917applied to a coroutine return type. It provides a hint to the compiler to apply
1918Heap Allocation Elision more aggressively.
1919
1920When a coroutine function returns such a type, a direct call expression therein
1921that returns a prvalue of a type attributed ``[[clang::coro_await_elidable]]``
1922is said to be under a safe elide context if one of the following is true:
1923- it is the immediate right-hand side operand to a co_await expression.
1924- it is an argument to a ``[[clang::coro_await_elidable_argument]]`` parameter
1925or parameter pack of another direct call expression under a safe elide context.
1926
1927Do note that the safe elide context applies only to the call expression itself,
1928and the context does not transitively include any of its subexpressions unless
1929exceptional rules of ``[[clang::coro_await_elidable_argument]]`` apply.
1930
1931The compiler performs heap allocation elision on call expressions under a safe
1932elide context, if the callee is a coroutine.
1933
1934Example:
1935
1936.. code-block:: c++
1937
1938 class [[clang::coro_await_elidable]] Task { ... };
1939
1940 Task foo();
1941 Task bar() {
1942 co_await foo(); // foo()'s coroutine frame on this line is elidable
1943 auto t = foo(); // foo()'s coroutine frame on this line is NOT elidable
1944 co_await t;
1945 }
1946
1947Such elision replaces the heap allocated activation frame of the callee coroutine
1948with a local variable within the enclosing braces in the caller's stack frame.
1949The local variable, like other variables in coroutines, may be collected into the
1950coroutine frame, which may be allocated on the heap. The behavior is undefined
1951if the caller coroutine is destroyed earlier than the callee coroutine.)reST";
1952
1953static const char AttrDoc_CoroAwaitElidableArgument[] = R"reST(The ``[[clang::coro_await_elidable_argument]]`` is a function parameter attribute.
1954It works in conjunction with ``[[clang::coro_await_elidable]]`` to propagate a
1955safe elide context to a parameter or parameter pack if the function is called
1956under a safe elide context.
1957
1958This is sometimes necessary on utility functions used to compose or modify the
1959behavior of a callee coroutine.
1960
1961Example:
1962
1963.. code-block:: c++
1964
1965 template <typename T>
1966 class [[clang::coro_await_elidable]] Task { ... };
1967
1968 template <typename... T>
1969 class [[clang::coro_await_elidable]] WhenAll { ... };
1970
1971 // `when_all` is a utility function that composes coroutines. It does not
1972 // need to be a coroutine to propagate.
1973 template <typename... T>
1974 WhenAll<T...> when_all([[clang::coro_await_elidable_argument]] Task<T> tasks...);
1975
1976 Task<int> foo();
1977 Task<int> bar();
1978 Task<void> example1() {
1979 // `when_all``, `foo``, and `bar` are all elide safe because `when_all` is
1980 // under a safe elide context and, thanks to the [[clang::coro_await_elidable_argument]]
1981 // attribute, such context is propagated to foo and bar.
1982 co_await when_all(foo(), bar());
1983 }
1984
1985 Task<void> example2() {
1986 // `when_all` and `bar` are elide safe. `foo` is not elide safe.
1987 auto f = foo();
1988 co_await when_all(f, bar());
1989 }
1990
1991
1992 Task<void> example3() {
1993 // None of the calls are elide safe.
1994 auto t = when_all(foo(), bar());
1995 co_await t;
1996 })reST";
1997
1998static const char AttrDoc_CoroDisableLifetimeBound[] = R"reST(The ``[[clang::coro_lifetimebound]]`` is a class attribute which can be applied
1999to a coroutine return type (`coro_return_type, coro_wrapper`_) (i.e.
2000it should also be annotated with ``[[clang::coro_return_type]]``).
2001
2002All parameters of a function are considered to be lifetime bound if the function returns a
2003coroutine return type (CRT) annotated with ``[[clang::coro_lifetimebound]]``.
2004This lifetime bound analysis can be disabled for a coroutine wrapper or a coroutine by annotating the function
2005with ``[[clang::coro_disable_lifetimebound]]`` function attribute .
2006See documentation of `lifetimebound`_ for details about lifetime bound analysis.
2007
2008
2009Reference parameters of a coroutine are susceptible to capturing references to temporaries or local variables.
2010
2011For example,
2012
2013.. code-block:: c++
2014
2015 task<int> coro(const int& a) { co_return a + 1; }
2016 task<int> dangling_refs(int a) {
2017 // `coro` captures reference to a temporary. `foo` would now contain a dangling reference to `a`.
2018 auto foo = coro(1);
2019 // `coro` captures reference to local variable `a` which is destroyed after the return.
2020 return coro(a);
2021 }
2022
2023Lifetime bound static analysis can be used to detect such instances when coroutines capture references
2024which may die earlier than the coroutine frame itself. In the above example, if the CRT `task` is annotated with
2025``[[clang::coro_lifetimebound]]``, then lifetime bound analysis would detect capturing reference to
2026temporaries or return address of a local variable.
2027
2028Both coroutines and coroutine wrappers are part of this analysis.
2029
2030.. code-block:: c++
2031
2032 template <typename T> struct [[clang::coro_return_type, clang::coro_lifetimebound]] Task {
2033 using promise_type = some_promise_type;
2034 };
2035
2036 Task<int> coro(const int& a) { co_return a + 1; }
2037 [[clang::coro_wrapper]] Task<int> coro_wrapper(const int& a, const int& b) {
2038 return a > b ? coro(a) : coro(b);
2039 }
2040 Task<int> temporary_reference() {
2041 auto foo = coro(1); // warning: capturing reference to a temporary which would die after the expression.
2042
2043 int a = 1;
2044 auto bar = coro_wrapper(a, 0); // warning: `b` captures reference to a temporary.
2045
2046 co_return co_await coro(1); // fine.
2047 }
2048 [[clang::coro_wrapper]] Task<int> stack_reference(int a) {
2049 return coro(a); // warning: returning address of stack variable `a`.
2050 }
2051
2052This analysis can be disabled for all calls to a particular function by annotating the function
2053with function attribute ``[[clang::coro_disable_lifetimebound]]``.
2054For example, this could be useful for coroutine wrappers which accept reference parameters
2055but do not pass them to the underlying coroutine or pass them by value.
2056
2057.. code-block:: c++
2058
2059 Task<int> coro(int a) { co_return a + 1; }
2060 [[clang::coro_wrapper, clang::coro_disable_lifetimebound]] Task<int> coro_wrapper(const int& a) {
2061 return coro(a + 1);
2062 }
2063 void use() {
2064 auto task = coro_wrapper(1); // use of temporary is fine as the argument is not lifetime bound.
2065 })reST";
2066
2067static const char AttrDoc_CoroLifetimeBound[] = R"reST(The ``[[clang::coro_lifetimebound]]`` is a class attribute which can be applied
2068to a coroutine return type (`coro_return_type, coro_wrapper`_) (i.e.
2069it should also be annotated with ``[[clang::coro_return_type]]``).
2070
2071All parameters of a function are considered to be lifetime bound if the function returns a
2072coroutine return type (CRT) annotated with ``[[clang::coro_lifetimebound]]``.
2073This lifetime bound analysis can be disabled for a coroutine wrapper or a coroutine by annotating the function
2074with ``[[clang::coro_disable_lifetimebound]]`` function attribute .
2075See documentation of `lifetimebound`_ for details about lifetime bound analysis.
2076
2077
2078Reference parameters of a coroutine are susceptible to capturing references to temporaries or local variables.
2079
2080For example,
2081
2082.. code-block:: c++
2083
2084 task<int> coro(const int& a) { co_return a + 1; }
2085 task<int> dangling_refs(int a) {
2086 // `coro` captures reference to a temporary. `foo` would now contain a dangling reference to `a`.
2087 auto foo = coro(1);
2088 // `coro` captures reference to local variable `a` which is destroyed after the return.
2089 return coro(a);
2090 }
2091
2092Lifetime bound static analysis can be used to detect such instances when coroutines capture references
2093which may die earlier than the coroutine frame itself. In the above example, if the CRT `task` is annotated with
2094``[[clang::coro_lifetimebound]]``, then lifetime bound analysis would detect capturing reference to
2095temporaries or return address of a local variable.
2096
2097Both coroutines and coroutine wrappers are part of this analysis.
2098
2099.. code-block:: c++
2100
2101 template <typename T> struct [[clang::coro_return_type, clang::coro_lifetimebound]] Task {
2102 using promise_type = some_promise_type;
2103 };
2104
2105 Task<int> coro(const int& a) { co_return a + 1; }
2106 [[clang::coro_wrapper]] Task<int> coro_wrapper(const int& a, const int& b) {
2107 return a > b ? coro(a) : coro(b);
2108 }
2109 Task<int> temporary_reference() {
2110 auto foo = coro(1); // warning: capturing reference to a temporary which would die after the expression.
2111
2112 int a = 1;
2113 auto bar = coro_wrapper(a, 0); // warning: `b` captures reference to a temporary.
2114
2115 co_return co_await coro(1); // fine.
2116 }
2117 [[clang::coro_wrapper]] Task<int> stack_reference(int a) {
2118 return coro(a); // warning: returning address of stack variable `a`.
2119 }
2120
2121This analysis can be disabled for all calls to a particular function by annotating the function
2122with function attribute ``[[clang::coro_disable_lifetimebound]]``.
2123For example, this could be useful for coroutine wrappers which accept reference parameters
2124but do not pass them to the underlying coroutine or pass them by value.
2125
2126.. code-block:: c++
2127
2128 Task<int> coro(int a) { co_return a + 1; }
2129 [[clang::coro_wrapper, clang::coro_disable_lifetimebound]] Task<int> coro_wrapper(const int& a) {
2130 return coro(a + 1);
2131 }
2132 void use() {
2133 auto task = coro_wrapper(1); // use of temporary is fine as the argument is not lifetime bound.
2134 })reST";
2135
2136static const char AttrDoc_CoroOnlyDestroyWhenComplete[] = R"reST(The `coro_only_destroy_when_complete` attribute should be marked on a C++ class. The coroutines
2137whose return type is marked with the attribute are assumed to be destroyed only after the coroutine has
2138reached the final suspend point.
2139
2140This is helpful for the optimizers to reduce the size of the destroy function for the coroutines.
2141
2142For example,
2143
2144.. code-block:: c++
2145
2146 A foo() {
2147 dtor d;
2148 co_await something();
2149 dtor d1;
2150 co_await something();
2151 dtor d2;
2152 co_return 43;
2153 }
2154
2155The compiler may generate the following pseudocode:
2156
2157.. code-block:: c++
2158
2159 void foo.destroy(foo.Frame *frame) {
2160 switch(frame->suspend_index()) {
2161 case 1:
2162 frame->d.~dtor();
2163 break;
2164 case 2:
2165 frame->d.~dtor();
2166 frame->d1.~dtor();
2167 break;
2168 case 3:
2169 frame->d.~dtor();
2170 frame->d1.~dtor();
2171 frame->d2.~dtor();
2172 break;
2173 default: // coroutine completed or haven't started
2174 break;
2175 }
2176
2177 frame->promise.~promise_type();
2178 delete frame;
2179 }
2180
2181The `foo.destroy()` function's purpose is to release all of the resources
2182initialized for the coroutine when it is destroyed in a suspended state.
2183However, if the coroutine is only ever destroyed at the final suspend state,
2184the rest of the conditions are superfluous.
2185
2186The user can use the `coro_only_destroy_when_complete` attributo suppress
2187generation of the other destruction cases, optimizing the above `foo.destroy` to:
2188
2189.. code-block:: c++
2190
2191 void foo.destroy(foo.Frame *frame) {
2192 frame->promise.~promise_type();
2193 delete frame;
2194 })reST";
2195
2196static const char AttrDoc_CoroReturnType[] = R"reST(The ``[[clang::coro_return_type]]`` attribute is used to help static analyzers to recognize
2197coroutines from the function signatures.
2198
2199The ``coro_return_type`` attribute should be marked on a C++ class to mark it as
2200a **coroutine return type (CRT)**.
2201
2202A function ``R func(P1, .., PN)`` has a coroutine return type (CRT) ``R`` if ``R``
2203is marked by ``[[clang::coro_return_type]]`` and ``R`` has a promise type associated to it
2204(i.e., std::coroutine_traits<R, P1, .., PN>::promise_type is a valid promise type).
2205
2206If the return type of a function is a ``CRT`` then the function must be a coroutine.
2207Otherwise the program is invalid. It is allowed for a non-coroutine to return a ``CRT``
2208if the function is marked with ``[[clang::coro_wrapper]]``.
2209
2210The ``[[clang::coro_wrapper]]`` attribute should be marked on a C++ function to mark it as
2211a **coroutine wrapper**. A coroutine wrapper is a function which returns a ``CRT``,
2212is not a coroutine itself and is marked with ``[[clang::coro_wrapper]]``.
2213
2214Clang will enforce that all functions that return a ``CRT`` are either coroutines or marked
2215with ``[[clang::coro_wrapper]]``. Clang will enforce this with an error.
2216
2217From a language perspective, it is not possible to differentiate between a coroutine and a
2218function returning a CRT by merely looking at the function signature.
2219
2220Coroutine wrappers, in particular, are susceptible to capturing
2221references to temporaries and other lifetime issues. This allows to avoid such lifetime
2222issues with coroutine wrappers.
2223
2224For example,
2225
2226.. code-block:: c++
2227
2228 // This is a CRT.
2229 template <typename T> struct [[clang::coro_return_type]] Task {
2230 using promise_type = some_promise_type;
2231 };
2232
2233 Task<int> increment(int a) { co_return a + 1; } // Fine. This is a coroutine.
2234 Task<int> foo() { return increment(1); } // Error. foo is not a coroutine.
2235
2236 // Fine for a coroutine wrapper to return a CRT.
2237 [[clang::coro_wrapper]] Task<int> foo() { return increment(1); }
2238
2239 void bar() {
2240 // Invalid. This intantiates a function which returns a CRT but is not marked as
2241 // a coroutine wrapper.
2242 std::function<Task<int>(int)> f = increment;
2243 }
2244
2245Note: ``a_promise_type::get_return_object`` is exempted from this analysis as it is a necessary
2246implementation detail of any coroutine library.)reST";
2247
2248static const char AttrDoc_CoroWrapper[] = R"reST(The ``[[clang::coro_return_type]]`` attribute is used to help static analyzers to recognize
2249coroutines from the function signatures.
2250
2251The ``coro_return_type`` attribute should be marked on a C++ class to mark it as
2252a **coroutine return type (CRT)**.
2253
2254A function ``R func(P1, .., PN)`` has a coroutine return type (CRT) ``R`` if ``R``
2255is marked by ``[[clang::coro_return_type]]`` and ``R`` has a promise type associated to it
2256(i.e., std::coroutine_traits<R, P1, .., PN>::promise_type is a valid promise type).
2257
2258If the return type of a function is a ``CRT`` then the function must be a coroutine.
2259Otherwise the program is invalid. It is allowed for a non-coroutine to return a ``CRT``
2260if the function is marked with ``[[clang::coro_wrapper]]``.
2261
2262The ``[[clang::coro_wrapper]]`` attribute should be marked on a C++ function to mark it as
2263a **coroutine wrapper**. A coroutine wrapper is a function which returns a ``CRT``,
2264is not a coroutine itself and is marked with ``[[clang::coro_wrapper]]``.
2265
2266Clang will enforce that all functions that return a ``CRT`` are either coroutines or marked
2267with ``[[clang::coro_wrapper]]``. Clang will enforce this with an error.
2268
2269From a language perspective, it is not possible to differentiate between a coroutine and a
2270function returning a CRT by merely looking at the function signature.
2271
2272Coroutine wrappers, in particular, are susceptible to capturing
2273references to temporaries and other lifetime issues. This allows to avoid such lifetime
2274issues with coroutine wrappers.
2275
2276For example,
2277
2278.. code-block:: c++
2279
2280 // This is a CRT.
2281 template <typename T> struct [[clang::coro_return_type]] Task {
2282 using promise_type = some_promise_type;
2283 };
2284
2285 Task<int> increment(int a) { co_return a + 1; } // Fine. This is a coroutine.
2286 Task<int> foo() { return increment(1); } // Error. foo is not a coroutine.
2287
2288 // Fine for a coroutine wrapper to return a CRT.
2289 [[clang::coro_wrapper]] Task<int> foo() { return increment(1); }
2290
2291 void bar() {
2292 // Invalid. This intantiates a function which returns a CRT but is not marked as
2293 // a coroutine wrapper.
2294 std::function<Task<int>(int)> f = increment;
2295 }
2296
2297Note: ``a_promise_type::get_return_object`` is exempted from this analysis as it is a necessary
2298implementation detail of any coroutine library.)reST";
2299
2300static const char AttrDoc_CountedBy[] = R"reST(Clang supports the ``counted_by`` attribute on the flexible array member of a
2301structure in C. The argument for the attribute is the name of a field member
2302holding the count of elements in the flexible array. This information can be
2303used to improve the results of the array bound sanitizer and the
2304``__builtin_dynamic_object_size`` builtin. The ``count`` field member must be
2305within the same non-anonymous, enclosing struct as the flexible array member.
2306
2307This example specifies that the flexible array member ``array`` has the number
2308of elements allocated for it in ``count``:
2309
2310.. code-block:: c
2311
2312 struct bar;
2313
2314 struct foo {
2315 size_t count;
2316 char other;
2317 struct bar *array[] __attribute__((counted_by(count)));
2318 };
2319
2320This establishes a relationship between ``array`` and ``count``. Specifically,
2321``array`` must have at least ``count`` number of elements available. It's the
2322user's responsibility to ensure that this relationship is maintained through
2323changes to the structure.
2324
2325In the following example, the allocated array erroneously has fewer elements
2326than what's specified by ``p->count``. This would result in an out-of-bounds
2327access not being detected.
2328
2329.. code-block:: c
2330
2331 #define SIZE_INCR 42
2332
2333 struct foo *p;
2334
2335 void foo_alloc(size_t count) {
2336 p = malloc(MAX(sizeof(struct foo),
2337 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
2338 p->count = count + SIZE_INCR;
2339 }
2340
2341The next example updates ``p->count``, but breaks the relationship requirement
2342that ``p->array`` must have at least ``p->count`` number of elements available:
2343
2344.. code-block:: c
2345
2346 #define SIZE_INCR 42
2347
2348 struct foo *p;
2349
2350 void foo_alloc(size_t count) {
2351 p = malloc(MAX(sizeof(struct foo),
2352 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
2353 p->count = count;
2354 }
2355
2356 void use_foo(int index, int val) {
2357 p->count += SIZE_INCR + 1; /* 'count' is now larger than the number of elements of 'array'. */
2358 p->array[index] = val; /* The sanitizer can't properly check this access. */
2359 }
2360
2361In this example, an update to ``p->count`` maintains the relationship
2362requirement:
2363
2364.. code-block:: c
2365
2366 void use_foo(int index, int val) {
2367 if (p->count == 0)
2368 return;
2369 --p->count;
2370 p->array[index] = val;
2371 })reST";
2372
2373static const char AttrDoc_CountedByOrNull[] = R"reST(Clang supports the ``counted_by`` attribute on the flexible array member of a
2374structure in C. The argument for the attribute is the name of a field member
2375holding the count of elements in the flexible array. This information can be
2376used to improve the results of the array bound sanitizer and the
2377``__builtin_dynamic_object_size`` builtin. The ``count`` field member must be
2378within the same non-anonymous, enclosing struct as the flexible array member.
2379
2380This example specifies that the flexible array member ``array`` has the number
2381of elements allocated for it in ``count``:
2382
2383.. code-block:: c
2384
2385 struct bar;
2386
2387 struct foo {
2388 size_t count;
2389 char other;
2390 struct bar *array[] __attribute__((counted_by(count)));
2391 };
2392
2393This establishes a relationship between ``array`` and ``count``. Specifically,
2394``array`` must have at least ``count`` number of elements available. It's the
2395user's responsibility to ensure that this relationship is maintained through
2396changes to the structure.
2397
2398In the following example, the allocated array erroneously has fewer elements
2399than what's specified by ``p->count``. This would result in an out-of-bounds
2400access not being detected.
2401
2402.. code-block:: c
2403
2404 #define SIZE_INCR 42
2405
2406 struct foo *p;
2407
2408 void foo_alloc(size_t count) {
2409 p = malloc(MAX(sizeof(struct foo),
2410 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
2411 p->count = count + SIZE_INCR;
2412 }
2413
2414The next example updates ``p->count``, but breaks the relationship requirement
2415that ``p->array`` must have at least ``p->count`` number of elements available:
2416
2417.. code-block:: c
2418
2419 #define SIZE_INCR 42
2420
2421 struct foo *p;
2422
2423 void foo_alloc(size_t count) {
2424 p = malloc(MAX(sizeof(struct foo),
2425 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
2426 p->count = count;
2427 }
2428
2429 void use_foo(int index, int val) {
2430 p->count += SIZE_INCR + 1; /* 'count' is now larger than the number of elements of 'array'. */
2431 p->array[index] = val; /* The sanitizer can't properly check this access. */
2432 }
2433
2434In this example, an update to ``p->count`` maintains the relationship
2435requirement:
2436
2437.. code-block:: c
2438
2439 void use_foo(int index, int val) {
2440 if (p->count == 0)
2441 return;
2442 --p->count;
2443 p->array[index] = val;
2444 })reST";
2445
2446static const char AttrDoc_DLLExport[] = R"reST(The ``__declspec(dllexport)`` attribute declares a variable, function, or
2447Objective-C interface to be exported from the module. It is available under the
2448``-fdeclspec`` flag for compatibility with various compilers. The primary use
2449is for COFF object files which explicitly specify what interfaces are available
2450for external use. See the dllexport_ documentation on MSDN for more
2451information.
2452
2453.. _dllexport: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx)reST";
2454
2455static const char AttrDoc_DLLExportStaticLocal[] = R"reST()reST";
2456
2457static const char AttrDoc_DLLImport[] = R"reST(The ``__declspec(dllimport)`` attribute declares a variable, function, or
2458Objective-C interface to be imported from an external module. It is available
2459under the ``-fdeclspec`` flag for compatibility with various compilers. The
2460primary use is for COFF object files which explicitly specify what interfaces
2461are imported from external modules. See the dllimport_ documentation on MSDN
2462for more information.
2463
2464Note that a dllimport function may still be inlined, if its definition is
2465available and it doesn't reference any non-dllimport functions or global
2466variables.
2467
2468.. _dllimport: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx)reST";
2469
2470static const char AttrDoc_DLLImportStaticLocal[] = R"reST()reST";
2471
2472static const char AttrDoc_Deprecated[] = R"reST(The ``deprecated`` attribute can be applied to a function, a variable, or a
2473type. This is useful when identifying functions, variables, or types that are
2474expected to be removed in a future version of a program.
2475
2476Consider the function declaration for a hypothetical function ``f``:
2477
2478.. code-block:: c++
2479
2480 void f(void) __attribute__((deprecated("message", "replacement")));
2481
2482When spelled as ``__attribute__((deprecated))``, the deprecated attribute can have
2483two optional string arguments. The first one is the message to display when
2484emitting the warning; the second one enables the compiler to provide a Fix-It
2485to replace the deprecated name with a new name. Otherwise, when spelled as
2486``[[gnu::deprecated]]`` or ``[[deprecated]]``, the attribute can have one optional
2487string argument which is the message to display when emitting the warning.)reST";
2488
2489static const char AttrDoc_Destructor[] = R"reST(The ``constructor`` attribute causes the function to be called before entering
2490``main()``, and the ``destructor`` attribute causes the function to be called
2491after returning from ``main()`` or when the ``exit()`` function has been
2492called. Note, ``quick_exit()``, ``_Exit()``, and ``abort()`` prevent a function
2493marked ``destructor`` from being called.
2494
2495The constructor or destructor function should not accept any arguments and its
2496return type should be ``void``.
2497
2498The attributes accept an optional argument used to specify the priority order
2499in which to execute constructor and destructor functions. The priority is
2500given as an integer constant expression between 101 and 65535 (inclusive).
2501Priorities outside of that range are reserved for use by the implementation. A
2502lower value indicates a higher priority of initialization. Note that only the
2503relative ordering of values is important. For example:
2504
2505.. code-block:: c++
2506
2507 __attribute__((constructor(200))) void foo(void);
2508 __attribute__((constructor(101))) void bar(void);
2509
2510``bar()`` will be called before ``foo()``, and both will be called before
2511``main()``. If no argument is given to the ``constructor`` or ``destructor``
2512attribute, they default to the value ``65535``.)reST";
2513
2514static const char AttrDoc_DeviceKernel[] = R"reST(These attributes specify that the function represents a kernel for device offloading.
2515The specific semantics depend on the offloading language, target, and attribute spelling.
2516The ``sycl_kernel`` attribute specifies that a function template will be used
2517to outline device code and to generate an OpenCL kernel.
2518Here is a code example of the SYCL program, which demonstrates the compiler's
2519outlining job:
2520
2521.. code-block:: c++
2522
2523 int foo(int x) { return ++x; }
2524
2525 using namespace cl::sycl;
2526 queue Q;
2527 buffer<int, 1> a(range<1>{1024});
2528 Q.submit([&](handler& cgh) {
2529 auto A = a.get_access<access::mode::write>(cgh);
2530 cgh.parallel_for<init_a>(range<1>{1024}, [=](id<1> index) {
2531 A[index] = index[0] + foo(42);
2532 });
2533 }
2534
2535A C++ function object passed to the ``parallel_for`` is called a "SYCL kernel".
2536A SYCL kernel defines the entry point to the "device part" of the code. The
2537compiler will emit all symbols accessible from a "kernel". In this code
2538example, the compiler will emit "foo" function. More details about the
2539compilation of functions for the device part can be found in the SYCL 1.2.1
2540specification Section 6.4.
2541To show to the compiler entry point to the "device part" of the code, the SYCL
2542runtime can use the ``sycl_kernel`` attribute in the following way:
2543
2544.. code-block:: c++
2545
2546 namespace cl {
2547 namespace sycl {
2548 class handler {
2549 template <typename KernelName, typename KernelType/*, ...*/>
2550 __attribute__((sycl_kernel)) void sycl_kernel_function(KernelType KernelFuncObj) {
2551 // ...
2552 KernelFuncObj();
2553 }
2554
2555 template <typename KernelName, typename KernelType, int Dims>
2556 void parallel_for(range<Dims> NumWorkItems, KernelType KernelFunc) {
2557 #ifdef __SYCL_DEVICE_ONLY__
2558 sycl_kernel_function<KernelName, KernelType, Dims>(KernelFunc);
2559 #else
2560 // Host implementation
2561 #endif
2562 }
2563 };
2564 } // namespace sycl
2565 } // namespace cl
2566
2567The compiler will also generate an OpenCL kernel using the function marked with
2568the ``sycl_kernel`` attribute.
2569Here is the list of SYCL device compiler expectations with regard to the
2570function marked with the ``sycl_kernel`` attribute:
2571
2572- The function must be a template with at least two type template parameters.
2573 The compiler generates an OpenCL kernel and uses the first template parameter
2574 as a unique name for the generated OpenCL kernel. The host application uses
2575 this unique name to invoke the OpenCL kernel generated for the SYCL kernel
2576 specialized by this name and second template parameter ``KernelType`` (which
2577 might be an unnamed function object type).
2578- The function must have at least one parameter. The first parameter is
2579 required to be a function object type (named or unnamed i.e. lambda). The
2580 compiler uses function object type fields to generate OpenCL kernel
2581 parameters.
2582- The function must return void. The compiler reuses the body of marked functions to
2583 generate the OpenCL kernel body, and the OpenCL kernel must return ``void``.
2584
2585The SYCL kernel in the previous code sample meets these expectations.)reST";
2586
2587static const char AttrDoc_DiagnoseAsBuiltin[] = R"reST(The ``diagnose_as_builtin`` attribute indicates that Fortify diagnostics are to
2588be applied to the declared function as if it were the function specified by the
2589attribute. The builtin function whose diagnostics are to be mimicked should be
2590given. In addition, the order in which arguments should be applied must also
2591be given.
2592
2593For example, the attribute can be used as follows.
2594
2595.. code-block:: c
2596
2597 __attribute__((diagnose_as_builtin(__builtin_memset, 3, 2, 1)))
2598 void *mymemset(int n, int c, void *s) {
2599 // ...
2600 }
2601
2602This indicates that calls to ``mymemset`` should be diagnosed as if they were
2603calls to ``__builtin_memset``. The arguments ``3, 2, 1`` indicate by index the
2604order in which arguments of ``mymemset`` should be applied to
2605``__builtin_memset``. The third argument should be applied first, then the
2606second, and then the first. Thus (when Fortify warnings are enabled) the call
2607``mymemset(n, c, s)`` will diagnose overflows as if it were the call
2608``__builtin_memset(s, c, n)``.
2609
2610For variadic functions, the variadic arguments must come in the same order as
2611they would to the builtin function, after all normal arguments. For instance,
2612to diagnose a new function as if it were `sscanf`, we can use the attribute as
2613follows.
2614
2615.. code-block:: c
2616
2617 __attribute__((diagnose_as_builtin(sscanf, 1, 2)))
2618 int mysscanf(const char *str, const char *format, ...) {
2619 // ...
2620 }
2621
2622Then the call `mysscanf("abc def", "%4s %4s", buf1, buf2)` will be diagnosed as
2623if it were the call `sscanf("abc def", "%4s %4s", buf1, buf2)`.
2624
2625This attribute cannot be applied to non-static member functions.)reST";
2626
2627static const char AttrDoc_DiagnoseIf[] = R"reST(The ``diagnose_if`` attribute can be placed on function declarations to emit
2628warnings or errors at compile-time if calls to the attributed function meet
2629certain user-defined criteria. For example:
2630
2631.. code-block:: c
2632
2633 int abs(int a)
2634 __attribute__((diagnose_if(a >= 0, "Redundant abs call", "warning")));
2635 int must_abs(int a)
2636 __attribute__((diagnose_if(a >= 0, "Redundant abs call", "error")));
2637
2638 int val = abs(1); // warning: Redundant abs call
2639 int val2 = must_abs(1); // error: Redundant abs call
2640 int val3 = abs(val);
2641 int val4 = must_abs(val); // Because run-time checks are not emitted for
2642 // diagnose_if attributes, this executes without
2643 // issue.
2644
2645
2646``diagnose_if`` is closely related to ``enable_if``, with a few key differences:
2647
2648* Overload resolution is not aware of ``diagnose_if`` attributes: they're
2649 considered only after we select the best candidate from a given candidate set.
2650* Function declarations that differ only in their ``diagnose_if`` attributes are
2651 considered to be redeclarations of the same function (not overloads).
2652* If the condition provided to ``diagnose_if`` cannot be evaluated, no
2653 diagnostic will be emitted.
2654
2655Otherwise, ``diagnose_if`` is essentially the logical negation of ``enable_if``.
2656
2657As a result of bullet number two, ``diagnose_if`` attributes will stack on the
2658same function. For example:
2659
2660.. code-block:: c
2661
2662 int foo() __attribute__((diagnose_if(1, "diag1", "warning")));
2663 int foo() __attribute__((diagnose_if(1, "diag2", "warning")));
2664
2665 int bar = foo(); // warning: diag1
2666 // warning: diag2
2667 int (*fooptr)(void) = foo; // warning: diag1
2668 // warning: diag2
2669
2670 constexpr int supportsAPILevel(int N) { return N < 5; }
2671 int baz(int a)
2672 __attribute__((diagnose_if(!supportsAPILevel(10),
2673 "Upgrade to API level 10 to use baz", "error")));
2674 int baz(int a)
2675 __attribute__((diagnose_if(!a, "0 is not recommended.", "warning")));
2676
2677 int (*bazptr)(int) = baz; // error: Upgrade to API level 10 to use baz
2678 int v = baz(0); // error: Upgrade to API level 10 to use baz
2679
2680Query for this feature with ``__has_attribute(diagnose_if)``.)reST";
2681
2682static const char AttrDoc_DisableSanitizerInstrumentation[] = R"reST(Use the ``disable_sanitizer_instrumentation`` attribute on a function,
2683Objective-C method, or global variable, to specify that no sanitizer
2684instrumentation should be applied.
2685
2686This is not the same as ``__attribute__((no_sanitize(...)))``, which depending
2687on the tool may still insert instrumentation to prevent false positive reports.)reST";
2688
2689static const char AttrDoc_DisableTailCalls[] = R"reST(The ``disable_tail_calls`` attribute instructs the backend to not perform tail
2690call optimization inside the marked function.
2691
2692For example:
2693
2694 .. code-block:: c
2695
2696 int callee(int);
2697
2698 int foo(int a) __attribute__((disable_tail_calls)) {
2699 return callee(a); // This call is not tail-call optimized.
2700 }
2701
2702Marking virtual functions as ``disable_tail_calls`` is legal.
2703
2704 .. code-block:: c++
2705
2706 int callee(int);
2707
2708 class Base {
2709 public:
2710 [[clang::disable_tail_calls]] virtual int foo1() {
2711 return callee(); // This call is not tail-call optimized.
2712 }
2713 };
2714
2715 class Derived1 : public Base {
2716 public:
2717 int foo1() override {
2718 return callee(); // This call is tail-call optimized.
2719 }
2720 };)reST";
2721
2722static const char AttrDoc_EmptyBases[] = R"reST(The empty_bases attribute permits the compiler to utilize the
2723empty-base-optimization more frequently.
2724This attribute only applies to struct, class, and union types.
2725It is only supported when using the Microsoft C++ ABI.)reST";
2726
2727static const char AttrDoc_EnableIf[] = R"reST(.. Note:: Some features of this attribute are experimental. The meaning of
2728 multiple enable_if attributes on a single declaration is subject to change in
2729 a future version of clang. Also, the ABI is not standardized and the name
2730 mangling may change in future versions. To avoid that, use asm labels.
2731
2732The ``enable_if`` attribute can be placed on function declarations to control
2733which overload is selected based on the values of the function's arguments.
2734When combined with the ``overloadable`` attribute, this feature is also
2735available in C.
2736
2737.. code-block:: c++
2738
2739 int isdigit(int c);
2740 int isdigit(int c) __attribute__((enable_if(c <= -1 || c > 255, "chosen when 'c' is out of range"))) __attribute__((unavailable("'c' must have the value of an unsigned char or EOF")));
2741
2742 void foo(char c) {
2743 isdigit(c);
2744 isdigit(10);
2745 isdigit(-10); // results in a compile-time error.
2746 }
2747
2748The enable_if attribute takes two arguments, the first is an expression written
2749in terms of the function parameters, the second is a string explaining why this
2750overload candidate could not be selected to be displayed in diagnostics. The
2751expression is part of the function signature for the purposes of determining
2752whether it is a redeclaration (following the rules used when determining
2753whether a C++ template specialization is ODR-equivalent), but is not part of
2754the type.
2755
2756The enable_if expression is evaluated as if it were the body of a
2757bool-returning constexpr function declared with the arguments of the function
2758it is being applied to, then called with the parameters at the call site. If the
2759result is false or could not be determined through constant expression
2760evaluation, then this overload will not be chosen and the provided string may
2761be used in a diagnostic if the compile fails as a result.
2762
2763Because the enable_if expression is an unevaluated context, there are no global
2764state changes, nor the ability to pass information from the enable_if
2765expression to the function body. For example, suppose we want calls to
2766strnlen(strbuf, maxlen) to resolve to strnlen_chk(strbuf, maxlen, size of
2767strbuf) only if the size of strbuf can be determined:
2768
2769.. code-block:: c++
2770
2771 __attribute__((always_inline))
2772 static inline size_t strnlen(const char *s, size_t maxlen)
2773 __attribute__((overloadable))
2774 __attribute__((enable_if(__builtin_object_size(s, 0) != -1))),
2775 "chosen when the buffer size is known but 'maxlen' is not")))
2776 {
2777 return strnlen_chk(s, maxlen, __builtin_object_size(s, 0));
2778 }
2779
2780Multiple enable_if attributes may be applied to a single declaration. In this
2781case, the enable_if expressions are evaluated from left to right in the
2782following manner. First, the candidates whose enable_if expressions evaluate to
2783false or cannot be evaluated are discarded. If the remaining candidates do not
2784share ODR-equivalent enable_if expressions, the overload resolution is
2785ambiguous. Otherwise, enable_if overload resolution continues with the next
2786enable_if attribute on the candidates that have not been discarded and have
2787remaining enable_if attributes. In this way, we pick the most specific
2788overload out of a number of viable overloads using enable_if.
2789
2790.. code-block:: c++
2791
2792 void f() __attribute__((enable_if(true, ""))); // #1
2793 void f() __attribute__((enable_if(true, ""))) __attribute__((enable_if(true, ""))); // #2
2794
2795 void g(int i, int j) __attribute__((enable_if(i, ""))); // #1
2796 void g(int i, int j) __attribute__((enable_if(j, ""))) __attribute__((enable_if(true))); // #2
2797
2798In this example, a call to f() is always resolved to #2, as the first enable_if
2799expression is ODR-equivalent for both declarations, but #1 does not have another
2800enable_if expression to continue evaluating, so the next round of evaluation has
2801only a single candidate. In a call to g(1, 1), the call is ambiguous even though
2802#2 has more enable_if attributes, because the first enable_if expressions are
2803not ODR-equivalent.
2804
2805Query for this feature with ``__has_attribute(enable_if)``.
2806
2807Note that functions with one or more ``enable_if`` attributes may not have
2808their address taken, unless all of the conditions specified by said
2809``enable_if`` are constants that evaluate to ``true``. For example:
2810
2811.. code-block:: c
2812
2813 const int TrueConstant = 1;
2814 const int FalseConstant = 0;
2815 int f(int a) __attribute__((enable_if(a > 0, "")));
2816 int g(int a) __attribute__((enable_if(a == 0 || a != 0, "")));
2817 int h(int a) __attribute__((enable_if(1, "")));
2818 int i(int a) __attribute__((enable_if(TrueConstant, "")));
2819 int j(int a) __attribute__((enable_if(FalseConstant, "")));
2820
2821 void fn() {
2822 int (*ptr)(int);
2823 ptr = &f; // error: 'a > 0' is not always true
2824 ptr = &g; // error: 'a == 0 || a != 0' is not a truthy constant
2825 ptr = &h; // OK: 1 is a truthy constant
2826 ptr = &i; // OK: 'TrueConstant' is a truthy constant
2827 ptr = &j; // error: 'FalseConstant' is a constant, but not truthy
2828 }
2829
2830Because ``enable_if`` evaluation happens during overload resolution,
2831``enable_if`` may give unintuitive results when used with templates, depending
2832on when overloads are resolved. In the example below, clang will emit a
2833diagnostic about no viable overloads for ``foo`` in ``bar``, but not in ``baz``:
2834
2835.. code-block:: c++
2836
2837 double foo(int i) __attribute__((enable_if(i > 0, "")));
2838 void *foo(int i) __attribute__((enable_if(i <= 0, "")));
2839 template <int I>
2840 auto bar() { return foo(I); }
2841
2842 template <typename T>
2843 auto baz() { return foo(T::number); }
2844
2845 struct WithNumber { constexpr static int number = 1; };
2846 void callThem() {
2847 bar<sizeof(WithNumber)>();
2848 baz<WithNumber>();
2849 }
2850
2851This is because, in ``bar``, ``foo`` is resolved prior to template
2852instantiation, so the value for ``I`` isn't known (thus, both ``enable_if``
2853conditions for ``foo`` fail). However, in ``baz``, ``foo`` is resolved during
2854template instantiation, so the value for ``T::number`` is known.)reST";
2855
2856static const char AttrDoc_EnforceTCB[] = R"reST(The ``enforce_tcb`` attribute can be placed on functions to enforce that a
2857 trusted compute base (TCB) does not call out of the TCB. This generates a
2858 warning every time a function not marked with an ``enforce_tcb`` attribute is
2859 called from a function with the ``enforce_tcb`` attribute. A function may be a
2860 part of multiple TCBs. Invocations through function pointers are currently
2861 not checked. Builtins are considered to a part of every TCB.
2862
2863 - ``enforce_tcb(Name)`` indicates that this function is a part of the TCB named ``Name``)reST";
2864
2865static const char AttrDoc_EnforceTCBLeaf[] = R"reST(The ``enforce_tcb_leaf`` attribute satisfies the requirement enforced by
2866 ``enforce_tcb`` for the marked function to be in the named TCB but does not
2867 continue to check the functions called from within the leaf function.
2868
2869 - ``enforce_tcb_leaf(Name)`` indicates that this function is a part of the TCB named ``Name``)reST";
2870
2871static const char AttrDoc_EnumExtensibility[] = R"reST(Attribute ``enum_extensibility`` is used to distinguish between enum definitions
2872that are extensible and those that are not. The attribute can take either
2873``closed`` or ``open`` as an argument. ``closed`` indicates a variable of the
2874enum type takes a value that corresponds to one of the enumerators listed in the
2875enum definition or, when the enum is annotated with ``flag_enum``, a value that
2876can be constructed using values corresponding to the enumerators. ``open``
2877indicates a variable of the enum type can take any values allowed by the
2878standard and instructs clang to be more lenient when issuing warnings.
2879
2880.. code-block:: c
2881
2882 enum __attribute__((enum_extensibility(closed))) ClosedEnum {
2883 A0, A1
2884 };
2885
2886 enum __attribute__((enum_extensibility(open))) OpenEnum {
2887 B0, B1
2888 };
2889
2890 enum __attribute__((enum_extensibility(closed),flag_enum)) ClosedFlagEnum {
2891 C0 = 1 << 0, C1 = 1 << 1
2892 };
2893
2894 enum __attribute__((enum_extensibility(open),flag_enum)) OpenFlagEnum {
2895 D0 = 1 << 0, D1 = 1 << 1
2896 };
2897
2898 void foo1() {
2899 enum ClosedEnum ce;
2900 enum OpenEnum oe;
2901 enum ClosedFlagEnum cfe;
2902 enum OpenFlagEnum ofe;
2903
2904 ce = A1; // no warnings
2905 ce = 100; // warning issued
2906 oe = B1; // no warnings
2907 oe = 100; // no warnings
2908 cfe = C0 | C1; // no warnings
2909 cfe = C0 | C1 | 4; // warning issued
2910 ofe = D0 | D1; // no warnings
2911 ofe = D0 | D1 | 4; // no warnings
2912 })reST";
2913
2914static const char AttrDoc_Error[] = R"reST(The ``error`` and ``warning`` function attributes can be used to specify a
2915custom diagnostic to be emitted when a call to such a function is not
2916eliminated via optimizations. This can be used to create compile time
2917assertions that depend on optimizations, while providing diagnostics
2918pointing to precise locations of the call site in the source.
2919
2920.. code-block:: c++
2921
2922 __attribute__((warning("oh no"))) void dontcall();
2923 void foo() {
2924 if (someCompileTimeAssertionThatsTrue)
2925 dontcall(); // Warning
2926
2927 dontcall(); // Warning
2928
2929 if (someCompileTimeAssertionThatsFalse)
2930 dontcall(); // No Warning
2931 sizeof(dontcall()); // No Warning
2932 })reST";
2933
2934static const char AttrDoc_ExcludeFromExplicitInstantiation[] = R"reST(The ``exclude_from_explicit_instantiation`` attribute opts-out a member of a
2935class template from being part of explicit template instantiations of that
2936class template. This means that an explicit instantiation will not instantiate
2937members of the class template marked with the attribute, but also that code
2938where an extern template declaration of the enclosing class template is visible
2939will not take for granted that an external instantiation of the class template
2940would provide those members (which would otherwise be a link error, since the
2941explicit instantiation won't provide those members). For example, let's say we
2942don't want the ``data()`` method to be part of libc++'s ABI. To make sure it
2943is not exported from the dylib, we give it hidden visibility:
2944
2945 .. code-block:: c++
2946
2947 // in <string>
2948 template <class CharT>
2949 class basic_string {
2950 public:
2951 __attribute__((__visibility__("hidden")))
2952 const value_type* data() const noexcept { ... }
2953 };
2954
2955 template class basic_string<char>;
2956
2957Since an explicit template instantiation declaration for ``basic_string<char>``
2958is provided, the compiler is free to assume that ``basic_string<char>::data()``
2959will be provided by another translation unit, and it is free to produce an
2960external call to this function. However, since ``data()`` has hidden visibility
2961and the explicit template instantiation is provided in a shared library (as
2962opposed to simply another translation unit), ``basic_string<char>::data()``
2963won't be found and a link error will ensue. This happens because the compiler
2964assumes that ``basic_string<char>::data()`` is part of the explicit template
2965instantiation declaration, when it really isn't. To tell the compiler that
2966``data()`` is not part of the explicit template instantiation declaration, the
2967``exclude_from_explicit_instantiation`` attribute can be used:
2968
2969 .. code-block:: c++
2970
2971 // in <string>
2972 template <class CharT>
2973 class basic_string {
2974 public:
2975 __attribute__((__visibility__("hidden")))
2976 __attribute__((exclude_from_explicit_instantiation))
2977 const value_type* data() const noexcept { ... }
2978 };
2979
2980 template class basic_string<char>;
2981
2982Now, the compiler won't assume that ``basic_string<char>::data()`` is provided
2983externally despite there being an explicit template instantiation declaration:
2984the compiler will implicitly instantiate ``basic_string<char>::data()`` in the
2985TUs where it is used.
2986
2987This attribute can be used on static and non-static member functions of class
2988templates, static data members of class templates and member classes of class
2989templates.)reST";
2990
2991static const char AttrDoc_ExplicitInit[] = R"reST(The ``clang::require_explicit_initialization`` attribute indicates that a
2992field of an aggregate must be initialized explicitly by the user when an object
2993of the aggregate type is constructed. The attribute supports both C and C++,
2994but its usage is invalid on non-aggregates.
2995
2996Note that this attribute is *not* a memory safety feature, and is *not* intended
2997to guard against use of uninitialized memory.
2998
2999Rather, it is intended for use in "parameter-objects", used to simulate,
3000for example, the passing of named parameters.
3001The attribute generates a warning when explicit initializers for such
3002variables are not provided (this occurs regardless of whether any in-class field
3003initializers exist):
3004
3005.. code-block:: c++
3006
3007 struct Buffer {
3008 void *address [[clang::require_explicit_initialization]];
3009 size_t length [[clang::require_explicit_initialization]] = 0;
3010 };
3011
3012 struct ArrayIOParams {
3013 size_t count [[clang::require_explicit_initialization]];
3014 size_t element_size [[clang::require_explicit_initialization]];
3015 int flags = 0;
3016 };
3017
3018 size_t ReadArray(FILE *file, struct Buffer buffer,
3019 struct ArrayIOParams params);
3020
3021 int main() {
3022 unsigned int buf[512];
3023 ReadArray(stdin, {
3024 buf
3025 // warning: field 'length' is not explicitly initialized
3026 }, {
3027 .count = sizeof(buf) / sizeof(*buf),
3028 // warning: field 'element_size' is not explicitly initialized
3029 // (Note that a missing initializer for 'flags' is not diagnosed, because
3030 // the field is not marked as requiring explicit initialization.)
3031 });
3032 })reST";
3033
3034static const char AttrDoc_ExtVectorType[] = R"reST(The ``ext_vector_type(N)`` attribute specifies that a type is a vector with N
3035elements, directly mapping to an LLVM vector type. Originally from OpenCL, it
3036allows element access the array subscript operator ``[]``, ``sN`` where N is
3037a hexadecimal value, or ``x, y, z, w`` for graphics-style indexing.
3038This attribute enables efficient SIMD operations and is usable in
3039general-purpose code.
3040
3041.. code-block:: c++
3042
3043 template <typename T, uint32_t N>
3044 constexpr T simd_reduce(T [[clang::ext_vector_type(N)]] v) {
3045 static_assert((N & (N - 1)) == 0, "N must be a power of two");
3046 if constexpr (N == 1)
3047 return v[0];
3048 else
3049 return simd_reduce<T, N / 2>(v.hi + v.lo);
3050 }
3051
3052The vector type also supports swizzling up to sixteen elements. This can be done
3053using the object accessors. The OpenCL documentation lists all of the accepted
3054values.
3055
3056.. code-block:: c++
3057
3058 using f16_x16 = _Float16 __attribute__((ext_vector_type(16)));
3059
3060 f16_x16 reverse(f16_x16 v) { return v.sfedcba9876543210; }
3061
3062See the OpenCL documentation for some more complete examples.)reST";
3063
3064static const char AttrDoc_ExternalSourceSymbol[] = R"reST(The ``external_source_symbol`` attribute specifies that a declaration originates
3065from an external source and describes the nature of that source.
3066
3067The fact that Clang is capable of recognizing declarations that were defined
3068externally can be used to provide better tooling support for mixed-language
3069projects or projects that rely on auto-generated code. For instance, an IDE that
3070uses Clang and that supports mixed-language projects can use this attribute to
3071provide a correct 'jump-to-definition' feature. For a concrete example,
3072consider a protocol that's defined in a Swift file:
3073
3074.. code-block:: swift
3075
3076 @objc public protocol SwiftProtocol {
3077 func method()
3078 }
3079
3080This protocol can be used from Objective-C code by including a header file that
3081was generated by the Swift compiler. The declarations in that header can use
3082the ``external_source_symbol`` attribute to make Clang aware of the fact
3083that ``SwiftProtocol`` actually originates from a Swift module:
3084
3085.. code-block:: objc
3086
3087 __attribute__((external_source_symbol(language="Swift",defined_in="module")))
3088 @protocol SwiftProtocol
3089 @required
3090 - (void) method;
3091 @end
3092
3093Consequently, when 'jump-to-definition' is performed at a location that
3094references ``SwiftProtocol``, the IDE can jump to the original definition in
3095the Swift source file rather than jumping to the Objective-C declaration in the
3096auto-generated header file.
3097
3098The ``external_source_symbol`` attribute is a comma-separated list that includes
3099clauses that describe the origin and the nature of the particular declaration.
3100Those clauses can be:
3101
3102language=\ *string-literal*
3103 The name of the source language in which this declaration was defined.
3104
3105defined_in=\ *string-literal*
3106 The name of the source container in which the declaration was defined. The
3107 exact definition of source container is language-specific, e.g. Swift's
3108 source containers are modules, so ``defined_in`` should specify the Swift
3109 module name.
3110
3111USR=\ *string-literal*
3112 String that specifies a unified symbol resolution (USR) value for this
3113 declaration. USR string uniquely identifies this particular declaration, and
3114 is typically used when constructing an index of a codebase.
3115 The USR value in this attribute is expected to be generated by an external
3116 compiler that compiled the native declaration using its original source
3117 language. The exact format of the USR string and its other attributes
3118 are determined by the specification of this declaration's source language.
3119 When not specified, Clang's indexer will use the Clang USR for this symbol.
3120 User can query to see if Clang supports the use of the ``USR`` clause in
3121 the ``external_source_symbol`` attribute with
3122 ``__has_attribute(external_source_symbol) >= 20230206``.
3123
3124generated_declaration
3125 This declaration was automatically generated by some tool.
3126
3127The clauses can be specified in any order. The clauses that are listed above are
3128all optional, but the attribute has to have at least one clause.)reST";
3129
3130static const char AttrDoc_FallThrough[] = R"reST(The ``fallthrough`` (or ``clang::fallthrough``) attribute is used
3131to annotate intentional fall-through
3132between switch labels. It can only be applied to a null statement placed at a
3133point of execution between any statement and the next switch label. It is
3134common to mark these places with a specific comment, but this attribute is
3135meant to replace comments with a more strict annotation, which can be checked
3136by the compiler. This attribute doesn't change semantics of the code and can
3137be used wherever an intended fall-through occurs. It is designed to mimic
3138control-flow statements like ``break;``, so it can be placed in most places
3139where ``break;`` can, but only if there are no statements on the execution path
3140between it and the next switch label.
3141
3142By default, Clang does not warn on unannotated fallthrough from one ``switch``
3143case to another. Diagnostics on fallthrough without a corresponding annotation
3144can be enabled with the ``-Wimplicit-fallthrough`` argument.
3145
3146Here is an example:
3147
3148.. code-block:: c++
3149
3150 // compile with -Wimplicit-fallthrough
3151 switch (n) {
3152 case 22:
3153 case 33: // no warning: no statements between case labels
3154 f();
3155 case 44: // warning: unannotated fall-through
3156 g();
3157 [[clang::fallthrough]];
3158 case 55: // no warning
3159 if (x) {
3160 h();
3161 break;
3162 }
3163 else {
3164 i();
3165 [[clang::fallthrough]];
3166 }
3167 case 66: // no warning
3168 p();
3169 [[clang::fallthrough]]; // warning: fallthrough annotation does not
3170 // directly precede case label
3171 q();
3172 case 77: // warning: unannotated fall-through
3173 r();
3174 })reST";
3175
3176static const char AttrDoc_FastCall[] = R"reST(On 32-bit x86 targets, this attribute changes the calling convention of a
3177function to use ECX and EDX as register parameters and clear parameters off of
3178the stack on return. This convention does not support variadic calls or
3179unprototyped functions in C, and has no effect on x86_64 targets. This calling
3180convention is supported primarily for compatibility with existing code. Users
3181seeking register parameters should use the ``regparm`` attribute, which does
3182not require callee-cleanup. See the documentation for `__fastcall`_ on MSDN.
3183
3184.. _`__fastcall`: http://msdn.microsoft.com/en-us/library/6xa169sk.aspx)reST";
3185
3186static const char AttrDoc_Final[] = R"reST()reST";
3187
3188static const char AttrDoc_FlagEnum[] = R"reST(This attribute can be added to an enumerator to signal to the compiler that it
3189is intended to be used as a flag type. This will cause the compiler to assume
3190that the range of the type includes all of the values that you can get by
3191manipulating bits of the enumerator when issuing warnings.)reST";
3192
3193static const char AttrDoc_Flatten[] = R"reST(The ``flatten`` attribute causes calls within the attributed function to
3194be inlined unless it is impossible to do so, for example if the body of the
3195callee is unavailable or if the callee has the ``noinline`` attribute.)reST";
3196
3197static const char AttrDoc_Format[] = R"reST(Clang supports the ``format`` attribute, which indicates that the function
3198accepts (among other possibilities) a ``printf`` or ``scanf``-like format string
3199and corresponding arguments or a ``va_list`` that contains these arguments.
3200
3201Please see `GCC documentation about format attribute
3202<http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_ to find details
3203about attribute syntax.
3204
3205Clang implements two kinds of checks with this attribute.
3206
3207#. Clang checks that the function with the ``format`` attribute is called with
3208 a format string that uses format specifiers that are allowed, and that
3209 arguments match the format string. This is the ``-Wformat`` warning, it is
3210 on by default.
3211
3212#. Clang checks that the format string argument is a literal string. This is
3213 the ``-Wformat-nonliteral`` warning, it is off by default.
3214
3215 Clang implements this mostly the same way as GCC, but there is a difference
3216 for functions that accept a ``va_list`` argument (for example, ``vprintf``).
3217 GCC does not emit ``-Wformat-nonliteral`` warning for calls to such
3218 functions. Clang does not warn if the format string comes from a function
3219 parameter, where the function is annotated with a compatible attribute,
3220 otherwise it warns. For example:
3221
3222 .. code-block:: c
3223
3224 __attribute__((__format__ (__scanf__, 1, 3)))
3225 void foo(const char* s, char *buf, ...) {
3226 va_list ap;
3227 va_start(ap, buf);
3228
3229 vprintf(s, ap); // warning: format string is not a string literal
3230 }
3231
3232 In this case we warn because ``s`` contains a format string for a
3233 ``scanf``-like function, but it is passed to a ``printf``-like function.
3234
3235 If the attribute is removed, clang still warns, because the format string is
3236 not a string literal.
3237
3238 Another example:
3239
3240 .. code-block:: c
3241
3242 __attribute__((__format__ (__printf__, 1, 3)))
3243 void foo(const char* s, char *buf, ...) {
3244 va_list ap;
3245 va_start(ap, buf);
3246
3247 vprintf(s, ap); // warning
3248 }
3249
3250 In this case Clang does not warn because the format string ``s`` and
3251 the corresponding arguments are annotated. If the arguments are
3252 incorrect, the caller of ``foo`` will receive a warning.
3253
3254As an extension to GCC's behavior, Clang accepts the ``format`` attribute on
3255non-variadic functions. Clang checks non-variadic format functions for the same
3256classes of issues that can be found on variadic functions, as controlled by the
3257same warning flags, except that the types of formatted arguments is forced by
3258the function signature. For example:
3259
3260.. code-block:: c
3261
3262 __attribute__((__format__(__printf__, 1, 2)))
3263 void fmt(const char *s, const char *a, int b);
3264
3265 void bar(void) {
3266 fmt("%s %i", "hello", 123); // OK
3267 fmt("%i %g", "hello", 123); // warning: arguments don't match format
3268 extern const char *fmt;
3269 fmt(fmt, "hello", 123); // warning: format string is not a string literal
3270 }
3271
3272When using the format attribute on a variadic function, the first data parameter
3273_must_ be the index of the ellipsis in the parameter list. Clang will generate
3274a diagnostic otherwise, as it wouldn't be possible to forward that argument list
3275to `printf`-family functions. For instance, this is an error:
3276
3277.. code-block:: c
3278
3279 __attribute__((__format__(__printf__, 1, 2)))
3280 void fmt(const char *s, int b, ...);
3281 // ^ error: format attribute parameter 3 is out of bounds
3282 // (must be __printf__, 1, 3)
3283
3284Using the ``format`` attribute on a non-variadic function emits a GCC
3285compatibility diagnostic.)reST";
3286
3287static const char AttrDoc_FormatArg[] = R"reST(No documentation.)reST";
3288
3289static const char AttrDoc_FormatMatches[] = R"reST(The ``format`` attribute is the basis for the enforcement of diagnostics in the
3290``-Wformat`` family, but it only handles the case where the format string is
3291passed along with the arguments it is going to format. It cannot handle the case
3292where the format string and the format arguments are passed separately from each
3293other. For instance:
3294
3295.. code-block:: c
3296
3297 static const char *first_name;
3298 static double todays_temperature;
3299 static int wind_speed;
3300
3301 void say_hi(const char *fmt) {
3302 printf(fmt, first_name, todays_temperature);
3303 // ^ warning: format string is not a string literal
3304 printf(fmt, first_name, wind_speed);
3305 // ^ warning: format string is not a string literal
3306 }
3307
3308 int main() {
3309 say_hi("hello %s, it is %g degrees outside");
3310 say_hi("hello %s, it is %d degrees outside!");
3311 // ^ no diagnostic, but %d cannot format doubles
3312 }
3313
3314In this example, ``fmt`` is expected to format a ``const char *`` and a
3315``double``, but these values are not passed to ``say_hi``. Without the
3316``format`` attribute (which cannot apply in this case), the -Wformat-nonliteral
3317diagnostic unnecessarily triggers in the body of ``say_hi``, and incorrect
3318``say_hi`` call sites do not trigger a diagnostic.
3319
3320To complement the ``format`` attribute, Clang also defines the
3321``format_matches`` attribute. Its syntax is similar to the ``format``
3322attribute's, but instead of taking the index of the first formatted value
3323argument, it takes a C string literal with the expected specifiers:
3324
3325.. code-block:: c
3326
3327 static const char *first_name;
3328 static double todays_temperature;
3329 static int wind_speed;
3330
3331 __attribute__((__format_matches__(printf, 1, "%s %g")))
3332 void say_hi(const char *fmt) {
3333 printf(fmt, first_name, todays_temperature); // no dignostic
3334 printf(fmt, first_name, wind_speed); // warning: format specifies type 'int' but the argument has type 'double'
3335 }
3336
3337 int main() {
3338 say_hi("hello %s, it is %g degrees outside");
3339 say_hi("it is %g degrees outside, have a good day %s!");
3340 // warning: format specifies 'double' where 'const char *' is required
3341 // warning: format specifies 'const char *' where 'double' is required
3342 }
3343
3344The third argument to ``format_matches`` is expected to evaluate to a **C string
3345literal** even when the format string would normally be a different type for the
3346given flavor, like a ``CFStringRef`` or a ``NSString *``.
3347
3348The only requirement on the format string literal is that it has specifiers
3349that are compatible with the arguments that will be used. It can contain
3350arbitrary non-format characters. For instance, for the purposes of compile-time
3351validation, ``"%s scored %g%% on her test"`` and ``"%s%g"`` are interchangeable
3352as the format string argument. As a means of self-documentation, users may
3353prefer the former when it provides a useful example of an expected format
3354string.
3355
3356In the implementation of a function with the ``format_matches`` attribute,
3357format verification works as if the format string was identical to the one
3358specified in the attribute.
3359
3360.. code-block:: c
3361
3362 __attribute__((__format_matches__(printf, 1, "%s %g")))
3363 void say_hi(const char *fmt) {
3364 printf(fmt, "person", 546);
3365 // ^ warning: format specifies type 'double' but the
3366 // argument has type 'int'
3367 // note: format string is defined here:
3368 // __attribute__((__format_matches__(printf, 1, "%s %g")))
3369 // ^~
3370 }
3371
3372
3373At the call sites of functions with the ``format_matches`` attribute, format
3374verification instead compares the two format strings to evaluate their
3375equivalence. Each format flavor defines equivalence between format specifiers.
3376Generally speaking, two specifiers are equivalent if they format the same type.
3377For instance, in the ``printf`` flavor, ``%2i`` and ``%-0.5d`` are compatible.
3378When ``-Wformat-signedness`` is disabled, ``%d`` and ``%u`` are compatible. For
3379a negative example, ``%ld`` is incompatible with ``%d``.
3380
3381Do note the following un-obvious cases:
3382
3383* Passing ``NULL`` as the format string does not trigger format diagnostics.
3384* When the format string is not NULL, it cannot _miss_ specifiers, even in
3385 trailing positions. For instance, ``%d`` is not accepted when the required
3386 format is ``%d %d %d``.
3387* While checks for the ``format`` attribute tolerate sone size mismatches
3388 that standard argument promotion renders immaterial (such as formatting an
3389 ``int`` with ``%hhd``, which specifies a ``char``-sized integer), checks for
3390 ``format_matches`` require specified argument sizes to match exactly.
3391* Format strings expecting a variable modifier (such as ``%*s``) are
3392 incompatible with format strings that would itemize the variable modifiers
3393 (such as ``%i %s``), even if the two specify ABI-compatible argument lists.
3394* All pointer specifiers, modifiers aside, are mutually incompatible. For
3395 instance, ``%s`` is not compatible with ``%p``, and ``%p`` is not compatible
3396 with ``%n``, and ``%hhn`` is incompatible with ``%s``, even if the pointers
3397 are ABI-compatible or identical on the selected platform. However, ``%0.5s``
3398 is compatible with ``%s``, since the difference only exists in modifier flags.
3399 This is not overridable with ``-Wformat-pedantic`` or its inverse, which
3400 control similar behavior in ``-Wformat``.
3401
3402At this time, clang implements ``format_matches`` only for format types in the
3403``printf`` family. This includes variants such as Apple's NSString format and
3404the FreeBSD ``kprintf``, but excludes ``scanf``. Using a known but unsupported
3405format silently fails in order to be compatible with other implementations that
3406would support these formats.)reST";
3407
3408static const char AttrDoc_FunctionReturnThunks[] = R"reST(The attribute ``function_return`` can replace return instructions with jumps to
3409target-specific symbols. This attribute supports 2 possible values,
3410corresponding to the values supported by the ``-mfunction-return=`` command
3411line flag:
3412
3413* ``__attribute__((function_return("keep")))`` to disable related transforms.
3414 This is useful for undoing global setting from ``-mfunction-return=`` locally
3415 for individual functions.
3416* ``__attribute__((function_return("thunk-extern")))`` to replace returns with
3417 jumps, while NOT emitting the thunk.
3418
3419The values ``thunk`` and ``thunk-inline`` from GCC are not supported.
3420
3421The symbol used for ``thunk-extern`` is target specific:
3422* X86: ``__x86_return_thunk``
3423
3424As such, this function attribute is currently only supported on X86 targets.)reST";
3425
3426static const char AttrDoc_GNUInline[] = R"reST(The ``gnu_inline`` changes the meaning of ``extern inline`` to use GNU inline
3427semantics, meaning:
3428
3429* If any declaration that is declared ``inline`` is not declared ``extern``,
3430 then the ``inline`` keyword is just a hint. In particular, an out-of-line
3431 definition is still emitted for a function with external linkage, even if all
3432 call sites are inlined, unlike in C99 and C++ inline semantics.
3433
3434* If all declarations that are declared ``inline`` are also declared
3435 ``extern``, then the function body is present only for inlining and no
3436 out-of-line version is emitted.
3437
3438Some important consequences: ``static inline`` emits an out-of-line
3439version if needed, a plain ``inline`` definition emits an out-of-line version
3440always, and an ``extern inline`` definition (in a header) followed by a
3441(non-``extern``) ``inline`` declaration in a source file emits an out-of-line
3442version of the function in that source file but provides the function body for
3443inlining to all includers of the header.
3444
3445Either ``__GNUC_GNU_INLINE__`` (GNU inline semantics) or
3446``__GNUC_STDC_INLINE__`` (C99 semantics) will be defined (they are mutually
3447exclusive). If ``__GNUC_STDC_INLINE__`` is defined, then the ``gnu_inline``
3448function attribute can be used to get GNU inline semantics on a per function
3449basis. If ``__GNUC_GNU_INLINE__`` is defined, then the translation unit is
3450already being compiled with GNU inline semantics as the implied default. It is
3451unspecified which macro is defined in a C++ compilation.
3452
3453GNU inline semantics are the default behavior with ``-std=gnu89``,
3454``-std=c89``, ``-std=c94``, or ``-fgnu89-inline``.)reST";
3455
3456static const char AttrDoc_GuardedBy[] = R"reST(No documentation.)reST";
3457
3458static const char AttrDoc_GuardedVar[] = R"reST(No documentation.)reST";
3459
3460static const char AttrDoc_HIPManaged[] = R"reST(The ``__managed__`` attribute can be applied to a global variable declaration in HIP.
3461A managed variable is emitted as an undefined global symbol in the device binary and is
3462registered by ``__hipRegisterManagedVariable`` in init functions. The HIP runtime allocates
3463managed memory and uses it to define the symbol when loading the device binary.
3464A managed variable can be accessed in both device and host code.)reST";
3465
3466static const char AttrDoc_HLSLContainedType[] = R"reST()reST";
3467
3468static const char AttrDoc_HLSLControlFlowHint[] = R"reST()reST";
3469
3470static const char AttrDoc_HLSLGroupSharedAddressSpace[] = R"reST(HLSL enables threads of a compute shader to exchange values via shared memory.
3471HLSL provides barrier primitives such as GroupMemoryBarrierWithGroupSync,
3472and so on to ensure the correct ordering of reads and writes to shared memory
3473in the shader and to avoid data races.
3474Here's an example to declare a groupshared variable.
3475.. code-block:: c++
3476
3477 groupshared GSData data[5*5*1];
3478
3479The full documentation is available here: https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-variable-syntax#group-shared)reST";
3480
3481static const char AttrDoc_HLSLLoopHint[] = R"reST(The ``[loop]`` directive allows loop optimization hints to be
3482specified for the subsequent loop. The directive allows unrolling to
3483be disabled and is not compatible with [unroll(x)].
3484
3485Specifying the parameter, ``[loop]``, directs the
3486unroller to not unroll the loop.
3487
3488.. code-block:: hlsl
3489
3490 [loop]
3491 for (...) {
3492 ...
3493 }
3494
3495.. code-block:: hlsl
3496
3497 [loop]
3498 while (...) {
3499 ...
3500 }
3501
3502.. code-block:: hlsl
3503
3504 [loop]
3505 do {
3506 ...
3507 } while (...)
3508
3509See `hlsl loop extensions <https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-for>`_
3510for details.)reST";
3511
3512static const char AttrDoc_HLSLNumThreads[] = R"reST(The ``numthreads`` attribute applies to HLSL shaders where explcit thread counts
3513are required. The ``X``, ``Y``, and ``Z`` values provided to the attribute
3514dictate the thread id. Total number of threads executed is ``X * Y * Z``.
3515
3516The full documentation is available here: https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/sm5-attributes-numthreads)reST";
3517
3518static const char AttrDoc_HLSLPackOffset[] = R"reST(The packoffset attribute is used to change the layout of a cbuffer.
3519Attribute spelling in HLSL is: ``packoffset( c[Subcomponent][.component] )``.
3520A subcomponent is a register number, which is an integer. A component is in the form of [.xyzw].
3521
3522Examples:
3523
3524.. code-block:: hlsl
3525
3526 cbuffer A {
3527 float3 a : packoffset(c0.y);
3528 float4 b : packoffset(c4);
3529 }
3530
3531The full documentation is available here: https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-variable-packoffset)reST";
3532
3533static const char AttrDoc_HLSLParamModifier[] = R"reST(HLSL function parameters are passed by value. Parameter declarations support
3534three qualifiers to denote parameter passing behavior. The three qualifiers are
3535`in`, `out` and `inout`.
3536
3537Parameters annotated with `in` or with no annotation are passed by value from
3538the caller to the callee.
3539
3540Parameters annotated with `out` are written to the argument after the callee
3541returns (Note: arguments values passed into `out` parameters *are not* copied
3542into the callee).
3543
3544Parameters annotated with `inout` are copied into the callee via a temporary,
3545and copied back to the argument after the callee returns.)reST";
3546
3547static const char AttrDoc_HLSLROV[] = R"reST()reST";
3548
3549static const char AttrDoc_HLSLRawBuffer[] = R"reST()reST";
3550
3551static const char AttrDoc_HLSLResourceBinding[] = R"reST(The resource binding attribute sets the virtual register and logical register space for a resource.
3552Attribute spelling in HLSL is: ``register(slot [, space])``.
3553``slot`` takes the format ``[type][number]``,
3554where ``type`` is a single character specifying the resource type and ``number`` is the virtual register number.
3555
3556Register types are:
3557t for shader resource views (SRV),
3558s for samplers,
3559u for unordered access views (UAV),
3560b for constant buffer views (CBV).
3561
3562Register space is specified in the format ``space[number]`` and defaults to ``space0`` if omitted.
3563Here're resource binding examples with and without space:
3564
3565.. code-block:: hlsl
3566
3567 RWBuffer<float> Uav : register(u3, space1);
3568 Buffer<float> Buf : register(t1);
3569
3570The full documentation is available here: https://docs.microsoft.com/en-us/windows/win32/direct3d12/resource-binding-in-hlsl)reST";
3571
3572static const char AttrDoc_HLSLResourceClass[] = R"reST()reST";
3573
3574static const char AttrDoc_HLSLSV_DispatchThreadID[] = R"reST(The ``SV_DispatchThreadID`` semantic, when applied to an input parameter,
3575specifies a data binding to map the global thread offset within the Dispatch
3576call (per dimension of the group) to the specified parameter.
3577When applied to a field of a struct, the data binding is specified to the field
3578when the struct is used as a parameter type.
3579The semantic on the field is ignored when not used as a parameter.
3580This attribute is only supported in compute shaders.
3581
3582The full documentation is available here: https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/sv-dispatchthreadid)reST";
3583
3584static const char AttrDoc_HLSLSV_GroupID[] = R"reST(The ``SV_GroupID`` semantic, when applied to an input parameter, specifies which
3585thread group a shader is executing in. This attribute is only supported in compute shaders.
3586
3587The full documentation is available here: https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/sv-groupid)reST";
3588
3589static const char AttrDoc_HLSLSV_GroupIndex[] = R"reST(The ``SV_GroupIndex`` semantic, when applied to an input parameter, specifies a
3590data binding to map the group index to the specified parameter. This attribute
3591is only supported in compute shaders.
3592
3593The full documentation is available here: https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/sv-groupindex)reST";
3594
3595static const char AttrDoc_HLSLSV_GroupThreadID[] = R"reST(The ``SV_GroupThreadID`` semantic, when applied to an input parameter, specifies which
3596individual thread within a thread group is executing in. This attribute is
3597only supported in compute shaders.
3598
3599The full documentation is available here: https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/sv-groupthreadid)reST";
3600
3601static const char AttrDoc_HLSLSV_Position[] = R"reST(The ``SV_Position`` semantic, when applied to an input parameter in a pixel
3602shader, contains the location of the pixel center (x, y) in screen space.
3603This semantic can be applied to the parameter, or a field in a struct used
3604as an input parameter.
3605This attribute is supported as an input in pixel, hull, domain and mesh shaders.
3606This attribute is supported as an output in vertex, geometry and domain shaders.
3607
3608The full documentation is available here: https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-semantics)reST";
3609
3610static const char AttrDoc_HLSLShader[] = R"reST(The ``shader`` type attribute applies to HLSL shader entry functions to
3611identify the shader type for the entry function.
3612The syntax is:
3613
3614.. code-block:: text
3615
3616 ``[shader(string-literal)]``
3617
3618where the string literal is one of: "pixel", "vertex", "geometry", "hull",
3619"domain", "compute", "raygeneration", "intersection", "anyhit", "closesthit",
3620"miss", "callable", "mesh", "amplification". Normally the shader type is set
3621by shader target with the ``-T`` option like ``-Tps_6_1``. When compiling to a
3622library target like ``lib_6_3``, the shader type attribute can help the
3623compiler to identify the shader type. It is mostly used by Raytracing shaders
3624where shaders must be compiled into a library and linked at runtime.)reST";
3625
3626static const char AttrDoc_HLSLVkConstantId[] = R"reST(The ``vk::constant_id`` attribute specifies the id for a SPIR-V specialization
3627constant. The attribute applies to const global scalar variables. The variable must be initialized with a C++11 constexpr.
3628In SPIR-V, the
3629variable will be replaced with an `OpSpecConstant` with the given id.
3630The syntax is:
3631
3632.. code-block:: text
3633
3634 ``[[vk::constant_id(<Id>)]] const T Name = <Init>``)reST";
3635
3636static const char AttrDoc_HLSLVkExtBuiltinInput[] = R"reST(Vulkan shaders have `Input` builtins. Those variables are externally
3637initialized by the driver/pipeline, but each copy is private to the current
3638lane.
3639
3640Those builtins can be declared using the `[[vk::ext_builtin_input]]` attribute
3641like follows:
3642
3643.. code-block:: c++
3644
3645 [[vk::ext_builtin_input(/* WorkgroupId */ 26)]]
3646 static const uint3 groupid;
3647
3648This variable will be lowered into a module-level variable, with the `Input`
3649storage class, and the `BuiltIn 26` decoration.
3650
3651The full documentation for this inline SPIR-V attribute can be found here:
3652https://github.com/microsoft/hlsl-specs/blob/main/proposals/0011-inline-spirv.md)reST";
3653
3654static const char AttrDoc_HLSLWaveSize[] = R"reST(The ``WaveSize`` attribute specify a wave size on a shader entry point in order
3655to indicate either that a shader depends on or strongly prefers a specific wave
3656size.
3657There're 2 versions of the attribute: ``WaveSize`` and ``RangedWaveSize``.
3658The syntax for ``WaveSize`` is:
3659
3660.. code-block:: text
3661
3662 ``[WaveSize(<numLanes>)]``
3663
3664The allowed wave sizes that an HLSL shader may specify are the powers of 2
3665between 4 and 128, inclusive.
3666In other words, the set: [4, 8, 16, 32, 64, 128].
3667
3668The syntax for ``RangedWaveSize`` is:
3669
3670.. code-block:: text
3671
3672 ``[WaveSize(<minWaveSize>, <maxWaveSize>, [prefWaveSize])]``
3673
3674Where minWaveSize is the minimum wave size supported by the shader representing
3675the beginning of the allowed range, maxWaveSize is the maximum wave size
3676supported by the shader representing the end of the allowed range, and
3677prefWaveSize is the optional preferred wave size representing the size expected
3678to be the most optimal for this shader.
3679
3680``WaveSize`` is available for HLSL shader model 6.6 and later.
3681``RangedWaveSize`` available for HLSL shader model 6.8 and later.
3682
3683The full documentation is available here: https://microsoft.github.io/DirectX-Specs/d3d/HLSL_SM_6_6_WaveSize.html
3684and https://microsoft.github.io/hlsl-specs/proposals/0013-wave-size-range.html)reST";
3685
3686static const char AttrDoc_Hot[] = R"reST(``__attribute__((hot))`` marks a function as hot, as a manual alternative to PGO hotness data.
3687If PGO data is available, the annotation ``__attribute__((hot))`` overrides the profile count based hotness (unlike ``__attribute__((cold))``).)reST";
3688
3689static const char AttrDoc_HybridPatchable[] = R"reST(The ``hybrid_patchable`` attribute declares an ARM64EC function with an additional
3690x86-64 thunk, which may be patched at runtime.
3691
3692For more information see
3693`ARM64EC ABI documentation <https://learn.microsoft.com/en-us/windows/arm/arm64ec-abi>`_.)reST";
3694
3695static const char AttrDoc_IBAction[] = R"reST(No documentation.)reST";
3696
3697static const char AttrDoc_IBOutlet[] = R"reST(No documentation.)reST";
3698
3699static const char AttrDoc_IBOutletCollection[] = R"reST(No documentation.)reST";
3700
3701static const char AttrDoc_IFunc[] = R"reST(``__attribute__((ifunc("resolver")))`` is used to mark that the address of a
3702declaration should be resolved at runtime by calling a resolver function.
3703
3704The symbol name of the resolver function is given in quotes. A function with
3705this name (after mangling) must be defined in the current translation unit; it
3706may be ``static``. The resolver function should return a pointer.
3707
3708The ``ifunc`` attribute may only be used on a function declaration. A function
3709declaration with an ``ifunc`` attribute is considered to be a definition of the
3710declared entity. The entity must not have weak linkage; for example, in C++,
3711it cannot be applied to a declaration if a definition at that location would be
3712considered inline.
3713
3714Not all targets support this attribute:
3715
3716- ELF target support depends on both the linker and runtime linker, and is
3717 available in at least lld 4.0 and later, binutils 2.20.1 and later, glibc
3718 v2.11.1 and later, and FreeBSD 9.1 and later.
3719- Mach-O targets support it, but with slightly different semantics: the resolver
3720 is run at first call, instead of at load time by the runtime linker.
3721- Windows target supports it on AArch64, but with different semantics: the
3722 ``ifunc`` is replaced with a global function pointer, and the call is replaced
3723 with an indirect call. The function pointer is initialized by a constructor
3724 that calls the resolver.
3725- Baremetal target supports it on AVR.
3726- Other targets currently do not support this attribute.)reST";
3727
3728static const char AttrDoc_InferredNoReturn[] = R"reST()reST";
3729
3730static const char AttrDoc_InitPriority[] = R"reST(In C++, the order in which global variables are initialized across translation
3731units is unspecified, unlike the ordering within a single translation unit. The
3732``init_priority`` attribute allows you to specify a relative ordering for the
3733initialization of objects declared at namespace scope in C++ within a single
3734linked image on supported platforms. The priority is given as an integer constant
3735expression between 101 and 65535 (inclusive). Priorities outside of that range are
3736reserved for use by the implementation. A lower value indicates a higher priority
3737of initialization. Note that only the relative ordering of values is important.
3738For example:
3739
3740.. code-block:: c++
3741
3742 struct SomeType { SomeType(); };
3743 __attribute__((init_priority(200))) SomeType Obj1;
3744 __attribute__((init_priority(101))) SomeType Obj2;
3745
3746``Obj2`` will be initialized *before* ``Obj1`` despite the usual order of
3747initialization being the opposite.
3748
3749Note that this attribute does not control the initialization order of objects
3750across final linked image boundaries like shared objects and executables.
3751
3752On Windows, ``init_seg(compiler)`` is represented with a priority of 200 and
3753``init_seg(library)`` is represented with a priority of 400. ``init_seg(user)``
3754uses the default 65535 priority.
3755
3756On MachO platforms, this attribute also does not control the order of initialization
3757across translation units, where it only affects the order within a single TU.
3758
3759This attribute is only supported for C++ and Objective-C++ and is ignored in
3760other language modes. Currently, this attribute is not implemented on z/OS.)reST";
3761
3762static const char AttrDoc_InitSeg[] = R"reST(The attribute applied by ``pragma init_seg()`` controls the section into
3763which global initialization function pointers are emitted. It is only
3764available with ``-fms-extensions``. Typically, this function pointer is
3765emitted into ``.CRT$XCU`` on Windows. The user can change the order of
3766initialization by using a different section name with the same
3767``.CRT$XC`` prefix and a suffix that sorts lexicographically before or
3768after the standard ``.CRT$XCU`` sections. See the init_seg_
3769documentation on MSDN for more information.
3770
3771.. _init_seg: http://msdn.microsoft.com/en-us/library/7977wcck(v=vs.110).aspx)reST";
3772
3773static const char AttrDoc_IntelOclBicc[] = R"reST(No documentation.)reST";
3774
3775static const char AttrDoc_InternalLinkage[] = R"reST(The ``internal_linkage`` attribute changes the linkage type of the declaration
3776to internal. This is similar to C-style ``static``, but can be used on classes
3777and class methods. When applied to a class definition, this attribute affects
3778all methods and static data members of that class. This can be used to contain
3779the ABI of a C++ library by excluding unwanted class methods from the export
3780tables.)reST";
3781
3782static const char AttrDoc_LTOVisibilityPublic[] = R"reST(See :doc:`LTOVisibility`.)reST";
3783
3784static const char AttrDoc_LayoutVersion[] = R"reST(The layout_version attribute requests that the compiler utilize the class
3785layout rules of a particular compiler version.
3786This attribute only applies to struct, class, and union types.
3787It is only supported when using the Microsoft C++ ABI.)reST";
3788
3789static const char AttrDoc_Leaf[] = R"reST(The ``leaf`` attribute is used as a compiler hint to improve dataflow analysis
3790in library functions. Functions marked with the ``leaf`` attribute are not allowed
3791to jump back into the caller's translation unit, whether through invoking a
3792callback function, an external function call, use of ``longjmp``, or other means.
3793Therefore, they cannot use or modify any data that does not escape the caller function's
3794compilation unit.
3795
3796For more information see
3797`gcc documentation <https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html>`)reST";
3798
3799static const char AttrDoc_LifetimeBound[] = R"reST(The ``lifetimebound`` attribute on a function parameter or implicit object
3800parameter indicates that objects that are referred to by that parameter may
3801also be referred to by the return value of the annotated function (or, for a
3802parameter of a constructor, by the value of the constructed object).
3803
3804By default, a reference is considered to refer to its referenced object, a
3805pointer is considered to refer to its pointee, a ``std::initializer_list<T>``
3806is considered to refer to its underlying array, and aggregates (arrays and
3807simple ``struct``\s) are considered to refer to all objects that their
3808transitive subobjects refer to.
3809
3810Clang warns if it is able to detect that an object or reference refers to
3811another object with a shorter lifetime. For example, Clang will warn if a
3812function returns a reference to a local variable, or if a reference is bound to
3813a temporary object whose lifetime is not extended. By using the
3814``lifetimebound`` attribute, this determination can be extended to look through
3815user-declared functions. For example:
3816
3817.. code-block:: c++
3818
3819 #include <map>
3820 #include <string>
3821
3822 using namespace std::literals;
3823
3824 // Returns m[key] if key is present, or default_value if not.
3825 template<typename T, typename U>
3826 const U &get_or_default(const std::map<T, U> &m [[clang::lifetimebound]],
3827 const T &key, /* note, not lifetimebound */
3828 const U &default_value [[clang::lifetimebound]]) {
3829 if (auto iter = m.find(key); iter != m.end()) return iter->second;
3830 else return default_value;
3831 }
3832
3833 int main() {
3834 std::map<std::string, std::string> m;
3835 // warning: temporary bound to local reference 'val1' will be destroyed
3836 // at the end of the full-expression
3837 const std::string &val1 = get_or_default(m, "foo"s, "bar"s);
3838
3839 // No warning in this case.
3840 std::string def_val = "bar"s;
3841 const std::string &val2 = get_or_default(m, "foo"s, def_val);
3842
3843 return 0;
3844 }
3845
3846The attribute can be applied to the implicit ``this`` parameter of a member
3847function by writing the attribute after the function type:
3848
3849.. code-block:: c++
3850
3851 struct string {
3852 // The returned pointer should not outlive ``*this``.
3853 const char *data() const [[clang::lifetimebound]];
3854 };
3855
3856This attribute is inspired by the C++ committee paper `P0936R0
3857<http://wg21.link/p0936r0>`_, but does not affect whether temporary objects
3858have their lifetimes extended.)reST";
3859
3860static const char AttrDoc_LifetimeCaptureBy[] = R"reST(Similar to `lifetimebound`_, the ``lifetime_capture_by(X)`` attribute on a
3861function parameter or implicit object parameter indicates that the capturing
3862entity ``X`` may refer to the object referred by that parameter.
3863
3864Below is a list of types of the parameters and what they're considered to refer to:
3865
3866- A reference param (of non-view type) is considered to refer to its referenced object.
3867- A pointer param (of non-view type) is considered to refer to its pointee.
3868- View type param (type annotated with ``[[gsl::Pointer()]]``) is considered to refer
3869 to its pointee (gsl owner). This holds true even if the view type appears as a reference
3870 in the parameter. For example, both ``std::string_view`` and
3871 ``const std::string_view &`` are considered to refer to a ``std::string``.
3872- A ``std::initializer_list<T>`` is considered to refer to its underlying array.
3873- Aggregates (arrays and simple ``struct``\s) are considered to refer to all
3874 objects that their transitive subobjects refer to.
3875
3876Clang would diagnose when a temporary object is used as an argument to such an
3877annotated parameter.
3878In this case, the capturing entity ``X`` could capture a dangling reference to this
3879temporary object.
3880
3881.. code-block:: c++
3882
3883 void addToSet(std::string_view a [[clang::lifetime_capture_by(s)]], std::set<std::string_view>& s) {
3884 s.insert(a);
3885 }
3886 void use() {
3887 std::set<std::string_view> s;
3888 addToSet(std::string(), s); // Warning: object whose reference is captured by 's' will be destroyed at the end of the full-expression.
3889 // ^^^^^^^^^^^^^
3890 std::string local;
3891 addToSet(local, s); // Ok.
3892 }
3893
3894The capturing entity ``X`` can be one of the following:
3895
3896- Another (named) function parameter.
3897
3898 .. code-block:: c++
3899
3900 void addToSet(std::string_view a [[clang::lifetime_capture_by(s)]], std::set<std::string_view>& s) {
3901 s.insert(a);
3902 }
3903
3904- ``this`` (in case of member functions).
3905
3906 .. code-block:: c++
3907
3908 class S {
3909 void addToSet(std::string_view a [[clang::lifetime_capture_by(this)]]) {
3910 s.insert(a);
3911 }
3912 std::set<std::string_view> s;
3913 };
3914
3915 Note: When applied to a constructor parameter, `[[clang::lifetime_capture_by(this)]]` is just an alias of `[[clang::lifetimebound]]`.
3916
3917- `global`, `unknown`.
3918
3919 .. code-block:: c++
3920
3921 std::set<std::string_view> s;
3922 void addToSet(std::string_view a [[clang::lifetime_capture_by(global)]]) {
3923 s.insert(a);
3924 }
3925 void addSomewhere(std::string_view a [[clang::lifetime_capture_by(unknown)]]);
3926
3927The attribute can be applied to the implicit ``this`` parameter of a member
3928function by writing the attribute after the function type:
3929
3930.. code-block:: c++
3931
3932 struct S {
3933 const char *data(std::set<S*>& s) [[clang::lifetime_capture_by(s)]] {
3934 s.insert(this);
3935 }
3936 };
3937
3938The attribute supports specifying more than one capturing entities:
3939
3940.. code-block:: c++
3941
3942 void addToSets(std::string_view a [[clang::lifetime_capture_by(s1, s2)]],
3943 std::set<std::string_view>& s1,
3944 std::set<std::string_view>& s2) {
3945 s1.insert(a);
3946 s2.insert(a);
3947 }
3948
3949Limitation: The capturing entity ``X`` is not used by the analysis and is
3950used for documentation purposes only. This is because the analysis is
3951statement-local and only detects use of a temporary as an argument to the
3952annotated parameter.
3953
3954.. code-block:: c++
3955
3956 void addToSet(std::string_view a [[clang::lifetime_capture_by(s)]], std::set<std::string_view>& s);
3957 void use() {
3958 std::set<std::string_view> s;
3959 if (foo()) {
3960 std::string str;
3961 addToSet(str, s); // Not detected.
3962 }
3963 })reST";
3964
3965static const char AttrDoc_Likely[] = R"reST(The ``likely`` and ``unlikely`` attributes are used as compiler hints.
3966The attributes are used to aid the compiler to determine which branch is
3967likely or unlikely to be taken. This is done by marking the branch substatement
3968with one of the two attributes.
3969
3970It isn't allowed to annotate a single statement with both ``likely`` and
3971``unlikely``. Annotating the ``true`` and ``false`` branch of an ``if``
3972statement with the same likelihood attribute will result in a diagnostic and
3973the attributes are ignored on both branches.
3974
3975In a ``switch`` statement it's allowed to annotate multiple ``case`` labels
3976or the ``default`` label with the same likelihood attribute. This makes
3977* all labels without an attribute have a neutral likelihood,
3978* all labels marked ``[[likely]]`` have an equally positive likelihood, and
3979* all labels marked ``[[unlikely]]`` have an equally negative likelihood.
3980The neutral likelihood is the more likely of path execution than the negative
3981likelihood. The positive likelihood is the more likely of path of execution
3982than the neutral likelihood.
3983
3984These attributes have no effect on the generated code when using
3985PGO (Profile-Guided Optimization) or at optimization level 0.
3986
3987In Clang, the attributes will be ignored if they're not placed on
3988* the ``case`` or ``default`` label of a ``switch`` statement,
3989* or on the substatement of an ``if`` or ``else`` statement,
3990* or on the substatement of an ``for`` or ``while`` statement.
3991The C++ Standard recommends to honor them on every statement in the
3992path of execution, but that can be confusing:
3993
3994.. code-block:: c++
3995
3996 if (b) {
3997 [[unlikely]] --b; // In the path of execution,
3998 // this branch is considered unlikely.
3999 }
4000
4001 if (b) {
4002 --b;
4003 if(b)
4004 return;
4005 [[unlikely]] --b; // Not in the path of execution,
4006 } // the branch has no likelihood information.
4007
4008 if (b) {
4009 --b;
4010 foo(b);
4011 // Whether or not the next statement is in the path of execution depends
4012 // on the declaration of foo():
4013 // In the path of execution: void foo(int);
4014 // Not in the path of execution: [[noreturn]] void foo(int);
4015 // This means the likelihood of the branch depends on the declaration
4016 // of foo().
4017 [[unlikely]] --b;
4018 }
4019
4020
4021Below are some example usages of the likelihood attributes and their effects:
4022
4023.. code-block:: c++
4024
4025 if (b) [[likely]] { // Placement on the first statement in the branch.
4026 // The compiler will optimize to execute the code here.
4027 } else {
4028 }
4029
4030 if (b)
4031 [[unlikely]] b++; // Placement on the first statement in the branch.
4032 else {
4033 // The compiler will optimize to execute the code here.
4034 }
4035
4036 if (b) {
4037 [[unlikely]] b++; // Placement on the second statement in the branch.
4038 } // The attribute will be ignored.
4039
4040 if (b) [[likely]] {
4041 [[unlikely]] b++; // No contradiction since the second attribute
4042 } // is ignored.
4043
4044 if (b)
4045 ;
4046 else [[likely]] {
4047 // The compiler will optimize to execute the code here.
4048 }
4049
4050 if (b)
4051 ;
4052 else
4053 // The compiler will optimize to execute the next statement.
4054 [[likely]] b = f();
4055
4056 if (b) [[likely]]; // Both branches are likely. A diagnostic is issued
4057 else [[likely]]; // and the attributes are ignored.
4058
4059 if (b)
4060 [[likely]] int i = 5; // Issues a diagnostic since the attribute
4061 // isn't allowed on a declaration.
4062
4063 switch (i) {
4064 [[likely]] case 1: // This value is likely
4065 ...
4066 break;
4067
4068 [[unlikely]] case 2: // This value is unlikely
4069 ...
4070 [[fallthrough]];
4071
4072 case 3: // No likelihood attribute
4073 ...
4074 [[likely]] break; // No effect
4075
4076 case 4: [[likely]] { // attribute on substatement has no effect
4077 ...
4078 break;
4079 }
4080
4081 [[unlikely]] default: // All other values are unlikely
4082 ...
4083 break;
4084 }
4085
4086 switch (i) {
4087 [[likely]] case 0: // This value and code path is likely
4088 ...
4089 [[fallthrough]];
4090
4091 case 1: // No likelihood attribute, code path is neutral
4092 break; // falling through has no effect on the likelihood
4093
4094 case 2: // No likelihood attribute, code path is neutral
4095 [[fallthrough]];
4096
4097 [[unlikely]] default: // This value and code path are both unlikely
4098 break;
4099 }
4100
4101 for(int i = 0; i != size; ++i) [[likely]] {
4102 ... // The loop is the likely path of execution
4103 }
4104
4105 for(const auto &E : Elements) [[likely]] {
4106 ... // The loop is the likely path of execution
4107 }
4108
4109 while(i != size) [[unlikely]] {
4110 ... // The loop is the unlikely path of execution
4111 } // The generated code will optimize to skip the loop body
4112
4113 while(true) [[unlikely]] {
4114 ... // The attribute has no effect
4115 } // Clang elides the comparison and generates an infinite
4116 // loop)reST";
4117
4118static const char AttrDoc_LoaderUninitialized[] = R"reST(The ``loader_uninitialized`` attribute can be placed on global variables to
4119indicate that the variable does not need to be zero initialized by the loader.
4120On most targets, zero-initialization does not incur any additional cost.
4121For example, most general purpose operating systems deliberately ensure
4122that all memory is properly initialized in order to avoid leaking privileged
4123information from the kernel or other programs. However, some targets
4124do not make this guarantee, and on these targets, avoiding an unnecessary
4125zero-initialization can have a significant impact on load times and/or code
4126size.
4127
4128A declaration with this attribute is a non-tentative definition just as if it
4129provided an initializer. Variables with this attribute are considered to be
4130uninitialized in the same sense as a local variable, and the programs must
4131write to them before reading from them. If the variable's type is a C++ class
4132type with a non-trivial default constructor, or an array thereof, this attribute
4133only suppresses the static zero-initialization of the variable, not the dynamic
4134initialization provided by executing the default constructor.)reST";
4135
4136static const char AttrDoc_LockReturned[] = R"reST(No documentation.)reST";
4137
4138static const char AttrDoc_LocksExcluded[] = R"reST(No documentation.)reST";
4139
4140static const char AttrDoc_LoopHint[] = R"reST(The ``#pragma clang loop`` directive allows loop optimization hints to be
4141specified for the subsequent loop. The directive allows pipelining to be
4142disabled, or vectorization, vector predication, interleaving, and unrolling to
4143be enabled or disabled. Vector width, vector predication, interleave count,
4144unrolling count, and the initiation interval for pipelining can be explicitly
4145specified. See `language extensions
4146<http://clang.llvm.org/docs/LanguageExtensions.html#extensions-for-loop-hint-optimizations>`_
4147for details.)reST";
4148
4149static const char AttrDoc_M68kInterrupt[] = R"reST(No documentation.)reST";
4150
4151static const char AttrDoc_M68kRTD[] = R"reST(On M68k targets, this attribute changes the calling convention of a function
4152to clear parameters off the stack on return. In other words, callee is
4153responsible for cleaning out the stack space allocated for incoming paramters.
4154This convention does not support variadic calls or unprototyped functions in C.
4155When targeting M68010 or newer CPUs, this calling convention is implemented
4156using the `rtd` instruction.)reST";
4157
4158static const char AttrDoc_MIGServerRoutine[] = R"reST(The Mach Interface Generator release-on-success convention dictates
4159functions that follow it to only release arguments passed to them when they
4160return "success" (a ``kern_return_t`` error code that indicates that
4161no errors have occurred). Otherwise the release is performed by the MIG client
4162that called the function. The annotation ``__attribute__((mig_server_routine))``
4163is applied in order to specify which functions are expected to follow the
4164convention. This allows the Static Analyzer to find bugs caused by violations of
4165that convention. The attribute would normally appear on the forward declaration
4166of the actual server routine in the MIG server header, but it may also be
4167added to arbitrary functions that need to follow the same convention - for
4168example, a user can add them to auxiliary functions called by the server routine
4169that have their return value of type ``kern_return_t`` unconditionally returned
4170from the routine. The attribute can be applied to C++ methods, and in this case
4171it will be automatically applied to overrides if the method is virtual. The
4172attribute can also be written using C++11 syntax: ``[[mig::server_routine]]``.)reST";
4173
4174static const char AttrDoc_MSABI[] = R"reST(On non-Windows x86_64 targets, this attribute changes the calling convention of
4175a function to match the default convention used on Windows x86_64. This
4176attribute has no effect on Windows targets or non-x86_64 targets.)reST";
4177
4178static const char AttrDoc_MSAllocator[] = R"reST(The ``__declspec(allocator)`` attribute is applied to functions that allocate
4179memory, such as operator new in C++. When CodeView debug information is emitted
4180(enabled by ``clang -gcodeview`` or ``clang-cl /Z7``), Clang will attempt to
4181record the code offset of heap allocation call sites in the debug info. It will
4182also record the type being allocated using some local heuristics. The Visual
4183Studio debugger uses this information to `profile memory usage`_.
4184
4185.. _profile memory usage: https://docs.microsoft.com/en-us/visualstudio/profiling/memory-usage
4186
4187This attribute does not affect optimizations in any way, unlike GCC's
4188``__attribute__((malloc))``.)reST";
4189
4190static const char AttrDoc_MSConstexpr[] = R"reST(The ``[[msvc::constexpr]]`` attribute can be applied only to a function
4191definition or a ``return`` statement. It does not impact function declarations.
4192A ``[[msvc::constexpr]]`` function cannot be ``constexpr`` or ``consteval``.
4193A ``[[msvc::constexpr]]`` function is treated as if it were a ``constexpr`` function
4194when it is evaluated in a constant context of ``[[msvc::constexpr]] return`` statement.
4195Otherwise, it is treated as a regular function.
4196
4197Semantics of this attribute are enabled only under MSVC compatibility
4198(``-fms-compatibility-version``) 19.33 and later.)reST";
4199
4200static const char AttrDoc_MSInheritance[] = R"reST(This collection of keywords is enabled under ``-fms-extensions`` and controls
4201the pointer-to-member representation used on ``*-*-win32`` targets.
4202
4203The ``*-*-win32`` targets utilize a pointer-to-member representation which
4204varies in size and alignment depending on the definition of the underlying
4205class.
4206
4207However, this is problematic when a forward declaration is only available and
4208no definition has been made yet. In such cases, Clang is forced to utilize the
4209most general representation that is available to it.
4210
4211These keywords make it possible to use a pointer-to-member representation other
4212than the most general one regardless of whether or not the definition will ever
4213be present in the current translation unit.
4214
4215This family of keywords belong between the ``class-key`` and ``class-name``:
4216
4217.. code-block:: c++
4218
4219 struct __single_inheritance S;
4220 int S::*i;
4221 struct S {};
4222
4223This keyword can be applied to class templates but only has an effect when used
4224on full specializations:
4225
4226.. code-block:: c++
4227
4228 template <typename T, typename U> struct __single_inheritance A; // warning: inheritance model ignored on primary template
4229 template <typename T> struct __multiple_inheritance A<T, T>; // warning: inheritance model ignored on partial specialization
4230 template <> struct __single_inheritance A<int, float>;
4231
4232Note that choosing an inheritance model less general than strictly necessary is
4233an error:
4234
4235.. code-block:: c++
4236
4237 struct __multiple_inheritance S; // error: inheritance model does not match definition
4238 int S::*i;
4239 struct S {};)reST";
4240
4241static const char AttrDoc_MSNoVTable[] = R"reST(This attribute can be added to a class declaration or definition to signal to
4242the compiler that constructors and destructors will not reference the virtual
4243function table. It is only supported when using the Microsoft C++ ABI.)reST";
4244
4245static const char AttrDoc_MSP430Interrupt[] = R"reST(No documentation.)reST";
4246
4247static const char AttrDoc_MSStruct[] = R"reST(No documentation.)reST";
4248
4249static const char AttrDoc_MSVtorDisp[] = R"reST()reST";
4250
4251static const char AttrDoc_MaxFieldAlignment[] = R"reST()reST";
4252
4253static const char AttrDoc_MayAlias[] = R"reST(No documentation.)reST";
4254
4255static const char AttrDoc_MaybeUndef[] = R"reST(The ``maybe_undef`` attribute can be placed on a function parameter. It indicates
4256that the parameter is allowed to use undef values. It informs the compiler
4257to insert a freeze LLVM IR instruction on the function parameter.
4258Please note that this is an attribute that is used as an internal
4259implementation detail and not intended to be used by external users.
4260
4261In languages HIP, CUDA etc., some functions have multi-threaded semantics and
4262it is enough for only one or some threads to provide defined arguments.
4263Depending on semantics, undef arguments in some threads don't produce
4264undefined results in the function call. Since, these functions accept undefined
4265arguments, ``maybe_undef`` attribute can be placed.
4266
4267Sample usage:
4268.. code-block:: c
4269
4270 void maybeundeffunc(int __attribute__((maybe_undef))param);)reST";
4271
4272static const char AttrDoc_MicroMips[] = R"reST(Clang supports the GNU style ``__attribute__((micromips))`` and
4273``__attribute__((nomicromips))`` attributes on MIPS targets. These attributes
4274may be attached to a function definition and instructs the backend to generate
4275or not to generate microMIPS code for that function.
4276
4277These attributes override the ``-mmicromips`` and ``-mno-micromips`` options
4278on the command line.)reST";
4279
4280static const char AttrDoc_MinSize[] = R"reST(This function attribute indicates that optimization passes and code generator passes
4281make choices that keep the function code size as small as possible. Optimizations may
4282also sacrifice runtime performance in order to minimize the size of the generated code.)reST";
4283
4284static const char AttrDoc_MinVectorWidth[] = R"reST(Clang supports the ``__attribute__((min_vector_width(width)))`` attribute. This
4285attribute may be attached to a function and informs the backend that this
4286function desires vectors of at least this width to be generated. Target-specific
4287maximum vector widths still apply. This means even if you ask for something
4288larger than the target supports, you will only get what the target supports.
4289This attribute is meant to be a hint to control target heuristics that may
4290generate narrower vectors than what the target hardware supports.
4291
4292This is currently used by the X86 target to allow some CPUs that support 512-bit
4293vectors to be limited to using 256-bit vectors to avoid frequency penalties.
4294This is currently enabled with the ``-prefer-vector-width=256`` command line
4295option. The ``min_vector_width`` attribute can be used to prevent the backend
4296from trying to split vector operations to match the ``prefer-vector-width``. All
4297X86 vector intrinsics from x86intrin.h already set this attribute. Additionally,
4298use of any of the X86-specific vector builtins will implicitly set this
4299attribute on the calling function. The intent is that explicitly writing vector
4300code using the X86 intrinsics will prevent ``prefer-vector-width`` from
4301affecting the code.)reST";
4302
4303static const char AttrDoc_Mips16[] = R"reST(No documentation.)reST";
4304
4305static const char AttrDoc_MipsInterrupt[] = R"reST(Clang supports the GNU style ``__attribute__((interrupt("ARGUMENT")))`` attribute on
4306MIPS targets. This attribute may be attached to a function definition and instructs
4307the backend to generate appropriate function entry/exit code so that it can be used
4308directly as an interrupt service routine.
4309
4310By default, the compiler will produce a function prologue and epilogue suitable for
4311an interrupt service routine that handles an External Interrupt Controller (eic)
4312generated interrupt. This behavior can be explicitly requested with the "eic"
4313argument.
4314
4315Otherwise, for use with vectored interrupt mode, the argument passed should be
4316of the form "vector=LEVEL" where LEVEL is one of the following values:
4317"sw0", "sw1", "hw0", "hw1", "hw2", "hw3", "hw4", "hw5". The compiler will
4318then set the interrupt mask to the corresponding level which will mask all
4319interrupts up to and including the argument.
4320
4321The semantics are as follows:
4322
4323- The prologue is modified so that the Exception Program Counter (EPC) and
4324 Status coprocessor registers are saved to the stack. The interrupt mask is
4325 set so that the function can only be interrupted by a higher priority
4326 interrupt. The epilogue will restore the previous values of EPC and Status.
4327
4328- The prologue and epilogue are modified to save and restore all non-kernel
4329 registers as necessary.
4330
4331- The FPU is disabled in the prologue, as the floating pointer registers are not
4332 spilled to the stack.
4333
4334- The function return sequence is changed to use an exception return instruction.
4335
4336- The parameter sets the interrupt mask for the function corresponding to the
4337 interrupt level specified. If no mask is specified the interrupt mask
4338 defaults to "eic".)reST";
4339
4340static const char AttrDoc_MipsLongCall[] = R"reST(Clang supports the ``__attribute__((long_call))``, ``__attribute__((far))``,
4341and ``__attribute__((near))`` attributes on MIPS targets. These attributes may
4342only be added to function declarations and change the code generated
4343by the compiler when directly calling the function. The ``near`` attribute
4344allows calls to the function to be made using the ``jal`` instruction, which
4345requires the function to be located in the same naturally aligned 256MB
4346segment as the caller. The ``long_call`` and ``far`` attributes are synonyms
4347and require the use of a different call sequence that works regardless
4348of the distance between the functions.
4349
4350These attributes have no effect for position-independent code.
4351
4352These attributes take priority over command line switches such
4353as ``-mlong-calls`` and ``-mno-long-calls``.)reST";
4354
4355static const char AttrDoc_MipsShortCall[] = R"reST(Clang supports the ``__attribute__((long_call))``, ``__attribute__((far))``,
4356``__attribute__((short__call))``, and ``__attribute__((near))`` attributes
4357on MIPS targets. These attributes may only be added to function declarations
4358and change the code generated by the compiler when directly calling
4359the function. The ``short_call`` and ``near`` attributes are synonyms and
4360allow calls to the function to be made using the ``jal`` instruction, which
4361requires the function to be located in the same naturally aligned 256MB segment
4362as the caller. The ``long_call`` and ``far`` attributes are synonyms and
4363require the use of a different call sequence that works regardless
4364of the distance between the functions.
4365
4366These attributes have no effect for position-independent code.
4367
4368These attributes take priority over command line switches such
4369as ``-mlong-calls`` and ``-mno-long-calls``.)reST";
4370
4371static const char AttrDoc_Mode[] = R"reST(No documentation.)reST";
4372
4373static const char AttrDoc_MustTail[] = R"reST(If a ``return`` statement is marked ``musttail``, this indicates that the
4374compiler must generate a tail call for the program to be correct, even when
4375optimizations are disabled. This guarantees that the call will not cause
4376unbounded stack growth if it is part of a recursive cycle in the call graph.
4377
4378If the callee is a virtual function that is implemented by a thunk, there is
4379no guarantee in general that the thunk tail-calls the implementation of the
4380virtual function, so such a call in a recursive cycle can still result in
4381unbounded stack growth.
4382
4383``clang::musttail`` can only be applied to a ``return`` statement whose value
4384is the result of a function call (even functions returning void must use
4385``return``, although no value is returned). The target function must have the
4386same number of arguments as the caller. The types of the return value and all
4387arguments must be similar according to C++ rules (differing only in cv
4388qualifiers or array size), including the implicit "this" argument, if any.
4389Any variables in scope, including all arguments to the function and the
4390return value must be trivially destructible. The calling convention of the
4391caller and callee must match, and they must not be variadic functions or have
4392old style K&R C function declarations.
4393
4394The lifetimes of all local variables and function parameters end immediately
4395before the call to the function. This means that it is undefined behaviour to
4396pass a pointer or reference to a local variable to the called function, which
4397is not the case without the attribute. Clang will emit a warning in common
4398cases where this happens.
4399
4400``clang::musttail`` provides assurances that the tail call can be optimized on
4401all targets, not just one.)reST";
4402
4403static const char AttrDoc_NSConsumed[] = R"reST(The behavior of a function with respect to reference counting for Foundation
4404(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
4405convention (e.g. functions starting with "get" are assumed to return at
4406``+0``).
4407
4408It can be overridden using a family of the following attributes. In
4409Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
4410a function communicates that the object is returned at ``+1``, and the caller
4411is responsible for freeing it.
4412Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
4413specifies that the object is returned at ``+0`` and the ownership remains with
4414the callee.
4415The annotation ``__attribute__((ns_consumes_self))`` specifies that
4416the Objective-C method call consumes the reference to ``self``, e.g. by
4417attaching it to a supplied parameter.
4418Additionally, parameters can have an annotation
4419``__attribute__((ns_consumed))``, which specifies that passing an owned object
4420as that parameter effectively transfers the ownership, and the caller is no
4421longer responsible for it.
4422These attributes affect code generation when interacting with ARC code, and
4423they are used by the Clang Static Analyzer.
4424
4425In C programs using CoreFoundation, a similar set of attributes:
4426``__attribute__((cf_returns_not_retained))``,
4427``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
4428have the same respective semantics when applied to CoreFoundation objects.
4429These attributes affect code generation when interacting with ARC code, and
4430they are used by the Clang Static Analyzer.
4431
4432Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
4433the same attribute family is present:
4434``__attribute__((os_returns_not_retained))``,
4435``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
4436with the same respective semantics.
4437Similar to ``__attribute__((ns_consumes_self))``,
4438``__attribute__((os_consumes_this))`` specifies that the method call consumes
4439the reference to "this" (e.g., when attaching it to a different object supplied
4440as a parameter).
4441Out parameters (parameters the function is meant to write into,
4442either via pointers-to-pointers or references-to-pointers)
4443may be annotated with ``__attribute__((os_returns_retained))``
4444or ``__attribute__((os_returns_not_retained))`` which specifies that the object
4445written into the out parameter should (or respectively should not) be released
4446after use.
4447Since often out parameters may or may not be written depending on the exit
4448code of the function,
4449annotations ``__attribute__((os_returns_retained_on_zero))``
4450and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
4451an out parameter at ``+1`` is written if and only if the function returns a zero
4452(respectively non-zero) error code.
4453Observe that return-code-dependent out parameter annotations are only
4454available for retained out parameters, as non-retained object do not have to be
4455released by the callee.
4456These attributes are only used by the Clang Static Analyzer.
4457
4458The family of attributes ``X_returns_X_retained`` can be added to functions,
4459C++ methods, and Objective-C methods and properties.
4460Attributes ``X_consumed`` can be added to parameters of methods, functions,
4461and Objective-C methods.)reST";
4462
4463static const char AttrDoc_NSConsumesSelf[] = R"reST(The behavior of a function with respect to reference counting for Foundation
4464(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
4465convention (e.g. functions starting with "get" are assumed to return at
4466``+0``).
4467
4468It can be overridden using a family of the following attributes. In
4469Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
4470a function communicates that the object is returned at ``+1``, and the caller
4471is responsible for freeing it.
4472Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
4473specifies that the object is returned at ``+0`` and the ownership remains with
4474the callee.
4475The annotation ``__attribute__((ns_consumes_self))`` specifies that
4476the Objective-C method call consumes the reference to ``self``, e.g. by
4477attaching it to a supplied parameter.
4478Additionally, parameters can have an annotation
4479``__attribute__((ns_consumed))``, which specifies that passing an owned object
4480as that parameter effectively transfers the ownership, and the caller is no
4481longer responsible for it.
4482These attributes affect code generation when interacting with ARC code, and
4483they are used by the Clang Static Analyzer.
4484
4485In C programs using CoreFoundation, a similar set of attributes:
4486``__attribute__((cf_returns_not_retained))``,
4487``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
4488have the same respective semantics when applied to CoreFoundation objects.
4489These attributes affect code generation when interacting with ARC code, and
4490they are used by the Clang Static Analyzer.
4491
4492Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
4493the same attribute family is present:
4494``__attribute__((os_returns_not_retained))``,
4495``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
4496with the same respective semantics.
4497Similar to ``__attribute__((ns_consumes_self))``,
4498``__attribute__((os_consumes_this))`` specifies that the method call consumes
4499the reference to "this" (e.g., when attaching it to a different object supplied
4500as a parameter).
4501Out parameters (parameters the function is meant to write into,
4502either via pointers-to-pointers or references-to-pointers)
4503may be annotated with ``__attribute__((os_returns_retained))``
4504or ``__attribute__((os_returns_not_retained))`` which specifies that the object
4505written into the out parameter should (or respectively should not) be released
4506after use.
4507Since often out parameters may or may not be written depending on the exit
4508code of the function,
4509annotations ``__attribute__((os_returns_retained_on_zero))``
4510and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
4511an out parameter at ``+1`` is written if and only if the function returns a zero
4512(respectively non-zero) error code.
4513Observe that return-code-dependent out parameter annotations are only
4514available for retained out parameters, as non-retained object do not have to be
4515released by the callee.
4516These attributes are only used by the Clang Static Analyzer.
4517
4518The family of attributes ``X_returns_X_retained`` can be added to functions,
4519C++ methods, and Objective-C methods and properties.
4520Attributes ``X_consumed`` can be added to parameters of methods, functions,
4521and Objective-C methods.)reST";
4522
4523static const char AttrDoc_NSErrorDomain[] = R"reST(In Cocoa frameworks in Objective-C, one can group related error codes in enums
4524and categorize these enums with error domains.
4525
4526The ``ns_error_domain`` attribute indicates a global ``NSString`` or
4527``CFString`` constant representing the error domain that an error code belongs
4528to. For pointer uniqueness and code size this is a constant symbol, not a
4529literal.
4530
4531The domain and error code need to be used together. The ``ns_error_domain``
4532attribute links error codes to their domain at the source level.
4533
4534This metadata is useful for documentation purposes, for static analysis, and for
4535improving interoperability between Objective-C and Swift. It is not used for
4536code generation in Objective-C.
4537
4538For example:
4539
4540 .. code-block:: objc
4541
4542 #define NS_ERROR_ENUM(_type, _name, _domain) \
4543 enum _name : _type _name; enum __attribute__((ns_error_domain(_domain))) _name : _type
4544
4545 extern NSString *const MyErrorDomain;
4546 typedef NS_ERROR_ENUM(unsigned char, MyErrorEnum, MyErrorDomain) {
4547 MyErrFirst,
4548 MyErrSecond,
4549 };)reST";
4550
4551static const char AttrDoc_NSReturnsAutoreleased[] = R"reST(The behavior of a function with respect to reference counting for Foundation
4552(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
4553convention (e.g. functions starting with "get" are assumed to return at
4554``+0``).
4555
4556It can be overridden using a family of the following attributes. In
4557Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
4558a function communicates that the object is returned at ``+1``, and the caller
4559is responsible for freeing it.
4560Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
4561specifies that the object is returned at ``+0`` and the ownership remains with
4562the callee.
4563The annotation ``__attribute__((ns_consumes_self))`` specifies that
4564the Objective-C method call consumes the reference to ``self``, e.g. by
4565attaching it to a supplied parameter.
4566Additionally, parameters can have an annotation
4567``__attribute__((ns_consumed))``, which specifies that passing an owned object
4568as that parameter effectively transfers the ownership, and the caller is no
4569longer responsible for it.
4570These attributes affect code generation when interacting with ARC code, and
4571they are used by the Clang Static Analyzer.
4572
4573In C programs using CoreFoundation, a similar set of attributes:
4574``__attribute__((cf_returns_not_retained))``,
4575``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
4576have the same respective semantics when applied to CoreFoundation objects.
4577These attributes affect code generation when interacting with ARC code, and
4578they are used by the Clang Static Analyzer.
4579
4580Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
4581the same attribute family is present:
4582``__attribute__((os_returns_not_retained))``,
4583``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
4584with the same respective semantics.
4585Similar to ``__attribute__((ns_consumes_self))``,
4586``__attribute__((os_consumes_this))`` specifies that the method call consumes
4587the reference to "this" (e.g., when attaching it to a different object supplied
4588as a parameter).
4589Out parameters (parameters the function is meant to write into,
4590either via pointers-to-pointers or references-to-pointers)
4591may be annotated with ``__attribute__((os_returns_retained))``
4592or ``__attribute__((os_returns_not_retained))`` which specifies that the object
4593written into the out parameter should (or respectively should not) be released
4594after use.
4595Since often out parameters may or may not be written depending on the exit
4596code of the function,
4597annotations ``__attribute__((os_returns_retained_on_zero))``
4598and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
4599an out parameter at ``+1`` is written if and only if the function returns a zero
4600(respectively non-zero) error code.
4601Observe that return-code-dependent out parameter annotations are only
4602available for retained out parameters, as non-retained object do not have to be
4603released by the callee.
4604These attributes are only used by the Clang Static Analyzer.
4605
4606The family of attributes ``X_returns_X_retained`` can be added to functions,
4607C++ methods, and Objective-C methods and properties.
4608Attributes ``X_consumed`` can be added to parameters of methods, functions,
4609and Objective-C methods.)reST";
4610
4611static const char AttrDoc_NSReturnsNotRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
4612(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
4613convention (e.g. functions starting with "get" are assumed to return at
4614``+0``).
4615
4616It can be overridden using a family of the following attributes. In
4617Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
4618a function communicates that the object is returned at ``+1``, and the caller
4619is responsible for freeing it.
4620Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
4621specifies that the object is returned at ``+0`` and the ownership remains with
4622the callee.
4623The annotation ``__attribute__((ns_consumes_self))`` specifies that
4624the Objective-C method call consumes the reference to ``self``, e.g. by
4625attaching it to a supplied parameter.
4626Additionally, parameters can have an annotation
4627``__attribute__((ns_consumed))``, which specifies that passing an owned object
4628as that parameter effectively transfers the ownership, and the caller is no
4629longer responsible for it.
4630These attributes affect code generation when interacting with ARC code, and
4631they are used by the Clang Static Analyzer.
4632
4633In C programs using CoreFoundation, a similar set of attributes:
4634``__attribute__((cf_returns_not_retained))``,
4635``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
4636have the same respective semantics when applied to CoreFoundation objects.
4637These attributes affect code generation when interacting with ARC code, and
4638they are used by the Clang Static Analyzer.
4639
4640Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
4641the same attribute family is present:
4642``__attribute__((os_returns_not_retained))``,
4643``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
4644with the same respective semantics.
4645Similar to ``__attribute__((ns_consumes_self))``,
4646``__attribute__((os_consumes_this))`` specifies that the method call consumes
4647the reference to "this" (e.g., when attaching it to a different object supplied
4648as a parameter).
4649Out parameters (parameters the function is meant to write into,
4650either via pointers-to-pointers or references-to-pointers)
4651may be annotated with ``__attribute__((os_returns_retained))``
4652or ``__attribute__((os_returns_not_retained))`` which specifies that the object
4653written into the out parameter should (or respectively should not) be released
4654after use.
4655Since often out parameters may or may not be written depending on the exit
4656code of the function,
4657annotations ``__attribute__((os_returns_retained_on_zero))``
4658and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
4659an out parameter at ``+1`` is written if and only if the function returns a zero
4660(respectively non-zero) error code.
4661Observe that return-code-dependent out parameter annotations are only
4662available for retained out parameters, as non-retained object do not have to be
4663released by the callee.
4664These attributes are only used by the Clang Static Analyzer.
4665
4666The family of attributes ``X_returns_X_retained`` can be added to functions,
4667C++ methods, and Objective-C methods and properties.
4668Attributes ``X_consumed`` can be added to parameters of methods, functions,
4669and Objective-C methods.)reST";
4670
4671static const char AttrDoc_NSReturnsRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
4672(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
4673convention (e.g. functions starting with "get" are assumed to return at
4674``+0``).
4675
4676It can be overridden using a family of the following attributes. In
4677Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
4678a function communicates that the object is returned at ``+1``, and the caller
4679is responsible for freeing it.
4680Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
4681specifies that the object is returned at ``+0`` and the ownership remains with
4682the callee.
4683The annotation ``__attribute__((ns_consumes_self))`` specifies that
4684the Objective-C method call consumes the reference to ``self``, e.g. by
4685attaching it to a supplied parameter.
4686Additionally, parameters can have an annotation
4687``__attribute__((ns_consumed))``, which specifies that passing an owned object
4688as that parameter effectively transfers the ownership, and the caller is no
4689longer responsible for it.
4690These attributes affect code generation when interacting with ARC code, and
4691they are used by the Clang Static Analyzer.
4692
4693In C programs using CoreFoundation, a similar set of attributes:
4694``__attribute__((cf_returns_not_retained))``,
4695``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
4696have the same respective semantics when applied to CoreFoundation objects.
4697These attributes affect code generation when interacting with ARC code, and
4698they are used by the Clang Static Analyzer.
4699
4700Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
4701the same attribute family is present:
4702``__attribute__((os_returns_not_retained))``,
4703``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
4704with the same respective semantics.
4705Similar to ``__attribute__((ns_consumes_self))``,
4706``__attribute__((os_consumes_this))`` specifies that the method call consumes
4707the reference to "this" (e.g., when attaching it to a different object supplied
4708as a parameter).
4709Out parameters (parameters the function is meant to write into,
4710either via pointers-to-pointers or references-to-pointers)
4711may be annotated with ``__attribute__((os_returns_retained))``
4712or ``__attribute__((os_returns_not_retained))`` which specifies that the object
4713written into the out parameter should (or respectively should not) be released
4714after use.
4715Since often out parameters may or may not be written depending on the exit
4716code of the function,
4717annotations ``__attribute__((os_returns_retained_on_zero))``
4718and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
4719an out parameter at ``+1`` is written if and only if the function returns a zero
4720(respectively non-zero) error code.
4721Observe that return-code-dependent out parameter annotations are only
4722available for retained out parameters, as non-retained object do not have to be
4723released by the callee.
4724These attributes are only used by the Clang Static Analyzer.
4725
4726The family of attributes ``X_returns_X_retained`` can be added to functions,
4727C++ methods, and Objective-C methods and properties.
4728Attributes ``X_consumed`` can be added to parameters of methods, functions,
4729and Objective-C methods.)reST";
4730
4731static const char AttrDoc_Naked[] = R"reST(No documentation.)reST";
4732
4733static const char AttrDoc_NoAlias[] = R"reST(The ``noalias`` attribute indicates that the only memory accesses inside
4734function are loads and stores from objects pointed to by its pointer-typed
4735arguments, with arbitrary offsets.)reST";
4736
4737static const char AttrDoc_NoBuiltin[] = R"reST(The ``__attribute__((no_builtin))`` is similar to the ``-fno-builtin`` flag
4738except it is specific to the body of a function. The attribute may also be
4739applied to a virtual function but has no effect on the behavior of overriding
4740functions in a derived class.
4741
4742It accepts one or more strings corresponding to the specific names of the
4743builtins to disable (e.g. "memcpy", "memset").
4744If the attribute is used without parameters it will disable all buitins at
4745once.
4746
4747.. code-block:: c++
4748
4749 // The compiler is not allowed to add any builtin to foo's body.
4750 void foo(char* data, size_t count) __attribute__((no_builtin)) {
4751 // The compiler is not allowed to convert the loop into
4752 // `__builtin_memset(data, 0xFE, count);`.
4753 for (size_t i = 0; i < count; ++i)
4754 data[i] = 0xFE;
4755 }
4756
4757 // The compiler is not allowed to add the `memcpy` builtin to bar's body.
4758 void bar(char* data, size_t count) __attribute__((no_builtin("memcpy"))) {
4759 // The compiler is allowed to convert the loop into
4760 // `__builtin_memset(data, 0xFE, count);` but cannot generate any
4761 // `__builtin_memcpy`
4762 for (size_t i = 0; i < count; ++i)
4763 data[i] = 0xFE;
4764 })reST";
4765
4766static const char AttrDoc_NoCommon[] = R"reST(No documentation.)reST";
4767
4768static const char AttrDoc_NoConvergent[] = R"reST(This attribute prevents a function from being treated as convergent; when a
4769function is marked ``noconvergent``, calls to that function are not
4770automatically assumed to be convergent, unless such calls are explicitly marked
4771as ``convergent``. If a statement is marked as ``noconvergent``, any calls to
4772inline ``asm`` in that statement are no longer treated as convergent.
4773
4774In languages following SPMD/SIMT programming model, e.g., CUDA/HIP, function
4775declarations and inline asm calls are treated as convergent by default for
4776correctness. This ``noconvergent`` attribute is helpful for developers to
4777prevent them from being treated as convergent when it's safe.
4778
4779.. code-block:: c
4780
4781 __device__ float bar(float);
4782 __device__ float foo(float) __attribute__((noconvergent)) {}
4783
4784 __device__ int example(void) {
4785 float x;
4786 [[clang::noconvergent]] x = bar(x); // no effect on convergence
4787 [[clang::noconvergent]] { asm volatile ("nop"); } // the asm call is non-convergent
4788 })reST";
4789
4790static const char AttrDoc_NoDebug[] = R"reST(The ``nodebug`` attribute allows you to suppress debugging information for a
4791function or method, for a variable that is not a parameter or a non-static
4792data member, or for a typedef or using declaration.)reST";
4793
4794static const char AttrDoc_NoDeref[] = R"reST(The ``noderef`` attribute causes clang to diagnose dereferences of annotated pointer types.
4795This is ideally used with pointers that point to special memory which cannot be read
4796from or written to, but allowing for the pointer to be used in pointer arithmetic.
4797The following are examples of valid expressions where dereferences are diagnosed:
4798
4799.. code-block:: c
4800
4801 int __attribute__((noderef)) *p;
4802 int x = *p; // warning
4803
4804 int __attribute__((noderef)) **p2;
4805 x = **p2; // warning
4806
4807 int * __attribute__((noderef)) *p3;
4808 p = *p3; // warning
4809
4810 struct S {
4811 int a;
4812 };
4813 struct S __attribute__((noderef)) *s;
4814 x = s->a; // warning
4815 x = (*s).a; // warning
4816
4817Not all dereferences may diagnose a warning if the value directed by the pointer may not be
4818accessed. The following are examples of valid expressions where may not be diagnosed:
4819
4820.. code-block:: c
4821
4822 int *q;
4823 int __attribute__((noderef)) *p;
4824 q = &*p;
4825 q = *&p;
4826
4827 struct S {
4828 int a;
4829 };
4830 struct S __attribute__((noderef)) *s;
4831 p = &s->a;
4832 p = &(*s).a;
4833
4834``noderef`` is currently only supported for pointers and arrays and not usable
4835for references or Objective-C object pointers.
4836
4837.. code-block:: c++
4838
4839 int x = 2;
4840 int __attribute__((noderef)) &y = x; // warning: 'noderef' can only be used on an array or pointer type
4841
4842.. code-block:: objc
4843
4844 id __attribute__((noderef)) obj = [NSObject new]; // warning: 'noderef' can only be used on an array or pointer type)reST";
4845
4846static const char AttrDoc_NoDestroy[] = R"reST(The ``no_destroy`` attribute specifies that a variable with static or thread
4847storage duration shouldn't have its exit-time destructor run. Annotating every
4848static and thread duration variable with this attribute is equivalent to
4849invoking clang with -fno-c++-static-destructors.
4850
4851If a variable is declared with this attribute, clang doesn't access check or
4852generate the type's destructor. If you have a type that you only want to be
4853annotated with ``no_destroy``, you can therefore declare the destructor private:
4854
4855.. code-block:: c++
4856
4857 struct only_no_destroy {
4858 only_no_destroy();
4859 private:
4860 ~only_no_destroy();
4861 };
4862
4863 [[clang::no_destroy]] only_no_destroy global; // fine!
4864
4865Note that destructors are still required for subobjects of aggregates annotated
4866with this attribute. This is because previously constructed subobjects need to
4867be destroyed if an exception gets thrown before the initialization of the
4868complete object is complete. For instance:
4869
4870.. code-block:: c++
4871
4872 void f() {
4873 try {
4874 [[clang::no_destroy]]
4875 static only_no_destroy array[10]; // error, only_no_destroy has a private destructor.
4876 } catch (...) {
4877 // Handle the error
4878 }
4879 }
4880
4881Here, if the construction of ``array[9]`` fails with an exception, ``array[0..8]``
4882will be destroyed, so the element's destructor needs to be accessible.)reST";
4883
4884static const char AttrDoc_NoDuplicate[] = R"reST(The ``noduplicate`` attribute can be placed on function declarations to control
4885whether function calls to this function can be duplicated or not as a result of
4886optimizations. This is required for the implementation of functions with
4887certain special requirements, like the OpenCL "barrier" function, that might
4888need to be run concurrently by all the threads that are executing in lockstep
4889on the hardware. For example this attribute applied on the function
4890"nodupfunc" in the code below avoids that:
4891
4892.. code-block:: c
4893
4894 void nodupfunc() __attribute__((noduplicate));
4895 // Setting it as a C++11 attribute is also valid
4896 // void nodupfunc() [[clang::noduplicate]];
4897 void foo();
4898 void bar();
4899
4900 nodupfunc();
4901 if (a > n) {
4902 foo();
4903 } else {
4904 bar();
4905 }
4906
4907gets possibly modified by some optimizations into code similar to this:
4908
4909.. code-block:: c
4910
4911 if (a > n) {
4912 nodupfunc();
4913 foo();
4914 } else {
4915 nodupfunc();
4916 bar();
4917 }
4918
4919where the call to "nodupfunc" is duplicated and sunk into the two branches
4920of the condition.)reST";
4921
4922static const char AttrDoc_NoEscape[] = R"reST(``noescape`` placed on a function parameter of a pointer type is used to inform
4923the compiler that the pointer cannot escape: that is, no reference to the object
4924the pointer points to that is derived from the parameter value will survive
4925after the function returns. Users are responsible for making sure parameters
4926annotated with ``noescape`` do not actually escape. Calling ``free()`` on such
4927a parameter does not constitute an escape.
4928
4929For example:
4930
4931.. code-block:: c
4932
4933 int *gp;
4934
4935 void nonescapingFunc(__attribute__((noescape)) int *p) {
4936 *p += 100; // OK.
4937 }
4938
4939 void escapingFunc(__attribute__((noescape)) int *p) {
4940 gp = p; // Not OK.
4941 }
4942
4943Additionally, when the parameter is a `block pointer
4944<https://clang.llvm.org/docs/BlockLanguageSpec.html>`, the same restriction
4945applies to copies of the block. For example:
4946
4947.. code-block:: c
4948
4949 typedef void (^BlockTy)();
4950 BlockTy g0, g1;
4951
4952 void nonescapingFunc(__attribute__((noescape)) BlockTy block) {
4953 block(); // OK.
4954 }
4955
4956 void escapingFunc(__attribute__((noescape)) BlockTy block) {
4957 g0 = block; // Not OK.
4958 g1 = Block_copy(block); // Not OK either.
4959 })reST";
4960
4961static const char AttrDoc_NoInline[] = R"reST(This function attribute suppresses the inlining of a function at the call sites
4962of the function.
4963
4964``[[clang::noinline]]`` spelling can be used as a statement attribute; other
4965spellings of the attribute are not supported on statements. If a statement is
4966marked ``[[clang::noinline]]`` and contains calls, those calls inside the
4967statement will not be inlined by the compiler.
4968
4969``__noinline__`` can be used as a keyword in CUDA/HIP languages. This is to
4970avoid diagnostics due to usage of ``__attribute__((__noinline__))``
4971with ``__noinline__`` defined as a macro as ``__attribute__((noinline))``.
4972
4973.. code-block:: c
4974
4975 int example(void) {
4976 int r;
4977 [[clang::noinline]] foo();
4978 [[clang::noinline]] r = bar();
4979 return r;
4980 })reST";
4981
4982static const char AttrDoc_NoInstrumentFunction[] = R"reST(No documentation.)reST";
4983
4984static const char AttrDoc_NoMerge[] = R"reST(If a statement is marked ``nomerge`` and contains call expressions, those call
4985expressions inside the statement will not be merged during optimization. This
4986attribute can be used to prevent the optimizer from obscuring the source
4987location of certain calls. For example, it will prevent tail merging otherwise
4988identical code sequences that raise an exception or terminate the program. Tail
4989merging normally reduces the precision of source location information, making
4990stack traces less useful for debugging. This attribute gives the user control
4991over the tradeoff between code size and debug information precision.
4992
4993``nomerge`` attribute can also be used as function attribute to prevent all
4994calls to the specified function from merging. It has no effect on indirect
4995calls to such functions. For example:
4996
4997.. code-block:: c++
4998
4999 [[clang::nomerge]] void foo(int) {}
5000
5001 void bar(int x) {
5002 auto *ptr = foo;
5003 if (x) foo(1); else foo(2); // will not be merged
5004 if (x) ptr(1); else ptr(2); // indirect call, can be merged
5005 }
5006
5007``nomerge`` attribute can also be used for pointers to functions to
5008prevent calls through such pointer from merging. In such case the
5009effect applies only to a specific function pointer. For example:
5010
5011.. code-block:: c++
5012
5013 [[clang::nomerge]] void (*foo)(int);
5014
5015 void bar(int x) {
5016 auto *ptr = foo;
5017 if (x) foo(1); else foo(2); // will not be merged
5018 if (x) ptr(1); else ptr(2); // 'ptr' has no 'nomerge' attribute, can be merged
5019 })reST";
5020
5021static const char AttrDoc_NoMicroMips[] = R"reST(Clang supports the GNU style ``__attribute__((micromips))`` and
5022``__attribute__((nomicromips))`` attributes on MIPS targets. These attributes
5023may be attached to a function definition and instructs the backend to generate
5024or not to generate microMIPS code for that function.
5025
5026These attributes override the ``-mmicromips`` and ``-mno-micromips`` options
5027on the command line.)reST";
5028
5029static const char AttrDoc_NoMips16[] = R"reST(No documentation.)reST";
5030
5031static const char AttrDoc_NoProfileFunction[] = R"reST(Use the ``no_profile_instrument_function`` attribute on a function declaration
5032to denote that the compiler should not instrument the function with
5033profile-related instrumentation, such as via the
5034``-fprofile-generate`` / ``-fprofile-instr-generate`` /
5035``-fcs-profile-generate`` / ``-fprofile-arcs`` flags.)reST";
5036
5037static const char AttrDoc_NoRandomizeLayout[] = R"reST(The attribute ``randomize_layout``, when attached to a C structure, selects it
5038for structure layout field randomization; a compile-time hardening technique. A
5039"seed" value, is specified via the ``-frandomize-layout-seed=`` command line flag.
5040For example:
5041
5042.. code-block:: bash
5043
5044 SEED=`od -A n -t x8 -N 32 /dev/urandom | tr -d ' \n'`
5045 make ... CFLAGS="-frandomize-layout-seed=$SEED" ...
5046
5047You can also supply the seed in a file with ``-frandomize-layout-seed-file=``.
5048For example:
5049
5050.. code-block:: bash
5051
5052 od -A n -t x8 -N 32 /dev/urandom | tr -d ' \n' > /tmp/seed_file.txt
5053 make ... CFLAGS="-frandomize-layout-seed-file=/tmp/seed_file.txt" ...
5054
5055The randomization is deterministic based for a given seed, so the entire
5056program should be compiled with the same seed, but keep the seed safe
5057otherwise.
5058
5059The attribute ``no_randomize_layout``, when attached to a C structure,
5060instructs the compiler that this structure should not have its field layout
5061randomized.)reST";
5062
5063static const char AttrDoc_NoReturn[] = R"reST(No documentation.)reST";
5064
5065static const char AttrDoc_NoSanitize[] = R"reST(Use the ``no_sanitize`` attribute on a function or a global variable
5066declaration to specify that a particular instrumentation or set of
5067instrumentations should not be applied.
5068
5069The attribute takes a list of string literals with the following accepted
5070values:
5071* all values accepted by ``-fno-sanitize=``;
5072* ``coverage``, to disable SanitizerCoverage instrumentation.
5073
5074For example, ``__attribute__((no_sanitize("address", "thread")))`` specifies
5075that AddressSanitizer and ThreadSanitizer should not be applied to the function
5076or variable. Using ``__attribute__((no_sanitize("coverage")))`` specifies that
5077SanitizerCoverage should not be applied to the function.
5078
5079See :ref:`Controlling Code Generation <controlling-code-generation>` for a
5080full list of supported sanitizer flags.)reST";
5081
5082static const char AttrDoc_NoSpecializations[] = R"reST(``[[clang::no_specializations]]`` can be applied to function, class, or variable
5083templates which should not be explicitly specialized by users. This is primarily
5084used to diagnose user specializations of standard library type traits.)reST";
5085
5086static const char AttrDoc_NoSpeculativeLoadHardening[] = R"reST(This attribute can be applied to a function declaration in order to indicate
5087 that `Speculative Load Hardening <https://llvm.org/docs/SpeculativeLoadHardening.html>`_
5088 is *not* needed for the function body. This can also be applied to a method
5089 in Objective C. This attribute will take precedence over the command line flag in
5090 the case where `-mspeculative-load-hardening <https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mspeculative-load-hardening>`_ is specified.
5091
5092 Warning: This attribute may not prevent Speculative Load Hardening from being
5093 enabled for a function which inlines a function that has the
5094 'speculative_load_hardening' attribute. This is intended to provide a
5095 maximally conservative model where the code that is marked with the
5096 'speculative_load_hardening' attribute will always (even when inlined)
5097 be hardened. A user of this attribute may want to mark functions called by
5098 a function they do not want to be hardened with the 'noinline' attribute.
5099
5100 For example:
5101
5102 .. code-block:: c
5103
5104 __attribute__((speculative_load_hardening))
5105 int foo(int i) {
5106 return i;
5107 }
5108
5109 // Note: bar() may still have speculative load hardening enabled if
5110 // foo() is inlined into bar(). Mark foo() with __attribute__((noinline))
5111 // to avoid this situation.
5112 __attribute__((no_speculative_load_hardening))
5113 int bar(int i) {
5114 return foo(i);
5115 })reST";
5116
5117static const char AttrDoc_NoSplitStack[] = R"reST(The ``no_split_stack`` attribute disables the emission of the split stack
5118preamble for a particular function. It has no effect if ``-fsplit-stack``
5119is not specified.)reST";
5120
5121static const char AttrDoc_NoStackProtector[] = R"reST(Clang supports the GNU style ``__attribute__((no_stack_protector))`` and Microsoft
5122style ``__declspec(safebuffers)`` attribute which disables
5123the stack protector on the specified function. This attribute is useful for
5124selectively disabling the stack protector on some functions when building with
5125``-fstack-protector`` compiler option.
5126
5127For example, it disables the stack protector for the function ``foo`` but function
5128``bar`` will still be built with the stack protector with the ``-fstack-protector``
5129option.
5130
5131.. code-block:: c
5132
5133 int __attribute__((no_stack_protector))
5134 foo (int x); // stack protection will be disabled for foo.
5135
5136 int bar(int y); // bar can be built with the stack protector.)reST";
5137
5138static const char AttrDoc_NoThreadSafetyAnalysis[] = R"reST(No documentation.)reST";
5139
5140static const char AttrDoc_NoThrow[] = R"reST(Clang supports the GNU style ``__attribute__((nothrow))`` and Microsoft style
5141``__declspec(nothrow)`` attribute as an equivalent of ``noexcept`` on function
5142declarations. This attribute informs the compiler that the annotated function
5143does not throw an exception. This prevents exception-unwinding. This attribute
5144is particularly useful on functions in the C Standard Library that are
5145guaranteed to not throw an exception.)reST";
5146
5147static const char AttrDoc_NoTrivialAutoVarInit[] = R"reST(The ``__declspec(no_init_all)`` attribute disables the automatic initialization that the
5148`-ftrivial-auto-var-init`_ flag would have applied to locals in a marked function, or instances of
5149a marked type. Note that this attribute has no effect for locals that are automatically initialized
5150without the `-ftrivial-auto-var-init`_ flag.
5151
5152.. _`-ftrivial-auto-var-init`: ClangCommandLineReference.html#cmdoption-clang-ftrivial-auto-var-init)reST";
5153
5154static const char AttrDoc_NoUniqueAddress[] = R"reST(The ``no_unique_address`` attribute allows tail padding in a non-static data
5155member to overlap other members of the enclosing class (and in the special
5156case when the type is empty, permits it to fully overlap other members).
5157The field is laid out as if a base class were encountered at the corresponding
5158point within the class (except that it does not share a vptr with the enclosing
5159object).
5160
5161Example usage:
5162
5163.. code-block:: c++
5164
5165 template<typename T, typename Alloc> struct my_vector {
5166 T *p;
5167 [[no_unique_address]] Alloc alloc;
5168 // ...
5169 };
5170 static_assert(sizeof(my_vector<int, std::allocator<int>>) == sizeof(int*));
5171
5172``[[no_unique_address]]`` is a standard C++20 attribute. Clang supports its use
5173in C++11 onwards.
5174
5175On MSVC targets, ``[[no_unique_address]]`` is ignored; use
5176``[[msvc::no_unique_address]]`` instead. Currently there is no guarantee of ABI
5177compatibility or stability with MSVC.)reST";
5178
5179static const char AttrDoc_NoUwtable[] = R"reST(Clang supports the ``nouwtable`` attribute which skips emitting
5180the unwind table entry for the specified function. This attribute is useful for
5181selectively emitting the unwind table entry on some functions when building with
5182``-funwind-tables`` compiler option.)reST";
5183
5184static const char AttrDoc_NonAllocating[] = R"reST(Declares that a function or function type either does or does not allocate heap memory, according
5185to the optional, compile-time constant boolean argument, which defaults to true. When the argument
5186is false, the attribute is equivalent to ``allocating``.)reST";
5187
5188static const char AttrDoc_NonBlocking[] = R"reST(Declares that a function or function type either does or does not block in any way, according
5189to the optional, compile-time constant boolean argument, which defaults to true. When the argument
5190is false, the attribute is equivalent to ``blocking``.
5191
5192For the purposes of diagnostics, ``nonblocking`` is considered to include the
5193``nonallocating`` guarantee and is therefore a "stronger" constraint or attribute.)reST";
5194
5195static const char AttrDoc_NonNull[] = R"reST(The ``nonnull`` attribute indicates that some function parameters must not be
5196null, and can be used in several different ways. It's original usage
5197(`from GCC <https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes>`_)
5198is as a function (or Objective-C method) attribute that specifies which
5199parameters of the function are nonnull in a comma-separated list. For example:
5200
5201 .. code-block:: c
5202
5203 extern void * my_memcpy (void *dest, const void *src, size_t len)
5204 __attribute__((nonnull (1, 2)));
5205
5206Here, the ``nonnull`` attribute indicates that parameters 1 and 2
5207cannot have a null value. Omitting the parenthesized list of parameter indices
5208means that all parameters of pointer type cannot be null:
5209
5210 .. code-block:: c
5211
5212 extern void * my_memcpy (void *dest, const void *src, size_t len)
5213 __attribute__((nonnull));
5214
5215Clang also allows the ``nonnull`` attribute to be placed directly on a function
5216(or Objective-C method) parameter, eliminating the need to specify the
5217parameter index ahead of type. For example:
5218
5219 .. code-block:: c
5220
5221 extern void * my_memcpy (void *dest __attribute__((nonnull)),
5222 const void *src __attribute__((nonnull)), size_t len);
5223
5224Note that the ``nonnull`` attribute indicates that passing null to a non-null
5225parameter is undefined behavior, which the optimizer may take advantage of to,
5226e.g., remove null checks. The ``_Nonnull`` type qualifier indicates that a
5227pointer cannot be null in a more general manner (because it is part of the type
5228system) and does not imply undefined behavior, making it more widely applicable.)reST";
5229
5230static const char AttrDoc_NonString[] = R"reST(The ``nonstring`` attribute can be applied to the declaration of a variable or
5231a field whose type is a character array to specify that the character array is
5232not intended to behave like a null-terminated string. This will silence
5233diagnostics with code like:
5234
5235.. code-block:: c
5236
5237 char BadStr[3] = "foo"; // No space for the null terminator, diagnosed
5238 __attribute__((nonstring)) char NotAStr[3] = "foo"; // Not diagnosed)reST";
5239
5240static const char AttrDoc_NotTailCalled[] = R"reST(The ``not_tail_called`` attribute prevents tail-call optimization on statically
5241bound calls. Objective-c methods, and functions marked as ``always_inline``
5242cannot be marked as ``not_tail_called``.
5243
5244For example, it prevents tail-call optimization in the following case:
5245
5246 .. code-block:: c
5247
5248 int __attribute__((not_tail_called)) foo1(int);
5249
5250 int foo2(int a) {
5251 return foo1(a); // No tail-call optimization on direct calls.
5252 }
5253
5254However, it doesn't prevent tail-call optimization in this case:
5255
5256 .. code-block:: c
5257
5258 int __attribute__((not_tail_called)) foo1(int);
5259
5260 int foo2(int a) {
5261 int (*fn)(int) = &foo1;
5262
5263 // not_tail_called has no effect on an indirect call even if the call can
5264 // be resolved at compile time.
5265 return (*fn)(a);
5266 }
5267
5268Generally, marking an overriding virtual function as ``not_tail_called`` is
5269not useful, because this attribute is a property of the static type. Calls
5270made through a pointer or reference to the base class type will respect
5271the ``not_tail_called`` attribute of the base class's member function,
5272regardless of the runtime destination of the call:
5273
5274 .. code-block:: c++
5275
5276 struct Foo { virtual void f(); };
5277 struct Bar : Foo {
5278 [[clang::not_tail_called]] void f() override;
5279 };
5280 void callera(Bar& bar) {
5281 Foo& foo = bar;
5282 // not_tail_called has no effect on here, even though the
5283 // underlying method is f from Bar.
5284 foo.f();
5285 bar.f(); // No tail-call optimization on here.
5286 })reST";
5287
5288static const char AttrDoc_OMPAllocateDecl[] = R"reST()reST";
5289
5290static const char AttrDoc_OMPAssume[] = R"reST(Clang supports the ``[[omp::assume("assumption")]]`` attribute to
5291provide additional information to the optimizer. The string-literal, here
5292"assumption", will be attached to the function declaration such that later
5293analysis and optimization passes can assume the "assumption" to hold.
5294This is similar to :ref:`__builtin_assume <langext-__builtin_assume>` but
5295instead of an expression that can be assumed to be non-zero, the assumption is
5296expressed as a string and it holds for the entire function.
5297
5298A function can have multiple assume attributes and they propagate from prior
5299declarations to later definitions. Multiple assumptions are aggregated into a
5300single comma separated string. Thus, one can provide multiple assumptions via
5301a comma separated string, i.a.,
5302``[[omp::assume("assumption1,assumption2")]]``.
5303
5304While LLVM plugins might provide more assumption strings, the default LLVM
5305optimization passes are aware of the following assumptions:
5306
5307 .. code-block:: none
5308
5309 "omp_no_openmp"
5310 "omp_no_openmp_routines"
5311 "omp_no_parallelism"
5312 "omp_no_openmp_constructs"
5313
5314The OpenMP standard defines the meaning of OpenMP assumptions ("omp_XYZ" is
5315spelled "XYZ" in the `OpenMP 5.1 Standard`_).
5316
5317.. _`OpenMP 5.1 Standard`: https://www.openmp.org/spec-html/5.1/openmpsu37.html#x56-560002.5.2)reST";
5318
5319static const char AttrDoc_OMPCaptureKind[] = R"reST()reST";
5320
5321static const char AttrDoc_OMPCaptureNoInit[] = R"reST()reST";
5322
5323static const char AttrDoc_OMPDeclareSimdDecl[] = R"reST(The ``declare simd`` construct can be applied to a function to enable the creation
5324of one or more versions that can process multiple arguments using SIMD
5325instructions from a single invocation in a SIMD loop. The ``declare simd``
5326directive is a declarative directive. There may be multiple ``declare simd``
5327directives for a function. The use of a ``declare simd`` construct on a function
5328enables the creation of SIMD versions of the associated function that can be
5329used to process multiple arguments from a single invocation from a SIMD loop
5330concurrently.
5331The syntax of the ``declare simd`` construct is as follows:
5332
5333 .. code-block:: none
5334
5335 #pragma omp declare simd [clause[[,] clause] ...] new-line
5336 [#pragma omp declare simd [clause[[,] clause] ...] new-line]
5337 [...]
5338 function definition or declaration
5339
5340where clause is one of the following:
5341
5342 .. code-block:: none
5343
5344 simdlen(length)
5345 linear(argument-list[:constant-linear-step])
5346 aligned(argument-list[:alignment])
5347 uniform(argument-list)
5348 inbranch
5349 notinbranch)reST";
5350
5351static const char AttrDoc_OMPDeclareTargetDecl[] = R"reST(The ``declare target`` directive specifies that variables and functions are mapped
5352to a device for OpenMP offload mechanism.
5353
5354The syntax of the declare target directive is as follows:
5355
5356 .. code-block:: c
5357
5358 #pragma omp declare target new-line
5359 declarations-definition-seq
5360 #pragma omp end declare target new-line
5361
5362or
5363
5364 .. code-block:: c
5365
5366 #pragma omp declare target (extended-list) new-line
5367
5368or
5369
5370 .. code-block:: c
5371
5372 #pragma omp declare target clause[ [,] clause ... ] new-line
5373
5374where clause is one of the following:
5375
5376
5377 .. code-block:: c
5378
5379 to(extended-list)
5380 link(list)
5381 device_type(host | nohost | any))reST";
5382
5383static const char AttrDoc_OMPDeclareVariant[] = R"reST(The ``declare variant`` directive declares a specialized variant of a base
5384function and specifies the context in which that specialized variant is used.
5385The declare variant directive is a declarative directive.
5386The syntax of the ``declare variant`` construct is as follows:
5387
5388 .. code-block:: none
5389
5390 #pragma omp declare variant(variant-func-id) clause new-line
5391 [#pragma omp declare variant(variant-func-id) clause new-line]
5392 [...]
5393 function definition or declaration
5394
5395where clause is one of the following:
5396
5397 .. code-block:: none
5398
5399 match(context-selector-specification)
5400
5401and where ``variant-func-id`` is the name of a function variant that is either a
5402base language identifier or, for C++, a template-id.
5403
5404Clang provides the following context selector extensions, used via
5405``implementation={extension(EXTENSION)}``:
5406
5407 .. code-block:: none
5408
5409 match_all
5410 match_any
5411 match_none
5412 disable_implicit_base
5413 allow_templates
5414 bind_to_declaration
5415
5416The match extensions change when the *entire* context selector is considered a
5417match for an OpenMP context. The default is ``all``, with ``none`` no trait in the
5418selector is allowed to be in the OpenMP context, with ``any`` a single trait in
5419both the selector and OpenMP context is sufficient. Only a single match
5420extension trait is allowed per context selector.
5421The disable extensions remove default effects of the ``begin declare variant``
5422applied to a definition. If ``disable_implicit_base`` is given, we will not
5423introduce an implicit base function for a variant if no base function was
5424found. The variant is still generated but will never be called, due to the
5425absence of a base function and consequently calls to a base function.
5426The allow extensions change when the ``begin declare variant`` effect is
5427applied to a definition. If ``allow_templates`` is given, template function
5428definitions are considered as specializations of existing or assumed template
5429declarations with the same name. The template parameters for the base functions
5430are used to instantiate the specialization. If ``bind_to_declaration`` is given,
5431apply the same variant rules to function declarations. This allows the user to
5432override declarations with only a function declaration.)reST";
5433
5434static const char AttrDoc_OMPReferencedVar[] = R"reST()reST";
5435
5436static const char AttrDoc_OMPThreadPrivateDecl[] = R"reST()reST";
5437
5438static const char AttrDoc_OSConsumed[] = R"reST(The behavior of a function with respect to reference counting for Foundation
5439(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
5440convention (e.g. functions starting with "get" are assumed to return at
5441``+0``).
5442
5443It can be overridden using a family of the following attributes. In
5444Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
5445a function communicates that the object is returned at ``+1``, and the caller
5446is responsible for freeing it.
5447Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
5448specifies that the object is returned at ``+0`` and the ownership remains with
5449the callee.
5450The annotation ``__attribute__((ns_consumes_self))`` specifies that
5451the Objective-C method call consumes the reference to ``self``, e.g. by
5452attaching it to a supplied parameter.
5453Additionally, parameters can have an annotation
5454``__attribute__((ns_consumed))``, which specifies that passing an owned object
5455as that parameter effectively transfers the ownership, and the caller is no
5456longer responsible for it.
5457These attributes affect code generation when interacting with ARC code, and
5458they are used by the Clang Static Analyzer.
5459
5460In C programs using CoreFoundation, a similar set of attributes:
5461``__attribute__((cf_returns_not_retained))``,
5462``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
5463have the same respective semantics when applied to CoreFoundation objects.
5464These attributes affect code generation when interacting with ARC code, and
5465they are used by the Clang Static Analyzer.
5466
5467Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
5468the same attribute family is present:
5469``__attribute__((os_returns_not_retained))``,
5470``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
5471with the same respective semantics.
5472Similar to ``__attribute__((ns_consumes_self))``,
5473``__attribute__((os_consumes_this))`` specifies that the method call consumes
5474the reference to "this" (e.g., when attaching it to a different object supplied
5475as a parameter).
5476Out parameters (parameters the function is meant to write into,
5477either via pointers-to-pointers or references-to-pointers)
5478may be annotated with ``__attribute__((os_returns_retained))``
5479or ``__attribute__((os_returns_not_retained))`` which specifies that the object
5480written into the out parameter should (or respectively should not) be released
5481after use.
5482Since often out parameters may or may not be written depending on the exit
5483code of the function,
5484annotations ``__attribute__((os_returns_retained_on_zero))``
5485and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
5486an out parameter at ``+1`` is written if and only if the function returns a zero
5487(respectively non-zero) error code.
5488Observe that return-code-dependent out parameter annotations are only
5489available for retained out parameters, as non-retained object do not have to be
5490released by the callee.
5491These attributes are only used by the Clang Static Analyzer.
5492
5493The family of attributes ``X_returns_X_retained`` can be added to functions,
5494C++ methods, and Objective-C methods and properties.
5495Attributes ``X_consumed`` can be added to parameters of methods, functions,
5496and Objective-C methods.)reST";
5497
5498static const char AttrDoc_OSConsumesThis[] = R"reST(The behavior of a function with respect to reference counting for Foundation
5499(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
5500convention (e.g. functions starting with "get" are assumed to return at
5501``+0``).
5502
5503It can be overridden using a family of the following attributes. In
5504Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
5505a function communicates that the object is returned at ``+1``, and the caller
5506is responsible for freeing it.
5507Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
5508specifies that the object is returned at ``+0`` and the ownership remains with
5509the callee.
5510The annotation ``__attribute__((ns_consumes_self))`` specifies that
5511the Objective-C method call consumes the reference to ``self``, e.g. by
5512attaching it to a supplied parameter.
5513Additionally, parameters can have an annotation
5514``__attribute__((ns_consumed))``, which specifies that passing an owned object
5515as that parameter effectively transfers the ownership, and the caller is no
5516longer responsible for it.
5517These attributes affect code generation when interacting with ARC code, and
5518they are used by the Clang Static Analyzer.
5519
5520In C programs using CoreFoundation, a similar set of attributes:
5521``__attribute__((cf_returns_not_retained))``,
5522``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
5523have the same respective semantics when applied to CoreFoundation objects.
5524These attributes affect code generation when interacting with ARC code, and
5525they are used by the Clang Static Analyzer.
5526
5527Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
5528the same attribute family is present:
5529``__attribute__((os_returns_not_retained))``,
5530``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
5531with the same respective semantics.
5532Similar to ``__attribute__((ns_consumes_self))``,
5533``__attribute__((os_consumes_this))`` specifies that the method call consumes
5534the reference to "this" (e.g., when attaching it to a different object supplied
5535as a parameter).
5536Out parameters (parameters the function is meant to write into,
5537either via pointers-to-pointers or references-to-pointers)
5538may be annotated with ``__attribute__((os_returns_retained))``
5539or ``__attribute__((os_returns_not_retained))`` which specifies that the object
5540written into the out parameter should (or respectively should not) be released
5541after use.
5542Since often out parameters may or may not be written depending on the exit
5543code of the function,
5544annotations ``__attribute__((os_returns_retained_on_zero))``
5545and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
5546an out parameter at ``+1`` is written if and only if the function returns a zero
5547(respectively non-zero) error code.
5548Observe that return-code-dependent out parameter annotations are only
5549available for retained out parameters, as non-retained object do not have to be
5550released by the callee.
5551These attributes are only used by the Clang Static Analyzer.
5552
5553The family of attributes ``X_returns_X_retained`` can be added to functions,
5554C++ methods, and Objective-C methods and properties.
5555Attributes ``X_consumed`` can be added to parameters of methods, functions,
5556and Objective-C methods.)reST";
5557
5558static const char AttrDoc_OSReturnsNotRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
5559(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
5560convention (e.g. functions starting with "get" are assumed to return at
5561``+0``).
5562
5563It can be overridden using a family of the following attributes. In
5564Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
5565a function communicates that the object is returned at ``+1``, and the caller
5566is responsible for freeing it.
5567Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
5568specifies that the object is returned at ``+0`` and the ownership remains with
5569the callee.
5570The annotation ``__attribute__((ns_consumes_self))`` specifies that
5571the Objective-C method call consumes the reference to ``self``, e.g. by
5572attaching it to a supplied parameter.
5573Additionally, parameters can have an annotation
5574``__attribute__((ns_consumed))``, which specifies that passing an owned object
5575as that parameter effectively transfers the ownership, and the caller is no
5576longer responsible for it.
5577These attributes affect code generation when interacting with ARC code, and
5578they are used by the Clang Static Analyzer.
5579
5580In C programs using CoreFoundation, a similar set of attributes:
5581``__attribute__((cf_returns_not_retained))``,
5582``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
5583have the same respective semantics when applied to CoreFoundation objects.
5584These attributes affect code generation when interacting with ARC code, and
5585they are used by the Clang Static Analyzer.
5586
5587Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
5588the same attribute family is present:
5589``__attribute__((os_returns_not_retained))``,
5590``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
5591with the same respective semantics.
5592Similar to ``__attribute__((ns_consumes_self))``,
5593``__attribute__((os_consumes_this))`` specifies that the method call consumes
5594the reference to "this" (e.g., when attaching it to a different object supplied
5595as a parameter).
5596Out parameters (parameters the function is meant to write into,
5597either via pointers-to-pointers or references-to-pointers)
5598may be annotated with ``__attribute__((os_returns_retained))``
5599or ``__attribute__((os_returns_not_retained))`` which specifies that the object
5600written into the out parameter should (or respectively should not) be released
5601after use.
5602Since often out parameters may or may not be written depending on the exit
5603code of the function,
5604annotations ``__attribute__((os_returns_retained_on_zero))``
5605and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
5606an out parameter at ``+1`` is written if and only if the function returns a zero
5607(respectively non-zero) error code.
5608Observe that return-code-dependent out parameter annotations are only
5609available for retained out parameters, as non-retained object do not have to be
5610released by the callee.
5611These attributes are only used by the Clang Static Analyzer.
5612
5613The family of attributes ``X_returns_X_retained`` can be added to functions,
5614C++ methods, and Objective-C methods and properties.
5615Attributes ``X_consumed`` can be added to parameters of methods, functions,
5616and Objective-C methods.)reST";
5617
5618static const char AttrDoc_OSReturnsRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
5619(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
5620convention (e.g. functions starting with "get" are assumed to return at
5621``+0``).
5622
5623It can be overridden using a family of the following attributes. In
5624Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
5625a function communicates that the object is returned at ``+1``, and the caller
5626is responsible for freeing it.
5627Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
5628specifies that the object is returned at ``+0`` and the ownership remains with
5629the callee.
5630The annotation ``__attribute__((ns_consumes_self))`` specifies that
5631the Objective-C method call consumes the reference to ``self``, e.g. by
5632attaching it to a supplied parameter.
5633Additionally, parameters can have an annotation
5634``__attribute__((ns_consumed))``, which specifies that passing an owned object
5635as that parameter effectively transfers the ownership, and the caller is no
5636longer responsible for it.
5637These attributes affect code generation when interacting with ARC code, and
5638they are used by the Clang Static Analyzer.
5639
5640In C programs using CoreFoundation, a similar set of attributes:
5641``__attribute__((cf_returns_not_retained))``,
5642``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
5643have the same respective semantics when applied to CoreFoundation objects.
5644These attributes affect code generation when interacting with ARC code, and
5645they are used by the Clang Static Analyzer.
5646
5647Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
5648the same attribute family is present:
5649``__attribute__((os_returns_not_retained))``,
5650``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
5651with the same respective semantics.
5652Similar to ``__attribute__((ns_consumes_self))``,
5653``__attribute__((os_consumes_this))`` specifies that the method call consumes
5654the reference to "this" (e.g., when attaching it to a different object supplied
5655as a parameter).
5656Out parameters (parameters the function is meant to write into,
5657either via pointers-to-pointers or references-to-pointers)
5658may be annotated with ``__attribute__((os_returns_retained))``
5659or ``__attribute__((os_returns_not_retained))`` which specifies that the object
5660written into the out parameter should (or respectively should not) be released
5661after use.
5662Since often out parameters may or may not be written depending on the exit
5663code of the function,
5664annotations ``__attribute__((os_returns_retained_on_zero))``
5665and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
5666an out parameter at ``+1`` is written if and only if the function returns a zero
5667(respectively non-zero) error code.
5668Observe that return-code-dependent out parameter annotations are only
5669available for retained out parameters, as non-retained object do not have to be
5670released by the callee.
5671These attributes are only used by the Clang Static Analyzer.
5672
5673The family of attributes ``X_returns_X_retained`` can be added to functions,
5674C++ methods, and Objective-C methods and properties.
5675Attributes ``X_consumed`` can be added to parameters of methods, functions,
5676and Objective-C methods.)reST";
5677
5678static const char AttrDoc_OSReturnsRetainedOnNonZero[] = R"reST(The behavior of a function with respect to reference counting for Foundation
5679(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
5680convention (e.g. functions starting with "get" are assumed to return at
5681``+0``).
5682
5683It can be overridden using a family of the following attributes. In
5684Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
5685a function communicates that the object is returned at ``+1``, and the caller
5686is responsible for freeing it.
5687Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
5688specifies that the object is returned at ``+0`` and the ownership remains with
5689the callee.
5690The annotation ``__attribute__((ns_consumes_self))`` specifies that
5691the Objective-C method call consumes the reference to ``self``, e.g. by
5692attaching it to a supplied parameter.
5693Additionally, parameters can have an annotation
5694``__attribute__((ns_consumed))``, which specifies that passing an owned object
5695as that parameter effectively transfers the ownership, and the caller is no
5696longer responsible for it.
5697These attributes affect code generation when interacting with ARC code, and
5698they are used by the Clang Static Analyzer.
5699
5700In C programs using CoreFoundation, a similar set of attributes:
5701``__attribute__((cf_returns_not_retained))``,
5702``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
5703have the same respective semantics when applied to CoreFoundation objects.
5704These attributes affect code generation when interacting with ARC code, and
5705they are used by the Clang Static Analyzer.
5706
5707Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
5708the same attribute family is present:
5709``__attribute__((os_returns_not_retained))``,
5710``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
5711with the same respective semantics.
5712Similar to ``__attribute__((ns_consumes_self))``,
5713``__attribute__((os_consumes_this))`` specifies that the method call consumes
5714the reference to "this" (e.g., when attaching it to a different object supplied
5715as a parameter).
5716Out parameters (parameters the function is meant to write into,
5717either via pointers-to-pointers or references-to-pointers)
5718may be annotated with ``__attribute__((os_returns_retained))``
5719or ``__attribute__((os_returns_not_retained))`` which specifies that the object
5720written into the out parameter should (or respectively should not) be released
5721after use.
5722Since often out parameters may or may not be written depending on the exit
5723code of the function,
5724annotations ``__attribute__((os_returns_retained_on_zero))``
5725and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
5726an out parameter at ``+1`` is written if and only if the function returns a zero
5727(respectively non-zero) error code.
5728Observe that return-code-dependent out parameter annotations are only
5729available for retained out parameters, as non-retained object do not have to be
5730released by the callee.
5731These attributes are only used by the Clang Static Analyzer.
5732
5733The family of attributes ``X_returns_X_retained`` can be added to functions,
5734C++ methods, and Objective-C methods and properties.
5735Attributes ``X_consumed`` can be added to parameters of methods, functions,
5736and Objective-C methods.)reST";
5737
5738static const char AttrDoc_OSReturnsRetainedOnZero[] = R"reST(The behavior of a function with respect to reference counting for Foundation
5739(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
5740convention (e.g. functions starting with "get" are assumed to return at
5741``+0``).
5742
5743It can be overridden using a family of the following attributes. In
5744Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
5745a function communicates that the object is returned at ``+1``, and the caller
5746is responsible for freeing it.
5747Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
5748specifies that the object is returned at ``+0`` and the ownership remains with
5749the callee.
5750The annotation ``__attribute__((ns_consumes_self))`` specifies that
5751the Objective-C method call consumes the reference to ``self``, e.g. by
5752attaching it to a supplied parameter.
5753Additionally, parameters can have an annotation
5754``__attribute__((ns_consumed))``, which specifies that passing an owned object
5755as that parameter effectively transfers the ownership, and the caller is no
5756longer responsible for it.
5757These attributes affect code generation when interacting with ARC code, and
5758they are used by the Clang Static Analyzer.
5759
5760In C programs using CoreFoundation, a similar set of attributes:
5761``__attribute__((cf_returns_not_retained))``,
5762``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
5763have the same respective semantics when applied to CoreFoundation objects.
5764These attributes affect code generation when interacting with ARC code, and
5765they are used by the Clang Static Analyzer.
5766
5767Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
5768the same attribute family is present:
5769``__attribute__((os_returns_not_retained))``,
5770``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
5771with the same respective semantics.
5772Similar to ``__attribute__((ns_consumes_self))``,
5773``__attribute__((os_consumes_this))`` specifies that the method call consumes
5774the reference to "this" (e.g., when attaching it to a different object supplied
5775as a parameter).
5776Out parameters (parameters the function is meant to write into,
5777either via pointers-to-pointers or references-to-pointers)
5778may be annotated with ``__attribute__((os_returns_retained))``
5779or ``__attribute__((os_returns_not_retained))`` which specifies that the object
5780written into the out parameter should (or respectively should not) be released
5781after use.
5782Since often out parameters may or may not be written depending on the exit
5783code of the function,
5784annotations ``__attribute__((os_returns_retained_on_zero))``
5785and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
5786an out parameter at ``+1`` is written if and only if the function returns a zero
5787(respectively non-zero) error code.
5788Observe that return-code-dependent out parameter annotations are only
5789available for retained out parameters, as non-retained object do not have to be
5790released by the callee.
5791These attributes are only used by the Clang Static Analyzer.
5792
5793The family of attributes ``X_returns_X_retained`` can be added to functions,
5794C++ methods, and Objective-C methods and properties.
5795Attributes ``X_consumed`` can be added to parameters of methods, functions,
5796and Objective-C methods.)reST";
5797
5798static const char AttrDoc_ObjCBoxable[] = R"reST(Structs and unions marked with the ``objc_boxable`` attribute can be used
5799with the Objective-C boxed expression syntax, ``@(...)``.
5800
5801**Usage**: ``__attribute__((objc_boxable))``. This attribute
5802can only be placed on a declaration of a trivially-copyable struct or union:
5803
5804.. code-block:: objc
5805
5806 struct __attribute__((objc_boxable)) some_struct {
5807 int i;
5808 };
5809 union __attribute__((objc_boxable)) some_union {
5810 int i;
5811 float f;
5812 };
5813 typedef struct __attribute__((objc_boxable)) _some_struct some_struct;
5814
5815 // ...
5816
5817 some_struct ss;
5818 NSValue *boxed = @(ss);)reST";
5819
5820static const char AttrDoc_ObjCBridge[] = R"reST(No documentation.)reST";
5821
5822static const char AttrDoc_ObjCBridgeMutable[] = R"reST(No documentation.)reST";
5823
5824static const char AttrDoc_ObjCBridgeRelated[] = R"reST(No documentation.)reST";
5825
5826static const char AttrDoc_ObjCClassStub[] = R"reST(This attribute specifies that the Objective-C class to which it applies is
5827instantiated at runtime.
5828
5829Unlike ``__attribute__((objc_runtime_visible))``, a class having this attribute
5830still has a "class stub" that is visible to the linker. This allows categories
5831to be defined. Static message sends with the class as a receiver use a special
5832access pattern to ensure the class is lazily instantiated from the class stub.
5833
5834Classes annotated with this attribute cannot be subclassed and cannot have
5835implementations defined for them. This attribute is intended for use in
5836Swift-generated headers for classes defined in Swift.
5837
5838Adding or removing this attribute to a class is an ABI-breaking change.)reST";
5839
5840static const char AttrDoc_ObjCDesignatedInitializer[] = R"reST(No documentation.)reST";
5841
5842static const char AttrDoc_ObjCDirect[] = R"reST(The ``objc_direct`` attribute can be used to mark an Objective-C method as
5843being *direct*. A direct method is treated statically like an ordinary method,
5844but dynamically it behaves more like a C function. This lowers some of the costs
5845associated with the method but also sacrifices some of the ordinary capabilities
5846of Objective-C methods.
5847
5848A message send of a direct method calls the implementation directly, as if it
5849were a C function, rather than using ordinary Objective-C method dispatch. This
5850is substantially faster and potentially allows the implementation to be inlined,
5851but it also means the method cannot be overridden in subclasses or replaced
5852dynamically, as ordinary Objective-C methods can.
5853
5854Furthermore, a direct method is not listed in the class's method lists. This
5855substantially reduces the code-size overhead of the method but also means it
5856cannot be called dynamically using ordinary Objective-C method dispatch at all;
5857in particular, this means that it cannot override a superclass method or satisfy
5858a protocol requirement.
5859
5860Because a direct method cannot be overridden, it is an error to perform
5861a ``super`` message send of one.
5862
5863Although a message send of a direct method causes the method to be called
5864directly as if it were a C function, it still obeys Objective-C semantics in other
5865ways:
5866
5867- If the receiver is ``nil``, the message send does nothing and returns the zero value
5868 for the return type.
5869
5870- A message send of a direct class method will cause the class to be initialized,
5871 including calling the ``+initialize`` method if present.
5872
5873- The implicit ``_cmd`` parameter containing the method's selector is still defined.
5874 In order to minimize code-size costs, the implementation will not emit a reference
5875 to the selector if the parameter is unused within the method.
5876
5877Symbols for direct method implementations are implicitly given hidden
5878visibility, meaning that they can only be called within the same linkage unit.
5879
5880It is an error to do any of the following:
5881
5882- declare a direct method in a protocol,
5883- declare an override of a direct method with a method in a subclass,
5884- declare an override of a non-direct method with a direct method in a subclass,
5885- declare a method with different directness in different class interfaces, or
5886- implement a non-direct method (as declared in any class interface) with a direct method.
5887
5888If any of these rules would be violated if every method defined in an
5889``@implementation`` within a single linkage unit were declared in an
5890appropriate class interface, the program is ill-formed with no diagnostic
5891required. If a violation of this rule is not diagnosed, behavior remains
5892well-defined; this paragraph is simply reserving the right to diagnose such
5893conflicts in the future, not to treat them as undefined behavior.
5894
5895Additionally, Clang will warn about any ``@selector`` expression that
5896names a selector that is only known to be used for direct methods.
5897
5898For the purpose of these rules, a "class interface" includes a class's primary
5899``@interface`` block, its class extensions, its categories, its declared protocols,
5900and all the class interfaces of its superclasses.
5901
5902An Objective-C property can be declared with the ``direct`` property
5903attribute. If a direct property declaration causes an implicit declaration of
5904a getter or setter method (that is, if the given method is not explicitly
5905declared elsewhere), the method is declared to be direct.
5906
5907Some programmers may wish to make many methods direct at once. In order
5908to simplify this, the ``objc_direct_members`` attribute is provided; see its
5909documentation for more information.)reST";
5910
5911static const char AttrDoc_ObjCDirectMembers[] = R"reST(The ``objc_direct_members`` attribute can be placed on an Objective-C
5912``@interface`` or ``@implementation`` to mark that methods declared
5913therein should be considered direct by default. See the documentation
5914for ``objc_direct`` for more information about direct methods.
5915
5916When ``objc_direct_members`` is placed on an ``@interface`` block, every
5917method in the block is considered to be declared as direct. This includes any
5918implicit method declarations introduced by property declarations. If the method
5919redeclares a non-direct method, the declaration is ill-formed, exactly as if the
5920method was annotated with the ``objc_direct`` attribute.
5921
5922When ``objc_direct_members`` is placed on an ``@implementation`` block,
5923methods defined in the block are considered to be declared as direct unless
5924they have been previously declared as non-direct in any interface of the class.
5925This includes the implicit method definitions introduced by synthesized
5926properties, including auto-synthesized properties.)reST";
5927
5928static const char AttrDoc_ObjCException[] = R"reST(No documentation.)reST";
5929
5930static const char AttrDoc_ObjCExplicitProtocolImpl[] = R"reST(No documentation.)reST";
5931
5932static const char AttrDoc_ObjCExternallyRetained[] = R"reST(The ``objc_externally_retained`` attribute can be applied to strong local
5933variables, functions, methods, or blocks to opt into
5934`externally-retained semantics
5935<https://clang.llvm.org/docs/AutomaticReferenceCounting.html#externally-retained-variables>`_.
5936
5937When applied to the definition of a function, method, or block, every parameter
5938of the function with implicit strong retainable object pointer type is
5939considered externally-retained, and becomes ``const``. By explicitly annotating
5940a parameter with ``__strong``, you can opt back into the default
5941non-externally-retained behavior for that parameter. For instance,
5942``first_param`` is externally-retained below, but not ``second_param``:
5943
5944.. code-block:: objc
5945
5946 __attribute__((objc_externally_retained))
5947 void f(NSArray *first_param, __strong NSArray *second_param) {
5948 // ...
5949 }
5950
5951Likewise, when applied to a strong local variable, that variable becomes
5952``const`` and is considered externally-retained.
5953
5954When compiled without ``-fobjc-arc``, this attribute is ignored.)reST";
5955
5956static const char AttrDoc_ObjCGC[] = R"reST(No documentation.)reST";
5957
5958static const char AttrDoc_ObjCIndependentClass[] = R"reST(No documentation.)reST";
5959
5960static const char AttrDoc_ObjCInertUnsafeUnretained[] = R"reST()reST";
5961
5962static const char AttrDoc_ObjCKindOf[] = R"reST(No documentation.)reST";
5963
5964static const char AttrDoc_ObjCMethodFamily[] = R"reST(Many methods in Objective-C have conventional meanings determined by their
5965selectors. It is sometimes useful to be able to mark a method as having a
5966particular conventional meaning despite not having the right selector, or as
5967not having the conventional meaning that its selector would suggest. For these
5968use cases, we provide an attribute to specifically describe the "method family"
5969that a method belongs to.
5970
5971**Usage**: ``__attribute__((objc_method_family(X)))``, where ``X`` is one of
5972``none``, ``alloc``, ``copy``, ``init``, ``mutableCopy``, or ``new``. This
5973attribute can only be placed at the end of a method declaration:
5974
5975.. code-block:: objc
5976
5977 - (NSString *)initMyStringValue __attribute__((objc_method_family(none)));
5978
5979Users who do not wish to change the conventional meaning of a method, and who
5980merely want to document its non-standard retain and release semantics, should
5981use the retaining behavior attributes (``ns_returns_retained``,
5982``ns_returns_not_retained``, etc).
5983
5984Query for this feature with ``__has_attribute(objc_method_family)``.)reST";
5985
5986static const char AttrDoc_ObjCNSObject[] = R"reST(No documentation.)reST";
5987
5988static const char AttrDoc_ObjCNonLazyClass[] = R"reST(This attribute can be added to an Objective-C ``@interface`` or
5989``@implementation`` declaration to add the class to the list of non-lazily
5990initialized classes. A non-lazy class will be initialized eagerly when the
5991Objective-C runtime is loaded. This is required for certain system classes which
5992have instances allocated in non-standard ways, such as the classes for blocks
5993and constant strings. Adding this attribute is essentially equivalent to
5994providing a trivial ``+load`` method but avoids the (fairly small) load-time
5995overheads associated with defining and calling such a method.)reST";
5996
5997static const char AttrDoc_ObjCNonRuntimeProtocol[] = R"reST(The ``objc_non_runtime_protocol`` attribute can be used to mark that an
5998Objective-C protocol is only used during static type-checking and doesn't need
5999to be represented dynamically. This avoids several small code-size and run-time
6000overheads associated with handling the protocol's metadata. A non-runtime
6001protocol cannot be used as the operand of a ``@protocol`` expression, and
6002dynamic attempts to find it with ``objc_getProtocol`` will fail.
6003
6004If a non-runtime protocol inherits from any ordinary protocols, classes and
6005derived protocols that declare conformance to the non-runtime protocol will
6006dynamically list their conformance to those bare protocols.)reST";
6007
6008static const char AttrDoc_ObjCOwnership[] = R"reST(No documentation.)reST";
6009
6010static const char AttrDoc_ObjCPreciseLifetime[] = R"reST(No documentation.)reST";
6011
6012static const char AttrDoc_ObjCRequiresPropertyDefs[] = R"reST(No documentation.)reST";
6013
6014static const char AttrDoc_ObjCRequiresSuper[] = R"reST(Some Objective-C classes allow a subclass to override a particular method in a
6015parent class but expect that the overriding method also calls the overridden
6016method in the parent class. For these cases, we provide an attribute to
6017designate that a method requires a "call to ``super``" in the overriding
6018method in the subclass.
6019
6020**Usage**: ``__attribute__((objc_requires_super))``. This attribute can only
6021be placed at the end of a method declaration:
6022
6023.. code-block:: objc
6024
6025 - (void)foo __attribute__((objc_requires_super));
6026
6027This attribute can only be applied the method declarations within a class, and
6028not a protocol. Currently this attribute does not enforce any placement of
6029where the call occurs in the overriding method (such as in the case of
6030``-dealloc`` where the call must appear at the end). It checks only that it
6031exists.
6032
6033Note that on both OS X and iOS that the Foundation framework provides a
6034convenience macro ``NS_REQUIRES_SUPER`` that provides syntactic sugar for this
6035attribute:
6036
6037.. code-block:: objc
6038
6039 - (void)foo NS_REQUIRES_SUPER;
6040
6041This macro is conditionally defined depending on the compiler's support for
6042this attribute. If the compiler does not support the attribute the macro
6043expands to nothing.
6044
6045Operationally, when a method has this annotation the compiler will warn if the
6046implementation of an override in a subclass does not call super. For example:
6047
6048.. code-block:: objc
6049
6050 warning: method possibly missing a [super AnnotMeth] call
6051 - (void) AnnotMeth{};
6052 ^)reST";
6053
6054static const char AttrDoc_ObjCReturnsInnerPointer[] = R"reST(No documentation.)reST";
6055
6056static const char AttrDoc_ObjCRootClass[] = R"reST(No documentation.)reST";
6057
6058static const char AttrDoc_ObjCRuntimeName[] = R"reST(By default, the Objective-C interface or protocol identifier is used
6059in the metadata name for that object. The ``objc_runtime_name``
6060attribute allows annotated interfaces or protocols to use the
6061specified string argument in the object's metadata name instead of the
6062default name.
6063
6064**Usage**: ``__attribute__((objc_runtime_name("MyLocalName")))``. This attribute
6065can only be placed before an @protocol or @interface declaration:
6066
6067.. code-block:: objc
6068
6069 __attribute__((objc_runtime_name("MyLocalName")))
6070 @interface Message
6071 @end)reST";
6072
6073static const char AttrDoc_ObjCRuntimeVisible[] = R"reST(This attribute specifies that the Objective-C class to which it applies is
6074visible to the Objective-C runtime but not to the linker. Classes annotated
6075with this attribute cannot be subclassed and cannot have categories defined for
6076them.)reST";
6077
6078static const char AttrDoc_ObjCSubclassingRestricted[] = R"reST(This attribute can be added to an Objective-C ``@interface`` declaration to
6079ensure that this class cannot be subclassed.)reST";
6080
6081static const char AttrDoc_OpenACCRoutineAnnot[] = R"reST()reST";
6082
6083static const char AttrDoc_OpenACCRoutineDecl[] = R"reST()reST";
6084
6085static const char AttrDoc_OpenCLAccess[] = R"reST(The access qualifiers must be used with image object arguments or pipe arguments
6086to declare if they are being read or written by a kernel or function.
6087
6088The read_only/__read_only, write_only/__write_only and read_write/__read_write
6089names are reserved for use as access qualifiers and shall not be used otherwise.
6090
6091.. code-block:: c
6092
6093 kernel void
6094 foo (read_only image2d_t imageA,
6095 write_only image2d_t imageB) {
6096 ...
6097 }
6098
6099In the above example imageA is a read-only 2D image object, and imageB is a
6100write-only 2D image object.
6101
6102The read_write (or __read_write) qualifier can not be used with pipe.
6103
6104More details can be found in the OpenCL C language Spec v2.0, Section 6.6.)reST";
6105
6106static const char AttrDoc_OpenCLConstantAddressSpace[] = R"reST(The constant address space attribute signals that an object is located in
6107a constant (non-modifiable) memory region. It is available to all work items.
6108Any type can be annotated with the constant address space attribute. Objects
6109with the constant address space qualifier can be declared in any scope and must
6110have an initializer.)reST";
6111
6112static const char AttrDoc_OpenCLGenericAddressSpace[] = R"reST(The generic address space attribute is only available with OpenCL v2.0 and later.
6113It can be used with pointer types. Variables in global and local scope and
6114function parameters in non-kernel functions can have the generic address space
6115type attribute. It is intended to be a placeholder for any other address space
6116except for '__constant' in OpenCL code which can be used with multiple address
6117spaces.)reST";
6118
6119static const char AttrDoc_OpenCLGlobalAddressSpace[] = R"reST(The global address space attribute specifies that an object is allocated in
6120global memory, which is accessible by all work items. The content stored in this
6121memory area persists between kernel executions. Pointer types to the global
6122address space are allowed as function parameters or local variables. Starting
6123with OpenCL v2.0, the global address space can be used with global (program
6124scope) variables and static local variable as well.)reST";
6125
6126static const char AttrDoc_OpenCLGlobalDeviceAddressSpace[] = R"reST(The ``global_device`` and ``global_host`` address space attributes specify that
6127an object is allocated in global memory on the device/host. It helps to
6128distinguish USM (Unified Shared Memory) pointers that access global device
6129memory from those that access global host memory. These new address spaces are
6130a subset of the ``__global/opencl_global`` address space, the full address space
6131set model for OpenCL 2.0 with the extension looks as follows:
6132
6133 | generic->global->host
6134 | ->device
6135 | ->private
6136 | ->local
6137 | constant
6138
6139As ``global_device`` and ``global_host`` are a subset of
6140``__global/opencl_global`` address spaces it is allowed to convert
6141``global_device`` and ``global_host`` address spaces to
6142``__global/opencl_global`` address spaces (following ISO/IEC TR 18037 5.1.3
6143"Address space nesting and rules for pointers").)reST";
6144
6145static const char AttrDoc_OpenCLGlobalHostAddressSpace[] = R"reST(The ``global_device`` and ``global_host`` address space attributes specify that
6146an object is allocated in global memory on the device/host. It helps to
6147distinguish USM (Unified Shared Memory) pointers that access global device
6148memory from those that access global host memory. These new address spaces are
6149a subset of the ``__global/opencl_global`` address space, the full address space
6150set model for OpenCL 2.0 with the extension looks as follows:
6151
6152 | generic->global->host
6153 | ->device
6154 | ->private
6155 | ->local
6156 | constant
6157
6158As ``global_device`` and ``global_host`` are a subset of
6159``__global/opencl_global`` address spaces it is allowed to convert
6160``global_device`` and ``global_host`` address spaces to
6161``__global/opencl_global`` address spaces (following ISO/IEC TR 18037 5.1.3
6162"Address space nesting and rules for pointers").)reST";
6163
6164static const char AttrDoc_OpenCLIntelReqdSubGroupSize[] = R"reST(The optional attribute intel_reqd_sub_group_size can be used to indicate that
6165the kernel must be compiled and executed with the specified subgroup size. When
6166this attribute is present, get_max_sub_group_size() is guaranteed to return the
6167specified integer value. This is important for the correctness of many subgroup
6168algorithms, and in some cases may be used by the compiler to generate more optimal
6169code. See `cl_intel_required_subgroup_size
6170<https://www.khronos.org/registry/OpenCL/extensions/intel/cl_intel_required_subgroup_size.txt>`
6171for details.)reST";
6172
6173static const char AttrDoc_OpenCLLocalAddressSpace[] = R"reST(The local address space specifies that an object is allocated in the local (work
6174group) memory area, which is accessible to all work items in the same work
6175group. The content stored in this memory region is not accessible after
6176the kernel execution ends. In a kernel function scope, any variable can be in
6177the local address space. In other scopes, only pointer types to the local address
6178space are allowed. Local address space variables cannot have an initializer.)reST";
6179
6180static const char AttrDoc_OpenCLPrivateAddressSpace[] = R"reST(The private address space specifies that an object is allocated in the private
6181(work item) memory. Other work items cannot access the same memory area and its
6182content is destroyed after work item execution ends. Local variables can be
6183declared in the private address space. Function arguments are always in the
6184private address space. Kernel function arguments of a pointer or an array type
6185cannot point to the private address space.)reST";
6186
6187static const char AttrDoc_OpenCLUnrollHint[] = R"reST(The opencl_unroll_hint attribute qualifier can be used to specify that a loop
6188(for, while and do loops) can be unrolled. This attribute qualifier can be
6189used to specify full unrolling or partial unrolling by a specified amount.
6190This is a compiler hint and the compiler may ignore this directive. See
6191`OpenCL v2.0 <https://www.khronos.org/registry/cl/specs/opencl-2.0.pdf>`_
6192s6.11.5 for details.)reST";
6193
6194static const char AttrDoc_OptimizeNone[] = R"reST(The ``optnone`` attribute suppresses essentially all optimizations
6195on a function or method, regardless of the optimization level applied to
6196the compilation unit as a whole. This is particularly useful when you
6197need to debug a particular function, but it is infeasible to build the
6198entire application without optimization. Avoiding optimization on the
6199specified function can improve the quality of the debugging information
6200for that function.
6201
6202This attribute is incompatible with the ``always_inline`` and ``minsize``
6203attributes.
6204
6205Note that this attribute does not apply recursively to nested functions such as
6206lambdas or blocks when using declaration-specific attribute syntaxes such as double
6207square brackets (``[[]]``) or ``__attribute__``. The ``#pragma`` syntax can be
6208used to apply the attribute to all functions, including nested functions, in a
6209range of source code.)reST";
6210
6211static const char AttrDoc_Overloadable[] = R"reST(Clang provides support for C++ function overloading in C. Function overloading
6212in C is introduced using the ``overloadable`` attribute. For example, one
6213might provide several overloaded versions of a ``tgsin`` function that invokes
6214the appropriate standard function computing the sine of a value with ``float``,
6215``double``, or ``long double`` precision:
6216
6217.. code-block:: c
6218
6219 #include <math.h>
6220 float __attribute__((overloadable)) tgsin(float x) { return sinf(x); }
6221 double __attribute__((overloadable)) tgsin(double x) { return sin(x); }
6222 long double __attribute__((overloadable)) tgsin(long double x) { return sinl(x); }
6223
6224Given these declarations, one can call ``tgsin`` with a ``float`` value to
6225receive a ``float`` result, with a ``double`` to receive a ``double`` result,
6226etc. Function overloading in C follows the rules of C++ function overloading
6227to pick the best overload given the call arguments, with a few C-specific
6228semantics:
6229
6230* Conversion from ``float`` or ``double`` to ``long double`` is ranked as a
6231 floating-point promotion (per C99) rather than as a floating-point conversion
6232 (as in C++).
6233
6234* A conversion from a pointer of type ``T*`` to a pointer of type ``U*`` is
6235 considered a pointer conversion (with conversion rank) if ``T`` and ``U`` are
6236 compatible types.
6237
6238* A conversion from type ``T`` to a value of type ``U`` is permitted if ``T``
6239 and ``U`` are compatible types. This conversion is given "conversion" rank.
6240
6241* If no viable candidates are otherwise available, we allow a conversion from a
6242 pointer of type ``T*`` to a pointer of type ``U*``, where ``T`` and ``U`` are
6243 incompatible. This conversion is ranked below all other types of conversions.
6244 Please note: ``U`` lacking qualifiers that are present on ``T`` is sufficient
6245 for ``T`` and ``U`` to be incompatible.
6246
6247The declaration of ``overloadable`` functions is restricted to function
6248declarations and definitions. If a function is marked with the ``overloadable``
6249attribute, then all declarations and definitions of functions with that name,
6250except for at most one (see the note below about unmarked overloads), must have
6251the ``overloadable`` attribute. In addition, redeclarations of a function with
6252the ``overloadable`` attribute must have the ``overloadable`` attribute, and
6253redeclarations of a function without the ``overloadable`` attribute must *not*
6254have the ``overloadable`` attribute. e.g.,
6255
6256.. code-block:: c
6257
6258 int f(int) __attribute__((overloadable));
6259 float f(float); // error: declaration of "f" must have the "overloadable" attribute
6260 int f(int); // error: redeclaration of "f" must have the "overloadable" attribute
6261
6262 int g(int) __attribute__((overloadable));
6263 int g(int) { } // error: redeclaration of "g" must also have the "overloadable" attribute
6264
6265 int h(int);
6266 int h(int) __attribute__((overloadable)); // error: declaration of "h" must not
6267 // have the "overloadable" attribute
6268
6269Functions marked ``overloadable`` must have prototypes. Therefore, the
6270following code is ill-formed:
6271
6272.. code-block:: c
6273
6274 int h() __attribute__((overloadable)); // error: h does not have a prototype
6275
6276However, ``overloadable`` functions are allowed to use a ellipsis even if there
6277are no named parameters (as is permitted in C++). This feature is particularly
6278useful when combined with the ``unavailable`` attribute:
6279
6280.. code-block:: c++
6281
6282 void honeypot(...) __attribute__((overloadable, unavailable)); // calling me is an error
6283
6284Functions declared with the ``overloadable`` attribute have their names mangled
6285according to the same rules as C++ function names. For example, the three
6286``tgsin`` functions in our motivating example get the mangled names
6287``_Z5tgsinf``, ``_Z5tgsind``, and ``_Z5tgsine``, respectively. There are two
6288caveats to this use of name mangling:
6289
6290* Future versions of Clang may change the name mangling of functions overloaded
6291 in C, so you should not depend on an specific mangling. To be completely
6292 safe, we strongly urge the use of ``static inline`` with ``overloadable``
6293 functions.
6294
6295* The ``overloadable`` attribute has almost no meaning when used in C++,
6296 because names will already be mangled and functions are already overloadable.
6297 However, when an ``overloadable`` function occurs within an ``extern "C"``
6298 linkage specification, its name *will* be mangled in the same way as it
6299 would in C.
6300
6301For the purpose of backwards compatibility, at most one function with the same
6302name as other ``overloadable`` functions may omit the ``overloadable``
6303attribute. In this case, the function without the ``overloadable`` attribute
6304will not have its name mangled.
6305
6306For example:
6307
6308.. code-block:: c
6309
6310 // Notes with mangled names assume Itanium mangling.
6311 int f(int);
6312 int f(double) __attribute__((overloadable));
6313 void foo() {
6314 f(5); // Emits a call to f (not _Z1fi, as it would with an overload that
6315 // was marked with overloadable).
6316 f(1.0); // Emits a call to _Z1fd.
6317 }
6318
6319Support for unmarked overloads is not present in some versions of clang. You may
6320query for it using ``__has_extension(overloadable_unmarked)``.
6321
6322Query for this attribute with ``__has_attribute(overloadable)``.)reST";
6323
6324static const char AttrDoc_Override[] = R"reST()reST";
6325
6326static const char AttrDoc_Owner[] = R"reST(.. Note:: This attribute is experimental and its effect on analysis is subject to change in
6327 a future version of clang.
6328
6329The attribute ``[[gsl::Owner(T)]]`` applies to structs and classes that own an
6330object of type ``T``:
6331
6332.. code::
6333
6334 class [[gsl::Owner(int)]] IntOwner {
6335 private:
6336 int value;
6337 public:
6338 int *getInt() { return &value; }
6339 };
6340
6341The argument ``T`` is optional and is ignored.
6342This attribute may be used by analysis tools and has no effect on code
6343generation. A ``void`` argument means that the class can own any type.
6344
6345See Pointer_ for an example.)reST";
6346
6347static const char AttrDoc_Ownership[] = R"reST(.. note::
6348
6349 In order for the Clang Static Analyzer to acknowledge these attributes, the
6350 ``Optimistic`` config needs to be set to true for the checker
6351 ``unix.DynamicMemoryModeling``:
6352
6353 ``-Xclang -analyzer-config -Xclang unix.DynamicMemoryModeling:Optimistic=true``
6354
6355These attributes are used by the Clang Static Analyzer's dynamic memory modeling
6356facilities to mark custom allocating/deallocating functions.
6357
6358All 3 attributes' first parameter of type string is the type of the allocation:
6359``malloc``, ``new``, etc. to allow for catching :ref:`mismatched deallocation
6360<unix-MismatchedDeallocator>` bugs. The allocation type can be any string, e.g.
6361a function annotated with
6362returning a piece of memory of type ``lasagna`` but freed with a function
6363annotated to release ``cheese`` typed memory will result in mismatched
6364deallocation warning.
6365
6366The (currently) only allocation type having special meaning is ``malloc`` --
6367the Clang Static Analyzer makes sure that allocating functions annotated with
6368``malloc`` are treated like they used the standard ``malloc()``, and can be
6369safely deallocated with the standard ``free()``.
6370
6371* Use ``ownership_returns`` to mark a function as an allocating function. Takes
6372 1 parameter to denote the allocation type.
6373* Use ``ownership_takes`` to mark a function as a deallocating function. Takes 2
6374 parameters: the allocation type, and the index of the parameter that is being
6375 deallocated (counting from 1).
6376* Use ``ownership_holds`` to mark that a function takes over the ownership of a
6377 piece of memory and will free it at some unspecified point in the future. Like
6378 ``ownership_takes``, this takes 2 parameters: the allocation type, and the
6379 index of the parameter whose ownership will be taken over (counting from 1).
6380
6381The annotations ``ownership_takes`` and ``ownership_holds`` both prevent memory
6382leak reports (concerning the specified argument); the difference between them
6383is that using taken memory is a use-after-free error, while using held memory
6384is assumed to be legitimate.
6385
6386Example:
6387
6388.. code-block:: c
6389
6390 // Denotes that my_malloc will return with a dynamically allocated piece of
6391 // memory using malloc().
6392 void __attribute((ownership_returns(malloc))) *my_malloc(size_t);
6393
6394 // Denotes that my_free will deallocate its parameter using free().
6395 void __attribute((ownership_takes(malloc, 1))) my_free(void *);
6396
6397 // Denotes that my_hold will take over the ownership of its parameter that was
6398 // allocated via malloc().
6399 void __attribute((ownership_holds(malloc, 1))) my_hold(void *);
6400
6401Further reading about dynamic memory modeling in the Clang Static Analyzer is
6402found in these checker docs:
6403:ref:`unix.Malloc <unix-Malloc>`, :ref:`unix.MallocSizeof <unix-MallocSizeof>`,
6404:ref:`unix.MismatchedDeallocator <unix-MismatchedDeallocator>`,
6405:ref:`cplusplus.NewDelete <cplusplus-NewDelete>`,
6406:ref:`cplusplus.NewDeleteLeaks <cplusplus-NewDeleteLeaks>`,
6407:ref:`optin.taint.TaintedAlloc <optin-taint-TaintedAlloc>`.
6408Mind that many more checkers are affected by dynamic memory modeling changes to
6409some extent.
6410
6411Further reading for other annotations:
6412`Source Annotations in the Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/user-docs/Annotations.html>`_.)reST";
6413
6414static const char AttrDoc_Packed[] = R"reST(No documentation.)reST";
6415
6416static const char AttrDoc_ParamTypestate[] = R"reST(This attribute specifies expectations about function parameters. Calls to an
6417function with annotated parameters will issue a warning if the corresponding
6418argument isn't in the expected state. The attribute is also used to set the
6419initial state of the parameter when analyzing the function's body.)reST";
6420
6421static const char AttrDoc_Pascal[] = R"reST(No documentation.)reST";
6422
6423static const char AttrDoc_PassObjectSize[] = R"reST(.. Note:: The mangling of functions with parameters that are annotated with
6424 ``pass_object_size`` is subject to change. You can get around this by
6425 using ``__asm__("foo")`` to explicitly name your functions, thus preserving
6426 your ABI; also, non-overloadable C functions with ``pass_object_size`` are
6427 not mangled.
6428
6429The ``pass_object_size(Type)`` attribute can be placed on function parameters to
6430instruct clang to call ``__builtin_object_size(param, Type)`` at each callsite
6431of said function, and implicitly pass the result of this call in as an invisible
6432argument of type ``size_t`` directly after the parameter annotated with
6433``pass_object_size``. Clang will also replace any calls to
6434``__builtin_object_size(param, Type)`` in the function by said implicit
6435parameter.
6436
6437Example usage:
6438
6439.. code-block:: c
6440
6441 int bzero1(char *const p __attribute__((pass_object_size(0))))
6442 __attribute__((noinline)) {
6443 int i = 0;
6444 for (/**/; i < (int)__builtin_object_size(p, 0); ++i) {
6445 p[i] = 0;
6446 }
6447 return i;
6448 }
6449
6450 int main() {
6451 char chars[100];
6452 int n = bzero1(&chars[0]);
6453 assert(n == sizeof(chars));
6454 return 0;
6455 }
6456
6457If successfully evaluating ``__builtin_object_size(param, Type)`` at the
6458callsite is not possible, then the "failed" value is passed in. So, using the
6459definition of ``bzero1`` from above, the following code would exit cleanly:
6460
6461.. code-block:: c
6462
6463 int main2(int argc, char *argv[]) {
6464 int n = bzero1(argv);
6465 assert(n == -1);
6466 return 0;
6467 }
6468
6469``pass_object_size`` plays a part in overload resolution. If two overload
6470candidates are otherwise equally good, then the overload with one or more
6471parameters with ``pass_object_size`` is preferred. This implies that the choice
6472between two identical overloads both with ``pass_object_size`` on one or more
6473parameters will always be ambiguous; for this reason, having two such overloads
6474is illegal. For example:
6475
6476.. code-block:: c++
6477
6478 #define PS(N) __attribute__((pass_object_size(N)))
6479 // OK
6480 void Foo(char *a, char *b); // Overload A
6481 // OK -- overload A has no parameters with pass_object_size.
6482 void Foo(char *a PS(0), char *b PS(0)); // Overload B
6483 // Error -- Same signature (sans pass_object_size) as overload B, and both
6484 // overloads have one or more parameters with the pass_object_size attribute.
6485 void Foo(void *a PS(0), void *b);
6486
6487 // OK
6488 void Bar(void *a PS(0)); // Overload C
6489 // OK
6490 void Bar(char *c PS(1)); // Overload D
6491
6492 void main() {
6493 char known[10], *unknown;
6494 Foo(unknown, unknown); // Calls overload B
6495 Foo(known, unknown); // Calls overload B
6496 Foo(unknown, known); // Calls overload B
6497 Foo(known, known); // Calls overload B
6498
6499 Bar(known); // Calls overload D
6500 Bar(unknown); // Calls overload D
6501 }
6502
6503Currently, ``pass_object_size`` is a bit restricted in terms of its usage:
6504
6505* Only one use of ``pass_object_size`` is allowed per parameter.
6506
6507* It is an error to take the address of a function with ``pass_object_size`` on
6508 any of its parameters. If you wish to do this, you can create an overload
6509 without ``pass_object_size`` on any parameters.
6510
6511* It is an error to apply the ``pass_object_size`` attribute to parameters that
6512 are not pointers. Additionally, any parameter that ``pass_object_size`` is
6513 applied to must be marked ``const`` at its function's definition.
6514
6515Clang also supports the ``pass_dynamic_object_size`` attribute, which behaves
6516identically to ``pass_object_size``, but evaluates a call to
6517``__builtin_dynamic_object_size`` at the callee instead of
6518``__builtin_object_size``. ``__builtin_dynamic_object_size`` provides some extra
6519runtime checks when the object size can't be determined at compile-time. You can
6520read more about ``__builtin_dynamic_object_size`` `here
6521<https://clang.llvm.org/docs/LanguageExtensions.html#evaluating-object-size-dynamically>`_.)reST";
6522
6523static const char AttrDoc_PatchableFunctionEntry[] = R"reST(``__attribute__((patchable_function_entry(N,M,Section)))`` is used to generate M
6524NOPs before the function entry and N-M NOPs after the function entry, with a record of
6525the entry stored in section ``Section``. This attribute takes precedence over the
6526command line option ``-fpatchable-function-entry=N,M,Section``. ``M`` defaults to 0
6527if omitted.``Section`` defaults to the ``-fpatchable-function-entry`` section name if
6528set, or to ``__patchable_function_entries`` otherwise.
6529
6530This attribute is only supported on
6531aarch64/aarch64-be/loongarch32/loongarch64/riscv32/riscv64/i386/x86-64/ppc/ppc64 targets.
6532For ppc/ppc64 targets, AIX is still not supported.)reST";
6533
6534static const char AttrDoc_Pcs[] = R"reST(On ARM targets, this attribute can be used to select calling conventions
6535similar to ``stdcall`` on x86. Valid parameter values are "aapcs" and
6536"aapcs-vfp".)reST";
6537
6538static const char AttrDoc_Pointer[] = R"reST(.. Note:: This attribute is experimental and its effect on analysis is subject to change in
6539 a future version of clang.
6540
6541The attribute ``[[gsl::Pointer(T)]]`` applies to structs and classes that behave
6542like pointers to an object of type ``T``:
6543
6544.. code::
6545
6546 class [[gsl::Pointer(int)]] IntPointer {
6547 private:
6548 int *valuePointer;
6549 public:
6550 IntPointer(const IntOwner&);
6551 int *getInt() { return valuePointer; }
6552 };
6553
6554The argument ``T`` is optional and is ignored.
6555This attribute may be used by analysis tools and has no effect on code
6556generation. A ``void`` argument means that the pointer can point to any type.
6557
6558Example:
6559When constructing an instance of a class annotated like this (a Pointer) from
6560an instance of a class annotated with ``[[gsl::Owner]]`` (an Owner),
6561then the analysis will consider the Pointer to point inside the Owner.
6562When the Owner's lifetime ends, it will consider the Pointer to be dangling.
6563
6564.. code-block:: c++
6565
6566 int f() {
6567 IntPointer P(IntOwner{}); // P "points into" a temporary IntOwner object
6568 P.getInt(); // P is dangling
6569 }
6570
6571If a template class is annotated with ``[[gsl::Owner]]``, and the first
6572instantiated template argument is a pointer type (raw pointer, or ``[[gsl::Pointer]]``),
6573the analysis will consider the instantiated class as a container of the pointer.
6574When constructing such an object from a GSL owner object, the analysis will
6575assume that the container holds a pointer to the owner object. Consequently,
6576when the owner object is destroyed, the pointer will be considered dangling.
6577
6578.. code-block:: c++
6579
6580 int f() {
6581 std::vector<std::string_view> v = {std::string()}; // v holds a dangling pointer.
6582 std::optional<std::string_view> o = std::string(); // o holds a dangling pointer.
6583 })reST";
6584
6585static const char AttrDoc_PointerAuth[] = R"reST(The ``__ptrauth`` qualifier allows the programmer to directly control
6586how pointers are signed when they are stored in a particular variable.
6587This can be used to strengthen the default protections of pointer
6588authentication and make it more difficult for an attacker to escalate
6589an ability to alter memory into full control of a process.
6590
6591.. code-block:: c
6592
6593 #include <ptrauth.h>
6594
6595 typedef void (*my_callback)(const void*);
6596 my_callback __ptrauth(ptrauth_key_process_dependent_code, 1, 0xe27a) callback;
6597
6598The first argument to ``__ptrauth`` is the name of the signing key.
6599Valid key names for the target are defined in ``<ptrauth.h>``.
6600
6601The second argument to ``__ptrauth`` is a flag (0 or 1) specifying whether
6602the object should use address discrimination.
6603
6604The third argument to ``__ptrauth`` is a 16-bit non-negative integer which
6605allows additional discrimination between objects.)reST";
6606
6607static const char AttrDoc_PragmaClangBSSSection[] = R"reST()reST";
6608
6609static const char AttrDoc_PragmaClangDataSection[] = R"reST()reST";
6610
6611static const char AttrDoc_PragmaClangRelroSection[] = R"reST()reST";
6612
6613static const char AttrDoc_PragmaClangRodataSection[] = R"reST()reST";
6614
6615static const char AttrDoc_PragmaClangTextSection[] = R"reST()reST";
6616
6617static const char AttrDoc_PreferredName[] = R"reST(The ``preferred_name`` attribute can be applied to a class template, and
6618specifies a preferred way of naming a specialization of the template. The
6619preferred name will be used whenever the corresponding template specialization
6620would otherwise be printed in a diagnostic or similar context.
6621
6622The preferred name must be a typedef or type alias declaration that refers to a
6623specialization of the class template (not including any type qualifiers). In
6624general this requires the template to be declared at least twice. For example:
6625
6626.. code-block:: c++
6627
6628 template<typename T> struct basic_string;
6629 using string = basic_string<char>;
6630 using wstring = basic_string<wchar_t>;
6631 template<typename T> struct [[clang::preferred_name(string),
6632 clang::preferred_name(wstring)]] basic_string {
6633 // ...
6634 };
6635
6636
6637Note that the ``preferred_name`` attribute will be ignored when the compiler
6638writes a C++20 Module interface now. This is due to a compiler issue
6639(https://github.com/llvm/llvm-project/issues/56490) that blocks users to modularize
6640declarations with `preferred_name`. This is intended to be fixed in the future.)reST";
6641
6642static const char AttrDoc_PreferredType[] = R"reST(This attribute allows adjusting the type of a bit-field in debug information.
6643This can be helpful when a bit-field is intended to store an enumeration value,
6644but has to be specified as having the enumeration's underlying type in order to
6645facilitate compiler optimizations or bit-field packing behavior. Normally, the
6646underlying type is what is emitted in debug information, which can make it hard
6647for debuggers to know to map a bit-field's value back to a particular enumeration.
6648
6649.. code-block:: c++
6650
6651 enum Colors { Red, Green, Blue };
6652
6653 struct S {
6654 [[clang::preferred_type(Colors)]] unsigned ColorVal : 2;
6655 [[clang::preferred_type(bool)]] unsigned UseAlternateColorSpace : 1;
6656 } s = { Green, false };
6657
6658Without the attribute, a debugger is likely to display the value ``1`` for ``ColorVal``
6659and ``0`` for ``UseAlternateColorSpace``. With the attribute, the debugger may now
6660display ``Green`` and ``false`` instead.
6661
6662This can be used to map a bit-field to an arbitrary type that isn't integral
6663or an enumeration type. For example:
6664
6665.. code-block:: c++
6666
6667 struct A {
6668 short a1;
6669 short a2;
6670 };
6671
6672 struct B {
6673 [[clang::preferred_type(A)]] unsigned b1 : 32 = 0x000F'000C;
6674 };
6675
6676will associate the type ``A`` with the ``b1`` bit-field and is intended to display
6677something like this in the debugger:
6678
6679.. code-block:: text
6680
6681 Process 2755547 stopped
6682 * thread #1, name = 'test-preferred-', stop reason = step in
6683 frame #0: 0x0000555555555148 test-preferred-type`main at test.cxx:13:14
6684 10 int main()
6685 11 {
6686 12 B b;
6687 -> 13 return b.b1;
6688 14 }
6689 (lldb) v -T
6690 (B) b = {
6691 (A:32) b1 = {
6692 (short) a1 = 12
6693 (short) a2 = 15
6694 }
6695 }
6696
6697Note that debuggers may not be able to handle more complex mappings, and so
6698this usage is debugger-dependent.)reST";
6699
6700static const char AttrDoc_PreserveAll[] = R"reST(On X86-64 and AArch64 targets, this attribute changes the calling convention of
6701a function. The ``preserve_all`` calling convention attempts to make the code
6702in the caller even less intrusive than the ``preserve_most`` calling convention.
6703This calling convention also behaves identical to the ``C`` calling convention
6704on how arguments and return values are passed, but it uses a different set of
6705caller/callee-saved registers. This removes the burden of saving and
6706recovering a large register set before and after the call in the caller. If
6707the arguments are passed in callee-saved registers, then they will be
6708preserved by the callee across the call. This doesn't apply for values
6709returned in callee-saved registers.
6710
6711- On X86-64 the callee preserves all general purpose registers, except for
6712 R11. R11 can be used as a scratch register. Furthermore it also preserves
6713 all floating-point registers (XMMs/YMMs).
6714
6715- On AArch64 the callee preserve all general purpose registers, except X0-X8 and
6716 X16-X18. Furthermore it also preserves lower 128 bits of V8-V31 SIMD - floating
6717 point registers.
6718
6719The idea behind this convention is to support calls to runtime functions
6720that don't need to call out to any other functions.
6721
6722This calling convention, like the ``preserve_most`` calling convention, will be
6723used by a future version of the Objective-C runtime and should be considered
6724experimental at this time.)reST";
6725
6726static const char AttrDoc_PreserveMost[] = R"reST(On X86-64 and AArch64 targets, this attribute changes the calling convention of
6727a function. The ``preserve_most`` calling convention attempts to make the code
6728in the caller as unintrusive as possible. This convention behaves identically
6729to the ``C`` calling convention on how arguments and return values are passed,
6730but it uses a different set of caller/callee-saved registers. This alleviates
6731the burden of saving and recovering a large register set before and after the
6732call in the caller. If the arguments are passed in callee-saved registers,
6733then they will be preserved by the callee across the call. This doesn't
6734apply for values returned in callee-saved registers.
6735
6736- On X86-64 the callee preserves all general purpose registers, except for
6737 R11. R11 can be used as a scratch register. Floating-point registers
6738 (XMMs/YMMs) are not preserved and need to be saved by the caller.
6739
6740- On AArch64 the callee preserve all general purpose registers, except X0-X8 and
6741 X16-X18.
6742
6743The idea behind this convention is to support calls to runtime functions
6744that have a hot path and a cold path. The hot path is usually a small piece
6745of code that doesn't use many registers. The cold path might need to call out to
6746another function and therefore only needs to preserve the caller-saved
6747registers, which haven't already been saved by the caller. The
6748``preserve_most`` calling convention is very similar to the ``cold`` calling
6749convention in terms of caller/callee-saved registers, but they are used for
6750different types of function calls. ``coldcc`` is for function calls that are
6751rarely executed, whereas ``preserve_most`` function calls are intended to be
6752on the hot path and definitely executed a lot. Furthermore ``preserve_most``
6753doesn't prevent the inliner from inlining the function call.
6754
6755This calling convention will be used by a future version of the Objective-C
6756runtime and should therefore still be considered experimental at this time.
6757Although this convention was created to optimize certain runtime calls to
6758the Objective-C runtime, it is not limited to this runtime and might be used
6759by other runtimes in the future too. The current implementation only
6760supports X86-64 and AArch64, but the intention is to support more architectures
6761in the future.)reST";
6762
6763static const char AttrDoc_PreserveNone[] = R"reST(On X86-64 and AArch64 targets, this attribute changes the calling convention of a function.
6764The ``preserve_none`` calling convention tries to preserve as few general
6765registers as possible. So all general registers are caller saved registers. It
6766also uses more general registers to pass arguments. This attribute doesn't
6767impact floating-point registers. ``preserve_none``'s ABI is still unstable, and
6768may be changed in the future.
6769
6770- On X86-64, only RSP and RBP are preserved by the callee.
6771 Registers R12, R13, R14, R15, RDI, RSI, RDX, RCX, R8, R9, R11, and RAX now can
6772 be used to pass function arguments. Floating-point registers (XMMs/YMMs) still
6773 follow the C calling convention.
6774- On AArch64, only LR and FP are preserved by the callee.
6775 Registers X20-X28, X0-X7, and X9-X14 are used to pass function arguments.
6776 X8, X16-X19, SIMD and floating-point registers follow the AAPCS calling
6777 convention. X15 is not available for argument passing on Windows, but is
6778 used to pass arguments on other platforms.)reST";
6779
6780static const char AttrDoc_PtGuardedBy[] = R"reST(No documentation.)reST";
6781
6782static const char AttrDoc_PtGuardedVar[] = R"reST(No documentation.)reST";
6783
6784static const char AttrDoc_Ptr32[] = R"reST(The ``__ptr32`` qualifier represents a native pointer on a 32-bit system. On a
678564-bit system, a pointer with ``__ptr32`` is extended to a 64-bit pointer. The
6786``__sptr`` and ``__uptr`` qualifiers can be used to specify whether the pointer
6787is sign extended or zero extended. This qualifier is enabled under
6788``-fms-extensions``.)reST";
6789
6790static const char AttrDoc_Ptr64[] = R"reST(The ``__ptr64`` qualifier represents a native pointer on a 64-bit system. On a
679132-bit system, a ``__ptr64`` pointer is truncated to a 32-bit pointer. This
6792qualifier is enabled under ``-fms-extensions``.)reST";
6793
6794static const char AttrDoc_Pure[] = R"reST(No documentation.)reST";
6795
6796static const char AttrDoc_RISCVInterrupt[] = R"reST(Clang supports the GNU style ``__attribute__((interrupt))`` attribute on RISCV
6797targets. This attribute may be attached to a function definition and instructs
6798the backend to generate appropriate function entry/exit code so that it can be
6799used directly as an interrupt service routine.
6800
6801Permissible values for this parameter are ``machine``, ``supervisor``,
6802``qci-nest``, ``qci-nonest``, ``SiFive-CLIC-preemptible``, and
6803``SiFive-CLIC-stack-swap``. If there is no parameter, then it defaults to
6804``machine``.
6805
6806The ``qci-nest`` and ``qci-nonest`` values require Qualcomm's Xqciint extension
6807and are used for Machine-mode Interrupts and Machine-mode Non-maskable
6808interrupts. These use the following instructions from Xqciint to save and
6809restore interrupt state to the stack -- the ``qci-nest`` value will use
6810``qc.c.mienter.nest`` and the ``qci-nonest`` value will use ``qc.c.mienter`` to
6811begin the interrupt handler. Both of these will use ``qc.c.mileaveret`` to
6812restore the state and return to the previous context.
6813
6814The ``SiFive-CLIC-preemptible`` and ``SiFive-CLIC-stack-swap`` values are used
6815for machine-mode interrupts. For ``SiFive-CLIC-preemptible`` interrupts, the
6816values of ``mcause`` and ``mepc`` are saved onto the stack, and interrupts are
6817re-enabled. For ``SiFive-CLIC-stack-swap`` interrupts, the stack pointer is
6818swapped with ``mscratch`` before its first use and after its last use.
6819
6820The SiFive CLIC values may be combined with each other and with the ``machine``
6821attribute value. Any other combination of different values is not allowed.
6822
6823Repeated interrupt attribute on the same declaration will cause a warning
6824to be emitted. In case of repeated declarations, the last one prevails.
6825
6826Refer to:
6827https://gcc.gnu.org/onlinedocs/gcc/RISC-V-Function-Attributes.html
6828https://riscv.org/specifications/privileged-isa/
6829The RISC-V Instruction Set Manual Volume II: Privileged Architecture
6830Version 1.10.
6831https://github.com/quic/riscv-unified-db/releases/tag/Xqci-0.13.0
6832https://sifive.cdn.prismic.io/sifive/d1984d2b-c9b9-4c91-8de0-d68a5e64fa0f_sifive-interrupt-cookbook-v1p2.pdf)reST";
6833
6834static const char AttrDoc_RISCVVLSCC[] = R"reST(The ``riscv_vls_cc`` attribute can be applied to a function. Functions
6835declared with this attribute will utilize the standard fixed-length vector
6836calling convention variant instead of the default calling convention defined by
6837the ABI. This variant aims to pass fixed-length vectors via vector registers,
6838if possible, rather than through general-purpose registers.)reST";
6839
6840static const char AttrDoc_RISCVVectorCC[] = R"reST(The ``riscv_vector_cc`` attribute can be applied to a function. It preserves 15
6841registers namely, v1-v7 and v24-v31 as callee-saved. Callers thus don't need
6842to save these registers before function calls, and callees only need to save
6843them if they use them.)reST";
6844
6845static const char AttrDoc_RandomizeLayout[] = R"reST(The attribute ``randomize_layout``, when attached to a C structure, selects it
6846for structure layout field randomization; a compile-time hardening technique. A
6847"seed" value, is specified via the ``-frandomize-layout-seed=`` command line flag.
6848For example:
6849
6850.. code-block:: bash
6851
6852 SEED=`od -A n -t x8 -N 32 /dev/urandom | tr -d ' \n'`
6853 make ... CFLAGS="-frandomize-layout-seed=$SEED" ...
6854
6855You can also supply the seed in a file with ``-frandomize-layout-seed-file=``.
6856For example:
6857
6858.. code-block:: bash
6859
6860 od -A n -t x8 -N 32 /dev/urandom | tr -d ' \n' > /tmp/seed_file.txt
6861 make ... CFLAGS="-frandomize-layout-seed-file=/tmp/seed_file.txt" ...
6862
6863The randomization is deterministic based for a given seed, so the entire
6864program should be compiled with the same seed, but keep the seed safe
6865otherwise.
6866
6867The attribute ``no_randomize_layout``, when attached to a C structure,
6868instructs the compiler that this structure should not have its field layout
6869randomized.)reST";
6870
6871static const char AttrDoc_ReadOnlyPlacement[] = R"reST(This attribute is attached to a structure, class or union declaration.
6872 When attached to a record declaration/definition, it checks if all instances
6873 of this type can be placed in the read-only data segment of the program. If it
6874 finds an instance that can not be placed in a read-only segment, the compiler
6875 emits a warning at the source location where the type was used.
6876
6877 Examples:
6878 * ``struct __attribute__((enforce_read_only_placement)) Foo;``
6879 * ``struct __attribute__((enforce_read_only_placement)) Bar { ... };``
6880
6881 Both ``Foo`` and ``Bar`` types have the ``enforce_read_only_placement`` attribute.
6882
6883 The goal of introducing this attribute is to assist developers with writing secure
6884 code. A ``const``-qualified global is generally placed in the read-only section
6885 of the memory that has additional run time protection from malicious writes. By
6886 attaching this attribute to a declaration, the developer can express the intent
6887 to place all instances of the annotated type in the read-only program memory.
6888
6889 Note 1: The attribute doesn't guarantee that the object will be placed in the
6890 read-only data segment as it does not instruct the compiler to ensure such
6891 a placement. It emits a warning if something in the code can be proven to prevent
6892 an instance from being placed in the read-only data segment.
6893
6894 Note 2: Currently, clang only checks if all global declarations of a given type 'T'
6895 are ``const``-qualified. The following conditions would also prevent the data to be
6896 put into read only segment, but the corresponding warnings are not yet implemented.
6897
6898 1. An instance of type ``T`` is allocated on the heap/stack.
6899 2. Type ``T`` defines/inherits a mutable field.
6900 3. Type ``T`` defines/inherits non-constexpr constructor(s) for initialization.
6901 4. A field of type ``T`` is defined by type ``Q``, which does not bear the
6902 ``enforce_read_only_placement`` attribute.
6903 5. A type ``Q`` inherits from type ``T`` and it does not have the
6904 ``enforce_read_only_placement`` attribute.)reST";
6905
6906static const char AttrDoc_ReentrantCapability[] = R"reST(No documentation.)reST";
6907
6908static const char AttrDoc_RegCall[] = R"reST(On x86 targets, this attribute changes the calling convention to
6909`__regcall`_ convention. This convention aims to pass as many arguments
6910as possible in registers. It also tries to utilize registers for the
6911return value whenever it is possible.
6912
6913.. _`__regcall`: https://www.intel.com/content/www/us/en/docs/dpcpp-cpp-compiler/developer-guide-reference/2023-2/c-c-sycl-calling-conventions.html)reST";
6914
6915static const char AttrDoc_Reinitializes[] = R"reST(The ``reinitializes`` attribute can be applied to a non-static, non-const C++
6916member function to indicate that this member function reinitializes the entire
6917object to a known state, independent of the previous state of the object.
6918
6919This attribute can be interpreted by static analyzers that warn about uses of an
6920object that has been left in an indeterminate state by a move operation. If a
6921member function marked with the ``reinitializes`` attribute is called on a
6922moved-from object, the analyzer can conclude that the object is no longer in an
6923indeterminate state.
6924
6925A typical example where this attribute would be used is on functions that clear
6926a container class:
6927
6928.. code-block:: c++
6929
6930 template <class T>
6931 class Container {
6932 public:
6933 ...
6934 [[clang::reinitializes]] void Clear();
6935 ...
6936 };)reST";
6937
6938static const char AttrDoc_ReleaseCapability[] = R"reST(Marks a function as releasing a capability.)reST";
6939
6940static const char AttrDoc_ReleaseHandle[] = R"reST(If a function parameter is annotated with ``release_handle(tag)`` it is assumed to
6941close the handle. It is also assumed to require an open handle to work with. The
6942attribute requires a string literal argument to identify the handle being released.
6943
6944.. code-block:: c++
6945
6946 zx_status_t zx_handle_close(zx_handle_t handle [[clang::release_handle("tag")]]);)reST";
6947
6948static const char AttrDoc_Replaceable[] = R"reST()reST";
6949
6950static const char AttrDoc_ReqdWorkGroupSize[] = R"reST(No documentation.)reST";
6951
6952static const char AttrDoc_RequiresCapability[] = R"reST(No documentation.)reST";
6953
6954static const char AttrDoc_Restrict[] = R"reST(The ``malloc`` attribute has two forms with different functionality. The first
6955is when it is used without arguments, where it marks that a function acts like
6956a system memory allocation function, returning a pointer to allocated storage
6957that does not alias storage from any other object accessible to the caller.
6958
6959The second form is when ``malloc`` takes one or two arguments. The first
6960argument names a function that should be associated with this function as its
6961deallocation function. When this form is used, it enables the compiler to
6962diagnose when the incorrect deallocation function is used with this variable.
6963However the associated warning, spelled `-Wmismatched-dealloc` in GCC, is not
6964yet implemented in clang.)reST";
6965
6966static const char AttrDoc_Retain[] = R"reST(This attribute, when attached to a function or variable definition, prevents
6967section garbage collection in the linker. It does not prevent other discard
6968mechanisms, such as archive member selection, and COMDAT group resolution.
6969
6970If the compiler does not emit the definition, e.g. because it was not used in
6971the translation unit or the compiler was able to eliminate all of the uses,
6972this attribute has no effect. This attribute is typically combined with the
6973``used`` attribute to force the definition to be emitted and preserved into the
6974final linked image.
6975
6976This attribute is only necessary on ELF targets; other targets prevent section
6977garbage collection by the linker when using the ``used`` attribute alone.
6978Using the attributes together should result in consistent behavior across
6979targets.
6980
6981This attribute requires the linker to support the ``SHF_GNU_RETAIN`` extension.
6982This support is available in GNU ``ld`` and ``gold`` as of binutils 2.36, as
6983well as in ``ld.lld`` 13.)reST";
6984
6985static const char AttrDoc_ReturnTypestate[] = R"reST(The ``return_typestate`` attribute can be applied to functions or parameters.
6986When applied to a function the attribute specifies the state of the returned
6987value. The function's body is checked to ensure that it always returns a value
6988in the specified state. On the caller side, values returned by the annotated
6989function are initialized to the given state.
6990
6991When applied to a function parameter it modifies the state of an argument after
6992a call to the function returns. The function's body is checked to ensure that
6993the parameter is in the expected state before returning.)reST";
6994
6995static const char AttrDoc_ReturnsNonNull[] = R"reST(The ``returns_nonnull`` attribute indicates that a particular function (or
6996Objective-C method) always returns a non-null pointer. For example, a
6997particular system ``malloc`` might be defined to terminate a process when
6998memory is not available rather than returning a null pointer:
6999
7000 .. code-block:: c
7001
7002 extern void * malloc (size_t size) __attribute__((returns_nonnull));
7003
7004The ``returns_nonnull`` attribute implies that returning a null pointer is
7005undefined behavior, which the optimizer may take advantage of. The ``_Nonnull``
7006type qualifier indicates that a pointer cannot be null in a more general manner
7007(because it is part of the type system) and does not imply undefined behavior,
7008making it more widely applicable)reST";
7009
7010static const char AttrDoc_ReturnsTwice[] = R"reST(No documentation.)reST";
7011
7012static const char AttrDoc_RootSignature[] = R"reST(The ``RootSignature`` attribute applies to HLSL entry functions to define what
7013types of resources are bound to the graphics pipeline.
7014
7015For details about the use and specification of Root Signatures please see here:
7016https://learn.microsoft.com/en-us/windows/win32/direct3d12/root-signatures)reST";
7017
7018static const char AttrDoc_SPtr[] = R"reST(The ``__sptr`` qualifier specifies that a 32-bit pointer should be sign
7019extended when converted to a 64-bit pointer.)reST";
7020
7021static const char AttrDoc_SYCLKernelEntryPoint[] = R"reST(The ``sycl_kernel_entry_point`` attribute facilitates the generation of an
7022offload kernel entry point, sometimes called a SYCL kernel caller function,
7023suitable for invoking a SYCL kernel on an offload device. The attribute is
7024intended for use in the implementation of SYCL kernel invocation functions
7025like the ``single_task`` and ``parallel_for`` member functions of the
7026``sycl::handler`` class specified in section 4.9.4, "Command group ``handler``
7027class", of the SYCL 2020 specification.
7028
7029The attribute requires a single type argument that specifies a class type that
7030meets the requirements for a SYCL kernel name as described in section 5.2,
7031"Naming of kernels", of the SYCL 2020 specification. A unique kernel name type
7032is required for each function declared with the attribute. The attribute may
7033not first appear on a declaration that follows a definition of the function.
7034
7035The attribute only appertains to functions and only those that meet the
7036following requirements.
7037
7038* Has a non-deduced ``void`` return type.
7039* Is not a non-static member function, constructor, or destructor.
7040* Is not a C variadic function.
7041* Is not a coroutine.
7042* Is not defined as deleted or as defaulted.
7043* Is not defined with a function try block.
7044* Is not declared with the ``constexpr`` or ``consteval`` specifiers.
7045* Is not declared with the ``[[noreturn]]`` attribute.
7046
7047Use in the implementation of a SYCL kernel invocation function might look as
7048follows.
7049
7050.. code-block:: c++
7051
7052 namespace sycl {
7053 class handler {
7054 template<typename KernelNameType, typename KernelType>
7055 [[ clang::sycl_kernel_entry_point(KernelNameType) ]]
7056 static void kernel_entry_point(KernelType kernel) {
7057 kernel();
7058 }
7059
7060 public:
7061 template<typename KernelNameType, typename KernelType>
7062 void single_task(KernelType kernel) {
7063 // Call kernel_entry_point() to trigger generation of an offload
7064 // kernel entry point.
7065 kernel_entry_point<KernelNameType>(kernel);
7066 // Call functions appropriate for the desired offload backend
7067 // (OpenCL, CUDA, HIP, Level Zero, etc...).
7068 }
7069 };
7070 } // namespace sycl
7071
7072A SYCL kernel is a callable object of class type that is constructed on a host,
7073often via a lambda expression, and then passed to a SYCL kernel invocation
7074function to be executed on an offload device. A SYCL kernel invocation function
7075is responsible for copying the provided SYCL kernel object to an offload
7076device and initiating a call to it. The SYCL kernel object and its data members
7077constitute the parameters of an offload kernel.
7078
7079A SYCL kernel type is required to satisfy the device copyability requirements
7080specified in section 3.13.1, "Device copyable", of the SYCL 2020 specification.
7081Additionally, any data members of the kernel object type are required to satisfy
7082section 4.12.4, "Rules for parameter passing to kernels". For most types, these
7083rules require that the type is trivially copyable. However, the SYCL
7084specification mandates that certain special SYCL types, such as
7085``sycl::accessor`` and ``sycl::stream`` be device copyable even if they are not
7086trivially copyable. These types require special handling because they cannot
7087be copied to device memory as if by ``memcpy()``. Additionally, some offload
7088backends, OpenCL for example, require objects of some of these types to be
7089passed as individual arguments to the offload kernel.
7090
7091An offload kernel consists of an entry point function that declares the
7092parameters of the offload kernel and the set of all functions and variables that
7093are directly or indirectly used by the entry point function.
7094
7095A SYCL kernel invocation function invokes a SYCL kernel on a device by
7096performing the following tasks (likely with the help of an offload backend
7097like OpenCL):
7098
7099#. Identifying the offload kernel entry point to be used for the SYCL kernel.
7100
7101#. Deconstructing the SYCL kernel object, if necessary, to produce the set of
7102 offload kernel arguments required by the offload kernel entry point.
7103
7104#. Copying the offload kernel arguments to device memory.
7105
7106#. Initiating execution of the offload kernel entry point.
7107
7108The offload kernel entry point for a SYCL kernel performs the following tasks:
7109
7110#. Reconstituting the SYCL kernel object, if necessary, using the offload
7111 kernel parameters.
7112
7113#. Calling the ``operator()`` member function of the (reconstituted) SYCL kernel
7114 object.
7115
7116The ``sycl_kernel_entry_point`` attribute automates generation of an offload
7117kernel entry point that performs those latter tasks. The parameters and body of
7118a function declared with the ``sycl_kernel_entry_point`` attribute specify a
7119pattern from which the parameters and body of the entry point function are
7120derived. Consider the following call to a SYCL kernel invocation function.
7121
7122.. code-block:: c++
7123
7124 struct S { int i; };
7125 void f(sycl::handler &handler, sycl::stream &sout, S s) {
7126 handler.single_task<struct KN>([=] {
7127 sout << "The value of s.i is " << s.i << "\n";
7128 });
7129 }
7130
7131The SYCL kernel object is the result of the lambda expression. It has two
7132data members corresponding to the captures of ``sout`` and ``s``. Since one
7133of these data members corresponds to a special SYCL type that must be passed
7134individually as an offload kernel parameter, it is necessary to decompose the
7135SYCL kernel object into its constituent parts; the offload kernel will have
7136two kernel parameters. Given a SYCL implementation that uses a
7137``sycl_kernel_entry_point`` attributed function like the one shown above, an
7138offload kernel entry point function will be generated that looks approximately
7139as follows.
7140
7141.. code-block:: c++
7142
7143 void sycl-kernel-caller-for-KN(sycl::stream sout, S s) {
7144 kernel-type kernel = { sout, s );
7145 kernel();
7146 }
7147
7148There are a few items worthy of note:
7149
7150#. The name of the generated function incorporates the SYCL kernel name,
7151 ``KN``, that was passed as the ``KernelNameType`` template parameter to
7152 ``kernel_entry_point()`` and provided as the argument to the
7153 ``sycl_kernel_entry_point`` attribute. There is a one-to-one correspondence
7154 between SYCL kernel names and offload kernel entry points.
7155
7156#. The SYCL kernel is a lambda closure type and therefore has no name;
7157 ``kernel-type`` is substituted above and corresponds to the ``KernelType``
7158 template parameter deduced in the call to ``kernel_entry_point()``.
7159 Lambda types cannot be declared and initialized using the aggregate
7160 initialization syntax used above, but the intended behavior should be clear.
7161
7162#. ``S`` is a device copyable type that does not directly or indirectly contain
7163 a data member of a SYCL special type. It therefore does not need to be
7164 decomposed into its constituent members to be passed as a kernel argument.
7165
7166#. The depiction of the ``sycl::stream`` parameter as a single self contained
7167 kernel parameter is an oversimplification. SYCL special types may require
7168 additional decomposition such that the generated function might have three
7169 or more parameters depending on how the SYCL library implementation defines
7170 these types.
7171
7172#. The call to ``kernel_entry_point()`` has no effect other than to trigger
7173 emission of the entry point function. The statments that make up the body
7174 of the function are not executed when the function is called; they are
7175 only used in the generation of the entry point function.
7176
7177It is not necessary for a function declared with the ``sycl_kernel_entry_point``
7178attribute to be called for the offload kernel entry point to be emitted. For
7179inline functions and function templates, any ODR-use will suffice. For other
7180functions, an ODR-use is not required; the offload kernel entry point will be
7181emitted if the function is defined.
7182
7183Functions declared with the ``sycl_kernel_entry_point`` attribute are not
7184limited to the simple example shown above. They may have additional template
7185parameters, declare additional function parameters, and have complex control
7186flow in the function body. Function parameter decomposition and reconstitution
7187is performed for all function parameters. The function must abide by the
7188language feature restrictions described in section 5.4, "Language restrictions
7189for device functions" in the SYCL 2020 specification.)reST";
7190
7191static const char AttrDoc_SYCLSpecialClass[] = R"reST(SYCL defines some special classes (accessor, sampler, and stream) which require
7192specific handling during the generation of the SPIR entry point.
7193The ``__attribute__((sycl_special_class))`` attribute is used in SYCL
7194headers to indicate that a class or a struct needs a specific handling when
7195it is passed from host to device.
7196Special classes will have a mandatory ``__init`` method and an optional
7197``__finalize`` method (the ``__finalize`` method is used only with the
7198``stream`` type). Kernel parameters types are extract from the ``__init`` method
7199parameters. The kernel function arguments list is derived from the
7200arguments of the ``__init`` method. The arguments of the ``__init`` method are
7201copied into the kernel function argument list and the ``__init`` and
7202``__finalize`` methods are called at the beginning and the end of the kernel,
7203respectively.
7204The ``__init`` and ``__finalize`` methods must be defined inside the
7205special class.
7206Please note that this is an attribute that is used as an internal
7207implementation detail and not intended to be used by external users.
7208
7209The syntax of the attribute is as follows:
7210
7211.. code-block:: text
7212
7213 class __attribute__((sycl_special_class)) accessor {};
7214 class [[clang::sycl_special_class]] accessor {};
7215
7216This is a code example that illustrates the use of the attribute:
7217
7218.. code-block:: c++
7219
7220 class __attribute__((sycl_special_class)) SpecialType {
7221 int F1;
7222 int F2;
7223 void __init(int f1) {
7224 F1 = f1;
7225 F2 = f1;
7226 }
7227 void __finalize() {}
7228 public:
7229 SpecialType() = default;
7230 int getF2() const { return F2; }
7231 };
7232
7233 int main () {
7234 SpecialType T;
7235 cgh.single_task([=] {
7236 T.getF2();
7237 });
7238 }
7239
7240This would trigger the following kernel entry point in the AST:
7241
7242.. code-block:: c++
7243
7244 void __sycl_kernel(int f1) {
7245 SpecialType T;
7246 T.__init(f1);
7247 ...
7248 T.__finalize()
7249 })reST";
7250
7251static const char AttrDoc_ScopedLockable[] = R"reST(No documentation.)reST";
7252
7253static const char AttrDoc_Section[] = R"reST(The ``section`` attribute allows you to specify a specific section a
7254global variable or function should be in after translation.)reST";
7255
7256static const char AttrDoc_SelectAny[] = R"reST(This attribute appertains to a global symbol, causing it to have a weak
7257definition (
7258`linkonce <https://llvm.org/docs/LangRef.html#linkage-types>`_
7259), allowing the linker to select any definition.
7260
7261For more information see
7262`gcc documentation <https://gcc.gnu.org/onlinedocs/gcc-7.2.0/gcc/Microsoft-Windows-Variable-Attributes.html>`_
7263or `msvc documentation <https://docs.microsoft.com/pl-pl/cpp/cpp/selectany>`_.)reST";
7264
7265static const char AttrDoc_Sentinel[] = R"reST(No documentation.)reST";
7266
7267static const char AttrDoc_SetTypestate[] = R"reST(Annotate methods that transition an object into a new state with
7268``__attribute__((set_typestate(new_state)))``. The new state must be
7269unconsumed, consumed, or unknown.)reST";
7270
7271static const char AttrDoc_SizedBy[] = R"reST(Clang supports the ``counted_by`` attribute on the flexible array member of a
7272structure in C. The argument for the attribute is the name of a field member
7273holding the count of elements in the flexible array. This information can be
7274used to improve the results of the array bound sanitizer and the
7275``__builtin_dynamic_object_size`` builtin. The ``count`` field member must be
7276within the same non-anonymous, enclosing struct as the flexible array member.
7277
7278This example specifies that the flexible array member ``array`` has the number
7279of elements allocated for it in ``count``:
7280
7281.. code-block:: c
7282
7283 struct bar;
7284
7285 struct foo {
7286 size_t count;
7287 char other;
7288 struct bar *array[] __attribute__((counted_by(count)));
7289 };
7290
7291This establishes a relationship between ``array`` and ``count``. Specifically,
7292``array`` must have at least ``count`` number of elements available. It's the
7293user's responsibility to ensure that this relationship is maintained through
7294changes to the structure.
7295
7296In the following example, the allocated array erroneously has fewer elements
7297than what's specified by ``p->count``. This would result in an out-of-bounds
7298access not being detected.
7299
7300.. code-block:: c
7301
7302 #define SIZE_INCR 42
7303
7304 struct foo *p;
7305
7306 void foo_alloc(size_t count) {
7307 p = malloc(MAX(sizeof(struct foo),
7308 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
7309 p->count = count + SIZE_INCR;
7310 }
7311
7312The next example updates ``p->count``, but breaks the relationship requirement
7313that ``p->array`` must have at least ``p->count`` number of elements available:
7314
7315.. code-block:: c
7316
7317 #define SIZE_INCR 42
7318
7319 struct foo *p;
7320
7321 void foo_alloc(size_t count) {
7322 p = malloc(MAX(sizeof(struct foo),
7323 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
7324 p->count = count;
7325 }
7326
7327 void use_foo(int index, int val) {
7328 p->count += SIZE_INCR + 1; /* 'count' is now larger than the number of elements of 'array'. */
7329 p->array[index] = val; /* The sanitizer can't properly check this access. */
7330 }
7331
7332In this example, an update to ``p->count`` maintains the relationship
7333requirement:
7334
7335.. code-block:: c
7336
7337 void use_foo(int index, int val) {
7338 if (p->count == 0)
7339 return;
7340 --p->count;
7341 p->array[index] = val;
7342 })reST";
7343
7344static const char AttrDoc_SizedByOrNull[] = R"reST(Clang supports the ``counted_by`` attribute on the flexible array member of a
7345structure in C. The argument for the attribute is the name of a field member
7346holding the count of elements in the flexible array. This information can be
7347used to improve the results of the array bound sanitizer and the
7348``__builtin_dynamic_object_size`` builtin. The ``count`` field member must be
7349within the same non-anonymous, enclosing struct as the flexible array member.
7350
7351This example specifies that the flexible array member ``array`` has the number
7352of elements allocated for it in ``count``:
7353
7354.. code-block:: c
7355
7356 struct bar;
7357
7358 struct foo {
7359 size_t count;
7360 char other;
7361 struct bar *array[] __attribute__((counted_by(count)));
7362 };
7363
7364This establishes a relationship between ``array`` and ``count``. Specifically,
7365``array`` must have at least ``count`` number of elements available. It's the
7366user's responsibility to ensure that this relationship is maintained through
7367changes to the structure.
7368
7369In the following example, the allocated array erroneously has fewer elements
7370than what's specified by ``p->count``. This would result in an out-of-bounds
7371access not being detected.
7372
7373.. code-block:: c
7374
7375 #define SIZE_INCR 42
7376
7377 struct foo *p;
7378
7379 void foo_alloc(size_t count) {
7380 p = malloc(MAX(sizeof(struct foo),
7381 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
7382 p->count = count + SIZE_INCR;
7383 }
7384
7385The next example updates ``p->count``, but breaks the relationship requirement
7386that ``p->array`` must have at least ``p->count`` number of elements available:
7387
7388.. code-block:: c
7389
7390 #define SIZE_INCR 42
7391
7392 struct foo *p;
7393
7394 void foo_alloc(size_t count) {
7395 p = malloc(MAX(sizeof(struct foo),
7396 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
7397 p->count = count;
7398 }
7399
7400 void use_foo(int index, int val) {
7401 p->count += SIZE_INCR + 1; /* 'count' is now larger than the number of elements of 'array'. */
7402 p->array[index] = val; /* The sanitizer can't properly check this access. */
7403 }
7404
7405In this example, an update to ``p->count`` maintains the relationship
7406requirement:
7407
7408.. code-block:: c
7409
7410 void use_foo(int index, int val) {
7411 if (p->count == 0)
7412 return;
7413 --p->count;
7414 p->array[index] = val;
7415 })reST";
7416
7417static const char AttrDoc_SpeculativeLoadHardening[] = R"reST(This attribute can be applied to a function declaration in order to indicate
7418 that `Speculative Load Hardening <https://llvm.org/docs/SpeculativeLoadHardening.html>`_
7419 should be enabled for the function body. This can also be applied to a method
7420 in Objective C. This attribute will take precedence over the command line flag in
7421 the case where `-mno-speculative-load-hardening <https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mspeculative-load-hardening>`_ is specified.
7422
7423 Speculative Load Hardening is a best-effort mitigation against
7424 information leak attacks that make use of control flow
7425 miss-speculation - specifically miss-speculation of whether a branch
7426 is taken or not. Typically vulnerabilities enabling such attacks are
7427 classified as "Spectre variant #1". Notably, this does not attempt to
7428 mitigate against miss-speculation of branch target, classified as
7429 "Spectre variant #2" vulnerabilities.
7430
7431 When inlining, the attribute is sticky. Inlining a function that
7432 carries this attribute will cause the caller to gain the
7433 attribute. This is intended to provide a maximally conservative model
7434 where the code in a function annotated with this attribute will always
7435 (even after inlining) end up hardened.)reST";
7436
7437static const char AttrDoc_StandaloneDebug[] = R"reST(The ``standalone_debug`` attribute causes debug info to be emitted for a record
7438type regardless of the debug info optimizations that are enabled with
7439-fno-standalone-debug. This attribute only has an effect when debug info
7440optimizations are enabled (e.g. with -fno-standalone-debug), and is C++-only.)reST";
7441
7442static const char AttrDoc_StdCall[] = R"reST(On 32-bit x86 targets, this attribute changes the calling convention of a
7443function to clear parameters off of the stack on return. This convention does
7444not support variadic calls or unprototyped functions in C, and has no effect on
7445x86_64 targets. This calling convention is used widely by the Windows API and
7446COM applications. See the documentation for `__stdcall`_ on MSDN.
7447
7448.. _`__stdcall`: http://msdn.microsoft.com/en-us/library/zxk0tw93.aspx)reST";
7449
7450static const char AttrDoc_StrictFP[] = R"reST()reST";
7451
7452static const char AttrDoc_StrictGuardStackCheck[] = R"reST(Clang supports the Microsoft style ``__declspec((strict_gs_check))`` attribute
7453which upgrades the stack protector check from ``-fstack-protector`` to
7454``-fstack-protector-strong``.
7455
7456For example, it upgrades the stack protector for the function ``foo`` to
7457``-fstack-protector-strong`` but function ``bar`` will still be built with the
7458stack protector with the ``-fstack-protector`` option.
7459
7460.. code-block:: c
7461
7462 __declspec((strict_gs_check))
7463 int foo(int x); // stack protection will be upgraded for foo.
7464
7465 int bar(int y); // bar can be built with the standard stack protector checks.)reST";
7466
7467static const char AttrDoc_Suppress[] = R"reST(The ``suppress`` attribute suppresses unwanted warnings coming from static
7468analysis tools such as the Clang Static Analyzer. The tool will not report
7469any issues in source code annotated with the attribute.
7470
7471The attribute cannot be used to suppress traditional Clang warnings, because
7472many such warnings are emitted before the attribute is fully parsed.
7473Consider using ``#pragma clang diagnostic`` to control such diagnostics,
7474as described in `Controlling Diagnostics via Pragmas
7475<https://clang.llvm.org/docs/UsersManual.html#controlling-diagnostics-via-pragmas>`_.
7476
7477The ``suppress`` attribute can be placed on an individual statement in order to
7478suppress warnings about undesirable behavior occurring at that statement:
7479
7480.. code-block:: c++
7481
7482 int foo() {
7483 int *x = nullptr;
7484 ...
7485 [[clang::suppress]]
7486 return *x; // null pointer dereference warning suppressed here
7487 }
7488
7489Putting the attribute on a compound statement suppresses all warnings in scope:
7490
7491.. code-block:: c++
7492
7493 int foo() {
7494 [[clang::suppress]] {
7495 int *x = nullptr;
7496 ...
7497 return *x; // warnings suppressed in the entire scope
7498 }
7499 }
7500
7501The attribute can also be placed on entire declarations of functions, classes,
7502variables, member variables, and so on, to suppress warnings related
7503to the declarations themselves. When used this way, the attribute additionally
7504suppresses all warnings in the lexical scope of the declaration:
7505
7506.. code-block:: c++
7507
7508 class [[clang::suppress]] C {
7509 int foo() {
7510 int *x = nullptr;
7511 ...
7512 return *x; // warnings suppressed in the entire class scope
7513 }
7514
7515 int bar();
7516 };
7517
7518 int C::bar() {
7519 int *x = nullptr;
7520 ...
7521 return *x; // warning NOT suppressed! - not lexically nested in 'class C{}'
7522 }
7523
7524Some static analysis warnings are accompanied by one or more notes, and the
7525line of code against which the warning is emitted isn't necessarily the best
7526for suppression purposes. In such cases the tools are allowed to implement
7527additional ways to suppress specific warnings based on the attribute attached
7528to a note location.
7529
7530For example, the Clang Static Analyzer suppresses memory leak warnings when
7531the suppression attribute is placed at the allocation site (highlited by
7532a "note: memory is allocated"), which may be different from the line of code
7533at which the program "loses track" of the pointer (where the warning
7534is ultimately emitted):
7535
7536.. code-block:: c
7537
7538 int bar1(bool coin_flip) {
7539 __attribute__((suppress))
7540 int *result = (int *)malloc(sizeof(int));
7541 if (coin_flip)
7542 return 1; // warning about this leak path is suppressed
7543
7544 return *result; // warning about this leak path is also suppressed
7545 }
7546
7547 int bar2(bool coin_flip) {
7548 int *result = (int *)malloc(sizeof(int));
7549 if (coin_flip)
7550 return 1; // leak warning on this path NOT suppressed
7551
7552 __attribute__((suppress))
7553 return *result; // leak warning is suppressed only on this path
7554 }
7555
7556
7557When written as ``[[gsl::suppress]]``, this attribute suppresses specific
7558clang-tidy diagnostics for rules of the `C++ Core Guidelines`_ in a portable
7559way. The attribute can be attached to declarations, statements, and at
7560namespace scope.
7561
7562.. code-block:: c++
7563
7564 [[gsl::suppress("Rh-public")]]
7565 void f_() {
7566 int *p;
7567 [[gsl::suppress("type")]] {
7568 p = reinterpret_cast<int*>(7);
7569 }
7570 }
7571 namespace N {
7572 [[clang::suppress("type", "bounds")]];
7573 ...
7574 }
7575
7576.. _`C++ Core Guidelines`: https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#inforce-enforcement)reST";
7577
7578static const char AttrDoc_SwiftAsync[] = R"reST(The ``swift_async`` attribute specifies if and how a particular function or
7579Objective-C method is imported into a swift async method. For instance:
7580
7581.. code-block:: objc
7582
7583 @interface MyClass : NSObject
7584 -(void)notActuallyAsync:(int)p1 withCompletionHandler:(void (^)())handler
7585 __attribute__((swift_async(none)));
7586
7587 -(void)actuallyAsync:(int)p1 callThisAsync:(void (^)())fun
7588 __attribute__((swift_async(swift_private, 1)));
7589 @end
7590
7591Here, ``notActuallyAsync:withCompletionHandler`` would have been imported as
7592``async`` (because it's last parameter's selector piece is
7593``withCompletionHandler``) if not for the ``swift_async(none)`` attribute.
7594Conversely, ``actuallyAsync:callThisAsync`` wouldn't have been imported as
7595``async`` if not for the ``swift_async`` attribute because it doesn't match the
7596naming convention.
7597
7598When using ``swift_async`` to enable importing, the first argument to the
7599attribute is either ``swift_private`` or ``not_swift_private`` to indicate
7600whether the function/method is private to the current framework, and the second
7601argument is the index of the completion handler parameter.)reST";
7602
7603static const char AttrDoc_SwiftAsyncCall[] = R"reST(The ``swiftasynccall`` attribute indicates that a function is
7604compatible with the low-level conventions of Swift async functions,
7605provided it declares the right formal arguments.
7606
7607In most respects, this is similar to the ``swiftcall`` attribute, except for
7608the following:
7609
7610- A parameter may be marked ``swift_async_context``, ``swift_context``
7611 or ``swift_indirect_result`` (with the same restrictions on parameter
7612 ordering as ``swiftcall``) but the parameter attribute
7613 ``swift_error_result`` is not permitted.
7614
7615- A ``swiftasynccall`` function must have return type ``void``.
7616
7617- Within a ``swiftasynccall`` function, a call to a ``swiftasynccall``
7618 function that is the immediate operand of a ``return`` statement is
7619 guaranteed to be performed as a tail call. This syntax is allowed even
7620 in C as an extension (a call to a void-returning function cannot be a
7621 return operand in standard C). If something in the calling function would
7622 semantically be performed after a guaranteed tail call, such as the
7623 non-trivial destruction of a local variable or temporary,
7624 then the program is ill-formed.
7625
7626Query for this attribute with ``__has_attribute(swiftasynccall)``. Query if
7627the target supports the calling convention with
7628``__has_extension(swiftasynccc)``.)reST";
7629
7630static const char AttrDoc_SwiftAsyncContext[] = R"reST(The ``swift_async_context`` attribute marks a parameter of a ``swiftasynccall``
7631function as having the special asynchronous context-parameter ABI treatment.
7632
7633If the function is not ``swiftasynccall``, this attribute only generates
7634extended frame information.
7635
7636A context parameter must have pointer or reference type.)reST";
7637
7638static const char AttrDoc_SwiftAsyncError[] = R"reST(The ``swift_async_error`` attribute specifies how an error state will be
7639represented in a swift async method. It's a bit analogous to the ``swift_error``
7640attribute for the generated async method. The ``swift_async_error`` attribute
7641can indicate a variety of different ways of representing an error.
7642
7643- ``__attribute__((swift_async_error(zero_argument, N)))``, specifies that the
7644 async method is considered to have failed if the Nth argument to the
7645 completion handler is zero.
7646
7647- ``__attribute__((swift_async_error(nonzero_argument, N)))``, specifies that
7648 the async method is considered to have failed if the Nth argument to the
7649 completion handler is non-zero.
7650
7651- ``__attribute__((swift_async_error(nonnull_error)))``, specifies that the
7652 async method is considered to have failed if the ``NSError *`` argument to the
7653 completion handler is non-null.
7654
7655- ``__attribute__((swift_async_error(none)))``, specifies that the async method
7656 cannot fail.
7657
7658
7659For instance:
7660
7661.. code-block:: objc
7662
7663 @interface MyClass : NSObject
7664 -(void)asyncMethod:(void (^)(char, int, float))handler
7665 __attribute__((swift_async(swift_private, 1)))
7666 __attribute__((swift_async_error(zero_argument, 2)));
7667 @end
7668
7669Here, the ``swift_async`` attribute specifies that ``handler`` is the completion
7670handler for this method, and the ``swift_async_error`` attribute specifies that
7671the ``int`` parameter is the one that represents the error.)reST";
7672
7673static const char AttrDoc_SwiftAsyncName[] = R"reST(The ``swift_async_name`` attribute provides the name of the ``async`` overload for
7674the given declaration in Swift. If this attribute is absent, the name is
7675transformed according to the algorithm built into the Swift compiler.
7676
7677The argument is a string literal that contains the Swift name of the function or
7678method. The name may be a compound Swift name. The function or method with such
7679an attribute must have more than zero parameters, as its last parameter is
7680assumed to be a callback that's eliminated in the Swift ``async`` name.
7681
7682 .. code-block:: objc
7683
7684 @interface URL
7685 + (void) loadContentsFrom:(URL *)url callback:(void (^)(NSData *))data __attribute__((__swift_async_name__("URL.loadContentsFrom(_:)")))
7686 @end)reST";
7687
7688static const char AttrDoc_SwiftAttr[] = R"reST(The ``swift_attr`` provides a Swift-specific annotation for the declaration
7689or type to which the attribute appertains to. It can be used on any declaration
7690or type in Clang. This kind of annotation is ignored by Clang as it doesn't have any
7691semantic meaning in languages supported by Clang. The Swift compiler can
7692interpret these annotations according to its own rules when importing C or
7693Objective-C declarations.)reST";
7694
7695static const char AttrDoc_SwiftBridge[] = R"reST(The ``swift_bridge`` attribute indicates that the declaration to which the
7696attribute appertains is bridged to the named Swift type.
7697
7698 .. code-block:: objc
7699
7700 __attribute__((__objc_root__))
7701 @interface Base
7702 - (instancetype)init;
7703 @end
7704
7705 __attribute__((__swift_bridge__("BridgedI")))
7706 @interface I : Base
7707 @end
7708
7709In this example, the Objective-C interface ``I`` will be made available to Swift
7710with the name ``BridgedI``. It would be possible for the compiler to refer to
7711``I`` still in order to bridge the type back to Objective-C.)reST";
7712
7713static const char AttrDoc_SwiftBridgedTypedef[] = R"reST(The ``swift_bridged_typedef`` attribute indicates that when the typedef to which
7714the attribute appertains is imported into Swift, it should refer to the bridged
7715Swift type (e.g. Swift's ``String``) rather than the Objective-C type as written
7716(e.g. ``NSString``).
7717
7718 .. code-block:: objc
7719
7720 @interface NSString;
7721 typedef NSString *AliasedString __attribute__((__swift_bridged_typedef__));
7722
7723 extern void acceptsAliasedString(AliasedString _Nonnull parameter);
7724
7725In this case, the function ``acceptsAliasedString`` will be imported into Swift
7726as a function which accepts a ``String`` type parameter.)reST";
7727
7728static const char AttrDoc_SwiftCall[] = R"reST(The ``swiftcall`` attribute indicates that a function should be called
7729using the Swift calling convention for a function or function pointer.
7730
7731The lowering for the Swift calling convention, as described by the Swift
7732ABI documentation, occurs in multiple phases. The first, "high-level"
7733phase breaks down the formal parameters and results into innately direct
7734and indirect components, adds implicit parameters for the generic
7735signature, and assigns the context and error ABI treatments to parameters
7736where applicable. The second phase breaks down the direct parameters
7737and results from the first phase and assigns them to registers or the
7738stack. The ``swiftcall`` convention only handles this second phase of
7739lowering; the C function type must accurately reflect the results
7740of the first phase, as follows:
7741
7742- Results classified as indirect by high-level lowering should be
7743 represented as parameters with the ``swift_indirect_result`` attribute.
7744
7745- Results classified as direct by high-level lowering should be represented
7746 as follows:
7747
7748 - First, remove any empty direct results.
7749
7750 - If there are no direct results, the C result type should be ``void``.
7751
7752 - If there is one direct result, the C result type should be a type with
7753 the exact layout of that result type.
7754
7755 - If there are a multiple direct results, the C result type should be
7756 a struct type with the exact layout of a tuple of those results.
7757
7758- Parameters classified as indirect by high-level lowering should be
7759 represented as parameters of pointer type.
7760
7761- Parameters classified as direct by high-level lowering should be
7762 omitted if they are empty types; otherwise, they should be represented
7763 as a parameter type with a layout exactly matching the layout of the
7764 Swift parameter type.
7765
7766- The context parameter, if present, should be represented as a trailing
7767 parameter with the ``swift_context`` attribute.
7768
7769- The error result parameter, if present, should be represented as a
7770 trailing parameter (always following a context parameter) with the
7771 ``swift_error_result`` attribute.
7772
7773``swiftcall`` does not support variadic arguments or unprototyped functions.
7774
7775The parameter ABI treatment attributes are aspects of the function type.
7776A function type which applies an ABI treatment attribute to a
7777parameter is a different type from an otherwise-identical function type
7778that does not. A single parameter may not have multiple ABI treatment
7779attributes.
7780
7781Support for this feature is target-dependent, although it should be
7782supported on every target that Swift supports. Query for this attribute
7783with ``__has_attribute(swiftcall)``. Query if the target supports the
7784calling convention with ``__has_extension(swiftcc)``. This implies
7785support for the ``swift_context``, ``swift_error_result``, and
7786``swift_indirect_result`` attributes.)reST";
7787
7788static const char AttrDoc_SwiftContext[] = R"reST(The ``swift_context`` attribute marks a parameter of a ``swiftcall``
7789or ``swiftasynccall`` function as having the special context-parameter
7790ABI treatment.
7791
7792This treatment generally passes the context value in a special register
7793which is normally callee-preserved.
7794
7795A ``swift_context`` parameter must either be the last parameter or must be
7796followed by a ``swift_error_result`` parameter (which itself must always be
7797the last parameter).
7798
7799A context parameter must have pointer or reference type.)reST";
7800
7801static const char AttrDoc_SwiftError[] = R"reST(The ``swift_error`` attribute controls whether a particular function (or
7802Objective-C method) is imported into Swift as a throwing function, and if so,
7803which dynamic convention it uses.
7804
7805All of these conventions except ``none`` require the function to have an error
7806parameter. Currently, the error parameter is always the last parameter of type
7807``NSError**`` or ``CFErrorRef*``. Swift will remove the error parameter from
7808the imported API. When calling the API, Swift will always pass a valid address
7809initialized to a null pointer.
7810
7811* ``swift_error(none)`` means that the function should not be imported as
7812 throwing. The error parameter and result type will be imported normally.
7813
7814* ``swift_error(null_result)`` means that calls to the function should be
7815 considered to have thrown if they return a null value. The return type must be
7816 a pointer type, and it will be imported into Swift with a non-optional type.
7817 This is the default error convention for Objective-C methods that return
7818 pointers.
7819
7820* ``swift_error(zero_result)`` means that calls to the function should be
7821 considered to have thrown if they return a zero result. The return type must be
7822 an integral type. If the return type would have been imported as ``Bool``, it
7823 is instead imported as ``Void``. This is the default error convention for
7824 Objective-C methods that return a type that would be imported as ``Bool``.
7825
7826* ``swift_error(nonzero_result)`` means that calls to the function should be
7827 considered to have thrown if they return a non-zero result. The return type must
7828 be an integral type. If the return type would have been imported as ``Bool``,
7829 it is instead imported as ``Void``.
7830
7831* ``swift_error(nonnull_error)`` means that calls to the function should be
7832 considered to have thrown if they leave a non-null error in the error parameter.
7833 The return type is left unmodified.)reST";
7834
7835static const char AttrDoc_SwiftErrorResult[] = R"reST(The ``swift_error_result`` attribute marks a parameter of a ``swiftcall``
7836function as having the special error-result ABI treatment.
7837
7838This treatment generally passes the underlying error value in and out of
7839the function through a special register which is normally callee-preserved.
7840This is modeled in C by pretending that the register is addressable memory:
7841
7842- The caller appears to pass the address of a variable of pointer type.
7843 The current value of this variable is copied into the register before
7844 the call; if the call returns normally, the value is copied back into the
7845 variable.
7846
7847- The callee appears to receive the address of a variable. This address
7848 is actually a hidden location in its own stack, initialized with the
7849 value of the register upon entry. When the function returns normally,
7850 the value in that hidden location is written back to the register.
7851
7852A ``swift_error_result`` parameter must be the last parameter, and it must be
7853preceded by a ``swift_context`` parameter.
7854
7855A ``swift_error_result`` parameter must have type ``T**`` or ``T*&`` for some
7856type T. Note that no qualifiers are permitted on the intermediate level.
7857
7858It is undefined behavior if the caller does not pass a pointer or
7859reference to a valid object.
7860
7861The standard convention is that the error value itself (that is, the
7862value stored in the apparent argument) will be null upon function entry,
7863but this is not enforced by the ABI.)reST";
7864
7865static const char AttrDoc_SwiftImportAsNonGeneric[] = R"reST()reST";
7866
7867static const char AttrDoc_SwiftImportPropertyAsAccessors[] = R"reST()reST";
7868
7869static const char AttrDoc_SwiftIndirectResult[] = R"reST(The ``swift_indirect_result`` attribute marks a parameter of a ``swiftcall``
7870or ``swiftasynccall`` function as having the special indirect-result ABI
7871treatment.
7872
7873This treatment gives the parameter the target's normal indirect-result
7874ABI treatment, which may involve passing it differently from an ordinary
7875parameter. However, only the first indirect result will receive this
7876treatment. Furthermore, low-level lowering may decide that a direct result
7877must be returned indirectly; if so, this will take priority over the
7878``swift_indirect_result`` parameters.
7879
7880A ``swift_indirect_result`` parameter must either be the first parameter or
7881follow another ``swift_indirect_result`` parameter.
7882
7883A ``swift_indirect_result`` parameter must have type ``T*`` or ``T&`` for
7884some object type ``T``. If ``T`` is a complete type at the point of
7885definition of a function, it is undefined behavior if the argument
7886value does not point to storage of adequate size and alignment for a
7887value of type ``T``.
7888
7889Making indirect results explicit in the signature allows C functions to
7890directly construct objects into them without relying on language
7891optimizations like C++'s named return value optimization (NRVO).)reST";
7892
7893static const char AttrDoc_SwiftName[] = R"reST(The ``swift_name`` attribute provides the name of the declaration in Swift. If
7894this attribute is absent, the name is transformed according to the algorithm
7895built into the Swift compiler.
7896
7897The argument is a string literal that contains the Swift name of the function,
7898variable, or type. When renaming a function, the name may be a compound Swift
7899name. For a type, enum constant, property, or variable declaration, the name
7900must be a simple or qualified identifier.
7901
7902 .. code-block:: objc
7903
7904 @interface URL
7905 - (void) initWithString:(NSString *)s __attribute__((__swift_name__("URL.init(_:)")))
7906 @end
7907
7908 void __attribute__((__swift_name__("squareRoot()"))) sqrt(double v) {
7909 })reST";
7910
7911static const char AttrDoc_SwiftNewType[] = R"reST(The ``swift_newtype`` attribute indicates that the typedef to which the
7912attribute appertains is imported as a new Swift type of the typedef's name.
7913Previously, the attribute was spelt ``swift_wrapper``. While the behaviour of
7914the attribute is identical with either spelling, ``swift_wrapper`` is
7915deprecated, only exists for compatibility purposes, and should not be used in
7916new code.
7917
7918* ``swift_newtype(struct)`` means that a Swift struct will be created for this
7919 typedef.
7920
7921* ``swift_newtype(enum)`` means that a Swift enum will be created for this
7922 typedef.
7923
7924 .. code-block:: c
7925
7926 // Import UIFontTextStyle as an enum type, with enumerated values being
7927 // constants.
7928 typedef NSString * UIFontTextStyle __attribute__((__swift_newtype__(enum)));
7929
7930 // Import UIFontDescriptorFeatureKey as a structure type, with enumerated
7931 // values being members of the type structure.
7932 typedef NSString * UIFontDescriptorFeatureKey __attribute__((__swift_newtype__(struct)));)reST";
7933
7934static const char AttrDoc_SwiftObjCMembers[] = R"reST(This attribute indicates that Swift subclasses and members of Swift extensions
7935of this class will be implicitly marked with the ``@objcMembers`` Swift
7936attribute, exposing them back to Objective-C.)reST";
7937
7938static const char AttrDoc_SwiftPrivate[] = R"reST(Declarations marked with the ``swift_private`` attribute are hidden from the
7939framework client but are still made available for use within the framework or
7940Swift SDK overlay.
7941
7942The purpose of this attribute is to permit a more idomatic implementation of
7943declarations in Swift while hiding the non-idiomatic one.)reST";
7944
7945static const char AttrDoc_SwiftVersionedAddition[] = R"reST()reST";
7946
7947static const char AttrDoc_SwiftVersionedRemoval[] = R"reST()reST";
7948
7949static const char AttrDoc_SysVABI[] = R"reST(On Windows x86_64 targets, this attribute changes the calling convention of a
7950function to match the default convention used on Sys V targets such as Linux,
7951Mac, and BSD. This attribute has no effect on other targets.)reST";
7952
7953static const char AttrDoc_TLSModel[] = R"reST(The ``tls_model`` attribute allows you to specify which thread-local storage
7954model to use. It accepts the following strings:
7955
7956* global-dynamic
7957* local-dynamic
7958* initial-exec
7959* local-exec
7960
7961TLS models are mutually exclusive.)reST";
7962
7963static const char AttrDoc_Target[] = R"reST(Clang supports the GNU style ``__attribute__((target("OPTIONS")))`` attribute.
7964This attribute may be attached to a function definition and instructs
7965the backend to use different code generation options than were passed on the
7966command line.
7967
7968The current set of options correspond to the existing "subtarget features" for
7969the target with or without a "-mno-" in front corresponding to the absence
7970of the feature, as well as ``arch="CPU"`` which will change the default "CPU"
7971for the function.
7972
7973For X86, the attribute also allows ``tune="CPU"`` to optimize the generated
7974code for the given CPU without changing the available instructions.
7975
7976For AArch64, ``arch="Arch"`` will set the architecture, similar to the -march
7977command line options. ``cpu="CPU"`` can be used to select a specific cpu,
7978as per the ``-mcpu`` option, similarly for ``tune=``. The attribute also allows the
7979"branch-protection=<args>" option, where the permissible arguments and their
7980effect on code generation are the same as for the command-line option
7981``-mbranch-protection``.
7982
7983Example "subtarget features" from the x86 backend include: "mmx", "sse", "sse4.2",
7984"avx", "xop" and largely correspond to the machine specific options handled by
7985the front end.
7986
7987Note that this attribute does not apply transitively to nested functions such
7988as blocks or C++ lambdas.
7989
7990Additionally, this attribute supports function multiversioning for ELF based
7991x86/x86-64 targets, which can be used to create multiple implementations of the
7992same function that will be resolved at runtime based on the priority of their
7993``target`` attribute strings. A function is considered a multiversioned function
7994if either two declarations of the function have different ``target`` attribute
7995strings, or if it has a ``target`` attribute string of ``default``. For
7996example:
7997
7998 .. code-block:: c++
7999
8000 __attribute__((target("arch=atom")))
8001 void foo() {} // will be called on 'atom' processors.
8002 __attribute__((target("default")))
8003 void foo() {} // will be called on any other processors.
8004
8005All multiversioned functions must contain a ``default`` (fallback)
8006implementation, otherwise usages of the function are considered invalid.
8007Additionally, a function may not become multiversioned after its first use.)reST";
8008
8009static const char AttrDoc_TargetClones[] = R"reST(Clang supports the ``target_clones("OPTIONS")`` attribute. This attribute may be
8010attached to a function declaration and causes function multiversioning, where
8011multiple versions of the function will be emitted with different code
8012generation options. Additionally, these versions will be resolved at runtime
8013based on the priority of their attribute options. All ``target_clone`` functions
8014are considered multiversioned functions.
8015
8016For AArch64 target:
8017The attribute contains comma-separated strings of target features joined by "+"
8018sign. For example:
8019
8020 .. code-block:: c++
8021
8022 __attribute__((target_clones("sha2+memtag", "fcma+sve2-pmull128")))
8023 void foo() {}
8024
8025For every multiversioned function a ``default`` (fallback) implementation
8026always generated if not specified directly.
8027
8028For x86/x86-64 targets:
8029All multiversioned functions must contain a ``default`` (fallback)
8030implementation, otherwise usages of the function are considered invalid.
8031Additionally, a function may not become multiversioned after its first use.
8032
8033The options to ``target_clones`` can either be a target-specific architecture
8034(specified as ``arch=CPU``), or one of a list of subtarget features.
8035
8036Example "subtarget features" from the x86 backend include: "mmx", "sse", "sse4.2",
8037"avx", "xop" and largely correspond to the machine specific options handled by
8038the front end.
8039
8040The versions can either be listed as a comma-separated sequence of string
8041literals or as a single string literal containing a comma-separated list of
8042versions. For compatibility with GCC, the two formats can be mixed. For
8043example, the following will emit 4 versions of the function:
8044
8045 .. code-block:: c++
8046
8047 __attribute__((target_clones("arch=atom,avx2","arch=ivybridge","default")))
8048 void foo() {}
8049
8050For targets that support the GNU indirect function (IFUNC) feature, dispatch
8051is performed by emitting an indirect function that is resolved to the appropriate
8052target clone at load time. The indirect function is given the name the
8053multiversioned function would have if it had been declared without the attribute.
8054For backward compatibility with earlier Clang releases, a function alias with an
8055``.ifunc`` suffix is also emitted. The ``.ifunc`` suffixed symbol is a deprecated
8056feature and support for it may be removed in the future.)reST";
8057
8058static const char AttrDoc_TargetVersion[] = R"reST(For AArch64 target clang supports function multiversioning by
8059``__attribute__((target_version("OPTIONS")))`` attribute. When applied to a
8060function it instructs compiler to emit multiple function versions based on
8061``target_version`` attribute strings, which resolved at runtime depend on their
8062priority and target features availability. One of the versions is always
8063( implicitly or explicitly ) the ``default`` (fallback). Attribute strings can
8064contain dependent features names joined by the "+" sign.
8065
8066For targets that support the GNU indirect function (IFUNC) feature, dispatch
8067is performed by emitting an indirect function that is resolved to the appropriate
8068target clone at load time. The indirect function is given the name the
8069multiversioned function would have if it had been declared without the attribute.
8070For backward compatibility with earlier Clang releases, a function alias with an
8071``.ifunc`` suffix is also emitted. The ``.ifunc`` suffixed symbol is a deprecated
8072feature and support for it may be removed in the future.)reST";
8073
8074static const char AttrDoc_TestTypestate[] = R"reST(Use ``__attribute__((test_typestate(tested_state)))`` to indicate that a method
8075returns true if the object is in the specified state..)reST";
8076
8077static const char AttrDoc_ThisCall[] = R"reST(On 32-bit x86 targets, this attribute changes the calling convention of a
8078function to use ECX for the first parameter (typically the implicit ``this``
8079parameter of C++ methods) and clear parameters off of the stack on return. This
8080convention does not support variadic calls or unprototyped functions in C, and
8081has no effect on x86_64 targets. See the documentation for `__thiscall`_ on
8082MSDN.
8083
8084.. _`__thiscall`: http://msdn.microsoft.com/en-us/library/ek8tkfbw.aspx)reST";
8085
8086static const char AttrDoc_Thread[] = R"reST(The ``__declspec(thread)`` attribute declares a variable with thread local
8087storage. It is available under the ``-fms-extensions`` flag for MSVC
8088compatibility. See the documentation for `__declspec(thread)`_ on MSDN.
8089
8090.. _`__declspec(thread)`: http://msdn.microsoft.com/en-us/library/9w1sdazb.aspx
8091
8092In Clang, ``__declspec(thread)`` is generally equivalent in functionality to the
8093GNU ``__thread`` keyword. The variable must not have a destructor and must have
8094a constant initializer, if any. The attribute only applies to variables
8095declared with static storage duration, such as globals, class static data
8096members, and static locals.)reST";
8097
8098static const char AttrDoc_TransparentUnion[] = R"reST(This attribute can be applied to a union to change the behavior of calls to
8099functions that have an argument with a transparent union type. The compiler
8100behavior is changed in the following manner:
8101
8102- A value whose type is any member of the transparent union can be passed as an
8103 argument without the need to cast that value.
8104
8105- The argument is passed to the function using the calling convention of the
8106 first member of the transparent union. Consequently, all the members of the
8107 transparent union should have the same calling convention as its first member.
8108
8109Transparent unions are not supported in C++.)reST";
8110
8111static const char AttrDoc_TrivialABI[] = R"reST(The ``trivial_abi`` attribute can be applied to a C++ class, struct, or union.
8112It instructs the compiler to pass and return the type using the C ABI for the
8113underlying type when the type would otherwise be considered non-trivial for the
8114purpose of calls.
8115A class annotated with ``trivial_abi`` can have non-trivial destructors or
8116copy/move constructors without automatically becoming non-trivial for the
8117purposes of calls. For example:
8118
8119 .. code-block:: c++
8120
8121 // A is trivial for the purposes of calls because ``trivial_abi`` makes the
8122 // user-provided special functions trivial.
8123 struct __attribute__((trivial_abi)) A {
8124 ~A();
8125 A(const A &);
8126 A(A &&);
8127 int x;
8128 };
8129
8130 // B's destructor and copy/move constructor are considered trivial for the
8131 // purpose of calls because A is trivial.
8132 struct B {
8133 A a;
8134 };
8135
8136If a type is trivial for the purposes of calls, has a non-trivial destructor,
8137and is passed as an argument by value, the convention is that the callee will
8138destroy the object before returning. The lifetime of the copy of the parameter
8139in the caller ends without a destructor call when the call begins.
8140
8141If a type is trivial for the purpose of calls, it is assumed to be trivially
8142relocatable for the purpose of ``__is_trivially_relocatable`` and
8143``__builtin_is_cpp_trivially_relocatable``.
8144When a type marked with ``[[trivial_abi]]`` is used as a function argument,
8145the compiler may omit the call to the copy constructor.
8146Thus, side effects of the copy constructor are potentially not performed.
8147For example, objects that contain pointers to themselves or otherwise depend
8148on their address (or the address or their subobjects) should not be declared
8149``[[trivial_abi]]``.
8150
8151Attribute ``trivial_abi`` has no effect in the following cases:
8152
8153- The class directly declares a virtual base or virtual methods.
8154- Copy constructors and move constructors of the class are all deleted.
8155- The class has a base class that is non-trivial for the purposes of calls.
8156- The class has a non-static data member whose type is non-trivial for the
8157 purposes of calls, which includes:
8158
8159 - classes that are non-trivial for the purposes of calls
8160 - __weak-qualified types in Objective-C++
8161 - arrays of any of the above)reST";
8162
8163static const char AttrDoc_TriviallyRelocatable[] = R"reST()reST";
8164
8165static const char AttrDoc_TryAcquireCapability[] = R"reST(Marks a function that attempts to acquire a capability. This function may fail to
8166actually acquire the capability; they accept a Boolean value determining
8167whether acquiring the capability means success (true), or failing to acquire
8168the capability means success (false).)reST";
8169
8170static const char AttrDoc_TypeNonNull[] = R"reST(The ``_Nonnull`` nullability qualifier indicates that null is not a meaningful
8171value for a value of the ``_Nonnull`` pointer type. For example, given a
8172declaration such as:
8173
8174 .. code-block:: c
8175
8176 int fetch(int * _Nonnull ptr);
8177
8178a caller of ``fetch`` should not provide a null value, and the compiler will
8179produce a warning if it sees a literal null value passed to ``fetch``. Note
8180that, unlike the declaration attribute ``nonnull``, the presence of
8181``_Nonnull`` does not imply that passing null is undefined behavior: ``fetch``
8182is free to consider null undefined behavior or (perhaps for
8183backward-compatibility reasons) defensively handle null.)reST";
8184
8185static const char AttrDoc_TypeNullUnspecified[] = R"reST(The ``_Null_unspecified`` nullability qualifier indicates that neither the
8186``_Nonnull`` nor ``_Nullable`` qualifiers make sense for a particular pointer
8187type. It is used primarily to indicate that the role of null with specific
8188pointers in a nullability-annotated header is unclear, e.g., due to
8189overly-complex implementations or historical factors with a long-lived API.)reST";
8190
8191static const char AttrDoc_TypeNullable[] = R"reST(The ``_Nullable`` nullability qualifier indicates that a value of the
8192``_Nullable`` pointer type can be null. For example, given:
8193
8194 .. code-block:: c
8195
8196 int fetch_or_zero(int * _Nullable ptr);
8197
8198a caller of ``fetch_or_zero`` can provide null.
8199
8200The ``_Nullable`` attribute on classes indicates that the given class can
8201represent null values, and so the ``_Nullable``, ``_Nonnull`` etc qualifiers
8202make sense for this type. For example:
8203
8204 .. code-block:: c
8205
8206 class _Nullable ArenaPointer { ... };
8207
8208 ArenaPointer _Nonnull x = ...;
8209 ArenaPointer _Nullable y = nullptr;)reST";
8210
8211static const char AttrDoc_TypeNullableResult[] = R"reST(The ``_Nullable_result`` nullability qualifier means that a value of the
8212``_Nullable_result`` pointer can be ``nil``, just like ``_Nullable``. Where this
8213attribute differs from ``_Nullable`` is when it's used on a parameter to a
8214completion handler in a Swift async method. For instance, here:
8215
8216 .. code-block:: objc
8217
8218 -(void)fetchSomeDataWithID:(int)identifier
8219 completionHandler:(void (^)(Data *_Nullable_result result, NSError *error))completionHandler;
8220
8221This method asynchronously calls ``completionHandler`` when the data is
8222available, or calls it with an error. ``_Nullable_result`` indicates to the
8223Swift importer that this is the uncommon case where ``result`` can get ``nil``
8224even if no error has occurred, and will therefore import it as a Swift optional
8225type. Otherwise, if ``result`` was annotated with ``_Nullable``, the Swift
8226importer will assume that ``result`` will always be non-nil unless an error
8227occurred.)reST";
8228
8229static const char AttrDoc_TypeTagForDatatype[] = R"reST(When declaring a variable, use
8230``__attribute__((type_tag_for_datatype(kind, type)))`` to create a type tag that
8231is tied to the ``type`` argument given to the attribute.
8232
8233In the attribute prototype above:
8234 * ``kind`` is an identifier that should be used when annotating all applicable
8235 type tags.
8236 * ``type`` indicates the name of the type.
8237
8238Clang supports annotating type tags of two forms.
8239
8240 * **Type tag that is a reference to a declared identifier.**
8241 Use ``__attribute__((type_tag_for_datatype(kind, type)))`` when declaring that
8242 identifier:
8243
8244 .. code-block:: c++
8245
8246 typedef int MPI_Datatype;
8247 extern struct mpi_datatype mpi_datatype_int
8248 __attribute__(( type_tag_for_datatype(mpi,int) ));
8249 #define MPI_INT ((MPI_Datatype) &mpi_datatype_int)
8250 // &mpi_datatype_int is a type tag. It is tied to type "int".
8251
8252 * **Type tag that is an integral literal.**
8253 Declare a ``static const`` variable with an initializer value and attach
8254 ``__attribute__((type_tag_for_datatype(kind, type)))`` on that declaration:
8255
8256 .. code-block:: c++
8257
8258 typedef int MPI_Datatype;
8259 static const MPI_Datatype mpi_datatype_int
8260 __attribute__(( type_tag_for_datatype(mpi,int) )) = 42;
8261 #define MPI_INT ((MPI_Datatype) 42)
8262 // The number 42 is a type tag. It is tied to type "int".
8263
8264
8265The ``type_tag_for_datatype`` attribute also accepts an optional third argument
8266that determines how the type of the function argument specified by either
8267``arg_idx`` or ``ptr_idx`` is compared against the type associated with the type
8268tag. (Recall that for the ``argument_with_type_tag`` attribute, the type of the
8269function argument specified by ``arg_idx`` is compared against the type
8270associated with the type tag. Also recall that for the ``pointer_with_type_tag``
8271attribute, the pointee type of the function argument specified by ``ptr_idx`` is
8272compared against the type associated with the type tag.) There are two supported
8273values for this optional third argument:
8274
8275 * ``layout_compatible`` will cause types to be compared according to
8276 layout-compatibility rules (In C++11 [class.mem] p 17, 18, see the
8277 layout-compatibility rules for two standard-layout struct types and for two
8278 standard-layout union types). This is useful when creating a type tag
8279 associated with a struct or union type. For example:
8280
8281 .. code-block:: c++
8282
8283 /* In mpi.h */
8284 typedef int MPI_Datatype;
8285 struct internal_mpi_double_int { double d; int i; };
8286 extern struct mpi_datatype mpi_datatype_double_int
8287 __attribute__(( type_tag_for_datatype(mpi,
8288 struct internal_mpi_double_int, layout_compatible) ));
8289
8290 #define MPI_DOUBLE_INT ((MPI_Datatype) &mpi_datatype_double_int)
8291
8292 int MPI_Send(void *buf, int count, MPI_Datatype datatype, ...)
8293 __attribute__(( pointer_with_type_tag(mpi,1,3) ));
8294
8295 /* In user code */
8296 struct my_pair { double a; int b; };
8297 struct my_pair *buffer;
8298 MPI_Send(buffer, 1, MPI_DOUBLE_INT /*, ... */); // no warning because the
8299 // layout of my_pair is
8300 // compatible with that of
8301 // internal_mpi_double_int
8302
8303 struct my_int_pair { int a; int b; }
8304 struct my_int_pair *buffer2;
8305 MPI_Send(buffer2, 1, MPI_DOUBLE_INT /*, ... */); // warning because the
8306 // layout of my_int_pair
8307 // does not match that of
8308 // internal_mpi_double_int
8309
8310 * ``must_be_null`` specifies that the function argument specified by either
8311 ``arg_idx`` (for the ``argument_with_type_tag`` attribute) or ``ptr_idx`` (for
8312 the ``pointer_with_type_tag`` attribute) should be a null pointer constant.
8313 The second argument to the ``type_tag_for_datatype`` attribute is ignored. For
8314 example:
8315
8316 .. code-block:: c++
8317
8318 /* In mpi.h */
8319 typedef int MPI_Datatype;
8320 extern struct mpi_datatype mpi_datatype_null
8321 __attribute__(( type_tag_for_datatype(mpi, void, must_be_null) ));
8322
8323 #define MPI_DATATYPE_NULL ((MPI_Datatype) &mpi_datatype_null)
8324 int MPI_Send(void *buf, int count, MPI_Datatype datatype, ...)
8325 __attribute__(( pointer_with_type_tag(mpi,1,3) ));
8326
8327 /* In user code */
8328 struct my_pair { double a; int b; };
8329 struct my_pair *buffer;
8330 MPI_Send(buffer, 1, MPI_DATATYPE_NULL /*, ... */); // warning: MPI_DATATYPE_NULL
8331 // was specified but buffer
8332 // is not a null pointer)reST";
8333
8334static const char AttrDoc_TypeVisibility[] = R"reST(The ``type_visibility`` attribute allows the visibility of a type and its vague
8335linkage objects (vtable, typeinfo, typeinfo name) to be controlled separately from
8336the visibility of functions and data members of the type.
8337
8338For example, this can be used to give default visibility to the typeinfo and the vtable
8339of a type while still keeping hidden visibility on its member functions and static data
8340members.
8341
8342This attribute can only be applied to types and namespaces.
8343
8344If both ``visibility`` and ``type_visibility`` are applied to a type or a namespace, the
8345visibility specified with the ``type_visibility`` attribute overrides the visibility
8346provided with the regular ``visibility`` attribute.)reST";
8347
8348static const char AttrDoc_UPtr[] = R"reST(The ``__uptr`` qualifier specifies that a 32-bit pointer should be zero
8349extended when converted to a 64-bit pointer.)reST";
8350
8351static const char AttrDoc_Unavailable[] = R"reST(No documentation.)reST";
8352
8353static const char AttrDoc_Uninitialized[] = R"reST(The command-line parameter ``-ftrivial-auto-var-init=*`` can be used to
8354initialize trivial automatic stack variables. By default, trivial automatic
8355stack variables are uninitialized. This attribute is used to override the
8356command-line parameter, forcing variables to remain uninitialized. It has no
8357semantic meaning in that using uninitialized values is undefined behavior,
8358it rather documents the programmer's intent.)reST";
8359
8360static const char AttrDoc_Unlikely[] = R"reST(The ``likely`` and ``unlikely`` attributes are used as compiler hints.
8361The attributes are used to aid the compiler to determine which branch is
8362likely or unlikely to be taken. This is done by marking the branch substatement
8363with one of the two attributes.
8364
8365It isn't allowed to annotate a single statement with both ``likely`` and
8366``unlikely``. Annotating the ``true`` and ``false`` branch of an ``if``
8367statement with the same likelihood attribute will result in a diagnostic and
8368the attributes are ignored on both branches.
8369
8370In a ``switch`` statement it's allowed to annotate multiple ``case`` labels
8371or the ``default`` label with the same likelihood attribute. This makes
8372* all labels without an attribute have a neutral likelihood,
8373* all labels marked ``[[likely]]`` have an equally positive likelihood, and
8374* all labels marked ``[[unlikely]]`` have an equally negative likelihood.
8375The neutral likelihood is the more likely of path execution than the negative
8376likelihood. The positive likelihood is the more likely of path of execution
8377than the neutral likelihood.
8378
8379These attributes have no effect on the generated code when using
8380PGO (Profile-Guided Optimization) or at optimization level 0.
8381
8382In Clang, the attributes will be ignored if they're not placed on
8383* the ``case`` or ``default`` label of a ``switch`` statement,
8384* or on the substatement of an ``if`` or ``else`` statement,
8385* or on the substatement of an ``for`` or ``while`` statement.
8386The C++ Standard recommends to honor them on every statement in the
8387path of execution, but that can be confusing:
8388
8389.. code-block:: c++
8390
8391 if (b) {
8392 [[unlikely]] --b; // In the path of execution,
8393 // this branch is considered unlikely.
8394 }
8395
8396 if (b) {
8397 --b;
8398 if(b)
8399 return;
8400 [[unlikely]] --b; // Not in the path of execution,
8401 } // the branch has no likelihood information.
8402
8403 if (b) {
8404 --b;
8405 foo(b);
8406 // Whether or not the next statement is in the path of execution depends
8407 // on the declaration of foo():
8408 // In the path of execution: void foo(int);
8409 // Not in the path of execution: [[noreturn]] void foo(int);
8410 // This means the likelihood of the branch depends on the declaration
8411 // of foo().
8412 [[unlikely]] --b;
8413 }
8414
8415
8416Below are some example usages of the likelihood attributes and their effects:
8417
8418.. code-block:: c++
8419
8420 if (b) [[likely]] { // Placement on the first statement in the branch.
8421 // The compiler will optimize to execute the code here.
8422 } else {
8423 }
8424
8425 if (b)
8426 [[unlikely]] b++; // Placement on the first statement in the branch.
8427 else {
8428 // The compiler will optimize to execute the code here.
8429 }
8430
8431 if (b) {
8432 [[unlikely]] b++; // Placement on the second statement in the branch.
8433 } // The attribute will be ignored.
8434
8435 if (b) [[likely]] {
8436 [[unlikely]] b++; // No contradiction since the second attribute
8437 } // is ignored.
8438
8439 if (b)
8440 ;
8441 else [[likely]] {
8442 // The compiler will optimize to execute the code here.
8443 }
8444
8445 if (b)
8446 ;
8447 else
8448 // The compiler will optimize to execute the next statement.
8449 [[likely]] b = f();
8450
8451 if (b) [[likely]]; // Both branches are likely. A diagnostic is issued
8452 else [[likely]]; // and the attributes are ignored.
8453
8454 if (b)
8455 [[likely]] int i = 5; // Issues a diagnostic since the attribute
8456 // isn't allowed on a declaration.
8457
8458 switch (i) {
8459 [[likely]] case 1: // This value is likely
8460 ...
8461 break;
8462
8463 [[unlikely]] case 2: // This value is unlikely
8464 ...
8465 [[fallthrough]];
8466
8467 case 3: // No likelihood attribute
8468 ...
8469 [[likely]] break; // No effect
8470
8471 case 4: [[likely]] { // attribute on substatement has no effect
8472 ...
8473 break;
8474 }
8475
8476 [[unlikely]] default: // All other values are unlikely
8477 ...
8478 break;
8479 }
8480
8481 switch (i) {
8482 [[likely]] case 0: // This value and code path is likely
8483 ...
8484 [[fallthrough]];
8485
8486 case 1: // No likelihood attribute, code path is neutral
8487 break; // falling through has no effect on the likelihood
8488
8489 case 2: // No likelihood attribute, code path is neutral
8490 [[fallthrough]];
8491
8492 [[unlikely]] default: // This value and code path are both unlikely
8493 break;
8494 }
8495
8496 for(int i = 0; i != size; ++i) [[likely]] {
8497 ... // The loop is the likely path of execution
8498 }
8499
8500 for(const auto &E : Elements) [[likely]] {
8501 ... // The loop is the likely path of execution
8502 }
8503
8504 while(i != size) [[unlikely]] {
8505 ... // The loop is the unlikely path of execution
8506 } // The generated code will optimize to skip the loop body
8507
8508 while(true) [[unlikely]] {
8509 ... // The attribute has no effect
8510 } // Clang elides the comparison and generates an infinite
8511 // loop)reST";
8512
8513static const char AttrDoc_UnsafeBufferUsage[] = R"reST(The attribute ``[[clang::unsafe_buffer_usage]]`` should be placed on functions
8514that need to be avoided as they are prone to buffer overflows or unsafe buffer
8515struct fields. It is designed to work together with the off-by-default compiler
8516warning ``-Wunsafe-buffer-usage`` to help codebases transition away from raw pointer
8517based buffer management, in favor of safer abstractions such as C++20 ``std::span``.
8518The attribute causes ``-Wunsafe-buffer-usage`` to warn on every use of the function or
8519the field it is attached to, and it may also lead to emission of automatic fix-it
8520hints which would help the user replace the use of unsafe functions(/fields) with safe
8521alternatives, though the attribute can be used even when the fix can't be automated.
8522
8523* Attribute attached to functions: The attribute suppresses all
8524 ``-Wunsafe-buffer-usage`` warnings within the function it is attached to, as the
8525 function is now classified as unsafe. The attribute should be used carefully, as it
8526 will silence all unsafe operation warnings inside the function; including any new
8527 unsafe operations introduced in the future.
8528
8529 The attribute is warranted even if the only way a function can overflow
8530 the buffer is by violating the function's preconditions. For example, it
8531 would make sense to put the attribute on function ``foo()`` below because
8532 passing an incorrect size parameter would cause a buffer overflow:
8533
8534 .. code-block:: c++
8535
8536 [[clang::unsafe_buffer_usage]]
8537 void foo(int *buf, size_t size) {
8538 for (size_t i = 0; i < size; ++i) {
8539 buf[i] = i;
8540 }
8541 }
8542
8543 The attribute is NOT warranted when the function uses safe abstractions,
8544 assuming that these abstractions weren't misused outside the function.
8545 For example, function ``bar()`` below doesn't need the attribute,
8546 because assuming that the container ``buf`` is well-formed (has size that
8547 fits the original buffer it refers to), overflow cannot occur:
8548
8549 .. code-block:: c++
8550
8551 void bar(std::span<int> buf) {
8552 for (size_t i = 0; i < buf.size(); ++i) {
8553 buf[i] = i;
8554 }
8555 }
8556
8557 In this case function ``bar()`` enables the user to keep the buffer
8558 "containerized" in a span for as long as possible. On the other hand,
8559 Function ``foo()`` in the previous example may have internal
8560 consistency, but by accepting a raw buffer it requires the user to unwrap
8561 their span, which is undesirable according to the programming model
8562 behind ``-Wunsafe-buffer-usage``.
8563
8564 The attribute is warranted when a function accepts a raw buffer only to
8565 immediately put it into a span:
8566
8567 .. code-block:: c++
8568
8569 [[clang::unsafe_buffer_usage]]
8570 void baz(int *buf, size_t size) {
8571 std::span<int> sp{ buf, size };
8572 for (size_t i = 0; i < sp.size(); ++i) {
8573 sp[i] = i;
8574 }
8575 }
8576
8577 In this case ``baz()`` does not contain any unsafe operations, but the awkward
8578 parameter type causes the caller to unwrap the span unnecessarily.
8579 Note that regardless of the attribute, code inside ``baz()`` isn't flagged
8580 by ``-Wunsafe-buffer-usage`` as unsafe. It is definitely undesirable,
8581 but if ``baz()`` is on an API surface, there is no way to improve it
8582 to make it as safe as ``bar()`` without breaking the source and binary
8583 compatibility with existing users of the function. In such cases
8584 the proper solution would be to create a different function (possibly
8585 an overload of ``baz()``) that accepts a safe container like ``bar()``,
8586 and then use the attribute on the original ``baz()`` to help the users
8587 update their code to use the new function.
8588
8589* Attribute attached to fields: The attribute should only be attached to
8590 struct fields, if the fields can not be updated to a safe type with bounds
8591 check, such as std::span. In other words, the buffers prone to unsafe accesses
8592 should always be updated to use safe containers/views and attaching the attribute
8593 must be last resort when such an update is infeasible.
8594
8595 The attribute can be placed on individual fields or a set of them as shown below.
8596
8597 .. code-block:: c++
8598
8599 struct A {
8600 [[clang::unsafe_buffer_usage]]
8601 int *ptr1;
8602
8603 [[clang::unsafe_buffer_usage]]
8604 int *ptr2, buf[10];
8605
8606 [[clang::unsafe_buffer_usage]]
8607 size_t sz;
8608 };
8609
8610 Here, every read/write to the fields ptr1, ptr2, buf and sz will trigger a warning
8611 that the field has been explcitly marked as unsafe due to unsafe-buffer operations.)reST";
8612
8613static const char AttrDoc_Unused[] = R"reST(When passing the ``-Wunused`` flag to Clang, entities that are unused by the
8614program may be diagnosed. The ``[[maybe_unused]]`` (or
8615``__attribute__((unused))``) attribute can be used to silence such diagnostics
8616when the entity cannot be removed. For instance, a local variable may exist
8617solely for use in an ``assert()`` statement, which makes the local variable
8618unused when ``NDEBUG`` is defined.
8619
8620The attribute may be applied to the declaration of a class, a typedef, a
8621variable, a function or method, a function parameter, an enumeration, an
8622enumerator, a non-static data member, or a label.
8623
8624.. code-block:: c++
8625
8626 #include <cassert>
8627
8628 [[maybe_unused]] void f([[maybe_unused]] bool thing1,
8629 [[maybe_unused]] bool thing2) {
8630 [[maybe_unused]] bool b = thing1 && thing2;
8631 assert(b);
8632 })reST";
8633
8634static const char AttrDoc_UseHandle[] = R"reST(A function taking a handle by value might close the handle. If a function
8635parameter is annotated with ``use_handle(tag)`` it is assumed to not to change
8636the state of the handle. It is also assumed to require an open handle to work with.
8637The attribute requires a string literal argument to identify the handle being used.
8638
8639.. code-block:: c++
8640
8641 zx_status_t zx_port_wait(zx_handle_t handle [[clang::use_handle("zircon")]],
8642 zx_time_t deadline,
8643 zx_port_packet_t* packet);)reST";
8644
8645static const char AttrDoc_Used[] = R"reST(This attribute, when attached to a function or variable definition, indicates
8646that there may be references to the entity which are not apparent in the source
8647code. For example, it may be referenced from inline ``asm``, or it may be
8648found through a dynamic symbol or section lookup.
8649
8650The compiler must emit the definition even if it appears to be unused, and it
8651must not apply optimizations which depend on fully understanding how the entity
8652is used.
8653
8654Whether this attribute has any effect on the linker depends on the target and
8655the linker. Most linkers support the feature of section garbage collection
8656(``--gc-sections``), also known as "dead stripping" (``ld64 -dead_strip``) or
8657discarding unreferenced sections (``link.exe /OPT:REF``). On COFF and Mach-O
8658targets (Windows and Apple platforms), the `used` attribute prevents symbols
8659from being removed by linker section GC. On ELF targets, it has no effect on its
8660own, and the linker may remove the definition if it is not otherwise referenced.
8661This linker GC can be avoided by also adding the ``retain`` attribute. Note
8662that ``retain`` requires special support from the linker; see that attribute's
8663documentation for further information.)reST";
8664
8665static const char AttrDoc_UsingIfExists[] = R"reST(The ``using_if_exists`` attribute applies to a using-declaration. It allows
8666programmers to import a declaration that potentially does not exist, instead
8667deferring any errors to the point of use. For instance:
8668
8669.. code-block:: c++
8670
8671 namespace empty_namespace {};
8672 __attribute__((using_if_exists))
8673 using empty_namespace::does_not_exist; // no error!
8674
8675 does_not_exist x; // error: use of unresolved 'using_if_exists'
8676
8677The C++ spelling of the attribute (`[[clang::using_if_exists]]`) is also
8678supported as a clang extension, since ISO C++ doesn't support attributes in this
8679position. If the entity referred to by the using-declaration is found by name
8680lookup, the attribute has no effect. This attribute is useful for libraries
8681(primarily, libc++) that wish to redeclare a set of declarations in another
8682namespace, when the availability of those declarations is difficult or
8683impossible to detect at compile time with the preprocessor.)reST";
8684
8685static const char AttrDoc_Uuid[] = R"reST(No documentation.)reST";
8686
8687static const char AttrDoc_VTablePointerAuthentication[] = R"reST(No documentation.)reST";
8688
8689static const char AttrDoc_VecReturn[] = R"reST(No documentation.)reST";
8690
8691static const char AttrDoc_VecTypeHint[] = R"reST(No documentation.)reST";
8692
8693static const char AttrDoc_VectorCall[] = R"reST(On 32-bit x86 *and* x86_64 targets, this attribute changes the calling
8694convention of a function to pass vector parameters in SSE registers.
8695
8696On 32-bit x86 targets, this calling convention is similar to ``__fastcall``.
8697The first two integer parameters are passed in ECX and EDX. Subsequent integer
8698parameters are passed in memory, and callee clears the stack. On x86_64
8699targets, the callee does *not* clear the stack, and integer parameters are
8700passed in RCX, RDX, R8, and R9 as is done for the default Windows x64 calling
8701convention.
8702
8703On both 32-bit x86 and x86_64 targets, vector and floating point arguments are
8704passed in XMM0-XMM5. Homogeneous vector aggregates of up to four elements are
8705passed in sequential SSE registers if enough are available. If AVX is enabled,
8706256 bit vectors are passed in YMM0-YMM5. Any vector or aggregate type that
8707cannot be passed in registers for any reason is passed by reference, which
8708allows the caller to align the parameter memory.
8709
8710See the documentation for `__vectorcall`_ on MSDN for more details.
8711
8712.. _`__vectorcall`: http://msdn.microsoft.com/en-us/library/dn375768.aspx)reST";
8713
8714static const char AttrDoc_Visibility[] = R"reST(No documentation.)reST";
8715
8716static const char AttrDoc_WarnUnused[] = R"reST(No documentation.)reST";
8717
8718static const char AttrDoc_WarnUnusedResult[] = R"reST(Clang supports the ability to diagnose when the results of a function call
8719expression are discarded under suspicious circumstances. A diagnostic is
8720generated when a function or its return type is marked with ``[[nodiscard]]``
8721(or ``__attribute__((warn_unused_result))``) and the function call appears as a
8722potentially-evaluated discarded-value expression that is not explicitly cast to
8723``void``.
8724
8725A string literal may optionally be provided to the attribute, which will be
8726reproduced in any resulting diagnostics. Redeclarations using different forms
8727of the attribute (with or without the string literal or with different string
8728literal contents) are allowed. If there are redeclarations of the entity with
8729differing string literals, it is unspecified which one will be used by Clang
8730in any resulting diagnostics.
8731
8732.. code-block:: c++
8733
8734 struct [[nodiscard]] error_info { /*...*/ };
8735 error_info enable_missile_safety_mode();
8736
8737 void launch_missiles();
8738 void test_missiles() {
8739 enable_missile_safety_mode(); // diagnoses
8740 launch_missiles();
8741 }
8742 error_info &foo();
8743 void f() { foo(); } // Does not diagnose, error_info is a reference.
8744
8745Additionally, discarded temporaries resulting from a call to a constructor
8746marked with ``[[nodiscard]]`` or a constructor of a type marked
8747``[[nodiscard]]`` will also diagnose. This also applies to type conversions that
8748use the annotated ``[[nodiscard]]`` constructor or result in an annotated type.
8749
8750.. code-block:: c++
8751
8752 struct [[nodiscard]] marked_type {/*..*/ };
8753 struct marked_ctor {
8754 [[nodiscard]] marked_ctor();
8755 marked_ctor(int);
8756 };
8757
8758 struct S {
8759 operator marked_type() const;
8760 [[nodiscard]] operator int() const;
8761 };
8762
8763 void usages() {
8764 marked_type(); // diagnoses.
8765 marked_ctor(); // diagnoses.
8766 marked_ctor(3); // Does not diagnose, int constructor isn't marked nodiscard.
8767
8768 S s;
8769 static_cast<marked_type>(s); // diagnoses
8770 (int)s; // diagnoses
8771 })reST";
8772
8773static const char AttrDoc_Weak[] = R"reST(In supported output formats the ``weak`` attribute can be used to
8774specify that a variable or function should be emitted as a symbol with
8775``weak`` (if a definition) or ``extern_weak`` (if a declaration of an
8776external symbol) `linkage
8777<https://llvm.org/docs/LangRef.html#linkage-types>`_.
8778
8779If there is a non-weak definition of the symbol the linker will select
8780that over the weak. They must have same type and alignment (variables
8781must also have the same size), but may have a different value.
8782
8783If there are multiple weak definitions of same symbol, but no non-weak
8784definition, they should have same type, size, alignment and value, the
8785linker will select one of them (see also selectany_ attribute).
8786
8787If the ``weak`` attribute is applied to a ``const`` qualified variable
8788definition that variable is no longer consider a compiletime constant
8789as its value can change during linking (or dynamic linking). This
8790means that it can e.g no longer be part of an initializer expression.
8791
8792.. code-block:: c
8793
8794 const int ANSWER __attribute__ ((weak)) = 42;
8795
8796 /* This function may be replaced link-time */
8797 __attribute__ ((weak)) void debug_log(const char *msg)
8798 {
8799 fprintf(stderr, "DEBUG: %s\n", msg);
8800 }
8801
8802 int main(int argc, const char **argv)
8803 {
8804 debug_log ("Starting up...");
8805
8806 /* This may print something else than "6 * 7 = 42",
8807 if there is a non-weak definition of "ANSWER" in
8808 an object linked in */
8809 printf("6 * 7 = %d\n", ANSWER);
8810
8811 return 0;
8812 }
8813
8814If an external declaration is marked weak and that symbol does not
8815exist during linking (possibly dynamic) the address of the symbol will
8816evaluate to NULL.
8817
8818.. code-block:: c
8819
8820 void may_not_exist(void) __attribute__ ((weak));
8821
8822 int main(int argc, const char **argv)
8823 {
8824 if (may_not_exist) {
8825 may_not_exist();
8826 } else {
8827 printf("Function did not exist\n");
8828 }
8829 return 0;
8830 })reST";
8831
8832static const char AttrDoc_WeakImport[] = R"reST(No documentation.)reST";
8833
8834static const char AttrDoc_WeakRef[] = R"reST(No documentation.)reST";
8835
8836static const char AttrDoc_WebAssemblyExportName[] = R"reST(Clang supports the ``__attribute__((export_name(<name>)))``
8837attribute for the WebAssembly target. This attribute may be attached to a
8838function declaration, where it modifies how the symbol is to be exported
8839from the linked WebAssembly.
8840
8841WebAssembly functions are exported via string name. By default when a symbol
8842is exported, the export name for C/C++ symbols are the same as their C/C++
8843symbol names. This attribute can be used to override the default behavior, and
8844request a specific string name be used instead.)reST";
8845
8846static const char AttrDoc_WebAssemblyFuncref[] = R"reST(Clang supports the ``__attribute__((export_name(<name>)))``
8847attribute for the WebAssembly target. This attribute may be attached to a
8848function declaration, where it modifies how the symbol is to be exported
8849from the linked WebAssembly.
8850
8851WebAssembly functions are exported via string name. By default when a symbol
8852is exported, the export name for C/C++ symbols are the same as their C/C++
8853symbol names. This attribute can be used to override the default behavior, and
8854request a specific string name be used instead.)reST";
8855
8856static const char AttrDoc_WebAssemblyImportModule[] = R"reST(Clang supports the ``__attribute__((import_module(<module_name>)))``
8857attribute for the WebAssembly target. This attribute may be attached to a
8858function declaration, where it modifies how the symbol is to be imported
8859within the WebAssembly linking environment.
8860
8861WebAssembly imports use a two-level namespace scheme, consisting of a module
8862name, which typically identifies a module from which to import, and a field
8863name, which typically identifies a field from that module to import. By
8864default, module names for C/C++ symbols are assigned automatically by the
8865linker. This attribute can be used to override the default behavior, and
8866request a specific module name be used instead.)reST";
8867
8868static const char AttrDoc_WebAssemblyImportName[] = R"reST(Clang supports the ``__attribute__((import_name(<name>)))``
8869attribute for the WebAssembly target. This attribute may be attached to a
8870function declaration, where it modifies how the symbol is to be imported
8871within the WebAssembly linking environment.
8872
8873WebAssembly imports use a two-level namespace scheme, consisting of a module
8874name, which typically identifies a module from which to import, and a field
8875name, which typically identifies a field from that module to import. By
8876default, field names for C/C++ symbols are the same as their C/C++ symbol
8877names. This attribute can be used to override the default behavior, and
8878request a specific field name be used instead.)reST";
8879
8880static const char AttrDoc_WorkGroupSizeHint[] = R"reST(No documentation.)reST";
8881
8882static const char AttrDoc_X86ForceAlignArgPointer[] = R"reST(Use this attribute to force stack alignment.
8883
8884Legacy x86 code uses 4-byte stack alignment. Newer aligned SSE instructions
8885(like 'movaps') that work with the stack require operands to be 16-byte aligned.
8886This attribute realigns the stack in the function prologue to make sure the
8887stack can be used with SSE instructions.
8888
8889Note that the x86_64 ABI forces 16-byte stack alignment at the call site.
8890Because of this, 'force_align_arg_pointer' is not needed on x86_64, except in
8891rare cases where the caller does not align the stack properly (e.g. flow
8892jumps from i386 arch code).
8893
8894 .. code-block:: c
8895
8896 __attribute__ ((force_align_arg_pointer))
8897 void f () {
8898 ...
8899 })reST";
8900
8901static const char AttrDoc_XRayInstrument[] = R"reST(``__attribute__((xray_always_instrument))`` or
8902``[[clang::xray_always_instrument]]`` is used to mark member functions (in C++),
8903methods (in Objective C), and free functions (in C, C++, and Objective C) to be
8904instrumented with XRay. This will cause the function to always have space at
8905the beginning and exit points to allow for runtime patching.
8906
8907Conversely, ``__attribute__((xray_never_instrument))`` or
8908``[[clang::xray_never_instrument]]`` will inhibit the insertion of these
8909instrumentation points.
8910
8911If a function has neither of these attributes, they become subject to the XRay
8912heuristics used to determine whether a function should be instrumented or
8913otherwise.
8914
8915``__attribute__((xray_log_args(N)))`` or ``[[clang::xray_log_args(N)]]`` is
8916used to preserve N function arguments for the logging function. Currently,
8917only N==1 is supported.)reST";
8918
8919static const char AttrDoc_XRayLogArgs[] = R"reST(``__attribute__((xray_always_instrument))`` or
8920``[[clang::xray_always_instrument]]`` is used to mark member functions (in C++),
8921methods (in Objective C), and free functions (in C, C++, and Objective C) to be
8922instrumented with XRay. This will cause the function to always have space at
8923the beginning and exit points to allow for runtime patching.
8924
8925Conversely, ``__attribute__((xray_never_instrument))`` or
8926``[[clang::xray_never_instrument]]`` will inhibit the insertion of these
8927instrumentation points.
8928
8929If a function has neither of these attributes, they become subject to the XRay
8930heuristics used to determine whether a function should be instrumented or
8931otherwise.
8932
8933``__attribute__((xray_log_args(N)))`` or ``[[clang::xray_log_args(N)]]`` is
8934used to preserve N function arguments for the logging function. Currently,
8935only N==1 is supported.)reST";
8936
8937static const char AttrDoc_ZeroCallUsedRegs[] = R"reST(This attribute, when attached to a function, causes the compiler to zero a
8938subset of all call-used registers before the function returns. It's used to
8939increase program security by either mitigating `Return-Oriented Programming`_
8940(ROP) attacks or preventing information leakage through registers.
8941
8942The term "call-used" means registers which are not guaranteed to be preserved
8943unchanged for the caller by the current calling convention. This could also be
8944described as "caller-saved" or "not callee-saved".
8945
8946The `choice` parameters gives the programmer flexibility to choose the subset
8947of the call-used registers to be zeroed:
8948
8949- ``skip`` doesn't zero any call-used registers. This choice overrides any
8950 command-line arguments.
8951- ``used`` only zeros call-used registers used in the function. By ``used``, we
8952 mean a register whose contents have been set or referenced in the function.
8953- ``used-gpr`` only zeros call-used GPR registers used in the function.
8954- ``used-arg`` only zeros call-used registers used to pass arguments to the
8955 function.
8956- ``used-gpr-arg`` only zeros call-used GPR registers used to pass arguments to
8957 the function.
8958- ``all`` zeros all call-used registers.
8959- ``all-gpr`` zeros all call-used GPR registers.
8960- ``all-arg`` zeros all call-used registers used to pass arguments to the
8961 function.
8962- ``all-gpr-arg`` zeros all call-used GPR registers used to pass arguments to
8963 the function.
8964
8965The default for the attribute is controlled by the ``-fzero-call-used-regs``
8966flag.
8967
8968.. _Return-Oriented Programming: https://en.wikipedia.org/wiki/Return-oriented_programming)reST";
8969