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(.. warning::
98 These attributes are deprecated. Use the ``amdgpu_waves_per_eu`` attribute to
99 control SGPR and VGPR usage instead.
100
101Clang supports the ``__attribute__((amdgpu_num_sgpr(<num_sgpr>)))`` and
102``__attribute__((amdgpu_num_vgpr(<num_vgpr>)))`` attributes for the AMDGPU
103target. These attributes may be attached to a kernel function definition and are
104an optimization hint.
105
106If these attributes are specified, then the AMDGPU target backend will attempt
107to limit the number of SGPRs and/or VGPRs used to the specified value(s). The
108number of used SGPRs and/or VGPRs may further be rounded up to satisfy the
109allocation requirements or constraints of the subtarget. Passing ``0`` as
110``num_sgpr`` and/or ``num_vgpr`` implies the default behavior (no limits).
111
112These attributes can be used to test the AMDGPU target backend. It is
113recommended that the ``amdgpu_waves_per_eu`` attribute be used to control
114resources such as SGPRs and VGPRs since it is aware of the limits for different
115subtargets.
116
117An error will be given if:
118 - Specified values violate subtarget specifications;
119 - Specified values are not compatible with values provided through other
120 attributes;
121 - The AMDGPU target backend is unable to create machine code that can meet the
122 request.)reST";
123
124static const char AttrDoc_AMDGPUNumVGPR[] = R"reST(.. warning::
125 These attributes are deprecated. Use the ``amdgpu_waves_per_eu`` attribute to
126 control SGPR and VGPR usage instead.
127
128Clang supports the ``__attribute__((amdgpu_num_sgpr(<num_sgpr>)))`` and
129``__attribute__((amdgpu_num_vgpr(<num_vgpr>)))`` attributes for the AMDGPU
130target. These attributes may be attached to a kernel function definition and are
131an optimization hint.
132
133If these attributes are specified, then the AMDGPU target backend will attempt
134to limit the number of SGPRs and/or VGPRs used to the specified value(s). The
135number of used SGPRs and/or VGPRs may further be rounded up to satisfy the
136allocation requirements or constraints of the subtarget. Passing ``0`` as
137``num_sgpr`` and/or ``num_vgpr`` implies the default behavior (no limits).
138
139These attributes can be used to test the AMDGPU target backend. It is
140recommended that the ``amdgpu_waves_per_eu`` attribute be used to control
141resources such as SGPRs and VGPRs since it is aware of the limits for different
142subtargets.
143
144An error will be given if:
145 - Specified values violate subtarget specifications;
146 - Specified values are not compatible with values provided through other
147 attributes;
148 - The AMDGPU target backend is unable to create machine code that can meet the
149 request.)reST";
150
151static const char AttrDoc_AMDGPUWavesPerEU[] = R"reST(A compute unit (CU) is responsible for executing the wavefronts of a work-group.
152It is composed of one or more execution units (EU), which are responsible for
153executing the wavefronts. An EU can have enough resources to maintain the state
154of more than one executing wavefront. This allows an EU to hide latency by
155switching between wavefronts in a similar way to symmetric multithreading on a
156CPU. In order to allow the state for multiple wavefronts to fit on an EU, the
157resources used by a single wavefront have to be limited. For example, the number
158of SGPRs and VGPRs. Limiting such resources can allow greater latency hiding,
159but can result in having to spill some register state to memory.
160
161Clang supports the ``__attribute__((amdgpu_waves_per_eu(<min>[, <max>])))``
162attribute for the AMDGPU target. This attribute may be attached to a kernel
163function definition and is an optimization hint.
164
165``<min>`` parameter specifies the requested minimum number of waves per EU, and
166*optional* ``<max>`` parameter specifies the requested maximum number of waves
167per EU (must be greater than ``<min>`` if specified). If ``<max>`` is omitted,
168then there is no restriction on the maximum number of waves per EU other than
169the one dictated by the hardware for which the kernel is compiled. Passing
170``0, 0`` as ``<min>, <max>`` implies the default behavior (no limits).
171
172If specified, this attribute allows an advanced developer to tune the number of
173wavefronts that are capable of fitting within the resources of an EU. The AMDGPU
174target backend can use this information to limit resources, such as number of
175SGPRs, number of VGPRs, size of available group and private memory segments, in
176such a way that guarantees that at least ``<min>`` wavefronts and at most
177``<max>`` wavefronts are able to fit within the resources of an EU. Requesting
178more wavefronts can hide memory latency but limits available registers which
179can result in spilling. Requesting fewer wavefronts can help reduce cache
180thrashing, but can reduce memory latency hiding.
181
182This attribute controls the machine code generated by the AMDGPU target backend
183to ensure it is capable of meeting the requested values. However, when the
184kernel is executed, there may be other reasons that prevent meeting the request,
185for example, there may be wavefronts from other kernels executing on the EU.
186
187An error will be given if:
188 - Specified values violate subtarget specifications;
189 - Specified values are not compatible with values provided through other
190 attributes;
191
192The AMDGPU target backend will emit a warning whenever it is unable to
193create machine code that meets the request.)reST";
194
195static const char AttrDoc_ARMInterrupt[] = R"reST(Clang supports the GNU style ``__attribute__((interrupt("TYPE")))`` attribute on
196ARM targets. This attribute may be attached to a function definition and
197instructs the backend to generate appropriate function entry/exit code so that
198it can be used directly as an interrupt service routine.
199
200The parameter passed to the interrupt attribute is optional, but if
201provided it must be a string literal with one of the following values: "IRQ",
202"FIQ", "SWI", "ABORT", "UNDEF".
203
204The semantics are as follows:
205
206- If the function is AAPCS, Clang instructs the backend to realign the stack to
207 8 bytes on entry. This is a general requirement of the AAPCS at public
208 interfaces, but may not hold when an exception is taken. Doing this allows
209 other AAPCS functions to be called.
210- If the CPU is M-class this is all that needs to be done since the architecture
211 itself is designed in such a way that functions obeying the normal AAPCS ABI
212 constraints are valid exception handlers.
213- If the CPU is not M-class, the prologue and epilogue are modified to save all
214 non-banked registers that are used, so that upon return the user-mode state
215 will not be corrupted. Note that to avoid unnecessary overhead, only
216 general-purpose (integer) registers are saved in this way. If VFP operations
217 are needed, that state must be saved manually.
218
219 Specifically, interrupt kinds other than "FIQ" will save all core registers
220 except "lr" and "sp". "FIQ" interrupts will save r0-r7.
221- If the CPU is not M-class, the return instruction is changed to one of the
222 canonical sequences permitted by the architecture for exception return. Where
223 possible the function itself will make the necessary "lr" adjustments so that
224 the "preferred return address" is selected.
225
226 Unfortunately the compiler is unable to make this guarantee for an "UNDEF"
227 handler, where the offset from "lr" to the preferred return address depends on
228 the execution state of the code which generated the exception. In this case
229 a sequence equivalent to "movs pc, lr" will be used.)reST";
230
231static const char AttrDoc_ARMInterruptSaveFP[] = R"reST(Clang supports the GNU style ``__attribute__((interrupt_save_fp("TYPE")))``
232on ARM targets. This attribute behaves the same way as the ARM interrupt
233attribute, except the general purpose floating point registers are also saved,
234along with FPEXC and FPSCR. Note, even on M-class CPUs, where the floating
235point context can be automatically saved depending on the FPCCR, the general
236purpose floating point registers will be saved.)reST";
237
238static const char AttrDoc_ARMSaveFP[] = R"reST()reST";
239
240static const char AttrDoc_AVRInterrupt[] = R"reST(Clang supports the GNU style ``__attribute__((interrupt))`` attribute on
241AVR targets. This attribute may be attached to a function definition and instructs
242the backend to generate appropriate function entry/exit code so that it can be used
243directly as an interrupt service routine.
244
245On the AVR, the hardware globally disables interrupts when an interrupt is executed.
246The first instruction of an interrupt handler declared with this attribute is a SEI
247instruction to re-enable interrupts. See also the signal attribute that
248does not insert a SEI instruction.)reST";
249
250static const char AttrDoc_AVRSignal[] = R"reST(Clang supports the GNU style ``__attribute__((signal))`` attribute on
251AVR targets. This attribute may be attached to a function definition and instructs
252the backend to generate appropriate function entry/exit code so that it can be used
253directly as an interrupt service routine.
254
255Interrupt handler functions defined with the signal attribute do not re-enable interrupts.)reST";
256
257static const char AttrDoc_AbiTag[] = R"reST(The ``abi_tag`` attribute can be applied to a function, variable, class or
258inline namespace declaration to modify the mangled name of the entity. It gives
259the ability to distinguish between different versions of the same entity but
260with different ABI versions supported. For example, a newer version of a class
261could have a different set of data members and thus have a different size. Using
262the ``abi_tag`` attribute, it is possible to have different mangled names for
263a global variable of the class type. Therefore, the old code could keep using
264the old mangled name and the new code will use the new mangled name with tags.)reST";
265
266static const char AttrDoc_AcquireCapability[] = R"reST(Marks a function as acquiring a capability.)reST";
267
268static const char AttrDoc_AcquireHandle[] = R"reST(If this annotation is on a function or a function type it is assumed to return
269a new handle. In case this annotation is on an output parameter,
270the function is assumed to fill the corresponding argument with a new
271handle. The attribute requires a string literal argument which used to
272identify the handle with later uses of ``use_handle`` or
273``release_handle``.
274
275.. code-block:: c++
276
277 // Output arguments from Zircon.
278 zx_status_t zx_socket_create(uint32_t options,
279 zx_handle_t __attribute__((acquire_handle("zircon"))) * out0,
280 zx_handle_t* out1 [[clang::acquire_handle("zircon")]]);
281
282
283 // Returned handle.
284 [[clang::acquire_handle("tag")]] int open(const char *path, int oflag, ... );
285 int open(const char *path, int oflag, ... ) __attribute__((acquire_handle("tag")));)reST";
286
287static const char AttrDoc_AcquiredAfter[] = R"reST(No documentation.)reST";
288
289static const char AttrDoc_AcquiredBefore[] = R"reST(No documentation.)reST";
290
291static const char AttrDoc_AddressSpace[] = R"reST(.. Note:: This attribute is mainly intended to be used by target headers
292 provided by the toolchain. End users should prefer the documented, named
293 address space annotations for their platform, such as the
294 `OpenCL address spaces`_, ``__global__``, ``__local__``, or something else.
295
296The ``address_space`` attribute functions as a type qualifier that allows the
297programmer to specify the address space for a pointer or reference type.
298Qualified pointer types are considered distinct types for the purposes of
299overload resolution. The attribute takes a single, non-negative integer
300constant expression identifying the address space. For example:
301
302.. code-block:: c
303
304 int * __attribute__((address_space(1))) ptr;
305
306 void foo(__attribute__((address_space(2))) float *buf);
307
308
309Only one address space qualifier may be applied to a given pointer or reference
310type. Where address spaces are allowed (e.g., variables, parameters, return
311types) and what values are valid depends on the target and language mode.
312
313The meaning of each value is defined by the target; multiple address spaces are
314used in environments such as OpenCL, CUDA, HIP, and other GPU programming
315models to distinguish global, local, constant, and private memory. See for
316example the address spaces defined in the `NVPTX Usage Guide`_ and the
317`AMDGPU Usage Guide`_.
318
319.. _`NVPTX Usage Guide`: https://llvm.org/docs/NVPTXUsage.html#address-spaces
320.. _`AMDGPU Usage Guide`: https://llvm.org/docs/AMDGPUUsage.html#address-spaces
321
322Address spaces may partially overlap or be entirely distinct. The compiler may
323reject attempts to convert between distinct, incompatible address spaces.
324Pointer width may vary between different address spaces, so some explicit casts
325may truncate.
326
327For more information, refer to `ISO TR18037`_, which covers embedded C language
328extensions. Section 5 covers named address spaces.
329
330.. _`ISO TR18037`: https://standards.iso.org/ittf/PubliclyAvailableStandards/c051126_ISO_IEC_TR_18037_2008.zip)reST";
331
332static const char AttrDoc_Alias[] = R"reST(No documentation.)reST";
333
334static const char AttrDoc_AlignMac68k[] = R"reST()reST";
335
336static const char AttrDoc_AlignNatural[] = R"reST()reST";
337
338static const char AttrDoc_AlignValue[] = R"reST(The align_value attribute can be added to the typedef of a pointer type or the
339declaration of a variable of pointer or reference type. It specifies that the
340pointer will point to, or the reference will bind to, only objects with at
341least the provided alignment. This alignment value must be some positive power
342of 2.
343
344 .. code-block:: c
345
346 typedef double * aligned_double_ptr __attribute__((align_value(64)));
347 void foo(double & x __attribute__((align_value(128))),
348 aligned_double_ptr y) { ... }
349
350If the pointer value does not have the specified alignment at runtime, the
351behavior of the program is undefined.)reST";
352
353static const char AttrDoc_Aligned[] = R"reST(No documentation.)reST";
354
355static const char AttrDoc_AllocAlign[] = R"reST(Use ``__attribute__((alloc_align(<alignment>))`` on a function
356declaration to specify that the return value of the function (which must be a
357pointer type) is at least as aligned as the value of the indicated parameter. The
358parameter is given by its index in the list of formal parameters; the first
359parameter has index 1 unless the function is a C++ non-static member function,
360in which case the first parameter has index 2 to account for the implicit ``this``
361parameter.
362
363.. code-block:: c++
364
365 // The returned pointer has the alignment specified by the first parameter.
366 void *a(size_t align) __attribute__((alloc_align(1)));
367
368 // The returned pointer has the alignment specified by the second parameter.
369 void *b(void *v, size_t align) __attribute__((alloc_align(2)));
370
371 // The returned pointer has the alignment specified by the second visible
372 // parameter, however it must be adjusted for the implicit 'this' parameter.
373 void *Foo::b(void *v, size_t align) __attribute__((alloc_align(3)));
374
375Note that this attribute merely informs the compiler that a function always
376returns a sufficiently aligned pointer. It does not cause the compiler to
377emit code to enforce that alignment. The behavior is undefined if the returned
378pointer is not sufficiently aligned.)reST";
379
380static const char AttrDoc_AllocSize[] = R"reST(The ``alloc_size`` attribute can be placed on functions that return pointers in
381order to hint to the compiler how many bytes of memory will be available at the
382returned pointer. ``alloc_size`` takes one or two arguments.
383
384- ``alloc_size(N)`` implies that argument number N equals the number of
385 available bytes at the returned pointer.
386- ``alloc_size(N, M)`` implies that the product of argument number N and
387 argument number M equals the number of available bytes at the returned
388 pointer.
389
390Argument numbers are 1-based.
391
392An example of how to use ``alloc_size``
393
394.. code-block:: c
395
396 void *my_malloc(int a) __attribute__((alloc_size(1)));
397 void *my_calloc(int a, int b) __attribute__((alloc_size(1, 2)));
398
399 int main() {
400 void *const p = my_malloc(100);
401 assert(__builtin_object_size(p, 0) == 100);
402 void *const a = my_calloc(20, 5);
403 assert(__builtin_object_size(a, 0) == 100);
404 }
405
406When ``-Walloc-size`` is enabled, this attribute allows the compiler to
407diagnose cases when the allocated memory is insufficient for the size of the
408type the returned pointer is cast to.
409
410.. code-block:: c
411
412 void *my_malloc(int a) __attribute__((alloc_size(1)));
413 void consumer_func(int *);
414
415 int main() {
416 int *ptr = my_malloc(sizeof(int)); // no warning
417 int *w = my_malloc(1); // warning: allocation of insufficient size '1' for type 'int' with size '4'
418 consumer_func(my_malloc(1)); // warning: allocation of insufficient size '1' for type 'int' with size '4'
419 }
420
421.. Note:: This attribute works differently in clang than it does in GCC.
422 Specifically, clang will only trace ``const`` pointers (as above); we give up
423 on pointers that are not marked as ``const``. In the vast majority of cases,
424 this is unimportant, because LLVM has support for the ``alloc_size``
425 attribute. However, this may cause mildly unintuitive behavior when used with
426 other attributes, such as ``enable_if``.)reST";
427
428static const char AttrDoc_Allocating[] = R"reST(Declares that a function potentially allocates heap memory, and prevents any potential inference
429of ``nonallocating`` by the compiler.)reST";
430
431static const char AttrDoc_AlwaysDestroy[] = R"reST(The ``always_destroy`` attribute specifies that a variable with static or thread
432storage duration should have its exit-time destructor run. This attribute is the
433default unless clang was invoked with -fno-c++-static-destructors.
434
435If a variable is explicitly declared with this attribute, Clang will silence
436otherwise applicable ``-Wexit-time-destructors`` warnings.)reST";
437
438static const char AttrDoc_AlwaysInline[] = R"reST(Inlining heuristics are disabled and inlining is always attempted regardless of
439optimization level.
440
441``[[clang::always_inline]]`` spelling can be used as a statement attribute; other
442spellings of the attribute are not supported on statements. If a statement is
443marked ``[[clang::always_inline]]`` and contains calls, the compiler attempts
444to inline those calls.
445
446.. code-block:: c
447
448 int example(void) {
449 int i;
450 [[clang::always_inline]] foo(); // attempts to inline foo
451 [[clang::always_inline]] i = bar(); // attempts to inline bar
452 [[clang::always_inline]] return f(42, baz(bar())); // attempts to inline everything
453 }
454
455A declaration statement, which is a statement, is not a statement that can have an
456attribute associated with it (the attribute applies to the declaration, not the
457statement in that case). So this use case will not work:
458
459.. code-block:: c
460
461 int example(void) {
462 [[clang::always_inline]] int i = bar();
463 return i;
464 }
465
466This attribute does not guarantee that inline substitution actually occurs.
467
468<ins>Note: applying this attribute to a coroutine at the `-O0` optimization level
469has no effect; other optimization levels may only partially inline and result in a
470diagnostic.</ins>
471
472See also `the Microsoft Docs on Inline Functions`_, `the GCC Common Function
473Attribute docs`_, and `the GCC Inline docs`_.
474
475.. _the Microsoft Docs on Inline Functions: https://docs.microsoft.com/en-us/cpp/cpp/inline-functions-cpp
476.. _the GCC Common Function Attribute docs: https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html
477.. _the GCC Inline docs: https://gcc.gnu.org/onlinedocs/gcc/Inline.html)reST";
478
479static const char AttrDoc_AnalyzerNoReturn[] = R"reST(No documentation.)reST";
480
481static const char AttrDoc_Annotate[] = R"reST(The `annotate` attribute is used to add annotations to declarations or statements,
482typically for use by static analysis tools that are not integrated into the
483core Clang compiler (e.g., Clang-Tidy checks or out-of-tree Clang-based tools).
484It is a counterpart to the `annotate_type` attribute, which serves the same
485purpose, but for types.
486
487The attribute takes a mandatory string literal argument specifying the
488annotation category and an arbitrary number of optional arguments that provide
489additional information specific to the annotation category. The optional
490arguments must be constant expressions of arbitrary type.
491
492For example:
493
494.. code-block:: c++
495
496 [[clang::annotate("category1", "foo", 1)]] void func(int val [[clang::annotate("category2")]]) {
497 [[clang::annotate("category3")]] if (val) {
498
499 }
500 })reST";
501
502static const char AttrDoc_AnnotateType[] = R"reST(This attribute is used to add annotations to types, typically for use by static
503analysis tools that are not integrated into the core Clang compiler (e.g.,
504Clang-Tidy checks or out-of-tree Clang-based tools). It is a counterpart to the
505`annotate` attribute, which serves the same purpose, but for declarations.
506
507The attribute takes a mandatory string literal argument specifying the
508annotation category and an arbitrary number of optional arguments that provide
509additional information specific to the annotation category. The optional
510arguments must be constant expressions of arbitrary type.
511
512For example:
513
514.. code-block:: c++
515
516 int* [[clang::annotate_type("category1", "foo", 1)]] f(int[[clang::annotate_type("category2")]] *);
517
518The attribute does not have any effect on the semantics of the type system,
519neither type checking rules, nor runtime semantics. In particular:
520
521- ``std::is_same<T, T [[clang::annotate_type("foo")]]>`` is true for all types
522 ``T``.
523
524- It is not permissible for overloaded functions or template specializations
525 to differ merely by an ``annotate_type`` attribute.
526
527- The presence of an ``annotate_type`` attribute will not affect name
528 mangling.)reST";
529
530static const char AttrDoc_AnyX86Interrupt[] = R"reST(Clang supports the GNU style ``__attribute__((interrupt))`` attribute on X86
531targets. This attribute may be attached to a function definition and instructs
532the backend to generate appropriate function entry/exit code so that it can be
533used directly as an interrupt service routine.
534
535Interrupt handlers have access to the stack frame pushed onto the stack by the processor,
536and return using the ``IRET`` instruction. All registers in an interrupt handler are callee-saved.
537Exception handlers also have access to the error code pushed onto the stack by the processor,
538when applicable.
539
540An interrupt handler must take the following arguments:
541
542 .. code-block:: c
543
544 __attribute__ ((interrupt))
545 void f (struct stack_frame *frame) {
546 ...
547 }
548
549 Where ``struct stack_frame`` is a suitable struct matching the stack frame pushed by the
550 processor.
551
552An exception handler must take the following arguments:
553
554 .. code-block:: c
555
556 __attribute__ ((interrupt))
557 void g (struct stack_frame *frame, unsigned long code) {
558 ...
559 }
560
561 On 32-bit targets, the ``code`` argument should be of type ``unsigned int``.
562
563Exception handlers should only be used when an error code is pushed by the processor.
564Using the incorrect handler type will crash the system.
565
566Interrupt and exception handlers cannot be called by other functions and must have return type ``void``.
567
568Interrupt and exception handlers should only call functions with the 'no_caller_saved_registers'
569attribute, or should be compiled with the '-mgeneral-regs-only' flag to avoid saving unused
570non-GPR registers.)reST";
571
572static const char AttrDoc_AnyX86NoCallerSavedRegisters[] = R"reST(Use this attribute to indicate that the specified function has no
573caller-saved registers. That is, all registers are callee-saved except for
574registers used for passing parameters to the function or returning parameters
575from the function.
576The compiler saves and restores any modified registers that were not used for
577passing or returning arguments to the function.
578
579The user can call functions specified with the 'no_caller_saved_registers'
580attribute from an interrupt handler without saving and restoring all
581call-clobbered registers.
582
583Functions specified with the 'no_caller_saved_registers' attribute should only
584call other functions with the 'no_caller_saved_registers' attribute, or should be
585compiled with the '-mgeneral-regs-only' flag to avoid saving unused non-GPR registers.
586
587Note that 'no_caller_saved_registers' attribute is not a calling convention.
588In fact, it only overrides the decision of which registers should be saved by
589the caller, but not how the parameters are passed from the caller to the callee.
590
591For example:
592
593 .. code-block:: c
594
595 __attribute__ ((no_caller_saved_registers, fastcall))
596 void f (int arg1, int arg2) {
597 ...
598 }
599
600 In this case parameters 'arg1' and 'arg2' will be passed in registers.
601 In this case, on 32-bit x86 targets, the function 'f' will use ECX and EDX as
602 register parameters. However, it will not assume any scratch registers and
603 should save and restore any modified registers except for ECX and EDX.)reST";
604
605static const char AttrDoc_AnyX86NoCfCheck[] = R"reST(Jump Oriented Programming attacks rely on tampering with addresses used by
606indirect call / jmp, e.g. redirect control-flow to non-programmer
607intended bytes in the binary.
608X86 Supports Indirect Branch Tracking (IBT) as part of Control-Flow
609Enforcement Technology (CET). IBT instruments ENDBR instructions used to
610specify valid targets of indirect call / jmp.
611The ``nocf_check`` attribute has two roles:
6121. Appertains to a function - do not add ENDBR instruction at the beginning of
613the function.
6142. Appertains to a function pointer - do not track the target function of this
615pointer (by adding nocf_check prefix to the indirect-call instruction).)reST";
616
617static const char AttrDoc_ArcWeakrefUnavailable[] = R"reST(No documentation.)reST";
618
619static const char AttrDoc_ArgumentWithTypeTag[] = R"reST(Use ``__attribute__((argument_with_type_tag(arg_kind, arg_idx,
620type_tag_idx)))`` on a function declaration to specify that the function
621accepts a type tag that determines the type of some other argument.
622
623This attribute is primarily useful for checking arguments of variadic functions
624(``pointer_with_type_tag`` can be used in most non-variadic cases).
625
626In the attribute prototype above:
627 * ``arg_kind`` is an identifier that should be used when annotating all
628 applicable type tags.
629 * ``arg_idx`` provides the position of a function argument. The expected type of
630 this function argument will be determined by the function argument specified
631 by ``type_tag_idx``. In the code example below, "3" means that the type of the
632 function's third argument will be determined by ``type_tag_idx``.
633 * ``type_tag_idx`` provides the position of a function argument. This function
634 argument will be a type tag. The type tag will determine the expected type of
635 the argument specified by ``arg_idx``. In the code example below, "2" means
636 that the type tag associated with the function's second argument should agree
637 with the type of the argument specified by ``arg_idx``.
638
639For example:
640
641.. code-block:: c++
642
643 int fcntl(int fd, int cmd, ...)
644 __attribute__(( argument_with_type_tag(fcntl,3,2) ));
645 // The function's second argument will be a type tag; this type tag will
646 // determine the expected type of the function's third argument.)reST";
647
648static const char AttrDoc_ArmAgnostic[] = R"reST(The ``__arm_agnostic`` keyword applies to prototyped function types and
649affects the function's calling convention for a given state S. This
650attribute allows the user to describe a function that preserves S, without
651requiring the function to share S with its callers and without making
652the assumption that S exists.
653
654If a function has the ``__arm_agnostic(S)`` attribute and calls a function
655without this attribute, then the function's object code will contain code
656to preserve state S. Otherwise, the function's object code will be the same
657as if it did not have the attribute.
658
659The attribute takes string arguments to describe state S. The supported
660states are:
661
662* ``"sme_za_state"`` for state enabled by PSTATE.ZA, such as ZA and ZT0.
663
664The attribute ``__arm_agnostic("sme_za_state")`` cannot be used in conjunction
665with ``__arm_in(S)``, ``__arm_out(S)``, ``__arm_inout(S)`` or
666``__arm_preserves(S)`` where state S describes state enabled by PSTATE.ZA,
667such as "za" or "zt0".)reST";
668
669static const char AttrDoc_ArmBuiltinAlias[] = R"reST(This attribute is used in the implementation of the ACLE intrinsics.
670It allows the intrinsic functions to
671be declared using the names defined in ACLE, and still be recognized
672as clang builtins equivalent to the underlying name. For example,
673``arm_mve.h`` declares the function ``vaddq_u32`` with
674``__attribute__((__clang_arm_mve_alias(__builtin_arm_mve_vaddq_u32)))``,
675and similarly, one of the type-overloaded declarations of ``vaddq``
676will have the same attribute. This ensures that both functions are
677recognized as that clang builtin, and in the latter case, the choice
678of which builtin to identify the function as can be deferred until
679after overload resolution.
680
681This attribute can only be used to set up the aliases for certain Arm
682intrinsic functions; it is intended for use only inside ``arm_*.h``
683and is not a general mechanism for declaring arbitrary aliases for
684clang builtin functions.
685
686In order to avoid duplicating the attribute definitions for similar
687purpose for other architecture, there is a general form for the
688attribute `clang_builtin_alias`.)reST";
689
690static const char AttrDoc_ArmIn[] = R"reST(The ``__arm_in`` keyword applies to prototyped function types and specifies
691that the function shares a given state S with its caller. For ``__arm_in``, the
692function takes the state S as input and returns with the state S unchanged.
693
694The attribute takes string arguments to instruct the compiler which state
695is shared. The supported states for S are:
696
697* ``"za"`` for Matrix Storage (requires SME)
698
699The attributes ``__arm_in(S)``, ``__arm_out(S)``, ``__arm_inout(S)`` and
700``__arm_preserves(S)`` are all mutually exclusive for the same state S.)reST";
701
702static const char AttrDoc_ArmInOut[] = R"reST(The ``__arm_inout`` keyword applies to prototyped function types and specifies
703that the function shares a given state S with its caller. For ``__arm_inout``,
704the function takes the state S as input and returns new state for S.
705
706The attribute takes string arguments to instruct the compiler which state
707is shared. The supported states for S are:
708
709* ``"za"`` for Matrix Storage (requires SME)
710
711The attributes ``__arm_in(S)``, ``__arm_out(S)``, ``__arm_inout(S)`` and
712``__arm_preserves(S)`` are all mutually exclusive for the same state S.)reST";
713
714static const char AttrDoc_ArmLocallyStreaming[] = R"reST(The ``__arm_locally_streaming`` keyword applies to function declarations
715and specifies that all the statements in the function are executed in
716streaming mode. This means that:
717
718* the function requires that the target processor implements the Scalable Matrix
719 Extension (SME).
720
721* the program automatically puts the machine into streaming mode before
722 executing the statements and automatically restores the previous mode
723 afterwards.
724
725Clang manages PSTATE.SM automatically; it is not the source code's
726responsibility to do this. For example, Clang will emit code to enable
727streaming mode at the start of the function, and disable streaming mode
728at the end of the function.)reST";
729
730static const char AttrDoc_ArmMveStrictPolymorphism[] = R"reST(This attribute is used in the implementation of the ACLE intrinsics for the Arm
731MVE instruction set. It is used to define the vector types used by the MVE
732intrinsics.
733
734Its effect is to modify the behavior of a vector type with respect to function
735overloading. If a candidate function for overload resolution has a parameter
736type with this attribute, then the selection of that candidate function will be
737disallowed if the actual argument can only be converted via a lax vector
738conversion. The aim is to prevent spurious ambiguity in ARM MVE polymorphic
739intrinsics.
740
741.. code-block:: c++
742
743 void overloaded(uint16x8_t vector, uint16_t scalar);
744 void overloaded(int32x4_t vector, int32_t scalar);
745 uint16x8_t myVector;
746 uint16_t myScalar;
747
748 // myScalar is promoted to int32_t as a side effect of the addition,
749 // so if lax vector conversions are considered for myVector, then
750 // the two overloads are equally good (one argument conversion
751 // each). But if the vector has the __clang_arm_mve_strict_polymorphism
752 // attribute, only the uint16x8_t,uint16_t overload will match.
753 overloaded(myVector, myScalar + 1);
754
755However, this attribute does not prohibit lax vector conversions in contexts
756other than overloading.
757
758.. code-block:: c++
759
760 uint16x8_t function();
761
762 // This is still permitted with lax vector conversion enabled, even
763 // if the vector types have __clang_arm_mve_strict_polymorphism
764 int32x4_t result = function();)reST";
765
766static const char AttrDoc_ArmNew[] = R"reST(The ``__arm_new`` keyword applies to function declarations and specifies
767that the function will create a new scope for state S.
768
769The attribute takes string arguments to instruct the compiler for which state
770to create new scope. The supported states for S are:
771
772* ``"za"`` for Matrix Storage (requires SME)
773
774For state ``"za"``, this means that:
775
776* the function requires that the target processor implements the Scalable Matrix
777 Extension (SME).
778
779* the function will commit any lazily saved ZA data.
780
781* the function will create a new ZA context and enable PSTATE.ZA.
782
783* the function will disable PSTATE.ZA (by setting it to 0) before returning.
784
785For ``__arm_new("za")`` functions Clang will set up the ZA context automatically
786on entry to the function and disable it before returning. For example, if ZA is
787in a dormant state Clang will generate the code to commit a lazy-save and set up
788a new ZA state before executing user code.)reST";
789
790static const char AttrDoc_ArmOut[] = R"reST(The ``__arm_out`` keyword applies to prototyped function types and specifies
791that the function shares a given state S with its caller. For ``__arm_out``,
792the function ignores the incoming state for S and returns new state for S.
793
794The attribute takes string arguments to instruct the compiler which state
795is shared. The supported states for S are:
796
797* ``"za"`` for Matrix Storage (requires SME)
798
799The attributes ``__arm_in(S)``, ``__arm_out(S)``, ``__arm_inout(S)`` and
800``__arm_preserves(S)`` are all mutually exclusive for the same state S.)reST";
801
802static const char AttrDoc_ArmPreserves[] = R"reST(The ``__arm_preserves`` keyword applies to prototyped function types and
803specifies that the function does not read a given state S and returns
804with state S unchanged.
805
806The attribute takes string arguments to instruct the compiler which state
807is shared. The supported states for S are:
808
809* ``"za"`` for Matrix Storage (requires SME)
810
811The attributes ``__arm_in(S)``, ``__arm_out(S)``, ``__arm_inout(S)`` and
812``__arm_preserves(S)`` are all mutually exclusive for the same state S.)reST";
813
814static const char AttrDoc_ArmStreaming[] = R"reST(The ``__arm_streaming`` keyword applies to prototyped function types and specifies
815that the function has a "streaming interface". This means that:
816
817* the function requires that the processor implements the Scalable Matrix
818 Extension (SME).
819
820* the function must be entered in streaming mode (that is, with PSTATE.SM
821 set to 1)
822
823* the function must return in streaming mode
824
825Clang manages PSTATE.SM automatically; it is not the source code's
826responsibility to do this. For example, if a non-streaming
827function calls an ``__arm_streaming`` function, Clang generates code
828that switches into streaming mode before calling the function and
829switches back to non-streaming mode on return.)reST";
830
831static const char AttrDoc_ArmStreamingCompatible[] = R"reST(The ``__arm_streaming_compatible`` keyword applies to prototyped function types and
832specifies that the function has a "streaming compatible interface". This
833means that:
834
835* the function may be entered in either non-streaming mode (PSTATE.SM=0) or
836 in streaming mode (PSTATE.SM=1).
837
838* the function must return in the same mode as it was entered.
839
840* the code executed in the function is compatible with either mode.
841
842Clang manages PSTATE.SM automatically; it is not the source code's
843responsibility to do this. Clang will ensure that the generated code in
844streaming-compatible functions is valid in either mode (PSTATE.SM=0 or
845PSTATE.SM=1). For example, if an ``__arm_streaming_compatible`` function calls a
846non-streaming function, Clang generates code to temporarily switch out of streaming
847mode before calling the function and switch back to streaming-mode on return if
848``PSTATE.SM`` is ``1`` on entry of the caller. If ``PSTATE.SM`` is ``0`` on
849entry to the ``__arm_streaming_compatible`` function, the call will be executed
850without changing modes.)reST";
851
852static const char AttrDoc_Artificial[] = R"reST(The ``artificial`` attribute can be applied to an inline function. If such a
853function is inlined, the attribute indicates that debuggers should associate
854the resulting instructions with the call site, rather than with the
855corresponding line within the inlined callee.)reST";
856
857static const char AttrDoc_AsmLabel[] = R"reST(This attribute can be used on a function or variable to specify its symbol name.
858
859On some targets, all C symbols are prefixed by default with a single character,
860typically ``_``. This was done historically to distinguish them from symbols
861used by other languages. (This prefix is also added to the standard Itanium
862C++ ABI prefix on "mangled" symbol names, so that e.g. on such targets the true
863symbol name for a C++ variable declared as ``int cppvar;`` would be
864``__Z6cppvar``; note the two underscores.) This prefix is *not* added to the
865symbol names specified by the ``__asm`` attribute; programmers wishing to match
866a C symbol name must compensate for this.
867
868For example, consider the following C code:
869
870.. code-block:: c
871
872 int var1 __asm("altvar") = 1; // "altvar" in symbol table.
873 int var2 = 1; // "_var2" in symbol table.
874
875 void func1(void) __asm("altfunc");
876 void func1(void) {} // "altfunc" in symbol table.
877 void func2(void) {} // "_func2" in symbol table.
878
879Clang's implementation of this attribute is compatible with GCC's, `documented here <https://gcc.gnu.org/onlinedocs/gcc/Asm-Labels.html>`_.
880
881While it is possible to use this attribute to name a special symbol used
882internally by the compiler, such as an LLVM intrinsic, this is neither
883recommended nor supported and may cause the compiler to crash or miscompile.
884Users who wish to gain access to intrinsic behavior are strongly encouraged to
885request new builtin functions.)reST";
886
887static const char AttrDoc_AssertCapability[] = R"reST(Marks a function that dynamically tests whether a capability is held, and halts
888the program if it is not held.)reST";
889
890static const char AttrDoc_AssumeAligned[] = R"reST(Use ``__attribute__((assume_aligned(<alignment>[,<offset>]))`` on a function
891declaration to specify that the return value of the function (which must be a
892pointer type) has the specified offset, in bytes, from an address with the
893specified alignment. The offset is taken to be zero if omitted.
894
895.. code-block:: c++
896
897 // The returned pointer value has 32-byte alignment.
898 void *a() __attribute__((assume_aligned (32)));
899
900 // The returned pointer value is 4 bytes greater than an address having
901 // 32-byte alignment.
902 void *b() __attribute__((assume_aligned (32, 4)));
903
904Note that this attribute provides information to the compiler regarding a
905condition that the code already ensures is true. It does not cause the compiler
906to enforce the provided alignment assumption.)reST";
907
908static const char AttrDoc_Atomic[] = R"reST(The ``atomic`` attribute can be applied to *compound statements* to override or
909further specify the default atomic code-generation behavior, especially on
910targets such as AMDGPU. You can annotate compound statements with options
911to modify how atomic instructions inside that statement are emitted at the IR
912level.
913
914For details, see the documentation for `@atomic
915<http://clang.llvm.org/docs/LanguageExtensions.html#extensions-for-controlling-atomic-code-generation>`_)reST";
916
917static const char AttrDoc_Availability[] = R"reST(The ``availability`` attribute can be placed on declarations to describe the
918lifecycle of that declaration relative to operating system versions. Consider
919the function declaration for a hypothetical function ``f``:
920
921.. code-block:: c++
922
923 void f(void) __attribute__((availability(macos,introduced=10.4,deprecated=10.6,obsoleted=10.7)));
924
925The availability attribute states that ``f`` was introduced in macOS 10.4,
926deprecated in macOS 10.6, and obsoleted in macOS 10.7. This information
927is used by Clang to determine when it is safe to use ``f``: for example, if
928Clang is instructed to compile code for macOS 10.5, a call to ``f()``
929succeeds. If Clang is instructed to compile code for macOS 10.6, the call
930succeeds but Clang emits a warning specifying that the function is deprecated.
931Finally, if Clang is instructed to compile code for macOS 10.7, the call
932fails because ``f()`` is no longer available.
933
934Clang is instructed to compile code for a minimum deployment version using
935the ``-target`` or ``-mtargetos`` command line arguments. For example,
936macOS 10.7 would be specified as ``-target x86_64-apple-macos10.7`` or
937``-mtargetos=macos10.7``. Variants like Mac Catalyst are specified as
938``-target arm64-apple-ios15.0-macabi`` or ``-mtargetos=ios15.0-macabi``
939
940The availability attribute is a comma-separated list starting with the
941platform name and then including clauses specifying important milestones in the
942declaration's lifetime (in any order) along with additional information. Those
943clauses can be:
944
945introduced=\ *version*
946 The first version in which this declaration was introduced.
947
948deprecated=\ *version*
949 The first version in which this declaration was deprecated, meaning that
950 users should migrate away from this API.
951
952obsoleted=\ *version*
953 The first version in which this declaration was obsoleted, meaning that it
954 was removed completely and can no longer be used.
955
956unavailable
957 This declaration is never available on this platform.
958
959message=\ *string-literal*
960 Additional message text that Clang will provide when emitting a warning or
961 error about use of a deprecated or obsoleted declaration. Useful to direct
962 users to replacement APIs.
963
964replacement=\ *string-literal*
965 Additional message text that Clang will use to provide Fix-It when emitting
966 a warning about use of a deprecated declaration. The Fix-It will replace
967 the deprecated declaration with the new declaration specified.
968
969environment=\ *identifier*
970 Target environment in which this declaration is available. If present,
971 the availability attribute applies only to targets with the same platform
972 and environment. The parameter is currently supported only in HLSL.
973
974Multiple availability attributes can be placed on a declaration, which may
975correspond to different platforms. For most platforms, the availability
976attribute with the platform corresponding to the target platform will be used;
977any others will be ignored. However, the availability for ``watchOS`` and
978``tvOS`` can be implicitly inferred from an ``iOS`` availability attribute.
979Any explicit availability attributes for those platforms are still preferred over
980the implicitly inferred availability attributes. If no availability attribute
981specifies availability for the current target platform, the availability
982attributes are ignored. Supported platforms are:
983
984``iOS``
985``macOS``
986``tvOS``
987``watchOS``
988``iOSApplicationExtension``
989``macOSApplicationExtension``
990``tvOSApplicationExtension``
991``watchOSApplicationExtension``
992``macCatalyst``
993``macCatalystApplicationExtension``
994``visionOS``
995``visionOSApplicationExtension``
996``driverkit``
997``anyAppleOS``
998``swift``
999``android``
1000``fuchsia``
1001``ohos``
1002``zos``
1003``ShaderModel``
1004
1005Some platforms have alias names:
1006
1007``ios``
1008``macos``
1009``macosx (deprecated)``
1010``tvos``
1011``watchos``
1012``ios_app_extension``
1013``macos_app_extension``
1014``macosx_app_extension (deprecated)``
1015``tvos_app_extension``
1016``watchos_app_extension``
1017``maccatalyst``
1018``maccatalyst_app_extension``
1019``visionos``
1020``visionos_app_extension``
1021``anyappleos``
1022``shadermodel``
1023
1024Supported environment names for the ShaderModel platform:
1025
1026``pixel``
1027``vertex``
1028``geometry``
1029``hull``
1030``domain``
1031``compute``
1032``raygeneration``
1033``intersection``
1034``anyhit``
1035``closesthit``
1036``miss``
1037``callable``
1038``mesh``
1039``amplification``
1040``library``
1041
1042The special platform ``anyAppleOS`` (alias: ``anyappleos``) is a shorthand that
1043applies the availability attribute to all Apple Darwin platforms. An explicit
1044platform-specific availability attribute takes precedence over an ``anyAppleOS``
1045attribute for that platform. Versions specified with ``anyAppleOS`` must be at
1046least 26.0, which is the first OS release where all supported Apple platforms
1047share a unified version number.
1048
1049A declaration can typically be used even when deploying back to a platform
1050version prior to when the declaration was introduced. When this happens, the
1051declaration is `weakly linked
1052<https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPFrameworks/Concepts/WeakLinking.html>`_,
1053as if the ``weak_import`` attribute were added to the declaration. A
1054weakly-linked declaration may or may not be present a run-time, and a program
1055can determine whether the declaration is present by checking whether the
1056address of that declaration is non-NULL.
1057
1058The flag ``strict`` disallows using API when deploying back to a
1059platform version prior to when the declaration was introduced. An
1060attempt to use such API before its introduction causes a hard error.
1061Weakly-linking is almost always a better API choice, since it allows
1062users to query availability at runtime.
1063
1064If there are multiple declarations of the same entity, the availability
1065attributes must either match on a per-platform basis or later
1066declarations must not have availability attributes for that
1067platform. For example:
1068
1069.. code-block:: c
1070
1071 void g(void) __attribute__((availability(macos,introduced=10.4)));
1072 void g(void) __attribute__((availability(macos,introduced=10.4))); // okay, matches
1073 void g(void) __attribute__((availability(ios,introduced=4.0))); // okay, adds a new platform
1074 void g(void); // okay, inherits both macos and ios availability from above.
1075 void g(void) __attribute__((availability(macos,introduced=10.5))); // error: mismatch
1076
1077When one method overrides another, the overriding method can be more widely available than the overridden method, e.g.,:
1078
1079.. code-block:: objc
1080
1081 @interface A
1082 - (id)method __attribute__((availability(macos,introduced=10.4)));
1083 - (id)method2 __attribute__((availability(macos,introduced=10.4)));
1084 @end
1085
1086 @interface B : A
1087 - (id)method __attribute__((availability(macos,introduced=10.3))); // okay: method moved into base class later
1088 - (id)method __attribute__((availability(macos,introduced=10.5))); // error: this method was available via the base class in 10.4
1089 @end
1090
1091Starting with the macOS 10.12 SDK, the ``API_AVAILABLE`` macro from
1092``<os/availability.h>`` can simplify the spelling:
1093
1094.. code-block:: objc
1095
1096 @interface A
1097 - (id)method API_AVAILABLE(macos(10.11)));
1098 - (id)otherMethod API_AVAILABLE(macos(10.11), ios(11.0));
1099 @end
1100
1101Availability attributes can also be applied using a ``#pragma clang attribute``.
1102Any explicit availability attribute whose platform corresponds to the target
1103platform is applied to a declaration regardless of the availability attributes
1104specified in the pragma. For example, in the code below,
1105``hasExplicitAvailabilityAttribute`` will use the ``macOS`` availability
1106attribute that is specified with the declaration, whereas
1107``getsThePragmaAvailabilityAttribute`` will use the ``macOS`` availability
1108attribute that is applied by the pragma.
1109
1110.. code-block:: c
1111
1112 #pragma clang attribute push (__attribute__((availability(macOS, introduced=10.12))), apply_to=function)
1113 void getsThePragmaAvailabilityAttribute(void);
1114 void hasExplicitAvailabilityAttribute(void) __attribute__((availability(macos,introduced=10.4)));
1115 #pragma clang attribute pop
1116
1117For platforms like ``watchOS`` and ``tvOS``, whose availability attributes can
1118be implicitly inferred from an ``iOS`` availability attribute, the logic is
1119slightly more complex. The explicit and the pragma-applied availability
1120attributes whose platform corresponds to the target platform are applied as
1121described in the previous paragraph. However, the implicitly inferred attributes
1122are applied to a declaration only when there is no explicit or pragma-applied
1123availability attribute whose platform corresponds to the target platform. For
1124example, the function below will receive the ``tvOS`` availability from the
1125pragma rather than using the inferred ``iOS`` availability from the declaration:
1126
1127.. code-block:: c
1128
1129 #pragma clang attribute push (__attribute__((availability(tvOS, introduced=12.0))), apply_to=function)
1130 void getsThePragmaTVOSAvailabilityAttribute(void) __attribute__((availability(iOS,introduced=11.0)));
1131 #pragma clang attribute pop
1132
1133The compiler is also able to apply implicitly inferred attributes from a pragma
1134as well. For example, when targeting ``tvOS``, the function below will receive
1135a ``tvOS`` availability attribute that is implicitly inferred from the ``iOS``
1136availability attribute applied by the pragma:
1137
1138.. code-block:: c
1139
1140 #pragma clang attribute push (__attribute__((availability(iOS, introduced=12.0))), apply_to=function)
1141 void infersTVOSAvailabilityFromPragma(void);
1142 #pragma clang attribute pop
1143
1144The implicit attributes that are inferred from explicitly specified attributes
1145whose platform corresponds to the target platform are applied to the declaration
1146even if there is an availability attribute that can be inferred from a pragma.
1147For example, the function below will receive the ``tvOS, introduced=11.0``
1148availability that is inferred from the attribute on the declaration rather than
1149inferring availability from the pragma:
1150
1151.. code-block:: c
1152
1153 #pragma clang attribute push (__attribute__((availability(iOS, unavailable))), apply_to=function)
1154 void infersTVOSAvailabilityFromAttributeNextToDeclaration(void)
1155 __attribute__((availability(iOS,introduced=11.0)));
1156 #pragma clang attribute pop
1157
1158Also see the documentation for `@available
1159<http://clang.llvm.org/docs/LanguageExtensions.html#objective-c-available>`_)reST";
1160
1161static const char AttrDoc_AvailableOnlyInDefaultEvalMethod[] = R"reST(No documentation.)reST";
1162
1163static const char AttrDoc_BPFFastCall[] = R"reST(Functions annotated with this attribute are likely to be inlined by BPF JIT.
1164It is assumed that inlined implementation uses less caller saved registers,
1165than a regular function.
1166Specifically, the following registers are likely to be preserved:
1167- ``R0`` if function return value is ``void``;
1168- ``R2-R5` if function takes 1 argument;
1169- ``R3-R5` if function takes 2 arguments;
1170- ``R4-R5` if function takes 3 arguments;
1171- ``R5`` if function takes 4 arguments;
1172
1173For such functions Clang generates code pattern that allows BPF JIT
1174to recognize and remove unnecessary spills and fills of the preserved
1175registers.)reST";
1176
1177static const char AttrDoc_BPFPreserveAccessIndex[] = R"reST(Clang supports the ``__attribute__((preserve_access_index))``
1178attribute for the BPF target. This attribute may be attached to a
1179struct or union declaration, where if -g is specified, it enables
1180preserving struct or union member access debuginfo indices of this
1181struct or union, similar to clang ``__builtin_preserve_access_index()``.)reST";
1182
1183static const char AttrDoc_BPFPreserveStaticOffset[] = R"reST(Clang supports the ``__attribute__((preserve_static_offset))``
1184attribute for the BPF target. This attribute may be attached to a
1185struct or union declaration. Reading or writing fields of types having
1186such annotation is guaranteed to generate LDX/ST/STX instruction with
1187offset corresponding to the field.
1188
1189For example:
1190
1191.. code-block:: c
1192
1193 struct foo {
1194 int a;
1195 int b;
1196 };
1197
1198 struct bar {
1199 int a;
1200 struct foo b;
1201 } __attribute__((preserve_static_offset));
1202
1203 void buz(struct bar *g) {
1204 g->b.a = 42;
1205 }
1206
1207The assignment to ``g``'s field would produce an ST instruction with
1208offset 8: ``*(u32)(r1 + 8) = 42;``.
1209
1210Without this attribute generated instructions might be different,
1211depending on optimizations behavior. E.g. the example above could be
1212rewritten as ``r1 += 8; *(u32)(r1 + 0) = 42;``.)reST";
1213
1214static const char AttrDoc_BTFDeclTag[] = R"reST(Clang supports the ``__attribute__((btf_decl_tag("ARGUMENT")))`` attribute for
1215all targets. This attribute may be attached to a struct/union, struct/union
1216field, function, function parameter, variable or typedef declaration. If -g is
1217specified, the ``ARGUMENT`` info will be preserved in IR and be emitted to
1218dwarf. For BPF targets, the ``ARGUMENT`` info will be emitted to .BTF ELF
1219section too.)reST";
1220
1221static const char AttrDoc_BTFTypeTag[] = R"reST(Clang supports the ``__attribute__((btf_type_tag("ARGUMENT")))`` attribute for
1222all targets. It only has effect when ``-g`` is specified on the command line.
1223
1224The attribute can be applied to a pointer type, in which case the tag is
1225associated with the pointee type, e.g.:
1226
1227.. code-block:: c
1228
1229 int __attribute__((btf_type_tag("tag"))) *p;
1230
1231It can also be applied to the underlying type of a typedef, in which case the
1232tag follows the typedef down to its base type, e.g.:
1233
1234.. code-block:: c
1235
1236 typedef struct foo __attribute__((btf_type_tag("tag"))) foo_t;
1237
1238The following is the corresponding btf:
1239
1240.. code-block::
1241
1242 ...
1243 [2] TYPE_TAG 'tag' type_id=4
1244 [3] TYPEDEF 'foo_t' type_id=2
1245 [4] STRUCT 'foo' size=4 vlen=1
1246 'c' type_id=5 bits_offset=0
1247 [5] INT 'int' size=4 bits_offset=0 nr_bits=32 encoding=SIGNED
1248 ...
1249
1250The attribute is currently silently ignored in any other position (note: this
1251scenario may be diagnosed in the future).
1252
1253The ``ARGUMENT`` string will be preserved in IR and emitted to DWARF for the
1254types used in variable declarations, function declarations, or typedef
1255declarations.
1256
1257For BPF targets, the ``ARGUMENT`` string will also be emitted to .BTF ELF
1258section.)reST";
1259
1260static const char AttrDoc_Blocking[] = R"reST(Declares that a function potentially blocks, and prevents any potential inference of ``nonblocking``
1261by the compiler.)reST";
1262
1263static const char AttrDoc_Blocks[] = R"reST(No documentation.)reST";
1264
1265static const char AttrDoc_Builtin[] = R"reST()reST";
1266
1267static const char AttrDoc_BuiltinAlias[] = R"reST(This attribute is used in the implementation of the C intrinsics.
1268It allows the C intrinsic functions to be declared using the names defined
1269in target builtins, and still be recognized as clang builtins equivalent to the
1270underlying name. For example, ``riscv_vector.h`` declares the function ``vadd``
1271with ``__attribute__((clang_builtin_alias(__builtin_rvv_vadd_vv_i8m1)))``.
1272This ensures that both functions are recognized as that clang builtin,
1273and in the latter case, the choice of which builtin to identify the
1274function as can be deferred until after overload resolution.
1275
1276This attribute can only be used to set up the aliases for certain ARM/RISC-V
1277C intrinsic functions; it is intended for use only inside ``arm_*.h`` and
1278``riscv_*.h`` and is not a general mechanism for declaring arbitrary aliases
1279for clang builtin functions.)reST";
1280
1281static const char AttrDoc_C11NoReturn[] = R"reST(A function declared as ``_Noreturn`` shall not return to its caller. The
1282compiler will generate a diagnostic for a function declared as ``_Noreturn``
1283that appears to be capable of returning to its caller. Despite being a type
1284specifier, the ``_Noreturn`` attribute cannot be specified on a function
1285pointer type.)reST";
1286
1287static const char AttrDoc_CDecl[] = R"reST(No documentation.)reST";
1288
1289static const char AttrDoc_CFAuditedTransfer[] = R"reST(No documentation.)reST";
1290
1291static const char AttrDoc_CFConsumed[] = R"reST(The behavior of a function with respect to reference counting for Foundation
1292(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
1293convention (e.g. functions starting with "get" are assumed to return at
1294``+0``).
1295
1296It can be overridden using a family of the following attributes. In
1297Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
1298a function communicates that the object is returned at ``+1``, and the caller
1299is responsible for freeing it.
1300Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
1301specifies that the object is returned at ``+0`` and the ownership remains with
1302the callee.
1303The annotation ``__attribute__((ns_consumes_self))`` specifies that
1304the Objective-C method call consumes the reference to ``self``, e.g. by
1305attaching it to a supplied parameter.
1306Additionally, parameters can have an annotation
1307``__attribute__((ns_consumed))``, which specifies that passing an owned object
1308as that parameter effectively transfers the ownership, and the caller is no
1309longer responsible for it.
1310These attributes affect code generation when interacting with ARC code, and
1311they are used by the Clang Static Analyzer.
1312
1313In C programs using CoreFoundation, a similar set of attributes:
1314``__attribute__((cf_returns_not_retained))``,
1315``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
1316have the same respective semantics when applied to CoreFoundation objects.
1317These attributes affect code generation when interacting with ARC code, and
1318they are used by the Clang Static Analyzer.
1319
1320Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
1321the same attribute family is present:
1322``__attribute__((os_returns_not_retained))``,
1323``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
1324with the same respective semantics.
1325Similar to ``__attribute__((ns_consumes_self))``,
1326``__attribute__((os_consumes_this))`` specifies that the method call consumes
1327the reference to "this" (e.g., when attaching it to a different object supplied
1328as a parameter).
1329Out parameters (parameters the function is meant to write into,
1330either via pointers-to-pointers or references-to-pointers)
1331may be annotated with ``__attribute__((os_returns_retained))``
1332or ``__attribute__((os_returns_not_retained))`` which specifies that the object
1333written into the out parameter should (or respectively should not) be released
1334after use.
1335Since often out parameters may or may not be written depending on the exit
1336code of the function,
1337annotations ``__attribute__((os_returns_retained_on_zero))``
1338and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
1339an out parameter at ``+1`` is written if and only if the function returns a zero
1340(respectively non-zero) error code.
1341Observe that return-code-dependent out parameter annotations are only
1342available for retained out parameters, as non-retained object do not have to be
1343released by the callee.
1344These attributes are only used by the Clang Static Analyzer.
1345
1346The family of attributes ``X_returns_X_retained`` can be added to functions,
1347C++ methods, and Objective-C methods and properties.
1348Attributes ``X_consumed`` can be added to parameters of methods, functions,
1349and Objective-C methods.)reST";
1350
1351static const char AttrDoc_CFGuard[] = R"reST(Code can indicate CFG checks are not wanted with the ``__declspec(guard(nocf))``
1352attribute. This directs the compiler to not insert any CFG checks for the entire
1353function. This approach is typically used only sparingly in specific situations
1354where the programmer has manually inserted "CFG-equivalent" protection. The
1355programmer knows that they are calling through some read-only function table
1356whose address is obtained through read-only memory references and for which the
1357index is masked to the function table limit. This approach may also be applied
1358to small wrapper functions that are not inlined and that do nothing more than
1359make a call through a function pointer. Since incorrect usage of this directive
1360can compromise the security of CFG, the programmer must be very careful using
1361the directive. Typically, this usage is limited to very small functions that
1362only call one function.
1363
1364`Control Flow Guard documentation <https://docs.microsoft.com/en-us/windows/win32/secbp/pe-metadata>`)reST";
1365
1366static const char AttrDoc_CFICanonicalJumpTable[] = R"reST(Use ``__attribute__((cfi_canonical_jump_table))`` on a function declaration to
1367make the function's CFI jump table canonical. See :ref:`the CFI documentation
1368<cfi-canonical-jump-tables>` for more details.)reST";
1369
1370static const char AttrDoc_CFISalt[] = R"reST(The ``cfi_salt`` attribute specifies a string literal that is used as a salt
1371for Control-Flow Integrity (CFI) checks to distinguish between functions with
1372the same type signature. This attribute can be applied to function declarations,
1373function definitions, and function pointer typedefs.
1374
1375The attribute prevents function pointers from being replaced with pointers to
1376functions that have a compatible type, which can be a CFI bypass vector.
1377
1378**Syntax:**
1379
1380* GNU-style: ``__attribute__((cfi_salt("<salt_string>")))``
1381* C++11-style: ``[[clang::cfi_salt("<salt_string>")]]``
1382
1383**Usage:**
1384
1385The attribute takes a single string literal argument that serves as the salt.
1386Functions or function types with different salt values will have different CFI
1387hashes, even if they have identical type signatures.
1388
1389**Motivation:**
1390
1391In large codebases like the Linux kernel, there are often hundreds of functions
1392with identical type signatures that are called indirectly:
1393
1394.. code-block::
1395
1396 1662 functions with void (*)(void)
1397 1179 functions with int (*)(void)
1398 ...
1399
1400By salting the CFI hashes, you can make CFI more robust by ensuring that
1401functions intended for different purposes have distinct CFI identities.
1402
1403**Type Compatibility:**
1404
1405* Functions with different salt values are considered to have incompatible types
1406* Function pointers with different salt values cannot be assigned to each other
1407* All declarations of the same function must use the same salt value
1408
1409**Example:**
1410
1411.. code-block:: c
1412
1413 // Header file - define convenience macros
1414 #define __cfi_salt(s) __attribute__((cfi_salt(s)))
1415
1416 // Typedef for regular function pointers
1417 typedef int (*fptr_t)(void);
1418
1419 // Typedef for salted function pointers
1420 typedef int (*fptr_salted_t)(void) __cfi_salt("pepper");
1421
1422 struct widget_ops {
1423 fptr_t init; // Regular CFI
1424 fptr_salted_t exec; // Salted CFI
1425 fptr_t cleanup; // Regular CFI
1426 };
1427
1428 // Function implementations
1429 static int widget_init(void) { return 0; }
1430 static int widget_exec(void) __cfi_salt("pepper") { return 1; }
1431 static int widget_cleanup(void) { return 0; }
1432
1433 static struct widget_ops ops = {
1434 .init = widget_init, // OK - compatible types
1435 .exec = widget_exec, // OK - both use "pepper" salt
1436 .cleanup = widget_cleanup // OK - compatible types
1437 };
1438
1439 // Using C++11 attribute syntax
1440 void secure_callback(void) [[clang::cfi_salt("secure")]];
1441
1442 // This would cause a compilation error:
1443 // fptr_t bad_ptr = widget_exec; // Error: incompatible types
1444
1445**Notes:**
1446
1447* The salt string can contain non-NULL ASCII characters, including spaces and
1448 quotes
1449* This attribute only applies to function types; using it on non-function
1450 types will generate a warning
1451* All declarations and definitions of the same function must use identical
1452 salt values
1453* The attribute affects type compatibility during compilation and CFI hash
1454 generation during code generation)reST";
1455
1456static const char AttrDoc_CFIUncheckedCallee[] = R"reST(``cfi_unchecked_callee`` is a function type attribute which prevents the compiler from instrumenting
1457`Control Flow Integrity <https://clang.llvm.org/docs/ControlFlowIntegrity.html>`_ checks on indirect
1458function calls. This also includes control flow checks added by
1459`-fsanitize=function <https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#available-checks>`.
1460Specifically, the attribute has the following semantics:
1461
14621. Indirect calls to a function type with this attribute will not be instrumented with CFI. That is,
1463 the indirect call will not be checked. Note that this only changes the behavior for indirect calls
1464 on pointers to function types having this attribute. It does not prevent all indirect function calls
1465 for a given type from being checked.
14662. All direct references to a function whose type has this attribute will always reference the
1467 function definition rather than an entry in the CFI jump table.
14683. When a pointer to a function with this attribute is implicitly cast to a pointer to a function
1469 without this attribute, the compiler will give a warning saying this attribute is discarded. This
1470 warning can be silenced with an explicit cast. Note an explicit cast just disables the warning, so
1471 direct references to a function with a ``cfi_unchecked_callee`` attribute will still reference the
1472 function definition rather than the CFI jump table.
1473
1474.. code-block:: c
1475
1476 #define CFI_UNCHECKED_CALLEE __attribute__((cfi_unchecked_callee))
1477
1478 void no_cfi() CFI_UNCHECKED_CALLEE {}
1479
1480 void (*with_cfi)() = no_cfi; // warning: implicit conversion discards `cfi_unchecked_callee` attribute.
1481 // `with_cfi` also points to the actual definition of `no_cfi` rather than
1482 // its jump table entry.
1483
1484 void invoke(void (CFI_UNCHECKED_CALLEE *func)()) {
1485 func(); // CFI will not instrument this indirect call.
1486
1487 void (*func2)() = func; // warning: implicit conversion discards `cfi_unchecked_callee` attribute.
1488
1489 func2(); // CFI will instrument this indirect call. Users should be careful however because if this
1490 // references a function with type `cfi_unchecked_callee`, then the CFI check may incorrectly
1491 // fail because the reference will be to the function definition rather than the CFI jump
1492 // table entry.
1493 }
1494
1495This attribute can only be applied on functions or member functions. This attribute can be a good
1496alternative to ``no_sanitize("cfi")`` if you only want to disable innstrumentation for specific indirect
1497calls rather than applying ``no_sanitize("cfi")`` on the whole function containing indirect call. Note
1498that ``cfi_unchecked_attribute`` is a type attribute doesn't disable CFI instrumentation on a function
1499body.)reST";
1500
1501static const char AttrDoc_CFReturnsNotRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
1502(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
1503convention (e.g. functions starting with "get" are assumed to return at
1504``+0``).
1505
1506It can be overridden using a family of the following attributes. In
1507Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
1508a function communicates that the object is returned at ``+1``, and the caller
1509is responsible for freeing it.
1510Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
1511specifies that the object is returned at ``+0`` and the ownership remains with
1512the callee.
1513The annotation ``__attribute__((ns_consumes_self))`` specifies that
1514the Objective-C method call consumes the reference to ``self``, e.g. by
1515attaching it to a supplied parameter.
1516Additionally, parameters can have an annotation
1517``__attribute__((ns_consumed))``, which specifies that passing an owned object
1518as that parameter effectively transfers the ownership, and the caller is no
1519longer responsible for it.
1520These attributes affect code generation when interacting with ARC code, and
1521they are used by the Clang Static Analyzer.
1522
1523In C programs using CoreFoundation, a similar set of attributes:
1524``__attribute__((cf_returns_not_retained))``,
1525``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
1526have the same respective semantics when applied to CoreFoundation objects.
1527These attributes affect code generation when interacting with ARC code, and
1528they are used by the Clang Static Analyzer.
1529
1530Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
1531the same attribute family is present:
1532``__attribute__((os_returns_not_retained))``,
1533``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
1534with the same respective semantics.
1535Similar to ``__attribute__((ns_consumes_self))``,
1536``__attribute__((os_consumes_this))`` specifies that the method call consumes
1537the reference to "this" (e.g., when attaching it to a different object supplied
1538as a parameter).
1539Out parameters (parameters the function is meant to write into,
1540either via pointers-to-pointers or references-to-pointers)
1541may be annotated with ``__attribute__((os_returns_retained))``
1542or ``__attribute__((os_returns_not_retained))`` which specifies that the object
1543written into the out parameter should (or respectively should not) be released
1544after use.
1545Since often out parameters may or may not be written depending on the exit
1546code of the function,
1547annotations ``__attribute__((os_returns_retained_on_zero))``
1548and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
1549an out parameter at ``+1`` is written if and only if the function returns a zero
1550(respectively non-zero) error code.
1551Observe that return-code-dependent out parameter annotations are only
1552available for retained out parameters, as non-retained object do not have to be
1553released by the callee.
1554These attributes are only used by the Clang Static Analyzer.
1555
1556The family of attributes ``X_returns_X_retained`` can be added to functions,
1557C++ methods, and Objective-C methods and properties.
1558Attributes ``X_consumed`` can be added to parameters of methods, functions,
1559and Objective-C methods.)reST";
1560
1561static const char AttrDoc_CFReturnsRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
1562(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
1563convention (e.g. functions starting with "get" are assumed to return at
1564``+0``).
1565
1566It can be overridden using a family of the following attributes. In
1567Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
1568a function communicates that the object is returned at ``+1``, and the caller
1569is responsible for freeing it.
1570Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
1571specifies that the object is returned at ``+0`` and the ownership remains with
1572the callee.
1573The annotation ``__attribute__((ns_consumes_self))`` specifies that
1574the Objective-C method call consumes the reference to ``self``, e.g. by
1575attaching it to a supplied parameter.
1576Additionally, parameters can have an annotation
1577``__attribute__((ns_consumed))``, which specifies that passing an owned object
1578as that parameter effectively transfers the ownership, and the caller is no
1579longer responsible for it.
1580These attributes affect code generation when interacting with ARC code, and
1581they are used by the Clang Static Analyzer.
1582
1583In C programs using CoreFoundation, a similar set of attributes:
1584``__attribute__((cf_returns_not_retained))``,
1585``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
1586have the same respective semantics when applied to CoreFoundation objects.
1587These attributes affect code generation when interacting with ARC code, and
1588they are used by the Clang Static Analyzer.
1589
1590Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
1591the same attribute family is present:
1592``__attribute__((os_returns_not_retained))``,
1593``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
1594with the same respective semantics.
1595Similar to ``__attribute__((ns_consumes_self))``,
1596``__attribute__((os_consumes_this))`` specifies that the method call consumes
1597the reference to "this" (e.g., when attaching it to a different object supplied
1598as a parameter).
1599Out parameters (parameters the function is meant to write into,
1600either via pointers-to-pointers or references-to-pointers)
1601may be annotated with ``__attribute__((os_returns_retained))``
1602or ``__attribute__((os_returns_not_retained))`` which specifies that the object
1603written into the out parameter should (or respectively should not) be released
1604after use.
1605Since often out parameters may or may not be written depending on the exit
1606code of the function,
1607annotations ``__attribute__((os_returns_retained_on_zero))``
1608and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
1609an out parameter at ``+1`` is written if and only if the function returns a zero
1610(respectively non-zero) error code.
1611Observe that return-code-dependent out parameter annotations are only
1612available for retained out parameters, as non-retained object do not have to be
1613released by the callee.
1614These attributes are only used by the Clang Static Analyzer.
1615
1616The family of attributes ``X_returns_X_retained`` can be added to functions,
1617C++ methods, and Objective-C methods and properties.
1618Attributes ``X_consumed`` can be added to parameters of methods, functions,
1619and Objective-C methods.)reST";
1620
1621static const char AttrDoc_CFUnknownTransfer[] = R"reST(No documentation.)reST";
1622
1623static const char AttrDoc_CPUDispatch[] = R"reST(The ``cpu_specific`` and ``cpu_dispatch`` attributes are used to define and
1624resolve multiversioned functions. This form of multiversioning provides a
1625mechanism for declaring versions across translation units and manually
1626specifying the resolved function list. A specified CPU defines a set of minimum
1627features that are required for the function to be called. The result of this is
1628that future processors execute the most restrictive version of the function the
1629new processor can execute.
1630
1631In addition, unlike the ICC implementation of this feature, the selection of the
1632version does not consider the manufacturer or microarchitecture of the processor.
1633It tests solely the list of features that are both supported by the specified
1634processor and present in the compiler-rt library. This can be surprising at times,
1635as the runtime processor may be from a completely different manufacturer, as long
1636as it supports the same feature set.
1637
1638This can additionally be surprising, as some processors are indistringuishable from
1639others based on the list of testable features. When this happens, the variant
1640is selected in an unspecified manner.
1641
1642Function versions are defined with ``cpu_specific``, which takes one or more CPU
1643names as a parameter. For example:
1644
1645.. code-block:: c
1646
1647 // Declares and defines the ivybridge version of single_cpu.
1648 __attribute__((cpu_specific(ivybridge)))
1649 void single_cpu(void){}
1650
1651 // Declares and defines the atom version of single_cpu.
1652 __attribute__((cpu_specific(atom)))
1653 void single_cpu(void){}
1654
1655 // Declares and defines both the ivybridge and atom version of multi_cpu.
1656 __attribute__((cpu_specific(ivybridge, atom)))
1657 void multi_cpu(void){}
1658
1659A dispatching (or resolving) function can be declared anywhere in a project's
1660source code with ``cpu_dispatch``. This attribute takes one or more CPU names
1661as a parameter (like ``cpu_specific``). Functions marked with ``cpu_dispatch``
1662are not expected to be defined, only declared. If such a marked function has a
1663definition, any side effects of the function are ignored; trivial function
1664bodies are permissible for ICC compatibility.
1665
1666.. code-block:: c
1667
1668 // Creates a resolver for single_cpu above.
1669 __attribute__((cpu_dispatch(ivybridge, atom)))
1670 void single_cpu(void){}
1671
1672 // Creates a resolver for multi_cpu, but adds a 3rd version defined in another
1673 // translation unit.
1674 __attribute__((cpu_dispatch(ivybridge, atom, sandybridge)))
1675 void multi_cpu(void){}
1676
1677Note that it is possible to have a resolving function that dispatches based on
1678more or fewer options than are present in the program. Specifying fewer will
1679result in the omitted options not being considered during resolution. Specifying
1680a version for resolution that isn't defined in the program will result in a
1681linking failure.
1682
1683It is also possible to specify a CPU name of ``generic`` which will be resolved
1684if the executing processor doesn't satisfy the features required in the CPU
1685name. The behavior of a program executing on a processor that doesn't satisfy
1686any option of a multiversioned function is undefined.)reST";
1687
1688static const char AttrDoc_CPUSpecific[] = R"reST(The ``cpu_specific`` and ``cpu_dispatch`` attributes are used to define and
1689resolve multiversioned functions. This form of multiversioning provides a
1690mechanism for declaring versions across translation units and manually
1691specifying the resolved function list. A specified CPU defines a set of minimum
1692features that are required for the function to be called. The result of this is
1693that future processors execute the most restrictive version of the function the
1694new processor can execute.
1695
1696In addition, unlike the ICC implementation of this feature, the selection of the
1697version does not consider the manufacturer or microarchitecture of the processor.
1698It tests solely the list of features that are both supported by the specified
1699processor and present in the compiler-rt library. This can be surprising at times,
1700as the runtime processor may be from a completely different manufacturer, as long
1701as it supports the same feature set.
1702
1703This can additionally be surprising, as some processors are indistringuishable from
1704others based on the list of testable features. When this happens, the variant
1705is selected in an unspecified manner.
1706
1707Function versions are defined with ``cpu_specific``, which takes one or more CPU
1708names as a parameter. For example:
1709
1710.. code-block:: c
1711
1712 // Declares and defines the ivybridge version of single_cpu.
1713 __attribute__((cpu_specific(ivybridge)))
1714 void single_cpu(void){}
1715
1716 // Declares and defines the atom version of single_cpu.
1717 __attribute__((cpu_specific(atom)))
1718 void single_cpu(void){}
1719
1720 // Declares and defines both the ivybridge and atom version of multi_cpu.
1721 __attribute__((cpu_specific(ivybridge, atom)))
1722 void multi_cpu(void){}
1723
1724A dispatching (or resolving) function can be declared anywhere in a project's
1725source code with ``cpu_dispatch``. This attribute takes one or more CPU names
1726as a parameter (like ``cpu_specific``). Functions marked with ``cpu_dispatch``
1727are not expected to be defined, only declared. If such a marked function has a
1728definition, any side effects of the function are ignored; trivial function
1729bodies are permissible for ICC compatibility.
1730
1731.. code-block:: c
1732
1733 // Creates a resolver for single_cpu above.
1734 __attribute__((cpu_dispatch(ivybridge, atom)))
1735 void single_cpu(void){}
1736
1737 // Creates a resolver for multi_cpu, but adds a 3rd version defined in another
1738 // translation unit.
1739 __attribute__((cpu_dispatch(ivybridge, atom, sandybridge)))
1740 void multi_cpu(void){}
1741
1742Note that it is possible to have a resolving function that dispatches based on
1743more or fewer options than are present in the program. Specifying fewer will
1744result in the omitted options not being considered during resolution. Specifying
1745a version for resolution that isn't defined in the program will result in a
1746linking failure.
1747
1748It is also possible to specify a CPU name of ``generic`` which will be resolved
1749if the executing processor doesn't satisfy the features required in the CPU
1750name. The behavior of a program executing on a processor that doesn't satisfy
1751any option of a multiversioned function is undefined.)reST";
1752
1753static const char AttrDoc_CUDAClusterDims[] = R"reST(In CUDA/HIP programming, the ``cluster_dims`` attribute, conventionally exposed as the
1754``__cluster_dims__`` macro, can be applied to a kernel function to set the dimensions of a
1755thread block cluster, which is an optional level of hierarchy and made up of thread blocks.
1756``__cluster_dims__`` defines the cluster size as ``(X, Y, Z)``, where each value is the number
1757of thread blocks in that dimension. The ``cluster_dims`` and `no_cluster`` attributes are
1758mutually exclusive.
1759
1760.. code::
1761
1762 __global__ __cluster_dims__(2, 1, 1) void kernel(...) {
1763 ...
1764 })reST";
1765
1766static const char AttrDoc_CUDAConstant[] = R"reST(No documentation.)reST";
1767
1768static const char AttrDoc_CUDADevice[] = R"reST(No documentation.)reST";
1769
1770static const char AttrDoc_CUDADeviceBuiltinSurfaceType[] = R"reST(The ``device_builtin_surface_type`` attribute can be applied to a class
1771template when declaring the surface reference. A surface reference variable
1772could be accessed on the host side and, on the device side, might be translated
1773into an internal surface object, which is established through surface bind and
1774unbind runtime APIs.)reST";
1775
1776static const char AttrDoc_CUDADeviceBuiltinTextureType[] = R"reST(The ``device_builtin_texture_type`` attribute can be applied to a class
1777template when declaring the texture reference. A texture reference variable
1778could be accessed on the host side and, on the device side, might be translated
1779into an internal texture object, which is established through texture bind and
1780unbind runtime APIs.)reST";
1781
1782static const char AttrDoc_CUDAGlobal[] = R"reST(No documentation.)reST";
1783
1784static const char AttrDoc_CUDAGridConstant[] = R"reST(The ``__grid_constant__`` attribute can be applied to a ``const``-qualified kernel
1785function argument and allows compiler to take the address of that argument without
1786making a copy. The argument applies to sm_70 or newer GPUs, during compilation
1787with CUDA-11.7(PTX 7.7) or newer, and is ignored otherwise.)reST";
1788
1789static const char AttrDoc_CUDAHost[] = R"reST(No documentation.)reST";
1790
1791static const char AttrDoc_CUDAInvalidTarget[] = R"reST()reST";
1792
1793static const char AttrDoc_CUDALaunchBounds[] = R"reST(No documentation.)reST";
1794
1795static const char AttrDoc_CUDANoCluster[] = R"reST(In CUDA/HIP programming, a kernel function can still be launched with the cluster feature enabled
1796at runtime, even without being annotated with ``__cluster_dims__``. The LLVM/Clang-exclusive
1797``no_cluster`` attribute, conventionally exposed as the ``__no_cluster__`` macro, can be applied to
1798a kernel function to explicitly indicate that the cluster feature will not be enabled either at
1799compile time or at kernel launch time. This allows the compiler to apply certain optimizations
1800without assuming that clustering could be enabled at runtime. It is undefined behavior to launch a
1801kernel annotated with ``__no_cluster__`` if the cluster feature is enabled at runtime.
1802The ``cluster_dims`` and ``no_cluster`` attributes are mutually exclusive.
1803
1804.. code::
1805
1806 __global__ __no_cluster__ void kernel(...) {
1807 ...
1808 })reST";
1809
1810static const char AttrDoc_CUDAShared[] = R"reST(No documentation.)reST";
1811
1812static const char AttrDoc_CXX11NoReturn[] = R"reST(A function declared as ``[[noreturn]]`` shall not return to its caller. The
1813compiler will generate a diagnostic for a function declared as ``[[noreturn]]``
1814that appears to be capable of returning to its caller.
1815
1816The ``[[_Noreturn]]`` spelling is deprecated and only exists to ease code
1817migration for code using ``[[noreturn]]`` after including ``<stdnoreturn.h>``.)reST";
1818
1819static const char AttrDoc_CXXAssume[] = R"reST(The ``assume`` attribute is used to indicate to the optimizer that a
1820certain condition is assumed to be true at a certain point in the
1821program. If this condition is violated at runtime, the behavior is
1822undefined. ``assume`` can only be applied to a null statement.
1823
1824Different optimisers are likely to react differently to the presence of
1825this attribute; in some cases, adding ``assume`` may affect performance
1826negatively. It should be used with parsimony and care.
1827
1828Example:
1829
1830.. code-block:: c++
1831
1832 int f(int x, int y) {
1833 [[assume(x == 27)]];
1834 [[assume(x == y)]];
1835 return y + 1; // May be optimised to `return 28`.
1836 })reST";
1837
1838static const char AttrDoc_CallableWhen[] = R"reST(Use ``__attribute__((callable_when(...)))`` to indicate what states a method
1839may be called in. Valid states are unconsumed, consumed, or unknown. Each
1840argument to this attribute must be a quoted string. E.g.:
1841
1842``__attribute__((callable_when("unconsumed", "unknown")))``)reST";
1843
1844static const char AttrDoc_Callback[] = R"reST(The ``callback`` attribute specifies that the annotated function may invoke the
1845specified callback zero or more times. The callback, as well as the passed
1846arguments, are identified by their parameter name or position (starting with
18471!) in the annotated function. The first position in the attribute identifies
1848the callback callee, the following positions declare describe its arguments.
1849The callback callee is required to be callable with the number, and order, of
1850the specified arguments. The index ``0``, or the identifier ``this``, is used to
1851represent an implicit "this" pointer in class methods. If there is no implicit
1852"this" pointer it shall not be referenced. The index '-1', or the name "__",
1853represents an unknown callback callee argument. This can be a value which is
1854not present in the declared parameter list, or one that is, but is potentially
1855inspected, captured, or modified. Parameter names and indices can be mixed in
1856the callback attribute.
1857
1858The ``callback`` attribute, which is directly translated to ``callback``
1859metadata <http://llvm.org/docs/LangRef.html#callback-metadata>, make the
1860connection between the call to the annotated function and the callback callee.
1861This can enable interprocedural optimizations which were otherwise impossible.
1862If a function parameter is mentioned in the ``callback`` attribute, through its
1863position, it is undefined if that parameter is used for anything other than the
1864actual callback. Inspected, captured, or modified parameters shall not be
1865listed in the ``callback`` metadata.
1866
1867Example encodings for the callback performed by ``pthread_create`` are shown
1868below. The explicit attribute annotation indicates that the third parameter
1869(``start_routine``) is called zero or more times by the ``pthread_create`` function,
1870and that the fourth parameter (``arg``) is passed along. Note that the callback
1871behavior of ``pthread_create`` is automatically recognized by Clang. In addition,
1872the declarations of ``__kmpc_fork_teams`` and ``__kmpc_fork_call``, generated for
1873``#pragma omp target teams`` and ``#pragma omp parallel``, respectively, are also
1874automatically recognized as broker functions. Further functions might be added
1875in the future.
1876
1877 .. code-block:: c
1878
1879 __attribute__((callback (start_routine, arg)))
1880 int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
1881 void *(*start_routine) (void *), void *arg);
1882
1883 __attribute__((callback (3, 4)))
1884 int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
1885 void *(*start_routine) (void *), void *arg);)reST";
1886
1887static const char AttrDoc_CalledOnce[] = R"reST(The ``called_once`` attribute specifies that the annotated function or method
1888parameter is invoked exactly once on all execution paths. It only applies
1889to parameters with function-like types, i.e. function pointers or blocks. This
1890concept is particularly useful for asynchronous programs.
1891
1892Clang implements a check for ``called_once`` parameters,
1893``-Wcalled-once-parameter``. It is on by default and finds the following
1894violations:
1895
1896* Parameter is not called at all.
1897
1898* Parameter is called more than once.
1899
1900* Parameter is not called on one of the execution paths.
1901
1902In the latter case, Clang pinpoints the path where parameter is not invoked
1903by showing the control-flow statement where the path diverges.
1904
1905.. code-block:: objc
1906
1907 void fooWithCallback(void (^callback)(void) __attribute__((called_once))) {
1908 if (somePredicate()) {
1909 ...
1910 callback();
1911 } else {
1912 callback(); // OK: callback is called on every path
1913 }
1914 }
1915
1916 void barWithCallback(void (^callback)(void) __attribute__((called_once))) {
1917 if (somePredicate()) {
1918 ...
1919 callback(); // note: previous call is here
1920 }
1921 callback(); // warning: callback is called twice
1922 }
1923
1924 void foobarWithCallback(void (^callback)(void) __attribute__((called_once))) {
1925 if (somePredicate()) { // warning: callback is not called when condition is false
1926 ...
1927 callback();
1928 }
1929 }
1930
1931This attribute is useful for API developers who want to double-check if they
1932implemented their method correctly.)reST";
1933
1934static const char AttrDoc_Capability[] = R"reST(No documentation.)reST";
1935
1936static const char AttrDoc_CapturedRecord[] = R"reST()reST";
1937
1938static const char AttrDoc_CarriesDependency[] = R"reST(The ``carries_dependency`` attribute specifies dependency propagation into and
1939out of functions.
1940
1941When specified on a function or Objective-C method, the ``carries_dependency``
1942attribute means that the return value carries a dependency out of the function,
1943so that the implementation need not constrain ordering upon return from that
1944function. Implementations of the function and its caller may choose to preserve
1945dependencies instead of emitting memory ordering instructions such as fences.
1946
1947Note, this attribute does not change the meaning of the program, but may result
1948in generation of more efficient code.)reST";
1949
1950static const char AttrDoc_Cleanup[] = R"reST(This attribute allows a function to be run when a local variable goes out of
1951scope. The attribute takes the identifier of a function with a parameter type
1952that is a pointer to the type with the attribute.
1953
1954.. code-block:: c
1955
1956 static void foo (int *) { ... }
1957 static void bar (int *) { ... }
1958 void baz (void) {
1959 int x __attribute__((cleanup(foo)));
1960 {
1961 int y __attribute__((cleanup(bar)));
1962 }
1963 }
1964
1965The above example will result in a call to ``bar`` being passed the address of
1966``y`` when ``y`` goes out of scope, then a call to ``foo`` being passed the
1967address of ``x`` when ``x`` goes out of scope. If two or more variables share
1968the same scope, their ``cleanup`` callbacks are invoked in the reverse order
1969the variables were declared in. It is not possible to check the return value
1970(if any) of these ``cleanup`` callback functions.)reST";
1971
1972static 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).
1973
1974.. code-block:: c
1975
1976 void __attribute__((clspv_libclc_builtin)) libclc_builtin() {}
1977
1978.. _`clspv`: https://github.com/google/clspv
1979.. _`libclc`: https://libclc.llvm.org)reST";
1980
1981static const char AttrDoc_CmseNSCall[] = R"reST(This attribute declares a non-secure function type. When compiling for secure
1982state, a call to such a function would switch from secure to non-secure state.
1983All non-secure function calls must happen only through a function pointer, and
1984a non-secure function type should only be used as a base type of a pointer.
1985See `ARMv8-M Security Extensions: Requirements on Development
1986Tools - Engineering Specification Documentation
1987<https://developer.arm.com/docs/ecm0359818/latest/>`_ for more information.)reST";
1988
1989static const char AttrDoc_CmseNSEntry[] = R"reST(This attribute declares a function that can be called from non-secure state, or
1990from secure state. Entering from and returning to non-secure state would switch
1991to and from secure state, respectively, and prevent flow of information
1992to non-secure state, except via return values. See `ARMv8-M Security Extensions:
1993Requirements on Development Tools - Engineering Specification Documentation
1994<https://developer.arm.com/docs/ecm0359818/latest/>`_ for more information.)reST";
1995
1996static const char AttrDoc_CodeAlign[] = R"reST(The ``clang::code_align(N)`` attribute applies to a loop and specifies the byte
1997alignment for a loop. The attribute accepts a positive integer constant
1998initialization expression indicating the number of bytes for the minimum
1999alignment boundary. Its value must be a power of 2, between 1 and 4096
2000(inclusive).
2001
2002.. code-block:: c++
2003
2004 void foo() {
2005 int var = 0;
2006 [[clang::code_align(16)]] for (int i = 0; i < 10; ++i) var++;
2007 }
2008
2009 void Array(int *array, size_t n) {
2010 [[clang::code_align(64)]] for (int i = 0; i < n; ++i) array[i] = 0;
2011 }
2012
2013 void count () {
2014 int a1[10], int i = 0;
2015 [[clang::code_align(32)]] while (i < 10) { a1[i] += 3; }
2016 }
2017
2018 void check() {
2019 int a = 10;
2020 [[clang::code_align(8)]] do {
2021 a = a + 1;
2022 } while (a < 20);
2023 }
2024
2025 template<int A>
2026 void func() {
2027 [[clang::code_align(A)]] for(;;) { }
2028 })reST";
2029
2030static const char AttrDoc_CodeModel[] = R"reST(The ``model`` attribute allows overriding the translation unit's
2031code model (specified by ``-mcmodel``) for a specific global variable.
2032
2033On LoongArch, allowed values are "normal", "medium", "extreme".
2034
2035On x86-64, allowed values are ``"small"`` and ``"large"``. ``"small"`` is
2036roughly equivalent to ``-mcmodel=small``, meaning the global is considered
2037"small" placed closer to the ``.text`` section relative to "large" globals, and
2038to prefer using 32-bit relocations to access the global. ``"large"`` is roughly
2039equivalent to ``-mcmodel=large``, meaning the global is considered "large" and
2040placed further from the ``.text`` section relative to "small" globals, and
204164-bit relocations must be used to access the global.)reST";
2042
2043static const char AttrDoc_CodeSeg[] = R"reST(The ``__declspec(code_seg)`` attribute enables the placement of code into separate
2044named segments that can be paged or locked in memory individually. This attribute
2045is used to control the placement of instantiated templates and compiler-generated
2046code. See the documentation for `__declspec(code_seg)`_ on MSDN.
2047
2048.. _`__declspec(code_seg)`: http://msdn.microsoft.com/en-us/library/dn636922.aspx)reST";
2049
2050static const char AttrDoc_Cold[] = R"reST(``__attribute__((cold))`` marks a function as cold, as a manual alternative to PGO hotness data.
2051If PGO data is available, the profile count based hotness overrides the ``__attribute__((cold))`` annotation (unlike ``__attribute__((hot))``).)reST";
2052
2053static const char AttrDoc_Common[] = R"reST(No documentation.)reST";
2054
2055static const char AttrDoc_Const[] = R"reST(No documentation.)reST";
2056
2057static const char AttrDoc_ConstInit[] = R"reST(This attribute specifies that the variable to which it is attached is intended
2058to have a `constant initializer <http://en.cppreference.com/w/cpp/language/constant_initialization>`_
2059according to the rules of [basic.start.static]. The variable is required to
2060have static or thread storage duration. If the initialization of the variable
2061is not a constant initializer an error will be produced. This attribute may
2062only be used in C++; the ``constinit`` spelling is only accepted in C++20
2063onwards.
2064
2065Note that in C++03 strict constant expression checking is not done. Instead
2066the attribute reports if Clang can emit the variable as a constant, even if it's
2067not technically a 'constant initializer'. This behavior is non-portable.
2068
2069Static storage duration variables with constant initializers avoid hard-to-find
2070bugs caused by the indeterminate order of dynamic initialization. They can also
2071be safely used during dynamic initialization across translation units.
2072
2073This attribute acts as a compile time assertion that the requirements
2074for constant initialization have been met. Since these requirements change
2075between dialects and have subtle pitfalls it's important to fail fast instead
2076of silently falling back on dynamic initialization.
2077
2078The first use of the attribute on a variable must be part of, or precede, the
2079initializing declaration of the variable. C++20 requires the ``constinit``
2080spelling of the attribute to be present on the initializing declaration if it
2081is used anywhere. The other spellings can be specified on a forward declaration
2082and omitted on a later initializing declaration.
2083
2084.. code-block:: c++
2085
2086 // -std=c++14
2087 #define SAFE_STATIC [[clang::require_constant_initialization]]
2088 struct T {
2089 constexpr T(int) {}
2090 ~T(); // non-trivial
2091 };
2092 SAFE_STATIC T x = {42}; // Initialization OK. Doesn't check destructor.
2093 SAFE_STATIC T y = 42; // error: variable does not have a constant initializer
2094 // copy initialization is not a constant expression on a non-literal type.)reST";
2095
2096static const char AttrDoc_Constructor[] = R"reST(The ``constructor`` attribute causes the function to be called before entering
2097``main()``, and the ``destructor`` attribute causes the function to be called
2098after returning from ``main()`` or when the ``exit()`` function has been
2099called. Note, ``quick_exit()``, ``_Exit()``, and ``abort()`` prevent a function
2100marked ``destructor`` from being called.
2101
2102The constructor or destructor function should not accept any arguments and its
2103return type should be ``void``.
2104
2105The attributes accept an optional argument used to specify the priority order
2106in which to execute constructor and destructor functions. The priority is
2107given as an integer constant expression between 101 and 65535 (inclusive).
2108Priorities outside of that range are reserved for use by the implementation. A
2109lower value indicates a higher priority of initialization. Note that only the
2110relative ordering of values is important. For example:
2111
2112.. code-block:: c++
2113
2114 __attribute__((constructor(200))) void foo(void);
2115 __attribute__((constructor(101))) void bar(void);
2116
2117``bar()`` will be called before ``foo()``, and both will be called before
2118``main()``. If no argument is given to the ``constructor`` or ``destructor``
2119attribute, they default to the value ``65535``.)reST";
2120
2121static const char AttrDoc_Consumable[] = R"reST(Each ``class`` that uses any of the typestate annotations must first be marked
2122using the ``consumable`` attribute. Failure to do so will result in a warning.
2123
2124This attribute accepts a single parameter that must be one of the following:
2125``unknown``, ``consumed``, or ``unconsumed``.)reST";
2126
2127static const char AttrDoc_ConsumableAutoCast[] = R"reST(No documentation.)reST";
2128
2129static const char AttrDoc_ConsumableSetOnRead[] = R"reST(No documentation.)reST";
2130
2131static const char AttrDoc_Convergent[] = R"reST(The ``convergent`` attribute can be placed on a function declaration. It is
2132translated into the LLVM ``convergent`` attribute, which indicates that the call
2133instructions of a function with this attribute cannot be made control-dependent
2134on any additional values.
2135
2136This attribute is different from ``noduplicate`` because it allows duplicating
2137function calls if it can be proved that the duplicated function calls are
2138not made control-dependent on any additional values, e.g., unrolling a loop
2139executed by all work items.
2140
2141Sample usage:
2142
2143.. code-block:: c
2144
2145 void convfunc(void) __attribute__((convergent));
2146 // Setting it as a C++11 attribute is also valid in a C++ program.
2147 // void convfunc(void) [[clang::convergent]];)reST";
2148
2149static const char AttrDoc_CoroAwaitElidable[] = R"reST(The ``[[clang::coro_await_elidable]]`` is a class attribute which can be
2150applied to a coroutine return type. It provides a hint to the compiler to apply
2151Heap Allocation Elision more aggressively.
2152
2153When a coroutine function returns such a type, a direct call expression therein
2154that returns a prvalue of a type attributed ``[[clang::coro_await_elidable]]``
2155is said to be under a safe elide context if one of the following is true:
2156
2157- it is the immediate right-hand side operand to a co_await expression.
2158- it is an argument to a ``[[clang::coro_await_elidable_argument]]`` parameter
2159 or parameter pack of another direct call expression under a safe elide context.
2160
2161Do note that the safe elide context applies only to the call expression itself,
2162and the context does not transitively include any of its subexpressions unless
2163exceptional rules of ``[[clang::coro_await_elidable_argument]]`` apply.
2164
2165The compiler performs heap allocation elision on call expressions under a safe
2166elide context, if the callee is a coroutine.
2167
2168Example:
2169
2170.. code-block:: c++
2171
2172 class [[clang::coro_await_elidable]] Task { ... };
2173
2174 Task foo();
2175 Task bar() {
2176 co_await foo(); // foo()'s coroutine frame on this line is elidable
2177 auto t = foo(); // foo()'s coroutine frame on this line is NOT elidable
2178 co_await t;
2179 }
2180
2181Such elision replaces the heap allocated activation frame of the callee coroutine
2182with a local variable within the enclosing braces in the caller's stack frame.
2183The local variable, like other variables in coroutines, may be collected into the
2184coroutine frame, which may be allocated on the heap. The behavior is undefined
2185if the caller coroutine is destroyed earlier than the callee coroutine.)reST";
2186
2187static const char AttrDoc_CoroAwaitElidableArgument[] = R"reST(The ``[[clang::coro_await_elidable_argument]]`` is a function parameter attribute.
2188It works in conjunction with ``[[clang::coro_await_elidable]]`` to propagate a
2189safe elide context to a parameter or parameter pack if the function is called
2190under a safe elide context.
2191
2192This is sometimes necessary on utility functions used to compose or modify the
2193behavior of a callee coroutine.
2194
2195Example:
2196
2197.. code-block:: c++
2198
2199 template <typename T>
2200 class [[clang::coro_await_elidable]] Task { ... };
2201
2202 template <typename... T>
2203 class [[clang::coro_await_elidable]] WhenAll { ... };
2204
2205 // `when_all` is a utility function that composes coroutines. It does not
2206 // need to be a coroutine to propagate.
2207 template <typename... T>
2208 WhenAll<T...> when_all([[clang::coro_await_elidable_argument]] Task<T> tasks...);
2209
2210 Task<int> foo();
2211 Task<int> bar();
2212 Task<void> example1() {
2213 // `when_all``, `foo``, and `bar` are all elide safe because `when_all` is
2214 // under a safe elide context and, thanks to the [[clang::coro_await_elidable_argument]]
2215 // attribute, such context is propagated to foo and bar.
2216 co_await when_all(foo(), bar());
2217 }
2218
2219 Task<void> example2() {
2220 // `when_all` and `bar` are elide safe. `foo` is not elide safe.
2221 auto f = foo();
2222 co_await when_all(f, bar());
2223 }
2224
2225
2226 Task<void> example3() {
2227 // None of the calls are elide safe.
2228 auto t = when_all(foo(), bar());
2229 co_await t;
2230 })reST";
2231
2232static const char AttrDoc_CoroDisableLifetimeBound[] = R"reST(The ``[[clang::coro_lifetimebound]]`` is a class attribute which can be applied
2233to a coroutine return type (`coro_return_type, coro_wrapper`_) (i.e.
2234it should also be annotated with ``[[clang::coro_return_type]]``).
2235
2236All parameters of a function are considered to be lifetime bound if the function returns a
2237coroutine return type (CRT) annotated with ``[[clang::coro_lifetimebound]]``.
2238This lifetime bound analysis can be disabled for a coroutine wrapper or a coroutine by annotating the function
2239with ``[[clang::coro_disable_lifetimebound]]`` function attribute .
2240See documentation of `lifetimebound`_ for details about lifetime bound analysis.
2241
2242
2243Reference parameters of a coroutine are susceptible to capturing references to temporaries or local variables.
2244
2245For example,
2246
2247.. code-block:: c++
2248
2249 task<int> coro(const int& a) { co_return a + 1; }
2250 task<int> dangling_refs(int a) {
2251 // `coro` captures reference to a temporary. `foo` would now contain a dangling reference to `a`.
2252 auto foo = coro(1);
2253 // `coro` captures reference to local variable `a` which is destroyed after the return.
2254 return coro(a);
2255 }
2256
2257Lifetime bound static analysis can be used to detect such instances when coroutines capture references
2258which may die earlier than the coroutine frame itself. In the above example, if the CRT `task` is annotated with
2259``[[clang::coro_lifetimebound]]``, then lifetime bound analysis would detect capturing reference to
2260temporaries or return address of a local variable.
2261
2262Both coroutines and coroutine wrappers are part of this analysis.
2263
2264.. code-block:: c++
2265
2266 template <typename T> struct [[clang::coro_return_type, clang::coro_lifetimebound]] Task {
2267 using promise_type = some_promise_type;
2268 };
2269
2270 Task<int> coro(const int& a) { co_return a + 1; }
2271 [[clang::coro_wrapper]] Task<int> coro_wrapper(const int& a, const int& b) {
2272 return a > b ? coro(a) : coro(b);
2273 }
2274 Task<int> temporary_reference() {
2275 auto foo = coro(1); // warning: capturing reference to a temporary which would die after the expression.
2276
2277 int a = 1;
2278 auto bar = coro_wrapper(a, 0); // warning: `b` captures reference to a temporary.
2279
2280 co_return co_await coro(1); // fine.
2281 }
2282 [[clang::coro_wrapper]] Task<int> stack_reference(int a) {
2283 return coro(a); // warning: returning address of stack variable `a`.
2284 }
2285
2286This analysis can be disabled for all calls to a particular function by annotating the function
2287with function attribute ``[[clang::coro_disable_lifetimebound]]``.
2288For example, this could be useful for coroutine wrappers which accept reference parameters
2289but do not pass them to the underlying coroutine or pass them by value.
2290
2291.. code-block:: c++
2292
2293 Task<int> coro(int a) { co_return a + 1; }
2294 [[clang::coro_wrapper, clang::coro_disable_lifetimebound]] Task<int> coro_wrapper(const int& a) {
2295 return coro(a + 1);
2296 }
2297 void use() {
2298 auto task = coro_wrapper(1); // use of temporary is fine as the argument is not lifetime bound.
2299 })reST";
2300
2301static const char AttrDoc_CoroLifetimeBound[] = R"reST(The ``[[clang::coro_lifetimebound]]`` is a class attribute which can be applied
2302to a coroutine return type (`coro_return_type, coro_wrapper`_) (i.e.
2303it should also be annotated with ``[[clang::coro_return_type]]``).
2304
2305All parameters of a function are considered to be lifetime bound if the function returns a
2306coroutine return type (CRT) annotated with ``[[clang::coro_lifetimebound]]``.
2307This lifetime bound analysis can be disabled for a coroutine wrapper or a coroutine by annotating the function
2308with ``[[clang::coro_disable_lifetimebound]]`` function attribute .
2309See documentation of `lifetimebound`_ for details about lifetime bound analysis.
2310
2311
2312Reference parameters of a coroutine are susceptible to capturing references to temporaries or local variables.
2313
2314For example,
2315
2316.. code-block:: c++
2317
2318 task<int> coro(const int& a) { co_return a + 1; }
2319 task<int> dangling_refs(int a) {
2320 // `coro` captures reference to a temporary. `foo` would now contain a dangling reference to `a`.
2321 auto foo = coro(1);
2322 // `coro` captures reference to local variable `a` which is destroyed after the return.
2323 return coro(a);
2324 }
2325
2326Lifetime bound static analysis can be used to detect such instances when coroutines capture references
2327which may die earlier than the coroutine frame itself. In the above example, if the CRT `task` is annotated with
2328``[[clang::coro_lifetimebound]]``, then lifetime bound analysis would detect capturing reference to
2329temporaries or return address of a local variable.
2330
2331Both coroutines and coroutine wrappers are part of this analysis.
2332
2333.. code-block:: c++
2334
2335 template <typename T> struct [[clang::coro_return_type, clang::coro_lifetimebound]] Task {
2336 using promise_type = some_promise_type;
2337 };
2338
2339 Task<int> coro(const int& a) { co_return a + 1; }
2340 [[clang::coro_wrapper]] Task<int> coro_wrapper(const int& a, const int& b) {
2341 return a > b ? coro(a) : coro(b);
2342 }
2343 Task<int> temporary_reference() {
2344 auto foo = coro(1); // warning: capturing reference to a temporary which would die after the expression.
2345
2346 int a = 1;
2347 auto bar = coro_wrapper(a, 0); // warning: `b` captures reference to a temporary.
2348
2349 co_return co_await coro(1); // fine.
2350 }
2351 [[clang::coro_wrapper]] Task<int> stack_reference(int a) {
2352 return coro(a); // warning: returning address of stack variable `a`.
2353 }
2354
2355This analysis can be disabled for all calls to a particular function by annotating the function
2356with function attribute ``[[clang::coro_disable_lifetimebound]]``.
2357For example, this could be useful for coroutine wrappers which accept reference parameters
2358but do not pass them to the underlying coroutine or pass them by value.
2359
2360.. code-block:: c++
2361
2362 Task<int> coro(int a) { co_return a + 1; }
2363 [[clang::coro_wrapper, clang::coro_disable_lifetimebound]] Task<int> coro_wrapper(const int& a) {
2364 return coro(a + 1);
2365 }
2366 void use() {
2367 auto task = coro_wrapper(1); // use of temporary is fine as the argument is not lifetime bound.
2368 })reST";
2369
2370static const char AttrDoc_CoroOnlyDestroyWhenComplete[] = R"reST(The `coro_only_destroy_when_complete` attribute should be marked on a C++ class. The coroutines
2371whose return type is marked with the attribute are assumed to be destroyed only after the coroutine has
2372reached the final suspend point.
2373
2374This is helpful for the optimizers to reduce the size of the destroy function for the coroutines.
2375
2376For example,
2377
2378.. code-block:: c++
2379
2380 A foo() {
2381 dtor d;
2382 co_await something();
2383 dtor d1;
2384 co_await something();
2385 dtor d2;
2386 co_return 43;
2387 }
2388
2389The compiler may generate the following pseudocode:
2390
2391.. code-block:: c++
2392
2393 void foo.destroy(foo.Frame *frame) {
2394 switch(frame->suspend_index()) {
2395 case 1:
2396 frame->d.~dtor();
2397 break;
2398 case 2:
2399 frame->d.~dtor();
2400 frame->d1.~dtor();
2401 break;
2402 case 3:
2403 frame->d.~dtor();
2404 frame->d1.~dtor();
2405 frame->d2.~dtor();
2406 break;
2407 default: // coroutine completed or haven't started
2408 break;
2409 }
2410
2411 frame->promise.~promise_type();
2412 delete frame;
2413 }
2414
2415The `foo.destroy()` function's purpose is to release all of the resources
2416initialized for the coroutine when it is destroyed in a suspended state.
2417However, if the coroutine is only ever destroyed at the final suspend state,
2418the rest of the conditions are superfluous.
2419
2420The user can use the `coro_only_destroy_when_complete` attributo suppress
2421generation of the other destruction cases, optimizing the above `foo.destroy` to:
2422
2423.. code-block:: c++
2424
2425 void foo.destroy(foo.Frame *frame) {
2426 frame->promise.~promise_type();
2427 delete frame;
2428 })reST";
2429
2430static const char AttrDoc_CoroReturnType[] = R"reST(The ``[[clang::coro_return_type]]`` attribute is used to help static analyzers to recognize
2431coroutines from the function signatures.
2432
2433The ``coro_return_type`` attribute should be marked on a C++ class to mark it as
2434a **coroutine return type (CRT)**.
2435
2436A function ``R func(P1, .., PN)`` has a coroutine return type (CRT) ``R`` if ``R``
2437is marked by ``[[clang::coro_return_type]]`` and ``R`` has a promise type associated to it
2438(i.e., std::coroutine_traits<R, P1, .., PN>::promise_type is a valid promise type).
2439
2440If the return type of a function is a ``CRT`` then the function must be a coroutine.
2441Otherwise the program is invalid. It is allowed for a non-coroutine to return a ``CRT``
2442if the function is marked with ``[[clang::coro_wrapper]]``.
2443
2444The ``[[clang::coro_wrapper]]`` attribute should be marked on a C++ function to mark it as
2445a **coroutine wrapper**. A coroutine wrapper is a function which returns a ``CRT``,
2446is not a coroutine itself and is marked with ``[[clang::coro_wrapper]]``.
2447
2448Clang will enforce that all functions that return a ``CRT`` are either coroutines or marked
2449with ``[[clang::coro_wrapper]]``. Clang will enforce this with an error.
2450
2451From a language perspective, it is not possible to differentiate between a coroutine and a
2452function returning a CRT by merely looking at the function signature.
2453
2454Coroutine wrappers, in particular, are susceptible to capturing
2455references to temporaries and other lifetime issues. This allows to avoid such lifetime
2456issues with coroutine wrappers.
2457
2458For example,
2459
2460.. code-block:: c++
2461
2462 // This is a CRT.
2463 template <typename T> struct [[clang::coro_return_type]] Task {
2464 using promise_type = some_promise_type;
2465 };
2466
2467 Task<int> increment(int a) { co_return a + 1; } // Fine. This is a coroutine.
2468 Task<int> foo() { return increment(1); } // Error. foo is not a coroutine.
2469
2470 // Fine for a coroutine wrapper to return a CRT.
2471 [[clang::coro_wrapper]] Task<int> foo() { return increment(1); }
2472
2473 void bar() {
2474 // Invalid. This intantiates a function which returns a CRT but is not marked as
2475 // a coroutine wrapper.
2476 std::function<Task<int>(int)> f = increment;
2477 }
2478
2479Note: ``a_promise_type::get_return_object`` is exempted from this analysis as it is a necessary
2480implementation detail of any coroutine library.)reST";
2481
2482static const char AttrDoc_CoroWrapper[] = R"reST(The ``[[clang::coro_return_type]]`` attribute is used to help static analyzers to recognize
2483coroutines from the function signatures.
2484
2485The ``coro_return_type`` attribute should be marked on a C++ class to mark it as
2486a **coroutine return type (CRT)**.
2487
2488A function ``R func(P1, .., PN)`` has a coroutine return type (CRT) ``R`` if ``R``
2489is marked by ``[[clang::coro_return_type]]`` and ``R`` has a promise type associated to it
2490(i.e., std::coroutine_traits<R, P1, .., PN>::promise_type is a valid promise type).
2491
2492If the return type of a function is a ``CRT`` then the function must be a coroutine.
2493Otherwise the program is invalid. It is allowed for a non-coroutine to return a ``CRT``
2494if the function is marked with ``[[clang::coro_wrapper]]``.
2495
2496The ``[[clang::coro_wrapper]]`` attribute should be marked on a C++ function to mark it as
2497a **coroutine wrapper**. A coroutine wrapper is a function which returns a ``CRT``,
2498is not a coroutine itself and is marked with ``[[clang::coro_wrapper]]``.
2499
2500Clang will enforce that all functions that return a ``CRT`` are either coroutines or marked
2501with ``[[clang::coro_wrapper]]``. Clang will enforce this with an error.
2502
2503From a language perspective, it is not possible to differentiate between a coroutine and a
2504function returning a CRT by merely looking at the function signature.
2505
2506Coroutine wrappers, in particular, are susceptible to capturing
2507references to temporaries and other lifetime issues. This allows to avoid such lifetime
2508issues with coroutine wrappers.
2509
2510For example,
2511
2512.. code-block:: c++
2513
2514 // This is a CRT.
2515 template <typename T> struct [[clang::coro_return_type]] Task {
2516 using promise_type = some_promise_type;
2517 };
2518
2519 Task<int> increment(int a) { co_return a + 1; } // Fine. This is a coroutine.
2520 Task<int> foo() { return increment(1); } // Error. foo is not a coroutine.
2521
2522 // Fine for a coroutine wrapper to return a CRT.
2523 [[clang::coro_wrapper]] Task<int> foo() { return increment(1); }
2524
2525 void bar() {
2526 // Invalid. This intantiates a function which returns a CRT but is not marked as
2527 // a coroutine wrapper.
2528 std::function<Task<int>(int)> f = increment;
2529 }
2530
2531Note: ``a_promise_type::get_return_object`` is exempted from this analysis as it is a necessary
2532implementation detail of any coroutine library.)reST";
2533
2534static const char AttrDoc_CountedBy[] = R"reST(Clang supports the ``counted_by`` attribute on the flexible array member of a
2535structure in C. The argument for the attribute is the name of a field member
2536holding the count of elements in the flexible array. This information can be
2537used to improve the results of the array bound sanitizer and the
2538``__builtin_dynamic_object_size`` builtin. The ``count`` field member must be
2539within the same non-anonymous, enclosing struct as the flexible array member.
2540
2541This example specifies that the flexible array member ``array`` has the number
2542of elements allocated for it in ``count``:
2543
2544.. code-block:: c
2545
2546 struct bar;
2547
2548 struct foo {
2549 size_t count;
2550 char other;
2551 struct bar *array[] __attribute__((counted_by(count)));
2552 };
2553
2554This establishes a relationship between ``array`` and ``count``. Specifically,
2555``array`` must have at least ``count`` number of elements available. It's the
2556user's responsibility to ensure that this relationship is maintained through
2557changes to the structure.
2558
2559In the following example, the allocated array erroneously has fewer elements
2560than what's specified by ``p->count``. This would result in an out-of-bounds
2561access not being detected.
2562
2563.. code-block:: c
2564
2565 #define SIZE_INCR 42
2566
2567 struct foo *p;
2568
2569 void foo_alloc(size_t count) {
2570 p = malloc(MAX(sizeof(struct foo),
2571 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
2572 p->count = count + SIZE_INCR;
2573 }
2574
2575The next example updates ``p->count``, but breaks the relationship requirement
2576that ``p->array`` must have at least ``p->count`` number of elements available:
2577
2578.. code-block:: c
2579
2580 #define SIZE_INCR 42
2581
2582 struct foo *p;
2583
2584 void foo_alloc(size_t count) {
2585 p = malloc(MAX(sizeof(struct foo),
2586 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
2587 p->count = count;
2588 }
2589
2590 void use_foo(int index, int val) {
2591 p->count += SIZE_INCR + 1; /* 'count' is now larger than the number of elements of 'array'. */
2592 p->array[index] = val; /* The sanitizer can't properly check this access. */
2593 }
2594
2595In this example, an update to ``p->count`` maintains the relationship
2596requirement:
2597
2598.. code-block:: c
2599
2600 void use_foo(int index, int val) {
2601 if (p->count == 0)
2602 return;
2603 --p->count;
2604 p->array[index] = val;
2605 })reST";
2606
2607static const char AttrDoc_CountedByOrNull[] = R"reST(Clang supports the ``counted_by`` attribute on the flexible array member of a
2608structure in C. The argument for the attribute is the name of a field member
2609holding the count of elements in the flexible array. This information can be
2610used to improve the results of the array bound sanitizer and the
2611``__builtin_dynamic_object_size`` builtin. The ``count`` field member must be
2612within the same non-anonymous, enclosing struct as the flexible array member.
2613
2614This example specifies that the flexible array member ``array`` has the number
2615of elements allocated for it in ``count``:
2616
2617.. code-block:: c
2618
2619 struct bar;
2620
2621 struct foo {
2622 size_t count;
2623 char other;
2624 struct bar *array[] __attribute__((counted_by(count)));
2625 };
2626
2627This establishes a relationship between ``array`` and ``count``. Specifically,
2628``array`` must have at least ``count`` number of elements available. It's the
2629user's responsibility to ensure that this relationship is maintained through
2630changes to the structure.
2631
2632In the following example, the allocated array erroneously has fewer elements
2633than what's specified by ``p->count``. This would result in an out-of-bounds
2634access not being detected.
2635
2636.. code-block:: c
2637
2638 #define SIZE_INCR 42
2639
2640 struct foo *p;
2641
2642 void foo_alloc(size_t count) {
2643 p = malloc(MAX(sizeof(struct foo),
2644 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
2645 p->count = count + SIZE_INCR;
2646 }
2647
2648The next example updates ``p->count``, but breaks the relationship requirement
2649that ``p->array`` must have at least ``p->count`` number of elements available:
2650
2651.. code-block:: c
2652
2653 #define SIZE_INCR 42
2654
2655 struct foo *p;
2656
2657 void foo_alloc(size_t count) {
2658 p = malloc(MAX(sizeof(struct foo),
2659 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
2660 p->count = count;
2661 }
2662
2663 void use_foo(int index, int val) {
2664 p->count += SIZE_INCR + 1; /* 'count' is now larger than the number of elements of 'array'. */
2665 p->array[index] = val; /* The sanitizer can't properly check this access. */
2666 }
2667
2668In this example, an update to ``p->count`` maintains the relationship
2669requirement:
2670
2671.. code-block:: c
2672
2673 void use_foo(int index, int val) {
2674 if (p->count == 0)
2675 return;
2676 --p->count;
2677 p->array[index] = val;
2678 })reST";
2679
2680static const char AttrDoc_DLLExport[] = R"reST(The ``__declspec(dllexport)`` attribute declares a variable, function, or
2681Objective-C interface to be exported from the module. It is available under the
2682``-fdeclspec`` flag for compatibility with various compilers. The primary use
2683is for COFF object files which explicitly specify what interfaces are available
2684for external use. See the dllexport_ documentation on MSDN for more
2685information.
2686
2687.. _dllexport: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx)reST";
2688
2689static const char AttrDoc_DLLExportOnDecl[] = R"reST()reST";
2690
2691static const char AttrDoc_DLLExportStaticLocal[] = R"reST()reST";
2692
2693static const char AttrDoc_DLLImport[] = R"reST(The ``__declspec(dllimport)`` attribute declares a variable, function, or
2694Objective-C interface to be imported from an external module. It is available
2695under the ``-fdeclspec`` flag for compatibility with various compilers. The
2696primary use is for COFF object files which explicitly specify what interfaces
2697are imported from external modules. See the dllimport_ documentation on MSDN
2698for more information.
2699
2700Note that a dllimport function may still be inlined, if its definition is
2701available and it doesn't reference any non-dllimport functions or global
2702variables.
2703
2704.. _dllimport: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx)reST";
2705
2706static const char AttrDoc_DLLImportStaticLocal[] = R"reST()reST";
2707
2708static const char AttrDoc_Deprecated[] = R"reST(The ``deprecated`` attribute can be applied to a function, a variable, or a
2709type. This is useful when identifying functions, variables, or types that are
2710expected to be removed in a future version of a program.
2711
2712Consider the function declaration for a hypothetical function ``f``:
2713
2714.. code-block:: c++
2715
2716 void f(void) __attribute__((deprecated("message", "replacement")));
2717
2718When spelled as ``__attribute__((deprecated))``, the deprecated attribute can have
2719two optional string arguments. The first one is the message to display when
2720emitting the warning; the second one enables the compiler to provide a Fix-It
2721to replace the deprecated name with a new name. Otherwise, when spelled as
2722``[[gnu::deprecated]]`` or ``[[deprecated]]``, the attribute can have one optional
2723string argument which is the message to display when emitting the warning.)reST";
2724
2725static const char AttrDoc_Destructor[] = R"reST(The ``constructor`` attribute causes the function to be called before entering
2726``main()``, and the ``destructor`` attribute causes the function to be called
2727after returning from ``main()`` or when the ``exit()`` function has been
2728called. Note, ``quick_exit()``, ``_Exit()``, and ``abort()`` prevent a function
2729marked ``destructor`` from being called.
2730
2731The constructor or destructor function should not accept any arguments and its
2732return type should be ``void``.
2733
2734The attributes accept an optional argument used to specify the priority order
2735in which to execute constructor and destructor functions. The priority is
2736given as an integer constant expression between 101 and 65535 (inclusive).
2737Priorities outside of that range are reserved for use by the implementation. A
2738lower value indicates a higher priority of initialization. Note that only the
2739relative ordering of values is important. For example:
2740
2741.. code-block:: c++
2742
2743 __attribute__((constructor(200))) void foo(void);
2744 __attribute__((constructor(101))) void bar(void);
2745
2746``bar()`` will be called before ``foo()``, and both will be called before
2747``main()``. If no argument is given to the ``constructor`` or ``destructor``
2748attribute, they default to the value ``65535``.)reST";
2749
2750static const char AttrDoc_DeviceKernel[] = R"reST(These attributes specify that the function represents a kernel for device offloading.
2751The specific semantics depend on the offloading language, target, and attribute spelling.
2752Here is a code example using the attribute to mark a function as a kernel:
2753
2754.. code-block:: c++
2755
2756 [[clang::device_kernel]] int foo(int x) { return ++x; })reST";
2757
2758static const char AttrDoc_DiagnoseAsBuiltin[] = R"reST(The ``diagnose_as_builtin`` attribute indicates that Fortify diagnostics are to
2759be applied to the declared function as if it were the function specified by the
2760attribute. The builtin function whose diagnostics are to be mimicked should be
2761given. In addition, the order in which arguments should be applied must also
2762be given.
2763
2764For example, the attribute can be used as follows.
2765
2766.. code-block:: c
2767
2768 __attribute__((diagnose_as_builtin(__builtin_memset, 3, 2, 1)))
2769 void *mymemset(int n, int c, void *s) {
2770 // ...
2771 }
2772
2773This indicates that calls to ``mymemset`` should be diagnosed as if they were
2774calls to ``__builtin_memset``. The arguments ``3, 2, 1`` indicate by index the
2775order in which arguments of ``mymemset`` should be applied to
2776``__builtin_memset``. The third argument should be applied first, then the
2777second, and then the first. Thus (when Fortify warnings are enabled) the call
2778``mymemset(n, c, s)`` will diagnose overflows as if it were the call
2779``__builtin_memset(s, c, n)``.
2780
2781For variadic functions, the variadic arguments must come in the same order as
2782they would to the builtin function, after all normal arguments. For instance,
2783to diagnose a new function as if it were `sscanf`, we can use the attribute as
2784follows.
2785
2786.. code-block:: c
2787
2788 __attribute__((diagnose_as_builtin(sscanf, 1, 2)))
2789 int mysscanf(const char *str, const char *format, ...) {
2790 // ...
2791 }
2792
2793Then the call `mysscanf("abc def", "%4s %4s", buf1, buf2)` will be diagnosed as
2794if it were the call `sscanf("abc def", "%4s %4s", buf1, buf2)`.
2795
2796This attribute cannot be applied to non-static member functions.)reST";
2797
2798static const char AttrDoc_DiagnoseIf[] = R"reST(The ``diagnose_if`` attribute can be placed on function declarations to emit
2799warnings or errors at compile-time if calls to the attributed function meet
2800certain user-defined criteria. For example:
2801
2802.. code-block:: c
2803
2804 int abs(int a)
2805 __attribute__((diagnose_if(a >= 0, "Redundant abs call", "warning")));
2806 int must_abs(int a)
2807 __attribute__((diagnose_if(a >= 0, "Redundant abs call", "error")));
2808
2809 int val = abs(1); // warning: Redundant abs call
2810 int val2 = must_abs(1); // error: Redundant abs call
2811 int val3 = abs(val);
2812 int val4 = must_abs(val); // Because run-time checks are not emitted for
2813 // diagnose_if attributes, this executes without
2814 // issue.
2815
2816
2817``diagnose_if`` is closely related to ``enable_if``, with a few key differences:
2818
2819* Overload resolution is not aware of ``diagnose_if`` attributes: they're
2820 considered only after we select the best candidate from a given candidate set.
2821* Function declarations that differ only in their ``diagnose_if`` attributes are
2822 considered to be redeclarations of the same function (not overloads).
2823* If the condition provided to ``diagnose_if`` cannot be evaluated, no
2824 diagnostic will be emitted.
2825
2826Otherwise, ``diagnose_if`` is essentially the logical negation of ``enable_if``.
2827
2828As a result of bullet number two, ``diagnose_if`` attributes will stack on the
2829same function. For example:
2830
2831.. code-block:: c
2832
2833 int foo() __attribute__((diagnose_if(1, "diag1", "warning")));
2834 int foo() __attribute__((diagnose_if(1, "diag2", "warning")));
2835
2836 int bar = foo(); // warning: diag1
2837 // warning: diag2
2838 int (*fooptr)(void) = foo; // warning: diag1
2839 // warning: diag2
2840
2841 constexpr int supportsAPILevel(int N) { return N < 5; }
2842 int baz(int a)
2843 __attribute__((diagnose_if(!supportsAPILevel(10),
2844 "Upgrade to API level 10 to use baz", "error")));
2845 int baz(int a)
2846 __attribute__((diagnose_if(!a, "0 is not recommended.", "warning")));
2847
2848 int (*bazptr)(int) = baz; // error: Upgrade to API level 10 to use baz
2849 int v = baz(0); // error: Upgrade to API level 10 to use baz
2850
2851Query for this feature with ``__has_attribute(diagnose_if)``.)reST";
2852
2853static const char AttrDoc_DisableSanitizerInstrumentation[] = R"reST(Use the ``disable_sanitizer_instrumentation`` attribute on a function,
2854Objective-C method, or global variable, to specify that no sanitizer
2855instrumentation should be applied.
2856
2857This is not the same as ``__attribute__((no_sanitize(...)))``, which depending
2858on the tool may still insert instrumentation to prevent false positive reports.)reST";
2859
2860static const char AttrDoc_DisableTailCalls[] = R"reST(The ``disable_tail_calls`` attribute instructs the backend to not perform tail
2861call optimization inside the marked function.
2862
2863For example:
2864
2865 .. code-block:: c
2866
2867 int callee(int);
2868
2869 int foo(int a) __attribute__((disable_tail_calls)) {
2870 return callee(a); // This call is not tail-call optimized.
2871 }
2872
2873Marking virtual functions as ``disable_tail_calls`` is legal.
2874
2875 .. code-block:: c++
2876
2877 int callee(int);
2878
2879 class Base {
2880 public:
2881 [[clang::disable_tail_calls]] virtual int foo1() {
2882 return callee(); // This call is not tail-call optimized.
2883 }
2884 };
2885
2886 class Derived1 : public Base {
2887 public:
2888 int foo1() override {
2889 return callee(); // This call is tail-call optimized.
2890 }
2891 };)reST";
2892
2893static const char AttrDoc_EmptyBases[] = R"reST(The empty_bases attribute permits the compiler to utilize the
2894empty-base-optimization more frequently.
2895This attribute only applies to struct, class, and union types.
2896It is only supported when using the Microsoft C++ ABI.)reST";
2897
2898static const char AttrDoc_EnableIf[] = R"reST(.. Note:: Some features of this attribute are experimental. The meaning of
2899 multiple enable_if attributes on a single declaration is subject to change in
2900 a future version of clang. Also, the ABI is not standardized and the name
2901 mangling may change in future versions. To avoid that, use asm labels.
2902
2903The ``enable_if`` attribute can be placed on function declarations to control
2904which overload is selected based on the values of the function's arguments.
2905When combined with the ``overloadable`` attribute, this feature is also
2906available in C.
2907
2908.. code-block:: c++
2909
2910 int isdigit(int c);
2911 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")));
2912
2913 void foo(char c) {
2914 isdigit(c);
2915 isdigit(10);
2916 isdigit(-10); // results in a compile-time error.
2917 }
2918
2919The enable_if attribute takes two arguments, the first is an expression written
2920in terms of the function parameters, the second is a string explaining why this
2921overload candidate could not be selected to be displayed in diagnostics. The
2922expression is part of the function signature for the purposes of determining
2923whether it is a redeclaration (following the rules used when determining
2924whether a C++ template specialization is ODR-equivalent), but is not part of
2925the type.
2926
2927The enable_if expression is evaluated as if it were the body of a
2928bool-returning constexpr function declared with the arguments of the function
2929it is being applied to, then called with the parameters at the call site. If the
2930result is false or could not be determined through constant expression
2931evaluation, then this overload will not be chosen and the provided string may
2932be used in a diagnostic if the compile fails as a result.
2933
2934Because the enable_if expression is an unevaluated context, there are no global
2935state changes, nor the ability to pass information from the enable_if
2936expression to the function body. For example, suppose we want calls to
2937strnlen(strbuf, maxlen) to resolve to strnlen_chk(strbuf, maxlen, size of
2938strbuf) only if the size of strbuf can be determined:
2939
2940.. code-block:: c++
2941
2942 __attribute__((always_inline))
2943 static inline size_t strnlen(const char *s, size_t maxlen)
2944 __attribute__((overloadable))
2945 __attribute__((enable_if(__builtin_object_size(s, 0) != -1))),
2946 "chosen when the buffer size is known but 'maxlen' is not")))
2947 {
2948 return strnlen_chk(s, maxlen, __builtin_object_size(s, 0));
2949 }
2950
2951Multiple enable_if attributes may be applied to a single declaration. In this
2952case, the enable_if expressions are evaluated from left to right in the
2953following manner. First, the candidates whose enable_if expressions evaluate to
2954false or cannot be evaluated are discarded. If the remaining candidates do not
2955share ODR-equivalent enable_if expressions, the overload resolution is
2956ambiguous. Otherwise, enable_if overload resolution continues with the next
2957enable_if attribute on the candidates that have not been discarded and have
2958remaining enable_if attributes. In this way, we pick the most specific
2959overload out of a number of viable overloads using enable_if.
2960
2961.. code-block:: c++
2962
2963 void f() __attribute__((enable_if(true, ""))); // #1
2964 void f() __attribute__((enable_if(true, ""))) __attribute__((enable_if(true, ""))); // #2
2965
2966 void g(int i, int j) __attribute__((enable_if(i, ""))); // #1
2967 void g(int i, int j) __attribute__((enable_if(j, ""))) __attribute__((enable_if(true))); // #2
2968
2969In this example, a call to f() is always resolved to #2, as the first enable_if
2970expression is ODR-equivalent for both declarations, but #1 does not have another
2971enable_if expression to continue evaluating, so the next round of evaluation has
2972only a single candidate. In a call to g(1, 1), the call is ambiguous even though
2973#2 has more enable_if attributes, because the first enable_if expressions are
2974not ODR-equivalent.
2975
2976Query for this feature with ``__has_attribute(enable_if)``.
2977
2978Note that functions with one or more ``enable_if`` attributes may not have
2979their address taken, unless all of the conditions specified by said
2980``enable_if`` are constants that evaluate to ``true``. For example:
2981
2982.. code-block:: c
2983
2984 const int TrueConstant = 1;
2985 const int FalseConstant = 0;
2986 int f(int a) __attribute__((enable_if(a > 0, "")));
2987 int g(int a) __attribute__((enable_if(a == 0 || a != 0, "")));
2988 int h(int a) __attribute__((enable_if(1, "")));
2989 int i(int a) __attribute__((enable_if(TrueConstant, "")));
2990 int j(int a) __attribute__((enable_if(FalseConstant, "")));
2991
2992 void fn() {
2993 int (*ptr)(int);
2994 ptr = &f; // error: 'a > 0' is not always true
2995 ptr = &g; // error: 'a == 0 || a != 0' is not a truthy constant
2996 ptr = &h; // OK: 1 is a truthy constant
2997 ptr = &i; // OK: 'TrueConstant' is a truthy constant
2998 ptr = &j; // error: 'FalseConstant' is a constant, but not truthy
2999 }
3000
3001Because ``enable_if`` evaluation happens during overload resolution,
3002``enable_if`` may give unintuitive results when used with templates, depending
3003on when overloads are resolved. In the example below, clang will emit a
3004diagnostic about no viable overloads for ``foo`` in ``bar``, but not in ``baz``:
3005
3006.. code-block:: c++
3007
3008 double foo(int i) __attribute__((enable_if(i > 0, "")));
3009 void *foo(int i) __attribute__((enable_if(i <= 0, "")));
3010 template <int I>
3011 auto bar() { return foo(I); }
3012
3013 template <typename T>
3014 auto baz() { return foo(T::number); }
3015
3016 struct WithNumber { constexpr static int number = 1; };
3017 void callThem() {
3018 bar<sizeof(WithNumber)>();
3019 baz<WithNumber>();
3020 }
3021
3022This is because, in ``bar``, ``foo`` is resolved prior to template
3023instantiation, so the value for ``I`` isn't known (thus, both ``enable_if``
3024conditions for ``foo`` fail). However, in ``baz``, ``foo`` is resolved during
3025template instantiation, so the value for ``T::number`` is known.)reST";
3026
3027static const char AttrDoc_EnforceTCB[] = R"reST(The ``enforce_tcb`` attribute can be placed on functions to enforce that a
3028 trusted compute base (TCB) does not call out of the TCB. This generates a
3029 warning every time a function not marked with an ``enforce_tcb`` attribute is
3030 called from a function with the ``enforce_tcb`` attribute. A function may be a
3031 part of multiple TCBs. Invocations through function pointers are currently
3032 not checked. Builtins are considered to a part of every TCB.
3033
3034 - ``enforce_tcb(Name)`` indicates that this function is a part of the TCB named ``Name``)reST";
3035
3036static const char AttrDoc_EnforceTCBLeaf[] = R"reST(The ``enforce_tcb_leaf`` attribute satisfies the requirement enforced by
3037 ``enforce_tcb`` for the marked function to be in the named TCB but does not
3038 continue to check the functions called from within the leaf function.
3039
3040 - ``enforce_tcb_leaf(Name)`` indicates that this function is a part of the TCB named ``Name``)reST";
3041
3042static const char AttrDoc_EnumExtensibility[] = R"reST(Attribute ``enum_extensibility`` is used to distinguish between enum definitions
3043that are extensible and those that are not. The attribute can take either
3044``closed`` or ``open`` as an argument. ``closed`` indicates a variable of the
3045enum type takes a value that corresponds to one of the enumerators listed in the
3046enum definition or, when the enum is annotated with ``flag_enum``, a value that
3047can be constructed using values corresponding to the enumerators. ``open``
3048indicates a variable of the enum type can take any values allowed by the
3049standard and instructs clang to be more lenient when issuing warnings.
3050
3051.. code-block:: c
3052
3053 enum __attribute__((enum_extensibility(closed))) ClosedEnum {
3054 A0, A1
3055 };
3056
3057 enum __attribute__((enum_extensibility(open))) OpenEnum {
3058 B0, B1
3059 };
3060
3061 enum __attribute__((enum_extensibility(closed),flag_enum)) ClosedFlagEnum {
3062 C0 = 1 << 0, C1 = 1 << 1
3063 };
3064
3065 enum __attribute__((enum_extensibility(open),flag_enum)) OpenFlagEnum {
3066 D0 = 1 << 0, D1 = 1 << 1
3067 };
3068
3069 void foo1() {
3070 enum ClosedEnum ce;
3071 enum OpenEnum oe;
3072 enum ClosedFlagEnum cfe;
3073 enum OpenFlagEnum ofe;
3074
3075 ce = A1; // no warnings
3076 ce = 100; // warning issued
3077 oe = B1; // no warnings
3078 oe = 100; // no warnings
3079 cfe = C0 | C1; // no warnings
3080 cfe = C0 | C1 | 4; // warning issued
3081 ofe = D0 | D1; // no warnings
3082 ofe = D0 | D1 | 4; // no warnings
3083 })reST";
3084
3085static const char AttrDoc_Error[] = R"reST(The ``error`` and ``warning`` function attributes can be used to specify a
3086custom diagnostic to be emitted when a call to such a function is not
3087eliminated via optimizations. This can be used to create compile time
3088assertions that depend on optimizations, while providing diagnostics
3089pointing to precise locations of the call site in the source.
3090
3091.. code-block:: c++
3092
3093 __attribute__((warning("oh no"))) void dontcall();
3094 void foo() {
3095 if (someCompileTimeAssertionThatsTrue)
3096 dontcall(); // Warning
3097
3098 dontcall(); // Warning
3099
3100 if (someCompileTimeAssertionThatsFalse)
3101 dontcall(); // No Warning
3102 sizeof(dontcall()); // No Warning
3103 }
3104
3105When the call occurs through inlined functions, the
3106``-fdiagnostics-show-inlining-chain`` option can be used to show the
3107inlining chain that led to the call. This helps identify which call site
3108triggered the diagnostic when the attributed function is called from
3109multiple locations through inline functions.
3110
3111When enabled, this option automatically uses debug info for accurate source
3112locations if available (``-gline-directives-only`` (implicitly enabled at
3113``-g1``) or higher), or falls back to a heuristic based on metadata tracking.
3114When falling back, a note is emitted suggesting ``-gline-directives-only`` for
3115more accurate locations.)reST";
3116
3117static const char AttrDoc_ExcludeFromExplicitInstantiation[] = R"reST(The ``exclude_from_explicit_instantiation`` attribute opts-out a member of a
3118class template from being part of explicit template instantiations of that
3119class template. This means that an explicit instantiation will not instantiate
3120members of the class template marked with the attribute, but also that code
3121where an extern template declaration of the enclosing class template is visible
3122will not take for granted that an external instantiation of the class template
3123would provide those members (which would otherwise be a link error, since the
3124explicit instantiation won't provide those members). For example, let's say we
3125don't want the ``data()`` method to be part of libc++'s ABI. To make sure it
3126is not exported from the dylib, we give it hidden visibility:
3127
3128 .. code-block:: c++
3129
3130 // in <string>
3131 template <class CharT>
3132 class basic_string {
3133 public:
3134 __attribute__((__visibility__("hidden")))
3135 const value_type* data() const noexcept { ... }
3136 };
3137
3138 template class basic_string<char>;
3139
3140Since an explicit template instantiation declaration for ``basic_string<char>``
3141is provided, the compiler is free to assume that ``basic_string<char>::data()``
3142will be provided by another translation unit, and it is free to produce an
3143external call to this function. However, since ``data()`` has hidden visibility
3144and the explicit template instantiation is provided in a shared library (as
3145opposed to simply another translation unit), ``basic_string<char>::data()``
3146won't be found and a link error will ensue. This happens because the compiler
3147assumes that ``basic_string<char>::data()`` is part of the explicit template
3148instantiation declaration, when it really isn't. To tell the compiler that
3149``data()`` is not part of the explicit template instantiation declaration, the
3150``exclude_from_explicit_instantiation`` attribute can be used:
3151
3152 .. code-block:: c++
3153
3154 // in <string>
3155 template <class CharT>
3156 class basic_string {
3157 public:
3158 __attribute__((__visibility__("hidden")))
3159 __attribute__((exclude_from_explicit_instantiation))
3160 const value_type* data() const noexcept { ... }
3161 };
3162
3163 template class basic_string<char>;
3164
3165Now, the compiler won't assume that ``basic_string<char>::data()`` is provided
3166externally despite there being an explicit template instantiation declaration:
3167the compiler will implicitly instantiate ``basic_string<char>::data()`` in the
3168TUs where it is used.
3169
3170This attribute can be used on static and non-static member functions of class
3171templates, static data members of class templates and member classes of class
3172templates.
3173
3174**Interaction with __declspec(dllexport/dllimport)**
3175
3176For a DLL platform (i.e., Windows), this attribute also means "this member will
3177never be exported or imported". Despite its name, this semantics applies to
3178implicit instantiations and non-template entities as well.
3179
3180 .. code-block:: c++
3181
3182 // in <exception>
3183 class __declspec(dllimport) nested_exception {
3184 ...
3185 public:
3186 __attribute__((exclude_from_explicit_instantiation))
3187 exception_ptr nested_ptr() const noexcept { ... }
3188 };
3189
3190In this case, ``nested_exception::nested_ptr`` will never be attempted to be
3191imported.)reST";
3192
3193static const char AttrDoc_ExplicitInit[] = R"reST(The ``clang::require_explicit_initialization`` attribute indicates that a
3194field of an aggregate must be initialized explicitly by the user when an object
3195of the aggregate type is constructed. The attribute supports both C and C++,
3196but its usage is invalid on non-aggregates.
3197
3198Note that this attribute is *not* a memory safety feature, and is *not* intended
3199to guard against use of uninitialized memory.
3200
3201Rather, it is intended for use in "parameter-objects", used to simulate,
3202for example, the passing of named parameters.
3203Except inside unevaluated contexts, the attribute generates a warning when
3204explicit initializers for such variables are not provided (this occurs
3205regardless of whether any in-class field initializers exist):
3206
3207.. code-block:: c++
3208
3209 struct Buffer {
3210 void *address [[clang::require_explicit_initialization]];
3211 size_t length [[clang::require_explicit_initialization]] = 0;
3212 };
3213
3214 struct ArrayIOParams {
3215 size_t count [[clang::require_explicit_initialization]];
3216 size_t element_size [[clang::require_explicit_initialization]];
3217 int flags = 0;
3218 };
3219
3220 size_t ReadArray(FILE *file, struct Buffer buffer,
3221 struct ArrayIOParams params);
3222
3223 int main() {
3224 unsigned int buf[512];
3225 ReadArray(stdin, {
3226 buf
3227 // warning: field 'length' is not explicitly initialized
3228 }, {
3229 .count = sizeof(buf) / sizeof(*buf),
3230 // warning: field 'element_size' is not explicitly initialized
3231 // (Note that a missing initializer for 'flags' is not diagnosed, because
3232 // the field is not marked as requiring explicit initialization.)
3233 });
3234 })reST";
3235
3236static const char AttrDoc_ExtVectorType[] = R"reST(The ``ext_vector_type(N)`` attribute specifies that a type is a vector with N
3237elements, directly mapping to an LLVM vector type. Originally from OpenCL, it
3238allows element access the array subscript operator ``[]``, ``sN`` where N is
3239a hexadecimal value, or ``x, y, z, w`` for graphics-style indexing.
3240This attribute enables efficient SIMD operations and is usable in
3241general-purpose code.
3242
3243.. code-block:: c++
3244
3245 template <typename T, uint32_t N>
3246 constexpr T simd_reduce(T [[clang::ext_vector_type(N)]] v) {
3247 static_assert((N & (N - 1)) == 0, "N must be a power of two");
3248 if constexpr (N == 1)
3249 return v[0];
3250 else
3251 return simd_reduce<T, N / 2>(v.hi + v.lo);
3252 }
3253
3254The vector type also supports swizzling up to sixteen elements. This can be done
3255using the object accessors. The OpenCL documentation lists all of the accepted
3256values.
3257
3258.. code-block:: c++
3259
3260 using f16_x16 = _Float16 __attribute__((ext_vector_type(16)));
3261
3262 f16_x16 reverse(f16_x16 v) { return v.sfedcba9876543210; }
3263
3264See the OpenCL documentation for some more complete examples.)reST";
3265
3266static const char AttrDoc_ExternalSourceSymbol[] = R"reST(The ``external_source_symbol`` attribute specifies that a declaration originates
3267from an external source and describes the nature of that source.
3268
3269The fact that Clang is capable of recognizing declarations that were defined
3270externally can be used to provide better tooling support for mixed-language
3271projects or projects that rely on auto-generated code. For instance, an IDE that
3272uses Clang and that supports mixed-language projects can use this attribute to
3273provide a correct 'jump-to-definition' feature. For a concrete example,
3274consider a protocol that's defined in a Swift file:
3275
3276.. code-block:: swift
3277
3278 @objc public protocol SwiftProtocol {
3279 func method()
3280 }
3281
3282This protocol can be used from Objective-C code by including a header file that
3283was generated by the Swift compiler. The declarations in that header can use
3284the ``external_source_symbol`` attribute to make Clang aware of the fact
3285that ``SwiftProtocol`` actually originates from a Swift module:
3286
3287.. code-block:: objc
3288
3289 __attribute__((external_source_symbol(language="Swift",defined_in="module")))
3290 @protocol SwiftProtocol
3291 @required
3292 - (void) method;
3293 @end
3294
3295Consequently, when 'jump-to-definition' is performed at a location that
3296references ``SwiftProtocol``, the IDE can jump to the original definition in
3297the Swift source file rather than jumping to the Objective-C declaration in the
3298auto-generated header file.
3299
3300The ``external_source_symbol`` attribute is a comma-separated list that includes
3301clauses that describe the origin and the nature of the particular declaration.
3302Those clauses can be:
3303
3304language=\ *string-literal*
3305 The name of the source language in which this declaration was defined.
3306
3307defined_in=\ *string-literal*
3308 The name of the source container in which the declaration was defined. The
3309 exact definition of source container is language-specific, e.g. Swift's
3310 source containers are modules, so ``defined_in`` should specify the Swift
3311 module name.
3312
3313USR=\ *string-literal*
3314 String that specifies a unified symbol resolution (USR) value for this
3315 declaration. USR string uniquely identifies this particular declaration, and
3316 is typically used when constructing an index of a codebase.
3317 The USR value in this attribute is expected to be generated by an external
3318 compiler that compiled the native declaration using its original source
3319 language. The exact format of the USR string and its other attributes
3320 are determined by the specification of this declaration's source language.
3321 When not specified, Clang's indexer will use the Clang USR for this symbol.
3322 User can query to see if Clang supports the use of the ``USR`` clause in
3323 the ``external_source_symbol`` attribute with
3324 ``__has_attribute(external_source_symbol) >= 20230206``.
3325
3326generated_declaration
3327 This declaration was automatically generated by some tool.
3328
3329The clauses can be specified in any order. The clauses that are listed above are
3330all optional, but the attribute has to have at least one clause.)reST";
3331
3332static const char AttrDoc_FallThrough[] = R"reST(The ``fallthrough`` (or ``clang::fallthrough``) attribute is used
3333to annotate intentional fall-through
3334between switch labels. It can only be applied to a null statement placed at a
3335point of execution between any statement and the next switch label. It is
3336common to mark these places with a specific comment, but this attribute is
3337meant to replace comments with a more strict annotation, which can be checked
3338by the compiler. This attribute doesn't change semantics of the code and can
3339be used wherever an intended fall-through occurs. It is designed to mimic
3340control-flow statements like ``break;``, so it can be placed in most places
3341where ``break;`` can, but only if there are no statements on the execution path
3342between it and the next switch label.
3343
3344By default, Clang does not warn on unannotated fallthrough from one ``switch``
3345case to another. Diagnostics on fallthrough without a corresponding annotation
3346can be enabled with the ``-Wimplicit-fallthrough`` argument.
3347
3348Here is an example:
3349
3350.. code-block:: c++
3351
3352 // compile with -Wimplicit-fallthrough
3353 switch (n) {
3354 case 22:
3355 case 33: // no warning: no statements between case labels
3356 f();
3357 case 44: // warning: unannotated fall-through
3358 g();
3359 [[clang::fallthrough]];
3360 case 55: // no warning
3361 if (x) {
3362 h();
3363 break;
3364 }
3365 else {
3366 i();
3367 [[clang::fallthrough]];
3368 }
3369 case 66: // no warning
3370 p();
3371 [[clang::fallthrough]]; // warning: fallthrough annotation does not
3372 // directly precede case label
3373 q();
3374 case 77: // warning: unannotated fall-through
3375 r();
3376 })reST";
3377
3378static const char AttrDoc_FastCall[] = R"reST(On 32-bit x86 targets, this attribute changes the calling convention of a
3379function to use ECX and EDX as register parameters and clear parameters off of
3380the stack on return. This convention does not support variadic calls or
3381unprototyped functions in C, and has no effect on x86_64 targets. This calling
3382convention is supported primarily for compatibility with existing code. Users
3383seeking register parameters should use the ``regparm`` attribute, which does
3384not require callee-cleanup. See the documentation for `__fastcall`_ on MSDN.
3385
3386.. _`__fastcall`: http://msdn.microsoft.com/en-us/library/6xa169sk.aspx)reST";
3387
3388static const char AttrDoc_Final[] = R"reST()reST";
3389
3390static const char AttrDoc_FlagEnum[] = R"reST(This attribute can be added to an enumerator to signal to the compiler that it
3391is intended to be used as a flag type. This will cause the compiler to assume
3392that the range of the type includes all of the values that you can get by
3393manipulating bits of the enumerator when issuing warnings.)reST";
3394
3395static const char AttrDoc_Flatten[] = R"reST(The ``flatten`` attribute causes calls within the attributed function to
3396be inlined unless it is impossible to do so, for example if the body of the
3397callee is unavailable or if the callee has the ``noinline`` attribute.)reST";
3398
3399static const char AttrDoc_Format[] = R"reST(Clang supports the ``format`` attribute, which indicates that the function
3400accepts (among other possibilities) a ``printf`` or ``scanf``-like format string
3401and corresponding arguments or a ``va_list`` that contains these arguments.
3402
3403Please see `GCC documentation about format attribute
3404<http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_ to find details
3405about attribute syntax.
3406
3407Clang implements two kinds of checks with this attribute.
3408
3409#. Clang checks that the function with the ``format`` attribute is called with
3410 a format string that uses format specifiers that are allowed, and that
3411 arguments match the format string. This is the ``-Wformat`` warning, it is
3412 on by default.
3413
3414#. Clang checks that the format string argument is a literal string. This is
3415 the ``-Wformat-nonliteral`` warning, it is off by default.
3416
3417 Clang implements this mostly the same way as GCC, but there is a difference
3418 for functions that accept a ``va_list`` argument (for example, ``vprintf``).
3419 GCC does not emit ``-Wformat-nonliteral`` warning for calls to such
3420 functions. Clang does not warn if the format string comes from a function
3421 parameter, where the function is annotated with a compatible attribute,
3422 otherwise it warns. For example:
3423
3424 .. code-block:: c
3425
3426 __attribute__((__format__ (__scanf__, 1, 3)))
3427 void foo(const char* s, char *buf, ...) {
3428 va_list ap;
3429 va_start(ap, buf);
3430
3431 vprintf(s, ap); // warning: format string is not a string literal
3432 }
3433
3434 In this case we warn because ``s`` contains a format string for a
3435 ``scanf``-like function, but it is passed to a ``printf``-like function.
3436
3437 If the attribute is removed, clang still warns, because the format string is
3438 not a string literal.
3439
3440 Another example:
3441
3442 .. code-block:: c
3443
3444 __attribute__((__format__ (__printf__, 1, 3)))
3445 void foo(const char* s, char *buf, ...) {
3446 va_list ap;
3447 va_start(ap, buf);
3448
3449 vprintf(s, ap); // warning
3450 }
3451
3452 In this case Clang does not warn because the format string ``s`` and
3453 the corresponding arguments are annotated. If the arguments are
3454 incorrect, the caller of ``foo`` will receive a warning.
3455
3456As an extension to GCC's behavior, Clang accepts the ``format`` attribute on
3457non-variadic functions. Clang checks non-variadic format functions for the same
3458classes of issues that can be found on variadic functions, as controlled by the
3459same warning flags, except that the types of formatted arguments is forced by
3460the function signature. For example:
3461
3462.. code-block:: c
3463
3464 __attribute__((__format__(__printf__, 1, 2)))
3465 void fmt(const char *s, const char *a, int b);
3466
3467 void bar(void) {
3468 fmt("%s %i", "hello", 123); // OK
3469 fmt("%i %g", "hello", 123); // warning: arguments don't match format
3470 extern const char *fmt;
3471 fmt(fmt, "hello", 123); // warning: format string is not a string literal
3472 }
3473
3474When using the format attribute on a variadic function, the first data parameter
3475_must_ be the index of the ellipsis in the parameter list. Clang will generate
3476a diagnostic otherwise, as it wouldn't be possible to forward that argument list
3477to `printf`-family functions. For instance, this is an error:
3478
3479.. code-block:: c
3480
3481 __attribute__((__format__(__printf__, 1, 2)))
3482 void fmt(const char *s, int b, ...);
3483 // ^ error: format attribute parameter 3 is out of bounds
3484 // (must be __printf__, 1, 3)
3485
3486Using the ``format`` attribute on a non-variadic function emits a GCC
3487compatibility diagnostic.)reST";
3488
3489static const char AttrDoc_FormatArg[] = R"reST(No documentation.)reST";
3490
3491static const char AttrDoc_FormatMatches[] = R"reST(The ``format`` attribute is the basis for the enforcement of diagnostics in the
3492``-Wformat`` family, but it only handles the case where the format string is
3493passed along with the arguments it is going to format. It cannot handle the case
3494where the format string and the format arguments are passed separately from each
3495other. For instance:
3496
3497.. code-block:: c
3498
3499 static const char *first_name;
3500 static double todays_temperature;
3501 static int wind_speed;
3502
3503 void say_hi(const char *fmt) {
3504 printf(fmt, first_name, todays_temperature);
3505 // ^ warning: format string is not a string literal
3506 printf(fmt, first_name, wind_speed);
3507 // ^ warning: format string is not a string literal
3508 }
3509
3510 int main() {
3511 say_hi("hello %s, it is %g degrees outside");
3512 say_hi("hello %s, it is %d degrees outside!");
3513 // ^ no diagnostic, but %d cannot format doubles
3514 }
3515
3516In this example, ``fmt`` is expected to format a ``const char *`` and a
3517``double``, but these values are not passed to ``say_hi``. Without the
3518``format`` attribute (which cannot apply in this case), the -Wformat-nonliteral
3519diagnostic unnecessarily triggers in the body of ``say_hi``, and incorrect
3520``say_hi`` call sites do not trigger a diagnostic.
3521
3522To complement the ``format`` attribute, Clang also defines the
3523``format_matches`` attribute. Its syntax is similar to the ``format``
3524attribute's, but instead of taking the index of the first formatted value
3525argument, it takes a C string literal with the expected specifiers:
3526
3527.. code-block:: c
3528
3529 static const char *first_name;
3530 static double todays_temperature;
3531 static int wind_speed;
3532
3533 __attribute__((__format_matches__(printf, 1, "%s %g")))
3534 void say_hi(const char *fmt) {
3535 printf(fmt, first_name, todays_temperature); // no dignostic
3536 printf(fmt, first_name, wind_speed); // warning: format specifies type 'int' but the argument has type 'double'
3537 }
3538
3539 int main() {
3540 say_hi("hello %s, it is %g degrees outside");
3541 say_hi("it is %g degrees outside, have a good day %s!");
3542 // warning: format specifies 'double' where 'const char *' is required
3543 // warning: format specifies 'const char *' where 'double' is required
3544 }
3545
3546The third argument to ``format_matches`` is expected to evaluate to a **C string
3547literal** even when the format string would normally be a different type for the
3548given flavor, like a ``CFStringRef`` or a ``NSString *``.
3549
3550The only requirement on the format string literal is that it has specifiers
3551that are compatible with the arguments that will be used. It can contain
3552arbitrary non-format characters. For instance, for the purposes of compile-time
3553validation, ``"%s scored %g%% on her test"`` and ``"%s%g"`` are interchangeable
3554as the format string argument. As a means of self-documentation, users may
3555prefer the former when it provides a useful example of an expected format
3556string.
3557
3558In the implementation of a function with the ``format_matches`` attribute,
3559format verification works as if the format string was identical to the one
3560specified in the attribute.
3561
3562.. code-block:: c
3563
3564 __attribute__((__format_matches__(printf, 1, "%s %g")))
3565 void say_hi(const char *fmt) {
3566 printf(fmt, "person", 546);
3567 // ^ warning: format specifies type 'double' but the
3568 // argument has type 'int'
3569 // note: format string is defined here:
3570 // __attribute__((__format_matches__(printf, 1, "%s %g")))
3571 // ^~
3572 }
3573
3574
3575At the call sites of functions with the ``format_matches`` attribute, format
3576verification instead compares the two format strings to evaluate their
3577equivalence. Each format flavor defines equivalence between format specifiers.
3578Generally speaking, two specifiers are equivalent if they format the same type.
3579For instance, in the ``printf`` flavor, ``%2i`` and ``%-0.5d`` are compatible.
3580When ``-Wformat-signedness`` is disabled, ``%d`` and ``%u`` are compatible. For
3581a negative example, ``%ld`` is incompatible with ``%d``.
3582
3583Do note the following un-obvious cases:
3584
3585* Passing ``NULL`` as the format string does not trigger format diagnostics.
3586* When the format string is not NULL, it cannot _miss_ specifiers, even in
3587 trailing positions. For instance, ``%d`` is not accepted when the required
3588 format is ``%d %d %d``.
3589* While checks for the ``format`` attribute tolerate sone size mismatches
3590 that standard argument promotion renders immaterial (such as formatting an
3591 ``int`` with ``%hhd``, which specifies a ``char``-sized integer), checks for
3592 ``format_matches`` require specified argument sizes to match exactly.
3593* Format strings expecting a variable modifier (such as ``%*s``) are
3594 incompatible with format strings that would itemize the variable modifiers
3595 (such as ``%i %s``), even if the two specify ABI-compatible argument lists.
3596* All pointer specifiers, modifiers aside, are mutually incompatible. For
3597 instance, ``%s`` is not compatible with ``%p``, and ``%p`` is not compatible
3598 with ``%n``, and ``%hhn`` is incompatible with ``%s``, even if the pointers
3599 are ABI-compatible or identical on the selected platform. However, ``%0.5s``
3600 is compatible with ``%s``, since the difference only exists in modifier flags.
3601 This is not overridable with ``-Wformat-pedantic`` or its inverse, which
3602 control similar behavior in ``-Wformat``.
3603
3604At this time, clang implements ``format_matches`` only for format types in the
3605``printf`` family. This includes variants such as Apple's NSString format and
3606the FreeBSD ``kprintf``, but excludes ``scanf``. Using a known but unsupported
3607format silently fails in order to be compatible with other implementations that
3608would support these formats.)reST";
3609
3610static const char AttrDoc_FunctionReturnThunks[] = R"reST(The attribute ``function_return`` can replace return instructions with jumps to
3611target-specific symbols. This attribute supports 2 possible values,
3612corresponding to the values supported by the ``-mfunction-return=`` command
3613line flag:
3614
3615* ``__attribute__((function_return("keep")))`` to disable related transforms.
3616 This is useful for undoing global setting from ``-mfunction-return=`` locally
3617 for individual functions.
3618* ``__attribute__((function_return("thunk-extern")))`` to replace returns with
3619 jumps, while NOT emitting the thunk.
3620
3621The values ``thunk`` and ``thunk-inline`` from GCC are not supported.
3622
3623The symbol used for ``thunk-extern`` is target specific:
3624* X86: ``__x86_return_thunk``
3625
3626As such, this function attribute is currently only supported on X86 targets.)reST";
3627
3628static const char AttrDoc_GCCStruct[] = R"reST(The ``ms_struct`` and ``gcc_struct`` attributes request the compiler to enter a
3629special record layout compatibility mode which mimics the layout of Microsoft or
3630Itanium C++ ABI respectively. Obviously, if the current C++ ABI matches the
3631requested ABI, the attribute does nothing. However, if it does not, annotated
3632structure or class is laid out in a special compatibility mode, which slightly
3633changes offsets for fields and bit-fields. The intention is to match the layout
3634of the requested ABI for structures which only use C features.
3635
3636Note that the default behavior can be controlled by ``-mms-bitfields`` and
3637``-mno-ms-bitfields`` switches and via ``#pragma ms_struct``.
3638
3639The primary difference is for bitfields, where the MS variant only packs
3640adjacent fields into the same allocation unit if they have integral types
3641of the same size, while the GCC/Itanium variant packs all fields in a bitfield
3642tightly.)reST";
3643
3644static const char AttrDoc_GNUInline[] = R"reST(The ``gnu_inline`` changes the meaning of ``extern inline`` to use GNU inline
3645semantics, meaning:
3646
3647* If any declaration that is declared ``inline`` is not declared ``extern``,
3648 then the ``inline`` keyword is just a hint. In particular, an out-of-line
3649 definition is still emitted for a function with external linkage, even if all
3650 call sites are inlined, unlike in C99 and C++ inline semantics.
3651
3652* If all declarations that are declared ``inline`` are also declared
3653 ``extern``, then the function body is present only for inlining and no
3654 out-of-line version is emitted.
3655
3656Some important consequences: ``static inline`` emits an out-of-line
3657version if needed, a plain ``inline`` definition emits an out-of-line version
3658always, and an ``extern inline`` definition (in a header) followed by a
3659(non-``extern``) ``inline`` declaration in a source file emits an out-of-line
3660version of the function in that source file but provides the function body for
3661inlining to all includers of the header.
3662
3663Either ``__GNUC_GNU_INLINE__`` (GNU inline semantics) or
3664``__GNUC_STDC_INLINE__`` (C99 semantics) will be defined (they are mutually
3665exclusive). If ``__GNUC_STDC_INLINE__`` is defined, then the ``gnu_inline``
3666function attribute can be used to get GNU inline semantics on a per function
3667basis. If ``__GNUC_GNU_INLINE__`` is defined, then the translation unit is
3668already being compiled with GNU inline semantics as the implied default. It is
3669unspecified which macro is defined in a C++ compilation.
3670
3671GNU inline semantics are the default behavior with ``-std=gnu89``,
3672``-std=c89``, ``-fgnu89-inline``, or ``-std=iso9899:199409``.)reST";
3673
3674static const char AttrDoc_GuardedBy[] = R"reST(No documentation.)reST";
3675
3676static const char AttrDoc_GuardedVar[] = R"reST(No documentation.)reST";
3677
3678static const char AttrDoc_HIPManaged[] = R"reST(The ``__managed__`` attribute can be applied to a global variable declaration in HIP.
3679A managed variable is emitted as an undefined global symbol in the device binary and is
3680registered by ``__hipRegisterManagedVariable`` in init functions. The HIP runtime allocates
3681managed memory and uses it to define the symbol when loading the device binary.
3682A managed variable can be accessed in both device and host code.)reST";
3683
3684static const char AttrDoc_HLSLAppliedSemantic[] = R"reST()reST";
3685
3686static const char AttrDoc_HLSLAssociatedResourceDecl[] = R"reST()reST";
3687
3688static const char AttrDoc_HLSLColumnMajor[] = R"reST(The ``row_major`` and ``column_major`` keywords specify the memory layout
3689of an HLSL matrix type.
3690
3691* ``row_major``: Matrices are stored in memory row-by-row.
3692* ``column_major``: Matrices are stored in memory column-by-column (default).
3693
3694Example:
3695.. code-block:: hlsl
3696
3697 row_major float2x2 myMatrix;)reST";
3698
3699static const char AttrDoc_HLSLContainedType[] = R"reST()reST";
3700
3701static const char AttrDoc_HLSLControlFlowHint[] = R"reST()reST";
3702
3703static const char AttrDoc_HLSLGroupSharedAddressSpace[] = R"reST(HLSL enables threads of a compute shader to exchange values via shared memory.
3704HLSL provides barrier primitives such as GroupMemoryBarrierWithGroupSync,
3705and so on to ensure the correct ordering of reads and writes to shared memory
3706in the shader and to avoid data races.
3707Here's an example to declare a groupshared variable.
3708.. code-block:: c++
3709
3710 groupshared GSData data[5*5*1];
3711
3712The full documentation is available here: https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-variable-syntax#group-shared)reST";
3713
3714static const char AttrDoc_HLSLIsArray[] = R"reST()reST";
3715
3716static const char AttrDoc_HLSLIsCounter[] = R"reST()reST";
3717
3718static const char AttrDoc_HLSLLoopHint[] = R"reST(The ``[loop]`` directive allows loop optimization hints to be
3719specified for the subsequent loop. The directive allows unrolling to
3720be disabled and is not compatible with [unroll(x)].
3721
3722Specifying the parameter, ``[loop]``, directs the
3723unroller to not unroll the loop.
3724
3725.. code-block:: hlsl
3726
3727 [loop]
3728 for (...) {
3729 ...
3730 }
3731
3732.. code-block:: hlsl
3733
3734 [loop]
3735 while (...) {
3736 ...
3737 }
3738
3739.. code-block:: hlsl
3740
3741 [loop]
3742 do {
3743 ...
3744 } while (...)
3745
3746See `hlsl loop extensions <https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-for>`_
3747for details.)reST";
3748
3749static const char AttrDoc_HLSLNumThreads[] = R"reST(The ``numthreads`` attribute applies to HLSL shaders where explcit thread counts
3750are required. The ``X``, ``Y``, and ``Z`` values provided to the attribute
3751dictate the thread id. Total number of threads executed is ``X * Y * Z``.
3752
3753The full documentation is available here: https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/sm5-attributes-numthreads)reST";
3754
3755static const char AttrDoc_HLSLPackOffset[] = R"reST(The packoffset attribute is used to change the layout of a cbuffer.
3756Attribute spelling in HLSL is: ``packoffset( c[Subcomponent][.component] )``.
3757A subcomponent is a register number, which is an integer. A component is in the form of [.xyzw].
3758
3759Examples:
3760
3761.. code-block:: hlsl
3762
3763 cbuffer A {
3764 float3 a : packoffset(c0.y);
3765 float4 b : packoffset(c4);
3766 }
3767
3768The full documentation is available here: https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-variable-packoffset)reST";
3769
3770static const char AttrDoc_HLSLParamModifier[] = R"reST(HLSL function parameters are passed by value. Parameter declarations support
3771three qualifiers to denote parameter passing behavior. The three qualifiers are
3772`in`, `out` and `inout`.
3773
3774Parameters annotated with `in` or with no annotation are passed by value from
3775the caller to the callee.
3776
3777Parameters annotated with `out` are written to the argument after the callee
3778returns (Note: arguments values passed into `out` parameters *are not* copied
3779into the callee).
3780
3781Parameters annotated with `inout` are copied into the callee via a temporary,
3782and copied back to the argument after the callee returns.)reST";
3783
3784static const char AttrDoc_HLSLParsedSemantic[] = R"reST()reST";
3785
3786static const char AttrDoc_HLSLROV[] = R"reST()reST";
3787
3788static const char AttrDoc_HLSLRawBuffer[] = R"reST()reST";
3789
3790static const char AttrDoc_HLSLResourceBinding[] = R"reST(The resource binding attribute sets the virtual register and logical register space for a resource.
3791Attribute spelling in HLSL is: ``register(slot [, space])``.
3792``slot`` takes the format ``[type][number]``,
3793where ``type`` is a single character specifying the resource type and ``number`` is the virtual register number.
3794
3795Register types are:
3796t for shader resource views (SRV),
3797s for samplers,
3798u for unordered access views (UAV),
3799b for constant buffer views (CBV).
3800
3801Register space is specified in the format ``space[number]`` and defaults to ``space0`` if omitted.
3802Here're resource binding examples with and without space:
3803
3804.. code-block:: hlsl
3805
3806 RWBuffer<float> Uav : register(u3, space1);
3807 Buffer<float> Buf : register(t1);
3808
3809The full documentation is available here: https://docs.microsoft.com/en-us/windows/win32/direct3d12/resource-binding-in-hlsl)reST";
3810
3811static const char AttrDoc_HLSLResourceClass[] = R"reST()reST";
3812
3813static const char AttrDoc_HLSLResourceDimension[] = R"reST()reST";
3814
3815static const char AttrDoc_HLSLRowMajor[] = R"reST(The ``row_major`` and ``column_major`` keywords specify the memory layout
3816of an HLSL matrix type.
3817
3818* ``row_major``: Matrices are stored in memory row-by-row.
3819* ``column_major``: Matrices are stored in memory column-by-column (default).
3820
3821Example:
3822.. code-block:: hlsl
3823
3824 row_major float2x2 myMatrix;)reST";
3825
3826static const char AttrDoc_HLSLShader[] = R"reST(The ``shader`` type attribute applies to HLSL shader entry functions to
3827identify the shader type for the entry function.
3828The syntax is:
3829
3830.. code-block:: text
3831
3832 ``[shader(string-literal)]``
3833
3834where the string literal is one of: "pixel", "vertex", "geometry", "hull",
3835"domain", "compute", "raygeneration", "intersection", "anyhit", "closesthit",
3836"miss", "callable", "mesh", "amplification". Normally the shader type is set
3837by shader target with the ``-T`` option like ``-Tps_6_1``. When compiling to a
3838library target like ``lib_6_3``, the shader type attribute can help the
3839compiler to identify the shader type. It is mostly used by Raytracing shaders
3840where shaders must be compiled into a library and linked at runtime.)reST";
3841
3842static const char AttrDoc_HLSLUnparsedSemantic[] = R"reST()reST";
3843
3844static const char AttrDoc_HLSLVkBinding[] = R"reST(The ``[[vk::binding]]`` attribute allows you to explicitly specify the descriptor
3845set and binding for a resource when targeting SPIR-V. This is particularly
3846useful when you need different bindings for SPIR-V and DXIL, as the ``register``
3847attribute can be used for DXIL-specific bindings.
3848
3849The attribute takes two integer arguments: the binding and the descriptor set.
3850The descriptor set is optional and defaults to 0 if not provided.
3851
3852.. code-block:: c++
3853
3854 // A structured buffer with binding 23 in descriptor set 102.
3855 [[vk::binding(23, 102)]] StructuredBuffer<float> Buf;
3856
3857 // A structured buffer with binding 14 in descriptor set 0.
3858 [[vk::binding(14)]] StructuredBuffer<float> Buf2;
3859
3860 // A cbuffer with binding 1 in descriptor set 2.
3861 [[vk::binding(1, 2)]] cbuffer MyCBuffer {
3862 float4x4 worldViewProj;
3863 };)reST";
3864
3865static const char AttrDoc_HLSLVkConstantId[] = R"reST(The ``vk::constant_id`` attribute specifies the id for a SPIR-V specialization
3866constant. The attribute applies to const global scalar variables. The variable must be initialized with a C++11 constexpr.
3867In SPIR-V, the
3868variable will be replaced with an `OpSpecConstant` with the given id.
3869The syntax is:
3870
3871.. code-block:: text
3872
3873 ``[[vk::constant_id(<Id>)]] const T Name = <Init>``)reST";
3874
3875static const char AttrDoc_HLSLVkExtBuiltinInput[] = R"reST(Vulkan shaders have `Input` builtins. Those variables are externally
3876initialized by the driver/pipeline, but each copy is private to the current
3877lane.
3878
3879Those builtins can be declared using the `[[vk::ext_builtin_input]]` attribute
3880like follows:
3881
3882.. code-block:: c++
3883
3884 [[vk::ext_builtin_input(/* WorkgroupId */ 26)]]
3885 static const uint3 groupid;
3886
3887This variable will be lowered into a module-level variable, with the `Input`
3888storage class, and the `BuiltIn 26` decoration.
3889
3890The full documentation for this inline SPIR-V attribute can be found here:
3891https://github.com/microsoft/hlsl-specs/blob/main/proposals/0011-inline-spirv.md)reST";
3892
3893static const char AttrDoc_HLSLVkExtBuiltinOutput[] = R"reST(Vulkan shaders have `Output` builtins. Those variables are externally
3894visible to the driver/pipeline, but each copy is private to the current
3895lane.
3896
3897Those builtins can be declared using the `[[vk::ext_builtin_output]]`
3898attribute like follows:
3899
3900.. code-block:: c++
3901
3902 [[vk::ext_builtin_output(/* Position */ 0)]]
3903 static float4 position;
3904
3905This variable will be lowered into a module-level variable, with the `Output`
3906storage class, and the `BuiltIn 0` decoration.
3907
3908The full documentation for this inline SPIR-V attribute can be found here:
3909https://github.com/microsoft/hlsl-specs/blob/main/proposals/0011-inline-spirv.md)reST";
3910
3911static const char AttrDoc_HLSLVkLocation[] = R"reST(Attribute used for specifying the location number for the stage input/output
3912variables. Allowed on function parameters, function returns, and struct
3913fields. This parameter has no effect when used outside of an entrypoint
3914parameter/parameter field/return value.
3915
3916This attribute maps to the 'Location' SPIR-V decoration.)reST";
3917
3918static const char AttrDoc_HLSLVkPushConstant[] = R"reST(Vulkan shaders have `PushConstants`
3919
3920The ``[[vk::push_constant]]`` attribute allows you to declare this
3921global variable as a push constant when targeting Vulkan.
3922This attribute is ignored otherwise.
3923
3924This attribute must be applied to the variable, not underlying type.
3925The variable type must be a struct, per the requirements of Vulkan, "there
3926must be no more than one push constant block statically used per shader entry
3927point.")reST";
3928
3929static const char AttrDoc_HLSLWaveSize[] = R"reST(The ``WaveSize`` attribute specify a wave size on a shader entry point in order
3930to indicate either that a shader depends on or strongly prefers a specific wave
3931size.
3932There're 2 versions of the attribute: ``WaveSize`` and ``RangedWaveSize``.
3933The syntax for ``WaveSize`` is:
3934
3935.. code-block:: text
3936
3937 ``[WaveSize(<numLanes>)]``
3938
3939The allowed wave sizes that an HLSL shader may specify are the powers of 2
3940between 4 and 128, inclusive.
3941In other words, the set: [4, 8, 16, 32, 64, 128].
3942
3943The syntax for ``RangedWaveSize`` is:
3944
3945.. code-block:: text
3946
3947 ``[WaveSize(<minWaveSize>, <maxWaveSize>, [prefWaveSize])]``
3948
3949Where minWaveSize is the minimum wave size supported by the shader representing
3950the beginning of the allowed range, maxWaveSize is the maximum wave size
3951supported by the shader representing the end of the allowed range, and
3952prefWaveSize is the optional preferred wave size representing the size expected
3953to be the most optimal for this shader.
3954
3955``WaveSize`` is available for HLSL shader model 6.6 and later.
3956``RangedWaveSize`` available for HLSL shader model 6.8 and later.
3957
3958The full documentation is available here: https://microsoft.github.io/DirectX-Specs/d3d/HLSL_SM_6_6_WaveSize.html
3959and https://microsoft.github.io/hlsl-specs/proposals/0013-wave-size-range.html)reST";
3960
3961static const char AttrDoc_Hot[] = R"reST(``__attribute__((hot))`` marks a function as hot, as a manual alternative to PGO hotness data.
3962If PGO data is available, the annotation ``__attribute__((hot))`` overrides the profile count based hotness (unlike ``__attribute__((cold))``).)reST";
3963
3964static const char AttrDoc_HybridPatchable[] = R"reST(The ``hybrid_patchable`` attribute declares an ARM64EC function with an additional
3965x86-64 thunk, which may be patched at runtime.
3966
3967For more information see
3968`ARM64EC ABI documentation <https://learn.microsoft.com/en-us/windows/arm/arm64ec-abi>`_.)reST";
3969
3970static const char AttrDoc_IBAction[] = R"reST(No documentation.)reST";
3971
3972static const char AttrDoc_IBOutlet[] = R"reST(No documentation.)reST";
3973
3974static const char AttrDoc_IBOutletCollection[] = R"reST(No documentation.)reST";
3975
3976static const char AttrDoc_IFunc[] = R"reST(``__attribute__((ifunc("resolver")))`` is used to mark that the address of a
3977declaration should be resolved at runtime by calling a resolver function.
3978
3979The symbol name of the resolver function is given in quotes. A function with
3980this name (after mangling) must be defined in the current translation unit; it
3981may be ``static``. The resolver function should return a pointer.
3982
3983The ``ifunc`` attribute may only be used on a function declaration. A function
3984declaration with an ``ifunc`` attribute is considered to be a definition of the
3985declared entity. The entity must not have weak linkage; for example, in C++,
3986it cannot be applied to a declaration if a definition at that location would be
3987considered inline.
3988
3989Not all targets support this attribute:
3990
3991- ELF target support depends on both the linker and runtime linker, and is
3992 available in at least lld 4.0 and later, binutils 2.20.1 and later, glibc
3993 v2.11.1 and later, and FreeBSD 9.1 and later.
3994- Mach-O targets support it, but with slightly different semantics: the resolver
3995 is run at first call, instead of at load time by the runtime linker.
3996- Windows target supports it on AArch64, but with different semantics: the
3997 ``ifunc`` is replaced with a global function pointer, and the call is replaced
3998 with an indirect call. The function pointer is initialized by a constructor
3999 that calls the resolver.
4000- Baremetal target supports it on AVR.
4001- AIX/XCOFF supports it via a compiler-only solution. An ifunc appears as a
4002 regular function (has an entry point ``.foo[PR]`` and a function descriptor
4003 ``foo[DS]``). The entry point is a stub that branches to the function address
4004 in the descriptor, and the descriptor is initialized via a constructor
4005 function (``__init_ifuncs``) that is linked into every shared object and
4006 executable. ``__init_ifuncs`` calls the resolver of each ifunc and stores the
4007 result in the corresponding descriptor.
4008- Other targets currently do not support this attribute.)reST";
4009
4010static const char AttrDoc_InferredNoReturn[] = R"reST()reST";
4011
4012static const char AttrDoc_InitPriority[] = R"reST(In C++, the order in which global variables are initialized across translation
4013units is unspecified, unlike the ordering within a single translation unit. The
4014``init_priority`` attribute allows you to specify a relative ordering for the
4015initialization of objects declared at namespace scope in C++ within a single
4016linked image on supported platforms. The priority is given as an integer constant
4017expression between 101 and 65535 (inclusive). Priorities outside of that range are
4018reserved for use by the implementation. A lower value indicates a higher priority
4019of initialization. Note that only the relative ordering of values is important.
4020For example:
4021
4022.. code-block:: c++
4023
4024 struct SomeType { SomeType(); };
4025 __attribute__((init_priority(200))) SomeType Obj1;
4026 __attribute__((init_priority(101))) SomeType Obj2;
4027
4028``Obj2`` will be initialized *before* ``Obj1`` despite the usual order of
4029initialization being the opposite.
4030
4031Note that this attribute does not control the initialization order of objects
4032across final linked image boundaries like shared objects and executables.
4033
4034On Windows, ``init_seg(compiler)`` is represented with a priority of 200 and
4035``init_seg(library)`` is represented with a priority of 400. ``init_seg(user)``
4036uses the default 65535 priority.
4037
4038On MachO platforms, this attribute also does not control the order of initialization
4039across translation units, where it only affects the order within a single TU.
4040
4041This attribute is only supported for C++ and Objective-C++ and is ignored in
4042other language modes.)reST";
4043
4044static const char AttrDoc_InitSeg[] = R"reST(The attribute applied by ``pragma init_seg()`` controls the section into
4045which global initialization function pointers are emitted. It is only
4046available with ``-fms-extensions``. Typically, this function pointer is
4047emitted into ``.CRT$XCU`` on Windows. The user can change the order of
4048initialization by using a different section name with the same
4049``.CRT$XC`` prefix and a suffix that sorts lexicographically before or
4050after the standard ``.CRT$XCU`` sections. See the init_seg_
4051documentation on MSDN for more information.
4052
4053.. _init_seg: http://msdn.microsoft.com/en-us/library/7977wcck(v=vs.110).aspx)reST";
4054
4055static const char AttrDoc_IntelOclBicc[] = R"reST(No documentation.)reST";
4056
4057static const char AttrDoc_InternalLinkage[] = R"reST(The ``internal_linkage`` attribute changes the linkage type of the declaration
4058to internal. This is similar to C-style ``static``, but can be used on classes
4059and class methods. When applied to a class definition, this attribute affects
4060all methods and static data members of that class. This can be used to contain
4061the ABI of a C++ library by excluding unwanted class methods from the export
4062tables.)reST";
4063
4064static const char AttrDoc_LTOVisibilityPublic[] = R"reST(See :doc:`LTOVisibility`.)reST";
4065
4066static const char AttrDoc_LayoutVersion[] = R"reST(The layout_version attribute requests that the compiler utilize the class
4067layout rules of a particular compiler version.
4068This attribute only applies to struct, class, and union types.
4069It is only supported when using the Microsoft C++ ABI.)reST";
4070
4071static const char AttrDoc_Leaf[] = R"reST(The ``leaf`` attribute is used as a compiler hint to improve dataflow analysis
4072in library functions. Functions marked with the ``leaf`` attribute are not allowed
4073to jump back into the caller's translation unit, whether through invoking a
4074callback function, an external function call, use of ``longjmp``, or other means.
4075Therefore, they cannot use or modify any data that does not escape the caller function's
4076compilation unit.
4077
4078For more information see
4079`gcc documentation <https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html>`)reST";
4080
4081static const char AttrDoc_LifetimeBound[] = R"reST(The ``lifetimebound`` attribute on a function parameter or implicit object
4082parameter indicates that objects that are referred to by that parameter may
4083also be referred to by the return value of the annotated function (or, for a
4084parameter of a constructor, by the value of the constructed object).
4085
4086By default, a reference is considered to refer to its referenced object, a
4087pointer is considered to refer to its pointee, a ``std::initializer_list<T>``
4088is considered to refer to its underlying array, and aggregates (arrays and
4089simple ``struct``\s) are considered to refer to all objects that their
4090transitive subobjects refer to.
4091
4092Clang warns if it is able to detect that an object or reference refers to
4093another object with a shorter lifetime. For example, Clang will warn if a
4094function returns a reference to a local variable, or if a reference is bound to
4095a temporary object whose lifetime is not extended. By using the
4096``lifetimebound`` attribute, this determination can be extended to look through
4097user-declared functions. For example:
4098
4099.. code-block:: c++
4100
4101 #include <map>
4102 #include <string>
4103
4104 using namespace std::literals;
4105
4106 // Returns m[key] if key is present, or default_value if not.
4107 template<typename T, typename U>
4108 const U &get_or_default(const std::map<T, U> &m [[clang::lifetimebound]],
4109 const T &key, /* note, not lifetimebound */
4110 const U &default_value [[clang::lifetimebound]]) {
4111 if (auto iter = m.find(key); iter != m.end()) return iter->second;
4112 else return default_value;
4113 }
4114
4115 int main() {
4116 std::map<std::string, std::string> m;
4117 // warning: temporary bound to local reference 'val1' will be destroyed
4118 // at the end of the full-expression
4119 const std::string &val1 = get_or_default(m, "foo"s, "bar"s);
4120
4121 // No warning in this case.
4122 std::string def_val = "bar"s;
4123 const std::string &val2 = get_or_default(m, "foo"s, def_val);
4124
4125 return 0;
4126 }
4127
4128The attribute can be applied to the implicit ``this`` parameter of a member
4129function by writing the attribute after the function type:
4130
4131.. code-block:: c++
4132
4133 struct string {
4134 // The returned pointer should not outlive ``*this``.
4135 const char *data() const [[clang::lifetimebound]];
4136 };
4137
4138This attribute is inspired by the C++ committee paper `P0936R0
4139<http://wg21.link/p0936r0>`_, but does not affect whether temporary objects
4140have their lifetimes extended.)reST";
4141
4142static const char AttrDoc_LifetimeCaptureBy[] = R"reST(Similar to `lifetimebound`_, the ``lifetime_capture_by`` attribute family on a
4143function parameter or implicit object parameter indicates that a capturing
4144entity may refer to the object referred to by that parameter. The capturing
4145entity can be named in ``lifetime_capture_by(X)`` or selected by one of the
4146standalone special forms listed below.
4147
4148Below is a list of types of the parameters and what they're considered to refer to:
4149
4150- A reference param (of non-view type) is considered to refer to its referenced object.
4151- A pointer param (of non-view type) is considered to refer to its pointee.
4152- View type param (type annotated with ``[[gsl::Pointer()]]``) is considered to refer
4153 to its pointee (gsl owner). This holds true even if the view type appears as a reference
4154 in the parameter. For example, both ``std::string_view`` and
4155 ``const std::string_view &`` are considered to refer to a ``std::string``.
4156- A ``std::initializer_list<T>`` is considered to refer to its underlying array.
4157- Aggregates (arrays and simple ``struct``\s) are considered to refer to all
4158 objects that their transitive subobjects refer to.
4159
4160Clang would diagnose when a temporary object is used as an argument to such an
4161annotated parameter.
4162In this case, the capturing entity ``X`` could capture a dangling reference to this
4163temporary object.
4164
4165.. code-block:: c++
4166
4167 void addToSet(std::string_view a [[clang::lifetime_capture_by(s)]], std::set<std::string_view>& s) {
4168 s.insert(a);
4169 }
4170 void use() {
4171 std::set<std::string_view> s;
4172 addToSet(std::string(), s); // Warning: object whose reference is captured by 's' will be destroyed at the end of the full-expression.
4173 // ^^^^^^^^^^^^^
4174 std::string local;
4175 addToSet(local, s); // Ok.
4176 }
4177
4178The capturing entity can be one of the following:
4179
4180- Another (named) function parameter.
4181
4182 .. code-block:: c++
4183
4184 void addToSet(std::string_view a [[clang::lifetime_capture_by(s)]], std::set<std::string_view>& s) {
4185 s.insert(a);
4186 }
4187
4188- ``this`` (in case of member functions), written as
4189 ``lifetime_capture_by_this``.
4190
4191 .. code-block:: c++
4192
4193 class S {
4194 void addToSet(std::string_view a [[clang::lifetime_capture_by_this]]) {
4195 s.insert(a);
4196 }
4197 std::set<std::string_view> s;
4198 };
4199
4200 Note: When applied to a constructor parameter, `[[clang::lifetime_capture_by_this]]` is just an alias of `[[clang::lifetimebound]]`.
4201
4202- ``global`` and ``unknown``, written as ``lifetime_capture_by_global`` and
4203 ``lifetime_capture_by_unknown`` respectively.
4204
4205 .. code-block:: c++
4206
4207 std::set<std::string_view> s;
4208 void addToSet(std::string_view a [[clang::lifetime_capture_by_global]]) {
4209 s.insert(a);
4210 }
4211 void addSomewhere(std::string_view a [[clang::lifetime_capture_by_unknown]]);
4212
4213The attribute can be applied to the implicit ``this`` parameter of a member
4214function by writing the attribute after the function type:
4215
4216.. code-block:: c++
4217
4218 struct S {
4219 const char *data(std::set<S*>& s) [[clang::lifetime_capture_by(s)]] {
4220 s.insert(this);
4221 }
4222 };
4223
4224The parameter-list form supports specifying more than one capturing entity:
4225
4226.. code-block:: c++
4227
4228 void addToSets(std::string_view a [[clang::lifetime_capture_by(s1, s2)]],
4229 std::set<std::string_view>& s1,
4230 std::set<std::string_view>& s2) {
4231 s1.insert(a);
4232 s2.insert(a);
4233 }
4234
4235Distinct ``lifetime_capture_by`` forms can also be combined on the same
4236declaration, but each form can appear at most once. For example,
4237``[[clang::lifetime_capture_by(s), clang::lifetime_capture_by_this]]`` is
4238allowed, but two ``[[clang::lifetime_capture_by(...)]]`` attributes or two
4239``[[clang::lifetime_capture_by_this]]`` attributes on the same declaration are
4240rejected.
4241
4242Limitation: The capturing entity ``X`` is not used by the analysis and is
4243used for documentation purposes only. This is because the analysis is
4244statement-local and only detects use of a temporary as an argument to the
4245annotated parameter.
4246
4247.. code-block:: c++
4248
4249 void addToSet(std::string_view a [[clang::lifetime_capture_by(s)]], std::set<std::string_view>& s);
4250 void use() {
4251 std::set<std::string_view> s;
4252 if (foo()) {
4253 std::string str;
4254 addToSet(str, s); // Not detected.
4255 }
4256 })reST";
4257
4258static const char AttrDoc_Likely[] = R"reST(The ``likely`` and ``unlikely`` attributes are used as compiler hints.
4259The attributes are used to aid the compiler to determine which branch is
4260likely or unlikely to be taken. This is done by marking the branch substatement
4261with one of the two attributes.
4262
4263It isn't allowed to annotate a single statement with both ``likely`` and
4264``unlikely``. Annotating the ``true`` and ``false`` branch of an ``if``
4265statement with the same likelihood attribute will result in a diagnostic and
4266the attributes are ignored on both branches.
4267
4268In a ``switch`` statement it's allowed to annotate multiple ``case`` labels
4269or the ``default`` label with the same likelihood attribute. This makes
4270* all labels without an attribute have a neutral likelihood,
4271* all labels marked ``[[likely]]`` have an equally positive likelihood, and
4272* all labels marked ``[[unlikely]]`` have an equally negative likelihood.
4273The neutral likelihood is the more likely of path execution than the negative
4274likelihood. The positive likelihood is the more likely of path of execution
4275than the neutral likelihood.
4276
4277These attributes have no effect on the generated code when using
4278PGO (Profile-Guided Optimization) or at optimization level 0.
4279
4280In Clang, the attributes will be ignored if they're not placed on
4281* the ``case`` or ``default`` label of a ``switch`` statement,
4282* or on the substatement of an ``if`` or ``else`` statement,
4283* or on the substatement of an ``for`` or ``while`` statement.
4284The C++ Standard recommends to honor them on every statement in the
4285path of execution, but that can be confusing:
4286
4287.. code-block:: c++
4288
4289 if (b) {
4290 [[unlikely]] --b; // Per the standard this is in the path of
4291 // execution, so this branch should be considered
4292 // unlikely. However, Clang ignores the attribute
4293 // here since it is not on the substatement.
4294 }
4295
4296 if (b) {
4297 --b;
4298 if(b)
4299 return;
4300 [[unlikely]] --b; // Not in the path of execution,
4301 } // the branch has no likelihood information.
4302
4303 if (b) {
4304 --b;
4305 foo(b);
4306 // Whether or not the next statement is in the path of execution depends
4307 // on the declaration of foo():
4308 // In the path of execution: void foo(int);
4309 // Not in the path of execution: [[noreturn]] void foo(int);
4310 // This means the likelihood of the branch depends on the declaration
4311 // of foo().
4312 [[unlikely]] --b;
4313 }
4314
4315
4316Below are some example usages of the likelihood attributes and their effects:
4317
4318.. code-block:: c++
4319
4320 if (b) [[likely]] { // Placement on the first statement in the branch.
4321 // The compiler will optimize to execute the code here.
4322 } else {
4323 }
4324
4325 if (b)
4326 [[unlikely]] b++; // Placement on the first statement in the branch.
4327 else {
4328 // The compiler will optimize to execute the code here.
4329 }
4330
4331 if (b) {
4332 [[unlikely]] b++; // Placement on the second statement in the branch.
4333 } // The attribute will be ignored.
4334
4335 if (b) [[likely]] {
4336 [[unlikely]] b++; // No contradiction since the second attribute
4337 } // is ignored.
4338
4339 if (b)
4340 ;
4341 else [[likely]] {
4342 // The compiler will optimize to execute the code here.
4343 }
4344
4345 if (b)
4346 ;
4347 else
4348 // The compiler will optimize to execute the next statement.
4349 [[likely]] b = f();
4350
4351 if (b) [[likely]]; // Both branches are likely. A diagnostic is issued
4352 else [[likely]]; // and the attributes are ignored.
4353
4354 if (b)
4355 [[likely]] int i = 5; // Issues a diagnostic since the attribute
4356 // isn't allowed on a declaration.
4357
4358 switch (i) {
4359 [[likely]] case 1: // This value is likely
4360 ...
4361 break;
4362
4363 [[unlikely]] case 2: // This value is unlikely
4364 ...
4365 [[fallthrough]];
4366
4367 case 3: // No likelihood attribute
4368 ...
4369 [[likely]] break; // No effect
4370
4371 case 4: [[likely]] { // attribute on substatement has no effect
4372 ...
4373 break;
4374 }
4375
4376 [[unlikely]] default: // All other values are unlikely
4377 ...
4378 break;
4379 }
4380
4381 switch (i) {
4382 [[likely]] case 0: // This value and code path is likely
4383 ...
4384 [[fallthrough]];
4385
4386 case 1: // No likelihood attribute, code path is neutral
4387 break; // falling through has no effect on the likelihood
4388
4389 case 2: // No likelihood attribute, code path is neutral
4390 [[fallthrough]];
4391
4392 [[unlikely]] default: // This value and code path are both unlikely
4393 break;
4394 }
4395
4396 for(int i = 0; i != size; ++i) [[likely]] {
4397 ... // The loop is the likely path of execution
4398 }
4399
4400 for(const auto &E : Elements) [[likely]] {
4401 ... // The loop is the likely path of execution
4402 }
4403
4404 while(i != size) [[unlikely]] {
4405 ... // The loop is the unlikely path of execution
4406 } // The generated code will optimize to skip the loop body
4407
4408 while(true) [[unlikely]] {
4409 ... // The attribute has no effect
4410 } // Clang elides the comparison and generates an infinite
4411 // loop)reST";
4412
4413static const char AttrDoc_LoaderUninitialized[] = R"reST(The ``loader_uninitialized`` attribute can be placed on global variables to
4414indicate that the variable does not need to be zero initialized by the loader.
4415On most targets, zero-initialization does not incur any additional cost.
4416For example, most general purpose operating systems deliberately ensure
4417that all memory is properly initialized in order to avoid leaking privileged
4418information from the kernel or other programs. However, some targets
4419do not make this guarantee, and on these targets, avoiding an unnecessary
4420zero-initialization can have a significant impact on load times and/or code
4421size.
4422
4423A declaration with this attribute is a non-tentative definition just as if it
4424provided an initializer. Variables with this attribute are considered to be
4425uninitialized in the same sense as a local variable, and the programs must
4426write to them before reading from them. If the variable's type is a C++ class
4427type with a non-trivial default constructor, or an array thereof, this attribute
4428only suppresses the static zero-initialization of the variable, not the dynamic
4429initialization provided by executing the default constructor.)reST";
4430
4431static const char AttrDoc_LockReturned[] = R"reST(No documentation.)reST";
4432
4433static const char AttrDoc_LocksExcluded[] = R"reST(No documentation.)reST";
4434
4435static const char AttrDoc_LoopHint[] = R"reST(The ``#pragma clang loop`` directive allows loop optimization hints to be
4436specified for the subsequent loop. The directive allows pipelining to be
4437disabled, or vectorization, vector predication, interleaving, and unrolling to
4438be enabled or disabled. Vector width, vector predication, interleave count,
4439unrolling count, and the initiation interval for pipelining can be explicitly
4440specified. See `language extensions
4441<http://clang.llvm.org/docs/LanguageExtensions.html#extensions-for-loop-hint-optimizations>`_
4442for details.)reST";
4443
4444static const char AttrDoc_M68kInterrupt[] = R"reST(No documentation.)reST";
4445
4446static const char AttrDoc_M68kRTD[] = R"reST(On M68k targets, this attribute changes the calling convention of a function
4447to clear parameters off the stack on return. In other words, callee is
4448responsible for cleaning out the stack space allocated for incoming paramters.
4449This convention does not support variadic calls or unprototyped functions in C.
4450When targeting M68010 or newer CPUs, this calling convention is implemented
4451using the `rtd` instruction.)reST";
4452
4453static const char AttrDoc_MIGServerRoutine[] = R"reST(The Mach Interface Generator release-on-success convention dictates
4454functions that follow it to only release arguments passed to them when they
4455return "success" (a ``kern_return_t`` error code that indicates that
4456no errors have occurred). Otherwise the release is performed by the MIG client
4457that called the function. The annotation ``__attribute__((mig_server_routine))``
4458is applied in order to specify which functions are expected to follow the
4459convention. This allows the Static Analyzer to find bugs caused by violations of
4460that convention. The attribute would normally appear on the forward declaration
4461of the actual server routine in the MIG server header, but it may also be
4462added to arbitrary functions that need to follow the same convention - for
4463example, a user can add them to auxiliary functions called by the server routine
4464that have their return value of type ``kern_return_t`` unconditionally returned
4465from the routine. The attribute can be applied to C++ methods, and in this case
4466it will be automatically applied to overrides if the method is virtual. The
4467attribute can also be written using C++11 syntax: ``[[mig::server_routine]]``.)reST";
4468
4469static const char AttrDoc_MSABI[] = R"reST(On non-Windows x86_64 and aarch64 targets, this attribute changes the calling convention of
4470a function to match the default convention used on Windows. This
4471attribute has no effect on Windows targets or non-x86_64, non-aarch64 targets.)reST";
4472
4473static const char AttrDoc_MSAllocator[] = R"reST(The ``__declspec(allocator)`` attribute is applied to functions that allocate
4474memory, such as operator new in C++. When CodeView debug information is emitted
4475(enabled by ``clang -gcodeview`` or ``clang-cl /Z7``), Clang will attempt to
4476record the code offset of heap allocation call sites in the debug info. It will
4477also record the type being allocated using some local heuristics. The Visual
4478Studio debugger uses this information to `profile memory usage`_.
4479
4480.. _profile memory usage: https://docs.microsoft.com/en-us/visualstudio/profiling/memory-usage
4481
4482This attribute does not affect optimizations in any way, unlike GCC's
4483``__attribute__((malloc))``.)reST";
4484
4485static const char AttrDoc_MSConstexpr[] = R"reST(The ``[[msvc::constexpr]]`` attribute can be applied only to a function
4486definition or a ``return`` statement. It does not impact function declarations.
4487A ``[[msvc::constexpr]]`` function cannot be ``constexpr`` or ``consteval``.
4488A ``[[msvc::constexpr]]`` function is treated as if it were a ``constexpr`` function
4489when it is evaluated in a constant context of ``[[msvc::constexpr]] return`` statement.
4490Otherwise, it is treated as a regular function.
4491
4492Semantics of this attribute are enabled only under MSVC compatibility
4493(``-fms-compatibility-version``) 19.33 and later.)reST";
4494
4495static const char AttrDoc_MSInheritance[] = R"reST(This collection of keywords is enabled under ``-fms-extensions`` and controls
4496the pointer-to-member representation used on ``*-*-win32`` targets.
4497
4498The ``*-*-win32`` targets utilize a pointer-to-member representation which
4499varies in size and alignment depending on the definition of the underlying
4500class.
4501
4502However, this is problematic when a forward declaration is only available and
4503no definition has been made yet. In such cases, Clang is forced to utilize the
4504most general representation that is available to it.
4505
4506These keywords make it possible to use a pointer-to-member representation other
4507than the most general one regardless of whether or not the definition will ever
4508be present in the current translation unit.
4509
4510This family of keywords belong between the ``class-key`` and ``class-name``:
4511
4512.. code-block:: c++
4513
4514 struct __single_inheritance S;
4515 int S::*i;
4516 struct S {};
4517
4518This keyword can be applied to class templates but only has an effect when used
4519on full specializations:
4520
4521.. code-block:: c++
4522
4523 template <typename T, typename U> struct __single_inheritance A; // warning: inheritance model ignored on primary template
4524 template <typename T> struct __multiple_inheritance A<T, T>; // warning: inheritance model ignored on partial specialization
4525 template <> struct __single_inheritance A<int, float>;
4526
4527Note that choosing an inheritance model less general than strictly necessary is
4528an error:
4529
4530.. code-block:: c++
4531
4532 struct __multiple_inheritance S; // error: inheritance model does not match definition
4533 int S::*i;
4534 struct S {};)reST";
4535
4536static const char AttrDoc_MSNoVTable[] = R"reST(This attribute can be added to a class declaration or definition to signal to
4537the compiler that constructors and destructors will not reference the virtual
4538function table. It is only supported when using the Microsoft C++ ABI.)reST";
4539
4540static const char AttrDoc_MSP430Interrupt[] = R"reST(No documentation.)reST";
4541
4542static const char AttrDoc_MSStruct[] = R"reST(The ``ms_struct`` and ``gcc_struct`` attributes request the compiler to enter a
4543special record layout compatibility mode which mimics the layout of Microsoft or
4544Itanium C++ ABI respectively. Obviously, if the current C++ ABI matches the
4545requested ABI, the attribute does nothing. However, if it does not, annotated
4546structure or class is laid out in a special compatibility mode, which slightly
4547changes offsets for fields and bit-fields. The intention is to match the layout
4548of the requested ABI for structures which only use C features.
4549
4550Note that the default behavior can be controlled by ``-mms-bitfields`` and
4551``-mno-ms-bitfields`` switches and via ``#pragma ms_struct``.
4552
4553The primary difference is for bitfields, where the MS variant only packs
4554adjacent fields into the same allocation unit if they have integral types
4555of the same size, while the GCC/Itanium variant packs all fields in a bitfield
4556tightly.)reST";
4557
4558static const char AttrDoc_MSVtorDisp[] = R"reST()reST";
4559
4560static const char AttrDoc_MallocSpan[] = R"reST(The ``malloc_span`` attribute can be used to mark that a function which acts
4561like a system memory allocation function and returns a span-like structure,
4562where the returned memory range does not alias storage from any other object
4563accessible to the caller.
4564
4565In this context, a span-like structure is assumed to have two non-static data
4566members, one of which is a pointer to the start of the allocated memory and
4567the other one is either an integer type containing the size of the actually
4568allocated memory or a pointer to the end of the allocated region. Note, static
4569data members do not impact whether a type is span-like or not.)reST";
4570
4571static const char AttrDoc_MaxFieldAlignment[] = R"reST()reST";
4572
4573static const char AttrDoc_MayAlias[] = R"reST(No documentation.)reST";
4574
4575static const char AttrDoc_MaybeUndef[] = R"reST(The ``maybe_undef`` attribute can be placed on a function parameter. It indicates
4576that the parameter is allowed to use undef values. It informs the compiler
4577to insert a freeze LLVM IR instruction on the function parameter.
4578Please note that this is an attribute that is used as an internal
4579implementation detail and not intended to be used by external users.
4580
4581In languages HIP, CUDA etc., some functions have multi-threaded semantics and
4582it is enough for only one or some threads to provide defined arguments.
4583Depending on semantics, undef arguments in some threads don't produce
4584undefined results in the function call. Since, these functions accept undefined
4585arguments, ``maybe_undef`` attribute can be placed.
4586
4587Sample usage:
4588.. code-block:: c
4589
4590 void maybeundeffunc(int __attribute__((maybe_undef))param);)reST";
4591
4592static const char AttrDoc_MicroMips[] = R"reST(Clang supports the GNU style ``__attribute__((micromips))`` and
4593``__attribute__((nomicromips))`` attributes on MIPS targets. These attributes
4594may be attached to a function definition and instructs the backend to generate
4595or not to generate microMIPS code for that function.
4596
4597These attributes override the ``-mmicromips`` and ``-mno-micromips`` options
4598on the command line.)reST";
4599
4600static const char AttrDoc_MinSize[] = R"reST(This function attribute indicates that optimization passes and code generator passes
4601make choices that keep the function code size as small as possible. Optimizations may
4602also sacrifice runtime performance in order to minimize the size of the generated code.)reST";
4603
4604static const char AttrDoc_MinVectorWidth[] = R"reST(Clang supports the ``__attribute__((min_vector_width(width)))`` attribute. This
4605attribute may be attached to a function and informs the backend that this
4606function desires vectors of at least this width to be generated. Target-specific
4607maximum vector widths still apply. This means even if you ask for something
4608larger than the target supports, you will only get what the target supports.
4609This attribute is meant to be a hint to control target heuristics that may
4610generate narrower vectors than what the target hardware supports.
4611
4612This is currently used by the X86 target to allow some CPUs that support 512-bit
4613vectors to be limited to using 256-bit vectors to avoid frequency penalties.
4614This is currently enabled with the ``-prefer-vector-width=256`` command line
4615option. The ``min_vector_width`` attribute can be used to prevent the backend
4616from trying to split vector operations to match the ``prefer-vector-width``. All
4617X86 vector intrinsics from x86intrin.h already set this attribute. Additionally,
4618use of any of the X86-specific vector builtins will implicitly set this
4619attribute on the calling function. The intent is that explicitly writing vector
4620code using the X86 intrinsics will prevent ``prefer-vector-width`` from
4621affecting the code.)reST";
4622
4623static const char AttrDoc_Mips16[] = R"reST(No documentation.)reST";
4624
4625static const char AttrDoc_MipsInterrupt[] = R"reST(Clang supports the GNU style ``__attribute__((interrupt("ARGUMENT")))`` attribute on
4626MIPS targets. This attribute may be attached to a function definition and instructs
4627the backend to generate appropriate function entry/exit code so that it can be used
4628directly as an interrupt service routine.
4629
4630By default, the compiler will produce a function prologue and epilogue suitable for
4631an interrupt service routine that handles an External Interrupt Controller (eic)
4632generated interrupt. This behavior can be explicitly requested with the "eic"
4633argument.
4634
4635Otherwise, for use with vectored interrupt mode, the argument passed should be
4636of the form "vector=LEVEL" where LEVEL is one of the following values:
4637"sw0", "sw1", "hw0", "hw1", "hw2", "hw3", "hw4", "hw5". The compiler will
4638then set the interrupt mask to the corresponding level which will mask all
4639interrupts up to and including the argument.
4640
4641The semantics are as follows:
4642
4643- The prologue is modified so that the Exception Program Counter (EPC) and
4644 Status coprocessor registers are saved to the stack. The interrupt mask is
4645 set so that the function can only be interrupted by a higher priority
4646 interrupt. The epilogue will restore the previous values of EPC and Status.
4647
4648- The prologue and epilogue are modified to save and restore all non-kernel
4649 registers as necessary.
4650
4651- The FPU is disabled in the prologue, as the floating pointer registers are not
4652 spilled to the stack.
4653
4654- The function return sequence is changed to use an exception return instruction.
4655
4656- The parameter sets the interrupt mask for the function corresponding to the
4657 interrupt level specified. If no mask is specified the interrupt mask
4658 defaults to "eic".)reST";
4659
4660static const char AttrDoc_MipsLongCall[] = R"reST(Clang supports the ``__attribute__((long_call))``, ``__attribute__((far))``,
4661and ``__attribute__((near))`` attributes on MIPS targets. These attributes may
4662only be added to function declarations and change the code generated
4663by the compiler when directly calling the function. The ``near`` attribute
4664allows calls to the function to be made using the ``jal`` instruction, which
4665requires the function to be located in the same naturally aligned 256MB
4666segment as the caller. The ``long_call`` and ``far`` attributes are synonyms
4667and require the use of a different call sequence that works regardless
4668of the distance between the functions.
4669
4670These attributes have no effect for position-independent code.
4671
4672These attributes take priority over command line switches such
4673as ``-mlong-calls`` and ``-mno-long-calls``.)reST";
4674
4675static const char AttrDoc_MipsShortCall[] = R"reST(Clang supports the ``__attribute__((long_call))``, ``__attribute__((far))``,
4676``__attribute__((short__call))``, and ``__attribute__((near))`` attributes
4677on MIPS targets. These attributes may only be added to function declarations
4678and change the code generated by the compiler when directly calling
4679the function. The ``short_call`` and ``near`` attributes are synonyms and
4680allow calls to the function to be made using the ``jal`` instruction, which
4681requires the function to be located in the same naturally aligned 256MB segment
4682as the caller. The ``long_call`` and ``far`` attributes are synonyms and
4683require the use of a different call sequence that works regardless
4684of the distance between the functions.
4685
4686These attributes have no effect for position-independent code.
4687
4688These attributes take priority over command line switches such
4689as ``-mlong-calls`` and ``-mno-long-calls``.)reST";
4690
4691static const char AttrDoc_Mode[] = R"reST(No documentation.)reST";
4692
4693static const char AttrDoc_ModularFormat[] = R"reST(The ``modular_format`` attribute can be applied to a function that bears the
4694``format`` attribute (or standard library functions) to indicate that the
4695implementation is "modular", that is, that the implementation is logically
4696divided into a number of named aspects. When the compiler can determine that
4697not all aspects of the implementation are needed for a given call, the compiler
4698may redirect the call to the identifier given as the first argument to the
4699attribute (the modular implementation function).
4700
4701The second argument is an implementation name, and the remaining arguments are
4702aspects of the format string for the compiler to report. The implementation
4703name is an unevaluated identifier in the C namespace.
4704
4705The compiler reports that a call requires an aspect by issuing a relocation for
4706the symbol ``<impl_name>_<aspect>`` at the point of the call. This arranges for
4707code and data needed to support the aspect of the implementation to be brought
4708into the link to satisfy weak references in the modular implemenation function.
4709If the compiler does not understand an aspect, it must summarily consider any
4710call to require that aspect.
4711
4712For example, say ``printf`` is annotated with
4713``modular_format(__modular_printf, "__printf", "float")``. Then, a call to
4714``printf(var, 42)`` would be untouched. A call to ``printf("%d", 42)`` would
4715become a call to ``__modular_printf`` with the same arguments, as would
4716``printf("%f", 42.0)``. The latter would be accompanied with a strong
4717relocation against the symbol ``__printf_float``, which would bring floating
4718point support for ``printf`` into the link.
4719
4720If the attribute appears more than once on a declaration, or across a chain of
4721redeclarations, it is an error for the attributes to have different arguments,
4722excepting that the aspects may be in any order.
4723
4724The following aspects are currently supported:
4725
4726- ``fixed``: The call has a C ISO 18037 fixed-point argument.
4727- ``float``: The call has a floating-point argument.)reST";
4728
4729static const char AttrDoc_MustTail[] = R"reST(If a ``return`` statement is marked ``musttail``, this indicates that the
4730compiler must generate a tail call for the program to be correct, even when
4731optimizations are disabled. This guarantees that the call will not cause
4732unbounded stack growth if it is part of a recursive cycle in the call graph.
4733
4734If the callee is a virtual function that is implemented by a thunk, there is
4735no guarantee in general that the thunk tail-calls the implementation of the
4736virtual function, so such a call in a recursive cycle can still result in
4737unbounded stack growth.
4738
4739``clang::musttail`` can only be applied to a ``return`` statement whose value
4740is the result of a function call (even functions returning void must use
4741``return``, although no value is returned). The target function must have the
4742same number of arguments as the caller. The types of the return value and all
4743arguments must be similar according to C++ rules (differing only in cv
4744qualifiers or array size), including the implicit "this" argument, if any.
4745Any variables in scope, including all arguments to the function and the
4746return value must be trivially destructible. The calling convention of the
4747caller and callee must match, and they must not be variadic functions or have
4748old style K&R C function declarations.
4749
4750The lifetimes of all local variables and function parameters end immediately
4751before the call to the function. This means that it is undefined behaviour to
4752pass a pointer or reference to a local variable to the called function, which
4753is not the case without the attribute. Clang will emit a warning in common
4754cases where this happens.
4755
4756``clang::musttail`` provides assurances that the tail call can be optimized on
4757all targets, not just one.)reST";
4758
4759static const char AttrDoc_NSConsumed[] = R"reST(The behavior of a function with respect to reference counting for Foundation
4760(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
4761convention (e.g. functions starting with "get" are assumed to return at
4762``+0``).
4763
4764It can be overridden using a family of the following attributes. In
4765Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
4766a function communicates that the object is returned at ``+1``, and the caller
4767is responsible for freeing it.
4768Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
4769specifies that the object is returned at ``+0`` and the ownership remains with
4770the callee.
4771The annotation ``__attribute__((ns_consumes_self))`` specifies that
4772the Objective-C method call consumes the reference to ``self``, e.g. by
4773attaching it to a supplied parameter.
4774Additionally, parameters can have an annotation
4775``__attribute__((ns_consumed))``, which specifies that passing an owned object
4776as that parameter effectively transfers the ownership, and the caller is no
4777longer responsible for it.
4778These attributes affect code generation when interacting with ARC code, and
4779they are used by the Clang Static Analyzer.
4780
4781In C programs using CoreFoundation, a similar set of attributes:
4782``__attribute__((cf_returns_not_retained))``,
4783``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
4784have the same respective semantics when applied to CoreFoundation objects.
4785These attributes affect code generation when interacting with ARC code, and
4786they are used by the Clang Static Analyzer.
4787
4788Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
4789the same attribute family is present:
4790``__attribute__((os_returns_not_retained))``,
4791``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
4792with the same respective semantics.
4793Similar to ``__attribute__((ns_consumes_self))``,
4794``__attribute__((os_consumes_this))`` specifies that the method call consumes
4795the reference to "this" (e.g., when attaching it to a different object supplied
4796as a parameter).
4797Out parameters (parameters the function is meant to write into,
4798either via pointers-to-pointers or references-to-pointers)
4799may be annotated with ``__attribute__((os_returns_retained))``
4800or ``__attribute__((os_returns_not_retained))`` which specifies that the object
4801written into the out parameter should (or respectively should not) be released
4802after use.
4803Since often out parameters may or may not be written depending on the exit
4804code of the function,
4805annotations ``__attribute__((os_returns_retained_on_zero))``
4806and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
4807an out parameter at ``+1`` is written if and only if the function returns a zero
4808(respectively non-zero) error code.
4809Observe that return-code-dependent out parameter annotations are only
4810available for retained out parameters, as non-retained object do not have to be
4811released by the callee.
4812These attributes are only used by the Clang Static Analyzer.
4813
4814The family of attributes ``X_returns_X_retained`` can be added to functions,
4815C++ methods, and Objective-C methods and properties.
4816Attributes ``X_consumed`` can be added to parameters of methods, functions,
4817and Objective-C methods.)reST";
4818
4819static const char AttrDoc_NSConsumesSelf[] = R"reST(The behavior of a function with respect to reference counting for Foundation
4820(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
4821convention (e.g. functions starting with "get" are assumed to return at
4822``+0``).
4823
4824It can be overridden using a family of the following attributes. In
4825Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
4826a function communicates that the object is returned at ``+1``, and the caller
4827is responsible for freeing it.
4828Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
4829specifies that the object is returned at ``+0`` and the ownership remains with
4830the callee.
4831The annotation ``__attribute__((ns_consumes_self))`` specifies that
4832the Objective-C method call consumes the reference to ``self``, e.g. by
4833attaching it to a supplied parameter.
4834Additionally, parameters can have an annotation
4835``__attribute__((ns_consumed))``, which specifies that passing an owned object
4836as that parameter effectively transfers the ownership, and the caller is no
4837longer responsible for it.
4838These attributes affect code generation when interacting with ARC code, and
4839they are used by the Clang Static Analyzer.
4840
4841In C programs using CoreFoundation, a similar set of attributes:
4842``__attribute__((cf_returns_not_retained))``,
4843``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
4844have the same respective semantics when applied to CoreFoundation objects.
4845These attributes affect code generation when interacting with ARC code, and
4846they are used by the Clang Static Analyzer.
4847
4848Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
4849the same attribute family is present:
4850``__attribute__((os_returns_not_retained))``,
4851``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
4852with the same respective semantics.
4853Similar to ``__attribute__((ns_consumes_self))``,
4854``__attribute__((os_consumes_this))`` specifies that the method call consumes
4855the reference to "this" (e.g., when attaching it to a different object supplied
4856as a parameter).
4857Out parameters (parameters the function is meant to write into,
4858either via pointers-to-pointers or references-to-pointers)
4859may be annotated with ``__attribute__((os_returns_retained))``
4860or ``__attribute__((os_returns_not_retained))`` which specifies that the object
4861written into the out parameter should (or respectively should not) be released
4862after use.
4863Since often out parameters may or may not be written depending on the exit
4864code of the function,
4865annotations ``__attribute__((os_returns_retained_on_zero))``
4866and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
4867an out parameter at ``+1`` is written if and only if the function returns a zero
4868(respectively non-zero) error code.
4869Observe that return-code-dependent out parameter annotations are only
4870available for retained out parameters, as non-retained object do not have to be
4871released by the callee.
4872These attributes are only used by the Clang Static Analyzer.
4873
4874The family of attributes ``X_returns_X_retained`` can be added to functions,
4875C++ methods, and Objective-C methods and properties.
4876Attributes ``X_consumed`` can be added to parameters of methods, functions,
4877and Objective-C methods.)reST";
4878
4879static const char AttrDoc_NSErrorDomain[] = R"reST(In Cocoa frameworks in Objective-C, one can group related error codes in enums
4880and categorize these enums with error domains.
4881
4882The ``ns_error_domain`` attribute indicates a global ``NSString`` or
4883``CFString`` constant representing the error domain that an error code belongs
4884to. For pointer uniqueness and code size this is a constant symbol, not a
4885literal.
4886
4887The domain and error code need to be used together. The ``ns_error_domain``
4888attribute links error codes to their domain at the source level.
4889
4890This metadata is useful for documentation purposes, for static analysis, and for
4891improving interoperability between Objective-C and Swift. It is not used for
4892code generation in Objective-C.
4893
4894For example:
4895
4896 .. code-block:: objc
4897
4898 #define NS_ERROR_ENUM(_type, _name, _domain) \
4899 enum _name : _type _name; enum __attribute__((ns_error_domain(_domain))) _name : _type
4900
4901 extern NSString *const MyErrorDomain;
4902 typedef NS_ERROR_ENUM(unsigned char, MyErrorEnum, MyErrorDomain) {
4903 MyErrFirst,
4904 MyErrSecond,
4905 };)reST";
4906
4907static const char AttrDoc_NSReturnsAutoreleased[] = R"reST(The behavior of a function with respect to reference counting for Foundation
4908(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
4909convention (e.g. functions starting with "get" are assumed to return at
4910``+0``).
4911
4912It can be overridden using a family of the following attributes. In
4913Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
4914a function communicates that the object is returned at ``+1``, and the caller
4915is responsible for freeing it.
4916Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
4917specifies that the object is returned at ``+0`` and the ownership remains with
4918the callee.
4919The annotation ``__attribute__((ns_consumes_self))`` specifies that
4920the Objective-C method call consumes the reference to ``self``, e.g. by
4921attaching it to a supplied parameter.
4922Additionally, parameters can have an annotation
4923``__attribute__((ns_consumed))``, which specifies that passing an owned object
4924as that parameter effectively transfers the ownership, and the caller is no
4925longer responsible for it.
4926These attributes affect code generation when interacting with ARC code, and
4927they are used by the Clang Static Analyzer.
4928
4929In C programs using CoreFoundation, a similar set of attributes:
4930``__attribute__((cf_returns_not_retained))``,
4931``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
4932have the same respective semantics when applied to CoreFoundation objects.
4933These attributes affect code generation when interacting with ARC code, and
4934they are used by the Clang Static Analyzer.
4935
4936Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
4937the same attribute family is present:
4938``__attribute__((os_returns_not_retained))``,
4939``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
4940with the same respective semantics.
4941Similar to ``__attribute__((ns_consumes_self))``,
4942``__attribute__((os_consumes_this))`` specifies that the method call consumes
4943the reference to "this" (e.g., when attaching it to a different object supplied
4944as a parameter).
4945Out parameters (parameters the function is meant to write into,
4946either via pointers-to-pointers or references-to-pointers)
4947may be annotated with ``__attribute__((os_returns_retained))``
4948or ``__attribute__((os_returns_not_retained))`` which specifies that the object
4949written into the out parameter should (or respectively should not) be released
4950after use.
4951Since often out parameters may or may not be written depending on the exit
4952code of the function,
4953annotations ``__attribute__((os_returns_retained_on_zero))``
4954and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
4955an out parameter at ``+1`` is written if and only if the function returns a zero
4956(respectively non-zero) error code.
4957Observe that return-code-dependent out parameter annotations are only
4958available for retained out parameters, as non-retained object do not have to be
4959released by the callee.
4960These attributes are only used by the Clang Static Analyzer.
4961
4962The family of attributes ``X_returns_X_retained`` can be added to functions,
4963C++ methods, and Objective-C methods and properties.
4964Attributes ``X_consumed`` can be added to parameters of methods, functions,
4965and Objective-C methods.)reST";
4966
4967static const char AttrDoc_NSReturnsNotRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
4968(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
4969convention (e.g. functions starting with "get" are assumed to return at
4970``+0``).
4971
4972It can be overridden using a family of the following attributes. In
4973Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
4974a function communicates that the object is returned at ``+1``, and the caller
4975is responsible for freeing it.
4976Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
4977specifies that the object is returned at ``+0`` and the ownership remains with
4978the callee.
4979The annotation ``__attribute__((ns_consumes_self))`` specifies that
4980the Objective-C method call consumes the reference to ``self``, e.g. by
4981attaching it to a supplied parameter.
4982Additionally, parameters can have an annotation
4983``__attribute__((ns_consumed))``, which specifies that passing an owned object
4984as that parameter effectively transfers the ownership, and the caller is no
4985longer responsible for it.
4986These attributes affect code generation when interacting with ARC code, and
4987they are used by the Clang Static Analyzer.
4988
4989In C programs using CoreFoundation, a similar set of attributes:
4990``__attribute__((cf_returns_not_retained))``,
4991``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
4992have the same respective semantics when applied to CoreFoundation objects.
4993These attributes affect code generation when interacting with ARC code, and
4994they are used by the Clang Static Analyzer.
4995
4996Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
4997the same attribute family is present:
4998``__attribute__((os_returns_not_retained))``,
4999``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
5000with the same respective semantics.
5001Similar to ``__attribute__((ns_consumes_self))``,
5002``__attribute__((os_consumes_this))`` specifies that the method call consumes
5003the reference to "this" (e.g., when attaching it to a different object supplied
5004as a parameter).
5005Out parameters (parameters the function is meant to write into,
5006either via pointers-to-pointers or references-to-pointers)
5007may be annotated with ``__attribute__((os_returns_retained))``
5008or ``__attribute__((os_returns_not_retained))`` which specifies that the object
5009written into the out parameter should (or respectively should not) be released
5010after use.
5011Since often out parameters may or may not be written depending on the exit
5012code of the function,
5013annotations ``__attribute__((os_returns_retained_on_zero))``
5014and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
5015an out parameter at ``+1`` is written if and only if the function returns a zero
5016(respectively non-zero) error code.
5017Observe that return-code-dependent out parameter annotations are only
5018available for retained out parameters, as non-retained object do not have to be
5019released by the callee.
5020These attributes are only used by the Clang Static Analyzer.
5021
5022The family of attributes ``X_returns_X_retained`` can be added to functions,
5023C++ methods, and Objective-C methods and properties.
5024Attributes ``X_consumed`` can be added to parameters of methods, functions,
5025and Objective-C methods.)reST";
5026
5027static const char AttrDoc_NSReturnsRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
5028(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
5029convention (e.g. functions starting with "get" are assumed to return at
5030``+0``).
5031
5032It can be overridden using a family of the following attributes. In
5033Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
5034a function communicates that the object is returned at ``+1``, and the caller
5035is responsible for freeing it.
5036Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
5037specifies that the object is returned at ``+0`` and the ownership remains with
5038the callee.
5039The annotation ``__attribute__((ns_consumes_self))`` specifies that
5040the Objective-C method call consumes the reference to ``self``, e.g. by
5041attaching it to a supplied parameter.
5042Additionally, parameters can have an annotation
5043``__attribute__((ns_consumed))``, which specifies that passing an owned object
5044as that parameter effectively transfers the ownership, and the caller is no
5045longer responsible for it.
5046These attributes affect code generation when interacting with ARC code, and
5047they are used by the Clang Static Analyzer.
5048
5049In C programs using CoreFoundation, a similar set of attributes:
5050``__attribute__((cf_returns_not_retained))``,
5051``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
5052have the same respective semantics when applied to CoreFoundation objects.
5053These attributes affect code generation when interacting with ARC code, and
5054they are used by the Clang Static Analyzer.
5055
5056Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
5057the same attribute family is present:
5058``__attribute__((os_returns_not_retained))``,
5059``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
5060with the same respective semantics.
5061Similar to ``__attribute__((ns_consumes_self))``,
5062``__attribute__((os_consumes_this))`` specifies that the method call consumes
5063the reference to "this" (e.g., when attaching it to a different object supplied
5064as a parameter).
5065Out parameters (parameters the function is meant to write into,
5066either via pointers-to-pointers or references-to-pointers)
5067may be annotated with ``__attribute__((os_returns_retained))``
5068or ``__attribute__((os_returns_not_retained))`` which specifies that the object
5069written into the out parameter should (or respectively should not) be released
5070after use.
5071Since often out parameters may or may not be written depending on the exit
5072code of the function,
5073annotations ``__attribute__((os_returns_retained_on_zero))``
5074and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
5075an out parameter at ``+1`` is written if and only if the function returns a zero
5076(respectively non-zero) error code.
5077Observe that return-code-dependent out parameter annotations are only
5078available for retained out parameters, as non-retained object do not have to be
5079released by the callee.
5080These attributes are only used by the Clang Static Analyzer.
5081
5082The family of attributes ``X_returns_X_retained`` can be added to functions,
5083C++ methods, and Objective-C methods and properties.
5084Attributes ``X_consumed`` can be added to parameters of methods, functions,
5085and Objective-C methods.)reST";
5086
5087static const char AttrDoc_Naked[] = R"reST(No documentation.)reST";
5088
5089static const char AttrDoc_NoAlias[] = R"reST(The ``noalias`` attribute indicates that the only memory accesses inside
5090function are loads and stores from objects pointed to by its pointer-typed
5091arguments, with arbitrary offsets.)reST";
5092
5093static const char AttrDoc_NoBuiltin[] = R"reST(The ``__attribute__((no_builtin))`` is similar to the ``-fno-builtin`` flag
5094except it is specific to the body of a function. The attribute may also be
5095applied to a virtual function but has no effect on the behavior of overriding
5096functions in a derived class.
5097
5098It accepts one or more strings corresponding to the specific names of the
5099builtins to disable (e.g. "memcpy", "memset").
5100If the attribute is used without parameters it will disable all buitins at
5101once.
5102
5103.. code-block:: c++
5104
5105 // The compiler is not allowed to add any builtin to foo's body.
5106 void foo(char* data, size_t count) __attribute__((no_builtin)) {
5107 // The compiler is not allowed to convert the loop into
5108 // `__builtin_memset(data, 0xFE, count);`.
5109 for (size_t i = 0; i < count; ++i)
5110 data[i] = 0xFE;
5111 }
5112
5113 // The compiler is not allowed to add the `memcpy` builtin to bar's body.
5114 void bar(char* data, size_t count) __attribute__((no_builtin("memcpy"))) {
5115 // The compiler is allowed to convert the loop into
5116 // `__builtin_memset(data, 0xFE, count);` but cannot generate any
5117 // `__builtin_memcpy`
5118 for (size_t i = 0; i < count; ++i)
5119 data[i] = 0xFE;
5120 })reST";
5121
5122static const char AttrDoc_NoCommon[] = R"reST(No documentation.)reST";
5123
5124static const char AttrDoc_NoConvergent[] = R"reST(This attribute prevents a function from being treated as convergent; when a
5125function is marked ``noconvergent``, calls to that function are not
5126automatically assumed to be convergent, unless such calls are explicitly marked
5127as ``convergent``. If a statement is marked as ``noconvergent``, any calls to
5128inline ``asm`` in that statement are no longer treated as convergent.
5129
5130In languages following SPMD/SIMT programming model, e.g., CUDA/HIP, function
5131declarations and inline asm calls are treated as convergent by default for
5132correctness. This ``noconvergent`` attribute is helpful for developers to
5133prevent them from being treated as convergent when it's safe.
5134
5135.. code-block:: c
5136
5137 __device__ float bar(float);
5138 __device__ float foo(float) __attribute__((noconvergent)) {}
5139
5140 __device__ int example(void) {
5141 float x;
5142 [[clang::noconvergent]] x = bar(x); // no effect on convergence
5143 [[clang::noconvergent]] { asm volatile ("nop"); } // the asm call is non-convergent
5144 })reST";
5145
5146static const char AttrDoc_NoDebug[] = R"reST(The ``nodebug`` attribute allows you to suppress debugging information for a
5147function or method, for a variable that is not a parameter or a non-static
5148data member, or for a typedef or using declaration.)reST";
5149
5150static const char AttrDoc_NoDeref[] = R"reST(The ``noderef`` attribute causes clang to diagnose dereferences of annotated pointer types.
5151This is ideally used with pointers that point to special memory which cannot be read
5152from or written to, but allowing for the pointer to be used in pointer arithmetic.
5153The following are examples of valid expressions where dereferences are diagnosed:
5154
5155.. code-block:: c
5156
5157 int __attribute__((noderef)) *p;
5158 int x = *p; // warning
5159
5160 int __attribute__((noderef)) **p2;
5161 x = **p2; // warning
5162
5163 int * __attribute__((noderef)) *p3;
5164 p = *p3; // warning
5165
5166 struct S {
5167 int a;
5168 };
5169 struct S __attribute__((noderef)) *s;
5170 x = s->a; // warning
5171 x = (*s).a; // warning
5172
5173Not all dereferences may diagnose a warning if the value directed by the pointer may not be
5174accessed. The following are examples of valid expressions where may not be diagnosed:
5175
5176.. code-block:: c
5177
5178 int *q;
5179 int __attribute__((noderef)) *p;
5180 q = &*p;
5181 q = *&p;
5182
5183 struct S {
5184 int a;
5185 };
5186 struct S __attribute__((noderef)) *s;
5187 p = &s->a;
5188 p = &(*s).a;
5189
5190``noderef`` is currently only supported for pointers and arrays and not usable
5191for references or Objective-C object pointers.
5192
5193.. code-block:: c++
5194
5195 int x = 2;
5196 int __attribute__((noderef)) &y = x; // warning: 'noderef' can only be used on an array or pointer type
5197
5198.. code-block:: objc
5199
5200 id __attribute__((noderef)) obj = [NSObject new]; // warning: 'noderef' can only be used on an array or pointer type)reST";
5201
5202static const char AttrDoc_NoDestroy[] = R"reST(The ``no_destroy`` attribute specifies that a variable with static or thread
5203storage duration shouldn't have its exit-time destructor run. Annotating every
5204static and thread duration variable with this attribute is equivalent to
5205invoking clang with -fno-c++-static-destructors.
5206
5207If a variable is declared with this attribute, clang doesn't access check or
5208generate the type's destructor. If you have a type that you only want to be
5209annotated with ``no_destroy``, you can therefore declare the destructor private:
5210
5211.. code-block:: c++
5212
5213 struct only_no_destroy {
5214 only_no_destroy();
5215 private:
5216 ~only_no_destroy();
5217 };
5218
5219 [[clang::no_destroy]] only_no_destroy global; // fine!
5220
5221Note that destructors are still required for subobjects of aggregates annotated
5222with this attribute. This is because previously constructed subobjects need to
5223be destroyed if an exception gets thrown before the initialization of the
5224complete object is complete. For instance:
5225
5226.. code-block:: c++
5227
5228 void f() {
5229 try {
5230 [[clang::no_destroy]]
5231 static only_no_destroy array[10]; // error, only_no_destroy has a private destructor.
5232 } catch (...) {
5233 // Handle the error
5234 }
5235 }
5236
5237Here, if the construction of ``array[9]`` fails with an exception, ``array[0..8]``
5238will be destroyed, so the element's destructor needs to be accessible.)reST";
5239
5240static const char AttrDoc_NoDuplicate[] = R"reST(The ``noduplicate`` attribute can be placed on function declarations to control
5241whether function calls to this function can be duplicated or not as a result of
5242optimizations. This is required for the implementation of functions with
5243certain special requirements, like the OpenCL "barrier" function, that might
5244need to be run concurrently by all the threads that are executing in lockstep
5245on the hardware. For example this attribute applied on the function
5246"nodupfunc" in the code below avoids that:
5247
5248.. code-block:: c
5249
5250 void nodupfunc() __attribute__((noduplicate));
5251 // Setting it as a C++11 attribute is also valid
5252 // void nodupfunc() [[clang::noduplicate]];
5253 void foo();
5254 void bar();
5255
5256 nodupfunc();
5257 if (a > n) {
5258 foo();
5259 } else {
5260 bar();
5261 }
5262
5263gets possibly modified by some optimizations into code similar to this:
5264
5265.. code-block:: c
5266
5267 if (a > n) {
5268 nodupfunc();
5269 foo();
5270 } else {
5271 nodupfunc();
5272 bar();
5273 }
5274
5275where the call to "nodupfunc" is duplicated and sunk into the two branches
5276of the condition.)reST";
5277
5278static const char AttrDoc_NoEscape[] = R"reST(``noescape`` placed on a function parameter of a pointer type is used to inform
5279the compiler that the pointer cannot escape: that is, no reference to the object
5280the pointer points to that is derived from the parameter value will survive
5281after the function returns. Users are responsible for making sure parameters
5282annotated with ``noescape`` do not actually escape. The optimizer may make
5283assumptions based on the fact that it knows that a call to the function does
5284not escape a certain parameter, so incorrectly annotating a parameter with
5285``noescape`` leads to undefined behavior. The callee is also not allowed to
5286deallocate memory through a ``noescape`` parameter: the optimizer does not make
5287assumptions based on this information at the moment, but may do so in the
5288future. Some cases of invalid uses of ``noescape`` can be found with
5289:ref:`-Wlifetime-safety-noescape <Wlifetime-safety-noescape>`.
5290
5291For example:
5292
5293.. code-block:: c
5294
5295 int *gp;
5296
5297 void nonescapingFunc(__attribute__((noescape)) int *p) {
5298 *p += 100; // OK.
5299 }
5300
5301 void escapingFunc(__attribute__((noescape)) int *p) {
5302 gp = p; // Not OK.
5303 }
5304
5305 void freeingFunc(__attribute__((noescape)) int *p) {
5306 free(p); // Not OK.
5307 }
5308
5309Since ``noescape`` is a parameter attribute and not a type attribute, it only
5310applies to the outermost pointer level, regardless of where in the parameter
5311declaration you place it:
5312
5313.. code-block:: c
5314
5315 int **gp;
5316
5317 void nestingEscapes(__attribute__((noescape)) int **p) {
5318 gp = p; // Not OK.
5319 *gp = *p; // OK, p does not escape.
5320 }
5321
5322Additionally, when the parameter is a `block pointer
5323<https://clang.llvm.org/docs/BlockLanguageSpec.html>`, the same restriction
5324applies to copies of the block. For example:
5325
5326.. code-block:: c
5327
5328 typedef void (^BlockTy)();
5329 BlockTy g0, g1;
5330
5331 void nonescapingFunc(__attribute__((noescape)) BlockTy block) {
5332 block(); // OK.
5333 }
5334
5335 void escapingFunc(__attribute__((noescape)) BlockTy block) {
5336 g0 = block; // Not OK.
5337 g1 = Block_copy(block); // Not OK either.
5338 }
5339
5340The function *is* allowed to leak information about the memory address of the
5341pointer, but not any provenance of the allocation:
5342
5343.. code-block:: c
5344
5345 bool isNull(__attribute__((noescape)) void *p) {
5346 return !p; // OK.
5347 }
5348
5349 uintptr_t gi;
5350
5351 void escapingAddress(__attribute__((noescape)) int *p) {
5352 // OK *if and only if* gi is never casted back to a pointer.
5353 gi = (uintptr_t)p;
5354 }
5355
5356 bool usingEscapedAddress(int *p) {
5357 return (uintptr_t)p > gi; // OK.
5358 }
5359
5360 bool usingEscapedPointer(int *p) {
5361 return p > (int*)gi; // Not OK.
5362 }
5363
5364 int *gp;
5365
5366 void escapingEndFunc(__attribute__((noescape)) int *p, size_t len) {
5367 gp = p + len; // Not OK.
5368 })reST";
5369
5370static const char AttrDoc_NoFieldProtection[] = R"reST(No documentation.)reST";
5371
5372static const char AttrDoc_NoInline[] = R"reST(This function attribute suppresses the inlining of a function at the call sites
5373of the function.
5374
5375``[[clang::noinline]]`` spelling can be used as a statement attribute; other
5376spellings of the attribute are not supported on statements. If a statement is
5377marked ``[[clang::noinline]]`` and contains calls, those calls inside the
5378statement will not be inlined by the compiler.
5379
5380``__noinline__`` can be used as a keyword in CUDA/HIP languages. This is to
5381avoid diagnostics due to usage of ``__attribute__((__noinline__))``
5382with ``__noinline__`` defined as a macro as ``__attribute__((noinline))``.
5383
5384.. code-block:: c
5385
5386 int example(void) {
5387 int r;
5388 [[clang::noinline]] foo();
5389 [[clang::noinline]] r = bar();
5390 return r;
5391 })reST";
5392
5393static const char AttrDoc_NoInstrumentFunction[] = R"reST(No documentation.)reST";
5394
5395static const char AttrDoc_NoMerge[] = R"reST(If a statement is marked ``nomerge`` and contains call expressions, those call
5396expressions inside the statement will not be merged during optimization. This
5397attribute can be used to prevent the optimizer from obscuring the source
5398location of certain calls. For example, it will prevent tail merging otherwise
5399identical code sequences that raise an exception or terminate the program. Tail
5400merging normally reduces the precision of source location information, making
5401stack traces less useful for debugging. This attribute gives the user control
5402over the tradeoff between code size and debug information precision.
5403
5404``nomerge`` attribute can also be used as function attribute to prevent all
5405calls to the specified function from merging. It has no effect on indirect
5406calls to such functions. For example:
5407
5408.. code-block:: c++
5409
5410 [[clang::nomerge]] void foo(int) {}
5411
5412 void bar(int x) {
5413 auto *ptr = foo;
5414 if (x) foo(1); else foo(2); // will not be merged
5415 if (x) ptr(1); else ptr(2); // indirect call, can be merged
5416 }
5417
5418``nomerge`` attribute can also be used for pointers to functions to
5419prevent calls through such pointer from merging. In such case the
5420effect applies only to a specific function pointer. For example:
5421
5422.. code-block:: c++
5423
5424 [[clang::nomerge]] void (*foo)(int);
5425
5426 void bar(int x) {
5427 auto *ptr = foo;
5428 if (x) foo(1); else foo(2); // will not be merged
5429 if (x) ptr(1); else ptr(2); // 'ptr' has no 'nomerge' attribute, can be merged
5430 })reST";
5431
5432static const char AttrDoc_NoMicroMips[] = R"reST(Clang supports the GNU style ``__attribute__((micromips))`` and
5433``__attribute__((nomicromips))`` attributes on MIPS targets. These attributes
5434may be attached to a function definition and instructs the backend to generate
5435or not to generate microMIPS code for that function.
5436
5437These attributes override the ``-mmicromips`` and ``-mno-micromips`` options
5438on the command line.)reST";
5439
5440static const char AttrDoc_NoMips16[] = R"reST(No documentation.)reST";
5441
5442static const char AttrDoc_NoOutline[] = R"reST(This function attribute suppresses outlining from the annotated function.
5443
5444Outlining is the process where common parts of separate functions are extracted
5445into a separate function (or assembly snippet), and calls to that function or
5446snippet are inserted in the original functions. In this way, it can be seen as
5447the opposite of inlining. It can help to reduce code size.)reST";
5448
5449static const char AttrDoc_NoProfileFunction[] = R"reST(Use the ``no_profile_instrument_function`` attribute on a function declaration
5450to denote that the compiler should not instrument the function with
5451profile-related instrumentation, such as via the
5452``-fprofile-generate`` / ``-fprofile-instr-generate`` /
5453``-fcs-profile-generate`` / ``-fprofile-arcs`` flags.)reST";
5454
5455static const char AttrDoc_NoRandomizeLayout[] = R"reST(The attribute ``randomize_layout``, when attached to a C structure, selects it
5456for structure layout field randomization; a compile-time hardening technique. A
5457"seed" value, is specified via the ``-frandomize-layout-seed=`` command line flag.
5458For example:
5459
5460.. code-block:: bash
5461
5462 SEED=`od -A n -t x8 -N 32 /dev/urandom | tr -d ' \n'`
5463 make ... CFLAGS="-frandomize-layout-seed=$SEED" ...
5464
5465You can also supply the seed in a file with ``-frandomize-layout-seed-file=``.
5466For example:
5467
5468.. code-block:: bash
5469
5470 od -A n -t x8 -N 32 /dev/urandom | tr -d ' \n' > /tmp/seed_file.txt
5471 make ... CFLAGS="-frandomize-layout-seed-file=/tmp/seed_file.txt" ...
5472
5473The randomization is deterministic based for a given seed, so the entire
5474program should be compiled with the same seed, but keep the seed safe
5475otherwise.
5476
5477The attribute ``no_randomize_layout``, when attached to a C structure,
5478instructs the compiler that this structure should not have its field layout
5479randomized.)reST";
5480
5481static const char AttrDoc_NoReturn[] = R"reST(No documentation.)reST";
5482
5483static const char AttrDoc_NoSanitize[] = R"reST(Use the ``no_sanitize`` attribute on a function or a global variable
5484declaration to specify that a particular instrumentation or set of
5485instrumentations should not be applied.
5486
5487The attribute takes a list of string literals with the following accepted
5488values:
5489
5490* all values accepted by ``-fno-sanitize=``;
5491* ``coverage``, to disable SanitizerCoverage instrumentation.
5492
5493For example, ``__attribute__((no_sanitize("address", "thread")))`` specifies
5494that AddressSanitizer and ThreadSanitizer should not be applied to the function
5495or variable. Using ``__attribute__((no_sanitize("coverage")))`` specifies that
5496SanitizerCoverage should not be applied to the function.
5497
5498See :ref:`Controlling Code Generation <controlling-code-generation>` for a
5499full list of supported sanitizer flags.)reST";
5500
5501static const char AttrDoc_NoSpecializations[] = R"reST(``[[clang::no_specializations]]`` can be applied to function, class, or variable
5502templates which should not be explicitly specialized by users. This is primarily
5503used to diagnose user specializations of standard library type traits.)reST";
5504
5505static const char AttrDoc_NoSpeculativeLoadHardening[] = R"reST(This attribute can be applied to a function declaration in order to indicate
5506 that `Speculative Load Hardening <https://llvm.org/docs/SpeculativeLoadHardening.html>`_
5507 is *not* needed for the function body. This can also be applied to a method
5508 in Objective C. This attribute will take precedence over the command line flag in
5509 the case where `-mspeculative-load-hardening <https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mspeculative-load-hardening>`_ is specified.
5510
5511 Warning: This attribute may not prevent Speculative Load Hardening from being
5512 enabled for a function which inlines a function that has the
5513 'speculative_load_hardening' attribute. This is intended to provide a
5514 maximally conservative model where the code that is marked with the
5515 'speculative_load_hardening' attribute will always (even when inlined)
5516 be hardened. A user of this attribute may want to mark functions called by
5517 a function they do not want to be hardened with the 'noinline' attribute.
5518
5519 For example:
5520
5521 .. code-block:: c
5522
5523 __attribute__((speculative_load_hardening))
5524 int foo(int i) {
5525 return i;
5526 }
5527
5528 // Note: bar() may still have speculative load hardening enabled if
5529 // foo() is inlined into bar(). Mark foo() with __attribute__((noinline))
5530 // to avoid this situation.
5531 __attribute__((no_speculative_load_hardening))
5532 int bar(int i) {
5533 return foo(i);
5534 })reST";
5535
5536static const char AttrDoc_NoSplitStack[] = R"reST(The ``no_split_stack`` attribute disables the emission of the split stack
5537preamble for a particular function. It has no effect if ``-fsplit-stack``
5538is not specified.)reST";
5539
5540static const char AttrDoc_NoStackProtector[] = R"reST(Clang supports the GNU style ``__attribute__((no_stack_protector))`` and Microsoft
5541style ``__declspec(safebuffers)`` attribute which disables
5542the stack protector on the specified function. This attribute is useful for
5543selectively disabling the stack protector on some functions when building with
5544``-fstack-protector`` compiler option.
5545
5546For example, it disables the stack protector for the function ``foo`` but function
5547``bar`` will still be built with the stack protector with the ``-fstack-protector``
5548option.
5549
5550.. code-block:: c
5551
5552 int __attribute__((no_stack_protector))
5553 foo (int x); // stack protection will be disabled for foo.
5554
5555 int bar(int y); // bar can be built with the stack protector.)reST";
5556
5557static const char AttrDoc_NoThreadSafetyAnalysis[] = R"reST(No documentation.)reST";
5558
5559static const char AttrDoc_NoThrow[] = R"reST(Clang supports the GNU style ``__attribute__((nothrow))`` and Microsoft style
5560``__declspec(nothrow)`` attribute as an equivalent of ``noexcept`` on function
5561declarations. This attribute informs the compiler that the annotated function
5562does not throw an exception. This prevents exception-unwinding. This attribute
5563is particularly useful on functions in the C Standard Library that are
5564guaranteed to not throw an exception.)reST";
5565
5566static const char AttrDoc_NoTrivialAutoVarInit[] = R"reST(The ``__declspec(no_init_all)`` attribute disables the automatic initialization that the
5567`-ftrivial-auto-var-init`_ flag would have applied to locals in a marked function, or instances of
5568a marked type. Note that this attribute has no effect for locals that are automatically initialized
5569without the `-ftrivial-auto-var-init`_ flag.
5570
5571.. _`-ftrivial-auto-var-init`: ClangCommandLineReference.html#cmdoption-clang-ftrivial-auto-var-init)reST";
5572
5573static const char AttrDoc_NoUniqueAddress[] = R"reST(The ``no_unique_address`` attribute allows tail padding in a non-static data
5574member to overlap other members of the enclosing class (and in the special
5575case when the type is empty, permits it to fully overlap other members).
5576The field is laid out as if a base class were encountered at the corresponding
5577point within the class (except that it does not share a vptr with the enclosing
5578object).
5579
5580Example usage:
5581
5582.. code-block:: c++
5583
5584 template<typename T, typename Alloc> struct my_vector {
5585 T *p;
5586 [[no_unique_address]] Alloc alloc;
5587 // ...
5588 };
5589 static_assert(sizeof(my_vector<int, std::allocator<int>>) == sizeof(int*));
5590
5591``[[no_unique_address]]`` is a standard C++20 attribute. Clang supports its use
5592in C++11 onwards.
5593
5594On MSVC targets, ``[[no_unique_address]]`` is ignored; use
5595``[[msvc::no_unique_address]]`` instead. Currently there is no guarantee of ABI
5596compatibility or stability with MSVC.)reST";
5597
5598static const char AttrDoc_NoUwtable[] = R"reST(Clang supports the ``nouwtable`` attribute which skips emitting
5599the unwind table entry for the specified function. This attribute is useful for
5600selectively emitting the unwind table entry on some functions when building with
5601``-funwind-tables`` compiler option.)reST";
5602
5603static const char AttrDoc_NonAllocating[] = R"reST(Declares that a function or function type either does or does not allocate heap memory, according
5604to the optional, compile-time constant boolean argument, which defaults to true. When the argument
5605is false, the attribute is equivalent to ``allocating``.)reST";
5606
5607static const char AttrDoc_NonBlocking[] = R"reST(Declares that a function or function type either does or does not block in any way, according
5608to the optional, compile-time constant boolean argument, which defaults to true. When the argument
5609is false, the attribute is equivalent to ``blocking``.
5610
5611For the purposes of diagnostics, ``nonblocking`` is considered to include the
5612``nonallocating`` guarantee and is therefore a "stronger" constraint or attribute.)reST";
5613
5614static const char AttrDoc_NonNull[] = R"reST(The ``nonnull`` attribute indicates that some function parameters must not be
5615null, and can be used in several different ways. It's original usage
5616(`from GCC <https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes>`_)
5617is as a function (or Objective-C method) attribute that specifies which
5618parameters of the function are nonnull in a comma-separated list. For example:
5619
5620 .. code-block:: c
5621
5622 extern void * my_memcpy (void *dest, const void *src, size_t len)
5623 __attribute__((nonnull (1, 2)));
5624
5625Here, the ``nonnull`` attribute indicates that parameters 1 and 2
5626cannot have a null value. Omitting the parenthesized list of parameter indices
5627means that all parameters of pointer type cannot be null:
5628
5629 .. code-block:: c
5630
5631 extern void * my_memcpy (void *dest, const void *src, size_t len)
5632 __attribute__((nonnull));
5633
5634Clang also allows the ``nonnull`` attribute to be placed directly on a function
5635(or Objective-C method) parameter, eliminating the need to specify the
5636parameter index ahead of type. For example:
5637
5638 .. code-block:: c
5639
5640 extern void * my_memcpy (void *dest __attribute__((nonnull)),
5641 const void *src __attribute__((nonnull)), size_t len);
5642
5643Note that the ``nonnull`` attribute indicates that passing null to a non-null
5644parameter is undefined behavior, which the optimizer may take advantage of to,
5645e.g., remove null checks. The ``_Nonnull`` type qualifier indicates that a
5646pointer cannot be null in a more general manner (because it is part of the type
5647system) and does not imply undefined behavior, making it more widely applicable.)reST";
5648
5649static const char AttrDoc_NonString[] = R"reST(The ``nonstring`` attribute can be applied to the declaration of a variable or
5650a field whose type is a character pointer or character array to specify that
5651the buffer is not intended to behave like a null-terminated string. This will
5652silence diagnostics with code like:
5653
5654.. code-block:: c
5655
5656 char BadStr[3] = "foo"; // No space for the null terminator, diagnosed
5657 __attribute__((nonstring)) char NotAStr[3] = "foo"; // Not diagnosed)reST";
5658
5659static const char AttrDoc_NotTailCalled[] = R"reST(The ``not_tail_called`` attribute prevents tail-call optimization on statically
5660bound calls. Objective-c methods, and functions marked as ``always_inline``
5661cannot be marked as ``not_tail_called``.
5662
5663For example, it prevents tail-call optimization in the following case:
5664
5665 .. code-block:: c
5666
5667 int __attribute__((not_tail_called)) foo1(int);
5668
5669 int foo2(int a) {
5670 return foo1(a); // No tail-call optimization on direct calls.
5671 }
5672
5673However, it doesn't prevent tail-call optimization in this case:
5674
5675 .. code-block:: c
5676
5677 int __attribute__((not_tail_called)) foo1(int);
5678
5679 int foo2(int a) {
5680 int (*fn)(int) = &foo1;
5681
5682 // not_tail_called has no effect on an indirect call even if the call can
5683 // be resolved at compile time.
5684 return (*fn)(a);
5685 }
5686
5687Generally, marking an overriding virtual function as ``not_tail_called`` is
5688not useful, because this attribute is a property of the static type. Calls
5689made through a pointer or reference to the base class type will respect
5690the ``not_tail_called`` attribute of the base class's member function,
5691regardless of the runtime destination of the call:
5692
5693 .. code-block:: c++
5694
5695 struct Foo { virtual void f(); };
5696 struct Bar : Foo {
5697 [[clang::not_tail_called]] void f() override;
5698 };
5699 void callera(Bar& bar) {
5700 Foo& foo = bar;
5701 // not_tail_called has no effect on here, even though the
5702 // underlying method is f from Bar.
5703 foo.f();
5704 bar.f(); // No tail-call optimization on here.
5705 })reST";
5706
5707static const char AttrDoc_OMPAllocateDecl[] = R"reST()reST";
5708
5709static const char AttrDoc_OMPAssume[] = R"reST(Clang supports the ``[[omp::assume("assumption")]]`` attribute to
5710provide additional information to the optimizer. The string-literal, here
5711"assumption", will be attached to the function declaration such that later
5712analysis and optimization passes can assume the "assumption" to hold.
5713This is similar to :ref:`__builtin_assume <langext-__builtin_assume>` but
5714instead of an expression that can be assumed to be non-zero, the assumption is
5715expressed as a string and it holds for the entire function.
5716
5717A function can have multiple assume attributes and they propagate from prior
5718declarations to later definitions. Multiple assumptions are aggregated into a
5719single comma separated string. Thus, one can provide multiple assumptions via
5720a comma separated string, i.a.,
5721``[[omp::assume("assumption1,assumption2")]]``.
5722
5723While LLVM plugins might provide more assumption strings, the default LLVM
5724optimization passes are aware of the following assumptions:
5725
5726 .. code-block:: none
5727
5728 "omp_no_openmp"
5729 "omp_no_openmp_routines"
5730 "omp_no_parallelism"
5731 "omp_no_openmp_constructs"
5732
5733The OpenMP standard defines the meaning of OpenMP assumptions ("omp_XYZ" is
5734spelled "XYZ" in the `OpenMP 5.1 Standard`_).
5735
5736.. _`OpenMP 5.1 Standard`: https://www.openmp.org/spec-html/5.1/openmpsu37.html#x56-560002.5.2)reST";
5737
5738static const char AttrDoc_OMPCaptureKind[] = R"reST()reST";
5739
5740static const char AttrDoc_OMPCaptureNoInit[] = R"reST()reST";
5741
5742static const char AttrDoc_OMPDeclareSimdDecl[] = R"reST(The ``declare simd`` construct can be applied to a function to enable the creation
5743of one or more versions that can process multiple arguments using SIMD
5744instructions from a single invocation in a SIMD loop. The ``declare simd``
5745directive is a declarative directive. There may be multiple ``declare simd``
5746directives for a function. The use of a ``declare simd`` construct on a function
5747enables the creation of SIMD versions of the associated function that can be
5748used to process multiple arguments from a single invocation from a SIMD loop
5749concurrently.
5750The syntax of the ``declare simd`` construct is as follows:
5751
5752 .. code-block:: none
5753
5754 #pragma omp declare simd [clause[[,] clause] ...] new-line
5755 [#pragma omp declare simd [clause[[,] clause] ...] new-line]
5756 [...]
5757 function definition or declaration
5758
5759where clause is one of the following:
5760
5761 .. code-block:: none
5762
5763 simdlen(length)
5764 linear(argument-list[:constant-linear-step])
5765 aligned(argument-list[:alignment])
5766 uniform(argument-list)
5767 inbranch
5768 notinbranch)reST";
5769
5770static const char AttrDoc_OMPDeclareTargetDecl[] = R"reST(The ``declare target`` directive specifies that variables and functions are mapped
5771to a device for OpenMP offload mechanism.
5772
5773The syntax of the declare target directive is as follows:
5774
5775 .. code-block:: c
5776
5777 #pragma omp declare target new-line
5778 declarations-definition-seq
5779 #pragma omp end declare target new-line
5780
5781or
5782
5783 .. code-block:: c
5784
5785 #pragma omp declare target (extended-list) new-line
5786
5787or
5788
5789 .. code-block:: c
5790
5791 #pragma omp declare target clause[ [,] clause ... ] new-line
5792
5793where clause is one of the following:
5794
5795
5796 .. code-block:: c
5797
5798 to(extended-list)
5799 link(list)
5800 device_type(host | nohost | any))reST";
5801
5802static const char AttrDoc_OMPDeclareVariant[] = R"reST(The ``declare variant`` directive declares a specialized variant of a base
5803function and specifies the context in which that specialized variant is used.
5804The declare variant directive is a declarative directive.
5805The syntax of the ``declare variant`` construct is as follows:
5806
5807 .. code-block:: none
5808
5809 #pragma omp declare variant(variant-func-id) clause new-line
5810 [#pragma omp declare variant(variant-func-id) clause new-line]
5811 [...]
5812 function definition or declaration
5813
5814where clause is one of the following:
5815
5816 .. code-block:: none
5817
5818 match(context-selector-specification)
5819
5820and where ``variant-func-id`` is the name of a function variant that is either a
5821base language identifier or, for C++, a template-id.
5822
5823Clang provides the following context selector extensions, used via
5824``implementation={extension(EXTENSION)}``:
5825
5826 .. code-block:: none
5827
5828 match_all
5829 match_any
5830 match_none
5831 disable_implicit_base
5832 allow_templates
5833 bind_to_declaration
5834
5835The match extensions change when the *entire* context selector is considered a
5836match for an OpenMP context. The default is ``all``, with ``none`` no trait in the
5837selector is allowed to be in the OpenMP context, with ``any`` a single trait in
5838both the selector and OpenMP context is sufficient. Only a single match
5839extension trait is allowed per context selector.
5840The disable extensions remove default effects of the ``begin declare variant``
5841applied to a definition. If ``disable_implicit_base`` is given, we will not
5842introduce an implicit base function for a variant if no base function was
5843found. The variant is still generated but will never be called, due to the
5844absence of a base function and consequently calls to a base function.
5845The allow extensions change when the ``begin declare variant`` effect is
5846applied to a definition. If ``allow_templates`` is given, template function
5847definitions are considered as specializations of existing or assumed template
5848declarations with the same name. The template parameters for the base functions
5849are used to instantiate the specialization. If ``bind_to_declaration`` is given,
5850apply the same variant rules to function declarations. This allows the user to
5851override declarations with only a function declaration.)reST";
5852
5853static const char AttrDoc_OMPGroupPrivateDecl[] = R"reST()reST";
5854
5855static const char AttrDoc_OMPReferencedVar[] = R"reST()reST";
5856
5857static const char AttrDoc_OMPTargetIndirectCall[] = R"reST()reST";
5858
5859static const char AttrDoc_OMPThreadPrivateDecl[] = R"reST()reST";
5860
5861static const char AttrDoc_OSConsumed[] = R"reST(The behavior of a function with respect to reference counting for Foundation
5862(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
5863convention (e.g. functions starting with "get" are assumed to return at
5864``+0``).
5865
5866It can be overridden using a family of the following attributes. In
5867Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
5868a function communicates that the object is returned at ``+1``, and the caller
5869is responsible for freeing it.
5870Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
5871specifies that the object is returned at ``+0`` and the ownership remains with
5872the callee.
5873The annotation ``__attribute__((ns_consumes_self))`` specifies that
5874the Objective-C method call consumes the reference to ``self``, e.g. by
5875attaching it to a supplied parameter.
5876Additionally, parameters can have an annotation
5877``__attribute__((ns_consumed))``, which specifies that passing an owned object
5878as that parameter effectively transfers the ownership, and the caller is no
5879longer responsible for it.
5880These attributes affect code generation when interacting with ARC code, and
5881they are used by the Clang Static Analyzer.
5882
5883In C programs using CoreFoundation, a similar set of attributes:
5884``__attribute__((cf_returns_not_retained))``,
5885``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
5886have the same respective semantics when applied to CoreFoundation objects.
5887These attributes affect code generation when interacting with ARC code, and
5888they are used by the Clang Static Analyzer.
5889
5890Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
5891the same attribute family is present:
5892``__attribute__((os_returns_not_retained))``,
5893``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
5894with the same respective semantics.
5895Similar to ``__attribute__((ns_consumes_self))``,
5896``__attribute__((os_consumes_this))`` specifies that the method call consumes
5897the reference to "this" (e.g., when attaching it to a different object supplied
5898as a parameter).
5899Out parameters (parameters the function is meant to write into,
5900either via pointers-to-pointers or references-to-pointers)
5901may be annotated with ``__attribute__((os_returns_retained))``
5902or ``__attribute__((os_returns_not_retained))`` which specifies that the object
5903written into the out parameter should (or respectively should not) be released
5904after use.
5905Since often out parameters may or may not be written depending on the exit
5906code of the function,
5907annotations ``__attribute__((os_returns_retained_on_zero))``
5908and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
5909an out parameter at ``+1`` is written if and only if the function returns a zero
5910(respectively non-zero) error code.
5911Observe that return-code-dependent out parameter annotations are only
5912available for retained out parameters, as non-retained object do not have to be
5913released by the callee.
5914These attributes are only used by the Clang Static Analyzer.
5915
5916The family of attributes ``X_returns_X_retained`` can be added to functions,
5917C++ methods, and Objective-C methods and properties.
5918Attributes ``X_consumed`` can be added to parameters of methods, functions,
5919and Objective-C methods.)reST";
5920
5921static const char AttrDoc_OSConsumesThis[] = R"reST(The behavior of a function with respect to reference counting for Foundation
5922(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
5923convention (e.g. functions starting with "get" are assumed to return at
5924``+0``).
5925
5926It can be overridden using a family of the following attributes. In
5927Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
5928a function communicates that the object is returned at ``+1``, and the caller
5929is responsible for freeing it.
5930Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
5931specifies that the object is returned at ``+0`` and the ownership remains with
5932the callee.
5933The annotation ``__attribute__((ns_consumes_self))`` specifies that
5934the Objective-C method call consumes the reference to ``self``, e.g. by
5935attaching it to a supplied parameter.
5936Additionally, parameters can have an annotation
5937``__attribute__((ns_consumed))``, which specifies that passing an owned object
5938as that parameter effectively transfers the ownership, and the caller is no
5939longer responsible for it.
5940These attributes affect code generation when interacting with ARC code, and
5941they are used by the Clang Static Analyzer.
5942
5943In C programs using CoreFoundation, a similar set of attributes:
5944``__attribute__((cf_returns_not_retained))``,
5945``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
5946have the same respective semantics when applied to CoreFoundation objects.
5947These attributes affect code generation when interacting with ARC code, and
5948they are used by the Clang Static Analyzer.
5949
5950Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
5951the same attribute family is present:
5952``__attribute__((os_returns_not_retained))``,
5953``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
5954with the same respective semantics.
5955Similar to ``__attribute__((ns_consumes_self))``,
5956``__attribute__((os_consumes_this))`` specifies that the method call consumes
5957the reference to "this" (e.g., when attaching it to a different object supplied
5958as a parameter).
5959Out parameters (parameters the function is meant to write into,
5960either via pointers-to-pointers or references-to-pointers)
5961may be annotated with ``__attribute__((os_returns_retained))``
5962or ``__attribute__((os_returns_not_retained))`` which specifies that the object
5963written into the out parameter should (or respectively should not) be released
5964after use.
5965Since often out parameters may or may not be written depending on the exit
5966code of the function,
5967annotations ``__attribute__((os_returns_retained_on_zero))``
5968and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
5969an out parameter at ``+1`` is written if and only if the function returns a zero
5970(respectively non-zero) error code.
5971Observe that return-code-dependent out parameter annotations are only
5972available for retained out parameters, as non-retained object do not have to be
5973released by the callee.
5974These attributes are only used by the Clang Static Analyzer.
5975
5976The family of attributes ``X_returns_X_retained`` can be added to functions,
5977C++ methods, and Objective-C methods and properties.
5978Attributes ``X_consumed`` can be added to parameters of methods, functions,
5979and Objective-C methods.)reST";
5980
5981static const char AttrDoc_OSReturnsNotRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
5982(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
5983convention (e.g. functions starting with "get" are assumed to return at
5984``+0``).
5985
5986It can be overridden using a family of the following attributes. In
5987Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
5988a function communicates that the object is returned at ``+1``, and the caller
5989is responsible for freeing it.
5990Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
5991specifies that the object is returned at ``+0`` and the ownership remains with
5992the callee.
5993The annotation ``__attribute__((ns_consumes_self))`` specifies that
5994the Objective-C method call consumes the reference to ``self``, e.g. by
5995attaching it to a supplied parameter.
5996Additionally, parameters can have an annotation
5997``__attribute__((ns_consumed))``, which specifies that passing an owned object
5998as that parameter effectively transfers the ownership, and the caller is no
5999longer responsible for it.
6000These attributes affect code generation when interacting with ARC code, and
6001they are used by the Clang Static Analyzer.
6002
6003In C programs using CoreFoundation, a similar set of attributes:
6004``__attribute__((cf_returns_not_retained))``,
6005``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
6006have the same respective semantics when applied to CoreFoundation objects.
6007These attributes affect code generation when interacting with ARC code, and
6008they are used by the Clang Static Analyzer.
6009
6010Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
6011the same attribute family is present:
6012``__attribute__((os_returns_not_retained))``,
6013``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
6014with the same respective semantics.
6015Similar to ``__attribute__((ns_consumes_self))``,
6016``__attribute__((os_consumes_this))`` specifies that the method call consumes
6017the reference to "this" (e.g., when attaching it to a different object supplied
6018as a parameter).
6019Out parameters (parameters the function is meant to write into,
6020either via pointers-to-pointers or references-to-pointers)
6021may be annotated with ``__attribute__((os_returns_retained))``
6022or ``__attribute__((os_returns_not_retained))`` which specifies that the object
6023written into the out parameter should (or respectively should not) be released
6024after use.
6025Since often out parameters may or may not be written depending on the exit
6026code of the function,
6027annotations ``__attribute__((os_returns_retained_on_zero))``
6028and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
6029an out parameter at ``+1`` is written if and only if the function returns a zero
6030(respectively non-zero) error code.
6031Observe that return-code-dependent out parameter annotations are only
6032available for retained out parameters, as non-retained object do not have to be
6033released by the callee.
6034These attributes are only used by the Clang Static Analyzer.
6035
6036The family of attributes ``X_returns_X_retained`` can be added to functions,
6037C++ methods, and Objective-C methods and properties.
6038Attributes ``X_consumed`` can be added to parameters of methods, functions,
6039and Objective-C methods.)reST";
6040
6041static const char AttrDoc_OSReturnsRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
6042(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
6043convention (e.g. functions starting with "get" are assumed to return at
6044``+0``).
6045
6046It can be overridden using a family of the following attributes. In
6047Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
6048a function communicates that the object is returned at ``+1``, and the caller
6049is responsible for freeing it.
6050Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
6051specifies that the object is returned at ``+0`` and the ownership remains with
6052the callee.
6053The annotation ``__attribute__((ns_consumes_self))`` specifies that
6054the Objective-C method call consumes the reference to ``self``, e.g. by
6055attaching it to a supplied parameter.
6056Additionally, parameters can have an annotation
6057``__attribute__((ns_consumed))``, which specifies that passing an owned object
6058as that parameter effectively transfers the ownership, and the caller is no
6059longer responsible for it.
6060These attributes affect code generation when interacting with ARC code, and
6061they are used by the Clang Static Analyzer.
6062
6063In C programs using CoreFoundation, a similar set of attributes:
6064``__attribute__((cf_returns_not_retained))``,
6065``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
6066have the same respective semantics when applied to CoreFoundation objects.
6067These attributes affect code generation when interacting with ARC code, and
6068they are used by the Clang Static Analyzer.
6069
6070Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
6071the same attribute family is present:
6072``__attribute__((os_returns_not_retained))``,
6073``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
6074with the same respective semantics.
6075Similar to ``__attribute__((ns_consumes_self))``,
6076``__attribute__((os_consumes_this))`` specifies that the method call consumes
6077the reference to "this" (e.g., when attaching it to a different object supplied
6078as a parameter).
6079Out parameters (parameters the function is meant to write into,
6080either via pointers-to-pointers or references-to-pointers)
6081may be annotated with ``__attribute__((os_returns_retained))``
6082or ``__attribute__((os_returns_not_retained))`` which specifies that the object
6083written into the out parameter should (or respectively should not) be released
6084after use.
6085Since often out parameters may or may not be written depending on the exit
6086code of the function,
6087annotations ``__attribute__((os_returns_retained_on_zero))``
6088and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
6089an out parameter at ``+1`` is written if and only if the function returns a zero
6090(respectively non-zero) error code.
6091Observe that return-code-dependent out parameter annotations are only
6092available for retained out parameters, as non-retained object do not have to be
6093released by the callee.
6094These attributes are only used by the Clang Static Analyzer.
6095
6096The family of attributes ``X_returns_X_retained`` can be added to functions,
6097C++ methods, and Objective-C methods and properties.
6098Attributes ``X_consumed`` can be added to parameters of methods, functions,
6099and Objective-C methods.)reST";
6100
6101static const char AttrDoc_OSReturnsRetainedOnNonZero[] = R"reST(The behavior of a function with respect to reference counting for Foundation
6102(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
6103convention (e.g. functions starting with "get" are assumed to return at
6104``+0``).
6105
6106It can be overridden using a family of the following attributes. In
6107Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
6108a function communicates that the object is returned at ``+1``, and the caller
6109is responsible for freeing it.
6110Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
6111specifies that the object is returned at ``+0`` and the ownership remains with
6112the callee.
6113The annotation ``__attribute__((ns_consumes_self))`` specifies that
6114the Objective-C method call consumes the reference to ``self``, e.g. by
6115attaching it to a supplied parameter.
6116Additionally, parameters can have an annotation
6117``__attribute__((ns_consumed))``, which specifies that passing an owned object
6118as that parameter effectively transfers the ownership, and the caller is no
6119longer responsible for it.
6120These attributes affect code generation when interacting with ARC code, and
6121they are used by the Clang Static Analyzer.
6122
6123In C programs using CoreFoundation, a similar set of attributes:
6124``__attribute__((cf_returns_not_retained))``,
6125``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
6126have the same respective semantics when applied to CoreFoundation objects.
6127These attributes affect code generation when interacting with ARC code, and
6128they are used by the Clang Static Analyzer.
6129
6130Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
6131the same attribute family is present:
6132``__attribute__((os_returns_not_retained))``,
6133``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
6134with the same respective semantics.
6135Similar to ``__attribute__((ns_consumes_self))``,
6136``__attribute__((os_consumes_this))`` specifies that the method call consumes
6137the reference to "this" (e.g., when attaching it to a different object supplied
6138as a parameter).
6139Out parameters (parameters the function is meant to write into,
6140either via pointers-to-pointers or references-to-pointers)
6141may be annotated with ``__attribute__((os_returns_retained))``
6142or ``__attribute__((os_returns_not_retained))`` which specifies that the object
6143written into the out parameter should (or respectively should not) be released
6144after use.
6145Since often out parameters may or may not be written depending on the exit
6146code of the function,
6147annotations ``__attribute__((os_returns_retained_on_zero))``
6148and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
6149an out parameter at ``+1`` is written if and only if the function returns a zero
6150(respectively non-zero) error code.
6151Observe that return-code-dependent out parameter annotations are only
6152available for retained out parameters, as non-retained object do not have to be
6153released by the callee.
6154These attributes are only used by the Clang Static Analyzer.
6155
6156The family of attributes ``X_returns_X_retained`` can be added to functions,
6157C++ methods, and Objective-C methods and properties.
6158Attributes ``X_consumed`` can be added to parameters of methods, functions,
6159and Objective-C methods.)reST";
6160
6161static const char AttrDoc_OSReturnsRetainedOnZero[] = R"reST(The behavior of a function with respect to reference counting for Foundation
6162(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
6163convention (e.g. functions starting with "get" are assumed to return at
6164``+0``).
6165
6166It can be overridden using a family of the following attributes. In
6167Objective-C, the annotation ``__attribute__((ns_returns_retained))`` applied to
6168a function communicates that the object is returned at ``+1``, and the caller
6169is responsible for freeing it.
6170Similarly, the annotation ``__attribute__((ns_returns_not_retained))``
6171specifies that the object is returned at ``+0`` and the ownership remains with
6172the callee.
6173The annotation ``__attribute__((ns_consumes_self))`` specifies that
6174the Objective-C method call consumes the reference to ``self``, e.g. by
6175attaching it to a supplied parameter.
6176Additionally, parameters can have an annotation
6177``__attribute__((ns_consumed))``, which specifies that passing an owned object
6178as that parameter effectively transfers the ownership, and the caller is no
6179longer responsible for it.
6180These attributes affect code generation when interacting with ARC code, and
6181they are used by the Clang Static Analyzer.
6182
6183In C programs using CoreFoundation, a similar set of attributes:
6184``__attribute__((cf_returns_not_retained))``,
6185``__attribute__((cf_returns_retained))`` and ``__attribute__((cf_consumed))``
6186have the same respective semantics when applied to CoreFoundation objects.
6187These attributes affect code generation when interacting with ARC code, and
6188they are used by the Clang Static Analyzer.
6189
6190Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
6191the same attribute family is present:
6192``__attribute__((os_returns_not_retained))``,
6193``__attribute__((os_returns_retained))`` and ``__attribute__((os_consumed))``,
6194with the same respective semantics.
6195Similar to ``__attribute__((ns_consumes_self))``,
6196``__attribute__((os_consumes_this))`` specifies that the method call consumes
6197the reference to "this" (e.g., when attaching it to a different object supplied
6198as a parameter).
6199Out parameters (parameters the function is meant to write into,
6200either via pointers-to-pointers or references-to-pointers)
6201may be annotated with ``__attribute__((os_returns_retained))``
6202or ``__attribute__((os_returns_not_retained))`` which specifies that the object
6203written into the out parameter should (or respectively should not) be released
6204after use.
6205Since often out parameters may or may not be written depending on the exit
6206code of the function,
6207annotations ``__attribute__((os_returns_retained_on_zero))``
6208and ``__attribute__((os_returns_retained_on_non_zero))`` specify that
6209an out parameter at ``+1`` is written if and only if the function returns a zero
6210(respectively non-zero) error code.
6211Observe that return-code-dependent out parameter annotations are only
6212available for retained out parameters, as non-retained object do not have to be
6213released by the callee.
6214These attributes are only used by the Clang Static Analyzer.
6215
6216The family of attributes ``X_returns_X_retained`` can be added to functions,
6217C++ methods, and Objective-C methods and properties.
6218Attributes ``X_consumed`` can be added to parameters of methods, functions,
6219and Objective-C methods.)reST";
6220
6221static const char AttrDoc_ObjCBoxable[] = R"reST(Structs and unions marked with the ``objc_boxable`` attribute can be used
6222with the Objective-C boxed expression syntax, ``@(...)``.
6223
6224**Usage**: ``__attribute__((objc_boxable))``. This attribute
6225can only be placed on a declaration of a trivially-copyable struct or union:
6226
6227.. code-block:: objc
6228
6229 struct __attribute__((objc_boxable)) some_struct {
6230 int i;
6231 };
6232 union __attribute__((objc_boxable)) some_union {
6233 int i;
6234 float f;
6235 };
6236 typedef struct __attribute__((objc_boxable)) _some_struct some_struct;
6237
6238 // ...
6239
6240 some_struct ss;
6241 NSValue *boxed = @(ss);)reST";
6242
6243static const char AttrDoc_ObjCBridge[] = R"reST(No documentation.)reST";
6244
6245static const char AttrDoc_ObjCBridgeMutable[] = R"reST(No documentation.)reST";
6246
6247static const char AttrDoc_ObjCBridgeRelated[] = R"reST(No documentation.)reST";
6248
6249static const char AttrDoc_ObjCClassStub[] = R"reST(This attribute specifies that the Objective-C class to which it applies is
6250instantiated at runtime.
6251
6252Unlike ``__attribute__((objc_runtime_visible))``, a class having this attribute
6253still has a "class stub" that is visible to the linker. This allows categories
6254to be defined. Static message sends with the class as a receiver use a special
6255access pattern to ensure the class is lazily instantiated from the class stub.
6256
6257Classes annotated with this attribute cannot be subclassed and cannot have
6258implementations defined for them. This attribute is intended for use in
6259Swift-generated headers for classes defined in Swift.
6260
6261Adding or removing this attribute to a class is an ABI-breaking change.)reST";
6262
6263static const char AttrDoc_ObjCDesignatedInitializer[] = R"reST(No documentation.)reST";
6264
6265static const char AttrDoc_ObjCDirect[] = R"reST(The ``objc_direct`` attribute can be used to mark an Objective-C method as
6266being *direct*. A direct method is treated statically like an ordinary method,
6267but dynamically it behaves more like a C function. This lowers some of the costs
6268associated with the method but also sacrifices some of the ordinary capabilities
6269of Objective-C methods.
6270
6271A message send of a direct method calls the implementation directly, as if it
6272were a C function, rather than using ordinary Objective-C method dispatch. This
6273is substantially faster and potentially allows the implementation to be inlined,
6274but it also means the method cannot be overridden in subclasses or replaced
6275dynamically, as ordinary Objective-C methods can.
6276
6277Furthermore, a direct method is not listed in the class's method lists. This
6278substantially reduces the code-size overhead of the method but also means it
6279cannot be called dynamically using ordinary Objective-C method dispatch at all;
6280in particular, this means that it cannot override a superclass method or satisfy
6281a protocol requirement.
6282
6283Because a direct method cannot be overridden, it is an error to perform
6284a ``super`` message send of one.
6285
6286Although a message send of a direct method causes the method to be called
6287directly as if it were a C function, it still obeys Objective-C semantics in other
6288ways:
6289
6290- If the receiver is ``nil``, the message send does nothing and returns the zero value
6291 for the return type.
6292
6293- A message send of a direct class method will cause the class to be initialized,
6294 including calling the ``+initialize`` method if present.
6295
6296- The implicit ``_cmd`` parameter containing the method's selector is still defined.
6297 In order to minimize code-size costs, the implementation will not emit a reference
6298 to the selector if the parameter is unused within the method.
6299
6300Symbols for direct method implementations are implicitly given hidden
6301visibility, meaning that they can only be called within the same linkage unit.
6302
6303It is an error to do any of the following:
6304
6305- declare a direct method in a protocol,
6306- declare an override of a direct method with a method in a subclass,
6307- declare an override of a non-direct method with a direct method in a subclass,
6308- declare a method with different directness in different class interfaces, or
6309- implement a non-direct method (as declared in any class interface) with a direct method.
6310
6311If any of these rules would be violated if every method defined in an
6312``@implementation`` within a single linkage unit were declared in an
6313appropriate class interface, the program is ill-formed with no diagnostic
6314required. If a violation of this rule is not diagnosed, behavior remains
6315well-defined; this paragraph is simply reserving the right to diagnose such
6316conflicts in the future, not to treat them as undefined behavior.
6317
6318Additionally, Clang will warn about any ``@selector`` expression that
6319names a selector that is only known to be used for direct methods.
6320
6321For the purpose of these rules, a "class interface" includes a class's primary
6322``@interface`` block, its class extensions, its categories, its declared protocols,
6323and all the class interfaces of its superclasses.
6324
6325An Objective-C property can be declared with the ``direct`` property
6326attribute. If a direct property declaration causes an implicit declaration of
6327a getter or setter method (that is, if the given method is not explicitly
6328declared elsewhere), the method is declared to be direct.
6329
6330Some programmers may wish to make many methods direct at once. In order
6331to simplify this, the ``objc_direct_members`` attribute is provided; see its
6332documentation for more information.)reST";
6333
6334static const char AttrDoc_ObjCDirectMembers[] = R"reST(The ``objc_direct_members`` attribute can be placed on an Objective-C
6335``@interface`` or ``@implementation`` to mark that methods declared
6336therein should be considered direct by default. See the documentation
6337for ``objc_direct`` for more information about direct methods.
6338
6339When ``objc_direct_members`` is placed on an ``@interface`` block, every
6340method in the block is considered to be declared as direct. This includes any
6341implicit method declarations introduced by property declarations. If the method
6342redeclares a non-direct method, the declaration is ill-formed, exactly as if the
6343method was annotated with the ``objc_direct`` attribute.
6344
6345When ``objc_direct_members`` is placed on an ``@implementation`` block,
6346methods defined in the block are considered to be declared as direct unless
6347they have been previously declared as non-direct in any interface of the class.
6348This includes the implicit method definitions introduced by synthesized
6349properties, including auto-synthesized properties.)reST";
6350
6351static const char AttrDoc_ObjCException[] = R"reST(No documentation.)reST";
6352
6353static const char AttrDoc_ObjCExplicitProtocolImpl[] = R"reST(No documentation.)reST";
6354
6355static const char AttrDoc_ObjCExternallyRetained[] = R"reST(The ``objc_externally_retained`` attribute can be applied to strong local
6356variables, functions, methods, or blocks to opt into
6357`externally-retained semantics
6358<https://clang.llvm.org/docs/AutomaticReferenceCounting.html#externally-retained-variables>`_.
6359
6360When applied to the definition of a function, method, or block, every parameter
6361of the function with implicit strong retainable object pointer type is
6362considered externally-retained, and becomes ``const``. By explicitly annotating
6363a parameter with ``__strong``, you can opt back into the default
6364non-externally-retained behavior for that parameter. For instance,
6365``first_param`` is externally-retained below, but not ``second_param``:
6366
6367.. code-block:: objc
6368
6369 __attribute__((objc_externally_retained))
6370 void f(NSArray *first_param, __strong NSArray *second_param) {
6371 // ...
6372 }
6373
6374Likewise, when applied to a strong local variable, that variable becomes
6375``const`` and is considered externally-retained.
6376
6377When compiled without ``-fobjc-arc``, this attribute is ignored.)reST";
6378
6379static const char AttrDoc_ObjCGC[] = R"reST(No documentation.)reST";
6380
6381static const char AttrDoc_ObjCIndependentClass[] = R"reST(No documentation.)reST";
6382
6383static const char AttrDoc_ObjCInertUnsafeUnretained[] = R"reST()reST";
6384
6385static const char AttrDoc_ObjCKindOf[] = R"reST(No documentation.)reST";
6386
6387static const char AttrDoc_ObjCMethodFamily[] = R"reST(Many methods in Objective-C have conventional meanings determined by their
6388selectors. It is sometimes useful to be able to mark a method as having a
6389particular conventional meaning despite not having the right selector, or as
6390not having the conventional meaning that its selector would suggest. For these
6391use cases, we provide an attribute to specifically describe the "method family"
6392that a method belongs to.
6393
6394**Usage**: ``__attribute__((objc_method_family(X)))``, where ``X`` is one of
6395``none``, ``alloc``, ``copy``, ``init``, ``mutableCopy``, or ``new``. This
6396attribute can only be placed at the end of a method declaration:
6397
6398.. code-block:: objc
6399
6400 - (NSString *)initMyStringValue __attribute__((objc_method_family(none)));
6401
6402Users who do not wish to change the conventional meaning of a method, and who
6403merely want to document its non-standard retain and release semantics, should
6404use the retaining behavior attributes (``ns_returns_retained``,
6405``ns_returns_not_retained``, etc).
6406
6407Query for this feature with ``__has_attribute(objc_method_family)``.)reST";
6408
6409static const char AttrDoc_ObjCNSObject[] = R"reST(No documentation.)reST";
6410
6411static const char AttrDoc_ObjCNonLazyClass[] = R"reST(This attribute can be added to an Objective-C ``@interface`` or
6412``@implementation`` declaration to add the class to the list of non-lazily
6413initialized classes. A non-lazy class will be initialized eagerly when the
6414Objective-C runtime is loaded. This is required for certain system classes which
6415have instances allocated in non-standard ways, such as the classes for blocks
6416and constant strings. Adding this attribute is essentially equivalent to
6417providing a trivial ``+load`` method but avoids the (fairly small) load-time
6418overheads associated with defining and calling such a method.)reST";
6419
6420static const char AttrDoc_ObjCNonRuntimeProtocol[] = R"reST(The ``objc_non_runtime_protocol`` attribute can be used to mark that an
6421Objective-C protocol is only used during static type-checking and doesn't need
6422to be represented dynamically. This avoids several small code-size and run-time
6423overheads associated with handling the protocol's metadata. A non-runtime
6424protocol cannot be used as the operand of a ``@protocol`` expression, and
6425dynamic attempts to find it with ``objc_getProtocol`` will fail.
6426
6427If a non-runtime protocol inherits from any ordinary protocols, classes and
6428derived protocols that declare conformance to the non-runtime protocol will
6429dynamically list their conformance to those bare protocols.)reST";
6430
6431static const char AttrDoc_ObjCOwnership[] = R"reST(No documentation.)reST";
6432
6433static const char AttrDoc_ObjCPreciseLifetime[] = R"reST(No documentation.)reST";
6434
6435static const char AttrDoc_ObjCRequiresPropertyDefs[] = R"reST(No documentation.)reST";
6436
6437static const char AttrDoc_ObjCRequiresSuper[] = R"reST(Some Objective-C classes allow a subclass to override a particular method in a
6438parent class but expect that the overriding method also calls the overridden
6439method in the parent class. For these cases, we provide an attribute to
6440designate that a method requires a "call to ``super``" in the overriding
6441method in the subclass.
6442
6443**Usage**: ``__attribute__((objc_requires_super))``. This attribute can only
6444be placed at the end of a method declaration:
6445
6446.. code-block:: objc
6447
6448 - (void)foo __attribute__((objc_requires_super));
6449
6450This attribute can only be applied the method declarations within a class, and
6451not a protocol. Currently this attribute does not enforce any placement of
6452where the call occurs in the overriding method (such as in the case of
6453``-dealloc`` where the call must appear at the end). It checks only that it
6454exists.
6455
6456Note that on both OS X and iOS that the Foundation framework provides a
6457convenience macro ``NS_REQUIRES_SUPER`` that provides syntactic sugar for this
6458attribute:
6459
6460.. code-block:: objc
6461
6462 - (void)foo NS_REQUIRES_SUPER;
6463
6464This macro is conditionally defined depending on the compiler's support for
6465this attribute. If the compiler does not support the attribute the macro
6466expands to nothing.
6467
6468Operationally, when a method has this annotation the compiler will warn if the
6469implementation of an override in a subclass does not call super. For example:
6470
6471.. code-block:: objc
6472
6473 warning: method possibly missing a [super AnnotMeth] call
6474 - (void) AnnotMeth{};
6475 ^)reST";
6476
6477static const char AttrDoc_ObjCReturnsInnerPointer[] = R"reST(No documentation.)reST";
6478
6479static const char AttrDoc_ObjCRootClass[] = R"reST(No documentation.)reST";
6480
6481static const char AttrDoc_ObjCRuntimeName[] = R"reST(By default, the Objective-C interface or protocol identifier is used
6482in the metadata name for that object. The ``objc_runtime_name``
6483attribute allows annotated interfaces or protocols to use the
6484specified string argument in the object's metadata name instead of the
6485default name.
6486
6487**Usage**: ``__attribute__((objc_runtime_name("MyLocalName")))``. This attribute
6488can only be placed before an @protocol or @interface declaration:
6489
6490.. code-block:: objc
6491
6492 __attribute__((objc_runtime_name("MyLocalName")))
6493 @interface Message
6494 @end)reST";
6495
6496static const char AttrDoc_ObjCRuntimeVisible[] = R"reST(This attribute specifies that the Objective-C class to which it applies is
6497visible to the Objective-C runtime but not to the linker. Classes annotated
6498with this attribute cannot be subclassed and cannot have categories defined for
6499them.)reST";
6500
6501static const char AttrDoc_ObjCSubclassingRestricted[] = R"reST(This attribute can be added to an Objective-C ``@interface`` declaration to
6502ensure that this class cannot be subclassed.)reST";
6503
6504static const char AttrDoc_OpenACCRoutineAnnot[] = R"reST()reST";
6505
6506static const char AttrDoc_OpenACCRoutineDecl[] = R"reST()reST";
6507
6508static const char AttrDoc_OpenCLAccess[] = R"reST(The access qualifiers must be used with image object arguments or pipe arguments
6509to declare if they are being read or written by a kernel or function.
6510
6511The read_only/__read_only, write_only/__write_only and read_write/__read_write
6512names are reserved for use as access qualifiers and shall not be used otherwise.
6513
6514.. code-block:: c
6515
6516 kernel void
6517 foo (read_only image2d_t imageA,
6518 write_only image2d_t imageB) {
6519 ...
6520 }
6521
6522In the above example imageA is a read-only 2D image object, and imageB is a
6523write-only 2D image object.
6524
6525The read_write (or __read_write) qualifier can not be used with pipe.
6526
6527More details can be found in the OpenCL C language Spec v2.0, Section 6.6.)reST";
6528
6529static const char AttrDoc_OpenCLConstantAddressSpace[] = R"reST(The constant address space attribute signals that an object is located in
6530a constant (non-modifiable) memory region. It is available to all work items.
6531Any type can be annotated with the constant address space attribute. Objects
6532with the constant address space qualifier can be declared in any scope and must
6533have an initializer.)reST";
6534
6535static const char AttrDoc_OpenCLGenericAddressSpace[] = R"reST(The generic address space attribute is only available with OpenCL v2.0 and later.
6536It can be used with pointer types. Variables in global and local scope and
6537function parameters in non-kernel functions can have the generic address space
6538type attribute. It is intended to be a placeholder for any other address space
6539except for '__constant' in OpenCL code which can be used with multiple address
6540spaces.)reST";
6541
6542static const char AttrDoc_OpenCLGlobalAddressSpace[] = R"reST(The global address space attribute specifies that an object is allocated in
6543global memory, which is accessible by all work items. The content stored in this
6544memory area persists between kernel executions. Pointer types to the global
6545address space are allowed as function parameters or local variables. Starting
6546with OpenCL v2.0, the global address space can be used with global (program
6547scope) variables and static local variable as well.)reST";
6548
6549static const char AttrDoc_OpenCLGlobalDeviceAddressSpace[] = R"reST(The ``global_device`` and ``global_host`` address space attributes specify that
6550an object is allocated in global memory on the device/host. It helps to
6551distinguish USM (Unified Shared Memory) pointers that access global device
6552memory from those that access global host memory. These new address spaces are
6553a subset of the ``__global/opencl_global`` address space, the full address space
6554set model for OpenCL 2.0 with the extension looks as follows:
6555
6556 | generic->global->host
6557 | ->device
6558 | ->private
6559 | ->local
6560 | constant
6561
6562As ``global_device`` and ``global_host`` are a subset of
6563``__global/opencl_global`` address spaces it is allowed to convert
6564``global_device`` and ``global_host`` address spaces to
6565``__global/opencl_global`` address spaces (following ISO/IEC TR 18037 5.1.3
6566"Address space nesting and rules for pointers").
6567
6568These attributes are deprecated and may be removed in a future version of Clang.)reST";
6569
6570static const char AttrDoc_OpenCLGlobalHostAddressSpace[] = R"reST(The ``global_device`` and ``global_host`` address space attributes specify that
6571an object is allocated in global memory on the device/host. It helps to
6572distinguish USM (Unified Shared Memory) pointers that access global device
6573memory from those that access global host memory. These new address spaces are
6574a subset of the ``__global/opencl_global`` address space, the full address space
6575set model for OpenCL 2.0 with the extension looks as follows:
6576
6577 | generic->global->host
6578 | ->device
6579 | ->private
6580 | ->local
6581 | constant
6582
6583As ``global_device`` and ``global_host`` are a subset of
6584``__global/opencl_global`` address spaces it is allowed to convert
6585``global_device`` and ``global_host`` address spaces to
6586``__global/opencl_global`` address spaces (following ISO/IEC TR 18037 5.1.3
6587"Address space nesting and rules for pointers").
6588
6589These attributes are deprecated and may be removed in a future version of Clang.)reST";
6590
6591static const char AttrDoc_OpenCLIntelReqdSubGroupSize[] = R"reST(The optional attribute intel_reqd_sub_group_size can be used to indicate that
6592the kernel must be compiled and executed with the specified subgroup size. When
6593this attribute is present, get_max_sub_group_size() is guaranteed to return the
6594specified integer value. This is important for the correctness of many subgroup
6595algorithms, and in some cases may be used by the compiler to generate more optimal
6596code. See `cl_intel_required_subgroup_size
6597<https://www.khronos.org/registry/OpenCL/extensions/intel/cl_intel_required_subgroup_size.txt>`
6598for details.)reST";
6599
6600static const char AttrDoc_OpenCLLocalAddressSpace[] = R"reST(The local address space specifies that an object is allocated in the local (work
6601group) memory area, which is accessible to all work items in the same work
6602group. The content stored in this memory region is not accessible after
6603the kernel execution ends. In a kernel function scope, any variable can be in
6604the local address space. In other scopes, only pointer types to the local address
6605space are allowed. Local address space variables cannot have an initializer.)reST";
6606
6607static const char AttrDoc_OpenCLPrivateAddressSpace[] = R"reST(The private address space specifies that an object is allocated in the private
6608(work item) memory. Other work items cannot access the same memory area and its
6609content is destroyed after work item execution ends. Local variables can be
6610declared in the private address space. Function arguments are always in the
6611private address space. Kernel function arguments of a pointer or an array type
6612cannot point to the private address space.)reST";
6613
6614static const char AttrDoc_OpenCLUnrollHint[] = R"reST(The opencl_unroll_hint attribute qualifier can be used to specify that a loop
6615(for, while and do loops) can be unrolled. This attribute qualifier can be
6616used to specify full unrolling or partial unrolling by a specified amount.
6617This is a compiler hint and the compiler may ignore this directive. See
6618`OpenCL v2.0 <https://www.khronos.org/registry/cl/specs/opencl-2.0.pdf>`_
6619s6.11.5 for details.)reST";
6620
6621static const char AttrDoc_OptimizeNone[] = R"reST(The ``optnone`` attribute suppresses essentially all optimizations
6622on a function or method, regardless of the optimization level applied to
6623the compilation unit as a whole. This is particularly useful when you
6624need to debug a particular function, but it is infeasible to build the
6625entire application without optimization. Avoiding optimization on the
6626specified function can improve the quality of the debugging information
6627for that function.
6628
6629This attribute is incompatible with the ``always_inline`` and ``minsize``
6630attributes.
6631
6632Note that this attribute does not apply recursively to nested functions such as
6633lambdas or blocks when using declaration-specific attribute syntaxes such as double
6634square brackets (``[[]]``) or ``__attribute__``. The ``#pragma`` syntax can be
6635used to apply the attribute to all functions, including nested functions, in a
6636range of source code.)reST";
6637
6638static const char AttrDoc_OverflowBehavior[] = R"reST(The ``overflow_behavior`` attribute provides fine-grained, type-level control
6639over how arithmetic operations on an integer type behave on overflow. It may be
6640applied to a ``typedef``, to a variable or data member, or to an integer type
6641directly, and accepts one of two behaviors as its argument:
6642
6643* ``wrap``: arithmetic on the attributed type wraps on overflow, using two's
6644 complement semantics. This is equivalent to ``-fwrapv`` but scoped to the
6645 attributed type, and works for both signed and unsigned types. UBSan's
6646 ``signed-integer-overflow``, ``unsigned-integer-overflow``,
6647 ``implicit-signed-integer-truncation``, and
6648 ``implicit-unsigned-integer-truncation`` checks are suppressed for the type.
6649
6650* ``trap``: arithmetic on the attributed type is checked for overflow, enabling
6651 overflow checks for the type even when ``-fwrapv`` is in effect globally.
6652
6653.. code-block:: c++
6654
6655 typedef unsigned int __attribute__((overflow_behavior(trap))) non_wrapping_uint;
6656
6657 non_wrapping_uint add_one(non_wrapping_uint a) {
6658 return a + 1; // Overflow is checked for this operation.
6659 }
6660
6661 int mul_alot(int n) {
6662 int __attribute__((overflow_behavior(wrap))) a = n;
6663 return a * 1337; // Overflow is not checked and is well-defined.
6664 }
6665
6666The keyword spellings ``__ob_wrap`` and ``__ob_trap`` are equivalent to
6667``overflow_behavior(wrap)`` and ``overflow_behavior(trap)`` respectively.
6668
6669The attribute wholly overrides global flags (``-ftrapv``, ``-fwrapv``,
6670sanitizers, and Sanitizer Special Case Lists) for the attributed type. It can
6671only be applied to integer types.
6672
6673This feature is experimental and must be enabled with the ``-cc1`` option
6674``-fexperimental-overflow-behavior-types``. For full details on promotion and
6675conversion rules, pointer semantics, diagnostics, and interaction with
6676sanitizers, see :doc:`OverflowBehaviorTypes`.)reST";
6677
6678static const char AttrDoc_Overloadable[] = R"reST(Clang provides support for C++ function overloading in C. Function overloading
6679in C is introduced using the ``overloadable`` attribute. For example, one
6680might provide several overloaded versions of a ``tgsin`` function that invokes
6681the appropriate standard function computing the sine of a value with ``float``,
6682``double``, or ``long double`` precision:
6683
6684.. code-block:: c
6685
6686 #include <math.h>
6687 float __attribute__((overloadable)) tgsin(float x) { return sinf(x); }
6688 double __attribute__((overloadable)) tgsin(double x) { return sin(x); }
6689 long double __attribute__((overloadable)) tgsin(long double x) { return sinl(x); }
6690
6691Given these declarations, one can call ``tgsin`` with a ``float`` value to
6692receive a ``float`` result, with a ``double`` to receive a ``double`` result,
6693etc. Function overloading in C follows the rules of C++ function overloading
6694to pick the best overload given the call arguments, with a few C-specific
6695semantics:
6696
6697* Conversion from ``float`` or ``double`` to ``long double`` is ranked as a
6698 floating-point promotion (per C99) rather than as a floating-point conversion
6699 (as in C++).
6700
6701* A conversion from a pointer of type ``T*`` to a pointer of type ``U*`` is
6702 considered a pointer conversion (with conversion rank) if ``T`` and ``U`` are
6703 compatible types.
6704
6705* A conversion from type ``T`` to a value of type ``U`` is permitted if ``T``
6706 and ``U`` are compatible types. This conversion is given "conversion" rank.
6707
6708* If no viable candidates are otherwise available, we allow a conversion from a
6709 pointer of type ``T*`` to a pointer of type ``U*``, where ``T`` and ``U`` are
6710 incompatible. This conversion is ranked below all other types of conversions.
6711 Please note: ``U`` lacking qualifiers that are present on ``T`` is sufficient
6712 for ``T`` and ``U`` to be incompatible.
6713
6714The declaration of ``overloadable`` functions is restricted to function
6715declarations and definitions. If a function is marked with the ``overloadable``
6716attribute, then all declarations and definitions of functions with that name,
6717except for at most one (see the note below about unmarked overloads), must have
6718the ``overloadable`` attribute. In addition, redeclarations of a function with
6719the ``overloadable`` attribute must have the ``overloadable`` attribute, and
6720redeclarations of a function without the ``overloadable`` attribute must *not*
6721have the ``overloadable`` attribute. e.g.,
6722
6723.. code-block:: c
6724
6725 int f(int) __attribute__((overloadable));
6726 float f(float); // error: declaration of "f" must have the "overloadable" attribute
6727 int f(int); // error: redeclaration of "f" must have the "overloadable" attribute
6728
6729 int g(int) __attribute__((overloadable));
6730 int g(int) { } // error: redeclaration of "g" must also have the "overloadable" attribute
6731
6732 int h(int);
6733 int h(int) __attribute__((overloadable)); // error: declaration of "h" must not
6734 // have the "overloadable" attribute
6735
6736Functions marked ``overloadable`` must have prototypes. Therefore, the
6737following code is ill-formed:
6738
6739.. code-block:: c
6740
6741 int h() __attribute__((overloadable)); // error: h does not have a prototype
6742
6743However, ``overloadable`` functions are allowed to use a ellipsis even if there
6744are no named parameters (as is permitted in C++). This feature is particularly
6745useful when combined with the ``unavailable`` attribute:
6746
6747.. code-block:: c++
6748
6749 void honeypot(...) __attribute__((overloadable, unavailable)); // calling me is an error
6750
6751Functions declared with the ``overloadable`` attribute have their names mangled
6752according to the same rules as C++ function names. For example, the three
6753``tgsin`` functions in our motivating example get the mangled names
6754``_Z5tgsinf``, ``_Z5tgsind``, and ``_Z5tgsine``, respectively. There are two
6755caveats to this use of name mangling:
6756
6757* Future versions of Clang may change the name mangling of functions overloaded
6758 in C, so you should not depend on an specific mangling. To be completely
6759 safe, we strongly urge the use of ``static inline`` with ``overloadable``
6760 functions.
6761
6762* The ``overloadable`` attribute has almost no meaning when used in C++,
6763 because names will already be mangled and functions are already overloadable.
6764 However, when an ``overloadable`` function occurs within an ``extern "C"``
6765 linkage specification, its name *will* be mangled in the same way as it
6766 would in C.
6767
6768For the purpose of backwards compatibility, at most one function with the same
6769name as other ``overloadable`` functions may omit the ``overloadable``
6770attribute. In this case, the function without the ``overloadable`` attribute
6771will not have its name mangled.
6772
6773For example:
6774
6775.. code-block:: c
6776
6777 // Notes with mangled names assume Itanium mangling.
6778 int f(int);
6779 int f(double) __attribute__((overloadable));
6780 void foo() {
6781 f(5); // Emits a call to f (not _Z1fi, as it would with an overload that
6782 // was marked with overloadable).
6783 f(1.0); // Emits a call to _Z1fd.
6784 }
6785
6786Support for unmarked overloads is not present in some versions of clang. You may
6787query for it using ``__has_extension(overloadable_unmarked)``.
6788
6789Query for this attribute with ``__has_attribute(overloadable)``.)reST";
6790
6791static const char AttrDoc_Override[] = R"reST()reST";
6792
6793static const char AttrDoc_Owner[] = R"reST(.. Note:: This attribute is experimental and its effect on analysis is subject to change in
6794 a future version of clang.
6795
6796The attribute ``[[gsl::Owner(T)]]`` applies to structs and classes that own an
6797object of type ``T``:
6798
6799.. code::
6800
6801 class [[gsl::Owner(int)]] IntOwner {
6802 private:
6803 int value;
6804 public:
6805 int *getInt() { return &value; }
6806 };
6807
6808The argument ``T`` is optional and is ignored.
6809This attribute may be used by analysis tools and has no effect on code
6810generation. A ``void`` argument means that the class can own any type.
6811
6812See Pointer_ for an example.)reST";
6813
6814static const char AttrDoc_Ownership[] = R"reST(.. note::
6815
6816 In order for the Clang Static Analyzer to acknowledge these attributes, the
6817 ``Optimistic`` config needs to be set to true for the checker
6818 ``unix.DynamicMemoryModeling``:
6819
6820 ``-Xclang -analyzer-config -Xclang unix.DynamicMemoryModeling:Optimistic=true``
6821
6822These attributes are used by the Clang Static Analyzer's dynamic memory modeling
6823facilities to mark custom allocating/deallocating functions.
6824
6825All 3 attributes' first parameter of type string is the type of the allocation:
6826``malloc``, ``new``, etc. to allow for catching :ref:`mismatched deallocation
6827<unix-MismatchedDeallocator>` bugs. The allocation type can be any string, e.g.
6828a function annotated with
6829returning a piece of memory of type ``lasagna`` but freed with a function
6830annotated to release ``cheese`` typed memory will result in mismatched
6831deallocation warning.
6832
6833The (currently) only allocation type having special meaning is ``malloc`` --
6834the Clang Static Analyzer makes sure that allocating functions annotated with
6835``malloc`` are treated like they used the standard ``malloc()``, and can be
6836safely deallocated with the standard ``free()``.
6837
6838* Use ``ownership_returns`` to mark a function as an allocating function.
6839 It takes 1 or 2 arguments.
6840 The first argument is a user-provided identifier representing the "kind" of the allocation.
6841 This is basically what is enforced when checking the deallocation. This is mandatory.
6842 The second argument is optional.
6843 It represents the index of the parameter that represents the allocation size in bytes (counting from 1).
6844 The referenced parameter must have some integral type.
6845 This attribute may appear at most once per declaration.
6846 If this argument is not set, then tooling, such as the Clang Static Analyzer,
6847 won't be able to reason about the size of the allocation, thus check potential out-of-bounds accesses.
6848 However, such tooling could still warn if the wrong deallocation function
6849 was used for the ``ownership_returns`` attributed resource.
6850 If forward declarations have this attribute, those must have the same arguments.
6851* Use ``ownership_takes`` to mark a function as a deallocating function. Takes 2
6852 arguments: the allocation type, and the index of the parameter that is being
6853 deallocated (counting from 1).
6854* Use ``ownership_holds`` to mark that a function takes over the ownership of a
6855 piece of memory and will free it at some unspecified point in the future. Like
6856 ``ownership_takes``, this takes 2 arguments: the allocation type, and the
6857 index of the parameter whose ownership will be taken over (counting from 1).
6858
6859The annotations ``ownership_takes`` and ``ownership_holds`` both prevent memory
6860leak reports (concerning the specified parameter); the difference between them
6861is that using taken memory is a use-after-free error, while using held memory
6862is assumed to be legitimate. However, releasing the held memory or passing it
6863to another holding call is reported by the analyzer as an "attempt to release
6864non-owned memory".
6865
6866Example:
6867
6868.. code-block:: c
6869
6870 // Denotes that my_malloc will return with a dynamically allocated piece of
6871 // memory using malloc().
6872 void __attribute((ownership_returns(malloc))) *my_malloc(size_t sz);
6873
6874 // 'sz' (parameter 1) is the allocation size.
6875 void __attribute((ownership_returns(malloc, 1))) *my_sized_malloc(size_t sz);
6876
6877 // Denotes that my_free will deallocate its argument using free().
6878 void __attribute((ownership_takes(malloc, 1))) my_free(void *);
6879
6880 // Denotes that my_hold will take over the ownership of its argument that was
6881 // allocated via malloc().
6882 void __attribute((ownership_holds(malloc, 1))) my_hold(void *);
6883
6884Further reading about dynamic memory modeling in the Clang Static Analyzer is
6885found in these checker docs:
6886:ref:`unix.Malloc <unix-Malloc>`, :ref:`unix.MallocSizeof <unix-MallocSizeof>`,
6887:ref:`unix.MismatchedDeallocator <unix-MismatchedDeallocator>`,
6888:ref:`cplusplus.NewDelete <cplusplus-NewDelete>`,
6889:ref:`cplusplus.NewDeleteLeaks <cplusplus-NewDeleteLeaks>`,
6890:ref:`optin.taint.TaintedAlloc <optin-taint-TaintedAlloc>`.
6891Mind that many more checkers are affected by dynamic memory modeling changes to
6892some extent.
6893
6894Further reading for other annotations:
6895`Source Annotations in the Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/user-docs/Annotations.html>`_.)reST";
6896
6897static const char AttrDoc_Packed[] = R"reST(No documentation.)reST";
6898
6899static const char AttrDoc_ParamTypestate[] = R"reST(This attribute specifies expectations about function parameters. Calls to an
6900function with annotated parameters will issue a warning if the corresponding
6901argument isn't in the expected state. The attribute is also used to set the
6902initial state of the parameter when analyzing the function's body.)reST";
6903
6904static const char AttrDoc_Pascal[] = R"reST(No documentation.)reST";
6905
6906static const char AttrDoc_PassObjectSize[] = R"reST(.. Note:: The mangling of functions with parameters that are annotated with
6907 ``pass_object_size`` is subject to change. You can get around this by
6908 using ``__asm__("foo")`` to explicitly name your functions, thus preserving
6909 your ABI; also, non-overloadable C functions with ``pass_object_size`` are
6910 not mangled.
6911
6912The ``pass_object_size(Type)`` attribute can be placed on function parameters to
6913instruct clang to call ``__builtin_object_size(param, Type)`` at each callsite
6914of said function, and implicitly pass the result of this call in as an invisible
6915argument of type ``size_t`` directly after the parameter annotated with
6916``pass_object_size``. Clang will also replace any calls to
6917``__builtin_object_size(param, Type)`` in the function by said implicit
6918parameter.
6919
6920Example usage:
6921
6922.. code-block:: c
6923
6924 int bzero1(char *const p __attribute__((pass_object_size(0))))
6925 __attribute__((noinline)) {
6926 int i = 0;
6927 for (/**/; i < (int)__builtin_object_size(p, 0); ++i) {
6928 p[i] = 0;
6929 }
6930 return i;
6931 }
6932
6933 int main() {
6934 char chars[100];
6935 int n = bzero1(&chars[0]);
6936 assert(n == sizeof(chars));
6937 return 0;
6938 }
6939
6940If successfully evaluating ``__builtin_object_size(param, Type)`` at the
6941callsite is not possible, then the "failed" value is passed in. So, using the
6942definition of ``bzero1`` from above, the following code would exit cleanly:
6943
6944.. code-block:: c
6945
6946 int main2(int argc, char *argv[]) {
6947 int n = bzero1(argv);
6948 assert(n == -1);
6949 return 0;
6950 }
6951
6952``pass_object_size`` plays a part in overload resolution. If two overload
6953candidates are otherwise equally good, then the overload with one or more
6954parameters with ``pass_object_size`` is preferred. This implies that the choice
6955between two identical overloads both with ``pass_object_size`` on one or more
6956parameters will always be ambiguous; for this reason, having two such overloads
6957is illegal. For example:
6958
6959.. code-block:: c++
6960
6961 #define PS(N) __attribute__((pass_object_size(N)))
6962 // OK
6963 void Foo(char *a, char *b); // Overload A
6964 // OK -- overload A has no parameters with pass_object_size.
6965 void Foo(char *a PS(0), char *b PS(0)); // Overload B
6966 // Error -- Same signature (sans pass_object_size) as overload B, and both
6967 // overloads have one or more parameters with the pass_object_size attribute.
6968 void Foo(void *a PS(0), void *b);
6969
6970 // OK
6971 void Bar(void *a PS(0)); // Overload C
6972 // OK
6973 void Bar(char *c PS(1)); // Overload D
6974
6975 void main() {
6976 char known[10], *unknown;
6977 Foo(unknown, unknown); // Calls overload B
6978 Foo(known, unknown); // Calls overload B
6979 Foo(unknown, known); // Calls overload B
6980 Foo(known, known); // Calls overload B
6981
6982 Bar(known); // Calls overload D
6983 Bar(unknown); // Calls overload D
6984 }
6985
6986Currently, ``pass_object_size`` is a bit restricted in terms of its usage:
6987
6988* Only one use of ``pass_object_size`` is allowed per parameter.
6989
6990* It is an error to take the address of a function with ``pass_object_size`` on
6991 any of its parameters. If you wish to do this, you can create an overload
6992 without ``pass_object_size`` on any parameters.
6993
6994* It is an error to apply the ``pass_object_size`` attribute to parameters that
6995 are not pointers. Additionally, any parameter that ``pass_object_size`` is
6996 applied to must be marked ``const`` at its function's definition.
6997
6998Clang also supports the ``pass_dynamic_object_size`` attribute, which behaves
6999identically to ``pass_object_size``, but evaluates a call to
7000``__builtin_dynamic_object_size`` at the callee instead of
7001``__builtin_object_size``. ``__builtin_dynamic_object_size`` provides some extra
7002runtime checks when the object size can't be determined at compile-time. You can
7003read more about ``__builtin_dynamic_object_size`` `here
7004<https://clang.llvm.org/docs/LanguageExtensions.html#evaluating-object-size-dynamically>`_.)reST";
7005
7006static const char AttrDoc_PatchableFunctionEntry[] = R"reST(``__attribute__((patchable_function_entry(N,M,Section)))`` is used to generate M
7007NOPs before the function entry and N-M NOPs after the function entry, with a record of
7008the entry stored in section ``Section``. This attribute takes precedence over the
7009command line option ``-fpatchable-function-entry=N,M,Section``. ``M`` defaults to 0
7010if omitted.``Section`` defaults to the ``-fpatchable-function-entry`` section name if
7011set, or to ``__patchable_function_entries`` otherwise.
7012
7013This attribute is only supported on
7014aarch64/aarch64-be/loongarch32/loongarch64/riscv32/riscv64/i386/x86-64/ppc/ppc64/ppc64le/s390x targets.
7015For ppc/ppc64 targets, AIX is still not supported.)reST";
7016
7017static const char AttrDoc_Pcs[] = R"reST(On ARM targets, this attribute can be used to select calling conventions
7018similar to ``stdcall`` on x86. Valid parameter values are "aapcs" and
7019"aapcs-vfp".)reST";
7020
7021static const char AttrDoc_Personality[] = R"reST(``__attribute__((personality(<routine>)))`` is used to specify a personality
7022routine that is different from the language that is being used to implement the
7023function. This is a targeted, low-level feature aimed at language runtime
7024implementors who write runtime support code in C/C++ but need that code to
7025participate in a foreign language's exception-handling or unwinding model.
7026
7027A personality routine is a language-specific callback attached to each stack
7028frame that the unwinder invokes to determine whether that frame handles a given
7029exception and what cleanup actions to perform. It effectively colors the
7030language-agnostic unwinding mechanism with language-specific semantics, enabling
7031different languages to coexist on the same call stack while each interpreting
7032exceptions according to their own rules.)reST";
7033
7034static const char AttrDoc_Pointer[] = R"reST(.. Note:: This attribute is experimental and its effect on analysis is subject to change in
7035 a future version of clang.
7036
7037The attribute ``[[gsl::Pointer(T)]]`` applies to structs and classes that behave
7038like pointers to an object of type ``T``:
7039
7040.. code::
7041
7042 class [[gsl::Pointer(int)]] IntPointer {
7043 private:
7044 int *valuePointer;
7045 public:
7046 IntPointer(const IntOwner&);
7047 int *getInt() { return valuePointer; }
7048 };
7049
7050The argument ``T`` is optional and is ignored.
7051This attribute may be used by analysis tools and has no effect on code
7052generation. A ``void`` argument means that the pointer can point to any type.
7053
7054Example:
7055When constructing an instance of a class annotated like this (a Pointer) from
7056an instance of a class annotated with ``[[gsl::Owner]]`` (an Owner),
7057then the analysis will consider the Pointer to point inside the Owner.
7058When the Owner's lifetime ends, it will consider the Pointer to be dangling.
7059
7060.. code-block:: c++
7061
7062 int f() {
7063 IntPointer P(IntOwner{}); // P "points into" a temporary IntOwner object
7064 P.getInt(); // P is dangling
7065 }
7066
7067**Transparent Member Functions**
7068
7069The analysis automatically tracks certain member functions of ``[[gsl::Pointer]]`` types
7070that provide transparent access to the pointed-to object. These include:
7071
7072* Dereference operators: ``operator*``, ``operator->``
7073* Data access methods: ``data()``, ``c_str()``, ``get()``
7074* Iterator operations: ``begin()``, ``end()``, ``rbegin()``, ``rend()``, ``cbegin()``, ``cend()``, ``crbegin()``, ``crend()``, ``operator+``, ``operator-``, ``operator++``, ``operator--``
7075
7076When these methods return pointers, view types, or references, the analysis treats them as
7077transparently borrowing from the same object that the pointer itself borrows from,
7078enabling detection of use-after-free through these access patterns:
7079
7080.. code-block:: c++
7081
7082 // For example, .data() here returns a borrow to 's' instead of 'v'.
7083 const char* f() {
7084 std::string s = "hello";
7085 std::string_view v = s; // warning: address of stack memory returned
7086 return v.data(); // note: returned here
7087 }
7088
7089 const MyObj& g(MyObj obj) {
7090 View v = obj; // warning: address of stack memory returned
7091 return *v; // note: returned here
7092 }
7093
7094This tracking also applies to range-based for loops, where the ``begin()`` and ``end()``
7095iterators are used to access elements:
7096
7097.. code-block:: c++
7098
7099 std::string_view f(std::vector<std::string> vec) {
7100 for (const std::string& s : vec) { // warning: address of stack memory returned
7101 return s; // note: returned here
7102 }
7103 }
7104
7105**Container Template Specialization**
7106
7107If a template class is annotated with ``[[gsl::Owner]]``, and the first
7108instantiated template argument is a pointer type (raw pointer, or ``[[gsl::Pointer]]``),
7109the analysis will consider the instantiated class as a container of the pointer.
7110When constructing such an object from a GSL owner object, the analysis will
7111assume that the container holds a pointer to the owner object. Consequently,
7112when the owner object is destroyed, the pointer will be considered dangling.
7113
7114.. code-block:: c++
7115
7116 int f() {
7117 std::vector<std::string_view> v = {std::string()}; // v holds a dangling pointer.
7118 std::optional<std::string_view> o = std::string(); // o holds a dangling pointer.
7119 })reST";
7120
7121static const char AttrDoc_PointerAuth[] = R"reST(The ``__ptrauth`` qualifier allows the programmer to directly control
7122how pointers are signed when they are stored in a particular variable.
7123This can be used to strengthen the default protections of pointer
7124authentication and make it more difficult for an attacker to escalate
7125an ability to alter memory into full control of a process.
7126
7127.. code-block:: c
7128
7129 #include <ptrauth.h>
7130
7131 typedef void (*my_callback)(const void*);
7132 my_callback __ptrauth(ptrauth_key_process_dependent_code, 1, 0xe27a) callback;
7133
7134The first argument to ``__ptrauth`` is the name of the signing key.
7135Valid key names for the target are defined in ``<ptrauth.h>``.
7136
7137The second argument to ``__ptrauth`` is a flag (0 or 1) specifying whether
7138the object should use address discrimination.
7139
7140The third argument to ``__ptrauth`` is a 16-bit non-negative integer which
7141allows additional discrimination between objects.)reST";
7142
7143static const char AttrDoc_PointerFieldProtection[] = R"reST(No documentation.)reST";
7144
7145static const char AttrDoc_PragmaClangBSSSection[] = R"reST()reST";
7146
7147static const char AttrDoc_PragmaClangDataSection[] = R"reST()reST";
7148
7149static const char AttrDoc_PragmaClangRelroSection[] = R"reST()reST";
7150
7151static const char AttrDoc_PragmaClangRodataSection[] = R"reST()reST";
7152
7153static const char AttrDoc_PragmaClangTextSection[] = R"reST()reST";
7154
7155static const char AttrDoc_PreferredName[] = R"reST(The ``preferred_name`` attribute can be applied to a class template, and
7156specifies a preferred way of naming a specialization of the template. The
7157preferred name will be used whenever the corresponding template specialization
7158would otherwise be printed in a diagnostic or similar context.
7159
7160The preferred name must be a typedef or type alias declaration that refers to a
7161specialization of the class template (not including any type qualifiers). In
7162general this requires the template to be declared at least twice. For example:
7163
7164.. code-block:: c++
7165
7166 template<typename T> struct basic_string;
7167 using string = basic_string<char>;
7168 using wstring = basic_string<wchar_t>;
7169 template<typename T> struct [[clang::preferred_name(string),
7170 clang::preferred_name(wstring)]] basic_string {
7171 // ...
7172 };
7173
7174
7175Note that the ``preferred_name`` attribute will be ignored when the compiler
7176writes a C++20 Module interface now. This is due to a compiler issue
7177(https://github.com/llvm/llvm-project/issues/56490) that blocks users to modularize
7178declarations with `preferred_name`. This is intended to be fixed in the future.)reST";
7179
7180static const char AttrDoc_PreferredType[] = R"reST(This attribute allows adjusting the type of a bit-field in debug information.
7181This can be helpful when a bit-field is intended to store an enumeration value,
7182but has to be specified as having the enumeration's underlying type in order to
7183facilitate compiler optimizations or bit-field packing behavior. Normally, the
7184underlying type is what is emitted in debug information, which can make it hard
7185for debuggers to know to map a bit-field's value back to a particular enumeration.
7186
7187.. code-block:: c++
7188
7189 enum Colors { Red, Green, Blue };
7190
7191 struct S {
7192 [[clang::preferred_type(Colors)]] unsigned ColorVal : 2;
7193 [[clang::preferred_type(bool)]] unsigned UseAlternateColorSpace : 1;
7194 } s = { Green, false };
7195
7196Without the attribute, a debugger is likely to display the value ``1`` for ``ColorVal``
7197and ``0`` for ``UseAlternateColorSpace``. With the attribute, the debugger may now
7198display ``Green`` and ``false`` instead.
7199
7200This can be used to map a bit-field to an arbitrary type that isn't integral
7201or an enumeration type. For example:
7202
7203.. code-block:: c++
7204
7205 struct A {
7206 short a1;
7207 short a2;
7208 };
7209
7210 struct B {
7211 [[clang::preferred_type(A)]] unsigned b1 : 32 = 0x000F'000C;
7212 };
7213
7214will associate the type ``A`` with the ``b1`` bit-field and is intended to display
7215something like this in the debugger:
7216
7217.. code-block:: text
7218
7219 Process 2755547 stopped
7220 * thread #1, name = 'test-preferred-', stop reason = step in
7221 frame #0: 0x0000555555555148 test-preferred-type`main at test.cxx:13:14
7222 10 int main()
7223 11 {
7224 12 B b;
7225 -> 13 return b.b1;
7226 14 }
7227 (lldb) v -T
7228 (B) b = {
7229 (A:32) b1 = {
7230 (short) a1 = 12
7231 (short) a2 = 15
7232 }
7233 }
7234
7235Note that debuggers may not be able to handle more complex mappings, and so
7236this usage is debugger-dependent.)reST";
7237
7238static const char AttrDoc_PreserveAll[] = R"reST(On X86-64 and AArch64 targets, this attribute changes the calling convention of
7239a function. The ``preserve_all`` calling convention attempts to make the code
7240in the caller even less intrusive than the ``preserve_most`` calling convention.
7241This calling convention also behaves identical to the ``C`` calling convention
7242on how arguments and return values are passed, but it uses a different set of
7243caller/callee-saved registers. This removes the burden of saving and
7244recovering a large register set before and after the call in the caller. If
7245the arguments are passed in callee-saved registers, then they will be
7246preserved by the callee across the call. This doesn't apply for values
7247returned in callee-saved registers.
7248
7249- On X86-64 the callee preserves all general purpose registers, except for
7250 R11. R11 can be used as a scratch register. Furthermore it also preserves
7251 all floating-point registers (XMMs/YMMs).
7252
7253- On AArch64 the callee preserve all general purpose registers, except X0-X8 and
7254 X16-X18. Furthermore it also preserves lower 128 bits of V8-V31 SIMD - floating
7255 point registers.
7256
7257The idea behind this convention is to support calls to runtime functions
7258that don't need to call out to any other functions.
7259
7260This calling convention, like the ``preserve_most`` calling convention, will be
7261used by a future version of the Objective-C runtime and should be considered
7262experimental at this time.)reST";
7263
7264static const char AttrDoc_PreserveMost[] = R"reST(On X86-64 and AArch64 targets, this attribute changes the calling convention of
7265a function. The ``preserve_most`` calling convention attempts to make the code
7266in the caller as unintrusive as possible. This convention behaves identically
7267to the ``C`` calling convention on how arguments and return values are passed,
7268but it uses a different set of caller/callee-saved registers. This alleviates
7269the burden of saving and recovering a large register set before and after the
7270call in the caller. If the arguments are passed in callee-saved registers,
7271then they will be preserved by the callee across the call. This doesn't
7272apply for values returned in callee-saved registers.
7273
7274- On X86-64 the callee preserves all general purpose registers, except for
7275 R11. R11 can be used as a scratch register. Floating-point registers
7276 (XMMs/YMMs) are not preserved and need to be saved by the caller.
7277
7278- On AArch64 the callee preserve all general purpose registers, except X0-X8 and
7279 X16-X18.
7280
7281The idea behind this convention is to support calls to runtime functions
7282that have a hot path and a cold path. The hot path is usually a small piece
7283of code that doesn't use many registers. The cold path might need to call out to
7284another function and therefore only needs to preserve the caller-saved
7285registers, which haven't already been saved by the caller. The
7286``preserve_most`` calling convention is very similar to the ``cold`` calling
7287convention in terms of caller/callee-saved registers, but they are used for
7288different types of function calls. ``coldcc`` is for function calls that are
7289rarely executed, whereas ``preserve_most`` function calls are intended to be
7290on the hot path and definitely executed a lot. Furthermore ``preserve_most``
7291doesn't prevent the inliner from inlining the function call.
7292
7293This calling convention will be used by a future version of the Objective-C
7294runtime and should therefore still be considered experimental at this time.
7295Although this convention was created to optimize certain runtime calls to
7296the Objective-C runtime, it is not limited to this runtime and might be used
7297by other runtimes in the future too. The current implementation only
7298supports X86-64 and AArch64, but the intention is to support more architectures
7299in the future.)reST";
7300
7301static const char AttrDoc_PreserveNone[] = R"reST(On X86-64 and AArch64 targets, this attribute changes the calling convention of a function.
7302The ``preserve_none`` calling convention tries to preserve as few general
7303registers as possible. So all general registers are caller saved registers. It
7304also uses more general registers to pass arguments. This attribute doesn't
7305impact floating-point registers. ``preserve_none``'s ABI is still unstable, and
7306may be changed in the future.
7307
7308- On X86-64, only RSP and RBP are preserved by the callee.
7309 Registers R12, R13, R14, R15, RDI, RSI, RDX, RCX, R8, R9, R11, and RAX now can
7310 be used to pass function arguments. Floating-point registers (XMMs/YMMs) still
7311 follow the C calling convention.
7312- On AArch64, only LR and FP are preserved by the callee.
7313 Registers X20-X28, X0-X7, and X9-X14 are used to pass function arguments.
7314 X8, X16-X19, SIMD and floating-point registers follow the AAPCS calling
7315 convention. X15 is not available for argument passing on Windows, but is
7316 used to pass arguments on other platforms.)reST";
7317
7318static const char AttrDoc_PtGuardedBy[] = R"reST(No documentation.)reST";
7319
7320static const char AttrDoc_PtGuardedVar[] = R"reST(No documentation.)reST";
7321
7322static const char AttrDoc_Ptr32[] = R"reST(The ``__ptr32`` qualifier represents a native pointer on a 32-bit system. On a
732364-bit system, a pointer with ``__ptr32`` is extended to a 64-bit pointer. The
7324``__sptr`` and ``__uptr`` qualifiers can be used to specify whether the pointer
7325is sign extended or zero extended. This qualifier is enabled under
7326``-fms-extensions``.)reST";
7327
7328static const char AttrDoc_Ptr64[] = R"reST(The ``__ptr64`` qualifier represents a native pointer on a 64-bit system. On a
732932-bit system, a ``__ptr64`` pointer is truncated to a 32-bit pointer. This
7330qualifier is enabled under ``-fms-extensions``.)reST";
7331
7332static const char AttrDoc_Pure[] = R"reST(No documentation.)reST";
7333
7334static const char AttrDoc_RISCVInterrupt[] = R"reST(Clang supports the GNU style ``__attribute__((interrupt))`` attribute on RISCV
7335targets. This attribute may be attached to a function definition and instructs
7336the backend to generate appropriate function entry/exit code so that it can be
7337used directly as an interrupt service routine.
7338
7339Permissible values for this parameter are ``machine``, ``supervisor``,
7340``rnmi``, ``qci-nest``, ``qci-nonest``, ``SiFive-CLIC-preemptible``, and
7341``SiFive-CLIC-stack-swap``. If there is no parameter, then it defaults to
7342``machine``.
7343
7344The ``rnmi`` value is used for resumable non-maskable interrupts. It requires the
7345standard Smrnmi extension.
7346
7347The ``qci-nest`` and ``qci-nonest`` values require Qualcomm's Xqciint extension
7348and are used for Machine-mode Interrupts and Machine-mode Non-maskable
7349interrupts. These use the following instructions from Xqciint to save and
7350restore interrupt state to the stack -- the ``qci-nest`` value will use
7351``qc.c.mienter.nest`` and the ``qci-nonest`` value will use ``qc.c.mienter`` to
7352begin the interrupt handler. Both of these will use ``qc.c.mileaveret`` to
7353restore the state and return to the previous context.
7354
7355The ``SiFive-CLIC-preemptible`` and ``SiFive-CLIC-stack-swap`` values are used
7356for machine-mode interrupts. For ``SiFive-CLIC-preemptible`` interrupts, the
7357values of ``mcause`` and ``mepc`` are saved onto the stack, and interrupts are
7358re-enabled. For ``SiFive-CLIC-stack-swap`` interrupts, the stack pointer is
7359swapped with ``mscratch`` before its first use and after its last use.
7360
7361The SiFive CLIC values may be combined with each other and with the ``machine``
7362attribute value. Any other combination of different values is not allowed.
7363
7364Repeated interrupt attribute on the same declaration will cause a warning
7365to be emitted. In case of repeated declarations, the last one prevails.
7366
7367Refer to:
7368https://gcc.gnu.org/onlinedocs/gcc/RISC-V-Function-Attributes.html
7369https://riscv.org/specifications/privileged-isa/
7370The RISC-V Instruction Set Manual Volume II: Privileged Architecture
7371Version 1.10.
7372https://github.com/quic/riscv-unified-db/releases/tag/Xqci-0.13.0
7373https://sifive.cdn.prismic.io/sifive/d1984d2b-c9b9-4c91-8de0-d68a5e64fa0f_sifive-interrupt-cookbook-v1p2.pdf)reST";
7374
7375static const char AttrDoc_RISCVVLSCC[] = R"reST(The ``riscv_vls_cc`` attribute can be applied to a function. Functions
7376declared with this attribute will utilize the standard fixed-length vector
7377calling convention variant instead of the default calling convention defined by
7378the ABI. This variant aims to pass fixed-length vectors via vector registers,
7379if possible, rather than through general-purpose registers.)reST";
7380
7381static const char AttrDoc_RISCVVectorCC[] = R"reST(The ``riscv_vector_cc`` attribute can be applied to a function. It preserves 15
7382registers namely, v1-v7 and v24-v31 as callee-saved. Callers thus don't need
7383to save these registers before function calls, and callees only need to save
7384them if they use them.)reST";
7385
7386static const char AttrDoc_RandomizeLayout[] = R"reST(The attribute ``randomize_layout``, when attached to a C structure, selects it
7387for structure layout field randomization; a compile-time hardening technique. A
7388"seed" value, is specified via the ``-frandomize-layout-seed=`` command line flag.
7389For example:
7390
7391.. code-block:: bash
7392
7393 SEED=`od -A n -t x8 -N 32 /dev/urandom | tr -d ' \n'`
7394 make ... CFLAGS="-frandomize-layout-seed=$SEED" ...
7395
7396You can also supply the seed in a file with ``-frandomize-layout-seed-file=``.
7397For example:
7398
7399.. code-block:: bash
7400
7401 od -A n -t x8 -N 32 /dev/urandom | tr -d ' \n' > /tmp/seed_file.txt
7402 make ... CFLAGS="-frandomize-layout-seed-file=/tmp/seed_file.txt" ...
7403
7404The randomization is deterministic based for a given seed, so the entire
7405program should be compiled with the same seed, but keep the seed safe
7406otherwise.
7407
7408The attribute ``no_randomize_layout``, when attached to a C structure,
7409instructs the compiler that this structure should not have its field layout
7410randomized.)reST";
7411
7412static const char AttrDoc_ReadOnlyPlacement[] = R"reST(This attribute is attached to a structure, class or union declaration.
7413 When attached to a record declaration/definition, it checks if all instances
7414 of this type can be placed in the read-only data segment of the program. If it
7415 finds an instance that can not be placed in a read-only segment, the compiler
7416 emits a warning at the source location where the type was used.
7417
7418 Examples:
7419 * ``struct __attribute__((enforce_read_only_placement)) Foo;``
7420 * ``struct __attribute__((enforce_read_only_placement)) Bar { ... };``
7421
7422 Both ``Foo`` and ``Bar`` types have the ``enforce_read_only_placement`` attribute.
7423
7424 The goal of introducing this attribute is to assist developers with writing secure
7425 code. A ``const``-qualified global is generally placed in the read-only section
7426 of the memory that has additional run time protection from malicious writes. By
7427 attaching this attribute to a declaration, the developer can express the intent
7428 to place all instances of the annotated type in the read-only program memory.
7429
7430 Note 1: The attribute doesn't guarantee that the object will be placed in the
7431 read-only data segment as it does not instruct the compiler to ensure such
7432 a placement. It emits a warning if something in the code can be proven to prevent
7433 an instance from being placed in the read-only data segment.
7434
7435 Note 2: Currently, clang only checks if all global declarations of a given type 'T'
7436 are ``const``-qualified. The following conditions would also prevent the data to be
7437 put into read only segment, but the corresponding warnings are not yet implemented.
7438
7439 1. An instance of type ``T`` is allocated on the heap/stack.
7440 2. Type ``T`` defines/inherits a mutable field.
7441 3. Type ``T`` defines/inherits non-constexpr constructor(s) for initialization.
7442 4. A field of type ``T`` is defined by type ``Q``, which does not bear the
7443 ``enforce_read_only_placement`` attribute.
7444 5. A type ``Q`` inherits from type ``T`` and it does not have the
7445 ``enforce_read_only_placement`` attribute.)reST";
7446
7447static const char AttrDoc_ReentrantCapability[] = R"reST(No documentation.)reST";
7448
7449static const char AttrDoc_RegCall[] = R"reST(On x86 targets, this attribute changes the calling convention to
7450`__regcall`_ convention. This convention aims to pass as many arguments
7451as possible in registers. It also tries to utilize registers for the
7452return value whenever it is possible.
7453
7454.. _`__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";
7455
7456static const char AttrDoc_Reinitializes[] = R"reST(The ``reinitializes`` attribute can be applied to a non-static, non-const C++
7457member function to indicate that this member function reinitializes the entire
7458object to a known state, independent of the previous state of the object.
7459
7460This attribute can be interpreted by static analyzers that warn about uses of an
7461object that has been left in an indeterminate state by a move operation. If a
7462member function marked with the ``reinitializes`` attribute is called on a
7463moved-from object, the analyzer can conclude that the object is no longer in an
7464indeterminate state.
7465
7466A typical example where this attribute would be used is on functions that clear
7467a container class:
7468
7469.. code-block:: c++
7470
7471 template <class T>
7472 class Container {
7473 public:
7474 ...
7475 [[clang::reinitializes]] void Clear();
7476 ...
7477 };)reST";
7478
7479static const char AttrDoc_ReleaseCapability[] = R"reST(Marks a function as releasing a capability.)reST";
7480
7481static const char AttrDoc_ReleaseHandle[] = R"reST(If a function parameter is annotated with ``release_handle(tag)`` it is assumed to
7482close the handle. It is also assumed to require an open handle to work with. The
7483attribute requires a string literal argument to identify the handle being released.
7484
7485.. code-block:: c++
7486
7487 zx_status_t zx_handle_close(zx_handle_t handle [[clang::release_handle("tag")]]);)reST";
7488
7489static const char AttrDoc_ReqdWorkGroupSize[] = R"reST(No documentation.)reST";
7490
7491static const char AttrDoc_RequiresCapability[] = R"reST(No documentation.)reST";
7492
7493static const char AttrDoc_Restrict[] = R"reST(The ``malloc`` attribute has two forms with different functionality. The first
7494is when it is used without arguments, where it marks that a function acts like
7495a system memory allocation function, returning a pointer to allocated storage
7496that does not alias storage from any other object accessible to the caller.
7497
7498The second form is when ``malloc`` takes one or two arguments. The first
7499argument names a function that should be associated with this function as its
7500deallocation function. When this form is used, it enables the compiler to
7501diagnose when the incorrect deallocation function is used with this variable.
7502However the associated warning, spelled `-Wmismatched-dealloc` in GCC, is not
7503yet implemented in clang.)reST";
7504
7505static const char AttrDoc_Retain[] = R"reST(This attribute, when attached to a function or variable definition, prevents
7506section garbage collection in the linker. It does not prevent other discard
7507mechanisms, such as archive member selection, and COMDAT group resolution.
7508
7509If the compiler does not emit the definition, e.g. because it was not used in
7510the translation unit or the compiler was able to eliminate all of the uses,
7511this attribute has no effect. This attribute is typically combined with the
7512``used`` attribute to force the definition to be emitted and preserved into the
7513final linked image.
7514
7515This attribute is only necessary on ELF targets; other targets prevent section
7516garbage collection by the linker when using the ``used`` attribute alone.
7517Using the attributes together should result in consistent behavior across
7518targets.
7519
7520This attribute requires the linker to support the ``SHF_GNU_RETAIN`` extension.
7521This support is available in GNU ``ld`` and ``gold`` as of binutils 2.36, as
7522well as in ``ld.lld`` 13.)reST";
7523
7524static const char AttrDoc_ReturnTypestate[] = R"reST(The ``return_typestate`` attribute can be applied to functions or parameters.
7525When applied to a function the attribute specifies the state of the returned
7526value. The function's body is checked to ensure that it always returns a value
7527in the specified state. On the caller side, values returned by the annotated
7528function are initialized to the given state.
7529
7530When applied to a function parameter it modifies the state of an argument after
7531a call to the function returns. The function's body is checked to ensure that
7532the parameter is in the expected state before returning.)reST";
7533
7534static const char AttrDoc_ReturnsNonNull[] = R"reST(The ``returns_nonnull`` attribute indicates that a particular function (or
7535Objective-C method) always returns a non-null pointer. For example, a
7536particular system ``malloc`` might be defined to terminate a process when
7537memory is not available rather than returning a null pointer:
7538
7539 .. code-block:: c
7540
7541 extern void * malloc (size_t size) __attribute__((returns_nonnull));
7542
7543The ``returns_nonnull`` attribute implies that returning a null pointer is
7544undefined behavior, which the optimizer may take advantage of. The ``_Nonnull``
7545type qualifier indicates that a pointer cannot be null in a more general manner
7546(because it is part of the type system) and does not imply undefined behavior,
7547making it more widely applicable)reST";
7548
7549static const char AttrDoc_ReturnsTwice[] = R"reST(No documentation.)reST";
7550
7551static const char AttrDoc_RootSignature[] = R"reST(The ``RootSignature`` attribute applies to HLSL entry functions to define what
7552types of resources are bound to the graphics pipeline.
7553
7554For details about the use and specification of Root Signatures please see here:
7555https://learn.microsoft.com/en-us/windows/win32/direct3d12/root-signatures)reST";
7556
7557static const char AttrDoc_SPtr[] = R"reST(The ``__sptr`` qualifier specifies that a 32-bit pointer should be sign
7558extended when converted to a 64-bit pointer.)reST";
7559
7560static const char AttrDoc_SYCLExternal[] = R"reST(The ``sycl_external`` attribute indicates that a function defined in another
7561translation unit may be called by a device function defined in the current
7562translation unit or, if defined in the current translation unit, the function
7563may be called by device functions defined in other translation units.
7564The attribute is intended for use in the implementation of the ``SYCL_EXTERNAL``
7565macro as specified in section 5.10.1, "SYCL functions and member functions
7566linkage", of the SYCL 2020 specification.
7567
7568The attribute only appertains to functions and only those that meet the
7569following requirements:
7570
7571* Has external linkage
7572* Is not explicitly defined as deleted (the function may be an explicitly
7573 defaulted function that is defined as deleted)
7574
7575The attribute shall be present on the first declaration of a function and
7576may optionally be present on subsequent declarations.
7577
7578When compiling for a SYCL device target that does not support the generic
7579address space, the function shall not specify a raw pointer or reference type
7580as the return type or as a parameter type.
7581See section 5.10, "SYCL offline linking", of the SYCL 2020 specification.
7582The following examples demonstrate the use of this attribute:
7583
7584.. code-block:: c++
7585
7586 [[clang::sycl_external]] void Foo(); // Ok.
7587
7588 [[clang::sycl_external]] void Bar() { /* ... */ } // Ok.
7589
7590 [[clang::sycl_external]] extern void Baz(); // Ok.
7591
7592 [[clang::sycl_external]] static void Quux() { /* ... */ } // error: Quux() has internal linkage.)reST";
7593
7594static const char AttrDoc_SYCLKernel[] = R"reST(The ``sycl_kernel`` attribute specifies that a function template will be used
7595to outline device code and to generate an OpenCL kernel.
7596Here is a code example of the SYCL program, which demonstrates the compiler's
7597outlining job:
7598
7599.. code-block:: c++
7600
7601 int foo(int x) { return ++x; }
7602
7603 using namespace cl::sycl;
7604 queue Q;
7605 buffer<int, 1> a(range<1>{1024});
7606 Q.submit([&](handler& cgh) {
7607 auto A = a.get_access<access::mode::write>(cgh);
7608 cgh.parallel_for<init_a>(range<1>{1024}, [=](id<1> index) {
7609 A[index] = index[0] + foo(42);
7610 });
7611 }
7612
7613A C++ function object passed to the ``parallel_for`` is called a "SYCL kernel".
7614A SYCL kernel defines the entry point to the "device part" of the code. The
7615compiler will emit all symbols accessible from a "kernel". In this code
7616example, the compiler will emit "foo" function. More details about the
7617compilation of functions for the device part can be found in the SYCL 1.2.1
7618specification Section 6.4.
7619To show to the compiler entry point to the "device part" of the code, the SYCL
7620runtime can use the ``sycl_kernel`` attribute in the following way:
7621
7622.. code-block:: c++
7623
7624 namespace cl {
7625 namespace sycl {
7626 class handler {
7627 template <typename KernelName, typename KernelType/*, ...*/>
7628 __attribute__((sycl_kernel)) void sycl_kernel_function(KernelType KernelFuncObj) {
7629 // ...
7630 KernelFuncObj();
7631 }
7632
7633 template <typename KernelName, typename KernelType, int Dims>
7634 void parallel_for(range<Dims> NumWorkItems, KernelType KernelFunc) {
7635 #ifdef __SYCL_DEVICE_ONLY__
7636 sycl_kernel_function<KernelName, KernelType, Dims>(KernelFunc);
7637 #else
7638 // Host implementation
7639 #endif
7640 }
7641 };
7642 } // namespace sycl
7643 } // namespace cl
7644
7645The compiler will also generate an OpenCL kernel using the function marked with
7646the ``sycl_kernel`` attribute.
7647Here is the list of SYCL device compiler expectations with regard to the
7648function marked with the ``sycl_kernel`` attribute:
7649
7650- The function must be a template with at least two type template parameters.
7651 The compiler generates an OpenCL kernel and uses the first template parameter
7652 as a unique name for the generated OpenCL kernel. The host application uses
7653 this unique name to invoke the OpenCL kernel generated for the SYCL kernel
7654 specialized by this name and second template parameter ``KernelType`` (which
7655 might be an unnamed function object type).
7656- The function must have at least one parameter. The first parameter is
7657 required to be a function object type (named or unnamed i.e. lambda). The
7658 compiler uses function object type fields to generate OpenCL kernel
7659 parameters.
7660- The function must return void. The compiler reuses the body of marked functions to
7661 generate the OpenCL kernel body, and the OpenCL kernel must return ``void``.
7662
7663The SYCL kernel in the previous code sample meets these expectations.)reST";
7664
7665static const char AttrDoc_SYCLKernelEntryPoint[] = R"reST(The ``sycl_kernel_entry_point`` attribute facilitates the launch of a SYCL
7666kernel and the generation of an offload kernel entry point, sometimes called
7667a SYCL kernel caller function, suitable for invoking a SYCL kernel on an
7668offload device. The attribute is intended for use in the implementation of
7669SYCL kernel invocation functions like the ``single_task`` and ``parallel_for``
7670member functions of the ``sycl::handler`` class specified in section 4.9.4,
7671"Command group ``handler`` class", of the SYCL 2020 specification.
7672
7673The attribute requires a single type argument that meets the requirements for
7674a SYCL kernel name as described in section 5.2, "Naming of kernels", of the
7675SYCL 2020 specification. A unique kernel name type is required for each
7676function declared with the attribute. The attribute may not first appear on a
7677declaration that follows a definition of the function.
7678
7679The attribute only appertains to functions and only those that meet the
7680following requirements.
7681
7682* Has a non-deduced ``void`` return type.
7683* Is not a constructor or destructor.
7684* Is not a non-static member function with an explicit object parameter.
7685* Is not a C variadic function.
7686* Is not a coroutine.
7687* Is not defined as deleted or as defaulted.
7688* Is not defined with a function try block.
7689* Is not declared with the ``constexpr`` or ``consteval`` specifiers.
7690* Is not declared with the ``[[noreturn]]`` attribute.
7691
7692Use in the implementation of a SYCL kernel invocation function might look as
7693follows.
7694
7695.. code-block:: c++
7696
7697 namespace sycl {
7698 class handler {
7699 template<typename KernelName, typename... Ts>
7700 void sycl_kernel_launch(const char* kernelSymbol, Ts&&... kernelArgs) {
7701 // This code will run on the host and is responsible for calling functions
7702 // appropriate for the desired offload backend (OpenCL, CUDA, HIP,
7703 // Level Zero, etc...) to copy the kernel arguments denoted by kernelArgs
7704 // to a device and to schedule an invocation of the offload kernel entry
7705 // point denoted by kernelSymbol with the copied arguments.
7706 }
7707
7708 template<typename KernelName, typename KernelType>
7709 [[ clang::sycl_kernel_entry_point(KernelName) ]]
7710 void kernel_entry_point(KernelType kernelFunc) {
7711 // This code will run on the device. The call to kernelFunc() invokes
7712 // the SYCL kernel.
7713 kernelFunc();
7714 }
7715
7716 public:
7717 template<typename KernelName, typename KernelType>
7718 void single_task(const KernelType& kernelFunc) {
7719 // This code will run on the host. kernel_entry_point() is called to
7720 // trigger generation of an offload kernel entry point and to schedule
7721 // an invocation of it on a device with kernelFunc (a SYCL kernel object)
7722 // passed as a kernel argument. This call will result in an implicit call
7723 // to sycl_kernel_launch() with the symbol name for the generated offload
7724 // kernel entry point passed as the first function argument followed by
7725 // kernelFunc.
7726 kernel_entry_point<KernelName>(kernelFunc);
7727 }
7728 };
7729 } // namespace sycl
7730
7731A SYCL kernel object is a callable object of class type that is constructed on
7732a host, often via a lambda expression, and then passed to a SYCL kernel
7733invocation function to be executed on an offload device. The ``kernelFunc``
7734parameters in the example code above correspond to SYCL kernel objects.
7735
7736A SYCL kernel object type is required to satisfy the device copyability
7737requirements specified in section 3.13.1, "Device copyable", of the SYCL 2020
7738specification. Additionally, any data members of the kernel object type are
7739required to satisfy section 4.12.4, "Rules for parameter passing to kernels".
7740For most types, these rules require that the type is trivially copyable.
7741However, the SYCL specification mandates that certain special SYCL types, such
7742as ``sycl::accessor`` and ``sycl::stream``, be device copyable even if they are
7743not trivially copyable. These types require special handling because they cannot
7744necessarily be copied to device memory as if by ``memcpy()``.
7745
7746The SYCL kernel object and its data members constitute the parameters of an
7747offload kernel. An offload kernel consists of an offload entry point function
7748and the set of all functions and variables that are directly or indirectly used
7749by the entry point function.
7750
7751A SYCL kernel invocation function is responsible for performing the following
7752tasks (likely with the help of an offload backend like OpenCL):
7753
7754#. Identifying the offload kernel entry point to be used for the SYCL kernel.
7755
7756#. Validating that the SYCL kernel object type and its data members meet the
7757 SYCL device copyability and kernel parameter requirements noted above.
7758
7759#. Copying the SYCL kernel object and any other kernel arguments to device
7760 memory including any special handling required for SYCL special types.
7761
7762#. Initiating execution of the offload kernel entry point.
7763
7764The offload kernel entry point for a SYCL kernel performs the following tasks:
7765
7766#. Calling the ``operator()`` member function of the SYCL kernel object.
7767
7768The ``sycl_kernel_entry_point`` attribute facilitates or automates these tasks
7769by providing generation of an offload kernel entry point with a unique symbol
7770name, type checking of kernel argument requirements, and initiation of kernel
7771execution via synthesized calls to a ``sycl_kernel_launch`` template.
7772
7773A function declared with the ``sycl_kernel_entry_point`` attribute specifies
7774the parameters and body of an offload entry point function. Consider the
7775following call to the ``single_task()`` SYCL kernel invocation function assuming
7776an implementation similar to the one shown above.
7777
7778.. code-block:: c++
7779
7780 struct S { int i; };
7781 void f(sycl::handler &handler, sycl::stream &sout, S s) {
7782 handler.single_task<struct KN>([=] {
7783 sout << "The value of s.i is " << s.i << "\n";
7784 });
7785 }
7786
7787The SYCL kernel object is the result of the lambda expression. The call to
7788``kernel_entry_point()`` via the call to ``single_task()`` triggers the
7789generation of an offload kernel entry point function that looks approximately
7790as follows.
7791
7792.. code-block:: c++
7793
7794 void sycl-kernel-caller-for-KN(kernel-type kernelFunc) {
7795 kernelFunc();
7796 }
7797
7798There are a few items worthy of note:
7799
7800#. ``sycl-kernel-caller-for-KN`` is an exposition only name; the actual name
7801 generated for an entry point is an implementation detail and subject to
7802 change. However, the name will incorporate the SYCL kernel name, ``KN``,
7803 that was passed as the ``KernelName`` template parameter to
7804 ``single_task()`` and eventually provided as the argument to the
7805 ``sycl_kernel_entry_point`` attribute in order to ensure that a unique
7806 name is generated for each entry point. There is a one-to-one correspondence
7807 between SYCL kernel names and offload kernel entry points.
7808
7809#. The SYCL kernel is a lambda closure type and therefore has no name;
7810 ``kernel-type`` is substituted above and corresponds to the ``KernelType``
7811 template parameter deduced in the call to ``single_task()``.
7812
7813#. The parameter and the call to ``kernelFunc()`` in the function body
7814 correspond to the definition of ``kernel_entry_point()`` as called by
7815 ``single_task()``.
7816
7817#. The parameter is type checked for conformance with the SYCL device
7818 copyability and kernel parameter requirements.
7819
7820Within ``single_task()``, the call to ``kernel_entry_point()`` is effectively
7821replaced with a synthesized call to a ''sycl_kernel_launch`` template that
7822looks approximately as follows.
7823
7824.. code-block:: c++
7825
7826 sycl_kernel_launch<KN>("sycl-kernel-caller-for-KN", kernelFunc);
7827
7828There are a few items worthy of note:
7829
7830#. Lookup for the ``sycl_kernel_launch`` template is performed as if from the
7831 body of the (possibly instantiated) definition of ``kernel_entry_point()``.
7832 If name lookup or overload resolution fails, the program is ill-formed.
7833 If the selected overload is a non-static member function, then ``this`` is
7834 passed as the implicit object parameter.
7835
7836#. Function arguments passed to ``sycl_kernel_launch()`` are passed
7837 as if by ``std::move(x)``.
7838
7839#. The ``sycl_kernel_launch`` template is expected to be provided by the SYCL
7840 library implementation. It is responsible for copying the kernel arguments
7841 to device memory and for scheduling execution of the generated offload
7842 kernel entry point identified by the symbol name passed as the first
7843 function argument. ``sycl-kernel-caller-for-KN`` is substituted above for
7844 the actual symbol name that would be generated for the offload kernel entry
7845 point.
7846
7847It is not necessary for a function declared with the ``sycl_kernel_entry_point``
7848attribute to be called for the offload kernel entry point to be emitted. For
7849inline functions and function templates, any ODR-use will suffice. For other
7850functions, an ODR-use is not required; the offload kernel entry point will be
7851emitted if the function is defined. In any case, a call to the function is
7852required for the synthesized call to ``sycl_kernel_launch()`` to occur.
7853
7854A function declared with the ``sycl_kernel_entry_point`` attribute may include
7855an exception specification. If a non-throwing exception specification is
7856present, an exception propagating from the implicit call to the
7857``sycl_kernel_launch`` template will result in a call to ``std::terminate()``.
7858Otherwise, such an exception will propagate normally.
7859
7860Functions declared with the ``sycl_kernel_entry_point`` attribute are not
7861limited to the simple example shown above. They may have additional template
7862parameters, declare additional function parameters, and have complex control
7863flow in the function body. The function must abide by the language feature
7864restrictions described in section 5.4, "Language restrictions for device
7865functions" in the SYCL 2020 specification. If the function is a non-static
7866member function, ``this`` shall not be used in a potentially evaluated
7867expression.)reST";
7868
7869static const char AttrDoc_SYCLSpecialClass[] = R"reST(SYCL defines some special classes (accessor, sampler, and stream) which require
7870specific handling during the generation of the SPIR entry point.
7871The ``__attribute__((sycl_special_class))`` attribute is used in SYCL
7872headers to indicate that a class or a struct needs a specific handling when
7873it is passed from host to device.
7874Special classes will have a mandatory ``__init`` method and an optional
7875``__finalize`` method (the ``__finalize`` method is used only with the
7876``stream`` type). Kernel parameters types are extract from the ``__init`` method
7877parameters. The kernel function arguments list is derived from the
7878arguments of the ``__init`` method. The arguments of the ``__init`` method are
7879copied into the kernel function argument list and the ``__init`` and
7880``__finalize`` methods are called at the beginning and the end of the kernel,
7881respectively.
7882The ``__init`` and ``__finalize`` methods must be defined inside the
7883special class.
7884Please note that this is an attribute that is used as an internal
7885implementation detail and not intended to be used by external users.
7886
7887The syntax of the attribute is as follows:
7888
7889.. code-block:: text
7890
7891 class __attribute__((sycl_special_class)) accessor {};
7892 class [[clang::sycl_special_class]] accessor {};
7893
7894This is a code example that illustrates the use of the attribute:
7895
7896.. code-block:: c++
7897
7898 class __attribute__((sycl_special_class)) SpecialType {
7899 int F1;
7900 int F2;
7901 void __init(int f1) {
7902 F1 = f1;
7903 F2 = f1;
7904 }
7905 void __finalize() {}
7906 public:
7907 SpecialType() = default;
7908 int getF2() const { return F2; }
7909 };
7910
7911 int main () {
7912 SpecialType T;
7913 cgh.single_task([=] {
7914 T.getF2();
7915 });
7916 }
7917
7918This would trigger the following kernel entry point in the AST:
7919
7920.. code-block:: c++
7921
7922 void __sycl_kernel(int f1) {
7923 SpecialType T;
7924 T.__init(f1);
7925 ...
7926 T.__finalize()
7927 })reST";
7928
7929static const char AttrDoc_ScopedLockable[] = R"reST(No documentation.)reST";
7930
7931static const char AttrDoc_Section[] = R"reST(The ``section`` attribute allows you to specify a specific section a
7932global variable or function should be in after translation.)reST";
7933
7934static const char AttrDoc_SelectAny[] = R"reST(This attribute appertains to a global symbol, causing it to have a weak
7935definition (
7936`linkonce <https://llvm.org/docs/LangRef.html#linkage-types>`_
7937), allowing the linker to select any definition.
7938
7939For more information see
7940`gcc documentation <https://gcc.gnu.org/onlinedocs/gcc-7.2.0/gcc/Microsoft-Windows-Variable-Attributes.html>`_
7941or `msvc documentation <https://docs.microsoft.com/pl-pl/cpp/cpp/selectany>`_.)reST";
7942
7943static const char AttrDoc_Sentinel[] = R"reST(The ``sentinel`` attribute can be applied to variadic functions and pointers to
7944variadic functions, to diagnose each function call that does not pass a
7945sentinel value (a null pointer constant) as the last argument to the function
7946call. The attribute accepts two optional arguments: the first argument is the
7947position of the expected sentinel value, starting from the last parameter. The
7948second argument describes whether the last fixed parameter is treated as a
7949valid sentinel value when set to '1'.
7950All arguments described above default to '0' when elided.
7951The attribute is also supported with blocks and in Objective-C.
7952
7953.. code-block:: c
7954
7955 void foo(const char*, ...) __attribute__((sentinel));
7956 void bar(int, ...) __attribute__((sentinel(1)));
7957 void baz(const char*, const char*, ...) __attribute__((sentinel(0, 1)));
7958
7959 void example() {
7960 foo("Example", (void*)0);
7961 foo("Another", "example", NULL);
7962 foo("Missing", "sentinel"); // Not OK
7963
7964 bar(1, 2, NULL, 3); // OK: sentinel value at the 2nd to last position
7965 bar(1, 2, 3, nullptr, 4); // OK: `nullptr` is valid in C23
7966 bar(1, 2, 3, 4, NULL); // Not OK
7967
7968 baz("Test", "with", "multiple", "args", NULL);
7969 baz("One", NULL); // OK: last fixed parameter is a valid sentinel
7970
7971 void (*ptr) (int arg, ...) __attribute__ ((__sentinel__));
7972 ptr(1, 2, 3, NULL);
7973 }
7974
7975.. code-block:: c++
7976
7977 struct Ty {
7978 int value;
7979
7980 template<typename T>
7981 auto&& foo(T&& val, ...) __attribute__((sentinel(1))) {
7982 return std::forward<T>(val);
7983 }
7984
7985 template<class Self>
7986 auto&& bar(this Self&& self, ...) __attribute__((sentinel(1))) {
7987 return std::forward<Self>(self).value;
7988 }
7989 };
7990
7991 void example2() {
7992 auto sty = Ty{};
7993 sty.foo(1, nullptr, 3);
7994 sty.bar(1, nullptr, 3);
7995
7996 auto lmbd = [](int a, ...) __attribute__((sentinel)) {};
7997 lmbd(1, 2, nullptr);
7998 })reST";
7999
8000static const char AttrDoc_SetTypestate[] = R"reST(Annotate methods that transition an object into a new state with
8001``__attribute__((set_typestate(new_state)))``. The new state must be
8002unconsumed, consumed, or unknown.)reST";
8003
8004static const char AttrDoc_SizedBy[] = R"reST(Clang supports the ``counted_by`` attribute on the flexible array member of a
8005structure in C. The argument for the attribute is the name of a field member
8006holding the count of elements in the flexible array. This information can be
8007used to improve the results of the array bound sanitizer and the
8008``__builtin_dynamic_object_size`` builtin. The ``count`` field member must be
8009within the same non-anonymous, enclosing struct as the flexible array member.
8010
8011This example specifies that the flexible array member ``array`` has the number
8012of elements allocated for it in ``count``:
8013
8014.. code-block:: c
8015
8016 struct bar;
8017
8018 struct foo {
8019 size_t count;
8020 char other;
8021 struct bar *array[] __attribute__((counted_by(count)));
8022 };
8023
8024This establishes a relationship between ``array`` and ``count``. Specifically,
8025``array`` must have at least ``count`` number of elements available. It's the
8026user's responsibility to ensure that this relationship is maintained through
8027changes to the structure.
8028
8029In the following example, the allocated array erroneously has fewer elements
8030than what's specified by ``p->count``. This would result in an out-of-bounds
8031access not being detected.
8032
8033.. code-block:: c
8034
8035 #define SIZE_INCR 42
8036
8037 struct foo *p;
8038
8039 void foo_alloc(size_t count) {
8040 p = malloc(MAX(sizeof(struct foo),
8041 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
8042 p->count = count + SIZE_INCR;
8043 }
8044
8045The next example updates ``p->count``, but breaks the relationship requirement
8046that ``p->array`` must have at least ``p->count`` number of elements available:
8047
8048.. code-block:: c
8049
8050 #define SIZE_INCR 42
8051
8052 struct foo *p;
8053
8054 void foo_alloc(size_t count) {
8055 p = malloc(MAX(sizeof(struct foo),
8056 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
8057 p->count = count;
8058 }
8059
8060 void use_foo(int index, int val) {
8061 p->count += SIZE_INCR + 1; /* 'count' is now larger than the number of elements of 'array'. */
8062 p->array[index] = val; /* The sanitizer can't properly check this access. */
8063 }
8064
8065In this example, an update to ``p->count`` maintains the relationship
8066requirement:
8067
8068.. code-block:: c
8069
8070 void use_foo(int index, int val) {
8071 if (p->count == 0)
8072 return;
8073 --p->count;
8074 p->array[index] = val;
8075 })reST";
8076
8077static const char AttrDoc_SizedByOrNull[] = R"reST(Clang supports the ``counted_by`` attribute on the flexible array member of a
8078structure in C. The argument for the attribute is the name of a field member
8079holding the count of elements in the flexible array. This information can be
8080used to improve the results of the array bound sanitizer and the
8081``__builtin_dynamic_object_size`` builtin. The ``count`` field member must be
8082within the same non-anonymous, enclosing struct as the flexible array member.
8083
8084This example specifies that the flexible array member ``array`` has the number
8085of elements allocated for it in ``count``:
8086
8087.. code-block:: c
8088
8089 struct bar;
8090
8091 struct foo {
8092 size_t count;
8093 char other;
8094 struct bar *array[] __attribute__((counted_by(count)));
8095 };
8096
8097This establishes a relationship between ``array`` and ``count``. Specifically,
8098``array`` must have at least ``count`` number of elements available. It's the
8099user's responsibility to ensure that this relationship is maintained through
8100changes to the structure.
8101
8102In the following example, the allocated array erroneously has fewer elements
8103than what's specified by ``p->count``. This would result in an out-of-bounds
8104access not being detected.
8105
8106.. code-block:: c
8107
8108 #define SIZE_INCR 42
8109
8110 struct foo *p;
8111
8112 void foo_alloc(size_t count) {
8113 p = malloc(MAX(sizeof(struct foo),
8114 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
8115 p->count = count + SIZE_INCR;
8116 }
8117
8118The next example updates ``p->count``, but breaks the relationship requirement
8119that ``p->array`` must have at least ``p->count`` number of elements available:
8120
8121.. code-block:: c
8122
8123 #define SIZE_INCR 42
8124
8125 struct foo *p;
8126
8127 void foo_alloc(size_t count) {
8128 p = malloc(MAX(sizeof(struct foo),
8129 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
8130 p->count = count;
8131 }
8132
8133 void use_foo(int index, int val) {
8134 p->count += SIZE_INCR + 1; /* 'count' is now larger than the number of elements of 'array'. */
8135 p->array[index] = val; /* The sanitizer can't properly check this access. */
8136 }
8137
8138In this example, an update to ``p->count`` maintains the relationship
8139requirement:
8140
8141.. code-block:: c
8142
8143 void use_foo(int index, int val) {
8144 if (p->count == 0)
8145 return;
8146 --p->count;
8147 p->array[index] = val;
8148 })reST";
8149
8150static const char AttrDoc_SpeculativeLoadHardening[] = R"reST(This attribute can be applied to a function declaration in order to indicate
8151 that `Speculative Load Hardening <https://llvm.org/docs/SpeculativeLoadHardening.html>`_
8152 should be enabled for the function body. This can also be applied to a method
8153 in Objective C. This attribute will take precedence over the command line flag in
8154 the case where `-mno-speculative-load-hardening <https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mspeculative-load-hardening>`_ is specified.
8155
8156 Speculative Load Hardening is a best-effort mitigation against
8157 information leak attacks that make use of control flow
8158 miss-speculation - specifically miss-speculation of whether a branch
8159 is taken or not. Typically vulnerabilities enabling such attacks are
8160 classified as "Spectre variant #1". Notably, this does not attempt to
8161 mitigate against miss-speculation of branch target, classified as
8162 "Spectre variant #2" vulnerabilities.
8163
8164 When inlining, the attribute is sticky. Inlining a function that
8165 carries this attribute will cause the caller to gain the
8166 attribute. This is intended to provide a maximally conservative model
8167 where the code in a function annotated with this attribute will always
8168 (even after inlining) end up hardened.)reST";
8169
8170static const char AttrDoc_StackProtectorIgnore[] = R"reST(The ``stack_protector_ignore`` attribute skips analysis of the given local
8171variable when determining if a function should use a stack protector.
8172
8173The ``-fstack-protector`` option uses a heuristic to only add stack protectors
8174to functions which contain variables or buffers over some size threshold. This
8175attribute overrides that heuristic for the attached variable, opting
8176them out. If this results in no variables or buffers remaining over the stack
8177protector threshold, then the function will no longer use a stack protector.)reST";
8178
8179static const char AttrDoc_StandaloneDebug[] = R"reST(The ``standalone_debug`` attribute causes debug info to be emitted for a record
8180type regardless of the debug info optimizations that are enabled with
8181-fno-standalone-debug. This attribute only has an effect when debug info
8182optimizations are enabled (e.g. with -fno-standalone-debug), and is C++-only.)reST";
8183
8184static const char AttrDoc_StdCall[] = R"reST(On 32-bit x86 targets, this attribute changes the calling convention of a
8185function to clear parameters off of the stack on return. This convention does
8186not support variadic calls or unprototyped functions in C, and has no effect on
8187x86_64 targets. This calling convention is used widely by the Windows API and
8188COM applications. See the documentation for `__stdcall`_ on MSDN.
8189
8190.. _`__stdcall`: http://msdn.microsoft.com/en-us/library/zxk0tw93.aspx)reST";
8191
8192static const char AttrDoc_StrictFP[] = R"reST()reST";
8193
8194static const char AttrDoc_StrictGuardStackCheck[] = R"reST(Clang supports the Microsoft style ``__declspec((strict_gs_check))`` attribute
8195which upgrades the stack protector check from ``-fstack-protector`` to
8196``-fstack-protector-strong``.
8197
8198For example, it upgrades the stack protector for the function ``foo`` to
8199``-fstack-protector-strong`` but function ``bar`` will still be built with the
8200stack protector with the ``-fstack-protector`` option.
8201
8202.. code-block:: c
8203
8204 __declspec((strict_gs_check))
8205 int foo(int x); // stack protection will be upgraded for foo.
8206
8207 int bar(int y); // bar can be built with the standard stack protector checks.)reST";
8208
8209static const char AttrDoc_Suppress[] = R"reST(The ``suppress`` attribute suppresses unwanted warnings coming from static
8210analysis tools such as the Clang Static Analyzer. The tool will not report
8211any issues in source code annotated with the attribute.
8212
8213The attribute cannot be used to suppress traditional Clang warnings, because
8214many such warnings are emitted before the attribute is fully parsed.
8215Consider using ``#pragma clang diagnostic`` to control such diagnostics,
8216as described in `Controlling Diagnostics via Pragmas
8217<https://clang.llvm.org/docs/UsersManual.html#controlling-diagnostics-via-pragmas>`_.
8218
8219The ``suppress`` attribute can be placed on an individual statement in order to
8220suppress warnings about undesirable behavior occurring at that statement:
8221
8222.. code-block:: c++
8223
8224 int foo() {
8225 int *x = nullptr;
8226 ...
8227 [[clang::suppress]]
8228 return *x; // null pointer dereference warning suppressed here
8229 }
8230
8231Putting the attribute on a compound statement suppresses all warnings in scope:
8232
8233.. code-block:: c++
8234
8235 int foo() {
8236 [[clang::suppress]] {
8237 int *x = nullptr;
8238 ...
8239 return *x; // warnings suppressed in the entire scope
8240 }
8241 }
8242
8243The attribute can also be placed on entire declarations of functions, classes,
8244variables, member variables, and so on, to suppress warnings related
8245to the declarations themselves. When used this way, the attribute additionally
8246suppresses all warnings in the lexical scope of the declaration:
8247
8248.. code-block:: c++
8249
8250 class [[clang::suppress]] C {
8251 int foo() {
8252 int *x = nullptr;
8253 ...
8254 return *x; // warnings suppressed in the entire class scope
8255 }
8256
8257 int bar();
8258 };
8259
8260 int C::bar() {
8261 int *x = nullptr;
8262 ...
8263 return *x; // warning NOT suppressed! - not lexically nested in 'class C{}'
8264 }
8265
8266Some static analysis warnings are accompanied by one or more notes, and the
8267line of code against which the warning is emitted isn't necessarily the best
8268for suppression purposes. In such cases the tools are allowed to implement
8269additional ways to suppress specific warnings based on the attribute attached
8270to a note location.
8271
8272For example, the Clang Static Analyzer suppresses memory leak warnings when
8273the suppression attribute is placed at the allocation site (highlited by
8274a "note: memory is allocated"), which may be different from the line of code
8275at which the program "loses track" of the pointer (where the warning
8276is ultimately emitted):
8277
8278.. code-block:: c
8279
8280 int bar1(bool coin_flip) {
8281 __attribute__((suppress))
8282 int *result = (int *)malloc(sizeof(int));
8283 if (coin_flip)
8284 return 1; // warning about this leak path is suppressed
8285
8286 return *result; // warning about this leak path is also suppressed
8287 }
8288
8289 int bar2(bool coin_flip) {
8290 int *result = (int *)malloc(sizeof(int));
8291 if (coin_flip)
8292 return 1; // leak warning on this path NOT suppressed
8293
8294 __attribute__((suppress))
8295 return *result; // leak warning is suppressed only on this path
8296 }
8297
8298
8299When written as ``[[gsl::suppress]]``, this attribute suppresses specific
8300clang-tidy diagnostics for rules of the `C++ Core Guidelines`_ in a portable
8301way. The attribute can be attached to declarations, statements, and at
8302namespace scope.
8303
8304.. code-block:: c++
8305
8306 [[gsl::suppress("Rh-public")]]
8307 void f_() {
8308 int *p;
8309 [[gsl::suppress("type")]] {
8310 p = reinterpret_cast<int*>(7);
8311 }
8312 }
8313 namespace N {
8314 [[clang::suppress("type", "bounds")]];
8315 ...
8316 }
8317
8318.. _`C++ Core Guidelines`: https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#inforce-enforcement)reST";
8319
8320static const char AttrDoc_SwiftAsync[] = R"reST(The ``swift_async`` attribute specifies if and how a particular function or
8321Objective-C method is imported into a swift async method. For instance:
8322
8323.. code-block:: objc
8324
8325 @interface MyClass : NSObject
8326 -(void)notActuallyAsync:(int)p1 withCompletionHandler:(void (^)())handler
8327 __attribute__((swift_async(none)));
8328
8329 -(void)actuallyAsync:(int)p1 callThisAsync:(void (^)())fun
8330 __attribute__((swift_async(swift_private, 1)));
8331 @end
8332
8333Here, ``notActuallyAsync:withCompletionHandler`` would have been imported as
8334``async`` (because it's last parameter's selector piece is
8335``withCompletionHandler``) if not for the ``swift_async(none)`` attribute.
8336Conversely, ``actuallyAsync:callThisAsync`` wouldn't have been imported as
8337``async`` if not for the ``swift_async`` attribute because it doesn't match the
8338naming convention.
8339
8340When using ``swift_async`` to enable importing, the first argument to the
8341attribute is either ``swift_private`` or ``not_swift_private`` to indicate
8342whether the function/method is private to the current framework, and the second
8343argument is the index of the completion handler parameter.)reST";
8344
8345static const char AttrDoc_SwiftAsyncCall[] = R"reST(The ``swiftasynccall`` attribute indicates that a function is
8346compatible with the low-level conventions of Swift async functions,
8347provided it declares the right formal arguments.
8348
8349In most respects, this is similar to the ``swiftcall`` attribute, except for
8350the following:
8351
8352- A parameter may be marked ``swift_async_context``, ``swift_context``
8353 or ``swift_indirect_result`` (with the same restrictions on parameter
8354 ordering as ``swiftcall``) but the parameter attribute
8355 ``swift_error_result`` is not permitted.
8356
8357- A ``swiftasynccall`` function must have return type ``void``.
8358
8359- Within a ``swiftasynccall`` function, a call to a ``swiftasynccall``
8360 function that is the immediate operand of a ``return`` statement is
8361 guaranteed to be performed as a tail call. This syntax is allowed even
8362 in C as an extension (a call to a void-returning function cannot be a
8363 return operand in standard C). If something in the calling function would
8364 semantically be performed after a guaranteed tail call, such as the
8365 non-trivial destruction of a local variable or temporary,
8366 then the program is ill-formed.
8367
8368Query for this attribute with ``__has_attribute(swiftasynccall)``. Query if
8369the target supports the calling convention with
8370``__has_extension(swiftasynccc)``.)reST";
8371
8372static const char AttrDoc_SwiftAsyncContext[] = R"reST(The ``swift_async_context`` attribute marks a parameter of a ``swiftasynccall``
8373function as having the special asynchronous context-parameter ABI treatment.
8374
8375If the function is not ``swiftasynccall``, this attribute only generates
8376extended frame information.
8377
8378A context parameter must have pointer or reference type.)reST";
8379
8380static const char AttrDoc_SwiftAsyncError[] = R"reST(The ``swift_async_error`` attribute specifies how an error state will be
8381represented in a swift async method. It's a bit analogous to the ``swift_error``
8382attribute for the generated async method. The ``swift_async_error`` attribute
8383can indicate a variety of different ways of representing an error.
8384
8385- ``__attribute__((swift_async_error(zero_argument, N)))``, specifies that the
8386 async method is considered to have failed if the Nth argument to the
8387 completion handler is zero.
8388
8389- ``__attribute__((swift_async_error(nonzero_argument, N)))``, specifies that
8390 the async method is considered to have failed if the Nth argument to the
8391 completion handler is non-zero.
8392
8393- ``__attribute__((swift_async_error(nonnull_error)))``, specifies that the
8394 async method is considered to have failed if the ``NSError *`` argument to the
8395 completion handler is non-null.
8396
8397- ``__attribute__((swift_async_error(none)))``, specifies that the async method
8398 cannot fail.
8399
8400
8401For instance:
8402
8403.. code-block:: objc
8404
8405 @interface MyClass : NSObject
8406 -(void)asyncMethod:(void (^)(char, int, float))handler
8407 __attribute__((swift_async(swift_private, 1)))
8408 __attribute__((swift_async_error(zero_argument, 2)));
8409 @end
8410
8411Here, the ``swift_async`` attribute specifies that ``handler`` is the completion
8412handler for this method, and the ``swift_async_error`` attribute specifies that
8413the ``int`` parameter is the one that represents the error.)reST";
8414
8415static const char AttrDoc_SwiftAsyncName[] = R"reST(The ``swift_async_name`` attribute provides the name of the ``async`` overload for
8416the given declaration in Swift. If this attribute is absent, the name is
8417transformed according to the algorithm built into the Swift compiler.
8418
8419The argument is a string literal that contains the Swift name of the function or
8420method. The name may be a compound Swift name. The function or method with such
8421an attribute must have more than zero parameters, as its last parameter is
8422assumed to be a callback that's eliminated in the Swift ``async`` name.
8423
8424 .. code-block:: objc
8425
8426 @interface URL
8427 + (void) loadContentsFrom:(URL *)url callback:(void (^)(NSData *))data __attribute__((__swift_async_name__("URL.loadContentsFrom(_:)")))
8428 @end)reST";
8429
8430static const char AttrDoc_SwiftAttr[] = R"reST(The ``swift_attr`` provides a Swift-specific annotation for the declaration
8431or type to which the attribute appertains to. It can be used on any declaration
8432or type in Clang. This kind of annotation is ignored by Clang as it doesn't have any
8433semantic meaning in languages supported by Clang. The Swift compiler can
8434interpret these annotations according to its own rules when importing C or
8435Objective-C declarations.)reST";
8436
8437static const char AttrDoc_SwiftBridge[] = R"reST(The ``swift_bridge`` attribute indicates that the declaration to which the
8438attribute appertains is bridged to the named Swift type.
8439
8440 .. code-block:: objc
8441
8442 __attribute__((__objc_root__))
8443 @interface Base
8444 - (instancetype)init;
8445 @end
8446
8447 __attribute__((__swift_bridge__("BridgedI")))
8448 @interface I : Base
8449 @end
8450
8451In this example, the Objective-C interface ``I`` will be made available to Swift
8452with the name ``BridgedI``. It would be possible for the compiler to refer to
8453``I`` still in order to bridge the type back to Objective-C.)reST";
8454
8455static const char AttrDoc_SwiftBridgedTypedef[] = R"reST(The ``swift_bridged_typedef`` attribute indicates that when the typedef to which
8456the attribute appertains is imported into Swift, it should refer to the bridged
8457Swift type (e.g. Swift's ``String``) rather than the Objective-C type as written
8458(e.g. ``NSString``).
8459
8460 .. code-block:: objc
8461
8462 @interface NSString;
8463 typedef NSString *AliasedString __attribute__((__swift_bridged_typedef__));
8464
8465 extern void acceptsAliasedString(AliasedString _Nonnull parameter);
8466
8467In this case, the function ``acceptsAliasedString`` will be imported into Swift
8468as a function which accepts a ``String`` type parameter.)reST";
8469
8470static const char AttrDoc_SwiftCall[] = R"reST(The ``swiftcall`` attribute indicates that a function should be called
8471using the Swift calling convention for a function or function pointer.
8472
8473The lowering for the Swift calling convention, as described by the Swift
8474ABI documentation, occurs in multiple phases. The first, "high-level"
8475phase breaks down the formal parameters and results into innately direct
8476and indirect components, adds implicit parameters for the generic
8477signature, and assigns the context and error ABI treatments to parameters
8478where applicable. The second phase breaks down the direct parameters
8479and results from the first phase and assigns them to registers or the
8480stack. The ``swiftcall`` convention only handles this second phase of
8481lowering; the C function type must accurately reflect the results
8482of the first phase, as follows:
8483
8484- Results classified as indirect by high-level lowering should be
8485 represented as parameters with the ``swift_indirect_result`` attribute.
8486
8487- Results classified as direct by high-level lowering should be represented
8488 as follows:
8489
8490 - First, remove any empty direct results.
8491
8492 - If there are no direct results, the C result type should be ``void``.
8493
8494 - If there is one direct result, the C result type should be a type with
8495 the exact layout of that result type.
8496
8497 - If there are a multiple direct results, the C result type should be
8498 a struct type with the exact layout of a tuple of those results.
8499
8500- Parameters classified as indirect by high-level lowering should be
8501 represented as parameters of pointer type.
8502
8503- Parameters classified as direct by high-level lowering should be
8504 omitted if they are empty types; otherwise, they should be represented
8505 as a parameter type with a layout exactly matching the layout of the
8506 Swift parameter type.
8507
8508- The context parameter, if present, should be represented as a trailing
8509 parameter with the ``swift_context`` attribute.
8510
8511- The error result parameter, if present, should be represented as a
8512 trailing parameter (always following a context parameter) with the
8513 ``swift_error_result`` attribute.
8514
8515``swiftcall`` does not support variadic arguments or unprototyped functions.
8516
8517The parameter ABI treatment attributes are aspects of the function type.
8518A function type which applies an ABI treatment attribute to a
8519parameter is a different type from an otherwise-identical function type
8520that does not. A single parameter may not have multiple ABI treatment
8521attributes.
8522
8523Support for this feature is target-dependent, although it should be
8524supported on every target that Swift supports. Query for this attribute
8525with ``__has_attribute(swiftcall)``. Query if the target supports the
8526calling convention with ``__has_extension(swiftcc)``. This implies
8527support for the ``swift_context``, ``swift_error_result``, and
8528``swift_indirect_result`` attributes.)reST";
8529
8530static const char AttrDoc_SwiftContext[] = R"reST(The ``swift_context`` attribute marks a parameter of a ``swiftcall``
8531or ``swiftasynccall`` function as having the special context-parameter
8532ABI treatment.
8533
8534This treatment generally passes the context value in a special register
8535which is normally callee-preserved.
8536
8537A ``swift_context`` parameter must either be the last parameter or must be
8538followed by a ``swift_error_result`` parameter (which itself must always be
8539the last parameter).
8540
8541A context parameter must have pointer or reference type.)reST";
8542
8543static const char AttrDoc_SwiftError[] = R"reST(The ``swift_error`` attribute controls whether a particular function (or
8544Objective-C method) is imported into Swift as a throwing function, and if so,
8545which dynamic convention it uses.
8546
8547All of these conventions except ``none`` require the function to have an error
8548parameter. Currently, the error parameter is always the last parameter of type
8549``NSError**`` or ``CFErrorRef*``. Swift will remove the error parameter from
8550the imported API. When calling the API, Swift will always pass a valid address
8551initialized to a null pointer.
8552
8553* ``swift_error(none)`` means that the function should not be imported as
8554 throwing. The error parameter and result type will be imported normally.
8555
8556* ``swift_error(null_result)`` means that calls to the function should be
8557 considered to have thrown if they return a null value. The return type must be
8558 a pointer type, and it will be imported into Swift with a non-optional type.
8559 This is the default error convention for Objective-C methods that return
8560 pointers.
8561
8562* ``swift_error(zero_result)`` means that calls to the function should be
8563 considered to have thrown if they return a zero result. The return type must be
8564 an integral type. If the return type would have been imported as ``Bool``, it
8565 is instead imported as ``Void``. This is the default error convention for
8566 Objective-C methods that return a type that would be imported as ``Bool``.
8567
8568* ``swift_error(nonzero_result)`` means that calls to the function should be
8569 considered to have thrown if they return a non-zero result. The return type must
8570 be an integral type. If the return type would have been imported as ``Bool``,
8571 it is instead imported as ``Void``.
8572
8573* ``swift_error(nonnull_error)`` means that calls to the function should be
8574 considered to have thrown if they leave a non-null error in the error parameter.
8575 The return type is left unmodified.)reST";
8576
8577static const char AttrDoc_SwiftErrorResult[] = R"reST(The ``swift_error_result`` attribute marks a parameter of a ``swiftcall``
8578function as having the special error-result ABI treatment.
8579
8580This treatment generally passes the underlying error value in and out of
8581the function through a special register which is normally callee-preserved.
8582This is modeled in C by pretending that the register is addressable memory:
8583
8584- The caller appears to pass the address of a variable of pointer type.
8585 The current value of this variable is copied into the register before
8586 the call; if the call returns normally, the value is copied back into the
8587 variable.
8588
8589- The callee appears to receive the address of a variable. This address
8590 is actually a hidden location in its own stack, initialized with the
8591 value of the register upon entry. When the function returns normally,
8592 the value in that hidden location is written back to the register.
8593
8594A ``swift_error_result`` parameter must be the last parameter, and it must be
8595preceded by a ``swift_context`` parameter.
8596
8597A ``swift_error_result`` parameter must have type ``T**`` or ``T*&`` for some
8598type T. Note that no qualifiers are permitted on the intermediate level.
8599
8600It is undefined behavior if the caller does not pass a pointer or
8601reference to a valid object.
8602
8603The standard convention is that the error value itself (that is, the
8604value stored in the apparent argument) will be null upon function entry,
8605but this is not enforced by the ABI.)reST";
8606
8607static const char AttrDoc_SwiftImportAsNonGeneric[] = R"reST()reST";
8608
8609static const char AttrDoc_SwiftImportPropertyAsAccessors[] = R"reST()reST";
8610
8611static const char AttrDoc_SwiftIndirectResult[] = R"reST(The ``swift_indirect_result`` attribute marks a parameter of a ``swiftcall``
8612or ``swiftasynccall`` function as having the special indirect-result ABI
8613treatment.
8614
8615This treatment gives the parameter the target's normal indirect-result
8616ABI treatment, which may involve passing it differently from an ordinary
8617parameter. However, only the first indirect result will receive this
8618treatment. Furthermore, low-level lowering may decide that a direct result
8619must be returned indirectly; if so, this will take priority over the
8620``swift_indirect_result`` parameters.
8621
8622A ``swift_indirect_result`` parameter must either be the first parameter or
8623follow another ``swift_indirect_result`` parameter.
8624
8625A ``swift_indirect_result`` parameter must have type ``T*`` or ``T&`` for
8626some object type ``T``. If ``T`` is a complete type at the point of
8627definition of a function, it is undefined behavior if the argument
8628value does not point to storage of adequate size and alignment for a
8629value of type ``T``.
8630
8631Making indirect results explicit in the signature allows C functions to
8632directly construct objects into them without relying on language
8633optimizations like C++'s named return value optimization (NRVO).)reST";
8634
8635static const char AttrDoc_SwiftName[] = R"reST(The ``swift_name`` attribute provides the name of the declaration in Swift. If
8636this attribute is absent, the name is transformed according to the algorithm
8637built into the Swift compiler.
8638
8639The argument is a string literal that contains the Swift name of the function,
8640variable, or type. When renaming a function, the name may be a compound Swift
8641name. For a type, enum constant, property, or variable declaration, the name
8642must be a simple or qualified identifier.
8643
8644 .. code-block:: objc
8645
8646 @interface URL
8647 - (void) initWithString:(NSString *)s __attribute__((__swift_name__("URL.init(_:)")))
8648 @end
8649
8650 void __attribute__((__swift_name__("squareRoot()"))) sqrt(double v) {
8651 })reST";
8652
8653static const char AttrDoc_SwiftNewType[] = R"reST(The ``swift_newtype`` attribute indicates that the typedef to which the
8654attribute appertains is imported as a new Swift type of the typedef's name.
8655Previously, the attribute was spelt ``swift_wrapper``. While the behaviour of
8656the attribute is identical with either spelling, ``swift_wrapper`` is
8657deprecated, only exists for compatibility purposes, and should not be used in
8658new code.
8659
8660* ``swift_newtype(struct)`` means that a Swift struct will be created for this
8661 typedef.
8662
8663* ``swift_newtype(enum)`` means that a Swift enum will be created for this
8664 typedef.
8665
8666 .. code-block:: c
8667
8668 // Import UIFontTextStyle as an enum type, with enumerated values being
8669 // constants.
8670 typedef NSString * UIFontTextStyle __attribute__((__swift_newtype__(enum)));
8671
8672 // Import UIFontDescriptorFeatureKey as a structure type, with enumerated
8673 // values being members of the type structure.
8674 typedef NSString * UIFontDescriptorFeatureKey __attribute__((__swift_newtype__(struct)));)reST";
8675
8676static const char AttrDoc_SwiftNullability[] = R"reST()reST";
8677
8678static const char AttrDoc_SwiftObjCMembers[] = R"reST(This attribute indicates that Swift subclasses and members of Swift extensions
8679of this class will be implicitly marked with the ``@objcMembers`` Swift
8680attribute, exposing them back to Objective-C.)reST";
8681
8682static const char AttrDoc_SwiftPrivate[] = R"reST(Declarations marked with the ``swift_private`` attribute are hidden from the
8683framework client but are still made available for use within the framework or
8684Swift SDK overlay.
8685
8686The purpose of this attribute is to permit a more idomatic implementation of
8687declarations in Swift while hiding the non-idiomatic one.)reST";
8688
8689static const char AttrDoc_SwiftType[] = R"reST()reST";
8690
8691static const char AttrDoc_SwiftVersionedAddition[] = R"reST()reST";
8692
8693static const char AttrDoc_SwiftVersionedRemoval[] = R"reST()reST";
8694
8695static const char AttrDoc_SysVABI[] = R"reST(On Windows x86_64 targets, this attribute changes the calling convention of a
8696function to match the default convention used on Sys V targets such as Linux,
8697Mac, and BSD. This attribute has no effect on other targets.)reST";
8698
8699static const char AttrDoc_TLSModel[] = R"reST(The ``tls_model`` attribute allows you to specify which thread-local storage
8700model to use. It accepts the following strings:
8701
8702* global-dynamic
8703* local-dynamic
8704* initial-exec
8705* local-exec
8706
8707TLS models are mutually exclusive.)reST";
8708
8709static const char AttrDoc_Target[] = R"reST(Clang supports the GNU style ``__attribute__((target("OPTIONS")))`` attribute.
8710This attribute may be attached to a function definition and instructs
8711the backend to use different code generation options than were passed on the
8712command line.
8713
8714The current set of options correspond to the existing "subtarget features" for
8715the target with or without a "-mno-" in front corresponding to the absence
8716of the feature, as well as ``arch="CPU"`` which will change the default "CPU"
8717for the function.
8718
8719For X86, the attribute also allows ``tune="CPU"`` to optimize the generated
8720code for the given CPU without changing the available instructions.
8721
8722For AArch64, ``arch="Arch"`` will set the architecture, similar to the -march
8723command line options. ``cpu="CPU"`` can be used to select a specific cpu,
8724as per the ``-mcpu`` option, similarly for ``tune=``. The attribute also allows the
8725"branch-protection=<args>" option, where the permissible arguments and their
8726effect on code generation are the same as for the command-line option
8727``-mbranch-protection``.
8728
8729Example "subtarget features" from the x86 backend include: "mmx", "sse", "sse4.2",
8730"avx", "xop" and largely correspond to the machine specific options handled by
8731the front end.
8732
8733Note that this attribute does not apply transitively to nested functions such
8734as blocks or C++ lambdas.
8735
8736Additionally, this attribute supports function multiversioning for ELF based
8737x86/x86-64 targets, which can be used to create multiple implementations of the
8738same function that will be resolved at runtime based on the priority of their
8739``target`` attribute strings. A function is considered a multiversioned function
8740if either two declarations of the function have different ``target`` attribute
8741strings, or if it has a ``target`` attribute string of ``default``. For
8742example:
8743
8744 .. code-block:: c++
8745
8746 __attribute__((target("arch=atom")))
8747 void foo() {} // will be called on 'atom' processors.
8748 __attribute__((target("default")))
8749 void foo() {} // will be called on any other processors.
8750
8751All multiversioned functions must contain a ``default`` (fallback)
8752implementation, otherwise usages of the function are considered invalid.
8753Additionally, a function may not become multiversioned after its first use.)reST";
8754
8755static const char AttrDoc_TargetClones[] = R"reST(Clang supports the ``target_clones("OPTIONS")`` attribute. This attribute may be
8756attached to a function declaration and causes function multiversioning, where
8757multiple versions of the function will be emitted with different code
8758generation options. Additionally, these versions will be resolved at runtime
8759based on the priority of their attribute options. All ``target_clone`` functions
8760are considered multiversioned functions.
8761
8762For AArch64 target:
8763The attribute contains comma-separated strings of target features joined by "+"
8764sign. For example:
8765
8766 .. code-block:: c++
8767
8768 __attribute__((target_clones("sha2+memtag", "fcma+sve2-pmull128")))
8769 void foo() {}
8770
8771For every multiversioned function a ``default`` (fallback) implementation
8772always generated if not specified directly.
8773
8774For x86/x86-64 targets:
8775All multiversioned functions must contain a ``default`` (fallback)
8776implementation, otherwise usages of the function are considered invalid.
8777Additionally, a function may not become multiversioned after its first use.
8778
8779The options to ``target_clones`` can either be a target-specific architecture
8780(specified as ``arch=CPU``), or one of a list of subtarget features.
8781
8782Example "subtarget features" from the x86 backend include: "mmx", "sse", "sse4.2",
8783"avx", "xop" and largely correspond to the machine specific options handled by
8784the front end.
8785
8786The versions can either be listed as a comma-separated sequence of string
8787literals or as a single string literal containing a comma-separated list of
8788versions. For compatibility with GCC, the two formats can be mixed. For
8789example, the following will emit 4 versions of the function:
8790
8791 .. code-block:: c++
8792
8793 __attribute__((target_clones("arch=atom,avx2","arch=ivybridge","default")))
8794 void foo() {}
8795
8796For targets that support the GNU indirect function (IFUNC) feature, dispatch
8797is performed by emitting an indirect function that is resolved to the appropriate
8798target clone at load time. The indirect function is given the name the
8799multiversioned function would have if it had been declared without the attribute.
8800For backward compatibility with earlier Clang releases, a function alias with an
8801``.ifunc`` suffix is also emitted. The ``.ifunc`` suffixed symbol is a deprecated
8802feature and support for it may be removed in the future.
8803
8804For PowerPC targets, ``target_clones`` is supported on AIX only. Only CPU
8805(specified as ``cpu=CPU``) and ``default`` options are allowed. IFUNC is supported
8806on AIX in Clang, so dispatch is implemented similar to other targets using IFUNC.
8807An FMV function that is only declared in a translation unit is treated as a
8808non-FMV. The resolver and the function clones are given internal linkage.)reST";
8809
8810static const char AttrDoc_TargetVersion[] = R"reST(For AArch64 target clang supports function multiversioning by
8811``__attribute__((target_version("OPTIONS")))`` attribute. When applied to a
8812function it instructs compiler to emit multiple function versions based on
8813``target_version`` attribute strings, which resolved at runtime depend on their
8814priority and target features availability. One of the versions is always
8815( implicitly or explicitly ) the ``default`` (fallback). Attribute strings can
8816contain dependent features names joined by the "+" sign.
8817
8818For targets that support the GNU indirect function (IFUNC) feature, dispatch
8819is performed by emitting an indirect function that is resolved to the appropriate
8820target clone at load time. The indirect function is given the name the
8821multiversioned function would have if it had been declared without the attribute.
8822For backward compatibility with earlier Clang releases, a function alias with an
8823``.ifunc`` suffix is also emitted. The ``.ifunc`` suffixed symbol is a deprecated
8824feature and support for it may be removed in the future.)reST";
8825
8826static const char AttrDoc_TestTypestate[] = R"reST(Use ``__attribute__((test_typestate(tested_state)))`` to indicate that a method
8827returns true if the object is in the specified state..)reST";
8828
8829static const char AttrDoc_ThisCall[] = R"reST(On 32-bit x86 targets, this attribute changes the calling convention of a
8830function to use ECX for the first parameter (typically the implicit ``this``
8831parameter of C++ methods) and clear parameters off of the stack on return. This
8832convention does not support variadic calls or unprototyped functions in C, and
8833has no effect on x86_64 targets. See the documentation for `__thiscall`_ on
8834MSDN.
8835
8836.. _`__thiscall`: http://msdn.microsoft.com/en-us/library/ek8tkfbw.aspx)reST";
8837
8838static const char AttrDoc_Thread[] = R"reST(The ``__declspec(thread)`` attribute declares a variable with thread local
8839storage. It is available under the ``-fms-extensions`` flag for MSVC
8840compatibility. See the documentation for `__declspec(thread)`_ on MSDN.
8841
8842.. _`__declspec(thread)`: http://msdn.microsoft.com/en-us/library/9w1sdazb.aspx
8843
8844In Clang, ``__declspec(thread)`` is generally equivalent in functionality to the
8845GNU ``__thread`` keyword. The variable must not have a destructor and must have
8846a constant initializer, if any. The attribute only applies to variables
8847declared with static storage duration, such as globals, class static data
8848members, and static locals.)reST";
8849
8850static const char AttrDoc_TransparentUnion[] = R"reST(This attribute can be applied to a union to change the behavior of calls to
8851functions that have an argument with a transparent union type. The compiler
8852behavior is changed in the following manner:
8853
8854- A value whose type is any member of the transparent union can be passed as an
8855 argument without the need to cast that value.
8856
8857- The argument is passed to the function using the calling convention of the
8858 first member of the transparent union. Consequently, all the members of the
8859 transparent union should have the same calling convention as its first member.
8860
8861Transparent unions are not supported in C++.)reST";
8862
8863static const char AttrDoc_TrivialABI[] = R"reST(The ``trivial_abi`` attribute can be applied to a C++ class, struct, or union.
8864It instructs the compiler to pass and return the type using the C ABI for the
8865underlying type when the type would otherwise be considered non-trivial for the
8866purpose of calls.
8867A class annotated with ``trivial_abi`` can have non-trivial destructors or
8868copy/move constructors without automatically becoming non-trivial for the
8869purposes of calls. For example:
8870
8871 .. code-block:: c++
8872
8873 // A is trivial for the purposes of calls because ``trivial_abi`` makes the
8874 // user-provided special functions trivial.
8875 struct __attribute__((trivial_abi)) A {
8876 ~A();
8877 A(const A &);
8878 A(A &&);
8879 int x;
8880 };
8881
8882 // B's destructor and copy/move constructor are considered trivial for the
8883 // purpose of calls because A is trivial.
8884 struct B {
8885 A a;
8886 };
8887
8888If a type is trivial for the purposes of calls, has a non-trivial destructor,
8889and is passed as an argument by value, the convention is that the callee will
8890destroy the object before returning. The lifetime of the copy of the parameter
8891in the caller ends without a destructor call when the call begins.
8892
8893If a type is trivial for the purpose of calls, it is assumed to be trivially
8894relocatable for the purpose of ``__is_trivially_relocatable`` and
8895``__builtin_is_cpp_trivially_relocatable``.
8896When a type marked with ``[[trivial_abi]]`` is used as a function argument,
8897the compiler may omit the call to the copy constructor.
8898Thus, side effects of the copy constructor are potentially not performed.
8899For example, objects that contain pointers to themselves or otherwise depend
8900on their address (or the address or their subobjects) should not be declared
8901``[[trivial_abi]]``.
8902
8903Attribute ``trivial_abi`` has no effect in the following cases:
8904
8905- The class directly declares a virtual base or virtual methods.
8906- Copy constructors and move constructors of the class are all deleted.
8907- The class has a base class that is non-trivial for the purposes of calls.
8908- The class has a non-static data member whose type is non-trivial for the
8909 purposes of calls, which includes:
8910
8911 - classes that are non-trivial for the purposes of calls
8912 - __weak-qualified types in Objective-C++
8913 - arrays of any of the above)reST";
8914
8915static const char AttrDoc_TryAcquireCapability[] = R"reST(Marks a function that attempts to acquire a capability. This function may fail to
8916actually acquire the capability; they accept a Boolean value determining
8917whether acquiring the capability means success (true), or failing to acquire
8918the capability means success (false).)reST";
8919
8920static const char AttrDoc_TypeNonNull[] = R"reST(The ``_Nonnull`` nullability qualifier indicates that null is not a meaningful
8921value for a value of the ``_Nonnull`` pointer type. For example, given a
8922declaration such as:
8923
8924 .. code-block:: c
8925
8926 int fetch(int * _Nonnull ptr);
8927
8928a caller of ``fetch`` should not provide a null value, and the compiler will
8929produce a warning if it sees a literal null value passed to ``fetch``. Note
8930that, unlike the declaration attribute ``nonnull``, the presence of
8931``_Nonnull`` does not imply that passing null is undefined behavior: ``fetch``
8932is free to consider null undefined behavior or (perhaps for
8933backward-compatibility reasons) defensively handle null.)reST";
8934
8935static const char AttrDoc_TypeNullUnspecified[] = R"reST(The ``_Null_unspecified`` nullability qualifier indicates that neither the
8936``_Nonnull`` nor ``_Nullable`` qualifiers make sense for a particular pointer
8937type. It is used primarily to indicate that the role of null with specific
8938pointers in a nullability-annotated header is unclear, e.g., due to
8939overly-complex implementations or historical factors with a long-lived API.)reST";
8940
8941static const char AttrDoc_TypeNullable[] = R"reST(The ``_Nullable`` nullability qualifier indicates that a value of the
8942``_Nullable`` pointer type can be null. For example, given:
8943
8944 .. code-block:: c
8945
8946 int fetch_or_zero(int * _Nullable ptr);
8947
8948a caller of ``fetch_or_zero`` can provide null.
8949
8950The ``_Nullable`` attribute on classes indicates that the given class can
8951represent null values, and so the ``_Nullable``, ``_Nonnull`` etc qualifiers
8952make sense for this type. For example:
8953
8954 .. code-block:: c
8955
8956 class _Nullable ArenaPointer { ... };
8957
8958 ArenaPointer _Nonnull x = ...;
8959 ArenaPointer _Nullable y = nullptr;)reST";
8960
8961static const char AttrDoc_TypeNullableResult[] = R"reST(The ``_Nullable_result`` nullability qualifier means that a value of the
8962``_Nullable_result`` pointer can be ``nil``, just like ``_Nullable``. Where this
8963attribute differs from ``_Nullable`` is when it's used on a parameter to a
8964completion handler in a Swift async method. For instance, here:
8965
8966 .. code-block:: objc
8967
8968 -(void)fetchSomeDataWithID:(int)identifier
8969 completionHandler:(void (^)(Data *_Nullable_result result, NSError *error))completionHandler;
8970
8971This method asynchronously calls ``completionHandler`` when the data is
8972available, or calls it with an error. ``_Nullable_result`` indicates to the
8973Swift importer that this is the uncommon case where ``result`` can get ``nil``
8974even if no error has occurred, and will therefore import it as a Swift optional
8975type. Otherwise, if ``result`` was annotated with ``_Nullable``, the Swift
8976importer will assume that ``result`` will always be non-nil unless an error
8977occurred.)reST";
8978
8979static const char AttrDoc_TypeTagForDatatype[] = R"reST(When declaring a variable, use
8980``__attribute__((type_tag_for_datatype(kind, type)))`` to create a type tag that
8981is tied to the ``type`` argument given to the attribute.
8982
8983In the attribute prototype above:
8984 * ``kind`` is an identifier that should be used when annotating all applicable
8985 type tags.
8986 * ``type`` indicates the name of the type.
8987
8988Clang supports annotating type tags of two forms.
8989
8990 * **Type tag that is a reference to a declared identifier.**
8991 Use ``__attribute__((type_tag_for_datatype(kind, type)))`` when declaring that
8992 identifier:
8993
8994 .. code-block:: c++
8995
8996 typedef int MPI_Datatype;
8997 extern struct mpi_datatype mpi_datatype_int
8998 __attribute__(( type_tag_for_datatype(mpi,int) ));
8999 #define MPI_INT ((MPI_Datatype) &mpi_datatype_int)
9000 // &mpi_datatype_int is a type tag. It is tied to type "int".
9001
9002 * **Type tag that is an integral literal.**
9003 Declare a ``static const`` variable with an initializer value and attach
9004 ``__attribute__((type_tag_for_datatype(kind, type)))`` on that declaration:
9005
9006 .. code-block:: c++
9007
9008 typedef int MPI_Datatype;
9009 static const MPI_Datatype mpi_datatype_int
9010 __attribute__(( type_tag_for_datatype(mpi,int) )) = 42;
9011 #define MPI_INT ((MPI_Datatype) 42)
9012 // The number 42 is a type tag. It is tied to type "int".
9013
9014
9015The ``type_tag_for_datatype`` attribute also accepts an optional third argument
9016that determines how the type of the function argument specified by either
9017``arg_idx`` or ``ptr_idx`` is compared against the type associated with the type
9018tag. (Recall that for the ``argument_with_type_tag`` attribute, the type of the
9019function argument specified by ``arg_idx`` is compared against the type
9020associated with the type tag. Also recall that for the ``pointer_with_type_tag``
9021attribute, the pointee type of the function argument specified by ``ptr_idx`` is
9022compared against the type associated with the type tag.) There are two supported
9023values for this optional third argument:
9024
9025 * ``layout_compatible`` will cause types to be compared according to
9026 layout-compatibility rules (In C++11 [class.mem] p 17, 18, see the
9027 layout-compatibility rules for two standard-layout struct types and for two
9028 standard-layout union types). This is useful when creating a type tag
9029 associated with a struct or union type. For example:
9030
9031 .. code-block:: c++
9032
9033 /* In mpi.h */
9034 typedef int MPI_Datatype;
9035 struct internal_mpi_double_int { double d; int i; };
9036 extern struct mpi_datatype mpi_datatype_double_int
9037 __attribute__(( type_tag_for_datatype(mpi,
9038 struct internal_mpi_double_int, layout_compatible) ));
9039
9040 #define MPI_DOUBLE_INT ((MPI_Datatype) &mpi_datatype_double_int)
9041
9042 int MPI_Send(void *buf, int count, MPI_Datatype datatype, ...)
9043 __attribute__(( pointer_with_type_tag(mpi,1,3) ));
9044
9045 /* In user code */
9046 struct my_pair { double a; int b; };
9047 struct my_pair *buffer;
9048 MPI_Send(buffer, 1, MPI_DOUBLE_INT /*, ... */); // no warning because the
9049 // layout of my_pair is
9050 // compatible with that of
9051 // internal_mpi_double_int
9052
9053 struct my_int_pair { int a; int b; }
9054 struct my_int_pair *buffer2;
9055 MPI_Send(buffer2, 1, MPI_DOUBLE_INT /*, ... */); // warning because the
9056 // layout of my_int_pair
9057 // does not match that of
9058 // internal_mpi_double_int
9059
9060 * ``must_be_null`` specifies that the function argument specified by either
9061 ``arg_idx`` (for the ``argument_with_type_tag`` attribute) or ``ptr_idx`` (for
9062 the ``pointer_with_type_tag`` attribute) should be a null pointer constant.
9063 The second argument to the ``type_tag_for_datatype`` attribute is ignored. For
9064 example:
9065
9066 .. code-block:: c++
9067
9068 /* In mpi.h */
9069 typedef int MPI_Datatype;
9070 extern struct mpi_datatype mpi_datatype_null
9071 __attribute__(( type_tag_for_datatype(mpi, void, must_be_null) ));
9072
9073 #define MPI_DATATYPE_NULL ((MPI_Datatype) &mpi_datatype_null)
9074 int MPI_Send(void *buf, int count, MPI_Datatype datatype, ...)
9075 __attribute__(( pointer_with_type_tag(mpi,1,3) ));
9076
9077 /* In user code */
9078 struct my_pair { double a; int b; };
9079 struct my_pair *buffer;
9080 MPI_Send(buffer, 1, MPI_DATATYPE_NULL /*, ... */); // warning: MPI_DATATYPE_NULL
9081 // was specified but buffer
9082 // is not a null pointer)reST";
9083
9084static const char AttrDoc_TypeVisibility[] = R"reST(The ``type_visibility`` attribute allows the visibility of a type and its vague
9085linkage objects (vtable, typeinfo, typeinfo name) to be controlled separately from
9086the visibility of functions and data members of the type.
9087
9088For example, this can be used to give default visibility to the typeinfo and the vtable
9089of a type while still keeping hidden visibility on its member functions and static data
9090members.
9091
9092This attribute can only be applied to types and namespaces.
9093
9094If both ``visibility`` and ``type_visibility`` are applied to a type or a namespace, the
9095visibility specified with the ``type_visibility`` attribute overrides the visibility
9096provided with the regular ``visibility`` attribute.)reST";
9097
9098static const char AttrDoc_UPtr[] = R"reST(The ``__uptr`` qualifier specifies that a 32-bit pointer should be zero
9099extended when converted to a 64-bit pointer.)reST";
9100
9101static const char AttrDoc_Unavailable[] = R"reST(No documentation.)reST";
9102
9103static const char AttrDoc_Uninitialized[] = R"reST(The command-line parameter ``-ftrivial-auto-var-init=*`` can be used to
9104initialize trivial automatic stack variables. By default, trivial automatic
9105stack variables are uninitialized. This attribute is used to override the
9106command-line parameter, forcing variables to remain uninitialized. It has no
9107semantic meaning in that using uninitialized values is undefined behavior,
9108it rather documents the programmer's intent.)reST";
9109
9110static const char AttrDoc_Unlikely[] = R"reST(The ``likely`` and ``unlikely`` attributes are used as compiler hints.
9111The attributes are used to aid the compiler to determine which branch is
9112likely or unlikely to be taken. This is done by marking the branch substatement
9113with one of the two attributes.
9114
9115It isn't allowed to annotate a single statement with both ``likely`` and
9116``unlikely``. Annotating the ``true`` and ``false`` branch of an ``if``
9117statement with the same likelihood attribute will result in a diagnostic and
9118the attributes are ignored on both branches.
9119
9120In a ``switch`` statement it's allowed to annotate multiple ``case`` labels
9121or the ``default`` label with the same likelihood attribute. This makes
9122* all labels without an attribute have a neutral likelihood,
9123* all labels marked ``[[likely]]`` have an equally positive likelihood, and
9124* all labels marked ``[[unlikely]]`` have an equally negative likelihood.
9125The neutral likelihood is the more likely of path execution than the negative
9126likelihood. The positive likelihood is the more likely of path of execution
9127than the neutral likelihood.
9128
9129These attributes have no effect on the generated code when using
9130PGO (Profile-Guided Optimization) or at optimization level 0.
9131
9132In Clang, the attributes will be ignored if they're not placed on
9133* the ``case`` or ``default`` label of a ``switch`` statement,
9134* or on the substatement of an ``if`` or ``else`` statement,
9135* or on the substatement of an ``for`` or ``while`` statement.
9136The C++ Standard recommends to honor them on every statement in the
9137path of execution, but that can be confusing:
9138
9139.. code-block:: c++
9140
9141 if (b) {
9142 [[unlikely]] --b; // Per the standard this is in the path of
9143 // execution, so this branch should be considered
9144 // unlikely. However, Clang ignores the attribute
9145 // here since it is not on the substatement.
9146 }
9147
9148 if (b) {
9149 --b;
9150 if(b)
9151 return;
9152 [[unlikely]] --b; // Not in the path of execution,
9153 } // the branch has no likelihood information.
9154
9155 if (b) {
9156 --b;
9157 foo(b);
9158 // Whether or not the next statement is in the path of execution depends
9159 // on the declaration of foo():
9160 // In the path of execution: void foo(int);
9161 // Not in the path of execution: [[noreturn]] void foo(int);
9162 // This means the likelihood of the branch depends on the declaration
9163 // of foo().
9164 [[unlikely]] --b;
9165 }
9166
9167
9168Below are some example usages of the likelihood attributes and their effects:
9169
9170.. code-block:: c++
9171
9172 if (b) [[likely]] { // Placement on the first statement in the branch.
9173 // The compiler will optimize to execute the code here.
9174 } else {
9175 }
9176
9177 if (b)
9178 [[unlikely]] b++; // Placement on the first statement in the branch.
9179 else {
9180 // The compiler will optimize to execute the code here.
9181 }
9182
9183 if (b) {
9184 [[unlikely]] b++; // Placement on the second statement in the branch.
9185 } // The attribute will be ignored.
9186
9187 if (b) [[likely]] {
9188 [[unlikely]] b++; // No contradiction since the second attribute
9189 } // is ignored.
9190
9191 if (b)
9192 ;
9193 else [[likely]] {
9194 // The compiler will optimize to execute the code here.
9195 }
9196
9197 if (b)
9198 ;
9199 else
9200 // The compiler will optimize to execute the next statement.
9201 [[likely]] b = f();
9202
9203 if (b) [[likely]]; // Both branches are likely. A diagnostic is issued
9204 else [[likely]]; // and the attributes are ignored.
9205
9206 if (b)
9207 [[likely]] int i = 5; // Issues a diagnostic since the attribute
9208 // isn't allowed on a declaration.
9209
9210 switch (i) {
9211 [[likely]] case 1: // This value is likely
9212 ...
9213 break;
9214
9215 [[unlikely]] case 2: // This value is unlikely
9216 ...
9217 [[fallthrough]];
9218
9219 case 3: // No likelihood attribute
9220 ...
9221 [[likely]] break; // No effect
9222
9223 case 4: [[likely]] { // attribute on substatement has no effect
9224 ...
9225 break;
9226 }
9227
9228 [[unlikely]] default: // All other values are unlikely
9229 ...
9230 break;
9231 }
9232
9233 switch (i) {
9234 [[likely]] case 0: // This value and code path is likely
9235 ...
9236 [[fallthrough]];
9237
9238 case 1: // No likelihood attribute, code path is neutral
9239 break; // falling through has no effect on the likelihood
9240
9241 case 2: // No likelihood attribute, code path is neutral
9242 [[fallthrough]];
9243
9244 [[unlikely]] default: // This value and code path are both unlikely
9245 break;
9246 }
9247
9248 for(int i = 0; i != size; ++i) [[likely]] {
9249 ... // The loop is the likely path of execution
9250 }
9251
9252 for(const auto &E : Elements) [[likely]] {
9253 ... // The loop is the likely path of execution
9254 }
9255
9256 while(i != size) [[unlikely]] {
9257 ... // The loop is the unlikely path of execution
9258 } // The generated code will optimize to skip the loop body
9259
9260 while(true) [[unlikely]] {
9261 ... // The attribute has no effect
9262 } // Clang elides the comparison and generates an infinite
9263 // loop)reST";
9264
9265static const char AttrDoc_UnsafeBufferUsage[] = R"reST(The attribute ``[[clang::unsafe_buffer_usage]]`` should be placed on functions
9266that need to be avoided as they are prone to buffer overflows or unsafe buffer
9267struct fields. It is designed to work together with the off-by-default compiler
9268warning ``-Wunsafe-buffer-usage`` to help codebases transition away from raw pointer
9269based buffer management, in favor of safer abstractions such as C++20 ``std::span``.
9270The attribute causes ``-Wunsafe-buffer-usage`` to warn on every use of the function or
9271the field it is attached to, and it may also lead to emission of automatic fix-it
9272hints which would help the user replace the use of unsafe functions(/fields) with safe
9273alternatives, though the attribute can be used even when the fix can't be automated.
9274
9275* Attribute attached to functions: The attribute suppresses all
9276 ``-Wunsafe-buffer-usage`` warnings within the function it is attached to, as the
9277 function is now classified as unsafe. The attribute should be used carefully, as it
9278 will silence all unsafe operation warnings inside the function; including any new
9279 unsafe operations introduced in the future.
9280
9281 The attribute is warranted even if the only way a function can overflow
9282 the buffer is by violating the function's preconditions. For example, it
9283 would make sense to put the attribute on function ``foo()`` below because
9284 passing an incorrect size parameter would cause a buffer overflow:
9285
9286 .. code-block:: c++
9287
9288 [[clang::unsafe_buffer_usage]]
9289 void foo(int *buf, size_t size) {
9290 for (size_t i = 0; i < size; ++i) {
9291 buf[i] = i;
9292 }
9293 }
9294
9295 The attribute is NOT warranted when the function uses safe abstractions,
9296 assuming that these abstractions weren't misused outside the function.
9297 For example, function ``bar()`` below doesn't need the attribute,
9298 because assuming that the container ``buf`` is well-formed (has size that
9299 fits the original buffer it refers to), overflow cannot occur:
9300
9301 .. code-block:: c++
9302
9303 void bar(std::span<int> buf) {
9304 for (size_t i = 0; i < buf.size(); ++i) {
9305 buf[i] = i;
9306 }
9307 }
9308
9309 In this case function ``bar()`` enables the user to keep the buffer
9310 "containerized" in a span for as long as possible. On the other hand,
9311 Function ``foo()`` in the previous example may have internal
9312 consistency, but by accepting a raw buffer it requires the user to unwrap
9313 their span, which is undesirable according to the programming model
9314 behind ``-Wunsafe-buffer-usage``.
9315
9316 The attribute is warranted when a function accepts a raw buffer only to
9317 immediately put it into a span:
9318
9319 .. code-block:: c++
9320
9321 [[clang::unsafe_buffer_usage]]
9322 void baz(int *buf, size_t size) {
9323 std::span<int> sp{ buf, size };
9324 for (size_t i = 0; i < sp.size(); ++i) {
9325 sp[i] = i;
9326 }
9327 }
9328
9329 In this case ``baz()`` does not contain any unsafe operations, but the awkward
9330 parameter type causes the caller to unwrap the span unnecessarily.
9331 Note that regardless of the attribute, code inside ``baz()`` isn't flagged
9332 by ``-Wunsafe-buffer-usage`` as unsafe. It is definitely undesirable,
9333 but if ``baz()`` is on an API surface, there is no way to improve it
9334 to make it as safe as ``bar()`` without breaking the source and binary
9335 compatibility with existing users of the function. In such cases
9336 the proper solution would be to create a different function (possibly
9337 an overload of ``baz()``) that accepts a safe container like ``bar()``,
9338 and then use the attribute on the original ``baz()`` to help the users
9339 update their code to use the new function.
9340
9341* Attribute attached to fields: The attribute should only be attached to
9342 struct fields, if the fields can not be updated to a safe type with bounds
9343 check, such as std::span. In other words, the buffers prone to unsafe accesses
9344 should always be updated to use safe containers/views and attaching the attribute
9345 must be last resort when such an update is infeasible.
9346
9347 The attribute can be placed on individual fields or a set of them as shown below.
9348
9349 .. code-block:: c++
9350
9351 struct A {
9352 [[clang::unsafe_buffer_usage]]
9353 int *ptr1;
9354
9355 [[clang::unsafe_buffer_usage]]
9356 int *ptr2, buf[10];
9357
9358 [[clang::unsafe_buffer_usage]]
9359 size_t sz;
9360 };
9361
9362 Here, every read/write to the fields ptr1, ptr2, buf and sz will trigger a warning
9363 that the field has been explcitly marked as unsafe due to unsafe-buffer operations.)reST";
9364
9365static const char AttrDoc_Unused[] = R"reST(When passing the ``-Wunused`` flag to Clang, entities that are unused by the
9366program may be diagnosed. The ``[[maybe_unused]]`` (or
9367``__attribute__((unused))``) attribute can be used to silence such diagnostics
9368when the entity cannot be removed. For instance, a local variable may exist
9369solely for use in an ``assert()`` statement, which makes the local variable
9370unused when ``NDEBUG`` is defined.
9371
9372The attribute may be applied to the declaration of a class, a typedef, a
9373variable, a function or method, a function parameter, an enumeration, an
9374enumerator, a non-static data member, or a label.
9375
9376.. code-block:: c++
9377
9378 #include <cassert>
9379
9380 [[maybe_unused]] void f([[maybe_unused]] bool thing1,
9381 [[maybe_unused]] bool thing2) {
9382 [[maybe_unused]] bool b = thing1 && thing2;
9383 assert(b);
9384 })reST";
9385
9386static const char AttrDoc_UseHandle[] = R"reST(A function taking a handle by value might close the handle. If a function
9387parameter is annotated with ``use_handle(tag)`` it is assumed to not to change
9388the state of the handle. It is also assumed to require an open handle to work with.
9389The attribute requires a string literal argument to identify the handle being used.
9390
9391.. code-block:: c++
9392
9393 zx_status_t zx_port_wait(zx_handle_t handle [[clang::use_handle("zircon")]],
9394 zx_time_t deadline,
9395 zx_port_packet_t* packet);)reST";
9396
9397static const char AttrDoc_Used[] = R"reST(This attribute, when attached to a function or variable definition, indicates
9398that there may be references to the entity which are not apparent in the source
9399code. For example, it may be referenced from inline ``asm``, or it may be
9400found through a dynamic symbol or section lookup.
9401
9402The compiler must emit the definition even if it appears to be unused, and it
9403must not apply optimizations which depend on fully understanding how the entity
9404is used.
9405
9406Whether this attribute has any effect on the linker depends on the target and
9407the linker. Most linkers support the feature of section garbage collection
9408(``--gc-sections``), also known as "dead stripping" (``ld64 -dead_strip``) or
9409discarding unreferenced sections (``link.exe /OPT:REF``). On COFF and Mach-O
9410targets (Windows and Apple platforms), the `used` attribute prevents symbols
9411from being removed by linker section GC. On ELF targets, it has no effect on its
9412own, and the linker may remove the definition if it is not otherwise referenced.
9413This linker GC can be avoided by also adding the ``retain`` attribute. Note
9414that ``retain`` requires special support from the linker; see that attribute's
9415documentation for further information.)reST";
9416
9417static const char AttrDoc_UsingIfExists[] = R"reST(The ``using_if_exists`` attribute applies to a using-declaration. It allows
9418programmers to import a declaration that potentially does not exist, instead
9419deferring any errors to the point of use. For instance:
9420
9421.. code-block:: c++
9422
9423 namespace empty_namespace {};
9424 __attribute__((using_if_exists))
9425 using empty_namespace::does_not_exist; // no error!
9426
9427 does_not_exist x; // error: use of unresolved 'using_if_exists'
9428
9429The C++ spelling of the attribute (`[[clang::using_if_exists]]`) is also
9430supported as a clang extension, since ISO C++ doesn't support attributes in this
9431position. If the entity referred to by the using-declaration is found by name
9432lookup, the attribute has no effect. This attribute is useful for libraries
9433(primarily, libc++) that wish to redeclare a set of declarations in another
9434namespace, when the availability of those declarations is difficult or
9435impossible to detect at compile time with the preprocessor.)reST";
9436
9437static const char AttrDoc_Uuid[] = R"reST(No documentation.)reST";
9438
9439static const char AttrDoc_VTablePointerAuthentication[] = R"reST(No documentation.)reST";
9440
9441static const char AttrDoc_VecReturn[] = R"reST(No documentation.)reST";
9442
9443static const char AttrDoc_VecTypeHint[] = R"reST(No documentation.)reST";
9444
9445static const char AttrDoc_VectorCall[] = R"reST(On 32-bit x86 *and* x86_64 targets, this attribute changes the calling
9446convention of a function to pass vector parameters in SSE registers.
9447
9448On 32-bit x86 targets, this calling convention is similar to ``__fastcall``.
9449The first two integer parameters are passed in ECX and EDX. Subsequent integer
9450parameters are passed in memory, and callee clears the stack. On x86_64
9451targets, the callee does *not* clear the stack, and integer parameters are
9452passed in RCX, RDX, R8, and R9 as is done for the default Windows x64 calling
9453convention.
9454
9455On both 32-bit x86 and x86_64 targets, vector and floating point arguments are
9456passed in XMM0-XMM5. Homogeneous vector aggregates of up to four elements are
9457passed in sequential SSE registers if enough are available. If AVX is enabled,
9458256 bit vectors are passed in YMM0-YMM5. Any vector or aggregate type that
9459cannot be passed in registers for any reason is passed by reference, which
9460allows the caller to align the parameter memory.
9461
9462See the documentation for `__vectorcall`_ on MSDN for more details.
9463
9464.. _`__vectorcall`: http://msdn.microsoft.com/en-us/library/dn375768.aspx)reST";
9465
9466static const char AttrDoc_Visibility[] = R"reST(No documentation.)reST";
9467
9468static const char AttrDoc_WarnUnused[] = R"reST(The ``warn_unused`` attribute can be placed on the declaration of a structure or union type.
9469When the ``-Wunused-variable`` diagnostic is enabled, local variables of types which have a non-trivial constructor or destructor are considered "used" by virtue of the constructor or destructor invocations involved.
9470Those constructor or destructor invocations are not considered a use if the type is declared with the ``warn_unused`` attribute.
9471The variable is considered used if it is named outside of its declaration.
9472
9473This attribute is available in both C and C++ language modes but is primarily useful in C++ for classes which have a non-trivial constructor or destructor but act as a value type rather than an RAII type.
9474
9475.. code-block:: c++
9476
9477 struct [[gnu::warn_unused]] S {
9478 S();
9479 ~S();
9480 };
9481
9482 struct T {
9483 T();
9484 ~T();
9485 };
9486
9487 int func() {
9488 S s1; // -Wunused-variable warning
9489 S s2; // No -Wunused-variable warning because of the member access expression below
9490 S s3; // No -Wunused-variable warning because of the sizeof operand below
9491 T t; // No -Wunused-variable warning
9492
9493 s2.~S();
9494 return sizeof(s3);
9495 })reST";
9496
9497static const char AttrDoc_WarnUnusedResult[] = R"reST(Clang supports the ability to diagnose when the results of a function call
9498expression are discarded under suspicious circumstances. A diagnostic is
9499generated when a function or its return type is marked with ``[[nodiscard]]``
9500(or ``__attribute__((warn_unused_result))``) and the function call appears as a
9501potentially-evaluated discarded-value expression that is not explicitly cast to
9502``void``.
9503
9504A string literal may optionally be provided to the attribute, which will be
9505reproduced in any resulting diagnostics. Redeclarations using different forms
9506of the attribute (with or without the string literal or with different string
9507literal contents) are allowed. If there are redeclarations of the entity with
9508differing string literals, it is unspecified which one will be used by Clang
9509in any resulting diagnostics.
9510
9511.. code-block:: c++
9512
9513 struct [[nodiscard]] error_info { /*...*/ };
9514 error_info enable_missile_safety_mode();
9515
9516 void launch_missiles();
9517 void test_missiles() {
9518 enable_missile_safety_mode(); // diagnoses
9519 launch_missiles();
9520 }
9521 error_info &foo();
9522 void f() { foo(); } // Does not diagnose, error_info is a reference.
9523
9524Additionally, discarded temporaries resulting from a call to a constructor
9525marked with ``[[nodiscard]]`` or a constructor of a type marked
9526``[[nodiscard]]`` will also diagnose. This also applies to type conversions that
9527use the annotated ``[[nodiscard]]`` constructor or result in an annotated type.
9528
9529.. code-block:: c++
9530
9531 struct [[nodiscard]] marked_type {/*..*/ };
9532 struct marked_ctor {
9533 [[nodiscard]] marked_ctor();
9534 marked_ctor(int);
9535 };
9536
9537 struct S {
9538 operator marked_type() const;
9539 [[nodiscard]] operator int() const;
9540 };
9541
9542 void usages() {
9543 marked_type(); // diagnoses.
9544 marked_ctor(); // diagnoses.
9545 marked_ctor(3); // Does not diagnose, int constructor isn't marked nodiscard.
9546
9547 S s;
9548 static_cast<marked_type>(s); // diagnoses
9549 (int)s; // diagnoses
9550 })reST";
9551
9552static const char AttrDoc_Weak[] = R"reST(In supported output formats the ``weak`` attribute can be used to
9553specify that a variable or function should be emitted as a symbol with
9554``weak`` (if a definition) or ``extern_weak`` (if a declaration of an
9555external symbol) `linkage
9556<https://llvm.org/docs/LangRef.html#linkage-types>`_.
9557
9558If there is a non-weak definition of the symbol the linker will select
9559that over the weak. They must have same type and alignment (variables
9560must also have the same size), but may have a different value.
9561
9562If there are multiple weak definitions of same symbol, but no non-weak
9563definition, they should have same type, size, alignment and value, the
9564linker will select one of them (see also selectany_ attribute).
9565
9566If the ``weak`` attribute is applied to a ``const`` qualified variable
9567definition that variable is no longer consider a compiletime constant
9568as its value can change during linking (or dynamic linking). This
9569means that it can e.g no longer be part of an initializer expression.
9570
9571.. code-block:: c
9572
9573 const int ANSWER __attribute__ ((weak)) = 42;
9574
9575 /* This function may be replaced link-time */
9576 __attribute__ ((weak)) void debug_log(const char *msg)
9577 {
9578 fprintf(stderr, "DEBUG: %s\n", msg);
9579 }
9580
9581 int main(int argc, const char **argv)
9582 {
9583 debug_log ("Starting up...");
9584
9585 /* This may print something else than "6 * 7 = 42",
9586 if there is a non-weak definition of "ANSWER" in
9587 an object linked in */
9588 printf("6 * 7 = %d\n", ANSWER);
9589
9590 return 0;
9591 }
9592
9593If an external declaration is marked weak and that symbol does not
9594exist during linking (possibly dynamic) the address of the symbol will
9595evaluate to NULL.
9596
9597.. code-block:: c
9598
9599 void may_not_exist(void) __attribute__ ((weak));
9600
9601 int main(int argc, const char **argv)
9602 {
9603 if (may_not_exist) {
9604 may_not_exist();
9605 } else {
9606 printf("Function did not exist\n");
9607 }
9608 return 0;
9609 })reST";
9610
9611static const char AttrDoc_WeakImport[] = R"reST(No documentation.)reST";
9612
9613static const char AttrDoc_WeakRef[] = R"reST(No documentation.)reST";
9614
9615static const char AttrDoc_WebAssemblyExportName[] = R"reST(Clang supports the ``__attribute__((export_name(<name>)))``
9616attribute for the WebAssembly target. This attribute may be attached to a
9617function declaration, where it modifies how the symbol is to be exported
9618from the linked WebAssembly.
9619
9620WebAssembly functions are exported via string name. By default when a symbol
9621is exported, the export name for C/C++ symbols are the same as their C/C++
9622symbol names. This attribute can be used to override the default behavior, and
9623request a specific string name be used instead.)reST";
9624
9625static const char AttrDoc_WebAssemblyFuncref[] = R"reST(Clang supports the ``__attribute__((export_name(<name>)))``
9626attribute for the WebAssembly target. This attribute may be attached to a
9627function declaration, where it modifies how the symbol is to be exported
9628from the linked WebAssembly.
9629
9630WebAssembly functions are exported via string name. By default when a symbol
9631is exported, the export name for C/C++ symbols are the same as their C/C++
9632symbol names. This attribute can be used to override the default behavior, and
9633request a specific string name be used instead.)reST";
9634
9635static const char AttrDoc_WebAssemblyImportModule[] = R"reST(Clang supports the ``__attribute__((import_module(<module_name>)))``
9636attribute for the WebAssembly target. This attribute may be attached to a
9637function declaration, where it modifies how the symbol is to be imported
9638within the WebAssembly linking environment.
9639
9640WebAssembly imports use a two-level namespace scheme, consisting of a module
9641name, which typically identifies a module from which to import, and a field
9642name, which typically identifies a field from that module to import. By
9643default, module names for C/C++ symbols are assigned automatically by the
9644linker. This attribute can be used to override the default behavior, and
9645request a specific module name be used instead.)reST";
9646
9647static const char AttrDoc_WebAssemblyImportName[] = R"reST(Clang supports the ``__attribute__((import_name(<name>)))``
9648attribute for the WebAssembly target. This attribute may be attached to a
9649function declaration, where it modifies how the symbol is to be imported
9650within the WebAssembly linking environment.
9651
9652WebAssembly imports use a two-level namespace scheme, consisting of a module
9653name, which typically identifies a module from which to import, and a field
9654name, which typically identifies a field from that module to import. By
9655default, field names for C/C++ symbols are the same as their C/C++ symbol
9656names. This attribute can be used to override the default behavior, and
9657request a specific field name be used instead.)reST";
9658
9659static const char AttrDoc_WorkGroupSizeHint[] = R"reST(No documentation.)reST";
9660
9661static const char AttrDoc_X86ForceAlignArgPointer[] = R"reST(Use this attribute to force stack alignment.
9662
9663Legacy x86 code uses 4-byte stack alignment. Newer aligned SSE instructions
9664(like 'movaps') that work with the stack require operands to be 16-byte aligned.
9665This attribute realigns the stack in the function prologue to make sure the
9666stack can be used with SSE instructions.
9667
9668Note that the x86_64 ABI forces 16-byte stack alignment at the call site.
9669Because of this, 'force_align_arg_pointer' is not needed on x86_64, except in
9670rare cases where the caller does not align the stack properly (e.g. flow
9671jumps from i386 arch code).
9672
9673 .. code-block:: c
9674
9675 __attribute__ ((force_align_arg_pointer))
9676 void f () {
9677 ...
9678 })reST";
9679
9680static const char AttrDoc_XRayInstrument[] = R"reST(``__attribute__((xray_always_instrument))`` or
9681``[[clang::xray_always_instrument]]`` is used to mark member functions (in C++),
9682methods (in Objective C), and free functions (in C, C++, and Objective C) to be
9683instrumented with XRay. This will cause the function to always have space at
9684the beginning and exit points to allow for runtime patching.
9685
9686Conversely, ``__attribute__((xray_never_instrument))`` or
9687``[[clang::xray_never_instrument]]`` will inhibit the insertion of these
9688instrumentation points.
9689
9690If a function has neither of these attributes, they become subject to the XRay
9691heuristics used to determine whether a function should be instrumented or
9692otherwise.
9693
9694``__attribute__((xray_log_args(N)))`` or ``[[clang::xray_log_args(N)]]`` is
9695used to preserve N function arguments for the logging function. Currently,
9696only N==1 is supported.)reST";
9697
9698static const char AttrDoc_XRayLogArgs[] = R"reST(``__attribute__((xray_always_instrument))`` or
9699``[[clang::xray_always_instrument]]`` is used to mark member functions (in C++),
9700methods (in Objective C), and free functions (in C, C++, and Objective C) to be
9701instrumented with XRay. This will cause the function to always have space at
9702the beginning and exit points to allow for runtime patching.
9703
9704Conversely, ``__attribute__((xray_never_instrument))`` or
9705``[[clang::xray_never_instrument]]`` will inhibit the insertion of these
9706instrumentation points.
9707
9708If a function has neither of these attributes, they become subject to the XRay
9709heuristics used to determine whether a function should be instrumented or
9710otherwise.
9711
9712``__attribute__((xray_log_args(N)))`` or ``[[clang::xray_log_args(N)]]`` is
9713used to preserve N function arguments for the logging function. Currently,
9714only N==1 is supported.)reST";
9715
9716static const char AttrDoc_ZeroCallUsedRegs[] = R"reST(This attribute, when attached to a function, causes the compiler to zero a
9717subset of all call-used registers before the function returns. It's used to
9718increase program security by either mitigating `Return-Oriented Programming`_
9719(ROP) attacks or preventing information leakage through registers.
9720
9721The term "call-used" means registers which are not guaranteed to be preserved
9722unchanged for the caller by the current calling convention. This could also be
9723described as "caller-saved" or "not callee-saved".
9724
9725The `choice` parameters gives the programmer flexibility to choose the subset
9726of the call-used registers to be zeroed:
9727
9728- ``skip`` doesn't zero any call-used registers. This choice overrides any
9729 command-line arguments.
9730- ``used`` only zeros call-used registers used in the function. By ``used``, we
9731 mean a register whose contents have been set or referenced in the function.
9732- ``used-gpr`` only zeros call-used GPR registers used in the function.
9733- ``used-arg`` only zeros call-used registers used to pass arguments to the
9734 function.
9735- ``used-gpr-arg`` only zeros call-used GPR registers used to pass arguments to
9736 the function.
9737- ``all`` zeros all call-used registers.
9738- ``all-gpr`` zeros all call-used GPR registers.
9739- ``all-arg`` zeros all call-used registers used to pass arguments to the
9740 function.
9741- ``all-gpr-arg`` zeros all call-used GPR registers used to pass arguments to
9742 the function.
9743
9744The default for the attribute is controlled by the ``-fzero-call-used-regs``
9745flag.
9746
9747.. _Return-Oriented Programming: https://en.wikipedia.org/wiki/Return-oriented_programming)reST";
9748