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][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_AMDGPUAvailableVisible[] = R"reST(This attribute controls availability and visibility as described in the [AMDGPU
53Memory Model](https://llvm.org/docs/AMDGPUMemoryModel.html). When placed on
54an atomic expression or fence, the resulting atomic or fence instruction carries
55the corresponding *AV Metadata*.
56
57The attribute takes a string literal as an argument, which currently has only
58one supported value:
59
60- `"none"`: Disable MakeAvailable and MakeVisible semantics on release and
61 acquire operations respectively.
62
63```c++
64[[clang::amdgpu_av("none")]] __atomic_thread_fence(__ATOMIC_SEQ_CST);
65[[clang::amdgpu_av("none")]] __atomic_fetch_add(ptr, 1, __ATOMIC_ACQ_REL);
66
67// Also works with _Atomic type qualifier operations.
68_Atomic int *p;
69[[clang::amdgpu_av("none")]] *p += 1;
70```)reST";
71
72static const char AttrDoc_AMDGPUFlatWorkGroupSize[] = R"reST(The flat work-group size is the number of work-items in the work-group size
73specified when the kernel is dispatched. It is the product of the sizes of the
74x, y, and z dimension of the work-group.
75
76Clang supports the
77`__attribute__((amdgpu_flat_work_group_size(<min>, <max>)))` attribute for the
78AMDGPU target. This attribute may be attached to a kernel function definition
79and is an optimization hint.
80
81`<min>` parameter specifies the minimum flat work-group size, and `<max>`
82parameter specifies the maximum flat work-group size (must be greater than
83`<min>`) to which all dispatches of the kernel will conform. Passing `0, 0`
84as `<min>, <max>` implies the default behavior (`128, 256`).
85
86If specified, the AMDGPU target backend might be able to produce better machine
87code for barriers and perform scratch promotion by estimating available group
88segment size.
89
90An error will be given if:
91: - Specified values violate subtarget specifications;
92 - Specified values are not compatible with values provided through other
93 attributes.)reST";
94
95static const char AttrDoc_AMDGPUMaxNumWorkGroups[] = R"reST(This attribute specifies the max number of work groups when the kernel
96is dispatched.
97
98Clang supports the
99`__attribute__((amdgpu_max_num_work_groups(<x>, <y>, <z>)))` or
100`[[clang::amdgpu_max_num_work_groups(<x>, <y>, <z>)]]` attribute for the
101AMDGPU target. This attribute may be attached to HIP or OpenCL kernel function
102definitions and is an optimization hint.
103
104The `<x>` parameter specifies the maximum number of work groups in the x dimension.
105Similarly `<y>` and `<z>` are for the y and z dimensions respectively.
106Each of the three values must be greater than 0 when provided. The `<x>` parameter
107is required, while `<y>` and `<z>` are optional with default value of 1.
108
109If specified, the AMDGPU target backend might be able to produce better machine
110code.
111
112An error will be given if:
113: - Specified values violate subtarget specifications;
114 - Specified values are not compatible with values provided through other
115 attributes.)reST";
116
117static const char AttrDoc_AMDGPUNamedBarrierWrapper[] = R"reST()reST";
118
119static const char AttrDoc_AMDGPUNumSGPR[] = R"reST(:::{warning}
120These attributes are deprecated. Use the `amdgpu_waves_per_eu` attribute to
121control SGPR and VGPR usage instead.
122:::
123
124Clang supports the `__attribute__((amdgpu_num_sgpr(<num_sgpr>)))` and
125`__attribute__((amdgpu_num_vgpr(<num_vgpr>)))` attributes for the AMDGPU
126target. These attributes may be attached to a kernel function definition and are
127an optimization hint.
128
129If these attributes are specified, then the AMDGPU target backend will attempt
130to limit the number of SGPRs and/or VGPRs used to the specified value(s). The
131number of used SGPRs and/or VGPRs may further be rounded up to satisfy the
132allocation requirements or constraints of the subtarget. Passing `0` as
133`num_sgpr` and/or `num_vgpr` implies the default behavior (no limits).
134
135These attributes can be used to test the AMDGPU target backend. It is
136recommended that the `amdgpu_waves_per_eu` attribute be used to control
137resources such as SGPRs and VGPRs since it is aware of the limits for different
138subtargets.
139
140An error will be given if:
141: - Specified values violate subtarget specifications;
142 - Specified values are not compatible with values provided through other
143 attributes;
144 - The AMDGPU target backend is unable to create machine code that can meet the
145 request.)reST";
146
147static const char AttrDoc_AMDGPUNumVGPR[] = R"reST(:::{warning}
148These attributes are deprecated. Use the `amdgpu_waves_per_eu` attribute to
149control SGPR and VGPR usage instead.
150:::
151
152Clang supports the `__attribute__((amdgpu_num_sgpr(<num_sgpr>)))` and
153`__attribute__((amdgpu_num_vgpr(<num_vgpr>)))` attributes for the AMDGPU
154target. These attributes may be attached to a kernel function definition and are
155an optimization hint.
156
157If these attributes are specified, then the AMDGPU target backend will attempt
158to limit the number of SGPRs and/or VGPRs used to the specified value(s). The
159number of used SGPRs and/or VGPRs may further be rounded up to satisfy the
160allocation requirements or constraints of the subtarget. Passing `0` as
161`num_sgpr` and/or `num_vgpr` implies the default behavior (no limits).
162
163These attributes can be used to test the AMDGPU target backend. It is
164recommended that the `amdgpu_waves_per_eu` attribute be used to control
165resources such as SGPRs and VGPRs since it is aware of the limits for different
166subtargets.
167
168An error will be given if:
169: - Specified values violate subtarget specifications;
170 - Specified values are not compatible with values provided through other
171 attributes;
172 - The AMDGPU target backend is unable to create machine code that can meet the
173 request.)reST";
174
175static const char AttrDoc_AMDGPUWavesPerEU[] = R"reST(A compute unit (CU) is responsible for executing the wavefronts of a work-group.
176It is composed of one or more execution units (EU), which are responsible for
177executing the wavefronts. An EU can have enough resources to maintain the state
178of more than one executing wavefront. This allows an EU to hide latency by
179switching between wavefronts in a similar way to symmetric multithreading on a
180CPU. In order to allow the state for multiple wavefronts to fit on an EU, the
181resources used by a single wavefront have to be limited. For example, the number
182of SGPRs and VGPRs. Limiting such resources can allow greater latency hiding,
183but can result in having to spill some register state to memory.
184
185Clang supports the `__attribute__((amdgpu_waves_per_eu(<min>[, <max>])))`
186attribute for the AMDGPU target. This attribute may be attached to a kernel
187function definition and is an optimization hint.
188
189`<min>` parameter specifies the requested minimum number of waves per EU, and
190*optional* `<max>` parameter specifies the requested maximum number of waves
191per EU (must be greater than `<min>` if specified). If `<max>` is omitted,
192then there is no restriction on the maximum number of waves per EU other than
193the one dictated by the hardware for which the kernel is compiled. Passing
194`0, 0` as `<min>, <max>` implies the default behavior (no limits).
195
196If specified, this attribute allows an advanced developer to tune the number of
197wavefronts that are capable of fitting within the resources of an EU. The AMDGPU
198target backend can use this information to limit resources, such as number of
199SGPRs, number of VGPRs, size of available group and private memory segments, in
200such a way that guarantees that at least `<min>` wavefronts and at most
201`<max>` wavefronts are able to fit within the resources of an EU. Requesting
202more wavefronts can hide memory latency but limits available registers which
203can result in spilling. Requesting fewer wavefronts can help reduce cache
204thrashing, but can reduce memory latency hiding.
205
206This attribute controls the machine code generated by the AMDGPU target backend
207to ensure it is capable of meeting the requested values. However, when the
208kernel is executed, there may be other reasons that prevent meeting the request,
209for example, there may be wavefronts from other kernels executing on the EU.
210
211An error will be given if:
212: - Specified values violate subtarget specifications;
213 - Specified values are not compatible with values provided through other
214 attributes;
215
216The AMDGPU target backend will emit a warning whenever it is unable to
217create machine code that meets the request.)reST";
218
219static const char AttrDoc_ARMInterrupt[] = R"reST(Clang supports the GNU style `__attribute__((interrupt("TYPE")))` attribute on
220ARM targets. This attribute may be attached to a function definition and
221instructs the backend to generate appropriate function entry/exit code so that
222it can be used directly as an interrupt service routine.
223
224The parameter passed to the interrupt attribute is optional, but if
225provided it must be a string literal with one of the following values: "IRQ",
226"FIQ", "SWI", "ABORT", "UNDEF".
227
228The semantics are as follows:
229
230- If the function is AAPCS, Clang instructs the backend to realign the stack to
231 8 bytes on entry. This is a general requirement of the AAPCS at public
232 interfaces, but may not hold when an exception is taken. Doing this allows
233 other AAPCS functions to be called.
234
235- If the CPU is M-class this is all that needs to be done since the architecture
236 itself is designed in such a way that functions obeying the normal AAPCS ABI
237 constraints are valid exception handlers.
238
239- If the CPU is not M-class, the prologue and epilogue are modified to save all
240 non-banked registers that are used, so that upon return the user-mode state
241 will not be corrupted. Note that to avoid unnecessary overhead, only
242 general-purpose (integer) registers are saved in this way. If VFP operations
243 are needed, that state must be saved manually.
244
245 Specifically, interrupt kinds other than "FIQ" will save all core registers
246 except "lr" and "sp". "FIQ" interrupts will save r0-r7.
247
248- If the CPU is not M-class, the return instruction is changed to one of the
249 canonical sequences permitted by the architecture for exception return. Where
250 possible the function itself will make the necessary "lr" adjustments so that
251 the "preferred return address" is selected.
252
253 Unfortunately the compiler is unable to make this guarantee for an "UNDEF"
254 handler, where the offset from "lr" to the preferred return address depends on
255 the execution state of the code which generated the exception. In this case
256 a sequence equivalent to "movs pc, lr" will be used.)reST";
257
258static const char AttrDoc_ARMInterruptSaveFP[] = R"reST(Clang supports the GNU style `__attribute__((interrupt_save_fp("TYPE")))`
259on ARM targets. This attribute behaves the same way as the ARM interrupt
260attribute, except the general purpose floating point registers are also saved,
261along with FPEXC and FPSCR. Note, even on M-class CPUs, where the floating
262point context can be automatically saved depending on the FPCCR, the general
263purpose floating point registers will be saved.)reST";
264
265static const char AttrDoc_ARMSaveFP[] = R"reST()reST";
266
267static const char AttrDoc_AVRInterrupt[] = R"reST(Clang supports the GNU style `__attribute__((interrupt))` attribute on
268AVR targets. This attribute may be attached to a function definition and instructs
269the backend to generate appropriate function entry/exit code so that it can be used
270directly as an interrupt service routine.
271
272On the AVR, the hardware globally disables interrupts when an interrupt is executed.
273The first instruction of an interrupt handler declared with this attribute is a SEI
274instruction to re-enable interrupts. See also the signal attribute that
275does not insert a SEI instruction.)reST";
276
277static const char AttrDoc_AVRSignal[] = R"reST(Clang supports the GNU style `__attribute__((signal))` attribute on
278AVR targets. This attribute may be attached to a function definition and instructs
279the backend to generate appropriate function entry/exit code so that it can be used
280directly as an interrupt service routine.
281
282Interrupt handler functions defined with the signal attribute do not re-enable interrupts.)reST";
283
284static const char AttrDoc_AbiTag[] = R"reST(The `abi_tag` attribute can be applied to a function, variable, class or
285inline namespace declaration to modify the mangled name of the entity. It gives
286the ability to distinguish between different versions of the same entity but
287with different ABI versions supported. For example, a newer version of a class
288could have a different set of data members and thus have a different size. Using
289the `abi_tag` attribute, it is possible to have different mangled names for
290a global variable of the class type. Therefore, the old code could keep using
291the old mangled name and the new code will use the new mangled name with tags.)reST";
292
293static const char AttrDoc_AcquireCapability[] = R"reST(Marks a function as acquiring a capability.)reST";
294
295static const char AttrDoc_AcquireHandle[] = R"reST(If this annotation is on a function or a function type it is assumed to return
296a new handle. In case this annotation is on an output parameter,
297the function is assumed to fill the corresponding argument with a new
298handle. The attribute requires a string literal argument which used to
299identify the handle with later uses of `use_handle` or
300`release_handle`.
301
302```c++
303// Output arguments from Zircon.
304zx_status_t zx_socket_create(uint32_t options,
305 zx_handle_t __attribute__((acquire_handle("zircon"))) * out0,
306 zx_handle_t* out1 [[clang::acquire_handle("zircon")]]);
307
308
309// Returned handle.
310[[clang::acquire_handle("tag")]] int open(const char *path, int oflag, ... );
311int open(const char *path, int oflag, ... ) __attribute__((acquire_handle("tag")));
312```)reST";
313
314static const char AttrDoc_AcquiredAfter[] = R"reST(No documentation.)reST";
315
316static const char AttrDoc_AcquiredBefore[] = R"reST(No documentation.)reST";
317
318static const char AttrDoc_AddressSpace[] = R"reST(:::{Note}
319This attribute is mainly intended to be used by target headers
320provided by the toolchain. End users should prefer the documented, named
321address space annotations for their platform, such as the
322[OpenCL address spaces], `__global__`, `__local__`, or something else.
323:::
324
325The `address_space` attribute functions as a type qualifier that allows the
326programmer to specify the address space for a pointer or reference type.
327Qualified pointer types are considered distinct types for the purposes of
328overload resolution. The attribute takes a single, non-negative integer
329constant expression identifying the address space. For example:
330
331```c
332int * __attribute__((address_space(1))) ptr;
333
334void foo(__attribute__((address_space(2))) float *buf);
335```
336
337Only one address space qualifier may be applied to a given pointer or reference
338type. Where address spaces are allowed (e.g., variables, parameters, return
339types) and what values are valid depends on the target and language mode.
340
341The meaning of each value is defined by the target; multiple address spaces are
342used in environments such as OpenCL, CUDA, HIP, and other GPU programming
343models to distinguish global, local, constant, and private memory. See for
344example the address spaces defined in the [NVPTX Usage Guide][nvptx usage guide] and the
345[AMDGPU Usage Guide][amdgpu usage guide].
346
347Address spaces may partially overlap or be entirely distinct. The compiler may
348reject attempts to convert between distinct, incompatible address spaces.
349Pointer width may vary between different address spaces, so some explicit casts
350may truncate.
351
352For more information, refer to [ISO TR18037][iso tr18037], which covers embedded C language
353extensions. Section 5 covers named address spaces.
354
355[amdgpu usage guide]: https://llvm.org/docs/AMDGPUUsage.html#address-spaces
356[iso tr18037]: https://standards.iso.org/ittf/PubliclyAvailableStandards/c051126_ISO_IEC_TR_18037_2008.zip
357[nvptx usage guide]: https://llvm.org/docs/NVPTXUsage.html#address-spaces)reST";
358
359static const char AttrDoc_Alias[] = R"reST(No documentation.)reST";
360
361static const char AttrDoc_AlignMac68k[] = R"reST()reST";
362
363static const char AttrDoc_AlignNatural[] = R"reST()reST";
364
365static const char AttrDoc_AlignValue[] = R"reST(The align_value attribute can be added to the typedef of a pointer type or the
366declaration of a variable of pointer or reference type. It specifies that the
367pointer will point to, or the reference will bind to, only objects with at
368least the provided alignment. This alignment value must be some positive power
369of 2.
370
371```c
372typedef double * aligned_double_ptr __attribute__((align_value(64)));
373void foo(double & x __attribute__((align_value(128))),
374 aligned_double_ptr y) { ... }
375```
376
377If the pointer value does not have the specified alignment at runtime, the
378behavior of the program is undefined.)reST";
379
380static const char AttrDoc_Aligned[] = R"reST(No documentation.)reST";
381
382static const char AttrDoc_AllocAlign[] = R"reST(Use `__attribute__((alloc_align(<parameter-index>)))` on a declaration with a
383function prototype to specify that the prototype's return value (which must be a
384pointer type) is at least as aligned as the value of the indicated parameter.
385This includes functions, Objective-C methods, blocks, and declarations of
386function pointer, member function pointer, function reference, and block pointer
387types. The attribute can also be applied to typedef or type alias declarations
388whose underlying type has a function prototype.
389
390The parameter is given by its index in the list of formal parameters; the first
391parameter has index 1 unless the function is a C++ non-static member function,
392in which case the first parameter has index 2 to account for the implicit `this`
393parameter.
394
395```c++
396// The returned pointer has the alignment specified by the first parameter.
397void *a(size_t align) __attribute__((alloc_align(1)));
398
399// The function pointer's returned pointer has the alignment specified by
400// the first parameter of the pointed-to function.
401void *(*allocator)(size_t align) __attribute__((alloc_align(1)));
402
403// The returned pointer has the alignment specified by the second parameter.
404void *b(void *v, size_t align) __attribute__((alloc_align(2)));
405
406// The returned pointer has the alignment specified by the second visible
407// parameter, however it must be adjusted for the implicit 'this' parameter.
408void *Foo::b(void *v, size_t align) __attribute__((alloc_align(3)));
409```
410
411Note that this attribute merely informs the compiler that a function always
412returns a sufficiently aligned pointer. It does not cause the compiler to
413emit code to enforce that alignment. The behavior is undefined if the returned
414pointer is not sufficiently aligned.)reST";
415
416static const char AttrDoc_AllocSize[] = R"reST(The `alloc_size` attribute can be placed on functions that return pointers in
417order to hint to the compiler how many bytes of memory will be available at the
418returned pointer. `alloc_size` takes one or two arguments.
419
420- `alloc_size(N)` implies that argument number N equals the number of
421 available bytes at the returned pointer.
422- `alloc_size(N, M)` implies that the product of argument number N and
423 argument number M equals the number of available bytes at the returned
424 pointer.
425
426Argument numbers are 1-based.
427
428An example of how to use `alloc_size`
429
430```c
431void *my_malloc(int a) __attribute__((alloc_size(1)));
432void *my_calloc(int a, int b) __attribute__((alloc_size(1, 2)));
433
434int main() {
435 void *const p = my_malloc(100);
436 assert(__builtin_object_size(p, 0) == 100);
437 void *const a = my_calloc(20, 5);
438 assert(__builtin_object_size(a, 0) == 100);
439}
440```
441
442When `-Walloc-size` is enabled, this attribute allows the compiler to
443diagnose cases when the allocated memory is insufficient for the size of the
444type the returned pointer is cast to.
445
446```c
447void *my_malloc(int a) __attribute__((alloc_size(1)));
448void consumer_func(int *);
449
450int main() {
451 int *ptr = my_malloc(sizeof(int)); // no warning
452 int *w = my_malloc(1); // warning: allocation of insufficient size '1' for type 'int' with size '4'
453 consumer_func(my_malloc(1)); // warning: allocation of insufficient size '1' for type 'int' with size '4'
454}
455```
456
457:::{Note}
458This attribute works differently in clang than it does in GCC.
459Specifically, clang will only trace `const` pointers (as above); we give up
460on pointers that are not marked as `const`. In the vast majority of cases,
461this is unimportant, because LLVM has support for the `alloc_size`
462attribute. However, this may cause mildly unintuitive behavior when used with
463other attributes, such as `enable_if`.
464:::)reST";
465
466static const char AttrDoc_Allocating[] = R"reST(Declares that a function potentially allocates heap memory, and prevents any potential inference
467of `nonallocating` by the compiler.)reST";
468
469static const char AttrDoc_AlwaysDestroy[] = R"reST(The `always_destroy` attribute specifies that a variable with static or thread
470storage duration should have its exit-time destructor run. This attribute is the
471default unless clang was invoked with -fno-c++-static-destructors.
472
473If a variable is explicitly declared with this attribute, Clang will silence
474otherwise applicable `-Wexit-time-destructors` warnings.)reST";
475
476static const char AttrDoc_AlwaysInline[] = R"reST(Inlining heuristics are disabled and inlining is always attempted regardless of
477optimization level.
478
479`[[clang::always_inline]]` spelling can be used as a statement attribute; other
480spellings of the attribute are not supported on statements. If a statement is
481marked `[[clang::always_inline]]` and contains calls, the compiler attempts
482to inline those calls.
483
484```c
485int example(void) {
486 int i;
487 [[clang::always_inline]] foo(); // attempts to inline foo
488 [[clang::always_inline]] i = bar(); // attempts to inline bar
489 [[clang::always_inline]] return f(42, baz(bar())); // attempts to inline everything
490}
491```
492
493A declaration statement, which is a statement, is not a statement that can have an
494attribute associated with it (the attribute applies to the declaration, not the
495statement in that case). So this use case will not work:
496
497```c
498int example(void) {
499 [[clang::always_inline]] int i = bar();
500 return i;
501}
502```
503
504This attribute does not guarantee that inline substitution actually occurs.
505
506\<ins>Note: applying this attribute to a coroutine at the `-O0` optimization level
507has no effect; other optimization levels may only partially inline and result in a
508diagnostic.\</ins>
509
510See also [the Microsoft Docs on Inline Functions][the microsoft docs on inline functions], [the GCC Common Function
511Attribute docs][the gcc common function attribute docs], and [the GCC Inline docs][the gcc inline docs].
512
513[the gcc common function attribute docs]: https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html
514[the gcc inline docs]: https://gcc.gnu.org/onlinedocs/gcc/Inline.html
515[the microsoft docs on inline functions]: https://docs.microsoft.com/en-us/cpp/cpp/inline-functions-cpp)reST";
516
517static const char AttrDoc_AnalyzerNoReturn[] = R"reST(No documentation.)reST";
518
519static const char AttrDoc_Annotate[] = R"reST(The `annotate` attribute is used to add annotations to declarations or statements,
520typically for use by static analysis tools that are not integrated into the
521core Clang compiler (e.g., Clang-Tidy checks or out-of-tree Clang-based tools).
522It is a counterpart to the `annotate_type` attribute, which serves the same
523purpose, but for types.
524
525The attribute takes a mandatory string literal argument specifying the
526annotation category and an arbitrary number of optional arguments that provide
527additional information specific to the annotation category. The optional
528arguments must be constant expressions of arbitrary type.
529
530For example:
531
532```c++
533[[clang::annotate("category1", "foo", 1)]] void func(int val [[clang::annotate("category2")]]) {
534 [[clang::annotate("category3")]] if (val) {
535
536 }
537}
538```)reST";
539
540static const char AttrDoc_AnnotateType[] = R"reST(This attribute is used to add annotations to types, typically for use by static
541analysis tools that are not integrated into the core Clang compiler (e.g.,
542Clang-Tidy checks or out-of-tree Clang-based tools). It is a counterpart to the
543`annotate` attribute, which serves the same purpose, but for declarations.
544
545The attribute takes a mandatory string literal argument specifying the
546annotation category and an arbitrary number of optional arguments that provide
547additional information specific to the annotation category. The optional
548arguments must be constant expressions of arbitrary type.
549
550For example:
551
552```c++
553int* [[clang::annotate_type("category1", "foo", 1)]] f(int[[clang::annotate_type("category2")]] *);
554```
555
556The attribute does not have any effect on the semantics of the type system,
557neither type checking rules, nor runtime semantics. In particular:
558
559- `std::is_same<T, T [[clang::annotate_type("foo")]]>` is true for all types
560 `T`.
561- It is not permissible for overloaded functions or template specializations
562 to differ merely by an `annotate_type` attribute.
563- The presence of an `annotate_type` attribute will not affect name
564 mangling.)reST";
565
566static const char AttrDoc_AnyX86Interrupt[] = R"reST(Clang supports the GNU style `__attribute__((interrupt))` attribute on X86
567targets. This attribute may be attached to a function definition and instructs
568the backend to generate appropriate function entry/exit code so that it can be
569used directly as an interrupt service routine.
570
571Interrupt handlers have access to the stack frame pushed onto the stack by the processor,
572and return using the `IRET` instruction. All registers in an interrupt handler are callee-saved.
573Exception handlers also have access to the error code pushed onto the stack by the processor,
574when applicable.
575
576An interrupt handler must take the following arguments:
577
578```c
579__attribute__ ((interrupt))
580void f (struct stack_frame *frame) {
581 ...
582}
583```
584
585Where `struct stack_frame` is a suitable struct matching the stack frame pushed
586by the processor.
587
588An exception handler must take the following arguments:
589
590```c
591__attribute__ ((interrupt))
592void g (struct stack_frame *frame, unsigned long code) {
593 ...
594}
595```
596
597On 32-bit targets, the `code` argument should be of type `unsigned int`.
598
599Exception handlers should only be used when an error code is pushed by the processor.
600Using the incorrect handler type will crash the system.
601
602Interrupt and exception handlers cannot be called by other functions and must have return type `void`.
603
604Interrupt and exception handlers should only call functions with the 'no_caller_saved_registers'
605attribute, or should be compiled with the '-mgeneral-regs-only' flag to avoid saving unused
606non-GPR registers.)reST";
607
608static const char AttrDoc_AnyX86NoCallerSavedRegisters[] = R"reST(Use this attribute to indicate that the specified function has no
609caller-saved registers. That is, all registers are callee-saved except for
610registers used for passing parameters to the function or returning parameters
611from the function.
612The compiler saves and restores any modified registers that were not used for
613passing or returning arguments to the function.
614
615The user can call functions specified with the 'no_caller_saved_registers'
616attribute from an interrupt handler without saving and restoring all
617call-clobbered registers.
618
619Functions specified with the 'no_caller_saved_registers' attribute should only
620call other functions with the 'no_caller_saved_registers' attribute, or should be
621compiled with the '-mgeneral-regs-only' flag to avoid saving unused non-GPR registers.
622
623Note that 'no_caller_saved_registers' attribute is not a calling convention.
624In fact, it only overrides the decision of which registers should be saved by
625the caller, but not how the parameters are passed from the caller to the callee.
626
627For example:
628
629```c
630__attribute__ ((no_caller_saved_registers, fastcall))
631void f (int arg1, int arg2) {
632 ...
633}
634```
635
636In this case parameters 'arg1' and 'arg2' will be passed in registers.
637In this case, on 32-bit x86 targets, the function 'f' will use ECX and EDX as
638register parameters. However, it will not assume any scratch registers and
639should save and restore any modified registers except for ECX and EDX.)reST";
640
641static const char AttrDoc_AnyX86NoCfCheck[] = R"reST(Jump Oriented Programming attacks rely on tampering with addresses used by
642indirect call / jmp, e.g. redirect control-flow to non-programmer
643intended bytes in the binary.
644X86 Supports Indirect Branch Tracking (IBT) as part of Control-Flow
645Enforcement Technology (CET). IBT instruments ENDBR instructions used to
646specify valid targets of indirect call / jmp.
647The `nocf_check` attribute has two roles:
6481\. Appertains to a function - do not add ENDBR instruction at the beginning of
649the function.
6502\. Appertains to a function pointer - do not track the target function of this
651pointer (by adding nocf_check prefix to the indirect-call instruction).)reST";
652
653static const char AttrDoc_ArcWeakrefUnavailable[] = R"reST(No documentation.)reST";
654
655static const char AttrDoc_ArgumentWithTypeTag[] = R"reST(Use `__attribute__((argument_with_type_tag(arg_kind, arg_idx,
656type_tag_idx)))` on a function declaration to specify that the function
657accepts a type tag that determines the type of some other argument.
658
659This attribute is primarily useful for checking arguments of variadic functions
660(`pointer_with_type_tag` can be used in most non-variadic cases).
661
662In the attribute prototype above:
663: - `arg_kind` is an identifier that should be used when annotating all
664 applicable type tags.
665 - `arg_idx` provides the position of a function argument. The expected type of
666 this function argument will be determined by the function argument specified
667 by `type_tag_idx`. In the code example below, "3" means that the type of the
668 function's third argument will be determined by `type_tag_idx`.
669 - `type_tag_idx` provides the position of a function argument. This function
670 argument will be a type tag. The type tag will determine the expected type of
671 the argument specified by `arg_idx`. In the code example below, "2" means
672 that the type tag associated with the function's second argument should agree
673 with the type of the argument specified by `arg_idx`.
674
675For example:
676
677```c++
678int fcntl(int fd, int cmd, ...)
679 __attribute__(( argument_with_type_tag(fcntl,3,2) ));
680// The function's second argument will be a type tag; this type tag will
681// determine the expected type of the function's third argument.
682```)reST";
683
684static const char AttrDoc_ArmAgnostic[] = R"reST(The `__arm_agnostic` keyword applies to prototyped function types and
685affects the function's calling convention for a given state S. This
686attribute allows the user to describe a function that preserves S, without
687requiring the function to share S with its callers and without making
688the assumption that S exists.
689
690If a function has the `__arm_agnostic(S)` attribute and calls a function
691without this attribute, then the function's object code will contain code
692to preserve state S. Otherwise, the function's object code will be the same
693as if it did not have the attribute.
694
695The attribute takes string arguments to describe state S. The supported
696states are:
697
698- `"sme_za_state"` for state enabled by PSTATE.ZA, such as ZA and ZT0.
699
700The attribute `__arm_agnostic("sme_za_state")` cannot be used in conjunction
701with `__arm_in(S)`, `__arm_out(S)`, `__arm_inout(S)` or
702`__arm_preserves(S)` where state S describes state enabled by PSTATE.ZA,
703such as "za" or "zt0".)reST";
704
705static const char AttrDoc_ArmBuiltinAlias[] = R"reST(This attribute is used in the implementation of the ACLE intrinsics.
706It allows the intrinsic functions to
707be declared using the names defined in ACLE, and still be recognized
708as clang builtins equivalent to the underlying name. For example,
709`arm_mve.h` declares the function `vaddq_u32` with
710`__attribute__((__clang_arm_mve_alias(__builtin_arm_mve_vaddq_u32)))`,
711and similarly, one of the type-overloaded declarations of `vaddq`
712will have the same attribute. This ensures that both functions are
713recognized as that clang builtin, and in the latter case, the choice
714of which builtin to identify the function as can be deferred until
715after overload resolution.
716
717This attribute can only be used to set up the aliases for certain Arm
718intrinsic functions; it is intended for use only inside `arm_*.h`
719and is not a general mechanism for declaring arbitrary aliases for
720clang builtin functions.
721
722In order to avoid duplicating the attribute definitions for similar
723purpose for other architecture, there is a general form for the
724attribute `clang_builtin_alias`.)reST";
725
726static const char AttrDoc_ArmIn[] = R"reST(The `__arm_in` keyword applies to prototyped function types and specifies
727that the function shares a given state S with its caller. For `__arm_in`, the
728function takes the state S as input and returns with the state S unchanged.
729
730The attribute takes string arguments to instruct the compiler which state
731is shared. The supported states for S are:
732
733- `"za"` for Matrix Storage (requires SME)
734
735The attributes `__arm_in(S)`, `__arm_out(S)`, `__arm_inout(S)` and
736`__arm_preserves(S)` are all mutually exclusive for the same state S.)reST";
737
738static const char AttrDoc_ArmInOut[] = R"reST(The `__arm_inout` keyword applies to prototyped function types and specifies
739that the function shares a given state S with its caller. For `__arm_inout`,
740the function takes the state S as input and returns new state for S.
741
742The attribute takes string arguments to instruct the compiler which state
743is shared. The supported states for S are:
744
745- `"za"` for Matrix Storage (requires SME)
746
747The attributes `__arm_in(S)`, `__arm_out(S)`, `__arm_inout(S)` and
748`__arm_preserves(S)` are all mutually exclusive for the same state S.)reST";
749
750static const char AttrDoc_ArmLocallyStreaming[] = R"reST(The `__arm_locally_streaming` keyword applies to function declarations
751and specifies that all the statements in the function are executed in
752streaming mode. This means that:
753
754- the function requires that the target processor implements the Scalable Matrix
755 Extension (SME).
756- the program automatically puts the machine into streaming mode before
757 executing the statements and automatically restores the previous mode
758 afterwards.
759
760Clang manages PSTATE.SM automatically; it is not the source code's
761responsibility to do this. For example, Clang will emit code to enable
762streaming mode at the start of the function, and disable streaming mode
763at the end of the function.)reST";
764
765static const char AttrDoc_ArmMveStrictPolymorphism[] = R"reST(This attribute is used in the implementation of the ACLE intrinsics for the Arm
766MVE instruction set. It is used to define the vector types used by the MVE
767intrinsics.
768
769Its effect is to modify the behavior of a vector type with respect to function
770overloading. If a candidate function for overload resolution has a parameter
771type with this attribute, then the selection of that candidate function will be
772disallowed if the actual argument can only be converted via a lax vector
773conversion. The aim is to prevent spurious ambiguity in ARM MVE polymorphic
774intrinsics.
775
776```c++
777void overloaded(uint16x8_t vector, uint16_t scalar);
778void overloaded(int32x4_t vector, int32_t scalar);
779uint16x8_t myVector;
780uint16_t myScalar;
781
782// myScalar is promoted to int32_t as a side effect of the addition,
783// so if lax vector conversions are considered for myVector, then
784// the two overloads are equally good (one argument conversion
785// each). But if the vector has the __clang_arm_mve_strict_polymorphism
786// attribute, only the uint16x8_t,uint16_t overload will match.
787overloaded(myVector, myScalar + 1);
788```
789
790However, this attribute does not prohibit lax vector conversions in contexts
791other than overloading.
792
793```c++
794uint16x8_t function();
795
796// This is still permitted with lax vector conversion enabled, even
797// if the vector types have __clang_arm_mve_strict_polymorphism
798int32x4_t result = function();
799```)reST";
800
801static const char AttrDoc_ArmNew[] = R"reST(The `__arm_new` keyword applies to function declarations and specifies
802that the function will create a new scope for state S.
803
804The attribute takes string arguments to instruct the compiler for which state
805to create new scope. The supported states for S are:
806
807- `"za"` for Matrix Storage (requires SME)
808
809For state `"za"`, this means that:
810
811- the function requires that the target processor implements the Scalable Matrix
812 Extension (SME).
813- the function will commit any lazily saved ZA data.
814- the function will create a new ZA context and enable PSTATE.ZA.
815- the function will disable PSTATE.ZA (by setting it to 0) before returning.
816
817For `__arm_new("za")` functions Clang will set up the ZA context automatically
818on entry to the function and disable it before returning. For example, if ZA is
819in a dormant state Clang will generate the code to commit a lazy-save and set up
820a new ZA state before executing user code.)reST";
821
822static const char AttrDoc_ArmOut[] = R"reST(The `__arm_out` keyword applies to prototyped function types and specifies
823that the function shares a given state S with its caller. For `__arm_out`,
824the function ignores the incoming state for S and returns new state for S.
825
826The attribute takes string arguments to instruct the compiler which state
827is shared. The supported states for S are:
828
829- `"za"` for Matrix Storage (requires SME)
830
831The attributes `__arm_in(S)`, `__arm_out(S)`, `__arm_inout(S)` and
832`__arm_preserves(S)` are all mutually exclusive for the same state S.)reST";
833
834static const char AttrDoc_ArmPreserves[] = R"reST(The `__arm_preserves` keyword applies to prototyped function types and
835specifies that the function does not read a given state S and returns
836with state S unchanged.
837
838The attribute takes string arguments to instruct the compiler which state
839is shared. The supported states for S are:
840
841- `"za"` for Matrix Storage (requires SME)
842
843The attributes `__arm_in(S)`, `__arm_out(S)`, `__arm_inout(S)` and
844`__arm_preserves(S)` are all mutually exclusive for the same state S.)reST";
845
846static const char AttrDoc_ArmStreaming[] = R"reST(The `__arm_streaming` keyword applies to prototyped function types and specifies
847that the function has a "streaming interface". This means that:
848
849- the function requires that the processor implements the Scalable Matrix
850 Extension (SME).
851- the function must be entered in streaming mode (that is, with PSTATE.SM
852 set to 1)
853- the function must return in streaming mode
854
855Clang manages PSTATE.SM automatically; it is not the source code's
856responsibility to do this. For example, if a non-streaming
857function calls an `__arm_streaming` function, Clang generates code
858that switches into streaming mode before calling the function and
859switches back to non-streaming mode on return.)reST";
860
861static const char AttrDoc_ArmStreamingCompatible[] = R"reST(The `__arm_streaming_compatible` keyword applies to prototyped function types and
862specifies that the function has a "streaming compatible interface". This
863means that:
864
865- the function may be entered in either non-streaming mode (PSTATE.SM=0) or
866 in streaming mode (PSTATE.SM=1).
867- the function must return in the same mode as it was entered.
868- the code executed in the function is compatible with either mode.
869
870Clang manages PSTATE.SM automatically; it is not the source code's
871responsibility to do this. Clang will ensure that the generated code in
872streaming-compatible functions is valid in either mode (PSTATE.SM=0 or
873PSTATE.SM=1). For example, if an `__arm_streaming_compatible` function calls a
874non-streaming function, Clang generates code to temporarily switch out of streaming
875mode before calling the function and switch back to streaming-mode on return if
876`PSTATE.SM` is `1` on entry of the caller. If `PSTATE.SM` is `0` on
877entry to the `__arm_streaming_compatible` function, the call will be executed
878without changing modes.)reST";
879
880static const char AttrDoc_Artificial[] = R"reST(The `artificial` attribute can be applied to an inline function. If such a
881function is inlined, the attribute indicates that debuggers should associate
882the resulting instructions with the call site, rather than with the
883corresponding line within the inlined callee.)reST";
884
885static const char AttrDoc_AsmLabel[] = R"reST(This attribute can be used on a function or variable to specify its symbol name.
886
887On some targets, all C symbols are prefixed by default with a single character,
888typically `_`. This was done historically to distinguish them from symbols
889used by other languages. (This prefix is also added to the standard Itanium
890C++ ABI prefix on "mangled" symbol names, so that e.g. on such targets the true
891symbol name for a C++ variable declared as `int cppvar;` would be
892`__Z6cppvar`; note the two underscores.) This prefix is *not* added to the
893symbol names specified by the `__asm` attribute; programmers wishing to match
894a C symbol name must compensate for this.
895
896For example, consider the following C code:
897
898```c
899int var1 __asm("altvar") = 1; // "altvar" in symbol table.
900int var2 = 1; // "_var2" in symbol table.
901
902void func1(void) __asm("altfunc");
903void func1(void) {} // "altfunc" in symbol table.
904void func2(void) {} // "_func2" in symbol table.
905```
906
907Clang's implementation of this attribute is compatible with GCC's, [documented here](https://gcc.gnu.org/onlinedocs/gcc/Asm-Labels.html).
908
909While it is possible to use this attribute to name a special symbol used
910internally by the compiler, such as an LLVM intrinsic, this is neither
911recommended nor supported and may cause the compiler to crash or miscompile.
912Users who wish to gain access to intrinsic behavior are strongly encouraged to
913request new builtin functions.)reST";
914
915static const char AttrDoc_AssertCapability[] = R"reST(Marks a function that dynamically tests whether a capability is held, and halts
916the program if it is not held.)reST";
917
918static const char AttrDoc_AssumeAligned[] = R"reST(Use `__attribute__((assume_aligned(<alignment>[,<offset>]))` on a function
919declaration to specify that the return value of the function (which must be a
920pointer type) has the specified offset, in bytes, from an address with the
921specified alignment. The offset is taken to be zero if omitted.
922
923```c++
924// The returned pointer value has 32-byte alignment.
925void *a() __attribute__((assume_aligned (32)));
926
927// The returned pointer value is 4 bytes greater than an address having
928// 32-byte alignment.
929void *b() __attribute__((assume_aligned (32, 4)));
930```
931
932Note that this attribute provides information to the compiler regarding a
933condition that the code already ensures is true. It does not cause the compiler
934to enforce the provided alignment assumption.)reST";
935
936static const char AttrDoc_Atomic[] = R"reST(The `atomic` attribute can be applied to *compound statements* to override or
937further specify the default atomic code-generation behavior, especially on
938targets such as AMDGPU. You can annotate compound statements with options
939to modify how atomic instructions inside that statement are emitted at the IR
940level.
941
942For details, see the documentation for
943{ref}`@atomic <langext-atomic-code-generation>`)reST";
944
945static const char AttrDoc_Availability[] = R"reST(The `availability` attribute can be placed on declarations to describe the
946lifecycle of that declaration relative to operating system versions. Consider
947the function declaration for a hypothetical function `f`:
948
949```c++
950void f(void) __attribute__((availability(macos,introduced=10.4,deprecated=10.6,obsoleted=10.7)));
951```
952
953The availability attribute states that `f` was introduced in macOS 10.4,
954deprecated in macOS 10.6, and obsoleted in macOS 10.7. This information
955is used by Clang to determine when it is safe to use `f`: for example, if
956Clang is instructed to compile code for macOS 10.5, a call to `f()`
957succeeds. If Clang is instructed to compile code for macOS 10.6, the call
958succeeds but Clang emits a warning specifying that the function is deprecated.
959Finally, if Clang is instructed to compile code for macOS 10.7, the call
960fails because `f()` is no longer available.
961
962Clang is instructed to compile code for a minimum deployment version using
963the `-target` or `-mtargetos` command line arguments. For example,
964macOS 10.7 would be specified as `-target x86_64-apple-macos10.7` or
965`-mtargetos=macos10.7`. Variants like Mac Catalyst are specified as
966`-target arm64-apple-ios15.0-macabi` or `-mtargetos=ios15.0-macabi`
967
968The availability attribute is a comma-separated list starting with the
969platform name and then including clauses specifying important milestones in the
970declaration's lifetime (in any order) along with additional information. Those
971clauses can be:
972
973introduced=*version*
974
975: The first version in which this declaration was introduced.
976
977deprecated=*version*
978
979: The first version in which this declaration was deprecated, meaning that
980 users should migrate away from this API.
981
982obsoleted=*version*
983
984: The first version in which this declaration was obsoleted, meaning that it
985 was removed completely and can no longer be used.
986
987unavailable
988
989: This declaration is never available on this platform.
990
991message=*string-literal*
992
993: Additional message text that Clang will provide when emitting a warning or
994 error about use of a deprecated or obsoleted declaration. Useful to direct
995 users to replacement APIs.
996
997replacement=*string-literal*
998
999: Additional message text that Clang will use to provide Fix-It when emitting
1000 a warning about use of a deprecated declaration. The Fix-It will replace
1001 the deprecated declaration with the new declaration specified.
1002
1003environment=*identifier*
1004
1005: Target environment in which this declaration is available. If present,
1006 the availability attribute applies only to targets with the same platform
1007 and environment. The parameter is currently supported only in HLSL.
1008
1009Multiple availability attributes can be placed on a declaration, which may
1010correspond to different platforms. For most platforms, the availability
1011attribute with the platform corresponding to the target platform will be used;
1012any others will be ignored. However, the availability for `watchOS` and
1013`tvOS` can be implicitly inferred from an `iOS` availability attribute.
1014Any explicit availability attributes for those platforms are still preferred over
1015the implicitly inferred availability attributes. If no availability attribute
1016specifies availability for the current target platform, the availability
1017attributes are ignored. Supported platforms are:
1018
1019`iOS`
1020`macOS`
1021`tvOS`
1022`watchOS`
1023`iOSApplicationExtension`
1024`macOSApplicationExtension`
1025`tvOSApplicationExtension`
1026`watchOSApplicationExtension`
1027`macCatalyst`
1028`macCatalystApplicationExtension`
1029`visionOS`
1030`visionOSApplicationExtension`
1031`driverkit`
1032`anyAppleOS`
1033`swift`
1034`android`
1035`fuchsia`
1036`ohos`
1037`zos`
1038`ShaderModel`
1039
1040Some platforms have alias names:
1041
1042`ios`
1043`macos`
1044`macosx (deprecated)`
1045`tvos`
1046`watchos`
1047`ios_app_extension`
1048`macos_app_extension`
1049`macosx_app_extension (deprecated)`
1050`tvos_app_extension`
1051`watchos_app_extension`
1052`maccatalyst`
1053`maccatalyst_app_extension`
1054`visionos`
1055`visionos_app_extension`
1056`anyappleos`
1057`shadermodel`
1058
1059Supported environment names for the ShaderModel platform:
1060
1061`pixel`
1062`vertex`
1063`geometry`
1064`hull`
1065`domain`
1066`compute`
1067`raygeneration`
1068`intersection`
1069`anyhit`
1070`closesthit`
1071`miss`
1072`callable`
1073`mesh`
1074`amplification`
1075`library`
1076
1077The special platform `anyAppleOS` (alias: `anyappleos`) is a shorthand that
1078applies the availability attribute to all Apple Darwin platforms. An explicit
1079platform-specific availability attribute takes precedence over an `anyAppleOS`
1080attribute for that platform. Versions specified with `anyAppleOS` must be at
1081least 26.0, which is the first OS release where all supported Apple platforms
1082share a unified version number.
1083
1084A declaration can typically be used even when deploying back to a platform
1085version prior to when the declaration was introduced. When this happens, the
1086declaration is [weakly linked](https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPFrameworks/Concepts/WeakLinking.html),
1087as if the `weak_import` attribute were added to the declaration. A
1088weakly-linked declaration may or may not be present a run-time, and a program
1089can determine whether the declaration is present by checking whether the
1090address of that declaration is non-NULL.
1091
1092The flag `strict` disallows using API when deploying back to a
1093platform version prior to when the declaration was introduced. An
1094attempt to use such API before its introduction causes a hard error.
1095Weakly-linking is almost always a better API choice, since it allows
1096users to query availability at runtime.
1097
1098If there are multiple declarations of the same entity, the availability
1099attributes must either match on a per-platform basis or later
1100declarations must not have availability attributes for that
1101platform. For example:
1102
1103```c
1104void g(void) __attribute__((availability(macos,introduced=10.4)));
1105void g(void) __attribute__((availability(macos,introduced=10.4))); // okay, matches
1106void g(void) __attribute__((availability(ios,introduced=4.0))); // okay, adds a new platform
1107void g(void); // okay, inherits both macos and ios availability from above.
1108void g(void) __attribute__((availability(macos,introduced=10.5))); // error: mismatch
1109```
1110
1111When one method overrides another, the overriding method can be more widely available than the overridden method, e.g.,:
1112
1113```objc
1114@interface A
1115- (id)method __attribute__((availability(macos,introduced=10.4)));
1116- (id)method2 __attribute__((availability(macos,introduced=10.4)));
1117@end
1118
1119@interface B : A
1120- (id)method __attribute__((availability(macos,introduced=10.3))); // okay: method moved into base class later
1121- (id)method __attribute__((availability(macos,introduced=10.5))); // error: this method was available via the base class in 10.4
1122@end
1123```
1124
1125Starting with the macOS 10.12 SDK, the `API_AVAILABLE` macro from
1126`<os/availability.h>` can simplify the spelling:
1127
1128```objc
1129@interface A
1130- (id)method API_AVAILABLE(macos(10.11)));
1131- (id)otherMethod API_AVAILABLE(macos(10.11), ios(11.0));
1132@end
1133```
1134
1135Availability attributes can also be applied using a `#pragma clang attribute`.
1136Any explicit availability attribute whose platform corresponds to the target
1137platform is applied to a declaration regardless of the availability attributes
1138specified in the pragma. For example, in the code below,
1139`hasExplicitAvailabilityAttribute` will use the `macOS` availability
1140attribute that is specified with the declaration, whereas
1141`getsThePragmaAvailabilityAttribute` will use the `macOS` availability
1142attribute that is applied by the pragma.
1143
1144```c
1145#pragma clang attribute push (__attribute__((availability(macOS, introduced=10.12))), apply_to=function)
1146void getsThePragmaAvailabilityAttribute(void);
1147void hasExplicitAvailabilityAttribute(void) __attribute__((availability(macos,introduced=10.4)));
1148#pragma clang attribute pop
1149```
1150
1151For platforms like `watchOS` and `tvOS`, whose availability attributes can
1152be implicitly inferred from an `iOS` availability attribute, the logic is
1153slightly more complex. The explicit and the pragma-applied availability
1154attributes whose platform corresponds to the target platform are applied as
1155described in the previous paragraph. However, the implicitly inferred attributes
1156are applied to a declaration only when there is no explicit or pragma-applied
1157availability attribute whose platform corresponds to the target platform. For
1158example, the function below will receive the `tvOS` availability from the
1159pragma rather than using the inferred `iOS` availability from the declaration:
1160
1161```c
1162#pragma clang attribute push (__attribute__((availability(tvOS, introduced=12.0))), apply_to=function)
1163void getsThePragmaTVOSAvailabilityAttribute(void) __attribute__((availability(iOS,introduced=11.0)));
1164#pragma clang attribute pop
1165```
1166
1167The compiler is also able to apply implicitly inferred attributes from a pragma
1168as well. For example, when targeting `tvOS`, the function below will receive
1169a `tvOS` availability attribute that is implicitly inferred from the `iOS`
1170availability attribute applied by the pragma:
1171
1172```c
1173#pragma clang attribute push (__attribute__((availability(iOS, introduced=12.0))), apply_to=function)
1174void infersTVOSAvailabilityFromPragma(void);
1175#pragma clang attribute pop
1176```
1177
1178The implicit attributes that are inferred from explicitly specified attributes
1179whose platform corresponds to the target platform are applied to the declaration
1180even if there is an availability attribute that can be inferred from a pragma.
1181For example, the function below will receive the `tvOS, introduced=11.0`
1182availability that is inferred from the attribute on the declaration rather than
1183inferring availability from the pragma:
1184
1185```c
1186#pragma clang attribute push (__attribute__((availability(iOS, unavailable))), apply_to=function)
1187void infersTVOSAvailabilityFromAttributeNextToDeclaration(void)
1188 __attribute__((availability(iOS,introduced=11.0)));
1189#pragma clang attribute pop
1190```
1191
1192Also see the documentation for
1193{ref}`@available <langext-objective-c-available>`)reST";
1194
1195static const char AttrDoc_AvailableOnlyInDefaultEvalMethod[] = R"reST(No documentation.)reST";
1196
1197static const char AttrDoc_BPFFastCall[] = R"reST(Functions annotated with this attribute are likely to be inlined by BPF JIT.
1198It is assumed that inlined implementation uses less caller saved registers,
1199than a regular function.
1200Specifically, the following registers are likely to be preserved:
1201- `R0` if function return value is `void`;
1202- `R2-R5` if function takes 1 argument;
1203- `R3-R5` if function takes 2 arguments;
1204- `R4-R5` if function takes 3 arguments;
1205- `R5` if function takes 4 arguments;
1206
1207For such functions Clang generates code pattern that allows BPF JIT
1208to recognize and remove unnecessary spills and fills of the preserved
1209registers.)reST";
1210
1211static const char AttrDoc_BPFPreserveAccessIndex[] = R"reST(Clang supports the `__attribute__((preserve_access_index))`
1212attribute for the BPF target. This attribute may be attached to a
1213struct or union declaration, where if -g is specified, it enables
1214preserving struct or union member access debuginfo indices of this
1215struct or union, similar to clang `__builtin_preserve_access_index()`.)reST";
1216
1217static const char AttrDoc_BPFPreserveStaticOffset[] = R"reST(Clang supports the `__attribute__((preserve_static_offset))`
1218attribute for the BPF target. This attribute may be attached to a
1219struct or union declaration. Reading or writing fields of types having
1220such annotation is guaranteed to generate LDX/ST/STX instruction with
1221offset corresponding to the field.
1222
1223For example:
1224
1225```c
1226struct foo {
1227 int a;
1228 int b;
1229};
1230
1231struct bar {
1232 int a;
1233 struct foo b;
1234} __attribute__((preserve_static_offset));
1235
1236void buz(struct bar *g) {
1237 g->b.a = 42;
1238}
1239```
1240
1241The assignment to `g`'s field would produce an ST instruction with
1242offset 8: `*(u32)(r1 + 8) = 42;`.
1243
1244Without this attribute generated instructions might be different,
1245depending on optimizations behavior. E.g. the example above could be
1246rewritten as `r1 += 8; *(u32)(r1 + 0) = 42;`.)reST";
1247
1248static const char AttrDoc_BTFDeclTag[] = R"reST(Clang supports the `__attribute__((btf_decl_tag("ARGUMENT")))` attribute for
1249all targets. This attribute may be attached to a struct/union, struct/union
1250field, function, function parameter, variable or typedef declaration. If -g is
1251specified, the `ARGUMENT` info will be preserved in IR and be emitted to
1252dwarf. For BPF targets, the `ARGUMENT` info will be emitted to .BTF ELF
1253section too.)reST";
1254
1255static const char AttrDoc_BTFTypeTag[] = R"reST(Clang supports the `__attribute__((btf_type_tag("ARGUMENT")))` attribute for
1256all targets. It only has effect when `-g` is specified on the command line.
1257
1258The attribute can be applied to a pointer type, in which case the tag is
1259associated with the pointee type, e.g.:
1260
1261```c
1262int __attribute__((btf_type_tag("tag"))) *p;
1263```
1264
1265It can also be applied to the underlying type of a typedef, in which case the
1266tag follows the typedef down to its base type, e.g.:
1267
1268```c
1269typedef struct foo __attribute__((btf_type_tag("tag"))) foo_t;
1270```
1271
1272The following is the corresponding btf:
1273
1274```
1275...
1276[2] TYPE_TAG 'tag' type_id=4
1277[3] TYPEDEF 'foo_t' type_id=2
1278[4] STRUCT 'foo' size=4 vlen=1
1279 'c' type_id=5 bits_offset=0
1280[5] INT 'int' size=4 bits_offset=0 nr_bits=32 encoding=SIGNED
1281...
1282```
1283
1284The attribute is currently silently ignored in any other position (note: this
1285scenario may be diagnosed in the future).
1286
1287The `ARGUMENT` string will be preserved in IR and emitted to DWARF for the
1288types used in variable declarations, function declarations, or typedef
1289declarations.
1290
1291For BPF targets, the `ARGUMENT` string will also be emitted to .BTF ELF
1292section.)reST";
1293
1294static const char AttrDoc_Blocking[] = R"reST(Declares that a function potentially blocks, and prevents any potential inference of `nonblocking`
1295by the compiler.)reST";
1296
1297static const char AttrDoc_Blocks[] = R"reST(No documentation.)reST";
1298
1299static const char AttrDoc_Builtin[] = R"reST()reST";
1300
1301static const char AttrDoc_BuiltinAlias[] = R"reST(This attribute is used in the implementation of the C intrinsics.
1302It allows the C intrinsic functions to be declared using the names defined
1303in target builtins, and still be recognized as clang builtins equivalent to the
1304underlying name. For example, `riscv_vector.h` declares the function `vadd`
1305with `__attribute__((clang_builtin_alias(__builtin_rvv_vadd_vv_i8m1)))`.
1306This ensures that both functions are recognized as that clang builtin,
1307and in the latter case, the choice of which builtin to identify the
1308function as can be deferred until after overload resolution.
1309
1310This attribute can only be used to set up the aliases for certain ARM/RISC-V
1311C intrinsic functions; it is intended for use only inside `arm_*.h` and
1312`riscv_*.h` and is not a general mechanism for declaring arbitrary aliases
1313for clang builtin functions.)reST";
1314
1315static const char AttrDoc_C11NoReturn[] = R"reST(A function declared as `_Noreturn` shall not return to its caller. The
1316compiler will generate a diagnostic for a function declared as `_Noreturn`
1317that appears to be capable of returning to its caller. Despite being a type
1318specifier, the `_Noreturn` attribute cannot be specified on a function
1319pointer type.)reST";
1320
1321static const char AttrDoc_CDecl[] = R"reST(No documentation.)reST";
1322
1323static const char AttrDoc_CFAuditedTransfer[] = R"reST(No documentation.)reST";
1324
1325static const char AttrDoc_CFConsumed[] = R"reST(The behavior of a function with respect to reference counting for Foundation
1326(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
1327convention (e.g. functions starting with "get" are assumed to return at
1328`+0`).
1329
1330It can be overridden using a family of the following attributes. In
1331Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
1332a function communicates that the object is returned at `+1`, and the caller
1333is responsible for freeing it.
1334Similarly, the annotation `__attribute__((ns_returns_not_retained))`
1335specifies that the object is returned at `+0` and the ownership remains with
1336the callee.
1337The annotation `__attribute__((ns_consumes_self))` specifies that
1338the Objective-C method call consumes the reference to `self`, e.g. by
1339attaching it to a supplied parameter.
1340Additionally, parameters can have an annotation
1341`__attribute__((ns_consumed))`, which specifies that passing an owned object
1342as that parameter effectively transfers the ownership, and the caller is no
1343longer responsible for it.
1344These attributes affect code generation when interacting with ARC code, and
1345they are used by the Clang Static Analyzer.
1346
1347In C programs using CoreFoundation, a similar set of attributes:
1348`__attribute__((cf_returns_not_retained))`,
1349`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
1350have the same respective semantics when applied to CoreFoundation objects.
1351These attributes affect code generation when interacting with ARC code, and
1352they are used by the Clang Static Analyzer.
1353
1354Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
1355the same attribute family is present:
1356`__attribute__((os_returns_not_retained))`,
1357`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
1358with the same respective semantics.
1359Similar to `__attribute__((ns_consumes_self))`,
1360`__attribute__((os_consumes_this))` specifies that the method call consumes
1361the reference to "this" (e.g., when attaching it to a different object supplied
1362as a parameter).
1363Out parameters (parameters the function is meant to write into,
1364either via pointers-to-pointers or references-to-pointers)
1365may be annotated with `__attribute__((os_returns_retained))`
1366or `__attribute__((os_returns_not_retained))` which specifies that the object
1367written into the out parameter should (or respectively should not) be released
1368after use.
1369Since often out parameters may or may not be written depending on the exit
1370code of the function,
1371annotations `__attribute__((os_returns_retained_on_zero))`
1372and `__attribute__((os_returns_retained_on_non_zero))` specify that
1373an out parameter at `+1` is written if and only if the function returns a zero
1374(respectively non-zero) error code.
1375Observe that return-code-dependent out parameter annotations are only
1376available for retained out parameters, as non-retained object do not have to be
1377released by the callee.
1378These attributes are only used by the Clang Static Analyzer.
1379
1380The family of attributes `X_returns_X_retained` can be added to functions,
1381C++ methods, and Objective-C methods and properties.
1382Attributes `X_consumed` can be added to parameters of methods, functions,
1383and Objective-C methods.)reST";
1384
1385static const char AttrDoc_CFGuard[] = R"reST(Code can indicate CFG checks are not wanted with the `__declspec(guard(nocf))`
1386attribute. This directs the compiler to not insert any CFG checks for the entire
1387function. This approach is typically used only sparingly in specific situations
1388where the programmer has manually inserted "CFG-equivalent" protection. The
1389programmer knows that they are calling through some read-only function table
1390whose address is obtained through read-only memory references and for which the
1391index is masked to the function table limit. This approach may also be applied
1392to small wrapper functions that are not inlined and that do nothing more than
1393make a call through a function pointer. Since incorrect usage of this directive
1394can compromise the security of CFG, the programmer must be very careful using
1395the directive. Typically, this usage is limited to very small functions that
1396only call one function.
1397
1398`Control Flow Guard documentation <https://docs.microsoft.com/en-us/windows/win32/secbp/pe-metadata>`)reST";
1399
1400static const char AttrDoc_CFICanonicalJumpTable[] = R"reST(Use `__attribute__((cfi_canonical_jump_table))` on a function declaration to
1401make the function's CFI jump table canonical. See {ref}`the CFI documentation
1402<cfi-canonical-jump-tables>` for more details.)reST";
1403
1404static const char AttrDoc_CFISalt[] = R"reST(The `cfi_salt` attribute specifies a string literal that is used as a salt
1405for Control-Flow Integrity (CFI) checks to distinguish between functions with
1406the same type signature. This attribute can be applied to function declarations,
1407function definitions, and function pointer typedefs.
1408
1409The attribute prevents function pointers from being replaced with pointers to
1410functions that have a compatible type, which can be a CFI bypass vector.
1411
1412**Syntax:**
1413
1414- GNU-style: `__attribute__((cfi_salt("<salt_string>")))`
1415- C++11-style: `[[clang::cfi_salt("<salt_string>")]]`
1416
1417**Usage:**
1418
1419The attribute takes a single string literal argument that serves as the salt.
1420Functions or function types with different salt values will have different CFI
1421hashes, even if they have identical type signatures.
1422
1423**Motivation:**
1424
1425In large codebases like the Linux kernel, there are often hundreds of functions
1426with identical type signatures that are called indirectly:
1427
1428```
14291662 functions with void (*)(void)
14301179 functions with int (*)(void)
1431 ...
1432```
1433
1434By salting the CFI hashes, you can make CFI more robust by ensuring that
1435functions intended for different purposes have distinct CFI identities.
1436
1437**Type Compatibility:**
1438
1439- Functions with different salt values are considered to have incompatible types
1440- Function pointers with different salt values cannot be assigned to each other
1441- All declarations of the same function must use the same salt value
1442
1443**Example:**
1444
1445```c
1446// Header file - define convenience macros
1447#define __cfi_salt(s) __attribute__((cfi_salt(s)))
1448
1449// Typedef for regular function pointers
1450typedef int (*fptr_t)(void);
1451
1452// Typedef for salted function pointers
1453typedef int (*fptr_salted_t)(void) __cfi_salt("pepper");
1454
1455struct widget_ops {
1456 fptr_t init; // Regular CFI
1457 fptr_salted_t exec; // Salted CFI
1458 fptr_t cleanup; // Regular CFI
1459};
1460
1461// Function implementations
1462static int widget_init(void) { return 0; }
1463static int widget_exec(void) __cfi_salt("pepper") { return 1; }
1464static int widget_cleanup(void) { return 0; }
1465
1466static struct widget_ops ops = {
1467 .init = widget_init, // OK - compatible types
1468 .exec = widget_exec, // OK - both use "pepper" salt
1469 .cleanup = widget_cleanup // OK - compatible types
1470};
1471
1472// Using C++11 attribute syntax
1473void secure_callback(void) [[clang::cfi_salt("secure")]];
1474
1475// This would cause a compilation error:
1476// fptr_t bad_ptr = widget_exec; // Error: incompatible types
1477```
1478
1479**Notes:**
1480
1481- The salt string can contain non-NULL ASCII characters, including spaces and
1482 quotes
1483- This attribute only applies to function types; using it on non-function
1484 types will generate a warning
1485- All declarations and definitions of the same function must use identical
1486 salt values
1487- The attribute affects type compatibility during compilation and CFI hash
1488 generation during code generation)reST";
1489
1490static const char AttrDoc_CFIUncheckedCallee[] = R"reST(`cfi_unchecked_callee` is a function type attribute which prevents the
1491compiler from instrumenting
1492{doc}`Control Flow Integrity <ControlFlowIntegrity>` checks on indirect
1493function calls. This also includes control flow checks added by
1494`-fsanitize=function`; see {ref}`Available checks <ubsan-checks>`.
1495Specifically, the attribute has the following semantics:
1496
14971. Indirect calls to a function type with this attribute will not be instrumented with CFI. That is,
1498 the indirect call will not be checked. Note that this only changes the behavior for indirect calls
1499 on pointers to function types having this attribute. It does not prevent all indirect function calls
1500 for a given type from being checked.
15012. All direct references to a function whose type has this attribute will always reference the
1502 function definition rather than an entry in the CFI jump table.
15033. When a pointer to a function with this attribute is implicitly cast to a pointer to a function
1504 without this attribute, the compiler will give a warning saying this attribute is discarded. This
1505 warning can be silenced with an explicit cast. Note an explicit cast just disables the warning, so
1506 direct references to a function with a `cfi_unchecked_callee` attribute will still reference the
1507 function definition rather than the CFI jump table.
1508
1509```c
1510#define CFI_UNCHECKED_CALLEE __attribute__((cfi_unchecked_callee))
1511
1512void no_cfi() CFI_UNCHECKED_CALLEE {}
1513
1514void (*with_cfi)() = no_cfi; // warning: implicit conversion discards `cfi_unchecked_callee` attribute.
1515 // `with_cfi` also points to the actual definition of `no_cfi` rather than
1516 // its jump table entry.
1517
1518void invoke(void (CFI_UNCHECKED_CALLEE *func)()) {
1519 func(); // CFI will not instrument this indirect call.
1520
1521 void (*func2)() = func; // warning: implicit conversion discards `cfi_unchecked_callee` attribute.
1522
1523 func2(); // CFI will instrument this indirect call. Users should be careful however because if this
1524 // references a function with type `cfi_unchecked_callee`, then the CFI check may incorrectly
1525 // fail because the reference will be to the function definition rather than the CFI jump
1526 // table entry.
1527}
1528```
1529
1530This attribute can only be applied on functions or member functions. This attribute can be a good
1531alternative to `no_sanitize("cfi")` if you only want to disable innstrumentation for specific indirect
1532calls rather than applying `no_sanitize("cfi")` on the whole function containing indirect call. Note
1533that `cfi_unchecked_attribute` is a type attribute doesn't disable CFI instrumentation on a function
1534body.)reST";
1535
1536static const char AttrDoc_CFReturnsNotRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
1537(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
1538convention (e.g. functions starting with "get" are assumed to return at
1539`+0`).
1540
1541It can be overridden using a family of the following attributes. In
1542Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
1543a function communicates that the object is returned at `+1`, and the caller
1544is responsible for freeing it.
1545Similarly, the annotation `__attribute__((ns_returns_not_retained))`
1546specifies that the object is returned at `+0` and the ownership remains with
1547the callee.
1548The annotation `__attribute__((ns_consumes_self))` specifies that
1549the Objective-C method call consumes the reference to `self`, e.g. by
1550attaching it to a supplied parameter.
1551Additionally, parameters can have an annotation
1552`__attribute__((ns_consumed))`, which specifies that passing an owned object
1553as that parameter effectively transfers the ownership, and the caller is no
1554longer responsible for it.
1555These attributes affect code generation when interacting with ARC code, and
1556they are used by the Clang Static Analyzer.
1557
1558In C programs using CoreFoundation, a similar set of attributes:
1559`__attribute__((cf_returns_not_retained))`,
1560`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
1561have the same respective semantics when applied to CoreFoundation objects.
1562These attributes affect code generation when interacting with ARC code, and
1563they are used by the Clang Static Analyzer.
1564
1565Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
1566the same attribute family is present:
1567`__attribute__((os_returns_not_retained))`,
1568`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
1569with the same respective semantics.
1570Similar to `__attribute__((ns_consumes_self))`,
1571`__attribute__((os_consumes_this))` specifies that the method call consumes
1572the reference to "this" (e.g., when attaching it to a different object supplied
1573as a parameter).
1574Out parameters (parameters the function is meant to write into,
1575either via pointers-to-pointers or references-to-pointers)
1576may be annotated with `__attribute__((os_returns_retained))`
1577or `__attribute__((os_returns_not_retained))` which specifies that the object
1578written into the out parameter should (or respectively should not) be released
1579after use.
1580Since often out parameters may or may not be written depending on the exit
1581code of the function,
1582annotations `__attribute__((os_returns_retained_on_zero))`
1583and `__attribute__((os_returns_retained_on_non_zero))` specify that
1584an out parameter at `+1` is written if and only if the function returns a zero
1585(respectively non-zero) error code.
1586Observe that return-code-dependent out parameter annotations are only
1587available for retained out parameters, as non-retained object do not have to be
1588released by the callee.
1589These attributes are only used by the Clang Static Analyzer.
1590
1591The family of attributes `X_returns_X_retained` can be added to functions,
1592C++ methods, and Objective-C methods and properties.
1593Attributes `X_consumed` can be added to parameters of methods, functions,
1594and Objective-C methods.)reST";
1595
1596static const char AttrDoc_CFReturnsRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
1597(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
1598convention (e.g. functions starting with "get" are assumed to return at
1599`+0`).
1600
1601It can be overridden using a family of the following attributes. In
1602Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
1603a function communicates that the object is returned at `+1`, and the caller
1604is responsible for freeing it.
1605Similarly, the annotation `__attribute__((ns_returns_not_retained))`
1606specifies that the object is returned at `+0` and the ownership remains with
1607the callee.
1608The annotation `__attribute__((ns_consumes_self))` specifies that
1609the Objective-C method call consumes the reference to `self`, e.g. by
1610attaching it to a supplied parameter.
1611Additionally, parameters can have an annotation
1612`__attribute__((ns_consumed))`, which specifies that passing an owned object
1613as that parameter effectively transfers the ownership, and the caller is no
1614longer responsible for it.
1615These attributes affect code generation when interacting with ARC code, and
1616they are used by the Clang Static Analyzer.
1617
1618In C programs using CoreFoundation, a similar set of attributes:
1619`__attribute__((cf_returns_not_retained))`,
1620`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
1621have the same respective semantics when applied to CoreFoundation objects.
1622These attributes affect code generation when interacting with ARC code, and
1623they are used by the Clang Static Analyzer.
1624
1625Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
1626the same attribute family is present:
1627`__attribute__((os_returns_not_retained))`,
1628`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
1629with the same respective semantics.
1630Similar to `__attribute__((ns_consumes_self))`,
1631`__attribute__((os_consumes_this))` specifies that the method call consumes
1632the reference to "this" (e.g., when attaching it to a different object supplied
1633as a parameter).
1634Out parameters (parameters the function is meant to write into,
1635either via pointers-to-pointers or references-to-pointers)
1636may be annotated with `__attribute__((os_returns_retained))`
1637or `__attribute__((os_returns_not_retained))` which specifies that the object
1638written into the out parameter should (or respectively should not) be released
1639after use.
1640Since often out parameters may or may not be written depending on the exit
1641code of the function,
1642annotations `__attribute__((os_returns_retained_on_zero))`
1643and `__attribute__((os_returns_retained_on_non_zero))` specify that
1644an out parameter at `+1` is written if and only if the function returns a zero
1645(respectively non-zero) error code.
1646Observe that return-code-dependent out parameter annotations are only
1647available for retained out parameters, as non-retained object do not have to be
1648released by the callee.
1649These attributes are only used by the Clang Static Analyzer.
1650
1651The family of attributes `X_returns_X_retained` can be added to functions,
1652C++ methods, and Objective-C methods and properties.
1653Attributes `X_consumed` can be added to parameters of methods, functions,
1654and Objective-C methods.)reST";
1655
1656static const char AttrDoc_CFUnknownTransfer[] = R"reST(No documentation.)reST";
1657
1658static const char AttrDoc_CPUDispatch[] = R"reST(The `cpu_specific` and `cpu_dispatch` attributes are used to define and
1659resolve multiversioned functions. This form of multiversioning provides a
1660mechanism for declaring versions across translation units and manually
1661specifying the resolved function list. A specified CPU defines a set of minimum
1662features that are required for the function to be called. The result of this is
1663that future processors execute the most restrictive version of the function the
1664new processor can execute.
1665
1666In addition, unlike the ICC implementation of this feature, the selection of the
1667version does not consider the manufacturer or microarchitecture of the processor.
1668It tests solely the list of features that are both supported by the specified
1669processor and present in the compiler-rt library. This can be surprising at times,
1670as the runtime processor may be from a completely different manufacturer, as long
1671as it supports the same feature set.
1672
1673This can additionally be surprising, as some processors are indistringuishable from
1674others based on the list of testable features. When this happens, the variant
1675is selected in an unspecified manner.
1676
1677Function versions are defined with `cpu_specific`, which takes one or more CPU
1678names as a parameter. For example:
1679
1680```c
1681// Declares and defines the ivybridge version of single_cpu.
1682__attribute__((cpu_specific(ivybridge)))
1683void single_cpu(void){}
1684
1685// Declares and defines the atom version of single_cpu.
1686__attribute__((cpu_specific(atom)))
1687void single_cpu(void){}
1688
1689// Declares and defines both the ivybridge and atom version of multi_cpu.
1690__attribute__((cpu_specific(ivybridge, atom)))
1691void multi_cpu(void){}
1692```
1693
1694A dispatching (or resolving) function can be declared anywhere in a project's
1695source code with `cpu_dispatch`. This attribute takes one or more CPU names
1696as a parameter (like `cpu_specific`). Functions marked with `cpu_dispatch`
1697are not expected to be defined, only declared. If such a marked function has a
1698definition, any side effects of the function are ignored; trivial function
1699bodies are permissible for ICC compatibility.
1700
1701```c
1702// Creates a resolver for single_cpu above.
1703__attribute__((cpu_dispatch(ivybridge, atom)))
1704void single_cpu(void){}
1705
1706// Creates a resolver for multi_cpu, but adds a 3rd version defined in another
1707// translation unit.
1708__attribute__((cpu_dispatch(ivybridge, atom, sandybridge)))
1709void multi_cpu(void){}
1710```
1711
1712Note that it is possible to have a resolving function that dispatches based on
1713more or fewer options than are present in the program. Specifying fewer will
1714result in the omitted options not being considered during resolution. Specifying
1715a version for resolution that isn't defined in the program will result in a
1716linking failure.
1717
1718It is also possible to specify a CPU name of `generic` which will be resolved
1719if the executing processor doesn't satisfy the features required in the CPU
1720name. The behavior of a program executing on a processor that doesn't satisfy
1721any option of a multiversioned function is undefined.)reST";
1722
1723static const char AttrDoc_CPUSpecific[] = R"reST(The `cpu_specific` and `cpu_dispatch` attributes are used to define and
1724resolve multiversioned functions. This form of multiversioning provides a
1725mechanism for declaring versions across translation units and manually
1726specifying the resolved function list. A specified CPU defines a set of minimum
1727features that are required for the function to be called. The result of this is
1728that future processors execute the most restrictive version of the function the
1729new processor can execute.
1730
1731In addition, unlike the ICC implementation of this feature, the selection of the
1732version does not consider the manufacturer or microarchitecture of the processor.
1733It tests solely the list of features that are both supported by the specified
1734processor and present in the compiler-rt library. This can be surprising at times,
1735as the runtime processor may be from a completely different manufacturer, as long
1736as it supports the same feature set.
1737
1738This can additionally be surprising, as some processors are indistringuishable from
1739others based on the list of testable features. When this happens, the variant
1740is selected in an unspecified manner.
1741
1742Function versions are defined with `cpu_specific`, which takes one or more CPU
1743names as a parameter. For example:
1744
1745```c
1746// Declares and defines the ivybridge version of single_cpu.
1747__attribute__((cpu_specific(ivybridge)))
1748void single_cpu(void){}
1749
1750// Declares and defines the atom version of single_cpu.
1751__attribute__((cpu_specific(atom)))
1752void single_cpu(void){}
1753
1754// Declares and defines both the ivybridge and atom version of multi_cpu.
1755__attribute__((cpu_specific(ivybridge, atom)))
1756void multi_cpu(void){}
1757```
1758
1759A dispatching (or resolving) function can be declared anywhere in a project's
1760source code with `cpu_dispatch`. This attribute takes one or more CPU names
1761as a parameter (like `cpu_specific`). Functions marked with `cpu_dispatch`
1762are not expected to be defined, only declared. If such a marked function has a
1763definition, any side effects of the function are ignored; trivial function
1764bodies are permissible for ICC compatibility.
1765
1766```c
1767// Creates a resolver for single_cpu above.
1768__attribute__((cpu_dispatch(ivybridge, atom)))
1769void single_cpu(void){}
1770
1771// Creates a resolver for multi_cpu, but adds a 3rd version defined in another
1772// translation unit.
1773__attribute__((cpu_dispatch(ivybridge, atom, sandybridge)))
1774void multi_cpu(void){}
1775```
1776
1777Note that it is possible to have a resolving function that dispatches based on
1778more or fewer options than are present in the program. Specifying fewer will
1779result in the omitted options not being considered during resolution. Specifying
1780a version for resolution that isn't defined in the program will result in a
1781linking failure.
1782
1783It is also possible to specify a CPU name of `generic` which will be resolved
1784if the executing processor doesn't satisfy the features required in the CPU
1785name. The behavior of a program executing on a processor that doesn't satisfy
1786any option of a multiversioned function is undefined.)reST";
1787
1788static const char AttrDoc_CUDAClusterDims[] = R"reST(In CUDA/HIP programming, the `cluster_dims` attribute, conventionally exposed as the
1789`__cluster_dims__` macro, can be applied to a kernel function to set the dimensions of a
1790thread block cluster, which is an optional level of hierarchy and made up of thread blocks.
1791`__cluster_dims__` defines the cluster size as `(X, Y, Z)`, where each value is the number
1792of thread blocks in that dimension. The `cluster_dims` and `no_cluster` attributes are
1793mutually exclusive.
1794
1795```
1796__global__ __cluster_dims__(2, 1, 1) void kernel(...) {
1797 ...
1798}
1799```)reST";
1800
1801static const char AttrDoc_CUDAConstant[] = R"reST(No documentation.)reST";
1802
1803static const char AttrDoc_CUDADevice[] = R"reST(No documentation.)reST";
1804
1805static const char AttrDoc_CUDADeviceBuiltinSurfaceType[] = R"reST(The `device_builtin_surface_type` attribute can be applied to a class
1806template when declaring the surface reference. A surface reference variable
1807could be accessed on the host side and, on the device side, might be translated
1808into an internal surface object, which is established through surface bind and
1809unbind runtime APIs.)reST";
1810
1811static const char AttrDoc_CUDADeviceBuiltinTextureType[] = R"reST(The `device_builtin_texture_type` attribute can be applied to a class
1812template when declaring the texture reference. A texture reference variable
1813could be accessed on the host side and, on the device side, might be translated
1814into an internal texture object, which is established through texture bind and
1815unbind runtime APIs.)reST";
1816
1817static const char AttrDoc_CUDAGlobal[] = R"reST(No documentation.)reST";
1818
1819static const char AttrDoc_CUDAGridConstant[] = R"reST(The `__grid_constant__` attribute can be applied to a `const`-qualified kernel
1820function argument and allows compiler to take the address of that argument without
1821making a copy. The argument applies to sm_70 or newer GPUs, during compilation
1822with CUDA-11.7(PTX 7.7) or newer, and is ignored otherwise.)reST";
1823
1824static const char AttrDoc_CUDAHost[] = R"reST(No documentation.)reST";
1825
1826static const char AttrDoc_CUDAInvalidTarget[] = R"reST()reST";
1827
1828static const char AttrDoc_CUDALaunchBounds[] = R"reST(The ``__launch_bounds__`` attribute (also spelled ``launch_bounds``) originates
1829in CUDA. It informs the compiler of the launch configuration a kernel will be
1830dispatched with, allowing it to optimize the kernel accordingly. It takes the
1831form ``__launch_bounds__(<max-threads-per-block>[,
1832<min-blocks-per-multiprocessor>[, <max-blocks-per-cluster>]])``. All arguments
1833are constant expressions.
1834
1835The attribute only takes effect on ``__global__`` (kernel) functions; like
1836NVCC, Clang ignores it on any other function.
1837
1838``<max-threads-per-block>`` specifies the maximum number of threads per block
1839the kernel will be launched with. ``<min-blocks-per-multiprocessor>`` specifies
1840the desired minimum number of blocks resident per multiprocessor, and
1841``<max-blocks-per-cluster>`` the maximum number of blocks per cluster.
1842
1843For the NVPTX target, ``<max-threads-per-block>`` and
1844``<min-blocks-per-multiprocessor>`` map to the ``.maxntid`` and ``.minnctapersm``
1845PTX directives, respectively, and ``<max-blocks-per-cluster>`` (which requires
1846``sm_90`` or newer) maps to ``.maxclusterrank``.
1847
1848For the AMDGPU target, the attribute is translated into the equivalent AMDGPU
1849kernel attributes:
1850
1851 - ``<max-threads-per-block>`` sets the maximum
1852 ``amdgpu_flat_work_group_size`` (as ``1, <max-threads-per-block>``).
1853 - ``<min-blocks-per-multiprocessor>`` sets the minimum
1854 ``amdgpu_waves_per_eu``. Note that HIP reinterprets this CUDA argument as a
1855 minimum number of waves per execution unit, so its meaning differs from the
1856 NVPTX interpretation.
1857 - ``<max-blocks-per-cluster>`` is currently ignored.
1858
1859An explicit ``amdgpu_flat_work_group_size`` or ``amdgpu_waves_per_eu`` attribute
1860takes precedence over the value derived from ``__launch_bounds__``.
1861
1862When the same kernel is declared multiple times, the launch bounds from the most
1863recent declaration that specifies them are used; a definition without
1864``__launch_bounds__`` inherits the bounds from an earlier declaration.)reST";
1865
1866static const char AttrDoc_CUDANoCluster[] = R"reST(In CUDA/HIP programming, a kernel function can still be launched with the cluster feature enabled
1867at runtime, even without being annotated with `__cluster_dims__`. The LLVM/Clang-exclusive
1868`no_cluster` attribute, conventionally exposed as the `__no_cluster__` macro, can be applied to
1869a kernel function to explicitly indicate that the cluster feature will not be enabled either at
1870compile time or at kernel launch time. This allows the compiler to apply certain optimizations
1871without assuming that clustering could be enabled at runtime. It is undefined behavior to launch a
1872kernel annotated with `__no_cluster__` if the cluster feature is enabled at runtime.
1873The `cluster_dims` and `no_cluster` attributes are mutually exclusive.
1874
1875```
1876__global__ __no_cluster__ void kernel(...) {
1877 ...
1878}
1879```)reST";
1880
1881static const char AttrDoc_CUDAShared[] = R"reST(No documentation.)reST";
1882
1883static const char AttrDoc_CXX11NoReturn[] = R"reST(A function declared as `[[noreturn]]` shall not return to its caller. The
1884compiler will generate a diagnostic for a function declared as `[[noreturn]]`
1885that appears to be capable of returning to its caller.
1886
1887The `[[_Noreturn]]` spelling is deprecated and only exists to ease code
1888migration for code using `[[noreturn]]` after including `<stdnoreturn.h>`.)reST";
1889
1890static const char AttrDoc_CXXAssume[] = R"reST(The `assume` attribute is used to indicate to the optimizer that a
1891certain condition is assumed to be true at a certain point in the
1892program. If this condition is violated at runtime, the behavior is
1893undefined. `assume` can only be applied to a null statement.
1894
1895Different optimisers are likely to react differently to the presence of
1896this attribute; in some cases, adding `assume` may affect performance
1897negatively. It should be used with parsimony and care.
1898
1899Example:
1900
1901```c++
1902int f(int x, int y) {
1903 [[assume(x == 27)]];
1904 [[assume(x == y)]];
1905 return y + 1; // May be optimised to `return 28`.
1906}
1907```)reST";
1908
1909static const char AttrDoc_CallableWhen[] = R"reST(Use `__attribute__((callable_when(...)))` to indicate what states a method
1910may be called in. Valid states are unconsumed, consumed, or unknown. Each
1911argument to this attribute must be a quoted string. E.g.:
1912
1913`__attribute__((callable_when("unconsumed", "unknown")))`)reST";
1914
1915static const char AttrDoc_Callback[] = R"reST(The `callback` attribute specifies that the annotated function may invoke the
1916specified callback zero or more times. The callback, as well as the passed
1917arguments, are identified by their parameter name or position (starting with
19181!) in the annotated function. The first position in the attribute identifies
1919the callback callee, the following positions declare describe its arguments.
1920The callback callee is required to be callable with the number, and order, of
1921the specified arguments. The index `0`, or the identifier `this`, is used to
1922represent an implicit "this" pointer in class methods. If there is no implicit
1923"this" pointer it shall not be referenced. The index '-1', or the name "\_\_",
1924represents an unknown callback callee argument. This can be a value which is
1925not present in the declared parameter list, or one that is, but is potentially
1926inspected, captured, or modified. Parameter names and indices can be mixed in
1927the callback attribute.
1928
1929The `callback` attribute, which is directly translated to `callback`
1930metadata \<<http://llvm.org/docs/LangRef.html#callback-metadata>>, make the
1931connection between the call to the annotated function and the callback callee.
1932This can enable interprocedural optimizations which were otherwise impossible.
1933If a function parameter is mentioned in the `callback` attribute, through its
1934position, it is undefined if that parameter is used for anything other than the
1935actual callback. Inspected, captured, or modified parameters shall not be
1936listed in the `callback` metadata.
1937
1938Example encodings for the callback performed by `pthread_create` are shown
1939below. The explicit attribute annotation indicates that the third parameter
1940(`start_routine`) is called zero or more times by the `pthread_create` function,
1941and that the fourth parameter (`arg`) is passed along. Note that the callback
1942behavior of `pthread_create` is automatically recognized by Clang. In addition,
1943the declarations of `__kmpc_fork_teams` and `__kmpc_fork_call`, generated for
1944`#pragma omp target teams` and `#pragma omp parallel`, respectively, are also
1945automatically recognized as broker functions. Further functions might be added
1946in the future.
1947
1948```c
1949__attribute__((callback (start_routine, arg)))
1950int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
1951 void *(*start_routine) (void *), void *arg);
1952
1953__attribute__((callback (3, 4)))
1954int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
1955 void *(*start_routine) (void *), void *arg);
1956```)reST";
1957
1958static const char AttrDoc_CalledOnce[] = R"reST(The `called_once` attribute specifies that the annotated function or method
1959parameter is invoked exactly once on all execution paths. It only applies
1960to parameters with function-like types, i.e. function pointers or blocks. This
1961concept is particularly useful for asynchronous programs.
1962
1963Clang implements a check for `called_once` parameters,
1964`-Wcalled-once-parameter`. It is on by default and finds the following
1965violations:
1966
1967- Parameter is not called at all.
1968- Parameter is called more than once.
1969- Parameter is not called on one of the execution paths.
1970
1971In the latter case, Clang pinpoints the path where parameter is not invoked
1972by showing the control-flow statement where the path diverges.
1973
1974```objc
1975void fooWithCallback(void (^callback)(void) __attribute__((called_once))) {
1976 if (somePredicate()) {
1977 ...
1978 callback();
1979 } else {
1980 callback(); // OK: callback is called on every path
1981 }
1982}
1983
1984void barWithCallback(void (^callback)(void) __attribute__((called_once))) {
1985 if (somePredicate()) {
1986 ...
1987 callback(); // note: previous call is here
1988 }
1989 callback(); // warning: callback is called twice
1990}
1991
1992void foobarWithCallback(void (^callback)(void) __attribute__((called_once))) {
1993 if (somePredicate()) { // warning: callback is not called when condition is false
1994 ...
1995 callback();
1996 }
1997}
1998```
1999
2000This attribute is useful for API developers who want to double-check if they
2001implemented their method correctly.)reST";
2002
2003static const char AttrDoc_Capability[] = R"reST(No documentation.)reST";
2004
2005static const char AttrDoc_CapturedRecord[] = R"reST()reST";
2006
2007static const char AttrDoc_Cleanup[] = R"reST(This attribute allows a function to be run when a local variable goes out of
2008scope. The attribute takes the identifier of a function with a parameter type
2009that is a pointer to the type with the attribute.
2010
2011```c
2012static void foo (int *) { ... }
2013static void bar (int *) { ... }
2014void baz (void) {
2015 int x __attribute__((cleanup(foo)));
2016 {
2017 int y __attribute__((cleanup(bar)));
2018 }
2019}
2020```
2021
2022The above example will result in a call to `bar` being passed the address of
2023`y` when `y` goes out of scope, then a call to `foo` being passed the
2024address of `x` when `x` goes out of scope. If two or more variables share
2025the same scope, their `cleanup` callbacks are invoked in the reverse order
2026the variables were declared in. It is not possible to check the return value
2027(if any) of these `cleanup` callback functions.)reST";
2028
2029static const char AttrDoc_ClspvLibclcBuiltin[] = R"reST(Attribute used by [clspv][clspv] (OpenCL-C to Vulkan SPIR-V compiler) to identify functions coming from [libclc][libclc] (OpenCL-C builtin library).
2030
2031```c
2032void __attribute__((clspv_libclc_builtin)) libclc_builtin() {}
2033```
2034
2035[clspv]: https://github.com/google/clspv
2036[libclc]: https://libclc.llvm.org)reST";
2037
2038static const char AttrDoc_CmseNSCall[] = R"reST(This attribute declares a non-secure function type. When compiling for secure
2039state, a call to such a function would switch from secure to non-secure state.
2040All non-secure function calls must happen only through a function pointer, and
2041a non-secure function type should only be used as a base type of a pointer.
2042See [ARMv8-M Security Extensions: Requirements on Development
2043Tools - Engineering Specification Documentation](https://developer.arm.com/docs/ecm0359818/latest/) for more information.)reST";
2044
2045static const char AttrDoc_CmseNSEntry[] = R"reST(This attribute declares a function that can be called from non-secure state, or
2046from secure state. Entering from and returning to non-secure state would switch
2047to and from secure state, respectively, and prevent flow of information
2048to non-secure state, except via return values. See [ARMv8-M Security Extensions:
2049Requirements on Development Tools - Engineering Specification Documentation](https://developer.arm.com/docs/ecm0359818/latest/) for more information.)reST";
2050
2051static const char AttrDoc_CodeAlign[] = R"reST(The `clang::code_align(N)` attribute applies to a loop and specifies the byte
2052alignment for a loop. The attribute accepts a positive integer constant
2053initialization expression indicating the number of bytes for the minimum
2054alignment boundary. Its value must be a power of 2, between 1 and 4096
2055(inclusive).
2056
2057```c++
2058void foo() {
2059 int var = 0;
2060 [[clang::code_align(16)]] for (int i = 0; i < 10; ++i) var++;
2061}
2062
2063void Array(int *array, size_t n) {
2064 [[clang::code_align(64)]] for (int i = 0; i < n; ++i) array[i] = 0;
2065}
2066
2067void count () {
2068 int a1[10], int i = 0;
2069 [[clang::code_align(32)]] while (i < 10) { a1[i] += 3; }
2070}
2071
2072void check() {
2073 int a = 10;
2074 [[clang::code_align(8)]] do {
2075 a = a + 1;
2076 } while (a < 20);
2077}
2078
2079template<int A>
2080void func() {
2081 [[clang::code_align(A)]] for(;;) { }
2082}
2083```)reST";
2084
2085static const char AttrDoc_CodeModel[] = R"reST(The `model` attribute allows overriding the translation unit's
2086code model (specified by `-mcmodel`) for a specific global variable.
2087
2088On LoongArch, allowed values are "normal", "medium", "extreme".
2089
2090On x86-64, allowed values are `"small"` and `"large"`. `"small"` is
2091roughly equivalent to `-mcmodel=small`, meaning the global is considered
2092"small" placed closer to the `.text` section relative to "large" globals, and
2093to prefer using 32-bit relocations to access the global. `"large"` is roughly
2094equivalent to `-mcmodel=large`, meaning the global is considered "large" and
2095placed further from the `.text` section relative to "small" globals, and
209664-bit relocations must be used to access the global.)reST";
2097
2098static const char AttrDoc_CodeSeg[] = R"reST(The `__declspec(code_seg)` attribute enables the placement of code into separate
2099named segments that can be paged or locked in memory individually. This attribute
2100is used to control the placement of instantiated templates and compiler-generated
2101code. See the documentation for [\_\_declspec(code_seg)][__declspec(code_seg)] on MSDN.
2102
2103[__declspec(code_seg)]: http://msdn.microsoft.com/en-us/library/dn636922.aspx)reST";
2104
2105static const char AttrDoc_Cold[] = R"reST(`__attribute__((cold))` marks a function as cold, as a manual alternative to PGO hotness data.
2106If PGO data is available, the profile count based hotness overrides the `__attribute__((cold))` annotation (unlike `__attribute__((hot))`).)reST";
2107
2108static const char AttrDoc_Common[] = R"reST(No documentation.)reST";
2109
2110static const char AttrDoc_Const[] = R"reST(No documentation.)reST";
2111
2112static const char AttrDoc_ConstInit[] = R"reST(This attribute specifies that the variable to which it is attached is intended
2113to have a [constant initializer](http://en.cppreference.com/w/cpp/language/constant_initialization)
2114according to the rules of [basic.start.static]. The variable is required to
2115have static or thread storage duration. If the initialization of the variable
2116is not a constant initializer an error will be produced. This attribute may
2117only be used in C++; the `constinit` spelling is only accepted in C++20
2118onwards.
2119
2120Note that in C++03 strict constant expression checking is not done. Instead
2121the attribute reports if Clang can emit the variable as a constant, even if it's
2122not technically a 'constant initializer'. This behavior is non-portable.
2123
2124Static storage duration variables with constant initializers avoid hard-to-find
2125bugs caused by the indeterminate order of dynamic initialization. They can also
2126be safely used during dynamic initialization across translation units.
2127
2128This attribute acts as a compile time assertion that the requirements
2129for constant initialization have been met. Since these requirements change
2130between dialects and have subtle pitfalls it's important to fail fast instead
2131of silently falling back on dynamic initialization.
2132
2133The first use of the attribute on a variable must be part of, or precede, the
2134initializing declaration of the variable. C++20 requires the `constinit`
2135spelling of the attribute to be present on the initializing declaration if it
2136is used anywhere. The other spellings can be specified on a forward declaration
2137and omitted on a later initializing declaration.
2138
2139```c++
2140// -std=c++14
2141#define SAFE_STATIC [[clang::require_constant_initialization]]
2142struct T {
2143 constexpr T(int) {}
2144 ~T(); // non-trivial
2145};
2146SAFE_STATIC T x = {42}; // Initialization OK. Doesn't check destructor.
2147SAFE_STATIC T y = 42; // error: variable does not have a constant initializer
2148// copy initialization is not a constant expression on a non-literal type.
2149```)reST";
2150
2151static const char AttrDoc_Constructor[] = R"reST(The `constructor` attribute causes the function to be called before entering
2152`main()`, and the `destructor` attribute causes the function to be called
2153after returning from `main()` or when the `exit()` function has been
2154called. Note, `quick_exit()`, `_Exit()`, and `abort()` prevent a function
2155marked `destructor` from being called.
2156
2157The constructor or destructor function should not accept any arguments and its
2158return type should be `void`.
2159
2160The attributes accept an optional argument used to specify the priority order
2161in which to execute constructor and destructor functions. The priority is
2162given as an integer constant expression between 101 and 65535 (inclusive).
2163Priorities outside of that range are reserved for use by the implementation. A
2164lower value indicates a higher priority of initialization. Note that only the
2165relative ordering of values is important. For example:
2166
2167```c++
2168__attribute__((constructor(200))) void foo(void);
2169__attribute__((constructor(101))) void bar(void);
2170```
2171
2172`bar()` will be called before `foo()`, and both will be called before
2173`main()`. If no argument is given to the `constructor` or `destructor`
2174attribute, they default to the value `65535`.)reST";
2175
2176static const char AttrDoc_Consumable[] = R"reST(Each `class` that uses any of the typestate annotations must first be marked
2177using the `consumable` attribute. Failure to do so will result in a warning.
2178
2179This attribute accepts a single parameter that must be one of the following:
2180`unknown`, `consumed`, or `unconsumed`.)reST";
2181
2182static const char AttrDoc_ConsumableAutoCast[] = R"reST(No documentation.)reST";
2183
2184static const char AttrDoc_ConsumableSetOnRead[] = R"reST(No documentation.)reST";
2185
2186static const char AttrDoc_Convergent[] = R"reST(The `convergent` attribute can be placed on a function declaration. It is
2187translated into the LLVM `convergent` attribute, which indicates that the call
2188instructions of a function with this attribute cannot be made control-dependent
2189on any additional values.
2190
2191This attribute is different from `noduplicate` because it allows duplicating
2192function calls if it can be proved that the duplicated function calls are
2193not made control-dependent on any additional values, e.g., unrolling a loop
2194executed by all work items.
2195
2196Sample usage:
2197
2198```c
2199void convfunc(void) __attribute__((convergent));
2200// Setting it as a C++11 attribute is also valid in a C++ program.
2201// void convfunc(void) [[clang::convergent]];
2202```)reST";
2203
2204static const char AttrDoc_CoroAwaitElidable[] = R"reST(The `[[clang::coro_await_elidable]]` is a class attribute which can be
2205applied to a coroutine return type. It provides a hint to the compiler to apply
2206Heap Allocation Elision more aggressively.
2207
2208When a coroutine function returns such a type, a direct call expression therein
2209that returns a prvalue of a type attributed `[[clang::coro_await_elidable]]`
2210is said to be under a safe elide context if one of the following is true:
2211
2212- it is the immediate right-hand side operand to a co_await expression.
2213- it is an argument to a `[[clang::coro_await_elidable_argument]]` parameter
2214 or parameter pack of another direct call expression under a safe elide context.
2215
2216Do note that the safe elide context applies only to the call expression itself,
2217and the context does not transitively include any of its subexpressions unless
2218exceptional rules of `[[clang::coro_await_elidable_argument]]` apply.
2219
2220The compiler performs heap allocation elision on call expressions under a safe
2221elide context, if the callee is a coroutine.
2222
2223Example:
2224
2225```c++
2226class [[clang::coro_await_elidable]] Task { ... };
2227
2228Task foo();
2229Task bar() {
2230 co_await foo(); // foo()'s coroutine frame on this line is elidable
2231 auto t = foo(); // foo()'s coroutine frame on this line is NOT elidable
2232 co_await t;
2233}
2234```
2235
2236Such elision replaces the heap allocated activation frame of the callee coroutine
2237with a local variable within the enclosing braces in the caller's stack frame.
2238The local variable, like other variables in coroutines, may be collected into the
2239coroutine frame, which may be allocated on the heap. The behavior is undefined
2240if the caller coroutine is destroyed earlier than the callee coroutine.)reST";
2241
2242static const char AttrDoc_CoroAwaitElidableArgument[] = R"reST(The `[[clang::coro_await_elidable_argument]]` is a function parameter attribute.
2243It works in conjunction with `[[clang::coro_await_elidable]]` to propagate a
2244safe elide context to a parameter or parameter pack if the function is called
2245under a safe elide context.
2246
2247This is sometimes necessary on utility functions used to compose or modify the
2248behavior of a callee coroutine.
2249
2250Example:
2251
2252```c++
2253template <typename T>
2254class [[clang::coro_await_elidable]] Task { ... };
2255
2256template <typename... T>
2257class [[clang::coro_await_elidable]] WhenAll { ... };
2258
2259// `when_all` is a utility function that composes coroutines. It does not
2260// need to be a coroutine to propagate.
2261template <typename... T>
2262WhenAll<T...> when_all([[clang::coro_await_elidable_argument]] Task<T> tasks...);
2263
2264Task<int> foo();
2265Task<int> bar();
2266Task<void> example1() {
2267 // `when_all`, `foo`, and `bar` are all elide safe because `when_all` is
2268 // under a safe elide context and, thanks to the [[clang::coro_await_elidable_argument]]
2269 // attribute, such context is propagated to foo and bar.
2270 co_await when_all(foo(), bar());
2271}
2272
2273Task<void> example2() {
2274 // `when_all` and `bar` are elide safe. `foo` is not elide safe.
2275 auto f = foo();
2276 co_await when_all(f, bar());
2277}
2278
2279
2280Task<void> example3() {
2281 // None of the calls are elide safe.
2282 auto t = when_all(foo(), bar());
2283 co_await t;
2284}
2285```)reST";
2286
2287static const char AttrDoc_CoroDisableLifetimeBound[] = R"reST(The `[[clang::coro_lifetimebound]]` is a class attribute which can be applied
2288to a coroutine return type ([coro_return_type, coro_wrapper]) (i.e.
2289it should also be annotated with `[[clang::coro_return_type]]`).
2290
2291All parameters of a function are considered to be lifetime bound if the function returns a
2292coroutine return type (CRT) annotated with `[[clang::coro_lifetimebound]]`.
2293This lifetime bound analysis can be disabled for a coroutine wrapper or a coroutine by annotating the function
2294with `[[clang::coro_disable_lifetimebound]]` function attribute .
2295See documentation of [lifetimebound] for details about lifetime bound analysis.
2296
2297Reference parameters of a coroutine are susceptible to capturing references to temporaries or local variables.
2298
2299For example,
2300
2301```c++
2302task<int> coro(const int& a) { co_return a + 1; }
2303task<int> dangling_refs(int a) {
2304 // `coro` captures reference to a temporary. `foo` would now contain a dangling reference to `a`.
2305 auto foo = coro(1);
2306 // `coro` captures reference to local variable `a` which is destroyed after the return.
2307 return coro(a);
2308}
2309```
2310
2311Lifetime bound static analysis can be used to detect such instances when coroutines capture references
2312which may die earlier than the coroutine frame itself. In the above example, if the CRT `task` is annotated with
2313`[[clang::coro_lifetimebound]]`, then lifetime bound analysis would detect capturing reference to
2314temporaries or return address of a local variable.
2315
2316Both coroutines and coroutine wrappers are part of this analysis.
2317
2318```c++
2319template <typename T> struct [[clang::coro_return_type, clang::coro_lifetimebound]] Task {
2320 using promise_type = some_promise_type;
2321};
2322
2323Task<int> coro(const int& a) { co_return a + 1; }
2324[[clang::coro_wrapper]] Task<int> coro_wrapper(const int& a, const int& b) {
2325 return a > b ? coro(a) : coro(b);
2326}
2327Task<int> temporary_reference() {
2328 auto foo = coro(1); // warning: capturing reference to a temporary which would die after the expression.
2329
2330 int a = 1;
2331 auto bar = coro_wrapper(a, 0); // warning: `b` captures reference to a temporary.
2332
2333 co_return co_await coro(1); // fine.
2334}
2335[[clang::coro_wrapper]] Task<int> stack_reference(int a) {
2336 return coro(a); // warning: returning address of stack variable `a`.
2337}
2338```
2339
2340This analysis can be disabled for all calls to a particular function by annotating the function
2341with function attribute `[[clang::coro_disable_lifetimebound]]`.
2342For example, this could be useful for coroutine wrappers which accept reference parameters
2343but do not pass them to the underlying coroutine or pass them by value.
2344
2345```c++
2346Task<int> coro(int a) { co_return a + 1; }
2347[[clang::coro_wrapper, clang::coro_disable_lifetimebound]] Task<int> coro_wrapper(const int& a) {
2348 return coro(a + 1);
2349}
2350void use() {
2351 auto task = coro_wrapper(1); // use of temporary is fine as the argument is not lifetime bound.
2352}
2353```)reST";
2354
2355static const char AttrDoc_CoroLifetimeBound[] = R"reST(The `[[clang::coro_lifetimebound]]` is a class attribute which can be applied
2356to a coroutine return type ([coro_return_type, coro_wrapper]) (i.e.
2357it should also be annotated with `[[clang::coro_return_type]]`).
2358
2359All parameters of a function are considered to be lifetime bound if the function returns a
2360coroutine return type (CRT) annotated with `[[clang::coro_lifetimebound]]`.
2361This lifetime bound analysis can be disabled for a coroutine wrapper or a coroutine by annotating the function
2362with `[[clang::coro_disable_lifetimebound]]` function attribute .
2363See documentation of [lifetimebound] for details about lifetime bound analysis.
2364
2365Reference parameters of a coroutine are susceptible to capturing references to temporaries or local variables.
2366
2367For example,
2368
2369```c++
2370task<int> coro(const int& a) { co_return a + 1; }
2371task<int> dangling_refs(int a) {
2372 // `coro` captures reference to a temporary. `foo` would now contain a dangling reference to `a`.
2373 auto foo = coro(1);
2374 // `coro` captures reference to local variable `a` which is destroyed after the return.
2375 return coro(a);
2376}
2377```
2378
2379Lifetime bound static analysis can be used to detect such instances when coroutines capture references
2380which may die earlier than the coroutine frame itself. In the above example, if the CRT `task` is annotated with
2381`[[clang::coro_lifetimebound]]`, then lifetime bound analysis would detect capturing reference to
2382temporaries or return address of a local variable.
2383
2384Both coroutines and coroutine wrappers are part of this analysis.
2385
2386```c++
2387template <typename T> struct [[clang::coro_return_type, clang::coro_lifetimebound]] Task {
2388 using promise_type = some_promise_type;
2389};
2390
2391Task<int> coro(const int& a) { co_return a + 1; }
2392[[clang::coro_wrapper]] Task<int> coro_wrapper(const int& a, const int& b) {
2393 return a > b ? coro(a) : coro(b);
2394}
2395Task<int> temporary_reference() {
2396 auto foo = coro(1); // warning: capturing reference to a temporary which would die after the expression.
2397
2398 int a = 1;
2399 auto bar = coro_wrapper(a, 0); // warning: `b` captures reference to a temporary.
2400
2401 co_return co_await coro(1); // fine.
2402}
2403[[clang::coro_wrapper]] Task<int> stack_reference(int a) {
2404 return coro(a); // warning: returning address of stack variable `a`.
2405}
2406```
2407
2408This analysis can be disabled for all calls to a particular function by annotating the function
2409with function attribute `[[clang::coro_disable_lifetimebound]]`.
2410For example, this could be useful for coroutine wrappers which accept reference parameters
2411but do not pass them to the underlying coroutine or pass them by value.
2412
2413```c++
2414Task<int> coro(int a) { co_return a + 1; }
2415[[clang::coro_wrapper, clang::coro_disable_lifetimebound]] Task<int> coro_wrapper(const int& a) {
2416 return coro(a + 1);
2417}
2418void use() {
2419 auto task = coro_wrapper(1); // use of temporary is fine as the argument is not lifetime bound.
2420}
2421```)reST";
2422
2423static const char AttrDoc_CoroOnlyDestroyWhenComplete[] = R"reST(The `coro_only_destroy_when_complete` attribute should be marked on a C++ class. The coroutines
2424whose return type is marked with the attribute are assumed to be destroyed only after the coroutine has
2425reached the final suspend point.
2426
2427This is helpful for the optimizers to reduce the size of the destroy function for the coroutines.
2428
2429For example,
2430
2431```c++
2432A foo() {
2433 dtor d;
2434 co_await something();
2435 dtor d1;
2436 co_await something();
2437 dtor d2;
2438 co_return 43;
2439}
2440```
2441
2442The compiler may generate the following pseudocode:
2443
2444```c++
2445void foo.destroy(foo.Frame *frame) {
2446 switch(frame->suspend_index()) {
2447 case 1:
2448 frame->d.~dtor();
2449 break;
2450 case 2:
2451 frame->d.~dtor();
2452 frame->d1.~dtor();
2453 break;
2454 case 3:
2455 frame->d.~dtor();
2456 frame->d1.~dtor();
2457 frame->d2.~dtor();
2458 break;
2459 default: // coroutine completed or haven't started
2460 break;
2461 }
2462
2463 frame->promise.~promise_type();
2464 delete frame;
2465}
2466```
2467
2468The `foo.destroy()` function's purpose is to release all of the resources
2469initialized for the coroutine when it is destroyed in a suspended state.
2470However, if the coroutine is only ever destroyed at the final suspend state,
2471the rest of the conditions are superfluous.
2472
2473The user can use the `coro_only_destroy_when_complete` attributo suppress
2474generation of the other destruction cases, optimizing the above `foo.destroy` to:
2475
2476```c++
2477void foo.destroy(foo.Frame *frame) {
2478 frame->promise.~promise_type();
2479 delete frame;
2480}
2481```)reST";
2482
2483static const char AttrDoc_CoroReturnType[] = R"reST(The `[[clang::coro_return_type]]` attribute is used to help static analyzers to recognize
2484coroutines from the function signatures.
2485
2486The `coro_return_type` attribute should be marked on a C++ class to mark it as
2487a **coroutine return type (CRT)**.
2488
2489A function `R func(P1, .., PN)` has a coroutine return type (CRT) `R` if `R`
2490is marked by `[[clang::coro_return_type]]` and `R` has a promise type associated to it
2491(i.e., std::coroutine_traits\<R, P1, .., PN>::promise_type is a valid promise type).
2492
2493If the return type of a function is a `CRT` then the function must be a coroutine.
2494Otherwise the program is invalid. It is allowed for a non-coroutine to return a `CRT`
2495if the function is marked with `[[clang::coro_wrapper]]`.
2496
2497The `[[clang::coro_wrapper]]` attribute should be marked on a C++ function to mark it as
2498a **coroutine wrapper**. A coroutine wrapper is a function which returns a `CRT`,
2499is not a coroutine itself and is marked with `[[clang::coro_wrapper]]`.
2500
2501Clang will enforce that all functions that return a `CRT` are either coroutines or marked
2502with `[[clang::coro_wrapper]]`. Clang will enforce this with an error.
2503
2504From a language perspective, it is not possible to differentiate between a coroutine and a
2505function returning a CRT by merely looking at the function signature.
2506
2507Coroutine wrappers, in particular, are susceptible to capturing
2508references to temporaries and other lifetime issues. This allows to avoid such lifetime
2509issues with coroutine wrappers.
2510
2511For example,
2512
2513```c++
2514// This is a CRT.
2515template <typename T> struct [[clang::coro_return_type]] Task {
2516 using promise_type = some_promise_type;
2517};
2518
2519Task<int> increment(int a) { co_return a + 1; } // Fine. This is a coroutine.
2520Task<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
2525void 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```
2531
2532Note: `a_promise_type::get_return_object` is exempted from this analysis as it is a necessary
2533implementation detail of any coroutine library.)reST";
2534
2535static const char AttrDoc_CoroWrapper[] = R"reST(The `[[clang::coro_return_type]]` attribute is used to help static analyzers to recognize
2536coroutines from the function signatures.
2537
2538The `coro_return_type` attribute should be marked on a C++ class to mark it as
2539a **coroutine return type (CRT)**.
2540
2541A function `R func(P1, .., PN)` has a coroutine return type (CRT) `R` if `R`
2542is marked by `[[clang::coro_return_type]]` and `R` has a promise type associated to it
2543(i.e., std::coroutine_traits\<R, P1, .., PN>::promise_type is a valid promise type).
2544
2545If the return type of a function is a `CRT` then the function must be a coroutine.
2546Otherwise the program is invalid. It is allowed for a non-coroutine to return a `CRT`
2547if the function is marked with `[[clang::coro_wrapper]]`.
2548
2549The `[[clang::coro_wrapper]]` attribute should be marked on a C++ function to mark it as
2550a **coroutine wrapper**. A coroutine wrapper is a function which returns a `CRT`,
2551is not a coroutine itself and is marked with `[[clang::coro_wrapper]]`.
2552
2553Clang will enforce that all functions that return a `CRT` are either coroutines or marked
2554with `[[clang::coro_wrapper]]`. Clang will enforce this with an error.
2555
2556From a language perspective, it is not possible to differentiate between a coroutine and a
2557function returning a CRT by merely looking at the function signature.
2558
2559Coroutine wrappers, in particular, are susceptible to capturing
2560references to temporaries and other lifetime issues. This allows to avoid such lifetime
2561issues with coroutine wrappers.
2562
2563For example,
2564
2565```c++
2566// This is a CRT.
2567template <typename T> struct [[clang::coro_return_type]] Task {
2568 using promise_type = some_promise_type;
2569};
2570
2571Task<int> increment(int a) { co_return a + 1; } // Fine. This is a coroutine.
2572Task<int> foo() { return increment(1); } // Error. foo is not a coroutine.
2573
2574// Fine for a coroutine wrapper to return a CRT.
2575[[clang::coro_wrapper]] Task<int> foo() { return increment(1); }
2576
2577void bar() {
2578 // Invalid. This intantiates a function which returns a CRT but is not marked as
2579 // a coroutine wrapper.
2580 std::function<Task<int>(int)> f = increment;
2581}
2582```
2583
2584Note: `a_promise_type::get_return_object` is exempted from this analysis as it is a necessary
2585implementation detail of any coroutine library.)reST";
2586
2587static const char AttrDoc_CountedBy[] = R"reST(The `counted_by` attribute is applied to a pointer or flexible array member to
2588indicate that the pointer points to (or the flexible array member contains) at
2589least the number of *elements* given by the attribute's argument.
2590
2591This attribute is used by {doc}`-fbounds-safety <BoundsSafety>` to propagate
2592bounds information on API surfaces without any ABI changes. This attribute is
2593also used to improve the results of the array bound sanitizer and the
2594`__builtin_dynamic_object_size` builtin.
2595
2596Because the size of the pointee type must be known to compute the pointer's
2597bounds, such a pointer must not be used while its pointee type is incomplete; a
2598pointer to a forward-declared type is accepted on fields annotated with
2599`counted_by`, but the type must be completed before the pointer is used. If
2600the pointee type can never be completed, `counted_by` is rejected and
2601`sized_by` should be used instead. `void *` is a special case: as a GNU
2602extension (diagnosed by `-Wgnu-pointer-arith`), `counted_by` is accepted on
2603it, where it behaves like `sized_by` (the argument is treated as a byte count,
2604`void` having an assumed size of one byte).
2605
2606A pointer annotated with `counted_by` must have a count of zero when it is
2607null. This requirement is currently only enforced when compiling with
2608{doc}`-fbounds-safety <BoundsSafety>` (see {ref}`Current status of
2609-fbounds-safety support in upstream Clang <bounds-safety-current-upstream-status>`). Use
2610`counted_by_or_null` for a pointer that may be null while carrying a nonzero
2611count.
2612
2613#### Keeping pointer and count in sync
2614
2615The `counted_by` attribute establishes a relationship between the annotated
2616pointer and its count: the pointer must point to at least `count` elements.
2617Assigning to only one of them can break this relationship.
2618Without {doc}`-fbounds-safety <BoundsSafety>`, it is the programmer's
2619responsibility to ensure the pointer and count remain in sync. With
2620`-fbounds-safety` it is automatically enforced. For example:
2621
2622```c
2623struct buffer {
2624 int *buf __attribute__((counted_by(count)));
2625 size_t count;
2626};
2627
2628void grow(struct buffer *b, size_t new_count) {
2629 // b->buf isn't updated. The underlying memory pointed to by b->buf might be
2630 // smaller than new_count which would contradict the counted_by attribute.
2631 // Compile error with -fbounds-safety but allowed without -fbounds-safety.
2632 b->count = new_count;
2633}
2634```
2635
2636Updating both together - so that `buf` points to `count` elements - keeps
2637the attribute true. For example:
2638
2639```c
2640void grow(struct buffer *b, size_t new_count) {
2641 // Allowed by -fbounds-safety
2642 int *new_buf = malloc(new_count * sizeof(int));
2643 // -fbounds-safety enforces that the `new_buf` points to at least `new_count`
2644 // integers at runtime. Without -fbounds-safety nothing enforces this.
2645 b->buf = new_buf;
2646 b->count = new_count;
2647}
2648```
2649
2650#### Flexible array members
2651
2652The `counted_by` attribute may also be applied to the flexible array member of
2653a structure in C. In this case the argument names the field member holding the
2654count of elements in the flexible array; that field must be within the same
2655non-anonymous, enclosing struct as the flexible array member.
2656
2657This example specifies that the flexible array member `array` has the number
2658of elements allocated for it in `count`:
2659
2660```c
2661struct bar;
2662
2663struct foo {
2664 size_t count;
2665 char other;
2666 struct bar *array[] __attribute__((counted_by(count)));
2667};
2668```
2669
2670This establishes a relationship between `array` and `count`. Specifically,
2671`array` must have at least `count` number of elements available. It's the
2672user's responsibility to ensure that this relationship is maintained through
2673changes to the structure.
2674
2675In the following example, the allocated array erroneously has fewer elements
2676than what's specified by `p->count`. This would result in an out-of-bounds
2677access not being detected.
2678
2679```c
2680#define SIZE_INCR 42
2681
2682struct foo *p;
2683
2684void foo_alloc(size_t count) {
2685 p = malloc(MAX(sizeof(struct foo),
2686 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
2687 p->count = count + SIZE_INCR;
2688}
2689```
2690
2691The next example updates `p->count`, but breaks the relationship requirement
2692that `p->array` must have at least `p->count` number of elements available:
2693
2694```c
2695#define SIZE_INCR 42
2696
2697struct foo *p;
2698
2699void foo_alloc(size_t count) {
2700 p = malloc(MAX(sizeof(struct foo),
2701 offsetof(struct foo, array[0]) + count * sizeof(struct bar *)));
2702 p->count = count;
2703}
2704
2705void use_foo(int index, int val) {
2706 p->count += SIZE_INCR + 1; /* 'count' is now larger than the number of elements of 'array'. */
2707 p->array[index] = val; /* The sanitizer can't properly check this access. */
2708}
2709```
2710
2711In this example, an update to `p->count` maintains the relationship
2712requirement:
2713
2714```c
2715void use_foo(int index, int val) {
2716 if (p->count == 0)
2717 return;
2718 --p->count;
2719 p->array[index] = val;
2720}
2721```)reST";
2722
2723static const char AttrDoc_CountedByOrNull[] = R"reST(The `counted_by_or_null` attribute is applied to a pointer to indicate that,
2724if the pointer is non-null, it points to memory containing at least the number
2725of *elements* given by the attribute's argument. If the pointer is null, the
2726value of the argument is ignored and the pointer points to zero elements.
2727
2728The `counted_by_or_null` attribute is identical to `counted_by` except that
2729it treats null pointers differently and cannot be applied to a flexible array
2730member. Whereas `counted_by` requires a null pointer to have a count of zero,
2731`counted_by_or_null` allows the pointer to be null regardless of the value of
2732the count. This supports the common idiom where a pointer is either null or
2733points to memory containing at least the given number of elements.
2734
2735Currently only {doc}`-fbounds-safety <BoundsSafety>` makes use of the
2736distinction between `counted_by_or_null` and `counted_by` (see
2737{ref}`Current status of -fbounds-safety support in upstream Clang
2738<bounds-safety-current-upstream-status>`).)reST";
2739
2740static const char AttrDoc_DLLExport[] = R"reST(The `__declspec(dllexport)` attribute declares a variable, function, or
2741Objective-C interface to be exported from the module. It is available under the
2742`-fdeclspec` flag for compatibility with various compilers. The primary use
2743is for COFF object files which explicitly specify what interfaces are available
2744for external use. See the [dllexport][dllexport] documentation on MSDN for more
2745information.
2746
2747[dllexport]: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx)reST";
2748
2749static const char AttrDoc_DLLExportOnDecl[] = R"reST()reST";
2750
2751static const char AttrDoc_DLLExportStaticLocal[] = R"reST()reST";
2752
2753static const char AttrDoc_DLLImport[] = R"reST(The `__declspec(dllimport)` attribute declares a variable, function, or
2754Objective-C interface to be imported from an external module. It is available
2755under the `-fdeclspec` flag for compatibility with various compilers. The
2756primary use is for COFF object files which explicitly specify what interfaces
2757are imported from external modules. See the [dllimport][dllimport] documentation on MSDN
2758for more information.
2759
2760Note that a dllimport function may still be inlined, if its definition is
2761available and it doesn't reference any non-dllimport functions or global
2762variables.
2763
2764[dllimport]: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx)reST";
2765
2766static const char AttrDoc_DLLImportStaticLocal[] = R"reST()reST";
2767
2768static const char AttrDoc_Deprecated[] = R"reST(The `deprecated` attribute can be applied to a function, a variable, or a
2769type. This is useful when identifying functions, variables, or types that are
2770expected to be removed in a future version of a program.
2771
2772Consider the function declaration for a hypothetical function `f`:
2773
2774```c++
2775void f(void) __attribute__((deprecated("message", "replacement")));
2776```
2777
2778When spelled as `__attribute__((deprecated))`, the deprecated attribute can have
2779two optional string arguments. The first one is the message to display when
2780emitting the warning; the second one enables the compiler to provide a Fix-It
2781to replace the deprecated name with a new name. Otherwise, when spelled as
2782`[[gnu::deprecated]]` or `[[deprecated]]`, the attribute can have one optional
2783string argument which is the message to display when emitting the warning.)reST";
2784
2785static const char AttrDoc_Destructor[] = R"reST(The `constructor` attribute causes the function to be called before entering
2786`main()`, and the `destructor` attribute causes the function to be called
2787after returning from `main()` or when the `exit()` function has been
2788called. Note, `quick_exit()`, `_Exit()`, and `abort()` prevent a function
2789marked `destructor` from being called.
2790
2791The constructor or destructor function should not accept any arguments and its
2792return type should be `void`.
2793
2794The attributes accept an optional argument used to specify the priority order
2795in which to execute constructor and destructor functions. The priority is
2796given as an integer constant expression between 101 and 65535 (inclusive).
2797Priorities outside of that range are reserved for use by the implementation. A
2798lower value indicates a higher priority of initialization. Note that only the
2799relative ordering of values is important. For example:
2800
2801```c++
2802__attribute__((constructor(200))) void foo(void);
2803__attribute__((constructor(101))) void bar(void);
2804```
2805
2806`bar()` will be called before `foo()`, and both will be called before
2807`main()`. If no argument is given to the `constructor` or `destructor`
2808attribute, they default to the value `65535`.)reST";
2809
2810static const char AttrDoc_DeviceKernel[] = R"reST(These attributes specify that the function represents a kernel for device offloading.
2811The specific semantics depend on the offloading language, target, and attribute spelling.
2812Here is a code example using the attribute to mark a function as a kernel:
2813
2814```c++
2815[[clang::device_kernel]] int foo(int x) { return ++x; }
2816```)reST";
2817
2818static const char AttrDoc_DiagnoseAsBuiltin[] = R"reST(The `diagnose_as_builtin` attribute indicates that Fortify diagnostics are to
2819be applied to the declared function as if it were the function specified by the
2820attribute. The builtin function whose diagnostics are to be mimicked should be
2821given. In addition, the order in which arguments should be applied must also
2822be given.
2823
2824For example, the attribute can be used as follows.
2825
2826```c
2827__attribute__((diagnose_as_builtin(__builtin_memset, 3, 2, 1)))
2828void *mymemset(int n, int c, void *s) {
2829 // ...
2830}
2831```
2832
2833This indicates that calls to `mymemset` should be diagnosed as if they were
2834calls to `__builtin_memset`. The arguments `3, 2, 1` indicate by index the
2835order in which arguments of `mymemset` should be applied to
2836`__builtin_memset`. The third argument should be applied first, then the
2837second, and then the first. Thus (when Fortify warnings are enabled) the call
2838`mymemset(n, c, s)` will diagnose overflows as if it were the call
2839`__builtin_memset(s, c, n)`.
2840
2841For variadic functions, the variadic arguments must come in the same order as
2842they would to the builtin function, after all normal arguments. For instance,
2843to diagnose a new function as if it were `sscanf`, we can use the attribute as
2844follows.
2845
2846```c
2847__attribute__((diagnose_as_builtin(sscanf, 1, 2)))
2848int mysscanf(const char *str, const char *format, ...) {
2849 // ...
2850}
2851```
2852
2853Then the call `mysscanf("abc def", "%4s %4s", buf1, buf2)` will be diagnosed as
2854if it were the call `sscanf("abc def", "%4s %4s", buf1, buf2)`.
2855
2856This attribute cannot be applied to non-static member functions.)reST";
2857
2858static const char AttrDoc_DiagnoseIf[] = R"reST(The `diagnose_if` attribute can be placed on function declarations to emit
2859warnings or errors at compile-time if calls to the attributed function meet
2860certain user-defined criteria. For example:
2861
2862```c
2863int abs(int a)
2864 __attribute__((diagnose_if(a >= 0, "Redundant abs call", "warning")));
2865int must_abs(int a)
2866 __attribute__((diagnose_if(a >= 0, "Redundant abs call", "error")));
2867
2868int val = abs(1); // warning: Redundant abs call
2869int val2 = must_abs(1); // error: Redundant abs call
2870int val3 = abs(val);
2871int val4 = must_abs(val); // Because run-time checks are not emitted for
2872 // diagnose_if attributes, this executes without
2873 // issue.
2874```
2875
2876`diagnose_if` is closely related to `enable_if`, with a few key differences:
2877
2878- Overload resolution is not aware of `diagnose_if` attributes: they're
2879 considered only after we select the best candidate from a given candidate set.
2880- Function declarations that differ only in their `diagnose_if` attributes are
2881 considered to be redeclarations of the same function (not overloads).
2882- If the condition provided to `diagnose_if` cannot be evaluated, no
2883 diagnostic will be emitted.
2884
2885Otherwise, `diagnose_if` is essentially the logical negation of `enable_if`.
2886
2887As a result of bullet number two, `diagnose_if` attributes will stack on the
2888same function. For example:
2889
2890```c
2891int foo() __attribute__((diagnose_if(1, "diag1", "warning")));
2892int foo() __attribute__((diagnose_if(1, "diag2", "warning")));
2893
2894int bar = foo(); // warning: diag1
2895 // warning: diag2
2896int (*fooptr)(void) = foo; // warning: diag1
2897 // warning: diag2
2898
2899constexpr int supportsAPILevel(int N) { return N < 5; }
2900int baz(int a)
2901 __attribute__((diagnose_if(!supportsAPILevel(10),
2902 "Upgrade to API level 10 to use baz", "error")));
2903int baz(int a)
2904 __attribute__((diagnose_if(!a, "0 is not recommended.", "warning")));
2905
2906int (*bazptr)(int) = baz; // error: Upgrade to API level 10 to use baz
2907int v = baz(0); // error: Upgrade to API level 10 to use baz
2908```
2909
2910Query for this feature with `__has_attribute(diagnose_if)`.)reST";
2911
2912static const char AttrDoc_DisableSanitizerInstrumentation[] = R"reST(Use the `disable_sanitizer_instrumentation` attribute on a function,
2913Objective-C method, or global variable, to specify that no sanitizer
2914instrumentation should be applied.
2915
2916This is not the same as `__attribute__((no_sanitize(...)))`, which depending
2917on the tool may still insert instrumentation to prevent false positive reports.)reST";
2918
2919static const char AttrDoc_DisableTailCalls[] = R"reST(The `disable_tail_calls` attribute instructs the backend to not perform tail
2920call optimization inside the marked function.
2921
2922For example:
2923
2924```c
2925int callee(int);
2926
2927int foo(int a) __attribute__((disable_tail_calls)) {
2928 return callee(a); // This call is not tail-call optimized.
2929}
2930```
2931
2932Marking virtual functions as `disable_tail_calls` is legal.
2933
2934```c++
2935int callee(int);
2936
2937class Base {
2938public:
2939 [[clang::disable_tail_calls]] virtual int foo1() {
2940 return callee(); // This call is not tail-call optimized.
2941 }
2942};
2943
2944class Derived1 : public Base {
2945public:
2946 int foo1() override {
2947 return callee(); // This call is tail-call optimized.
2948 }
2949};
2950```)reST";
2951
2952static const char AttrDoc_EmptyBases[] = R"reST(The empty_bases attribute permits the compiler to utilize the
2953empty-base-optimization more frequently.
2954This attribute only applies to struct, class, and union types.
2955It is only supported when using the Microsoft C++ ABI.)reST";
2956
2957static const char AttrDoc_EnableIf[] = R"reST(:::{Note}
2958Some features of this attribute are experimental. The meaning of
2959multiple enable_if attributes on a single declaration is subject to change in
2960a future version of clang. Also, the ABI is not standardized and the name
2961mangling may change in future versions. To avoid that, use asm labels.
2962:::
2963
2964The `enable_if` attribute can be placed on function declarations to control
2965which overload is selected based on the values of the function's arguments.
2966When combined with the `overloadable` attribute, this feature is also
2967available in C.
2968
2969```c++
2970int isdigit(int c);
2971int 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")));
2972
2973void foo(char c) {
2974 isdigit(c);
2975 isdigit(10);
2976 isdigit(-10); // results in a compile-time error.
2977}
2978```
2979
2980The enable_if attribute takes two arguments, the first is an expression written
2981in terms of the function parameters, the second is a string explaining why this
2982overload candidate could not be selected to be displayed in diagnostics. The
2983expression is part of the function signature for the purposes of determining
2984whether it is a redeclaration (following the rules used when determining
2985whether a C++ template specialization is ODR-equivalent), but is not part of
2986the type.
2987
2988The enable_if expression is evaluated as if it were the body of a
2989bool-returning constexpr function declared with the arguments of the function
2990it is being applied to, then called with the parameters at the call site. If the
2991result is false or could not be determined through constant expression
2992evaluation, then this overload will not be chosen and the provided string may
2993be used in a diagnostic if the compile fails as a result.
2994
2995Because the enable_if expression is an unevaluated context, there are no global
2996state changes, nor the ability to pass information from the enable_if
2997expression to the function body. For example, suppose we want calls to
2998strnlen(strbuf, maxlen) to resolve to strnlen_chk(strbuf, maxlen, size of
2999strbuf) only if the size of strbuf can be determined:
3000
3001```c++
3002__attribute__((always_inline))
3003static inline size_t strnlen(const char *s, size_t maxlen)
3004 __attribute__((overloadable))
3005 __attribute__((enable_if(__builtin_object_size(s, 0) != -1))),
3006 "chosen when the buffer size is known but 'maxlen' is not")))
3007{
3008 return strnlen_chk(s, maxlen, __builtin_object_size(s, 0));
3009}
3010```
3011
3012Multiple enable_if attributes may be applied to a single declaration. In this
3013case, the enable_if expressions are evaluated from left to right in the
3014following manner. First, the candidates whose enable_if expressions evaluate to
3015false or cannot be evaluated are discarded. If the remaining candidates do not
3016share ODR-equivalent enable_if expressions, the overload resolution is
3017ambiguous. Otherwise, enable_if overload resolution continues with the next
3018enable_if attribute on the candidates that have not been discarded and have
3019remaining enable_if attributes. In this way, we pick the most specific
3020overload out of a number of viable overloads using enable_if.
3021
3022```c++
3023void f() __attribute__((enable_if(true, ""))); // #1
3024void f() __attribute__((enable_if(true, ""))) __attribute__((enable_if(true, ""))); // #2
3025
3026void g(int i, int j) __attribute__((enable_if(i, ""))); // #1
3027void g(int i, int j) __attribute__((enable_if(j, ""))) __attribute__((enable_if(true))); // #2
3028```
3029
3030In this example, a call to f() is always resolved to #2, as the first enable_if
3031expression is ODR-equivalent for both declarations, but #1 does not have another
3032enable_if expression to continue evaluating, so the next round of evaluation has
3033only a single candidate. In a call to g(1, 1), the call is ambiguous even though
3034#2 has more enable_if attributes, because the first enable_if expressions are
3035not ODR-equivalent.
3036
3037Query for this feature with `__has_attribute(enable_if)`.
3038
3039Note that functions with one or more `enable_if` attributes may not have
3040their address taken, unless all of the conditions specified by said
3041`enable_if` are constants that evaluate to `true`. For example:
3042
3043```c
3044const int TrueConstant = 1;
3045const int FalseConstant = 0;
3046int f(int a) __attribute__((enable_if(a > 0, "")));
3047int g(int a) __attribute__((enable_if(a == 0 || a != 0, "")));
3048int h(int a) __attribute__((enable_if(1, "")));
3049int i(int a) __attribute__((enable_if(TrueConstant, "")));
3050int j(int a) __attribute__((enable_if(FalseConstant, "")));
3051
3052void fn() {
3053 int (*ptr)(int);
3054 ptr = &f; // error: 'a > 0' is not always true
3055 ptr = &g; // error: 'a == 0 || a != 0' is not a truthy constant
3056 ptr = &h; // OK: 1 is a truthy constant
3057 ptr = &i; // OK: 'TrueConstant' is a truthy constant
3058 ptr = &j; // error: 'FalseConstant' is a constant, but not truthy
3059}
3060```
3061
3062Because `enable_if` evaluation happens during overload resolution,
3063`enable_if` may give unintuitive results when used with templates, depending
3064on when overloads are resolved. In the example below, clang will emit a
3065diagnostic about no viable overloads for `foo` in `bar`, but not in `baz`:
3066
3067```c++
3068double foo(int i) __attribute__((enable_if(i > 0, "")));
3069void *foo(int i) __attribute__((enable_if(i <= 0, "")));
3070template <int I>
3071auto bar() { return foo(I); }
3072
3073template <typename T>
3074auto baz() { return foo(T::number); }
3075
3076struct WithNumber { constexpr static int number = 1; };
3077void callThem() {
3078 bar<sizeof(WithNumber)>();
3079 baz<WithNumber>();
3080}
3081```
3082
3083This is because, in `bar`, `foo` is resolved prior to template
3084instantiation, so the value for `I` isn't known (thus, both `enable_if`
3085conditions for `foo` fail). However, in `baz`, `foo` is resolved during
3086template instantiation, so the value for `T::number` is known.)reST";
3087
3088static const char AttrDoc_EnforceTCB[] = R"reST(The `enforce_tcb` attribute can be placed on functions to enforce that a
3089trusted compute base (TCB) does not call out of the TCB. This generates a
3090warning every time a function not marked with an `enforce_tcb` attribute is
3091called from a function with the `enforce_tcb` attribute. A function may be a
3092part of multiple TCBs. Invocations through function pointers are currently
3093not checked. Builtins are considered to a part of every TCB.
3094
3095- `enforce_tcb(Name)` indicates that this function is a part of the TCB named `Name`)reST";
3096
3097static const char AttrDoc_EnforceTCBLeaf[] = R"reST(The `enforce_tcb_leaf` attribute satisfies the requirement enforced by
3098`enforce_tcb` for the marked function to be in the named TCB but does not
3099continue to check the functions called from within the leaf function.
3100
3101- `enforce_tcb_leaf(Name)` indicates that this function is a part of the TCB named `Name`)reST";
3102
3103static const char AttrDoc_EnumExtensibility[] = R"reST(Attribute `enum_extensibility` is used to distinguish between enum definitions
3104that are extensible and those that are not. The attribute can take either
3105`closed` or `open` as an argument. `closed` indicates a variable of the
3106enum type takes a value that corresponds to one of the enumerators listed in the
3107enum definition or, when the enum is annotated with `flag_enum`, a value that
3108can be constructed using values corresponding to the enumerators. `open`
3109indicates a variable of the enum type can take any values allowed by the
3110standard and instructs clang to be more lenient when issuing warnings.
3111
3112```c
3113enum __attribute__((enum_extensibility(closed))) ClosedEnum {
3114 A0, A1
3115};
3116
3117enum __attribute__((enum_extensibility(open))) OpenEnum {
3118 B0, B1
3119};
3120
3121enum __attribute__((enum_extensibility(closed),flag_enum)) ClosedFlagEnum {
3122 C0 = 1 << 0, C1 = 1 << 1
3123};
3124
3125enum __attribute__((enum_extensibility(open),flag_enum)) OpenFlagEnum {
3126 D0 = 1 << 0, D1 = 1 << 1
3127};
3128
3129void foo1() {
3130 enum ClosedEnum ce;
3131 enum OpenEnum oe;
3132 enum ClosedFlagEnum cfe;
3133 enum OpenFlagEnum ofe;
3134
3135 ce = A1; // no warnings
3136 ce = 100; // warning issued
3137 oe = B1; // no warnings
3138 oe = 100; // no warnings
3139 cfe = C0 | C1; // no warnings
3140 cfe = C0 | C1 | 4; // warning issued
3141 ofe = D0 | D1; // no warnings
3142 ofe = D0 | D1 | 4; // no warnings
3143}
3144```)reST";
3145
3146static const char AttrDoc_Error[] = R"reST(The `error` and `warning` function attributes can be used to specify a
3147custom diagnostic to be emitted when a call to such a function is not
3148eliminated via optimizations. This can be used to create compile time
3149assertions that depend on optimizations, while providing diagnostics
3150pointing to precise locations of the call site in the source.
3151
3152```c++
3153__attribute__((warning("oh no"))) void dontcall();
3154void foo() {
3155 if (someCompileTimeAssertionThatsTrue)
3156 dontcall(); // Warning
3157
3158 dontcall(); // Warning
3159
3160 if (someCompileTimeAssertionThatsFalse)
3161 dontcall(); // No Warning
3162 sizeof(dontcall()); // No Warning
3163}
3164```
3165
3166When the call occurs through inlined functions, the
3167`-fdiagnostics-show-inlining-chain` option can be used to show the
3168inlining chain that led to the call. This helps identify which call site
3169triggered the diagnostic when the attributed function is called from
3170multiple locations through inline functions.
3171
3172When enabled, this option automatically uses debug info for accurate source
3173locations if available (`-gline-directives-only` (implicitly enabled at
3174`-g1`) or higher), or falls back to a heuristic based on metadata tracking.
3175When falling back, a note is emitted suggesting `-gline-directives-only` for
3176more accurate locations.)reST";
3177
3178static const char AttrDoc_ExcludeFromExplicitInstantiation[] = R"reST(The `exclude_from_explicit_instantiation` attribute opts-out a member of a
3179class template from being part of explicit template instantiations of that
3180class template. This means that an explicit instantiation will not instantiate
3181members of the class template marked with the attribute, but also that code
3182where an extern template declaration of the enclosing class template is visible
3183will not take for granted that an external instantiation of the class template
3184would provide those members (which would otherwise be a link error, since the
3185explicit instantiation won't provide those members). For example, let's say we
3186don't want the `data()` method to be part of libc++'s ABI. To make sure it
3187is not exported from the dylib, we give it hidden visibility:
3188
3189```c++
3190// in <string>
3191template <class CharT>
3192class basic_string {
3193public:
3194 __attribute__((__visibility__("hidden")))
3195 const value_type* data() const noexcept { ... }
3196};
3197
3198template class basic_string<char>;
3199```
3200
3201Since an explicit template instantiation declaration for `basic_string<char>`
3202is provided, the compiler is free to assume that `basic_string<char>::data()`
3203will be provided by another translation unit, and it is free to produce an
3204external call to this function. However, since `data()` has hidden visibility
3205and the explicit template instantiation is provided in a shared library (as
3206opposed to simply another translation unit), `basic_string<char>::data()`
3207won't be found and a link error will ensue. This happens because the compiler
3208assumes that `basic_string<char>::data()` is part of the explicit template
3209instantiation declaration, when it really isn't. To tell the compiler that
3210`data()` is not part of the explicit template instantiation declaration, the
3211`exclude_from_explicit_instantiation` attribute can be used:
3212
3213```c++
3214// in <string>
3215template <class CharT>
3216class basic_string {
3217public:
3218 __attribute__((__visibility__("hidden")))
3219 __attribute__((exclude_from_explicit_instantiation))
3220 const value_type* data() const noexcept { ... }
3221};
3222
3223template class basic_string<char>;
3224```
3225
3226Now, the compiler won't assume that `basic_string<char>::data()` is provided
3227externally despite there being an explicit template instantiation declaration:
3228the compiler will implicitly instantiate `basic_string<char>::data()` in the
3229TUs where it is used.
3230
3231This attribute can be used on static and non-static member functions of class
3232templates, static data members of class templates and member classes of class
3233templates.
3234
3235**Interaction with \_\_declspec(dllexport/dllimport)**
3236
3237For a DLL platform (i.e., Windows), this attribute also means "this member will
3238never be exported or imported". Despite its name, this semantics applies to
3239implicit instantiations and non-template entities as well.
3240
3241```c++
3242// in <exception>
3243class __declspec(dllimport) nested_exception {
3244 ...
3245public:
3246 __attribute__((exclude_from_explicit_instantiation))
3247 exception_ptr nested_ptr() const noexcept { ... }
3248};
3249```
3250
3251In this case, `nested_exception::nested_ptr` will never be attempted to be
3252imported.)reST";
3253
3254static const char AttrDoc_ExplicitInit[] = R"reST(The `clang::require_explicit_initialization` attribute indicates that a
3255field of an aggregate must be initialized explicitly by the user when an object
3256of the aggregate type is constructed. The attribute supports both C and C++,
3257but its usage is invalid on non-aggregates.
3258
3259Note that this attribute is *not* a memory safety feature, and is *not* intended
3260to guard against use of uninitialized memory.
3261
3262Rather, it is intended for use in "parameter-objects", used to simulate,
3263for example, the passing of named parameters.
3264Except inside unevaluated contexts, the attribute generates a warning when
3265explicit initializers for such variables are not provided (this occurs
3266regardless of whether any in-class field initializers exist):
3267
3268```c++
3269struct Buffer {
3270 void *address [[clang::require_explicit_initialization]];
3271 size_t length [[clang::require_explicit_initialization]] = 0;
3272};
3273
3274struct ArrayIOParams {
3275 size_t count [[clang::require_explicit_initialization]];
3276 size_t element_size [[clang::require_explicit_initialization]];
3277 int flags = 0;
3278};
3279
3280size_t ReadArray(FILE *file, struct Buffer buffer,
3281 struct ArrayIOParams params);
3282
3283int main() {
3284 unsigned int buf[512];
3285 ReadArray(stdin, {
3286 buf
3287 // warning: field 'length' is not explicitly initialized
3288 }, {
3289 .count = sizeof(buf) / sizeof(*buf),
3290 // warning: field 'element_size' is not explicitly initialized
3291 // (Note that a missing initializer for 'flags' is not diagnosed, because
3292 // the field is not marked as requiring explicit initialization.)
3293 });
3294}
3295```)reST";
3296
3297static const char AttrDoc_ExtVectorType[] = R"reST(The `ext_vector_type(N)` attribute specifies that a type is a vector with N
3298elements, directly mapping to an LLVM vector type. Originally from OpenCL, it
3299allows element access the array subscript operator `[]`, `sN` where N is
3300a hexadecimal value, or `x, y, z, w` for graphics-style indexing.
3301This attribute enables efficient SIMD operations and is usable in
3302general-purpose code.
3303
3304```c++
3305template <typename T, uint32_t N>
3306constexpr T simd_reduce(T [[clang::ext_vector_type(N)]] v) {
3307 static_assert((N & (N - 1)) == 0, "N must be a power of two");
3308 if constexpr (N == 1)
3309 return v[0];
3310 else
3311 return simd_reduce<T, N / 2>(v.hi + v.lo);
3312}
3313```
3314
3315The vector type also supports swizzling up to sixteen elements. This can be done
3316using the object accessors. The OpenCL documentation lists all of the accepted
3317values.
3318
3319```c++
3320using f16_x16 = _Float16 __attribute__((ext_vector_type(16)));
3321
3322f16_x16 reverse(f16_x16 v) { return v.sfedcba9876543210; }
3323```
3324
3325See the OpenCL documentation for some more complete examples.)reST";
3326
3327static const char AttrDoc_ExternalSourceSymbol[] = R"reST(The `external_source_symbol` attribute specifies that a declaration originates
3328from an external source and describes the nature of that source.
3329
3330The fact that Clang is capable of recognizing declarations that were defined
3331externally can be used to provide better tooling support for mixed-language
3332projects or projects that rely on auto-generated code. For instance, an IDE that
3333uses Clang and that supports mixed-language projects can use this attribute to
3334provide a correct 'jump-to-definition' feature. For a concrete example,
3335consider a protocol that's defined in a Swift file:
3336
3337```swift
3338@objc public protocol SwiftProtocol {
3339 func method()
3340}
3341```
3342
3343This protocol can be used from Objective-C code by including a header file that
3344was generated by the Swift compiler. The declarations in that header can use
3345the `external_source_symbol` attribute to make Clang aware of the fact
3346that `SwiftProtocol` actually originates from a Swift module:
3347
3348```objc
3349__attribute__((external_source_symbol(language="Swift",defined_in="module")))
3350@protocol SwiftProtocol
3351@required
3352- (void) method;
3353@end
3354```
3355
3356Consequently, when 'jump-to-definition' is performed at a location that
3357references `SwiftProtocol`, the IDE can jump to the original definition in
3358the Swift source file rather than jumping to the Objective-C declaration in the
3359auto-generated header file.
3360
3361The `external_source_symbol` attribute is a comma-separated list that includes
3362clauses that describe the origin and the nature of the particular declaration.
3363Those clauses can be:
3364
3365language=*string-literal*
3366
3367: The name of the source language in which this declaration was defined.
3368
3369defined_in=*string-literal*
3370
3371: The name of the source container in which the declaration was defined. The
3372 exact definition of source container is language-specific, e.g. Swift's
3373 source containers are modules, so `defined_in` should specify the Swift
3374 module name.
3375
3376USR=*string-literal*
3377
3378: String that specifies a unified symbol resolution (USR) value for this
3379 declaration. USR string uniquely identifies this particular declaration, and
3380 is typically used when constructing an index of a codebase.
3381 The USR value in this attribute is expected to be generated by an external
3382 compiler that compiled the native declaration using its original source
3383 language. The exact format of the USR string and its other attributes
3384 are determined by the specification of this declaration's source language.
3385 When not specified, Clang's indexer will use the Clang USR for this symbol.
3386 User can query to see if Clang supports the use of the `USR` clause in
3387 the `external_source_symbol` attribute with
3388 `__has_attribute(external_source_symbol) >= 20230206`.
3389
3390generated_declaration
3391
3392: This declaration was automatically generated by some tool.
3393
3394The clauses can be specified in any order. The clauses that are listed above are
3395all optional, but the attribute has to have at least one clause.)reST";
3396
3397static const char AttrDoc_FallThrough[] = R"reST(The `fallthrough` (or `clang::fallthrough`) attribute is used
3398to annotate intentional fall-through
3399between switch labels. It can only be applied to a null statement placed at a
3400point of execution between any statement and the next switch label. It is
3401common to mark these places with a specific comment, but this attribute is
3402meant to replace comments with a more strict annotation, which can be checked
3403by the compiler. This attribute doesn't change semantics of the code and can
3404be used wherever an intended fall-through occurs. It is designed to mimic
3405control-flow statements like `break;`, so it can be placed in most places
3406where `break;` can, but only if there are no statements on the execution path
3407between it and the next switch label.
3408
3409By default, Clang does not warn on unannotated fallthrough from one `switch`
3410case to another. Diagnostics on fallthrough without a corresponding annotation
3411can be enabled with the `-Wimplicit-fallthrough` argument.
3412
3413Here is an example:
3414
3415```c++
3416// compile with -Wimplicit-fallthrough
3417switch (n) {
3418case 22:
3419case 33: // no warning: no statements between case labels
3420 f();
3421case 44: // warning: unannotated fall-through
3422 g();
3423 [[clang::fallthrough]];
3424case 55: // no warning
3425 if (x) {
3426 h();
3427 break;
3428 }
3429 else {
3430 i();
3431 [[clang::fallthrough]];
3432 }
3433case 66: // no warning
3434 p();
3435 [[clang::fallthrough]]; // warning: fallthrough annotation does not
3436 // directly precede case label
3437 q();
3438case 77: // warning: unannotated fall-through
3439 r();
3440}
3441```)reST";
3442
3443static const char AttrDoc_FastCall[] = R"reST(On 32-bit x86 targets, this attribute changes the calling convention of a
3444function to use ECX and EDX as register parameters and clear parameters off of
3445the stack on return. This convention does not support variadic calls or
3446unprototyped functions in C, and has no effect on x86_64 targets. This calling
3447convention is supported primarily for compatibility with existing code. Users
3448seeking register parameters should use the `regparm` attribute, which does
3449not require callee-cleanup. See the documentation for [\_\_fastcall][__fastcall] on MSDN.
3450
3451[__fastcall]: http://msdn.microsoft.com/en-us/library/6xa169sk.aspx)reST";
3452
3453static const char AttrDoc_Final[] = R"reST()reST";
3454
3455static const char AttrDoc_FlagEnum[] = R"reST(This attribute can be added to an enumerator to signal to the compiler that it
3456is intended to be used as a flag type. This will cause the compiler to assume
3457that the range of the type includes all of the values that you can get by
3458manipulating bits of the enumerator when issuing warnings.)reST";
3459
3460static const char AttrDoc_Flatten[] = R"reST(The `flatten` attribute causes calls within the attributed function to
3461be inlined unless it is impossible to do so, for example if the body of the
3462callee is unavailable or if the callee has the `noinline` attribute.)reST";
3463
3464static const char AttrDoc_Format[] = R"reST(Clang supports the `format` attribute, which indicates that the function
3465accepts (among other possibilities) a `printf` or `scanf`-like format string
3466and corresponding arguments or a `va_list` that contains these arguments.
3467
3468Please see [GCC documentation about format attribute](http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html) to find details
3469about attribute syntax.
3470
3471Clang implements two kinds of checks with this attribute.
3472
34731. Clang checks that the function with the `format` attribute is called with
3474 a format string that uses format specifiers that are allowed, and that
3475 arguments match the format string. This is the `-Wformat` warning, it is
3476 on by default.
3477
34782. Clang checks that the format string argument is a literal string. This is
3479 the `-Wformat-nonliteral` warning, it is off by default.
3480
3481 Clang implements this mostly the same way as GCC, but there is a difference
3482 for functions that accept a `va_list` argument (for example, `vprintf`).
3483 GCC does not emit `-Wformat-nonliteral` warning for calls to such
3484 functions. Clang does not warn if the format string comes from a function
3485 parameter, where the function is annotated with a compatible attribute,
3486 otherwise it warns. For example:
3487
3488 ```c
3489 __attribute__((__format__ (__scanf__, 1, 3)))
3490 void foo(const char* s, char *buf, ...) {
3491 va_list ap;
3492 va_start(ap, buf);
3493
3494 vprintf(s, ap); // warning: format string is not a string literal
3495 }
3496 ```
3497
3498 In this case we warn because `s` contains a format string for a
3499 `scanf`-like function, but it is passed to a `printf`-like function.
3500
3501 If the attribute is removed, clang still warns, because the format string is
3502 not a string literal.
3503
3504 Another example:
3505
3506 ```c
3507 __attribute__((__format__ (__printf__, 1, 3)))
3508 void foo(const char* s, char *buf, ...) {
3509 va_list ap;
3510 va_start(ap, buf);
3511
3512 vprintf(s, ap); // warning
3513 }
3514 ```
3515
3516 In this case Clang does not warn because the format string `s` and
3517 the corresponding arguments are annotated. If the arguments are
3518 incorrect, the caller of `foo` will receive a warning.
3519
3520As an extension to GCC's behavior, Clang accepts the `format` attribute on
3521non-variadic functions. Clang checks non-variadic format functions for the same
3522classes of issues that can be found on variadic functions, as controlled by the
3523same warning flags, except that the types of formatted arguments is forced by
3524the function signature. For example:
3525
3526```c
3527__attribute__((__format__(__printf__, 1, 2)))
3528void fmt(const char *s, const char *a, int b);
3529
3530void bar(void) {
3531 fmt("%s %i", "hello", 123); // OK
3532 fmt("%i %g", "hello", 123); // warning: arguments don't match format
3533 extern const char *fmt;
3534 fmt(fmt, "hello", 123); // warning: format string is not a string literal
3535}
3536```
3537
3538When using the format attribute on a variadic function, the first data parameter
3539\_must\_ be the index of the ellipsis in the parameter list. Clang will generate
3540a diagnostic otherwise, as it wouldn't be possible to forward that argument list
3541to `printf`-family functions. For instance, this is an error:
3542
3543```c
3544__attribute__((__format__(__printf__, 1, 2)))
3545void fmt(const char *s, int b, ...);
3546// ^ error: format attribute parameter 3 is out of bounds
3547// (must be __printf__, 1, 3)
3548```
3549
3550Using the `format` attribute on a non-variadic function emits a GCC
3551compatibility diagnostic.)reST";
3552
3553static const char AttrDoc_FormatArg[] = R"reST(No documentation.)reST";
3554
3555static const char AttrDoc_FormatMatches[] = R"reST(The `format` attribute is the basis for the enforcement of diagnostics in the
3556`-Wformat` family, but it only handles the case where the format string is
3557passed along with the arguments it is going to format. It cannot handle the case
3558where the format string and the format arguments are passed separately from each
3559other. For instance:
3560
3561```c
3562static const char *first_name;
3563static double todays_temperature;
3564static int wind_speed;
3565
3566void say_hi(const char *fmt) {
3567 printf(fmt, first_name, todays_temperature);
3568 // ^ warning: format string is not a string literal
3569 printf(fmt, first_name, wind_speed);
3570 // ^ warning: format string is not a string literal
3571}
3572
3573int main() {
3574 say_hi("hello %s, it is %g degrees outside");
3575 say_hi("hello %s, it is %d degrees outside!");
3576 // ^ no diagnostic, but %d cannot format doubles
3577}
3578```
3579
3580In this example, `fmt` is expected to format a `const char *` and a
3581`double`, but these values are not passed to `say_hi`. Without the
3582`format` attribute (which cannot apply in this case), the -Wformat-nonliteral
3583diagnostic unnecessarily triggers in the body of `say_hi`, and incorrect
3584`say_hi` call sites do not trigger a diagnostic.
3585
3586To complement the `format` attribute, Clang also defines the
3587`format_matches` attribute. Its syntax is similar to the `format`
3588attribute's, but instead of taking the index of the first formatted value
3589argument, it takes a C string literal with the expected specifiers:
3590
3591```c
3592static const char *first_name;
3593static double todays_temperature;
3594static int wind_speed;
3595
3596__attribute__((__format_matches__(printf, 1, "%s %g")))
3597void say_hi(const char *fmt) {
3598 printf(fmt, first_name, todays_temperature); // no dignostic
3599 printf(fmt, first_name, wind_speed); // warning: format specifies type 'int' but the argument has type 'double'
3600}
3601
3602int main() {
3603 say_hi("hello %s, it is %g degrees outside");
3604 say_hi("it is %g degrees outside, have a good day %s!");
3605 // warning: format specifies 'double' where 'const char *' is required
3606 // warning: format specifies 'const char *' where 'double' is required
3607}
3608```
3609
3610The third argument to `format_matches` is expected to evaluate to a **C string
3611literal** even when the format string would normally be a different type for the
3612given flavor, like a `CFStringRef` or a `NSString *`.
3613
3614The only requirement on the format string literal is that it has specifiers
3615that are compatible with the arguments that will be used. It can contain
3616arbitrary non-format characters. For instance, for the purposes of compile-time
3617validation, `"%s scored %g%% on her test"` and `"%s%g"` are interchangeable
3618as the format string argument. As a means of self-documentation, users may
3619prefer the former when it provides a useful example of an expected format
3620string.
3621
3622In the implementation of a function with the `format_matches` attribute,
3623format verification works as if the format string was identical to the one
3624specified in the attribute.
3625
3626```c
3627__attribute__((__format_matches__(printf, 1, "%s %g")))
3628void say_hi(const char *fmt) {
3629 printf(fmt, "person", 546);
3630 // ^ warning: format specifies type 'double' but the
3631 // argument has type 'int'
3632 // note: format string is defined here:
3633 // __attribute__((__format_matches__(printf, 1, "%s %g")))
3634 // ^~
3635}
3636```
3637
3638At the call sites of functions with the `format_matches` attribute, format
3639verification instead compares the two format strings to evaluate their
3640equivalence. Each format flavor defines equivalence between format specifiers.
3641Generally speaking, two specifiers are equivalent if they format the same type.
3642For instance, in the `printf` flavor, `%2i` and `%-0.5d` are compatible.
3643When `-Wformat-signedness` is disabled, `%d` and `%u` are compatible. For
3644a negative example, `%ld` is incompatible with `%d`.
3645
3646Do note the following un-obvious cases:
3647
3648- Passing `NULL` as the format string does not trigger format diagnostics.
3649- When the format string is not NULL, it cannot \_miss\_ specifiers, even in
3650 trailing positions. For instance, `%d` is not accepted when the required
3651 format is `%d %d %d`.
3652- While checks for the `format` attribute tolerate sone size mismatches
3653 that standard argument promotion renders immaterial (such as formatting an
3654 `int` with `%hhd`, which specifies a `char`-sized integer), checks for
3655 `format_matches` require specified argument sizes to match exactly.
3656- Format strings expecting a variable modifier (such as `%*s`) are
3657 incompatible with format strings that would itemize the variable modifiers
3658 (such as `%i %s`), even if the two specify ABI-compatible argument lists.
3659- All pointer specifiers, modifiers aside, are mutually incompatible. For
3660 instance, `%s` is not compatible with `%p`, and `%p` is not compatible
3661 with `%n`, and `%hhn` is incompatible with `%s`, even if the pointers
3662 are ABI-compatible or identical on the selected platform. However, `%0.5s`
3663 is compatible with `%s`, since the difference only exists in modifier flags.
3664 This is not overridable with `-Wformat-pedantic` or its inverse, which
3665 control similar behavior in `-Wformat`.
3666
3667At this time, clang implements `format_matches` only for format types in the
3668`printf` family. This includes variants such as Apple's NSString format and
3669the FreeBSD `kprintf`, but excludes `scanf`. Using a known but unsupported
3670format silently fails in order to be compatible with other implementations that
3671would support these formats.)reST";
3672
3673static const char AttrDoc_FunctionReturnThunks[] = R"reST(The attribute `function_return` can replace return instructions with jumps to
3674target-specific symbols. This attribute supports 2 possible values,
3675corresponding to the values supported by the `-mfunction-return=` command
3676line flag:
3677
3678- `__attribute__((function_return("keep")))` to disable related transforms.
3679 This is useful for undoing global setting from `-mfunction-return=` locally
3680 for individual functions.
3681- `__attribute__((function_return("thunk-extern")))` to replace returns with
3682 jumps, while NOT emitting the thunk.
3683
3684The values `thunk` and `thunk-inline` from GCC are not supported.
3685
3686The symbol used for `thunk-extern` is target specific:
3687\* X86: `__x86_return_thunk`
3688
3689As such, this function attribute is currently only supported on X86 targets.)reST";
3690
3691static const char AttrDoc_GCCStruct[] = R"reST(The `ms_struct` and `gcc_struct` attributes request the compiler to enter a
3692special record layout compatibility mode which mimics the layout of Microsoft or
3693Itanium C++ ABI respectively. Obviously, if the current C++ ABI matches the
3694requested ABI, the attribute does nothing. However, if it does not, annotated
3695structure or class is laid out in a special compatibility mode, which slightly
3696changes offsets for fields and bit-fields. The intention is to match the layout
3697of the requested ABI for structures which only use C features.
3698
3699Note that the default behavior can be controlled by `-mms-bitfields` and
3700`-mno-ms-bitfields` switches and via `#pragma ms_struct`.
3701
3702The primary difference is for bitfields, where the MS variant only packs
3703adjacent fields into the same allocation unit if they have integral types
3704of the same size, while the GCC/Itanium variant packs all fields in a bitfield
3705tightly.)reST";
3706
3707static const char AttrDoc_GNUInline[] = R"reST(The `gnu_inline` changes the meaning of `extern inline` to use GNU inline
3708semantics, meaning:
3709
3710- If any declaration that is declared `inline` is not declared `extern`,
3711 then the `inline` keyword is just a hint. In particular, an out-of-line
3712 definition is still emitted for a function with external linkage, even if all
3713 call sites are inlined, unlike in C99 and C++ inline semantics.
3714- If all declarations that are declared `inline` are also declared
3715 `extern`, then the function body is present only for inlining and no
3716 out-of-line version is emitted.
3717
3718Some important consequences: `static inline` emits an out-of-line
3719version if needed, a plain `inline` definition emits an out-of-line version
3720always, and an `extern inline` definition (in a header) followed by a
3721(non-`extern`) `inline` declaration in a source file emits an out-of-line
3722version of the function in that source file but provides the function body for
3723inlining to all includers of the header.
3724
3725Either `__GNUC_GNU_INLINE__` (GNU inline semantics) or
3726`__GNUC_STDC_INLINE__` (C99 semantics) will be defined (they are mutually
3727exclusive). If `__GNUC_STDC_INLINE__` is defined, then the `gnu_inline`
3728function attribute can be used to get GNU inline semantics on a per function
3729basis. If `__GNUC_GNU_INLINE__` is defined, then the translation unit is
3730already being compiled with GNU inline semantics as the implied default. It is
3731unspecified which macro is defined in a C++ compilation.
3732
3733GNU inline semantics are the default behavior with `-std=gnu89`,
3734`-std=c89`, `-fgnu89-inline`, or `-std=iso9899:199409`.)reST";
3735
3736static const char AttrDoc_GuardedBy[] = R"reST(No documentation.)reST";
3737
3738static const char AttrDoc_GuardedVar[] = R"reST(No documentation.)reST";
3739
3740static const char AttrDoc_HIPManaged[] = R"reST(The `__managed__` attribute can be applied to a global variable declaration in HIP.
3741A managed variable is emitted as an undefined global symbol in the device binary and is
3742registered by `__hipRegisterManagedVar` in init functions. The HIP runtime allocates
3743managed memory and uses it to define the symbol when loading the device binary.
3744A managed variable can be accessed in both device and host code.)reST";
3745
3746static const char AttrDoc_HLSLAppliedSemantic[] = R"reST()reST";
3747
3748static const char AttrDoc_HLSLAssociatedResourceDecl[] = R"reST()reST";
3749
3750static const char AttrDoc_HLSLColumnMajor[] = R"reST(The `row_major` and `column_major` keywords specify the memory layout
3751of an HLSL matrix type.
3752
3753- `row_major`: Matrices are stored in memory row-by-row.
3754- `column_major`: Matrices are stored in memory column-by-column (default).
3755
3756Example:
3757
3758```hlsl
3759row_major float2x2 myMatrix;
3760```)reST";
3761
3762static const char AttrDoc_HLSLContainedType[] = R"reST(The ``hlsl::contained_type`` attribute specifies the type of the HLSL resource
3763represented by a member variable of type ``__hlsl_resource_t``.
3764
3765This attribute is only valid for resource handles, and is an implementation
3766detail of clang's HLSL implementation. For more information see `HLSL Resource
3767Types`_
3768
3769.. _`HLSL Resource Types`: https://clang.llvm.org/docs/HLSL/ResourceTypes.html>)reST";
3770
3771static const char AttrDoc_HLSLControlFlowHint[] = R"reST(The ``branch`` and ``flatten`` attributes can be applied to *if* and *switch*
3772statements in the HLSL language mode to provide hints for how the backend
3773should execute them.
3774
3775- ``branch`` means that control flow is preferred. The condition should be
3776 evaluated first and we should only execute the block guarded by it.
3777
3778- ``flatten`` means that control flow should be avoided. All blocks should be
3779 executed and variables that are modified should be conditionally assigned.
3780
3781These control flow hints are preserved through the compilation and emitted in a
3782backend-specific way.
3783
3784For details, see the Direct3D documentation for `if Statement`_ and `switch Statement`_.
3785
3786.. _`if Statement`: https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-if
3787.. _`switch Statement`: https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-switchhttps://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-switch)reST";
3788
3789static const char AttrDoc_HLSLGroupSharedAddressSpace[] = R"reST(HLSL enables threads of a compute shader to exchange values via shared memory.
3790HLSL provides barrier primitives such as GroupMemoryBarrierWithGroupSync,
3791and so on to ensure the correct ordering of reads and writes to shared memory
3792in the shader and to avoid data races.
3793Here's an example to declare a groupshared variable.
3794
3795```c++
3796groupshared GSData data[5*5*1];
3797```
3798
3799The full documentation is available here: <https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-variable-syntax#group-shared>)reST";
3800
3801static const char AttrDoc_HLSLIsArray[] = R"reST(The ``hlsl::is_array`` attribute specifies that the HLSL resource represented
3802by a member variable of type ``__hlsl_resource_t`` has array dimensions.
3803
3804This attribute is only valid for resource handles, and is an implementation
3805detail of clang's HLSL implementation. For more information see `HLSL Resource
3806Types`_
3807
3808.. _`HLSL Resource Types`: https://clang.llvm.org/docs/HLSL/ResourceTypes.html>)reST";
3809
3810static const char AttrDoc_HLSLIsCounter[] = R"reST(The ``hlsl::is_counter`` attribute specifies that the HLSL resource represented
3811by a member variable of type ``__hlsl_resource_t`` is a counter buffer.
3812
3813This attribute is only valid for resource handles, and is an implementation
3814detail of clang's HLSL implementation. For more information see `HLSL Resource
3815Types`_
3816
3817.. _`HLSL Resource Types`: https://clang.llvm.org/docs/HLSL/ResourceTypes.html>)reST";
3818
3819static const char AttrDoc_HLSLIsMultiSampled[] = R"reST(The ``hlsl::is_array`` attribute specifies that the HLSL resource represented
3820by a member variable of type ``__hlsl_resource_t`` is multisampled.
3821
3822This attribute is only valid for resource handles, and is an implementation
3823detail of clang's HLSL implementation. For more information see `HLSL Resource
3824Types`_
3825
3826.. _`HLSL Resource Types`: https://clang.llvm.org/docs/HLSL/ResourceTypes.html>)reST";
3827
3828static const char AttrDoc_HLSLIsROV[] = R"reST(The ``hlsl::is_rov`` attribute specifies that the HLSL resource represented by
3829a member variable of type ``__hlsl_resource_t`` is a rasterizer ordered view.
3830
3831This attribute is only valid for resource handles, and is an implementation
3832detail of clang's HLSL implementation. For more information see `HLSL Resource
3833Types`_
3834
3835.. _`HLSL Resource Types`: https://clang.llvm.org/docs/HLSL/ResourceTypes.html>)reST";
3836
3837static const char AttrDoc_HLSLLoopHint[] = R"reST(The `[loop]` directive allows loop optimization hints to be
3838specified for the subsequent loop. The directive allows unrolling to
3839be disabled and is not compatible with [unroll(x)].
3840
3841Specifying the parameter, `[loop]`, directs the
3842unroller to not unroll the loop.
3843
3844```hlsl
3845[loop]
3846for (...) {
3847 ...
3848}
3849```
3850
3851```hlsl
3852[loop]
3853while (...) {
3854 ...
3855}
3856```
3857
3858```hlsl
3859[loop]
3860do {
3861 ...
3862} while (...)
3863```
3864
3865See [hlsl loop extensions](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-for)
3866for details.)reST";
3867
3868static const char AttrDoc_HLSLNumThreads[] = R"reST(The `numthreads` attribute applies to HLSL shaders where explcit thread counts
3869are required. The `X`, `Y`, and `Z` values provided to the attribute
3870dictate the thread id. Total number of threads executed is `X * Y * Z`.
3871
3872The full documentation is available here: <https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/sm5-attributes-numthreads>)reST";
3873
3874static const char AttrDoc_HLSLPackOffset[] = R"reST(The packoffset attribute is used to change the layout of a cbuffer.
3875Attribute spelling in HLSL is: `packoffset( c[Subcomponent][.component] )`.
3876A subcomponent is a register number, which is an integer. A component is in the form of [.xyzw].
3877
3878Examples:
3879
3880```hlsl
3881cbuffer A {
3882 float3 a : packoffset(c0.y);
3883 float4 b : packoffset(c4);
3884}
3885```
3886
3887The full documentation is available here: <https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-variable-packoffset>)reST";
3888
3889static const char AttrDoc_HLSLParamModifier[] = R"reST(HLSL function parameters are passed by value. Parameter declarations support
3890three qualifiers to denote parameter passing behavior. The three qualifiers are
3891`in`, `out` and `inout`.
3892
3893Parameters annotated with `in` or with no annotation are passed by value from
3894the caller to the callee.
3895
3896Parameters annotated with `out` are written to the argument after the callee
3897returns (Note: arguments values passed into `out` parameters *are not* copied
3898into the callee).
3899
3900Parameters annotated with `inout` are copied into the callee via a temporary,
3901and copied back to the argument after the callee returns.)reST";
3902
3903static const char AttrDoc_HLSLParsedSemantic[] = R"reST()reST";
3904
3905static const char AttrDoc_HLSLRawBuffer[] = R"reST(The ``hlsl::raw_buffer`` attribute specifies that the HLSL resource represented
3906by a member variable of type ``__hlsl_resource_t`` has raw buffer semantics.
3907
3908This attribute is only valid for resource handles, and is an implementation
3909detail of clang's HLSL implementation. For more information see `HLSL Resource
3910Types`_
3911
3912.. _`HLSL Resource Types`: https://clang.llvm.org/docs/HLSL/ResourceTypes.html>)reST";
3913
3914static const char AttrDoc_HLSLResourceBinding[] = R"reST(The resource binding attribute sets the virtual register and logical register space for a resource.
3915Attribute spelling in HLSL is: `register(slot [, space])`.
3916`slot` takes the format `[type][number]`,
3917where `type` is a single character specifying the resource type and `number` is the virtual register number.
3918
3919Register types are:
3920t for shader resource views (SRV),
3921s for samplers,
3922u for unordered access views (UAV),
3923b for constant buffer views (CBV).
3924
3925Register space is specified in the format `space[number]` and defaults to `space0` if omitted.
3926Here're resource binding examples with and without space:
3927
3928```hlsl
3929RWBuffer<float> Uav : register(u3, space1);
3930Buffer<float> Buf : register(t1);
3931```
3932
3933The full documentation is available here: <https://docs.microsoft.com/en-us/windows/win32/direct3d12/resource-binding-in-hlsl>)reST";
3934
3935static const char AttrDoc_HLSLResourceClass[] = R"reST(The ``hlsl::resource_class`` attribute specifies the resource class of the HLSL
3936resource represented by a member variable of type ``__hlsl_resource_t``,
3937declaring it to be an SRV, UAV, CBuffer, or Sampler resource.
3938
3939This attribute is only valid for resource handles, and is an implementation
3940detail of clang's HLSL implementation. For more information see `HLSL Resource
3941Types`_
3942
3943.. _`HLSL Resource Types`: https://clang.llvm.org/docs/HLSL/ResourceTypes.html>)reST";
3944
3945static const char AttrDoc_HLSLResourceDimension[] = R"reST(The ``hlsl::dimension`` attribute specifies the dimensions of the HLSL resource
3946represented by a member variable of type ``__hlsl_resource_t``, declaring the
3947resource to have Unknown, 1D, 2D, 3D, or Cube dimension.
3948
3949This attribute is only valid for resource handles, and is an implementation
3950detail of clang's HLSL implementation. For more information see `HLSL Resource
3951Types`_
3952
3953.. _`HLSL Resource Types`: https://clang.llvm.org/docs/HLSL/ResourceTypes.html>)reST";
3954
3955static const char AttrDoc_HLSLRowMajor[] = R"reST(The `row_major` and `column_major` keywords specify the memory layout
3956of an HLSL matrix type.
3957
3958- `row_major`: Matrices are stored in memory row-by-row.
3959- `column_major`: Matrices are stored in memory column-by-column (default).
3960
3961Example:
3962
3963```hlsl
3964row_major float2x2 myMatrix;
3965```)reST";
3966
3967static const char AttrDoc_HLSLShader[] = R"reST(The `shader` type attribute applies to HLSL shader entry functions to
3968identify the shader type for the entry function.
3969The syntax is:
3970
3971```text
3972``[shader(string-literal)]``
3973```
3974
3975where the string literal is one of: "pixel", "vertex", "geometry", "hull",
3976"domain", "compute", "raygeneration", "intersection", "anyhit", "closesthit",
3977"miss", "callable", "mesh", "amplification". Normally the shader type is set
3978by shader target with the `-T` option like `-Tps_6_1`. When compiling to a
3979library target like `lib_6_3`, the shader type attribute can help the
3980compiler to identify the shader type. It is mostly used by Raytracing shaders
3981where shaders must be compiled into a library and linked at runtime.)reST";
3982
3983static const char AttrDoc_HLSLUnparsedSemantic[] = R"reST()reST";
3984
3985static const char AttrDoc_HLSLVkBinding[] = R"reST(The `[[vk::binding]]` attribute allows you to explicitly specify the descriptor
3986set and binding for a resource when targeting SPIR-V. This is particularly
3987useful when you need different bindings for SPIR-V and DXIL, as the `register`
3988attribute can be used for DXIL-specific bindings.
3989
3990The attribute takes two integer arguments: the binding and the descriptor set.
3991The descriptor set is optional and defaults to 0 if not provided.
3992
3993```c++
3994// A structured buffer with binding 23 in descriptor set 102.
3995[[vk::binding(23, 102)]] StructuredBuffer<float> Buf;
3996
3997// A structured buffer with binding 14 in descriptor set 0.
3998[[vk::binding(14)]] StructuredBuffer<float> Buf2;
3999
4000// A cbuffer with binding 1 in descriptor set 2.
4001[[vk::binding(1, 2)]] cbuffer MyCBuffer {
4002 float4x4 worldViewProj;
4003};
4004```)reST";
4005
4006static const char AttrDoc_HLSLVkConstantId[] = R"reST(The `vk::constant_id` attribute specifies the id for a SPIR-V specialization
4007constant. The attribute applies to const global scalar variables. The variable must be initialized with a C++11 constexpr.
4008In SPIR-V, the
4009variable will be replaced with an `OpSpecConstant` with the given id.
4010The syntax is:
4011
4012```text
4013``[[vk::constant_id(<Id>)]] const T Name = <Init>``
4014```)reST";
4015
4016static const char AttrDoc_HLSLVkExtBuiltinInput[] = R"reST(Vulkan shaders have `Input` builtins. Those variables are externally
4017initialized by the driver/pipeline, but each copy is private to the current
4018lane.
4019
4020Those builtins can be declared using the `[[vk::ext_builtin_input]]` attribute
4021like follows:
4022
4023```c++
4024[[vk::ext_builtin_input(/* WorkgroupId */ 26)]]
4025static const uint3 groupid;
4026```
4027
4028This variable will be lowered into a module-level variable, with the `Input`
4029storage class, and the `BuiltIn 26` decoration.
4030
4031The full documentation for this inline SPIR-V attribute can be found here:
4032<https://github.com/microsoft/hlsl-specs/blob/main/proposals/0011-inline-spirv.md>)reST";
4033
4034static const char AttrDoc_HLSLVkExtBuiltinOutput[] = R"reST(Vulkan shaders have `Output` builtins. Those variables are externally
4035visible to the driver/pipeline, but each copy is private to the current
4036lane.
4037
4038Those builtins can be declared using the `[[vk::ext_builtin_output]]`
4039attribute like follows:
4040
4041```c++
4042[[vk::ext_builtin_output(/* Position */ 0)]]
4043static float4 position;
4044```
4045
4046This variable will be lowered into a module-level variable, with the `Output`
4047storage class, and the `BuiltIn 0` decoration.
4048
4049The full documentation for this inline SPIR-V attribute can be found here:
4050<https://github.com/microsoft/hlsl-specs/blob/main/proposals/0011-inline-spirv.md>)reST";
4051
4052static const char AttrDoc_HLSLVkLocation[] = R"reST(Attribute used for specifying the location number for the stage input/output
4053variables. Allowed on function parameters, function returns, and struct
4054fields. This parameter has no effect when used outside of an entrypoint
4055parameter/parameter field/return value.
4056
4057This attribute maps to the 'Location' SPIR-V decoration.)reST";
4058
4059static const char AttrDoc_HLSLVkPushConstant[] = R"reST(Vulkan shaders have `PushConstants`
4060
4061The `[[vk::push_constant]]` attribute allows you to declare this
4062global variable as a push constant when targeting Vulkan.
4063This attribute is ignored otherwise.
4064
4065This attribute must be applied to the variable, not underlying type.
4066The variable type must be a struct, per the requirements of Vulkan, "there
4067must be no more than one push constant block statically used per shader entry
4068point.")reST";
4069
4070static const char AttrDoc_HLSLWaveSize[] = R"reST(The `WaveSize` attribute specify a wave size on a shader entry point in order
4071to indicate either that a shader depends on or strongly prefers a specific wave
4072size.
4073There're 2 versions of the attribute: `WaveSize` and `RangedWaveSize`.
4074The syntax for `WaveSize` is:
4075
4076```text
4077``[WaveSize(<numLanes>)]``
4078```
4079
4080The allowed wave sizes that an HLSL shader may specify are the powers of 2
4081between 4 and 128, inclusive.
4082In other words, the set: [4, 8, 16, 32, 64, 128].
4083
4084The syntax for `RangedWaveSize` is:
4085
4086```text
4087``[WaveSize(<minWaveSize>, <maxWaveSize>, [prefWaveSize])]``
4088```
4089
4090Where minWaveSize is the minimum wave size supported by the shader representing
4091the beginning of the allowed range, maxWaveSize is the maximum wave size
4092supported by the shader representing the end of the allowed range, and
4093prefWaveSize is the optional preferred wave size representing the size expected
4094to be the most optimal for this shader.
4095
4096`WaveSize` is available for HLSL shader model 6.6 and later.
4097`RangedWaveSize` available for HLSL shader model 6.8 and later.
4098
4099The full documentation is available here: <https://microsoft.github.io/DirectX-Specs/d3d/HLSL_SM_6_6_WaveSize.html>
4100and <https://microsoft.github.io/hlsl-specs/proposals/0013-wave-size-range.html>)reST";
4101
4102static const char AttrDoc_Hot[] = R"reST(`__attribute__((hot))` marks a function as hot, as a manual alternative to PGO hotness data.
4103If PGO data is available, the annotation `__attribute__((hot))` overrides the profile count based hotness (unlike `__attribute__((cold))`).)reST";
4104
4105static const char AttrDoc_HybridPatchable[] = R"reST(The `hybrid_patchable` attribute declares an ARM64EC function with an additional
4106x86-64 thunk, which may be patched at runtime.
4107
4108For more information see
4109[ARM64EC ABI documentation](https://learn.microsoft.com/en-us/windows/arm/arm64ec-abi).)reST";
4110
4111static const char AttrDoc_IBAction[] = R"reST(No documentation.)reST";
4112
4113static const char AttrDoc_IBOutlet[] = R"reST(No documentation.)reST";
4114
4115static const char AttrDoc_IBOutletCollection[] = R"reST(No documentation.)reST";
4116
4117static const char AttrDoc_IFunc[] = R"reST(`__attribute__((ifunc("resolver")))` is used to mark that the address of a
4118declaration should be resolved at runtime by calling a resolver function.
4119
4120The symbol name of the resolver function is given in quotes. A function with
4121this name (after mangling) must be defined in the current translation unit; it
4122may be `static`. The resolver function should return a pointer.
4123
4124The `ifunc` attribute may only be used on a function declaration. A function
4125declaration with an `ifunc` attribute is considered to be a definition of the
4126declared entity. The entity must not have weak linkage; for example, in C++,
4127it cannot be applied to a declaration if a definition at that location would be
4128considered inline.
4129
4130Not all targets support this attribute:
4131
4132- ELF target support depends on both the linker and runtime linker, and is
4133 available in at least lld 4.0 and later, binutils 2.20.1 and later, glibc
4134 v2.11.1 and later, and FreeBSD 9.1 and later.
4135- Mach-O targets support it, but with slightly different semantics: the resolver
4136 is run at first call, instead of at load time by the runtime linker.
4137- Windows target supports it on AArch64, but with different semantics: the
4138 `ifunc` is replaced with a global function pointer, and the call is replaced
4139 with an indirect call. The function pointer is initialized by a constructor
4140 that calls the resolver.
4141- Baremetal target supports it on AVR.
4142- AIX/XCOFF supports it via a compiler-only solution. An ifunc appears as a
4143 regular function (has an entry point `.foo[PR]` and a function descriptor
4144 `foo[DS]`). The entry point is a stub that branches to the function address
4145 in the descriptor, and the descriptor is initialized via a constructor
4146 function (`__init_ifuncs`) that is linked into every shared object and
4147 executable. `__init_ifuncs` calls the resolver of each ifunc and stores the
4148 result in the corresponding descriptor.
4149- Other targets currently do not support this attribute.)reST";
4150
4151static const char AttrDoc_InferredNoReturn[] = R"reST()reST";
4152
4153static const char AttrDoc_InitPriority[] = R"reST(In C++, the order in which global variables are initialized across translation
4154units is unspecified, unlike the ordering within a single translation unit. The
4155`init_priority` attribute allows you to specify a relative ordering for the
4156initialization of objects declared at namespace scope in C++ within a single
4157linked image on supported platforms. The priority is given as an integer constant
4158expression between 101 and 65535 (inclusive). Priorities outside of that range are
4159reserved for use by the implementation. A lower value indicates a higher priority
4160of initialization. Note that only the relative ordering of values is important.
4161For example:
4162
4163```c++
4164struct SomeType { SomeType(); };
4165__attribute__((init_priority(200))) SomeType Obj1;
4166__attribute__((init_priority(101))) SomeType Obj2;
4167```
4168
4169`Obj2` will be initialized *before* `Obj1` despite the usual order of
4170initialization being the opposite.
4171
4172Note that this attribute does not control the initialization order of objects
4173across final linked image boundaries like shared objects and executables.
4174
4175On Windows, `init_seg(compiler)` is represented with a priority of 200 and
4176`init_seg(library)` is represented with a priority of 400. `init_seg(user)`
4177uses the default 65535 priority.
4178
4179On MachO platforms, this attribute also does not control the order of initialization
4180across translation units, where it only affects the order within a single TU.
4181
4182This attribute is only supported for C++ and Objective-C++ and is ignored in
4183other language modes.)reST";
4184
4185static const char AttrDoc_InitSeg[] = R"reST(The attribute applied by `pragma init_seg()` controls the section into
4186which global initialization function pointers are emitted. It is only
4187available with `-fms-extensions`. Typically, this function pointer is
4188emitted into `.CRT$XCU` on Windows. The user can change the order of
4189initialization by using a different section name with the same
4190`.CRT$XC` prefix and a suffix that sorts lexicographically before or
4191after the standard `.CRT$XCU` sections. See the [init_seg][init_seg]
4192documentation on MSDN for more information.
4193
4194[init_seg]: http://msdn.microsoft.com/en-us/library/7977wcck(v=vs.110).aspx)reST";
4195
4196static const char AttrDoc_IntelOclBicc[] = R"reST(No documentation.)reST";
4197
4198static const char AttrDoc_InternalLinkage[] = R"reST(The `internal_linkage` attribute changes the linkage type of the declaration
4199to internal. This is similar to C-style `static`, but can be used on classes
4200and class methods. When applied to a class definition, this attribute affects
4201all methods and static data members of that class. This can be used to contain
4202the ABI of a C++ library by excluding unwanted class methods from the export
4203tables.)reST";
4204
4205static const char AttrDoc_LTOVisibilityPublic[] = R"reST(See {doc}`LTOVisibility`.)reST";
4206
4207static const char AttrDoc_LayoutVersion[] = R"reST(The layout_version attribute requests that the compiler utilize the class
4208layout rules of a particular compiler version.
4209This attribute only applies to struct, class, and union types.
4210It is only supported when using the Microsoft C++ ABI.)reST";
4211
4212static const char AttrDoc_Leaf[] = R"reST(The `leaf` attribute is used as a compiler hint to improve dataflow analysis
4213in library functions. Functions marked with the `leaf` attribute are not allowed
4214to jump back into the caller's translation unit, whether through invoking a
4215callback function, an external function call, use of `longjmp`, or other means.
4216Therefore, they cannot use or modify any data that does not escape the caller function's
4217compilation unit.
4218
4219For more information see
4220`gcc documentation <https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html>`)reST";
4221
4222static const char AttrDoc_LifetimeBound[] = R"reST(The `lifetimebound` attribute on a function parameter or implicit object
4223parameter indicates that objects that are referred to by that parameter may
4224also be referred to by the return value of the annotated function (or, for a
4225parameter of a constructor, by the value of the constructed object).
4226
4227By default, a reference is considered to refer to its referenced object, a
4228pointer is considered to refer to its pointee, a `std::initializer_list<T>`
4229is considered to refer to its underlying array, and aggregates (arrays and
4230simple `struct`s) are considered to refer to all objects that their
4231transitive subobjects refer to.
4232
4233Clang warns if it is able to detect that an object or reference refers to
4234another object with a shorter lifetime. For example, Clang will warn if a
4235function returns a reference to a local variable, or if a reference is bound to
4236a temporary object whose lifetime is not extended. By using the
4237`lifetimebound` attribute, this determination can be extended to look through
4238user-declared functions. For example:
4239
4240```c++
4241#include <map>
4242#include <string>
4243
4244using namespace std::literals;
4245
4246// Returns m[key] if key is present, or default_value if not.
4247template<typename T, typename U>
4248const U &get_or_default(const std::map<T, U> &m [[clang::lifetimebound]],
4249 const T &key, /* note, not lifetimebound */
4250 const U &default_value [[clang::lifetimebound]]) {
4251 if (auto iter = m.find(key); iter != m.end()) return iter->second;
4252 else return default_value;
4253}
4254
4255int main() {
4256 std::map<std::string, std::string> m;
4257 // warning: temporary bound to local reference 'val1' will be destroyed
4258 // at the end of the full-expression
4259 const std::string &val1 = get_or_default(m, "foo"s, "bar"s);
4260
4261 // No warning in this case.
4262 std::string def_val = "bar"s;
4263 const std::string &val2 = get_or_default(m, "foo"s, def_val);
4264
4265 return 0;
4266}
4267```
4268
4269The attribute can be applied to the implicit `this` parameter of a member
4270function by writing the attribute after the function type:
4271
4272```c++
4273struct string {
4274 // The returned pointer should not outlive ``*this``.
4275 const char *data() const [[clang::lifetimebound]];
4276};
4277```
4278
4279This attribute is inspired by the C++ committee paper [P0936R0](http://wg21.link/p0936r0), but does not affect whether temporary objects
4280have their lifetimes extended.)reST";
4281
4282static const char AttrDoc_LifetimeCaptureBy[] = R"reST(Similar to [lifetimebound], the `lifetime_capture_by` attribute family on a
4283function parameter or implicit object parameter indicates that a capturing
4284entity may refer to the object referred to by that parameter. The capturing
4285entity can be named in `lifetime_capture_by(X)` or selected by one of the
4286standalone special forms listed below.
4287
4288Below is a list of types of the parameters and what they're considered to refer to:
4289
4290- A reference param (of non-view type) is considered to refer to its referenced object.
4291- A pointer param (of non-view type) is considered to refer to its pointee.
4292- View type param (type annotated with `[[gsl::Pointer()]]`) is considered to refer
4293 to its pointee (gsl owner). This holds true even if the view type appears as a reference
4294 in the parameter. For example, both `std::string_view` and
4295 `const std::string_view &` are considered to refer to a `std::string`.
4296- A `std::initializer_list<T>` is considered to refer to its underlying array.
4297- Aggregates (arrays and simple `struct`s) are considered to refer to all
4298 objects that their transitive subobjects refer to.
4299
4300Clang would diagnose when a temporary object is used as an argument to such an
4301annotated parameter.
4302In this case, the capturing entity `X` could capture a dangling reference to this
4303temporary object.
4304
4305```c++
4306void addToSet(std::string_view a [[clang::lifetime_capture_by(s)]], std::set<std::string_view>& s) {
4307 s.insert(a);
4308}
4309void use() {
4310 std::set<std::string_view> s;
4311 addToSet(std::string(), s); // Warning: object whose reference is captured by 's' will be destroyed at the end of the full-expression.
4312 // ^^^^^^^^^^^^^
4313 std::string local;
4314 addToSet(local, s); // Ok.
4315}
4316```
4317
4318The capturing entity can be one of the following:
4319
4320- Another (named) function parameter.
4321
4322 ```c++
4323 void addToSet(std::string_view a [[clang::lifetime_capture_by(s)]], std::set<std::string_view>& s) {
4324 s.insert(a);
4325 }
4326 ```
4327
4328- `this` (in case of member functions), written as
4329 `lifetime_capture_by_this`.
4330
4331 ```c++
4332 class S {
4333 void addToSet(std::string_view a [[clang::lifetime_capture_by_this]]) {
4334 s.insert(a);
4335 }
4336 std::set<std::string_view> s;
4337 };
4338 ```
4339
4340 Note: When applied to a constructor parameter, `[[clang::lifetime_capture_by_this]]` is just an alias of `[[clang::lifetimebound]]`.
4341
4342- `global` and `unknown`, written as `lifetime_capture_by_global` and
4343 `lifetime_capture_by_unknown` respectively.
4344
4345 ```c++
4346 std::set<std::string_view> s;
4347 void addToSet(std::string_view a [[clang::lifetime_capture_by_global]]) {
4348 s.insert(a);
4349 }
4350 void addSomewhere(std::string_view a [[clang::lifetime_capture_by_unknown]]);
4351 ```
4352
4353The attribute can be applied to the implicit `this` parameter of a member
4354function by writing the attribute after the function type:
4355
4356```c++
4357struct S {
4358 const char *data(std::set<S*>& s) [[clang::lifetime_capture_by(s)]] {
4359 s.insert(this);
4360 }
4361};
4362```
4363
4364The parameter-list form supports specifying more than one capturing entity:
4365
4366```c++
4367void addToSets(std::string_view a [[clang::lifetime_capture_by(s1, s2)]],
4368 std::set<std::string_view>& s1,
4369 std::set<std::string_view>& s2) {
4370 s1.insert(a);
4371 s2.insert(a);
4372}
4373```
4374
4375Distinct `lifetime_capture_by` forms can also be combined on the same
4376declaration, but each form can appear at most once. For example,
4377`[[clang::lifetime_capture_by(s), clang::lifetime_capture_by_this]]` is
4378allowed, but two `[[clang::lifetime_capture_by(...)]]` attributes or two
4379`[[clang::lifetime_capture_by_this]]` attributes on the same declaration are
4380rejected.
4381
4382Limitation: The capturing entity `X` is not used by the analysis and is
4383used for documentation purposes only. This is because the analysis is
4384statement-local and only detects use of a temporary as an argument to the
4385annotated parameter.
4386
4387```c++
4388void addToSet(std::string_view a [[clang::lifetime_capture_by(s)]], std::set<std::string_view>& s);
4389void use() {
4390 std::set<std::string_view> s;
4391 if (foo()) {
4392 std::string str;
4393 addToSet(str, s); // Not detected.
4394 }
4395}
4396```)reST";
4397
4398static const char AttrDoc_Likely[] = R"reST(The `likely` and `unlikely` attributes are used as compiler hints.
4399The attributes are used to aid the compiler to determine which branch is
4400likely or unlikely to be taken. This is done by marking the branch substatement
4401with one of the two attributes.
4402
4403It isn't allowed to annotate a single statement with both `likely` and
4404`unlikely`. Annotating the `true` and `false` branch of an `if`
4405statement with the same likelihood attribute will result in a diagnostic and
4406the attributes are ignored on both branches.
4407
4408In a `switch` statement it's allowed to annotate multiple `case` labels
4409or the `default` label with the same likelihood attribute. This makes
4410\* all labels without an attribute have a neutral likelihood,
4411\* all labels marked `[[likely]]` have an equally positive likelihood, and
4412\* all labels marked `[[unlikely]]` have an equally negative likelihood.
4413The neutral likelihood is the more likely of path execution than the negative
4414likelihood. The positive likelihood is the more likely of path of execution
4415than the neutral likelihood.
4416
4417These attributes have no effect on the generated code when using
4418PGO (Profile-Guided Optimization) or at optimization level 0.
4419
4420In Clang, the attributes will be ignored if they're not placed on
4421\* the `case` or `default` label of a `switch` statement,
4422\* or on the substatement of an `if` or `else` statement,
4423\* or on the substatement of an `for` or `while` statement.
4424The C++ Standard recommends to honor them on every statement in the
4425path of execution, but that can be confusing:
4426
4427```c++
4428if (b) {
4429 [[unlikely]] --b; // Per the standard this is in the path of
4430 // execution, so this branch should be considered
4431 // unlikely. However, Clang ignores the attribute
4432 // here since it is not on the substatement.
4433}
4434
4435if (b) {
4436 --b;
4437 if(b)
4438 return;
4439 [[unlikely]] --b; // Not in the path of execution,
4440} // the branch has no likelihood information.
4441
4442if (b) {
4443 --b;
4444 foo(b);
4445 // Whether or not the next statement is in the path of execution depends
4446 // on the declaration of foo():
4447 // In the path of execution: void foo(int);
4448 // Not in the path of execution: [[noreturn]] void foo(int);
4449 // This means the likelihood of the branch depends on the declaration
4450 // of foo().
4451 [[unlikely]] --b;
4452}
4453```
4454
4455Below are some example usages of the likelihood attributes and their effects:
4456
4457```c++
4458if (b) [[likely]] { // Placement on the first statement in the branch.
4459 // The compiler will optimize to execute the code here.
4460} else {
4461}
4462
4463if (b)
4464 [[unlikely]] b++; // Placement on the first statement in the branch.
4465else {
4466 // The compiler will optimize to execute the code here.
4467}
4468
4469if (b) {
4470 [[unlikely]] b++; // Placement on the second statement in the branch.
4471} // The attribute will be ignored.
4472
4473if (b) [[likely]] {
4474 [[unlikely]] b++; // No contradiction since the second attribute
4475} // is ignored.
4476
4477if (b)
4478 ;
4479else [[likely]] {
4480 // The compiler will optimize to execute the code here.
4481}
4482
4483if (b)
4484 ;
4485else
4486 // The compiler will optimize to execute the next statement.
4487 [[likely]] b = f();
4488
4489if (b) [[likely]]; // Both branches are likely. A diagnostic is issued
4490else [[likely]]; // and the attributes are ignored.
4491
4492if (b)
4493 [[likely]] int i = 5; // Issues a diagnostic since the attribute
4494 // isn't allowed on a declaration.
4495
4496switch (i) {
4497 [[likely]] case 1: // This value is likely
4498 ...
4499 break;
4500
4501 [[unlikely]] case 2: // This value is unlikely
4502 ...
4503 [[fallthrough]];
4504
4505 case 3: // No likelihood attribute
4506 ...
4507 [[likely]] break; // No effect
4508
4509 case 4: [[likely]] { // attribute on substatement has no effect
4510 ...
4511 break;
4512 }
4513
4514 [[unlikely]] default: // All other values are unlikely
4515 ...
4516 break;
4517}
4518
4519switch (i) {
4520 [[likely]] case 0: // This value and code path is likely
4521 ...
4522 [[fallthrough]];
4523
4524 case 1: // No likelihood attribute, code path is neutral
4525 break; // falling through has no effect on the likelihood
4526
4527 case 2: // No likelihood attribute, code path is neutral
4528 [[fallthrough]];
4529
4530 [[unlikely]] default: // This value and code path are both unlikely
4531 break;
4532}
4533
4534for(int i = 0; i != size; ++i) [[likely]] {
4535 ... // The loop is the likely path of execution
4536}
4537
4538for(const auto &E : Elements) [[likely]] {
4539 ... // The loop is the likely path of execution
4540}
4541
4542while(i != size) [[unlikely]] {
4543 ... // The loop is the unlikely path of execution
4544} // The generated code will optimize to skip the loop body
4545
4546while(true) [[unlikely]] {
4547 ... // The attribute has no effect
4548} // Clang elides the comparison and generates an infinite
4549 // loop
4550```)reST";
4551
4552static const char AttrDoc_LoaderUninitialized[] = R"reST(The `loader_uninitialized` attribute can be placed on global variables to
4553indicate that the variable does not need to be zero initialized by the loader.
4554On most targets, zero-initialization does not incur any additional cost.
4555For example, most general purpose operating systems deliberately ensure
4556that all memory is properly initialized in order to avoid leaking privileged
4557information from the kernel or other programs. However, some targets
4558do not make this guarantee, and on these targets, avoiding an unnecessary
4559zero-initialization can have a significant impact on load times and/or code
4560size.
4561
4562A declaration with this attribute is a non-tentative definition just as if it
4563provided an initializer. Variables with this attribute are considered to be
4564uninitialized in the same sense as a local variable, and the programs must
4565write to them before reading from them. If the variable's type is a C++ class
4566type with a non-trivial default constructor, or an array thereof, this attribute
4567only suppresses the static zero-initialization of the variable, not the dynamic
4568initialization provided by executing the default constructor.)reST";
4569
4570static const char AttrDoc_LockReturned[] = R"reST(No documentation.)reST";
4571
4572static const char AttrDoc_LocksExcluded[] = R"reST(No documentation.)reST";
4573
4574static const char AttrDoc_LoopHint[] = R"reST(The `#pragma clang loop` directive allows loop optimization hints to be
4575specified for the subsequent loop. The directive allows pipelining to be
4576disabled, or vectorization, vector predication, interleaving, and unrolling to
4577be enabled or disabled. Vector width, vector predication, interleave count,
4578unrolling count, and the initiation interval for pipelining can be explicitly
4579specified. See
4580{ref}`loop hint optimizations <langext-loop-hint-optimizations>` for details.)reST";
4581
4582static const char AttrDoc_M68kInterrupt[] = R"reST(No documentation.)reST";
4583
4584static const char AttrDoc_M68kRTD[] = R"reST(On M68k targets, this attribute changes the calling convention of a function
4585to clear parameters off the stack on return. In other words, callee is
4586responsible for cleaning out the stack space allocated for incoming paramters.
4587This convention does not support variadic calls or unprototyped functions in C.
4588When targeting M68010 or newer CPUs, this calling convention is implemented
4589using the `rtd` instruction.)reST";
4590
4591static const char AttrDoc_MIGServerRoutine[] = R"reST(The Mach Interface Generator release-on-success convention dictates
4592
4593functions that follow it to only release arguments passed to them when they
4594return "success" (a `kern_return_t` error code that indicates that
4595no errors have occurred). Otherwise the release is performed by the MIG client
4596that called the function. The annotation `__attribute__((mig_server_routine))`
4597is applied in order to specify which functions are expected to follow the
4598convention. This allows the Static Analyzer to find bugs caused by violations of
4599that convention. The attribute would normally appear on the forward declaration
4600of the actual server routine in the MIG server header, but it may also be
4601added to arbitrary functions that need to follow the same convention - for
4602example, a user can add them to auxiliary functions called by the server routine
4603that have their return value of type `kern_return_t` unconditionally returned
4604from the routine. The attribute can be applied to C++ methods, and in this case
4605it will be automatically applied to overrides if the method is virtual. The
4606attribute can also be written using C++11 syntax: `[[mig::server_routine]]`.)reST";
4607
4608static const char AttrDoc_MSABI[] = R"reST(On non-Windows x86_64 and aarch64 targets, this attribute changes the calling convention of
4609a function to match the default convention used on Windows. This
4610attribute has no effect on Windows targets or non-x86_64, non-aarch64 targets.)reST";
4611
4612static const char AttrDoc_MSAllocator[] = R"reST(The `__declspec(allocator)` attribute is applied to functions that allocate
4613memory, such as operator new in C++. When CodeView debug information is emitted
4614(enabled by `clang -gcodeview` or `clang-cl /Z7`), Clang will attempt to
4615record the code offset of heap allocation call sites in the debug info. It will
4616also record the type being allocated using some local heuristics. The Visual
4617Studio debugger uses this information to [profile memory usage][profile memory usage].
4618
4619This attribute does not affect optimizations in any way, unlike GCC's
4620`__attribute__((malloc))`.
4621
4622[profile memory usage]: https://docs.microsoft.com/en-us/visualstudio/profiling/memory-usage)reST";
4623
4624static const char AttrDoc_MSConstexpr[] = R"reST(The `[[msvc::constexpr]]` attribute can be applied only to a function
4625definition or a `return` statement. It does not impact function declarations.
4626A `[[msvc::constexpr]]` function cannot be `constexpr` or `consteval`.
4627A `[[msvc::constexpr]]` function is treated as if it were a `constexpr` function
4628when it is evaluated in a constant context of `[[msvc::constexpr]] return` statement.
4629Otherwise, it is treated as a regular function.
4630
4631Semantics of this attribute are enabled only under MSVC compatibility
4632(`-fms-compatibility-version`) 19.33 and later.)reST";
4633
4634static const char AttrDoc_MSInheritance[] = R"reST(This collection of keywords is enabled under `-fms-extensions` and controls
4635the pointer-to-member representation used on `*-*-win32` targets.
4636
4637The `*-*-win32` targets utilize a pointer-to-member representation which
4638varies in size and alignment depending on the definition of the underlying
4639class.
4640
4641However, this is problematic when a forward declaration is only available and
4642no definition has been made yet. In such cases, Clang is forced to utilize the
4643most general representation that is available to it.
4644
4645These keywords make it possible to use a pointer-to-member representation other
4646than the most general one regardless of whether or not the definition will ever
4647be present in the current translation unit.
4648
4649This family of keywords belong between the `class-key` and `class-name`:
4650
4651```c++
4652struct __single_inheritance S;
4653int S::*i;
4654struct S {};
4655```
4656
4657This keyword can be applied to class templates but only has an effect when used
4658on full specializations:
4659
4660```c++
4661template <typename T, typename U> struct __single_inheritance A; // warning: inheritance model ignored on primary template
4662template <typename T> struct __multiple_inheritance A<T, T>; // warning: inheritance model ignored on partial specialization
4663template <> struct __single_inheritance A<int, float>;
4664```
4665
4666Note that choosing an inheritance model less general than strictly necessary is
4667an error:
4668
4669```c++
4670struct __multiple_inheritance S; // error: inheritance model does not match definition
4671int S::*i;
4672struct S {};
4673```)reST";
4674
4675static const char AttrDoc_MSNoVTable[] = R"reST(This attribute can be added to a class declaration or definition to signal to
4676the compiler that constructors and destructors will not reference the virtual
4677function table. It is only supported when using the Microsoft C++ ABI.)reST";
4678
4679static const char AttrDoc_MSP430Interrupt[] = R"reST(No documentation.)reST";
4680
4681static const char AttrDoc_MSStruct[] = R"reST(The `ms_struct` and `gcc_struct` attributes request the compiler to enter a
4682special record layout compatibility mode which mimics the layout of Microsoft or
4683Itanium C++ ABI respectively. Obviously, if the current C++ ABI matches the
4684requested ABI, the attribute does nothing. However, if it does not, annotated
4685structure or class is laid out in a special compatibility mode, which slightly
4686changes offsets for fields and bit-fields. The intention is to match the layout
4687of the requested ABI for structures which only use C features.
4688
4689Note that the default behavior can be controlled by `-mms-bitfields` and
4690`-mno-ms-bitfields` switches and via `#pragma ms_struct`.
4691
4692The primary difference is for bitfields, where the MS variant only packs
4693adjacent fields into the same allocation unit if they have integral types
4694of the same size, while the GCC/Itanium variant packs all fields in a bitfield
4695tightly.)reST";
4696
4697static const char AttrDoc_MSVtorDisp[] = R"reST()reST";
4698
4699static const char AttrDoc_MallocSpan[] = R"reST(The `malloc_span` attribute can be used to mark that a function which acts
4700like a system memory allocation function and returns a span-like structure,
4701where the returned memory range does not alias storage from any other object
4702accessible to the caller.
4703
4704In this context, a span-like structure is assumed to have two non-static data
4705members, one of which is a pointer to the start of the allocated memory and
4706the other one is either an integer type containing the size of the actually
4707allocated memory or a pointer to the end of the allocated region. Note, static
4708data members do not impact whether a type is span-like or not.
4709
4710In combination with the `alloc_size` attribute, if the begin pointer is
4711non-null, the size of the returned span-like object has to be greater or equal
4712to the number of bytes guaranteed to be dereferenceable by `alloc_size`. It also
4713guarantees that the number of dereferenceable bytes is at least size.)reST";
4714
4715static const char AttrDoc_MaxFieldAlignment[] = R"reST()reST";
4716
4717static const char AttrDoc_MayAlias[] = R"reST(No documentation.)reST";
4718
4719static const char AttrDoc_MaybeUndef[] = R"reST(The `maybe_undef` attribute can be placed on a function parameter. It indicates
4720that the parameter is allowed to use undef values. It informs the compiler
4721to insert a freeze LLVM IR instruction on the function parameter.
4722Please note that this is an attribute that is used as an internal
4723implementation detail and not intended to be used by external users.
4724
4725In languages HIP, CUDA etc., some functions have multi-threaded semantics and
4726it is enough for only one or some threads to provide defined arguments.
4727Depending on semantics, undef arguments in some threads don't produce
4728undefined results in the function call. Since, these functions accept undefined
4729arguments, `maybe_undef` attribute can be placed.
4730
4731Sample usage:
4732
4733```c
4734void maybeundeffunc(int __attribute__((maybe_undef))param);
4735```)reST";
4736
4737static const char AttrDoc_MicroMips[] = R"reST(Clang supports the GNU style `__attribute__((micromips))` and
4738`__attribute__((nomicromips))` attributes on MIPS targets. These attributes
4739may be attached to a function definition and instructs the backend to generate
4740or not to generate microMIPS code for that function.
4741
4742These attributes override the `-mmicromips` and `-mno-micromips` options
4743on the command line.)reST";
4744
4745static const char AttrDoc_MinSize[] = R"reST(This function attribute indicates that optimization passes and code generator passes
4746make choices that keep the function code size as small as possible. Optimizations may
4747also sacrifice runtime performance in order to minimize the size of the generated code.)reST";
4748
4749static const char AttrDoc_MinVectorWidth[] = R"reST(Clang supports the `__attribute__((min_vector_width(width)))` attribute. This
4750attribute may be attached to a function and informs the backend that this
4751function desires vectors of at least this width to be generated. Target-specific
4752maximum vector widths still apply. This means even if you ask for something
4753larger than the target supports, you will only get what the target supports.
4754This attribute is meant to be a hint to control target heuristics that may
4755generate narrower vectors than what the target hardware supports.
4756
4757This is currently used by the X86 target to allow some CPUs that support 512-bit
4758vectors to be limited to using 256-bit vectors to avoid frequency penalties.
4759This is currently enabled with the `-prefer-vector-width=256` command line
4760option. The `min_vector_width` attribute can be used to prevent the backend
4761from trying to split vector operations to match the `prefer-vector-width`. All
4762X86 vector intrinsics from x86intrin.h already set this attribute. Additionally,
4763use of any of the X86-specific vector builtins will implicitly set this
4764attribute on the calling function. The intent is that explicitly writing vector
4765code using the X86 intrinsics will prevent `prefer-vector-width` from
4766affecting the code.)reST";
4767
4768static const char AttrDoc_Mips16[] = R"reST(No documentation.)reST";
4769
4770static const char AttrDoc_MipsInterrupt[] = R"reST(Clang supports the GNU style `__attribute__((interrupt("ARGUMENT")))` attribute on
4771MIPS targets. This attribute may be attached to a function definition and instructs
4772the backend to generate appropriate function entry/exit code so that it can be used
4773directly as an interrupt service routine.
4774
4775By default, the compiler will produce a function prologue and epilogue suitable for
4776an interrupt service routine that handles an External Interrupt Controller (eic)
4777generated interrupt. This behavior can be explicitly requested with the "eic"
4778argument.
4779
4780Otherwise, for use with vectored interrupt mode, the argument passed should be
4781of the form "vector=LEVEL" where LEVEL is one of the following values:
4782"sw0", "sw1", "hw0", "hw1", "hw2", "hw3", "hw4", "hw5". The compiler will
4783then set the interrupt mask to the corresponding level which will mask all
4784interrupts up to and including the argument.
4785
4786The semantics are as follows:
4787
4788- The prologue is modified so that the Exception Program Counter (EPC) and
4789 Status coprocessor registers are saved to the stack. The interrupt mask is
4790 set so that the function can only be interrupted by a higher priority
4791 interrupt. The epilogue will restore the previous values of EPC and Status.
4792- The prologue and epilogue are modified to save and restore all non-kernel
4793 registers as necessary.
4794- The FPU is disabled in the prologue, as the floating pointer registers are not
4795 spilled to the stack.
4796- The function return sequence is changed to use an exception return instruction.
4797- The parameter sets the interrupt mask for the function corresponding to the
4798 interrupt level specified. If no mask is specified the interrupt mask
4799 defaults to "eic".)reST";
4800
4801static const char AttrDoc_MipsLongCall[] = R"reST(Clang supports the `__attribute__((long_call))`, `__attribute__((far))`,
4802and `__attribute__((near))` attributes on MIPS targets. These attributes may
4803only be added to function declarations and change the code generated
4804by the compiler when directly calling the function. The `near` attribute
4805allows calls to the function to be made using the `jal` instruction, which
4806requires the function to be located in the same naturally aligned 256MB
4807segment as the caller. The `long_call` and `far` attributes are synonyms
4808and require the use of a different call sequence that works regardless
4809of the distance between the functions.
4810
4811These attributes have no effect for position-independent code.
4812
4813These attributes take priority over command line switches such
4814as `-mlong-calls` and `-mno-long-calls`.)reST";
4815
4816static const char AttrDoc_MipsShortCall[] = R"reST(Clang supports the `__attribute__((long_call))`, `__attribute__((far))`,
4817`__attribute__((short__call))`, and `__attribute__((near))` attributes
4818on MIPS targets. These attributes may only be added to function declarations
4819and change the code generated by the compiler when directly calling
4820the function. The `short_call` and `near` attributes are synonyms and
4821allow calls to the function to be made using the `jal` instruction, which
4822requires the function to be located in the same naturally aligned 256MB segment
4823as the caller. The `long_call` and `far` attributes are synonyms and
4824require the use of a different call sequence that works regardless
4825of the distance between the functions.
4826
4827These attributes have no effect for position-independent code.
4828
4829These attributes take priority over command line switches such
4830as `-mlong-calls` and `-mno-long-calls`.)reST";
4831
4832static const char AttrDoc_Mode[] = R"reST(No documentation.)reST";
4833
4834static const char AttrDoc_ModularFormat[] = R"reST(The `modular_format` attribute can be applied to a function that bears the
4835`format` attribute (or standard library functions) to indicate that the
4836implementation is "modular", that is, that the implementation is logically
4837divided into a number of named aspects. When the compiler can determine that
4838not all aspects of the implementation are needed for a given call, the compiler
4839may redirect the call to the identifier given as the first argument to the
4840attribute (the modular implementation function).
4841
4842The second argument is an implementation name, and the remaining arguments are
4843aspects of the format string for the compiler to report. The implementation
4844name is an unevaluated identifier in the C namespace.
4845
4846The compiler reports that a call requires an aspect by issuing a relocation for
4847the symbol `<impl_name>_<aspect>` at the point of the call. This arranges for
4848code and data needed to support the aspect of the implementation to be brought
4849into the link to satisfy weak references in the modular implemenation function.
4850If the compiler does not understand an aspect, it must summarily consider any
4851call to require that aspect.
4852
4853For example, say `printf` is annotated with
4854`modular_format(__modular_printf, "__printf", "float")`. Then, a call to
4855`printf(var, 42)` would be untouched. A call to `printf("%d", 42)` would
4856become a call to `__modular_printf` with the same arguments, as would
4857`printf("%f", 42.0)`. The latter would be accompanied with a strong
4858relocation against the symbol `__printf_float`, which would bring floating
4859point support for `printf` into the link.
4860
4861If the attribute appears more than once on a declaration, or across a chain of
4862redeclarations, it is an error for the attributes to have different arguments,
4863excepting that the aspects may be in any order.
4864
4865The following aspects are currently supported:
4866
4867- `fixed`: The call has a C ISO 18037 fixed-point argument.
4868- `float`: The call has a floating-point argument.)reST";
4869
4870static const char AttrDoc_MustTail[] = R"reST(If a `return` statement is marked `musttail`, this indicates that the
4871compiler must generate a tail call for the program to be correct, even when
4872optimizations are disabled. This guarantees that the call will not cause
4873unbounded stack growth if it is part of a recursive cycle in the call graph.
4874
4875If the callee is a virtual function that is implemented by a thunk, there is
4876no guarantee in general that the thunk tail-calls the implementation of the
4877virtual function, so such a call in a recursive cycle can still result in
4878unbounded stack growth.
4879
4880`clang::musttail` can only be applied to a `return` statement whose value
4881is the result of a function call (even functions returning void must use
4882`return`, although no value is returned). The target function must have the
4883same number of arguments as the caller. The types of the return value and all
4884arguments must be similar according to C++ rules (differing only in cv
4885qualifiers or array size), including the implicit "this" argument, if any.
4886Any variables in scope, including all arguments to the function and the
4887return value must be trivially destructible. The calling convention of the
4888caller and callee must match, and they must not be variadic functions or have
4889old style K&R C function declarations.
4890
4891The lifetimes of all local variables and function parameters end immediately
4892before the call to the function. This means that it is undefined behaviour to
4893pass a pointer or reference to a local variable to the called function, which
4894is not the case without the attribute. Clang will emit a warning in common
4895cases where this happens.
4896
4897`clang::musttail` provides assurances that the tail call can be optimized on
4898all targets, not just one.)reST";
4899
4900static const char AttrDoc_NSConsumed[] = R"reST(The behavior of a function with respect to reference counting for Foundation
4901(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
4902convention (e.g. functions starting with "get" are assumed to return at
4903`+0`).
4904
4905It can be overridden using a family of the following attributes. In
4906Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
4907a function communicates that the object is returned at `+1`, and the caller
4908is responsible for freeing it.
4909Similarly, the annotation `__attribute__((ns_returns_not_retained))`
4910specifies that the object is returned at `+0` and the ownership remains with
4911the callee.
4912The annotation `__attribute__((ns_consumes_self))` specifies that
4913the Objective-C method call consumes the reference to `self`, e.g. by
4914attaching it to a supplied parameter.
4915Additionally, parameters can have an annotation
4916`__attribute__((ns_consumed))`, which specifies that passing an owned object
4917as that parameter effectively transfers the ownership, and the caller is no
4918longer responsible for it.
4919These attributes affect code generation when interacting with ARC code, and
4920they are used by the Clang Static Analyzer.
4921
4922In C programs using CoreFoundation, a similar set of attributes:
4923`__attribute__((cf_returns_not_retained))`,
4924`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
4925have the same respective semantics when applied to CoreFoundation objects.
4926These attributes affect code generation when interacting with ARC code, and
4927they are used by the Clang Static Analyzer.
4928
4929Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
4930the same attribute family is present:
4931`__attribute__((os_returns_not_retained))`,
4932`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
4933with the same respective semantics.
4934Similar to `__attribute__((ns_consumes_self))`,
4935`__attribute__((os_consumes_this))` specifies that the method call consumes
4936the reference to "this" (e.g., when attaching it to a different object supplied
4937as a parameter).
4938Out parameters (parameters the function is meant to write into,
4939either via pointers-to-pointers or references-to-pointers)
4940may be annotated with `__attribute__((os_returns_retained))`
4941or `__attribute__((os_returns_not_retained))` which specifies that the object
4942written into the out parameter should (or respectively should not) be released
4943after use.
4944Since often out parameters may or may not be written depending on the exit
4945code of the function,
4946annotations `__attribute__((os_returns_retained_on_zero))`
4947and `__attribute__((os_returns_retained_on_non_zero))` specify that
4948an out parameter at `+1` is written if and only if the function returns a zero
4949(respectively non-zero) error code.
4950Observe that return-code-dependent out parameter annotations are only
4951available for retained out parameters, as non-retained object do not have to be
4952released by the callee.
4953These attributes are only used by the Clang Static Analyzer.
4954
4955The family of attributes `X_returns_X_retained` can be added to functions,
4956C++ methods, and Objective-C methods and properties.
4957Attributes `X_consumed` can be added to parameters of methods, functions,
4958and Objective-C methods.)reST";
4959
4960static const char AttrDoc_NSConsumesSelf[] = R"reST(The behavior of a function with respect to reference counting for Foundation
4961(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
4962convention (e.g. functions starting with "get" are assumed to return at
4963`+0`).
4964
4965It can be overridden using a family of the following attributes. In
4966Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
4967a function communicates that the object is returned at `+1`, and the caller
4968is responsible for freeing it.
4969Similarly, the annotation `__attribute__((ns_returns_not_retained))`
4970specifies that the object is returned at `+0` and the ownership remains with
4971the callee.
4972The annotation `__attribute__((ns_consumes_self))` specifies that
4973the Objective-C method call consumes the reference to `self`, e.g. by
4974attaching it to a supplied parameter.
4975Additionally, parameters can have an annotation
4976`__attribute__((ns_consumed))`, which specifies that passing an owned object
4977as that parameter effectively transfers the ownership, and the caller is no
4978longer responsible for it.
4979These attributes affect code generation when interacting with ARC code, and
4980they are used by the Clang Static Analyzer.
4981
4982In C programs using CoreFoundation, a similar set of attributes:
4983`__attribute__((cf_returns_not_retained))`,
4984`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
4985have the same respective semantics when applied to CoreFoundation objects.
4986These attributes affect code generation when interacting with ARC code, and
4987they are used by the Clang Static Analyzer.
4988
4989Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
4990the same attribute family is present:
4991`__attribute__((os_returns_not_retained))`,
4992`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
4993with the same respective semantics.
4994Similar to `__attribute__((ns_consumes_self))`,
4995`__attribute__((os_consumes_this))` specifies that the method call consumes
4996the reference to "this" (e.g., when attaching it to a different object supplied
4997as a parameter).
4998Out parameters (parameters the function is meant to write into,
4999either via pointers-to-pointers or references-to-pointers)
5000may be annotated with `__attribute__((os_returns_retained))`
5001or `__attribute__((os_returns_not_retained))` which specifies that the object
5002written into the out parameter should (or respectively should not) be released
5003after use.
5004Since often out parameters may or may not be written depending on the exit
5005code of the function,
5006annotations `__attribute__((os_returns_retained_on_zero))`
5007and `__attribute__((os_returns_retained_on_non_zero))` specify that
5008an out parameter at `+1` is written if and only if the function returns a zero
5009(respectively non-zero) error code.
5010Observe that return-code-dependent out parameter annotations are only
5011available for retained out parameters, as non-retained object do not have to be
5012released by the callee.
5013These attributes are only used by the Clang Static Analyzer.
5014
5015The family of attributes `X_returns_X_retained` can be added to functions,
5016C++ methods, and Objective-C methods and properties.
5017Attributes `X_consumed` can be added to parameters of methods, functions,
5018and Objective-C methods.)reST";
5019
5020static const char AttrDoc_NSErrorDomain[] = R"reST(In Cocoa frameworks in Objective-C, one can group related error codes in enums
5021and categorize these enums with error domains.
5022
5023The `ns_error_domain` attribute indicates a global `NSString` or
5024`CFString` constant representing the error domain that an error code belongs
5025to. For pointer uniqueness and code size this is a constant symbol, not a
5026literal.
5027
5028The domain and error code need to be used together. The `ns_error_domain`
5029attribute links error codes to their domain at the source level.
5030
5031This metadata is useful for documentation purposes, for static analysis, and for
5032improving interoperability between Objective-C and Swift. It is not used for
5033code generation in Objective-C.
5034
5035For example:
5036
5037```objc
5038#define NS_ERROR_ENUM(_type, _name, _domain) \
5039 enum _name : _type _name; enum __attribute__((ns_error_domain(_domain))) _name : _type
5040
5041extern NSString *const MyErrorDomain;
5042typedef NS_ERROR_ENUM(unsigned char, MyErrorEnum, MyErrorDomain) {
5043 MyErrFirst,
5044 MyErrSecond,
5045};
5046```)reST";
5047
5048static const char AttrDoc_NSReturnsAutoreleased[] = R"reST(The behavior of a function with respect to reference counting for Foundation
5049(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
5050convention (e.g. functions starting with "get" are assumed to return at
5051`+0`).
5052
5053It can be overridden using a family of the following attributes. In
5054Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
5055a function communicates that the object is returned at `+1`, and the caller
5056is responsible for freeing it.
5057Similarly, the annotation `__attribute__((ns_returns_not_retained))`
5058specifies that the object is returned at `+0` and the ownership remains with
5059the callee.
5060The annotation `__attribute__((ns_consumes_self))` specifies that
5061the Objective-C method call consumes the reference to `self`, e.g. by
5062attaching it to a supplied parameter.
5063Additionally, parameters can have an annotation
5064`__attribute__((ns_consumed))`, which specifies that passing an owned object
5065as that parameter effectively transfers the ownership, and the caller is no
5066longer responsible for it.
5067These attributes affect code generation when interacting with ARC code, and
5068they are used by the Clang Static Analyzer.
5069
5070In C programs using CoreFoundation, a similar set of attributes:
5071`__attribute__((cf_returns_not_retained))`,
5072`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
5073have the same respective semantics when applied to CoreFoundation objects.
5074These attributes affect code generation when interacting with ARC code, and
5075they are used by the Clang Static Analyzer.
5076
5077Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
5078the same attribute family is present:
5079`__attribute__((os_returns_not_retained))`,
5080`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
5081with the same respective semantics.
5082Similar to `__attribute__((ns_consumes_self))`,
5083`__attribute__((os_consumes_this))` specifies that the method call consumes
5084the reference to "this" (e.g., when attaching it to a different object supplied
5085as a parameter).
5086Out parameters (parameters the function is meant to write into,
5087either via pointers-to-pointers or references-to-pointers)
5088may be annotated with `__attribute__((os_returns_retained))`
5089or `__attribute__((os_returns_not_retained))` which specifies that the object
5090written into the out parameter should (or respectively should not) be released
5091after use.
5092Since often out parameters may or may not be written depending on the exit
5093code of the function,
5094annotations `__attribute__((os_returns_retained_on_zero))`
5095and `__attribute__((os_returns_retained_on_non_zero))` specify that
5096an out parameter at `+1` is written if and only if the function returns a zero
5097(respectively non-zero) error code.
5098Observe that return-code-dependent out parameter annotations are only
5099available for retained out parameters, as non-retained object do not have to be
5100released by the callee.
5101These attributes are only used by the Clang Static Analyzer.
5102
5103The family of attributes `X_returns_X_retained` can be added to functions,
5104C++ methods, and Objective-C methods and properties.
5105Attributes `X_consumed` can be added to parameters of methods, functions,
5106and Objective-C methods.)reST";
5107
5108static const char AttrDoc_NSReturnsNotRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
5109(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
5110convention (e.g. functions starting with "get" are assumed to return at
5111`+0`).
5112
5113It can be overridden using a family of the following attributes. In
5114Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
5115a function communicates that the object is returned at `+1`, and the caller
5116is responsible for freeing it.
5117Similarly, the annotation `__attribute__((ns_returns_not_retained))`
5118specifies that the object is returned at `+0` and the ownership remains with
5119the callee.
5120The annotation `__attribute__((ns_consumes_self))` specifies that
5121the Objective-C method call consumes the reference to `self`, e.g. by
5122attaching it to a supplied parameter.
5123Additionally, parameters can have an annotation
5124`__attribute__((ns_consumed))`, which specifies that passing an owned object
5125as that parameter effectively transfers the ownership, and the caller is no
5126longer responsible for it.
5127These attributes affect code generation when interacting with ARC code, and
5128they are used by the Clang Static Analyzer.
5129
5130In C programs using CoreFoundation, a similar set of attributes:
5131`__attribute__((cf_returns_not_retained))`,
5132`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
5133have the same respective semantics when applied to CoreFoundation objects.
5134These attributes affect code generation when interacting with ARC code, and
5135they are used by the Clang Static Analyzer.
5136
5137Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
5138the same attribute family is present:
5139`__attribute__((os_returns_not_retained))`,
5140`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
5141with the same respective semantics.
5142Similar to `__attribute__((ns_consumes_self))`,
5143`__attribute__((os_consumes_this))` specifies that the method call consumes
5144the reference to "this" (e.g., when attaching it to a different object supplied
5145as a parameter).
5146Out parameters (parameters the function is meant to write into,
5147either via pointers-to-pointers or references-to-pointers)
5148may be annotated with `__attribute__((os_returns_retained))`
5149or `__attribute__((os_returns_not_retained))` which specifies that the object
5150written into the out parameter should (or respectively should not) be released
5151after use.
5152Since often out parameters may or may not be written depending on the exit
5153code of the function,
5154annotations `__attribute__((os_returns_retained_on_zero))`
5155and `__attribute__((os_returns_retained_on_non_zero))` specify that
5156an out parameter at `+1` is written if and only if the function returns a zero
5157(respectively non-zero) error code.
5158Observe that return-code-dependent out parameter annotations are only
5159available for retained out parameters, as non-retained object do not have to be
5160released by the callee.
5161These attributes are only used by the Clang Static Analyzer.
5162
5163The family of attributes `X_returns_X_retained` can be added to functions,
5164C++ methods, and Objective-C methods and properties.
5165Attributes `X_consumed` can be added to parameters of methods, functions,
5166and Objective-C methods.)reST";
5167
5168static const char AttrDoc_NSReturnsRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
5169(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
5170convention (e.g. functions starting with "get" are assumed to return at
5171`+0`).
5172
5173It can be overridden using a family of the following attributes. In
5174Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
5175a function communicates that the object is returned at `+1`, and the caller
5176is responsible for freeing it.
5177Similarly, the annotation `__attribute__((ns_returns_not_retained))`
5178specifies that the object is returned at `+0` and the ownership remains with
5179the callee.
5180The annotation `__attribute__((ns_consumes_self))` specifies that
5181the Objective-C method call consumes the reference to `self`, e.g. by
5182attaching it to a supplied parameter.
5183Additionally, parameters can have an annotation
5184`__attribute__((ns_consumed))`, which specifies that passing an owned object
5185as that parameter effectively transfers the ownership, and the caller is no
5186longer responsible for it.
5187These attributes affect code generation when interacting with ARC code, and
5188they are used by the Clang Static Analyzer.
5189
5190In C programs using CoreFoundation, a similar set of attributes:
5191`__attribute__((cf_returns_not_retained))`,
5192`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
5193have the same respective semantics when applied to CoreFoundation objects.
5194These attributes affect code generation when interacting with ARC code, and
5195they are used by the Clang Static Analyzer.
5196
5197Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
5198the same attribute family is present:
5199`__attribute__((os_returns_not_retained))`,
5200`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
5201with the same respective semantics.
5202Similar to `__attribute__((ns_consumes_self))`,
5203`__attribute__((os_consumes_this))` specifies that the method call consumes
5204the reference to "this" (e.g., when attaching it to a different object supplied
5205as a parameter).
5206Out parameters (parameters the function is meant to write into,
5207either via pointers-to-pointers or references-to-pointers)
5208may be annotated with `__attribute__((os_returns_retained))`
5209or `__attribute__((os_returns_not_retained))` which specifies that the object
5210written into the out parameter should (or respectively should not) be released
5211after use.
5212Since often out parameters may or may not be written depending on the exit
5213code of the function,
5214annotations `__attribute__((os_returns_retained_on_zero))`
5215and `__attribute__((os_returns_retained_on_non_zero))` specify that
5216an out parameter at `+1` is written if and only if the function returns a zero
5217(respectively non-zero) error code.
5218Observe that return-code-dependent out parameter annotations are only
5219available for retained out parameters, as non-retained object do not have to be
5220released by the callee.
5221These attributes are only used by the Clang Static Analyzer.
5222
5223The family of attributes `X_returns_X_retained` can be added to functions,
5224C++ methods, and Objective-C methods and properties.
5225Attributes `X_consumed` can be added to parameters of methods, functions,
5226and Objective-C methods.)reST";
5227
5228static const char AttrDoc_Naked[] = R"reST(No documentation.)reST";
5229
5230static const char AttrDoc_NoAlias[] = R"reST(The `noalias` attribute indicates that the only memory accesses inside
5231function are loads and stores from objects pointed to by its pointer-typed
5232arguments, with arbitrary offsets.)reST";
5233
5234static const char AttrDoc_NoBuiltin[] = R"reST(The `__attribute__((no_builtin))` is similar to the `-fno-builtin` flag
5235except it is specific to the body of a function. The attribute may also be
5236applied to a virtual function but has no effect on the behavior of overriding
5237functions in a derived class.
5238
5239It accepts one or more strings corresponding to the specific names of the
5240builtins to disable (e.g. "memcpy", "memset").
5241If the attribute is used without parameters it will disable all buitins at
5242once.
5243
5244```c++
5245// The compiler is not allowed to add any builtin to foo's body.
5246void foo(char* data, size_t count) __attribute__((no_builtin)) {
5247 // The compiler is not allowed to convert the loop into
5248 // `__builtin_memset(data, 0xFE, count);`.
5249 for (size_t i = 0; i < count; ++i)
5250 data[i] = 0xFE;
5251}
5252
5253// The compiler is not allowed to add the `memcpy` builtin to bar's body.
5254void bar(char* data, size_t count) __attribute__((no_builtin("memcpy"))) {
5255 // The compiler is allowed to convert the loop into
5256 // `__builtin_memset(data, 0xFE, count);` but cannot generate any
5257 // `__builtin_memcpy`
5258 for (size_t i = 0; i < count; ++i)
5259 data[i] = 0xFE;
5260}
5261```)reST";
5262
5263static const char AttrDoc_NoCommon[] = R"reST(No documentation.)reST";
5264
5265static const char AttrDoc_NoConvergent[] = R"reST(This attribute prevents a function from being treated as convergent; when a
5266function is marked `noconvergent`, calls to that function are not
5267automatically assumed to be convergent, unless such calls are explicitly marked
5268as `convergent`. If a statement is marked as `noconvergent`, any calls to
5269inline `asm` in that statement are no longer treated as convergent.
5270
5271In languages following SPMD/SIMT programming model, e.g., CUDA/HIP, function
5272declarations and inline asm calls are treated as convergent by default for
5273correctness. This `noconvergent` attribute is helpful for developers to
5274prevent them from being treated as convergent when it's safe.
5275
5276```c
5277__device__ float bar(float);
5278__device__ float foo(float) __attribute__((noconvergent)) {}
5279
5280__device__ int example(void) {
5281 float x;
5282 [[clang::noconvergent]] x = bar(x); // no effect on convergence
5283 [[clang::noconvergent]] { asm volatile ("nop"); } // the asm call is non-convergent
5284}
5285```)reST";
5286
5287static const char AttrDoc_NoDebug[] = R"reST(The `nodebug` attribute allows you to suppress debugging information for a
5288function or method, for a variable that is not a parameter or a non-static
5289data member, or for a typedef or using declaration.)reST";
5290
5291static const char AttrDoc_NoDeref[] = R"reST(The `noderef` attribute causes clang to diagnose dereferences of annotated pointer types.
5292This is ideally used with pointers that point to special memory which cannot be read
5293from or written to, but allowing for the pointer to be used in pointer arithmetic.
5294The following are examples of valid expressions where dereferences are diagnosed:
5295
5296```c
5297int __attribute__((noderef)) *p;
5298int x = *p; // warning
5299
5300int __attribute__((noderef)) **p2;
5301x = **p2; // warning
5302
5303int * __attribute__((noderef)) *p3;
5304p = *p3; // warning
5305
5306struct S {
5307 int a;
5308};
5309struct S __attribute__((noderef)) *s;
5310x = s->a; // warning
5311x = (*s).a; // warning
5312```
5313
5314Not all dereferences may diagnose a warning if the value directed by the pointer may not be
5315accessed. The following are examples of valid expressions where may not be diagnosed:
5316
5317```c
5318int *q;
5319int __attribute__((noderef)) *p;
5320q = &*p;
5321q = *&p;
5322
5323struct S {
5324 int a;
5325};
5326struct S __attribute__((noderef)) *s;
5327p = &s->a;
5328p = &(*s).a;
5329```
5330
5331`noderef` is currently only supported for pointers and arrays and not usable
5332for references or Objective-C object pointers.
5333
5334```c++
5335int x = 2;
5336int __attribute__((noderef)) &y = x; // warning: 'noderef' can only be used on an array or pointer type
5337```
5338
5339```objc
5340id __attribute__((noderef)) obj = [NSObject new]; // warning: 'noderef' can only be used on an array or pointer type
5341```)reST";
5342
5343static const char AttrDoc_NoDestroy[] = R"reST(The `no_destroy` attribute specifies that a variable with static or thread
5344storage duration shouldn't have its exit-time destructor run. Annotating every
5345static and thread duration variable with this attribute is equivalent to
5346invoking clang with -fno-c++-static-destructors.
5347
5348If a variable is declared with this attribute, clang doesn't access check or
5349generate the type's destructor. If you have a type that you only want to be
5350annotated with `no_destroy`, you can therefore declare the destructor private:
5351
5352```c++
5353struct only_no_destroy {
5354 only_no_destroy();
5355private:
5356 ~only_no_destroy();
5357};
5358
5359[[clang::no_destroy]] only_no_destroy global; // fine!
5360```
5361
5362Note that destructors are still required for subobjects of aggregates annotated
5363with this attribute. This is because previously constructed subobjects need to
5364be destroyed if an exception gets thrown before the initialization of the
5365complete object is complete. For instance:
5366
5367```c++
5368void f() {
5369 try {
5370 [[clang::no_destroy]]
5371 static only_no_destroy array[10]; // error, only_no_destroy has a private destructor.
5372 } catch (...) {
5373 // Handle the error
5374 }
5375}
5376```
5377
5378Here, if the construction of `array[9]` fails with an exception, `array[0..8]`
5379will be destroyed, so the element's destructor needs to be accessible.)reST";
5380
5381static const char AttrDoc_NoDuplicate[] = R"reST(The `noduplicate` attribute can be placed on function declarations to control
5382whether function calls to this function can be duplicated or not as a result of
5383optimizations. This is required for the implementation of functions with
5384certain special requirements, like the OpenCL "barrier" function, that might
5385need to be run concurrently by all the threads that are executing in lockstep
5386on the hardware. For example this attribute applied on the function
5387"nodupfunc" in the code below avoids that:
5388
5389```c
5390void nodupfunc() __attribute__((noduplicate));
5391// Setting it as a C++11 attribute is also valid
5392// void nodupfunc() [[clang::noduplicate]];
5393void foo();
5394void bar();
5395
5396nodupfunc();
5397if (a > n) {
5398 foo();
5399} else {
5400 bar();
5401}
5402```
5403
5404gets possibly modified by some optimizations into code similar to this:
5405
5406```c
5407if (a > n) {
5408 nodupfunc();
5409 foo();
5410} else {
5411 nodupfunc();
5412 bar();
5413}
5414```
5415
5416where the call to "nodupfunc" is duplicated and sunk into the two branches
5417of the condition.)reST";
5418
5419static const char AttrDoc_NoEscape[] = R"reST(`noescape` placed on a function parameter of a pointer type is used to inform
5420the compiler that the pointer cannot escape: that is, no reference to the object
5421the pointer points to that is derived from the parameter value will survive
5422after the function returns. Users are responsible for making sure parameters
5423annotated with `noescape` do not actually escape. The optimizer may make
5424assumptions based on the fact that it knows that a call to the function does
5425not escape a certain parameter, so incorrectly annotating a parameter with
5426`noescape` leads to undefined behavior. The callee is also not allowed to
5427deallocate memory through a `noescape` parameter: the optimizer does not make
5428assumptions based on this information at the moment, but may do so in the
5429future. Some cases of invalid uses of `noescape` can be found with
5430{ref}`-Wlifetime-safety-noescape <Wlifetime-safety-noescape>`.
5431
5432For example:
5433
5434```c
5435int *gp;
5436
5437void nonescapingFunc(__attribute__((noescape)) int *p) {
5438 *p += 100; // OK.
5439}
5440
5441void escapingFunc(__attribute__((noescape)) int *p) {
5442 gp = p; // Not OK.
5443}
5444
5445void freeingFunc(__attribute__((noescape)) int *p) {
5446 free(p); // Not OK.
5447}
5448```
5449
5450Since `noescape` is a parameter attribute and not a type attribute, it only
5451applies to the outermost pointer level, regardless of where in the parameter
5452declaration you place it:
5453
5454```c
5455int **gp;
5456
5457void nestingEscapes(__attribute__((noescape)) int **p) {
5458 gp = p; // Not OK.
5459 *gp = *p; // OK, p does not escape.
5460}
5461```
5462
5463Additionally, when the parameter is a
5464{doc}`block pointer <BlockLanguageSpec>`, the same restriction applies to
5465copies of the block. For example:
5466
5467```c
5468typedef void (^BlockTy)();
5469BlockTy g0, g1;
5470
5471void nonescapingFunc(__attribute__((noescape)) BlockTy block) {
5472 block(); // OK.
5473}
5474
5475void escapingFunc(__attribute__((noescape)) BlockTy block) {
5476 g0 = block; // Not OK.
5477 g1 = Block_copy(block); // Not OK either.
5478}
5479```
5480
5481The function *is* allowed to leak information about the memory address of the
5482pointer, but not any provenance of the allocation:
5483
5484```c
5485bool isNull(__attribute__((noescape)) void *p) {
5486 return !p; // OK.
5487}
5488
5489uintptr_t gi;
5490
5491void escapingAddress(__attribute__((noescape)) int *p) {
5492 // OK *if and only if* gi is never casted back to a pointer.
5493 gi = (uintptr_t)p;
5494}
5495
5496bool usingEscapedAddress(int *p) {
5497 return (uintptr_t)p > gi; // OK.
5498}
5499
5500bool usingEscapedPointer(int *p) {
5501 return p > (int*)gi; // Not OK.
5502}
5503
5504int *gp;
5505
5506void escapingEndFunc(__attribute__((noescape)) int *p, size_t len) {
5507 gp = p + len; // Not OK.
5508}
5509```)reST";
5510
5511static const char AttrDoc_NoFieldProtection[] = R"reST(No documentation.)reST";
5512
5513static const char AttrDoc_NoInline[] = R"reST(This function attribute suppresses the inlining of a function at the call sites
5514of the function.
5515
5516`[[clang::noinline]]` spelling can be used as a statement attribute; other
5517spellings of the attribute are not supported on statements. If a statement is
5518marked `[[clang::noinline]]` and contains calls, those calls inside the
5519statement will not be inlined by the compiler.
5520
5521`__noinline__` can be used as a keyword in CUDA/HIP languages. This is to
5522avoid diagnostics due to usage of `__attribute__((__noinline__))`
5523with `__noinline__` defined as a macro as `__attribute__((noinline))`.
5524
5525```c
5526int example(void) {
5527 int r;
5528 [[clang::noinline]] foo();
5529 [[clang::noinline]] r = bar();
5530 return r;
5531}
5532```)reST";
5533
5534static const char AttrDoc_NoInstrumentFunction[] = R"reST(No documentation.)reST";
5535
5536static const char AttrDoc_NoMerge[] = R"reST(If a statement is marked `nomerge` and contains call expressions, those call
5537expressions inside the statement will not be merged during optimization. This
5538attribute can be used to prevent the optimizer from obscuring the source
5539location of certain calls. For example, it will prevent tail merging otherwise
5540identical code sequences that raise an exception or terminate the program. Tail
5541merging normally reduces the precision of source location information, making
5542stack traces less useful for debugging. This attribute gives the user control
5543over the tradeoff between code size and debug information precision.
5544
5545`nomerge` attribute can also be used as function attribute to prevent all
5546calls to the specified function from merging. It has no effect on indirect
5547calls to such functions. For example:
5548
5549```c++
5550[[clang::nomerge]] void foo(int) {}
5551
5552void bar(int x) {
5553 auto *ptr = foo;
5554 if (x) foo(1); else foo(2); // will not be merged
5555 if (x) ptr(1); else ptr(2); // indirect call, can be merged
5556}
5557```
5558
5559`nomerge` attribute can also be used for pointers to functions to
5560prevent calls through such pointer from merging. In such case the
5561effect applies only to a specific function pointer. For example:
5562
5563```c++
5564[[clang::nomerge]] void (*foo)(int);
5565
5566void bar(int x) {
5567 auto *ptr = foo;
5568 if (x) foo(1); else foo(2); // will not be merged
5569 if (x) ptr(1); else ptr(2); // 'ptr' has no 'nomerge' attribute, can be merged
5570}
5571```)reST";
5572
5573static const char AttrDoc_NoMicroMips[] = R"reST(Clang supports the GNU style `__attribute__((micromips))` and
5574`__attribute__((nomicromips))` attributes on MIPS targets. These attributes
5575may be attached to a function definition and instructs the backend to generate
5576or not to generate microMIPS code for that function.
5577
5578These attributes override the `-mmicromips` and `-mno-micromips` options
5579on the command line.)reST";
5580
5581static const char AttrDoc_NoMips16[] = R"reST(No documentation.)reST";
5582
5583static const char AttrDoc_NoOutline[] = R"reST(This function attribute suppresses outlining from the annotated function.
5584
5585Outlining is the process where common parts of separate functions are extracted
5586into a separate function (or assembly snippet), and calls to that function or
5587snippet are inserted in the original functions. In this way, it can be seen as
5588the opposite of inlining. It can help to reduce code size.)reST";
5589
5590static const char AttrDoc_NoProfileFunction[] = R"reST(Use the `no_profile_instrument_function` attribute on a function declaration
5591to denote that the compiler should not instrument the function with
5592profile-related instrumentation, such as via the
5593`-fprofile-generate` / `-fprofile-instr-generate` /
5594`-fcs-profile-generate` / `-fprofile-arcs` flags.)reST";
5595
5596static const char AttrDoc_NoRandomizeLayout[] = R"reST(The attribute `randomize_layout`, when attached to a C structure, selects it
5597for structure layout field randomization; a compile-time hardening technique. A
5598"seed" value, is specified via the `-frandomize-layout-seed=` command line flag.
5599For example:
5600
5601```bash
5602SEED=`od -A n -t x8 -N 32 /dev/urandom | tr -d ' \n'`
5603make ... CFLAGS="-frandomize-layout-seed=$SEED" ...
5604```
5605
5606You can also supply the seed in a file with `-frandomize-layout-seed-file=`.
5607For example:
5608
5609```bash
5610od -A n -t x8 -N 32 /dev/urandom | tr -d ' \n' > /tmp/seed_file.txt
5611make ... CFLAGS="-frandomize-layout-seed-file=/tmp/seed_file.txt" ...
5612```
5613
5614The randomization is deterministic based for a given seed, so the entire
5615program should be compiled with the same seed, but keep the seed safe
5616otherwise.
5617
5618The attribute `no_randomize_layout`, when attached to a C structure,
5619instructs the compiler that this structure should not have its field layout
5620randomized.)reST";
5621
5622static const char AttrDoc_NoReturn[] = R"reST(No documentation.)reST";
5623
5624static const char AttrDoc_NoSanitize[] = R"reST(Use the `no_sanitize` attribute on a function or a global variable
5625declaration to specify that a particular instrumentation or set of
5626instrumentations should not be applied.
5627
5628The attribute takes a list of string literals with the following accepted
5629values:
5630
5631- all values accepted by `-fno-sanitize=`;
5632- `coverage`, to disable SanitizerCoverage instrumentation.
5633
5634For example, `__attribute__((no_sanitize("address", "thread")))` specifies
5635that AddressSanitizer and ThreadSanitizer should not be applied to the function
5636or variable. Using `__attribute__((no_sanitize("coverage")))` specifies that
5637SanitizerCoverage should not be applied to the function.
5638
5639See {ref}`Controlling Code Generation <controlling-code-generation>` for a
5640full list of supported sanitizer flags.)reST";
5641
5642static const char AttrDoc_NoSpecializations[] = R"reST(``[[clang::no_specializations]]`` can be applied to function, class, or variable
5643templates for which neither an explicit specialization nor a partial specialization should be declared by users. This is primarily
5644used to diagnose user specializations of standard library type traits.)reST";
5645
5646static const char AttrDoc_NoSpeculativeLoadHardening[] = R"reST(This attribute can be applied to a function declaration in order to indicate
5647that [Speculative Load Hardening][slh] is *not* needed for the function body.
5648This can also be applied to a method in Objective C. This attribute will take
5649precedence over the command line flag in the case where
5650{option}`-mspeculative-load-hardening` is specified.
5651
5652Warning: This attribute may not prevent Speculative Load Hardening from being
5653enabled for a function which inlines a function that has the
5654'speculative_load_hardening' attribute. This is intended to provide a
5655maximally conservative model where the code that is marked with the
5656'speculative_load_hardening' attribute will always (even when inlined)
5657be hardened. A user of this attribute may want to mark functions called by
5658a function they do not want to be hardened with the 'noinline' attribute.
5659
5660For example:
5661
5662```c
5663__attribute__((speculative_load_hardening))
5664int foo(int i) {
5665 return i;
5666}
5667
5668// Note: bar() may still have speculative load hardening enabled if
5669// foo() is inlined into bar(). Mark foo() with __attribute__((noinline))
5670// to avoid this situation.
5671__attribute__((no_speculative_load_hardening))
5672int bar(int i) {
5673 return foo(i);
5674}
5675```)reST";
5676
5677static const char AttrDoc_NoSplitStack[] = R"reST(The `no_split_stack` attribute disables the emission of the split stack
5678preamble for a particular function. It has no effect if `-fsplit-stack`
5679is not specified.)reST";
5680
5681static const char AttrDoc_NoStackProtector[] = R"reST(Clang supports the GNU style `__attribute__((no_stack_protector))` and Microsoft
5682style `__declspec(safebuffers)` attribute which disables
5683the stack protector on the specified function. This attribute is useful for
5684selectively disabling the stack protector on some functions when building with
5685`-fstack-protector` compiler option.
5686
5687For example, it disables the stack protector for the function `foo` but function
5688`bar` will still be built with the stack protector with the `-fstack-protector`
5689option.
5690
5691```c
5692int __attribute__((no_stack_protector))
5693foo (int x); // stack protection will be disabled for foo.
5694
5695int bar(int y); // bar can be built with the stack protector.
5696```)reST";
5697
5698static const char AttrDoc_NoThreadSafetyAnalysis[] = R"reST(No documentation.)reST";
5699
5700static const char AttrDoc_NoThrow[] = R"reST(Clang supports the GNU style `__attribute__((nothrow))` and Microsoft style
5701`__declspec(nothrow)` attribute as an equivalent of `noexcept` on function
5702declarations. This attribute informs the compiler that the annotated function
5703does not throw an exception. This prevents exception-unwinding. This attribute
5704is particularly useful on functions in the C Standard Library that are
5705guaranteed to not throw an exception.)reST";
5706
5707static const char AttrDoc_NoTrivialAutoVarInit[] = R"reST(The `__declspec(no_init_all)` attribute disables the automatic initialization
5708that the {option}`-ftrivial-auto-var-init` flag would have applied to locals in
5709a marked function, or instances of a marked type. Note that this attribute has
5710no effect for locals that are automatically initialized without the
5711{option}`-ftrivial-auto-var-init` flag.)reST";
5712
5713static const char AttrDoc_NoUniqueAddress[] = R"reST(The `no_unique_address` attribute allows tail padding in a non-static data
5714member to overlap other members of the enclosing class (and in the special
5715case when the type is empty, permits it to fully overlap other members).
5716The field is laid out as if a base class were encountered at the corresponding
5717point within the class (except that it does not share a vptr with the enclosing
5718object).
5719
5720Example usage:
5721
5722```c++
5723template<typename T, typename Alloc> struct my_vector {
5724 T *p;
5725 [[no_unique_address]] Alloc alloc;
5726 // ...
5727};
5728static_assert(sizeof(my_vector<int, std::allocator<int>>) == sizeof(int*));
5729```
5730
5731`[[no_unique_address]]` is a standard C++20 attribute. Clang supports its use
5732in C++11 onwards.
5733
5734On MSVC targets, `[[no_unique_address]]` is ignored; use
5735`[[msvc::no_unique_address]]` instead. Currently there is no guarantee of ABI
5736compatibility or stability with MSVC.)reST";
5737
5738static const char AttrDoc_NoUwtable[] = R"reST(Clang supports the `nouwtable` attribute which skips emitting
5739the unwind table entry for the specified function. This attribute is useful for
5740selectively emitting the unwind table entry on some functions when building with
5741`-funwind-tables` compiler option.)reST";
5742
5743static const char AttrDoc_NonAllocating[] = R"reST(Declares that a function or function type either does or does not allocate heap memory, according
5744to the optional, compile-time constant boolean argument, which defaults to true. When the argument
5745is false, the attribute is equivalent to `allocating`.)reST";
5746
5747static const char AttrDoc_NonBlocking[] = R"reST(Declares that a function or function type either does or does not block in any way, according
5748to the optional, compile-time constant boolean argument, which defaults to true. When the argument
5749is false, the attribute is equivalent to `blocking`.
5750
5751For the purposes of diagnostics, `nonblocking` is considered to include the
5752`nonallocating` guarantee and is therefore a "stronger" constraint or attribute.)reST";
5753
5754static const char AttrDoc_NonNull[] = R"reST(The `nonnull` attribute indicates that some function parameters must not be
5755null, and can be used in several different ways. It's original usage
5756([from GCC](https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes))
5757is as a function (or Objective-C method) attribute that specifies which
5758parameters of the function are nonnull in a comma-separated list. For example:
5759
5760```c
5761extern void * my_memcpy (void *dest, const void *src, size_t len)
5762 __attribute__((nonnull (1, 2)));
5763```
5764
5765Here, the `nonnull` attribute indicates that parameters 1 and 2
5766cannot have a null value. Omitting the parenthesized list of parameter indices
5767means that all parameters of pointer type cannot be null:
5768
5769```c
5770extern void * my_memcpy (void *dest, const void *src, size_t len)
5771 __attribute__((nonnull));
5772```
5773
5774Clang also allows the `nonnull` attribute to be placed directly on a function
5775(or Objective-C method) parameter, eliminating the need to specify the
5776parameter index ahead of type. For example:
5777
5778```c
5779extern void * my_memcpy (void *dest __attribute__((nonnull)),
5780 const void *src __attribute__((nonnull)), size_t len);
5781```
5782
5783Note that the `nonnull` attribute indicates that passing null to a non-null
5784parameter is undefined behavior, which the optimizer may take advantage of to,
5785e.g., remove null checks. The `_Nonnull` type qualifier indicates that a
5786pointer cannot be null in a more general manner (because it is part of the type
5787system) and does not imply undefined behavior, making it more widely applicable.)reST";
5788
5789static const char AttrDoc_NonString[] = R"reST(The `nonstring` attribute can be applied to the declaration of a variable or
5790a field whose type is a character pointer or character array to specify that
5791the buffer is not intended to behave like a null-terminated string. This will
5792silence diagnostics with code like:
5793
5794```c
5795char BadStr[3] = "foo"; // No space for the null terminator, diagnosed
5796__attribute__((nonstring)) char NotAStr[3] = "foo"; // Not diagnosed
5797```)reST";
5798
5799static const char AttrDoc_NotTailCalled[] = R"reST(The `not_tail_called` attribute prevents tail-call optimization on statically
5800bound calls. Objective-c methods, and functions marked as `always_inline`
5801cannot be marked as `not_tail_called`.
5802
5803For example, it prevents tail-call optimization in the following case:
5804
5805```c
5806int __attribute__((not_tail_called)) foo1(int);
5807
5808int foo2(int a) {
5809 return foo1(a); // No tail-call optimization on direct calls.
5810}
5811```
5812
5813However, it doesn't prevent tail-call optimization in this case:
5814
5815```c
5816int __attribute__((not_tail_called)) foo1(int);
5817
5818int foo2(int a) {
5819 int (*fn)(int) = &foo1;
5820
5821 // not_tail_called has no effect on an indirect call even if the call can
5822 // be resolved at compile time.
5823 return (*fn)(a);
5824}
5825```
5826
5827Generally, marking an overriding virtual function as `not_tail_called` is
5828not useful, because this attribute is a property of the static type. Calls
5829made through a pointer or reference to the base class type will respect
5830the `not_tail_called` attribute of the base class's member function,
5831regardless of the runtime destination of the call:
5832
5833```c++
5834struct Foo { virtual void f(); };
5835struct Bar : Foo {
5836 [[clang::not_tail_called]] void f() override;
5837};
5838void callera(Bar& bar) {
5839 Foo& foo = bar;
5840 // not_tail_called has no effect on here, even though the
5841 // underlying method is f from Bar.
5842 foo.f();
5843 bar.f(); // No tail-call optimization on here.
5844}
5845```)reST";
5846
5847static const char AttrDoc_OMPAllocateDecl[] = R"reST()reST";
5848
5849static const char AttrDoc_OMPAssume[] = R"reST(Clang supports the `[[omp::assume("assumption")]]` attribute to
5850provide additional information to the optimizer. The string-literal, here
5851"assumption", will be attached to the function declaration such that later
5852analysis and optimization passes can assume the "assumption" to hold.
5853This is similar to {ref}`__builtin_assume <langext-__builtin_assume>` but
5854instead of an expression that can be assumed to be non-zero, the assumption is
5855expressed as a string and it holds for the entire function.
5856
5857A function can have multiple assume attributes and they propagate from prior
5858declarations to later definitions. Multiple assumptions are aggregated into a
5859single comma separated string. Thus, one can provide multiple assumptions via
5860a comma separated string, i.a.,
5861`[[omp::assume("assumption1,assumption2")]]`.
5862
5863While LLVM plugins might provide more assumption strings, the default LLVM
5864optimization passes are aware of the following assumptions:
5865
5866```none
5867"omp_no_openmp"
5868"omp_no_openmp_routines"
5869"omp_no_parallelism"
5870"omp_no_openmp_constructs"
5871```
5872
5873The OpenMP standard defines the meaning of OpenMP assumptions ("omp_XYZ" is
5874spelled "XYZ" in the [OpenMP 5.1 Standard][openmp 5.1 standard]).
5875
5876[openmp 5.1 standard]: https://www.openmp.org/spec-html/5.1/openmpsu37.html#x56-560002.5.2)reST";
5877
5878static const char AttrDoc_OMPCaptureKind[] = R"reST()reST";
5879
5880static const char AttrDoc_OMPCaptureNoInit[] = R"reST()reST";
5881
5882static const char AttrDoc_OMPDeclareSimdDecl[] = R"reST(The `declare simd` construct can be applied to a function to enable the creation
5883of one or more versions that can process multiple arguments using SIMD
5884instructions from a single invocation in a SIMD loop. The `declare simd`
5885directive is a declarative directive. There may be multiple `declare simd`
5886directives for a function. The use of a `declare simd` construct on a function
5887enables the creation of SIMD versions of the associated function that can be
5888used to process multiple arguments from a single invocation from a SIMD loop
5889concurrently.
5890The syntax of the `declare simd` construct is as follows:
5891
5892```none
5893#pragma omp declare simd [clause[[,] clause] ...] new-line
5894[#pragma omp declare simd [clause[[,] clause] ...] new-line]
5895[...]
5896function definition or declaration
5897```
5898
5899where clause is one of the following:
5900
5901```none
5902simdlen(length)
5903linear(argument-list[:constant-linear-step])
5904aligned(argument-list[:alignment])
5905uniform(argument-list)
5906inbranch
5907notinbranch
5908```)reST";
5909
5910static const char AttrDoc_OMPDeclareTargetDecl[] = R"reST(The `declare target` directive specifies that variables and functions are mapped
5911to a device for OpenMP offload mechanism.
5912
5913The syntax of the declare target directive is as follows:
5914
5915```c
5916#pragma omp declare target new-line
5917declarations-definition-seq
5918#pragma omp end declare target new-line
5919```
5920
5921or
5922
5923```c
5924#pragma omp declare target (extended-list) new-line
5925```
5926
5927or
5928
5929```c
5930#pragma omp declare target clause[ [,] clause ... ] new-line
5931```
5932
5933where clause is one of the following:
5934
5935```c
5936to(extended-list)
5937link(list)
5938device_type(host | nohost | any)
5939```)reST";
5940
5941static const char AttrDoc_OMPDeclareVariant[] = R"reST(The `declare variant` directive declares a specialized variant of a base
5942function and specifies the context in which that specialized variant is used.
5943The declare variant directive is a declarative directive.
5944The syntax of the `declare variant` construct is as follows:
5945
5946```none
5947#pragma omp declare variant(variant-func-id) clause new-line
5948[#pragma omp declare variant(variant-func-id) clause new-line]
5949[...]
5950function definition or declaration
5951```
5952
5953where clause is one of the following:
5954
5955```none
5956match(context-selector-specification)
5957```
5958
5959and where `variant-func-id` is the name of a function variant that is either a
5960base language identifier or, for C++, a template-id.
5961
5962Clang provides the following context selector extensions, used via
5963`implementation={extension(EXTENSION)}`:
5964
5965```none
5966match_all
5967match_any
5968match_none
5969disable_implicit_base
5970allow_templates
5971bind_to_declaration
5972```
5973
5974The match extensions change when the *entire* context selector is considered a
5975match for an OpenMP context. The default is `all`, with `none` no trait in the
5976selector is allowed to be in the OpenMP context, with `any` a single trait in
5977both the selector and OpenMP context is sufficient. Only a single match
5978extension trait is allowed per context selector.
5979The disable extensions remove default effects of the `begin declare variant`
5980applied to a definition. If `disable_implicit_base` is given, we will not
5981introduce an implicit base function for a variant if no base function was
5982found. The variant is still generated but will never be called, due to the
5983absence of a base function and consequently calls to a base function.
5984The allow extensions change when the `begin declare variant` effect is
5985applied to a definition. If `allow_templates` is given, template function
5986definitions are considered as specializations of existing or assumed template
5987declarations with the same name. The template parameters for the base functions
5988are used to instantiate the specialization. If `bind_to_declaration` is given,
5989apply the same variant rules to function declarations. This allows the user to
5990override declarations with only a function declaration.)reST";
5991
5992static const char AttrDoc_OMPGroupPrivateDecl[] = R"reST()reST";
5993
5994static const char AttrDoc_OMPInvariantPredicateBound[] = R"reST()reST";
5995
5996static const char AttrDoc_OMPReferencedVar[] = R"reST()reST";
5997
5998static const char AttrDoc_OMPTargetIndirectCall[] = R"reST()reST";
5999
6000static const char AttrDoc_OMPThreadPrivateDecl[] = R"reST()reST";
6001
6002static const char AttrDoc_OSConsumed[] = R"reST(The behavior of a function with respect to reference counting for Foundation
6003(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
6004convention (e.g. functions starting with "get" are assumed to return at
6005`+0`).
6006
6007It can be overridden using a family of the following attributes. In
6008Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
6009a function communicates that the object is returned at `+1`, and the caller
6010is responsible for freeing it.
6011Similarly, the annotation `__attribute__((ns_returns_not_retained))`
6012specifies that the object is returned at `+0` and the ownership remains with
6013the callee.
6014The annotation `__attribute__((ns_consumes_self))` specifies that
6015the Objective-C method call consumes the reference to `self`, e.g. by
6016attaching it to a supplied parameter.
6017Additionally, parameters can have an annotation
6018`__attribute__((ns_consumed))`, which specifies that passing an owned object
6019as that parameter effectively transfers the ownership, and the caller is no
6020longer responsible for it.
6021These attributes affect code generation when interacting with ARC code, and
6022they are used by the Clang Static Analyzer.
6023
6024In C programs using CoreFoundation, a similar set of attributes:
6025`__attribute__((cf_returns_not_retained))`,
6026`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
6027have the same respective semantics when applied to CoreFoundation objects.
6028These attributes affect code generation when interacting with ARC code, and
6029they are used by the Clang Static Analyzer.
6030
6031Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
6032the same attribute family is present:
6033`__attribute__((os_returns_not_retained))`,
6034`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
6035with the same respective semantics.
6036Similar to `__attribute__((ns_consumes_self))`,
6037`__attribute__((os_consumes_this))` specifies that the method call consumes
6038the reference to "this" (e.g., when attaching it to a different object supplied
6039as a parameter).
6040Out parameters (parameters the function is meant to write into,
6041either via pointers-to-pointers or references-to-pointers)
6042may be annotated with `__attribute__((os_returns_retained))`
6043or `__attribute__((os_returns_not_retained))` which specifies that the object
6044written into the out parameter should (or respectively should not) be released
6045after use.
6046Since often out parameters may or may not be written depending on the exit
6047code of the function,
6048annotations `__attribute__((os_returns_retained_on_zero))`
6049and `__attribute__((os_returns_retained_on_non_zero))` specify that
6050an out parameter at `+1` is written if and only if the function returns a zero
6051(respectively non-zero) error code.
6052Observe that return-code-dependent out parameter annotations are only
6053available for retained out parameters, as non-retained object do not have to be
6054released by the callee.
6055These attributes are only used by the Clang Static Analyzer.
6056
6057The family of attributes `X_returns_X_retained` can be added to functions,
6058C++ methods, and Objective-C methods and properties.
6059Attributes `X_consumed` can be added to parameters of methods, functions,
6060and Objective-C methods.)reST";
6061
6062static const char AttrDoc_OSConsumesThis[] = R"reST(The behavior of a function with respect to reference counting for Foundation
6063(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
6064convention (e.g. functions starting with "get" are assumed to return at
6065`+0`).
6066
6067It can be overridden using a family of the following attributes. In
6068Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
6069a function communicates that the object is returned at `+1`, and the caller
6070is responsible for freeing it.
6071Similarly, the annotation `__attribute__((ns_returns_not_retained))`
6072specifies that the object is returned at `+0` and the ownership remains with
6073the callee.
6074The annotation `__attribute__((ns_consumes_self))` specifies that
6075the Objective-C method call consumes the reference to `self`, e.g. by
6076attaching it to a supplied parameter.
6077Additionally, parameters can have an annotation
6078`__attribute__((ns_consumed))`, which specifies that passing an owned object
6079as that parameter effectively transfers the ownership, and the caller is no
6080longer responsible for it.
6081These attributes affect code generation when interacting with ARC code, and
6082they are used by the Clang Static Analyzer.
6083
6084In C programs using CoreFoundation, a similar set of attributes:
6085`__attribute__((cf_returns_not_retained))`,
6086`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
6087have the same respective semantics when applied to CoreFoundation objects.
6088These attributes affect code generation when interacting with ARC code, and
6089they are used by the Clang Static Analyzer.
6090
6091Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
6092the same attribute family is present:
6093`__attribute__((os_returns_not_retained))`,
6094`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
6095with the same respective semantics.
6096Similar to `__attribute__((ns_consumes_self))`,
6097`__attribute__((os_consumes_this))` specifies that the method call consumes
6098the reference to "this" (e.g., when attaching it to a different object supplied
6099as a parameter).
6100Out parameters (parameters the function is meant to write into,
6101either via pointers-to-pointers or references-to-pointers)
6102may be annotated with `__attribute__((os_returns_retained))`
6103or `__attribute__((os_returns_not_retained))` which specifies that the object
6104written into the out parameter should (or respectively should not) be released
6105after use.
6106Since often out parameters may or may not be written depending on the exit
6107code of the function,
6108annotations `__attribute__((os_returns_retained_on_zero))`
6109and `__attribute__((os_returns_retained_on_non_zero))` specify that
6110an out parameter at `+1` is written if and only if the function returns a zero
6111(respectively non-zero) error code.
6112Observe that return-code-dependent out parameter annotations are only
6113available for retained out parameters, as non-retained object do not have to be
6114released by the callee.
6115These attributes are only used by the Clang Static Analyzer.
6116
6117The family of attributes `X_returns_X_retained` can be added to functions,
6118C++ methods, and Objective-C methods and properties.
6119Attributes `X_consumed` can be added to parameters of methods, functions,
6120and Objective-C methods.)reST";
6121
6122static const char AttrDoc_OSReturnsNotRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
6123(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
6124convention (e.g. functions starting with "get" are assumed to return at
6125`+0`).
6126
6127It can be overridden using a family of the following attributes. In
6128Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
6129a function communicates that the object is returned at `+1`, and the caller
6130is responsible for freeing it.
6131Similarly, the annotation `__attribute__((ns_returns_not_retained))`
6132specifies that the object is returned at `+0` and the ownership remains with
6133the callee.
6134The annotation `__attribute__((ns_consumes_self))` specifies that
6135the Objective-C method call consumes the reference to `self`, e.g. by
6136attaching it to a supplied parameter.
6137Additionally, parameters can have an annotation
6138`__attribute__((ns_consumed))`, which specifies that passing an owned object
6139as that parameter effectively transfers the ownership, and the caller is no
6140longer responsible for it.
6141These attributes affect code generation when interacting with ARC code, and
6142they are used by the Clang Static Analyzer.
6143
6144In C programs using CoreFoundation, a similar set of attributes:
6145`__attribute__((cf_returns_not_retained))`,
6146`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
6147have the same respective semantics when applied to CoreFoundation objects.
6148These attributes affect code generation when interacting with ARC code, and
6149they are used by the Clang Static Analyzer.
6150
6151Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
6152the same attribute family is present:
6153`__attribute__((os_returns_not_retained))`,
6154`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
6155with the same respective semantics.
6156Similar to `__attribute__((ns_consumes_self))`,
6157`__attribute__((os_consumes_this))` specifies that the method call consumes
6158the reference to "this" (e.g., when attaching it to a different object supplied
6159as a parameter).
6160Out parameters (parameters the function is meant to write into,
6161either via pointers-to-pointers or references-to-pointers)
6162may be annotated with `__attribute__((os_returns_retained))`
6163or `__attribute__((os_returns_not_retained))` which specifies that the object
6164written into the out parameter should (or respectively should not) be released
6165after use.
6166Since often out parameters may or may not be written depending on the exit
6167code of the function,
6168annotations `__attribute__((os_returns_retained_on_zero))`
6169and `__attribute__((os_returns_retained_on_non_zero))` specify that
6170an out parameter at `+1` is written if and only if the function returns a zero
6171(respectively non-zero) error code.
6172Observe that return-code-dependent out parameter annotations are only
6173available for retained out parameters, as non-retained object do not have to be
6174released by the callee.
6175These attributes are only used by the Clang Static Analyzer.
6176
6177The family of attributes `X_returns_X_retained` can be added to functions,
6178C++ methods, and Objective-C methods and properties.
6179Attributes `X_consumed` can be added to parameters of methods, functions,
6180and Objective-C methods.)reST";
6181
6182static const char AttrDoc_OSReturnsRetained[] = R"reST(The behavior of a function with respect to reference counting for Foundation
6183(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
6184convention (e.g. functions starting with "get" are assumed to return at
6185`+0`).
6186
6187It can be overridden using a family of the following attributes. In
6188Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
6189a function communicates that the object is returned at `+1`, and the caller
6190is responsible for freeing it.
6191Similarly, the annotation `__attribute__((ns_returns_not_retained))`
6192specifies that the object is returned at `+0` and the ownership remains with
6193the callee.
6194The annotation `__attribute__((ns_consumes_self))` specifies that
6195the Objective-C method call consumes the reference to `self`, e.g. by
6196attaching it to a supplied parameter.
6197Additionally, parameters can have an annotation
6198`__attribute__((ns_consumed))`, which specifies that passing an owned object
6199as that parameter effectively transfers the ownership, and the caller is no
6200longer responsible for it.
6201These attributes affect code generation when interacting with ARC code, and
6202they are used by the Clang Static Analyzer.
6203
6204In C programs using CoreFoundation, a similar set of attributes:
6205`__attribute__((cf_returns_not_retained))`,
6206`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
6207have the same respective semantics when applied to CoreFoundation objects.
6208These attributes affect code generation when interacting with ARC code, and
6209they are used by the Clang Static Analyzer.
6210
6211Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
6212the same attribute family is present:
6213`__attribute__((os_returns_not_retained))`,
6214`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
6215with the same respective semantics.
6216Similar to `__attribute__((ns_consumes_self))`,
6217`__attribute__((os_consumes_this))` specifies that the method call consumes
6218the reference to "this" (e.g., when attaching it to a different object supplied
6219as a parameter).
6220Out parameters (parameters the function is meant to write into,
6221either via pointers-to-pointers or references-to-pointers)
6222may be annotated with `__attribute__((os_returns_retained))`
6223or `__attribute__((os_returns_not_retained))` which specifies that the object
6224written into the out parameter should (or respectively should not) be released
6225after use.
6226Since often out parameters may or may not be written depending on the exit
6227code of the function,
6228annotations `__attribute__((os_returns_retained_on_zero))`
6229and `__attribute__((os_returns_retained_on_non_zero))` specify that
6230an out parameter at `+1` is written if and only if the function returns a zero
6231(respectively non-zero) error code.
6232Observe that return-code-dependent out parameter annotations are only
6233available for retained out parameters, as non-retained object do not have to be
6234released by the callee.
6235These attributes are only used by the Clang Static Analyzer.
6236
6237The family of attributes `X_returns_X_retained` can be added to functions,
6238C++ methods, and Objective-C methods and properties.
6239Attributes `X_consumed` can be added to parameters of methods, functions,
6240and Objective-C methods.)reST";
6241
6242static const char AttrDoc_OSReturnsRetainedOnNonZero[] = R"reST(The behavior of a function with respect to reference counting for Foundation
6243(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
6244convention (e.g. functions starting with "get" are assumed to return at
6245`+0`).
6246
6247It can be overridden using a family of the following attributes. In
6248Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
6249a function communicates that the object is returned at `+1`, and the caller
6250is responsible for freeing it.
6251Similarly, the annotation `__attribute__((ns_returns_not_retained))`
6252specifies that the object is returned at `+0` and the ownership remains with
6253the callee.
6254The annotation `__attribute__((ns_consumes_self))` specifies that
6255the Objective-C method call consumes the reference to `self`, e.g. by
6256attaching it to a supplied parameter.
6257Additionally, parameters can have an annotation
6258`__attribute__((ns_consumed))`, which specifies that passing an owned object
6259as that parameter effectively transfers the ownership, and the caller is no
6260longer responsible for it.
6261These attributes affect code generation when interacting with ARC code, and
6262they are used by the Clang Static Analyzer.
6263
6264In C programs using CoreFoundation, a similar set of attributes:
6265`__attribute__((cf_returns_not_retained))`,
6266`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
6267have the same respective semantics when applied to CoreFoundation objects.
6268These attributes affect code generation when interacting with ARC code, and
6269they are used by the Clang Static Analyzer.
6270
6271Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
6272the same attribute family is present:
6273`__attribute__((os_returns_not_retained))`,
6274`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
6275with the same respective semantics.
6276Similar to `__attribute__((ns_consumes_self))`,
6277`__attribute__((os_consumes_this))` specifies that the method call consumes
6278the reference to "this" (e.g., when attaching it to a different object supplied
6279as a parameter).
6280Out parameters (parameters the function is meant to write into,
6281either via pointers-to-pointers or references-to-pointers)
6282may be annotated with `__attribute__((os_returns_retained))`
6283or `__attribute__((os_returns_not_retained))` which specifies that the object
6284written into the out parameter should (or respectively should not) be released
6285after use.
6286Since often out parameters may or may not be written depending on the exit
6287code of the function,
6288annotations `__attribute__((os_returns_retained_on_zero))`
6289and `__attribute__((os_returns_retained_on_non_zero))` specify that
6290an out parameter at `+1` is written if and only if the function returns a zero
6291(respectively non-zero) error code.
6292Observe that return-code-dependent out parameter annotations are only
6293available for retained out parameters, as non-retained object do not have to be
6294released by the callee.
6295These attributes are only used by the Clang Static Analyzer.
6296
6297The family of attributes `X_returns_X_retained` can be added to functions,
6298C++ methods, and Objective-C methods and properties.
6299Attributes `X_consumed` can be added to parameters of methods, functions,
6300and Objective-C methods.)reST";
6301
6302static const char AttrDoc_OSReturnsRetainedOnZero[] = R"reST(The behavior of a function with respect to reference counting for Foundation
6303(Objective-C), CoreFoundation (C) and OSObject (C++) is determined by a naming
6304convention (e.g. functions starting with "get" are assumed to return at
6305`+0`).
6306
6307It can be overridden using a family of the following attributes. In
6308Objective-C, the annotation `__attribute__((ns_returns_retained))` applied to
6309a function communicates that the object is returned at `+1`, and the caller
6310is responsible for freeing it.
6311Similarly, the annotation `__attribute__((ns_returns_not_retained))`
6312specifies that the object is returned at `+0` and the ownership remains with
6313the callee.
6314The annotation `__attribute__((ns_consumes_self))` specifies that
6315the Objective-C method call consumes the reference to `self`, e.g. by
6316attaching it to a supplied parameter.
6317Additionally, parameters can have an annotation
6318`__attribute__((ns_consumed))`, which specifies that passing an owned object
6319as that parameter effectively transfers the ownership, and the caller is no
6320longer responsible for it.
6321These attributes affect code generation when interacting with ARC code, and
6322they are used by the Clang Static Analyzer.
6323
6324In C programs using CoreFoundation, a similar set of attributes:
6325`__attribute__((cf_returns_not_retained))`,
6326`__attribute__((cf_returns_retained))` and `__attribute__((cf_consumed))`
6327have the same respective semantics when applied to CoreFoundation objects.
6328These attributes affect code generation when interacting with ARC code, and
6329they are used by the Clang Static Analyzer.
6330
6331Finally, in C++ interacting with XNU kernel (objects inheriting from OSObject),
6332the same attribute family is present:
6333`__attribute__((os_returns_not_retained))`,
6334`__attribute__((os_returns_retained))` and `__attribute__((os_consumed))`,
6335with the same respective semantics.
6336Similar to `__attribute__((ns_consumes_self))`,
6337`__attribute__((os_consumes_this))` specifies that the method call consumes
6338the reference to "this" (e.g., when attaching it to a different object supplied
6339as a parameter).
6340Out parameters (parameters the function is meant to write into,
6341either via pointers-to-pointers or references-to-pointers)
6342may be annotated with `__attribute__((os_returns_retained))`
6343or `__attribute__((os_returns_not_retained))` which specifies that the object
6344written into the out parameter should (or respectively should not) be released
6345after use.
6346Since often out parameters may or may not be written depending on the exit
6347code of the function,
6348annotations `__attribute__((os_returns_retained_on_zero))`
6349and `__attribute__((os_returns_retained_on_non_zero))` specify that
6350an out parameter at `+1` is written if and only if the function returns a zero
6351(respectively non-zero) error code.
6352Observe that return-code-dependent out parameter annotations are only
6353available for retained out parameters, as non-retained object do not have to be
6354released by the callee.
6355These attributes are only used by the Clang Static Analyzer.
6356
6357The family of attributes `X_returns_X_retained` can be added to functions,
6358C++ methods, and Objective-C methods and properties.
6359Attributes `X_consumed` can be added to parameters of methods, functions,
6360and Objective-C methods.)reST";
6361
6362static const char AttrDoc_ObjCBoxable[] = R"reST(Structs and unions marked with the `objc_boxable` attribute can be used
6363with the Objective-C boxed expression syntax, `@(...)`.
6364
6365**Usage**: `__attribute__((objc_boxable))`. This attribute
6366can only be placed on a declaration of a trivially-copyable struct or union:
6367
6368```objc
6369struct __attribute__((objc_boxable)) some_struct {
6370 int i;
6371};
6372union __attribute__((objc_boxable)) some_union {
6373 int i;
6374 float f;
6375};
6376typedef struct __attribute__((objc_boxable)) _some_struct some_struct;
6377
6378// ...
6379
6380some_struct ss;
6381NSValue *boxed = @(ss);
6382```)reST";
6383
6384static const char AttrDoc_ObjCBridge[] = R"reST(No documentation.)reST";
6385
6386static const char AttrDoc_ObjCBridgeMutable[] = R"reST(No documentation.)reST";
6387
6388static const char AttrDoc_ObjCBridgeRelated[] = R"reST(No documentation.)reST";
6389
6390static const char AttrDoc_ObjCClassStub[] = R"reST(This attribute specifies that the Objective-C class to which it applies is
6391instantiated at runtime.
6392
6393Unlike `__attribute__((objc_runtime_visible))`, a class having this attribute
6394still has a "class stub" that is visible to the linker. This allows categories
6395to be defined. Static message sends with the class as a receiver use a special
6396access pattern to ensure the class is lazily instantiated from the class stub.
6397
6398Classes annotated with this attribute cannot be subclassed and cannot have
6399implementations defined for them. This attribute is intended for use in
6400Swift-generated headers for classes defined in Swift.
6401
6402Adding or removing this attribute to a class is an ABI-breaking change.)reST";
6403
6404static const char AttrDoc_ObjCDesignatedInitializer[] = R"reST(No documentation.)reST";
6405
6406static const char AttrDoc_ObjCDirect[] = R"reST(The `objc_direct` attribute can be used to mark an Objective-C method as
6407being *direct*. A direct method is treated statically like an ordinary method,
6408but dynamically it behaves more like a C function. This lowers some of the costs
6409associated with the method but also sacrifices some of the ordinary capabilities
6410of Objective-C methods.
6411
6412A message send of a direct method calls the implementation directly, as if it
6413were a C function, rather than using ordinary Objective-C method dispatch. This
6414is substantially faster and potentially allows the implementation to be inlined,
6415but it also means the method cannot be overridden in subclasses or replaced
6416dynamically, as ordinary Objective-C methods can.
6417
6418Furthermore, a direct method is not listed in the class's method lists. This
6419substantially reduces the code-size overhead of the method but also means it
6420cannot be called dynamically using ordinary Objective-C method dispatch at all;
6421in particular, this means that it cannot override a superclass method or satisfy
6422a protocol requirement.
6423
6424Because a direct method cannot be overridden, it is an error to perform
6425a `super` message send of one.
6426
6427Although a message send of a direct method causes the method to be called
6428directly as if it were a C function, it still obeys Objective-C semantics in other
6429ways:
6430
6431- If the receiver is `nil`, the message send does nothing and returns the zero value
6432 for the return type.
6433- A message send of a direct class method will cause the class to be initialized,
6434 including calling the `+initialize` method if present.
6435- The implicit `_cmd` parameter containing the method's selector is still defined.
6436 In order to minimize code-size costs, the implementation will not emit a reference
6437 to the selector if the parameter is unused within the method.
6438
6439Symbols for direct method implementations are implicitly given hidden
6440visibility, meaning that they can only be called within the same linkage unit.
6441
6442It is an error to do any of the following:
6443
6444- declare a direct method in a protocol,
6445- declare an override of a direct method with a method in a subclass,
6446- declare an override of a non-direct method with a direct method in a subclass,
6447- declare a method with different directness in different class interfaces, or
6448- implement a non-direct method (as declared in any class interface) with a direct method.
6449
6450If any of these rules would be violated if every method defined in an
6451`@implementation` within a single linkage unit were declared in an
6452appropriate class interface, the program is ill-formed with no diagnostic
6453required. If a violation of this rule is not diagnosed, behavior remains
6454well-defined; this paragraph is simply reserving the right to diagnose such
6455conflicts in the future, not to treat them as undefined behavior.
6456
6457Additionally, Clang will warn about any `@selector` expression that
6458names a selector that is only known to be used for direct methods.
6459
6460For the purpose of these rules, a "class interface" includes a class's primary
6461`@interface` block, its class extensions, its categories, its declared protocols,
6462and all the class interfaces of its superclasses.
6463
6464An Objective-C property can be declared with the `direct` property
6465attribute. If a direct property declaration causes an implicit declaration of
6466a getter or setter method (that is, if the given method is not explicitly
6467declared elsewhere), the method is declared to be direct.
6468
6469Some programmers may wish to make many methods direct at once. In order
6470to simplify this, the `objc_direct_members` attribute is provided; see its
6471documentation for more information.)reST";
6472
6473static const char AttrDoc_ObjCDirectMembers[] = R"reST(The `objc_direct_members` attribute can be placed on an Objective-C
6474`@interface` or `@implementation` to mark that methods declared
6475therein should be considered direct by default. See the documentation
6476for `objc_direct` for more information about direct methods.
6477
6478When `objc_direct_members` is placed on an `@interface` block, every
6479method in the block is considered to be declared as direct. This includes any
6480implicit method declarations introduced by property declarations. If the method
6481redeclares a non-direct method, the declaration is ill-formed, exactly as if the
6482method was annotated with the `objc_direct` attribute.
6483
6484When `objc_direct_members` is placed on an `@implementation` block,
6485methods defined in the block are considered to be declared as direct unless
6486they have been previously declared as non-direct in any interface of the class.
6487This includes the implicit method definitions introduced by synthesized
6488properties, including auto-synthesized properties.)reST";
6489
6490static const char AttrDoc_ObjCException[] = R"reST(No documentation.)reST";
6491
6492static const char AttrDoc_ObjCExplicitProtocolImpl[] = R"reST(No documentation.)reST";
6493
6494static const char AttrDoc_ObjCExternallyRetained[] = R"reST(The `objc_externally_retained` attribute can be applied to strong local
6495variables, functions, methods, or blocks to opt into
6496{ref}`externally-retained semantics <arc.misc.externally_retained>`.
6497
6498When applied to the definition of a function, method, or block, every parameter
6499of the function with implicit strong retainable object pointer type is
6500considered externally-retained, and becomes `const`. By explicitly annotating
6501a parameter with `__strong`, you can opt back into the default
6502non-externally-retained behavior for that parameter. For instance,
6503`first_param` is externally-retained below, but not `second_param`:
6504
6505```objc
6506__attribute__((objc_externally_retained))
6507void f(NSArray *first_param, __strong NSArray *second_param) {
6508 // ...
6509}
6510```
6511
6512Likewise, when applied to a strong local variable, that variable becomes
6513`const` and is considered externally-retained.
6514
6515When compiled without `-fobjc-arc`, this attribute is ignored.)reST";
6516
6517static const char AttrDoc_ObjCGC[] = R"reST(No documentation.)reST";
6518
6519static const char AttrDoc_ObjCIndependentClass[] = R"reST(No documentation.)reST";
6520
6521static const char AttrDoc_ObjCInertUnsafeUnretained[] = R"reST()reST";
6522
6523static const char AttrDoc_ObjCKindOf[] = R"reST(No documentation.)reST";
6524
6525static const char AttrDoc_ObjCMethodFamily[] = R"reST(Many methods in Objective-C have conventional meanings determined by their
6526selectors. It is sometimes useful to be able to mark a method as having a
6527particular conventional meaning despite not having the right selector, or as
6528not having the conventional meaning that its selector would suggest. For these
6529use cases, we provide an attribute to specifically describe the "method family"
6530that a method belongs to.
6531
6532**Usage**: `__attribute__((objc_method_family(X)))`, where `X` is one of
6533`none`, `alloc`, `copy`, `init`, `mutableCopy`, or `new`. This
6534attribute can only be placed at the end of a method declaration:
6535
6536```objc
6537- (NSString *)initMyStringValue __attribute__((objc_method_family(none)));
6538```
6539
6540Users who do not wish to change the conventional meaning of a method, and who
6541merely want to document its non-standard retain and release semantics, should
6542use the retaining behavior attributes (`ns_returns_retained`,
6543`ns_returns_not_retained`, etc).
6544
6545Query for this feature with `__has_attribute(objc_method_family)`.)reST";
6546
6547static const char AttrDoc_ObjCNSObject[] = R"reST(No documentation.)reST";
6548
6549static const char AttrDoc_ObjCNonLazyClass[] = R"reST(This attribute can be added to an Objective-C `@interface` or
6550`@implementation` declaration to add the class to the list of non-lazily
6551initialized classes. A non-lazy class will be initialized eagerly when the
6552Objective-C runtime is loaded. This is required for certain system classes which
6553have instances allocated in non-standard ways, such as the classes for blocks
6554and constant strings. Adding this attribute is essentially equivalent to
6555providing a trivial `+load` method but avoids the (fairly small) load-time
6556overheads associated with defining and calling such a method.)reST";
6557
6558static const char AttrDoc_ObjCNonRuntimeProtocol[] = R"reST(The `objc_non_runtime_protocol` attribute can be used to mark that an
6559Objective-C protocol is only used during static type-checking and doesn't need
6560to be represented dynamically. This avoids several small code-size and run-time
6561overheads associated with handling the protocol's metadata. A non-runtime
6562protocol cannot be used as the operand of a `@protocol` expression, and
6563dynamic attempts to find it with `objc_getProtocol` will fail.
6564
6565If a non-runtime protocol inherits from any ordinary protocols, classes and
6566derived protocols that declare conformance to the non-runtime protocol will
6567dynamically list their conformance to those bare protocols.)reST";
6568
6569static const char AttrDoc_ObjCOwnership[] = R"reST(No documentation.)reST";
6570
6571static const char AttrDoc_ObjCPreciseLifetime[] = R"reST(No documentation.)reST";
6572
6573static const char AttrDoc_ObjCRequiresPropertyDefs[] = R"reST(No documentation.)reST";
6574
6575static const char AttrDoc_ObjCRequiresSuper[] = R"reST(Some Objective-C classes allow a subclass to override a particular method in a
6576parent class but expect that the overriding method also calls the overridden
6577method in the parent class. For these cases, we provide an attribute to
6578designate that a method requires a "call to `super`" in the overriding
6579method in the subclass.
6580
6581**Usage**: `__attribute__((objc_requires_super))`. This attribute can only
6582be placed at the end of a method declaration:
6583
6584```objc
6585- (void)foo __attribute__((objc_requires_super));
6586```
6587
6588This attribute can only be applied the method declarations within a class, and
6589not a protocol. Currently this attribute does not enforce any placement of
6590where the call occurs in the overriding method (such as in the case of
6591`-dealloc` where the call must appear at the end). It checks only that it
6592exists.
6593
6594Note that on both OS X and iOS that the Foundation framework provides a
6595convenience macro `NS_REQUIRES_SUPER` that provides syntactic sugar for this
6596attribute:
6597
6598```objc
6599- (void)foo NS_REQUIRES_SUPER;
6600```
6601
6602This macro is conditionally defined depending on the compiler's support for
6603this attribute. If the compiler does not support the attribute the macro
6604expands to nothing.
6605
6606Operationally, when a method has this annotation the compiler will warn if the
6607implementation of an override in a subclass does not call super. For example:
6608
6609```objc
6610warning: method possibly missing a [super AnnotMeth] call
6611- (void) AnnotMeth{};
6612 ^
6613```)reST";
6614
6615static const char AttrDoc_ObjCReturnsInnerPointer[] = R"reST(No documentation.)reST";
6616
6617static const char AttrDoc_ObjCRootClass[] = R"reST(No documentation.)reST";
6618
6619static const char AttrDoc_ObjCRuntimeName[] = R"reST(By default, the Objective-C interface or protocol identifier is used
6620in the metadata name for that object. The `objc_runtime_name`
6621attribute allows annotated interfaces or protocols to use the
6622specified string argument in the object's metadata name instead of the
6623default name.
6624
6625**Usage**: `__attribute__((objc_runtime_name("MyLocalName")))`. This attribute
6626can only be placed before an @protocol or @interface declaration:
6627
6628```objc
6629__attribute__((objc_runtime_name("MyLocalName")))
6630@interface Message
6631@end
6632```)reST";
6633
6634static const char AttrDoc_ObjCRuntimeVisible[] = R"reST(This attribute specifies that the Objective-C class to which it applies is
6635visible to the Objective-C runtime but not to the linker. Classes annotated
6636with this attribute cannot be subclassed and cannot have categories defined for
6637them.)reST";
6638
6639static const char AttrDoc_ObjCSubclassingRestricted[] = R"reST(This attribute can be added to an Objective-C `@interface` declaration to
6640ensure that this class cannot be subclassed.)reST";
6641
6642static const char AttrDoc_OpenACCRoutineAnnot[] = R"reST()reST";
6643
6644static const char AttrDoc_OpenACCRoutineDecl[] = R"reST()reST";
6645
6646static const char AttrDoc_OpenCLAccess[] = R"reST(The access qualifiers must be used with image object arguments or pipe arguments
6647to declare if they are being read or written by a kernel or function.
6648
6649The read_only/\_\_read_only, write_only/\_\_write_only and read_write/\_\_read_write
6650names are reserved for use as access qualifiers and shall not be used otherwise.
6651
6652```c
6653kernel void
6654foo (read_only image2d_t imageA,
6655 write_only image2d_t imageB) {
6656 ...
6657}
6658```
6659
6660In the above example imageA is a read-only 2D image object, and imageB is a
6661write-only 2D image object.
6662
6663The read_write (or \_\_read_write) qualifier can not be used with pipe.
6664
6665More details can be found in the OpenCL C language Spec v2.0, Section 6.6.)reST";
6666
6667static const char AttrDoc_OpenCLConstantAddressSpace[] = R"reST(The constant address space attribute signals that an object is located in
6668a constant (non-modifiable) memory region. It is available to all work items.
6669Any type can be annotated with the constant address space attribute. Objects
6670with the constant address space qualifier can be declared in any scope and must
6671have an initializer.)reST";
6672
6673static const char AttrDoc_OpenCLGenericAddressSpace[] = R"reST(The generic address space attribute is only available with OpenCL v2.0 and later.
6674It can be used with pointer types. Variables in global and local scope and
6675function parameters in non-kernel functions can have the generic address space
6676type attribute. It is intended to be a placeholder for any other address space
6677except for '\_\_constant' in OpenCL code which can be used with multiple address
6678spaces.)reST";
6679
6680static const char AttrDoc_OpenCLGlobalAddressSpace[] = R"reST(The global address space attribute specifies that an object is allocated in
6681global memory, which is accessible by all work items. The content stored in this
6682memory area persists between kernel executions. Pointer types to the global
6683address space are allowed as function parameters or local variables. Starting
6684with OpenCL v2.0, the global address space can be used with global (program
6685scope) variables and static local variable as well.)reST";
6686
6687static const char AttrDoc_OpenCLGlobalDeviceAddressSpace[] = R"reST(The `global_device` and `global_host` address space attributes specify that
6688an object is allocated in global memory on the device/host. It helps to
6689distinguish USM (Unified Shared Memory) pointers that access global device
6690memory from those that access global host memory. These new address spaces are
6691a subset of the `__global/opencl_global` address space, the full address space
6692set model for OpenCL 2.0 with the extension looks as follows:
6693
6694```text
6695generic->global->host
6696 ->device
6697 ->private
6698 ->local
6699constant
6700```
6701
6702As `global_device` and `global_host` are a subset of
6703`__global/opencl_global` address spaces it is allowed to convert
6704`global_device` and `global_host` address spaces to
6705`__global/opencl_global` address spaces (following ISO/IEC TR 18037 5.1.3
6706"Address space nesting and rules for pointers").
6707
6708These attributes are deprecated and may be removed in a future version of Clang.)reST";
6709
6710static const char AttrDoc_OpenCLGlobalHostAddressSpace[] = R"reST(The `global_device` and `global_host` address space attributes specify that
6711an object is allocated in global memory on the device/host. It helps to
6712distinguish USM (Unified Shared Memory) pointers that access global device
6713memory from those that access global host memory. These new address spaces are
6714a subset of the `__global/opencl_global` address space, the full address space
6715set model for OpenCL 2.0 with the extension looks as follows:
6716
6717```text
6718generic->global->host
6719 ->device
6720 ->private
6721 ->local
6722constant
6723```
6724
6725As `global_device` and `global_host` are a subset of
6726`__global/opencl_global` address spaces it is allowed to convert
6727`global_device` and `global_host` address spaces to
6728`__global/opencl_global` address spaces (following ISO/IEC TR 18037 5.1.3
6729"Address space nesting and rules for pointers").
6730
6731These attributes are deprecated and may be removed in a future version of Clang.)reST";
6732
6733static const char AttrDoc_OpenCLIntelReqdSubGroupSize[] = R"reST(The optional attribute intel_reqd_sub_group_size can be used to indicate that
6734the kernel must be compiled and executed with the specified subgroup size. When
6735this attribute is present, get_max_sub_group_size() is guaranteed to return the
6736specified integer value. This is important for the correctness of many subgroup
6737algorithms, and in some cases may be used by the compiler to generate more optimal
6738code. See `cl_intel_required_subgroup_size
6739<https://www.khronos.org/registry/OpenCL/extensions/intel/cl_intel_required_subgroup_size.txt>`
6740for details.)reST";
6741
6742static const char AttrDoc_OpenCLLocalAddressSpace[] = R"reST(The local address space specifies that an object is allocated in the local (work
6743group) memory area, which is accessible to all work items in the same work
6744group. The content stored in this memory region is not accessible after
6745the kernel execution ends. In a kernel function scope, any variable can be in
6746the local address space. In other scopes, only pointer types to the local address
6747space are allowed. Local address space variables cannot have an initializer.)reST";
6748
6749static const char AttrDoc_OpenCLPrivateAddressSpace[] = R"reST(The private address space specifies that an object is allocated in the private
6750(work item) memory. Other work items cannot access the same memory area and its
6751content is destroyed after work item execution ends. Local variables can be
6752declared in the private address space. Function arguments are always in the
6753private address space. Kernel function arguments of a pointer or an array type
6754cannot point to the private address space.)reST";
6755
6756static const char AttrDoc_OpenCLUnrollHint[] = R"reST(The opencl_unroll_hint attribute qualifier can be used to specify that a loop
6757(for, while and do loops) can be unrolled. This attribute qualifier can be
6758used to specify full unrolling or partial unrolling by a specified amount.
6759This is a compiler hint and the compiler may ignore this directive. See
6760[OpenCL v2.0](https://www.khronos.org/registry/cl/specs/opencl-2.0.pdf)
6761s6.11.5 for details.)reST";
6762
6763static const char AttrDoc_OptimizeNone[] = R"reST(The `optnone` attribute suppresses essentially all optimizations
6764on a function or method, regardless of the optimization level applied to
6765the compilation unit as a whole. This is particularly useful when you
6766need to debug a particular function, but it is infeasible to build the
6767entire application without optimization. Avoiding optimization on the
6768specified function can improve the quality of the debugging information
6769for that function.
6770
6771This attribute is incompatible with the `always_inline` and `minsize`
6772attributes.
6773
6774Note that this attribute does not apply recursively to nested functions such as
6775lambdas or blocks when using declaration-specific attribute syntaxes such as double
6776square brackets (`[[]]`) or `__attribute__`. The `#pragma` syntax can be
6777used to apply the attribute to all functions, including nested functions, in a
6778range of source code.)reST";
6779
6780static const char AttrDoc_OverflowBehavior[] = R"reST(The `overflow_behavior` attribute provides fine-grained, type-level control
6781over how arithmetic operations on an integer type behave on overflow. It may be
6782applied to a `typedef`, to a variable or data member, or to an integer type
6783directly, and accepts one of two behaviors as its argument:
6784
6785- `wrap`: arithmetic on the attributed type wraps on overflow, using two's
6786 complement semantics. This is equivalent to `-fwrapv` but scoped to the
6787 attributed type, and works for both signed and unsigned types. UBSan's
6788 `signed-integer-overflow`, `unsigned-integer-overflow`,
6789 `implicit-signed-integer-truncation`, and
6790 `implicit-unsigned-integer-truncation` checks are suppressed for the type.
6791- `trap`: arithmetic on the attributed type is checked for overflow, enabling
6792 overflow checks for the type even when `-fwrapv` is in effect globally.
6793
6794```c++
6795typedef unsigned int __attribute__((overflow_behavior(trap))) non_wrapping_uint;
6796
6797non_wrapping_uint add_one(non_wrapping_uint a) {
6798 return a + 1; // Overflow is checked for this operation.
6799}
6800
6801int mul_alot(int n) {
6802 int __attribute__((overflow_behavior(wrap))) a = n;
6803 return a * 1337; // Overflow is not checked and is well-defined.
6804}
6805```
6806
6807The keyword spellings `__ob_wrap` and `__ob_trap` are equivalent to
6808`overflow_behavior(wrap)` and `overflow_behavior(trap)` respectively.
6809
6810The attribute wholly overrides global flags (`-ftrapv`, `-fwrapv`,
6811sanitizers, and Sanitizer Special Case Lists) for the attributed type. It can
6812only be applied to integer types.
6813
6814This feature is experimental and must be enabled with the `-cc1` option
6815`-fexperimental-overflow-behavior-types`. For full details on promotion and
6816conversion rules, pointer semantics, diagnostics, and interaction with
6817sanitizers, see {doc}`OverflowBehaviorTypes`.)reST";
6818
6819static const char AttrDoc_Overloadable[] = R"reST(Clang provides support for C++ function overloading in C. Function overloading
6820in C is introduced using the `overloadable` attribute. For example, one
6821might provide several overloaded versions of a `tgsin` function that invokes
6822the appropriate standard function computing the sine of a value with `float`,
6823`double`, or `long double` precision:
6824
6825```c
6826#include <math.h>
6827float __attribute__((overloadable)) tgsin(float x) { return sinf(x); }
6828double __attribute__((overloadable)) tgsin(double x) { return sin(x); }
6829long double __attribute__((overloadable)) tgsin(long double x) { return sinl(x); }
6830```
6831
6832Given these declarations, one can call `tgsin` with a `float` value to
6833receive a `float` result, with a `double` to receive a `double` result,
6834etc. Function overloading in C follows the rules of C++ function overloading
6835to pick the best overload given the call arguments, with a few C-specific
6836semantics:
6837
6838- Conversion from `float` or `double` to `long double` is ranked as a
6839 floating-point promotion (per C99) rather than as a floating-point conversion
6840 (as in C++).
6841- A conversion from a pointer of type `T*` to a pointer of type `U*` is
6842 considered a pointer conversion (with conversion rank) if `T` and `U` are
6843 compatible types.
6844- A conversion from type `T` to a value of type `U` is permitted if `T`
6845 and `U` are compatible types. This conversion is given "conversion" rank.
6846- If no viable candidates are otherwise available, we allow a conversion from a
6847 pointer of type `T*` to a pointer of type `U*`, where `T` and `U` are
6848 incompatible. This conversion is ranked below all other types of conversions.
6849 Please note: `U` lacking qualifiers that are present on `T` is sufficient
6850 for `T` and `U` to be incompatible.
6851
6852The declaration of `overloadable` functions is restricted to function
6853declarations and definitions. If a function is marked with the `overloadable`
6854attribute, then all declarations and definitions of functions with that name,
6855except for at most one (see the note below about unmarked overloads), must have
6856the `overloadable` attribute. In addition, redeclarations of a function with
6857the `overloadable` attribute must have the `overloadable` attribute, and
6858redeclarations of a function without the `overloadable` attribute must *not*
6859have the `overloadable` attribute. e.g.,
6860
6861```c
6862int f(int) __attribute__((overloadable));
6863float f(float); // error: declaration of "f" must have the "overloadable" attribute
6864int f(int); // error: redeclaration of "f" must have the "overloadable" attribute
6865
6866int g(int) __attribute__((overloadable));
6867int g(int) { } // error: redeclaration of "g" must also have the "overloadable" attribute
6868
6869int h(int);
6870int h(int) __attribute__((overloadable)); // error: declaration of "h" must not
6871 // have the "overloadable" attribute
6872```
6873
6874Functions marked `overloadable` must have prototypes. Therefore, the
6875following code is ill-formed:
6876
6877```c
6878int h() __attribute__((overloadable)); // error: h does not have a prototype
6879```
6880
6881However, `overloadable` functions are allowed to use a ellipsis even if there
6882are no named parameters (as is permitted in C++). This feature is particularly
6883useful when combined with the `unavailable` attribute:
6884
6885```c++
6886void honeypot(...) __attribute__((overloadable, unavailable)); // calling me is an error
6887```
6888
6889Functions declared with the `overloadable` attribute have their names mangled
6890according to the same rules as C++ function names. For example, the three
6891`tgsin` functions in our motivating example get the mangled names
6892`_Z5tgsinf`, `_Z5tgsind`, and `_Z5tgsine`, respectively. There are two
6893caveats to this use of name mangling:
6894
6895- Future versions of Clang may change the name mangling of functions overloaded
6896 in C, so you should not depend on an specific mangling. To be completely
6897 safe, we strongly urge the use of `static inline` with `overloadable`
6898 functions.
6899- The `overloadable` attribute has almost no meaning when used in C++,
6900 because names will already be mangled and functions are already overloadable.
6901 However, when an `overloadable` function occurs within an `extern "C"`
6902 linkage specification, its name *will* be mangled in the same way as it
6903 would in C.
6904
6905For the purpose of backwards compatibility, at most one function with the same
6906name as other `overloadable` functions may omit the `overloadable`
6907attribute. In this case, the function without the `overloadable` attribute
6908will not have its name mangled.
6909
6910For example:
6911
6912```c
6913// Notes with mangled names assume Itanium mangling.
6914int f(int);
6915int f(double) __attribute__((overloadable));
6916void foo() {
6917 f(5); // Emits a call to f (not _Z1fi, as it would with an overload that
6918 // was marked with overloadable).
6919 f(1.0); // Emits a call to _Z1fd.
6920}
6921```
6922
6923Support for unmarked overloads is not present in some versions of clang. You may
6924query for it using `__has_extension(overloadable_unmarked)`.
6925
6926Query for this attribute with `__has_attribute(overloadable)`.)reST";
6927
6928static const char AttrDoc_Override[] = R"reST()reST";
6929
6930static const char AttrDoc_Owner[] = R"reST(:::{Note}
6931This attribute is experimental and its effect on analysis is subject to change in
6932a future version of clang.
6933:::
6934
6935The attribute `[[gsl::Owner(T)]]` applies to structs and classes that own an
6936object of type `T`:
6937
6938```
6939class [[gsl::Owner(int)]] IntOwner {
6940private:
6941 int value;
6942public:
6943 int *getInt() { return &value; }
6944};
6945```
6946
6947The argument `T` is optional and is ignored.
6948This attribute may be used by analysis tools and has no effect on code
6949generation. A `void` argument means that the class can own any type.
6950
6951See [Pointer] for an example.)reST";
6952
6953static const char AttrDoc_Ownership[] = R"reST(:::{note}
6954In order for the Clang Static Analyzer to acknowledge these attributes, the
6955`Optimistic` config needs to be set to true for the checker
6956`unix.DynamicMemoryModeling`:
6957
6958`-Xclang -analyzer-config -Xclang unix.DynamicMemoryModeling:Optimistic=true`
6959:::
6960
6961These attributes are used by the Clang Static Analyzer's dynamic memory modeling
6962facilities to mark custom allocating/deallocating functions.
6963
6964All 3 attributes' first parameter of type string is the type of the allocation:
6965`malloc`, `new`, etc. to allow for catching {ref}`mismatched deallocation
6966<unix-MismatchedDeallocator>` bugs. The allocation type can be any string, e.g.
6967a function annotated with
6968returning a piece of memory of type `lasagna` but freed with a function
6969annotated to release `cheese` typed memory will result in mismatched
6970deallocation warning.
6971
6972The (currently) only allocation type having special meaning is `malloc` --
6973the Clang Static Analyzer makes sure that allocating functions annotated with
6974`malloc` are treated like they used the standard `malloc()`, and can be
6975safely deallocated with the standard `free()`.
6976
6977- Use `ownership_returns` to mark a function as an allocating function.
6978 It takes 1 or 2 arguments.
6979 The first argument is a user-provided identifier representing the "kind" of the allocation.
6980 This is basically what is enforced when checking the deallocation. This is mandatory.
6981 The second argument is optional.
6982 It represents the index of the parameter that represents the allocation size in bytes (counting from 1).
6983 The referenced parameter must have some integral type.
6984 This attribute may appear at most once per declaration.
6985 If this argument is not set, then tooling, such as the Clang Static Analyzer,
6986 won't be able to reason about the size of the allocation, thus check potential out-of-bounds accesses.
6987 However, such tooling could still warn if the wrong deallocation function
6988 was used for the `ownership_returns` attributed resource.
6989 If forward declarations have this attribute, those must have the same arguments.
6990- Use `ownership_takes` to mark a function as a deallocating function. Takes 2
6991 arguments: the allocation type, and the index of the parameter that is being
6992 deallocated (counting from 1).
6993- Use `ownership_holds` to mark that a function takes over the ownership of a
6994 piece of memory and will free it at some unspecified point in the future. Like
6995 `ownership_takes`, this takes 2 arguments: the allocation type, and the
6996 index of the parameter whose ownership will be taken over (counting from 1).
6997
6998The annotations `ownership_takes` and `ownership_holds` both prevent memory
6999leak reports (concerning the specified parameter); the difference between them
7000is that using taken memory is a use-after-free error, while using held memory
7001is assumed to be legitimate. However, releasing the held memory or passing it
7002to another holding call is reported by the analyzer as an "attempt to release
7003non-owned memory".
7004
7005Example:
7006
7007```c
7008// Denotes that my_malloc will return with a dynamically allocated piece of
7009// memory using malloc().
7010void __attribute((ownership_returns(malloc))) *my_malloc(size_t sz);
7011
7012// 'sz' (parameter 1) is the allocation size.
7013void __attribute((ownership_returns(malloc, 1))) *my_sized_malloc(size_t sz);
7014
7015// Denotes that my_free will deallocate its argument using free().
7016void __attribute((ownership_takes(malloc, 1))) my_free(void *);
7017
7018// Denotes that my_hold will take over the ownership of its argument that was
7019// allocated via malloc().
7020void __attribute((ownership_holds(malloc, 1))) my_hold(void *);
7021```
7022
7023Further reading about dynamic memory modeling in the Clang Static Analyzer is
7024found in these checker docs:
7025{ref}`unix.Malloc <unix-Malloc>`, {ref}`unix.MallocSizeof <unix-MallocSizeof>`,
7026{ref}`unix.MismatchedDeallocator <unix-MismatchedDeallocator>`,
7027{ref}`cplusplus.NewDelete <cplusplus-NewDelete>`,
7028{ref}`cplusplus.NewDeleteLeaks <cplusplus-NewDeleteLeaks>`,
7029{ref}`optin.taint.TaintedAlloc <optin-taint-TaintedAlloc>`.
7030Mind that many more checkers are affected by dynamic memory modeling changes to
7031some extent.
7032
7033Further reading for other annotations:
7034{doc}`Static Analyzer source annotations <analyzer/user-docs/Annotations>`.)reST";
7035
7036static const char AttrDoc_Packed[] = R"reST(No documentation.)reST";
7037
7038static const char AttrDoc_ParamTypestate[] = R"reST(This attribute specifies expectations about function parameters. Calls to an
7039function with annotated parameters will issue a warning if the corresponding
7040argument isn't in the expected state. The attribute is also used to set the
7041initial state of the parameter when analyzing the function's body.)reST";
7042
7043static const char AttrDoc_Pascal[] = R"reST(No documentation.)reST";
7044
7045static const char AttrDoc_PassObjectSize[] = R"reST(:::{Note}
7046The mangling of functions with parameters that are annotated with
7047`pass_object_size` is subject to change. You can get around this by
7048using `__asm__("foo")` to explicitly name your functions, thus preserving
7049your ABI; also, non-overloadable C functions with `pass_object_size` are
7050not mangled.
7051:::
7052
7053The `pass_object_size(Type)` attribute can be placed on function parameters to
7054instruct clang to call `__builtin_object_size(param, Type)` at each callsite
7055of said function, and implicitly pass the result of this call in as an invisible
7056argument of type `size_t` directly after the parameter annotated with
7057`pass_object_size`. Clang will also replace any calls to
7058`__builtin_object_size(param, Type)` in the function by said implicit
7059parameter.
7060
7061Example usage:
7062
7063```c
7064int bzero1(char *const p __attribute__((pass_object_size(0))))
7065 __attribute__((noinline)) {
7066 int i = 0;
7067 for (/**/; i < (int)__builtin_object_size(p, 0); ++i) {
7068 p[i] = 0;
7069 }
7070 return i;
7071}
7072
7073int main() {
7074 char chars[100];
7075 int n = bzero1(&chars[0]);
7076 assert(n == sizeof(chars));
7077 return 0;
7078}
7079```
7080
7081If successfully evaluating `__builtin_object_size(param, Type)` at the
7082callsite is not possible, then the "failed" value is passed in. So, using the
7083definition of `bzero1` from above, the following code would exit cleanly:
7084
7085```c
7086int main2(int argc, char *argv[]) {
7087 int n = bzero1(argv);
7088 assert(n == -1);
7089 return 0;
7090}
7091```
7092
7093`pass_object_size` plays a part in overload resolution. If two overload
7094candidates are otherwise equally good, then the overload with one or more
7095parameters with `pass_object_size` is preferred. This implies that the choice
7096between two identical overloads both with `pass_object_size` on one or more
7097parameters will always be ambiguous; for this reason, having two such overloads
7098is illegal. For example:
7099
7100```c++
7101#define PS(N) __attribute__((pass_object_size(N)))
7102// OK
7103void Foo(char *a, char *b); // Overload A
7104// OK -- overload A has no parameters with pass_object_size.
7105void Foo(char *a PS(0), char *b PS(0)); // Overload B
7106// Error -- Same signature (sans pass_object_size) as overload B, and both
7107// overloads have one or more parameters with the pass_object_size attribute.
7108void Foo(void *a PS(0), void *b);
7109
7110// OK
7111void Bar(void *a PS(0)); // Overload C
7112// OK
7113void Bar(char *c PS(1)); // Overload D
7114
7115void main() {
7116 char known[10], *unknown;
7117 Foo(unknown, unknown); // Calls overload B
7118 Foo(known, unknown); // Calls overload B
7119 Foo(unknown, known); // Calls overload B
7120 Foo(known, known); // Calls overload B
7121
7122 Bar(known); // Calls overload D
7123 Bar(unknown); // Calls overload D
7124}
7125```
7126
7127Currently, `pass_object_size` is a bit restricted in terms of its usage:
7128
7129- Only one use of `pass_object_size` is allowed per parameter.
7130- It is an error to take the address of a function with `pass_object_size` on
7131 any of its parameters. If you wish to do this, you can create an overload
7132 without `pass_object_size` on any parameters.
7133- It is an error to apply the `pass_object_size` attribute to parameters that
7134 are not pointers. Additionally, any parameter that `pass_object_size` is
7135 applied to must be marked `const` at its function's definition.
7136
7137Clang also supports the `pass_dynamic_object_size` attribute, which behaves
7138identically to `pass_object_size`, but evaluates a call to
7139`__builtin_dynamic_object_size` at the callee instead of
7140`__builtin_object_size`. `__builtin_dynamic_object_size` provides some extra
7141runtime checks when the object size can't be determined at compile-time. You can
7142read more about `__builtin_dynamic_object_size` in
7143{ref}`Evaluating Object Size <langext-evaluating-object-size>`.)reST";
7144
7145static const char AttrDoc_PatchableFunctionEntry[] = R"reST(`__attribute__((patchable_function_entry(N,M,Section)))` is used to generate M
7146NOPs before the function entry and N-M NOPs after the function entry, with a record of
7147the entry stored in section `Section`. This attribute takes precedence over the
7148command line option `-fpatchable-function-entry=N,M,Section`. `M` defaults to 0
7149if omitted. `Section` defaults to the `-fpatchable-function-entry` section name if
7150set, or to `__patchable_function_entries` otherwise.
7151
7152This attribute is only supported on
7153aarch64/aarch64-be/loongarch32/loongarch64/riscv32/riscv64/i386/x86-64/ppc/ppc64/ppc64le/s390x targets.
7154For ppc/ppc64 targets, AIX is still not supported.)reST";
7155
7156static const char AttrDoc_Pcs[] = R"reST(On ARM targets, this attribute can be used to select calling conventions
7157similar to `stdcall` on x86. Valid parameter values are "aapcs" and
7158"aapcs-vfp".)reST";
7159
7160static const char AttrDoc_Personality[] = R"reST(`__attribute__((personality(<routine>)))` is used to specify a personality
7161routine that is different from the language that is being used to implement the
7162function. This is a targeted, low-level feature aimed at language runtime
7163implementors who write runtime support code in C/C++ but need that code to
7164participate in a foreign language's exception-handling or unwinding model.
7165
7166A personality routine is a language-specific callback attached to each stack
7167frame that the unwinder invokes to determine whether that frame handles a given
7168exception and what cleanup actions to perform. It effectively colors the
7169language-agnostic unwinding mechanism with language-specific semantics, enabling
7170different languages to coexist on the same call stack while each interpreting
7171exceptions according to their own rules.)reST";
7172
7173static const char AttrDoc_Pointer[] = R"reST(:::{Note}
7174This attribute is experimental and its effect on analysis is subject to change in
7175a future version of clang.
7176:::
7177
7178The attribute `[[gsl::Pointer(T)]]` applies to structs and classes that behave
7179like pointers to an object of type `T`:
7180
7181```
7182class [[gsl::Pointer(int)]] IntPointer {
7183private:
7184 int *valuePointer;
7185public:
7186 IntPointer(const IntOwner&);
7187 int *getInt() { return valuePointer; }
7188};
7189```
7190
7191The argument `T` is optional and is ignored.
7192This attribute may be used by analysis tools and has no effect on code
7193generation. A `void` argument means that the pointer can point to any type.
7194
7195Example:
7196When constructing an instance of a class annotated like this (a Pointer) from
7197an instance of a class annotated with `[[gsl::Owner]]` (an Owner),
7198then the analysis will consider the Pointer to point inside the Owner.
7199When the Owner's lifetime ends, it will consider the Pointer to be dangling.
7200
7201```c++
7202int f() {
7203 IntPointer P(IntOwner{}); // P "points into" a temporary IntOwner object
7204 P.getInt(); // P is dangling
7205}
7206```
7207
7208**Transparent Member Functions**
7209
7210The analysis automatically tracks certain member functions of `[[gsl::Pointer]]` types
7211that provide transparent access to the pointed-to object. These include:
7212
7213- Dereference operators: `operator*`, `operator->`
7214- Data access methods: `data()`, `c_str()`, `get()`
7215- Iterator operations: `begin()`, `end()`, `rbegin()`, `rend()`, `cbegin()`, `cend()`, `crbegin()`, `crend()`, `operator+`, `operator-`, `operator++`, `operator--`
7216
7217When these methods return pointers, view types, or references, the analysis treats them as
7218transparently borrowing from the same object that the pointer itself borrows from,
7219enabling detection of use-after-free through these access patterns:
7220
7221```c++
7222// For example, .data() here returns a borrow to 's' instead of 'v'.
7223const char* f() {
7224 std::string s = "hello";
7225 std::string_view v = s; // warning: address of stack memory returned
7226 return v.data(); // note: returned here
7227}
7228
7229const MyObj& g(MyObj obj) {
7230 View v = obj; // warning: address of stack memory returned
7231 return *v; // note: returned here
7232}
7233```
7234
7235This tracking also applies to range-based for loops, where the `begin()` and `end()`
7236iterators are used to access elements:
7237
7238```c++
7239std::string_view f(std::vector<std::string> vec) {
7240 for (const std::string& s : vec) { // warning: address of stack memory returned
7241 return s; // note: returned here
7242 }
7243}
7244```
7245
7246**Container Template Specialization**
7247
7248If a template class is annotated with `[[gsl::Owner]]`, and the first
7249instantiated template argument is a pointer type (raw pointer, or `[[gsl::Pointer]]`),
7250the analysis will consider the instantiated class as a container of the pointer.
7251When constructing such an object from a GSL owner object, the analysis will
7252assume that the container holds a pointer to the owner object. Consequently,
7253when the owner object is destroyed, the pointer will be considered dangling.
7254
7255```c++
7256int f() {
7257 std::vector<std::string_view> v = {std::string()}; // v holds a dangling pointer.
7258 std::optional<std::string_view> o = std::string(); // o holds a dangling pointer.
7259}
7260```)reST";
7261
7262static const char AttrDoc_PointerAuth[] = R"reST(The `__ptrauth` qualifier allows the programmer to directly control
7263how pointers are signed when they are stored in a particular variable.
7264This can be used to strengthen the default protections of pointer
7265authentication and make it more difficult for an attacker to escalate
7266an ability to alter memory into full control of a process.
7267
7268```c
7269#include <ptrauth.h>
7270
7271typedef void (*my_callback)(const void*);
7272my_callback __ptrauth(ptrauth_key_process_dependent_code, 1, 0xe27a) callback;
7273```
7274
7275The first argument to `__ptrauth` is the name of the signing key.
7276Valid key names for the target are defined in `<ptrauth.h>`.
7277
7278The second argument to `__ptrauth` is a flag (0 or 1) specifying whether
7279the object should use address discrimination.
7280
7281The third argument to `__ptrauth` is a 16-bit non-negative integer which
7282allows additional discrimination between objects.)reST";
7283
7284static const char AttrDoc_PointerFieldProtection[] = R"reST(No documentation.)reST";
7285
7286static const char AttrDoc_PragmaClangBSSSection[] = R"reST()reST";
7287
7288static const char AttrDoc_PragmaClangDataSection[] = R"reST()reST";
7289
7290static const char AttrDoc_PragmaClangRelroSection[] = R"reST()reST";
7291
7292static const char AttrDoc_PragmaClangRodataSection[] = R"reST()reST";
7293
7294static const char AttrDoc_PragmaClangTextSection[] = R"reST()reST";
7295
7296static const char AttrDoc_PreferredName[] = R"reST(The `preferred_name` attribute can be applied to a class template, and
7297specifies a preferred way of naming a specialization of the template. The
7298preferred name will be used whenever the corresponding template specialization
7299would otherwise be printed in a diagnostic or similar context.
7300
7301The preferred name must be a typedef or type alias declaration that refers to a
7302specialization of the class template (not including any type qualifiers). In
7303general this requires the template to be declared at least twice. For example:
7304
7305```c++
7306template<typename T> struct basic_string;
7307using string = basic_string<char>;
7308using wstring = basic_string<wchar_t>;
7309template<typename T> struct [[clang::preferred_name(string),
7310 clang::preferred_name(wstring)]] basic_string {
7311 // ...
7312};
7313```
7314
7315Note that the `preferred_name` attribute will be ignored when the compiler
7316writes a C++20 Module interface now. This is due to a compiler issue
7317(<https://github.com/llvm/llvm-project/issues/56490>) that blocks users to modularize
7318declarations with `preferred_name`. This is intended to be fixed in the future.)reST";
7319
7320static const char AttrDoc_PreferredType[] = R"reST(This attribute allows adjusting the type of a bit-field in debug information.
7321This can be helpful when a bit-field is intended to store an enumeration value,
7322but has to be specified as having the enumeration's underlying type in order to
7323facilitate compiler optimizations or bit-field packing behavior. Normally, the
7324underlying type is what is emitted in debug information, which can make it hard
7325for debuggers to know to map a bit-field's value back to a particular enumeration.
7326
7327```c++
7328enum Colors { Red, Green, Blue };
7329
7330struct S {
7331 [[clang::preferred_type(Colors)]] unsigned ColorVal : 2;
7332 [[clang::preferred_type(bool)]] unsigned UseAlternateColorSpace : 1;
7333} s = { Green, false };
7334```
7335
7336Without the attribute, a debugger is likely to display the value `1` for `ColorVal`
7337and `0` for `UseAlternateColorSpace`. With the attribute, the debugger may now
7338display `Green` and `false` instead.
7339
7340This can be used to map a bit-field to an arbitrary type that isn't integral
7341or an enumeration type. For example:
7342
7343```c++
7344struct A {
7345 short a1;
7346 short a2;
7347};
7348
7349struct B {
7350 [[clang::preferred_type(A)]] unsigned b1 : 32 = 0x000F'000C;
7351};
7352```
7353
7354will associate the type `A` with the `b1` bit-field and is intended to display
7355something like this in the debugger:
7356
7357```text
7358Process 2755547 stopped
7359* thread #1, name = 'test-preferred-', stop reason = step in
7360 frame #0: 0x0000555555555148 test-preferred-type`main at test.cxx:13:14
7361 10 int main()
7362 11 {
7363 12 B b;
7364-> 13 return b.b1;
7365 14 }
7366(lldb) v -T
7367(B) b = {
7368 (A:32) b1 = {
7369 (short) a1 = 12
7370 (short) a2 = 15
7371 }
7372}
7373```
7374
7375Note that debuggers may not be able to handle more complex mappings, and so
7376this usage is debugger-dependent.)reST";
7377
7378static const char AttrDoc_PreserveAll[] = R"reST(On X86-64 and AArch64 targets, this attribute changes the calling convention of
7379a function. The `preserve_all` calling convention attempts to make the code
7380in the caller even less intrusive than the `preserve_most` calling convention.
7381This calling convention also behaves identical to the `C` calling convention
7382on how arguments and return values are passed, but it uses a different set of
7383caller/callee-saved registers. This removes the burden of saving and
7384recovering a large register set before and after the call in the caller. If
7385the arguments are passed in callee-saved registers, then they will be
7386preserved by the callee across the call. This doesn't apply for values
7387returned in callee-saved registers.
7388
7389- On X86-64 the callee preserves all general purpose registers, except for
7390 R11. R11 can be used as a scratch register. Furthermore it also preserves
7391 all floating-point registers (XMMs/YMMs).
7392- On AArch64 the callee preserve all general purpose registers, except X0-X8 and
7393 X16-X18. Furthermore it also preserves lower 128 bits of V8-V31 SIMD - floating
7394 point registers.
7395
7396The idea behind this convention is to support calls to runtime functions
7397that don't need to call out to any other functions.
7398
7399This calling convention, like the `preserve_most` calling convention, will be
7400used by a future version of the Objective-C runtime and should be considered
7401experimental at this time.)reST";
7402
7403static const char AttrDoc_PreserveMost[] = R"reST(On X86-64 and AArch64 targets, this attribute changes the calling convention of
7404a function. The `preserve_most` calling convention attempts to make the code
7405in the caller as unintrusive as possible. This convention behaves identically
7406to the `C` calling convention on how arguments and return values are passed,
7407but it uses a different set of caller/callee-saved registers. This alleviates
7408the burden of saving and recovering a large register set before and after the
7409call in the caller. If the arguments are passed in callee-saved registers,
7410then they will be preserved by the callee across the call. This doesn't
7411apply for values returned in callee-saved registers.
7412
7413- On X86-64 the callee preserves all general purpose registers, except for
7414 R11. R11 can be used as a scratch register. Floating-point registers
7415 (XMMs/YMMs) are not preserved and need to be saved by the caller.
7416- On AArch64 the callee preserve all general purpose registers, except X0-X8 and
7417 X16-X18.
7418
7419The idea behind this convention is to support calls to runtime functions
7420that have a hot path and a cold path. The hot path is usually a small piece
7421of code that doesn't use many registers. The cold path might need to call out to
7422another function and therefore only needs to preserve the caller-saved
7423registers, which haven't already been saved by the caller. The
7424`preserve_most` calling convention is very similar to the `cold` calling
7425convention in terms of caller/callee-saved registers, but they are used for
7426different types of function calls. `coldcc` is for function calls that are
7427rarely executed, whereas `preserve_most` function calls are intended to be
7428on the hot path and definitely executed a lot. Furthermore `preserve_most`
7429doesn't prevent the inliner from inlining the function call.
7430
7431This calling convention will be used by a future version of the Objective-C
7432runtime and should therefore still be considered experimental at this time.
7433Although this convention was created to optimize certain runtime calls to
7434the Objective-C runtime, it is not limited to this runtime and might be used
7435by other runtimes in the future too. The current implementation only
7436supports X86-64 and AArch64, but the intention is to support more architectures
7437in the future.)reST";
7438
7439static const char AttrDoc_PreserveNone[] = R"reST(On X86-64 and AArch64 targets, this attribute changes the calling convention of a function.
7440The `preserve_none` calling convention tries to preserve as few general
7441registers as possible. So all general registers are caller saved registers. It
7442also uses more general registers to pass arguments. This attribute doesn't
7443impact floating-point registers. `preserve_none`'s ABI is still unstable, and
7444may be changed in the future.
7445
7446- On X86-64, only RSP and RBP are preserved by the callee.
7447 Registers R12, R13, R14, R15, RDI, RSI, RDX, RCX, R8, R9, R11, and RAX now can
7448 be used to pass function arguments. Floating-point registers (XMMs/YMMs) still
7449 follow the C calling convention.
7450- On AArch64, only LR and FP are preserved by the callee.
7451 Registers X20-X28, X0-X7, and X9-X14 are used to pass function arguments.
7452 X8, X16-X19, SIMD and floating-point registers follow the AAPCS calling
7453 convention. X15 is not available for argument passing on Windows, but is
7454 used to pass arguments on other platforms.)reST";
7455
7456static const char AttrDoc_PtGuardedBy[] = R"reST(No documentation.)reST";
7457
7458static const char AttrDoc_PtGuardedVar[] = R"reST(No documentation.)reST";
7459
7460static const char AttrDoc_Ptr32[] = R"reST(The `__ptr32` qualifier represents a native pointer on a 32-bit system. On a
746164-bit system, a pointer with `__ptr32` is extended to a 64-bit pointer. The
7462`__sptr` and `__uptr` qualifiers can be used to specify whether the pointer
7463is sign extended or zero extended. This qualifier is enabled under
7464`-fms-extensions`.)reST";
7465
7466static const char AttrDoc_Ptr64[] = R"reST(The `__ptr64` qualifier represents a native pointer on a 64-bit system. On a
746732-bit system, a `__ptr64` pointer is truncated to a 32-bit pointer. This
7468qualifier is enabled under `-fms-extensions`.)reST";
7469
7470static const char AttrDoc_Pure[] = R"reST(No documentation.)reST";
7471
7472static const char AttrDoc_RISCVInterrupt[] = R"reST(Clang supports the GNU style `__attribute__((interrupt))` attribute on RISCV
7473targets. This attribute may be attached to a function definition and instructs
7474the backend to generate appropriate function entry/exit code so that it can be
7475used directly as an interrupt service routine.
7476
7477Permissible values for this parameter are `machine`, `supervisor`,
7478`rnmi`, `qci-nest`, `qci-nonest`, `SiFive-CLIC-preemptible`, and
7479`SiFive-CLIC-stack-swap`. If there is no parameter, then it defaults to
7480`machine`.
7481
7482The `rnmi` value is used for resumable non-maskable interrupts. It requires the
7483standard Smrnmi extension.
7484
7485The `qci-nest` and `qci-nonest` values require Qualcomm's Xqciint extension
7486and are used for Machine-mode Interrupts and Machine-mode Non-maskable
7487interrupts. These use the following instructions from Xqciint to save and
7488restore interrupt state to the stack -- the `qci-nest` value will use
7489`qc.c.mienter.nest` and the `qci-nonest` value will use `qc.c.mienter` to
7490begin the interrupt handler. Both of these will use `qc.c.mileaveret` to
7491restore the state and return to the previous context.
7492
7493The `SiFive-CLIC-preemptible` and `SiFive-CLIC-stack-swap` values are used
7494for machine-mode interrupts. For `SiFive-CLIC-preemptible` interrupts, the
7495values of `mcause` and `mepc` are saved onto the stack, and interrupts are
7496re-enabled. For `SiFive-CLIC-stack-swap` interrupts, the stack pointer is
7497swapped with `mscratch` before its first use and after its last use.
7498
7499The SiFive CLIC values may be combined with each other and with the `machine`
7500attribute value. Any other combination of different values is not allowed.
7501
7502Repeated interrupt attribute on the same declaration will cause a warning
7503to be emitted. In case of repeated declarations, the last one prevails.
7504
7505Refer to:
7506<https://gcc.gnu.org/onlinedocs/gcc/RISC-V-Function-Attributes.html>
7507<https://riscv.org/specifications/privileged-isa/>
7508The RISC-V Instruction Set Manual Volume II: Privileged Architecture
7509Version 1.10.
7510<https://github.com/quic/riscv-unified-db/releases/tag/Xqci-0.13.0>
7511<https://sifive.cdn.prismic.io/sifive/d1984d2b-c9b9-4c91-8de0-d68a5e64fa0f_sifive-interrupt-cookbook-v1p2.pdf>)reST";
7512
7513static const char AttrDoc_RISCVVLSCC[] = R"reST(The `riscv_vls_cc` attribute can be applied to a function. Functions
7514declared with this attribute will utilize the standard fixed-length vector
7515calling convention variant instead of the default calling convention defined by
7516the ABI. This variant aims to pass fixed-length vectors via vector registers,
7517if possible, rather than through general-purpose registers.)reST";
7518
7519static const char AttrDoc_RISCVVectorCC[] = R"reST(The `riscv_vector_cc` attribute can be applied to a function. It preserves 15
7520registers namely, v1-v7 and v24-v31 as callee-saved. Callers thus don't need
7521to save these registers before function calls, and callees only need to save
7522them if they use them.)reST";
7523
7524static const char AttrDoc_RandomizeLayout[] = R"reST(The attribute `randomize_layout`, when attached to a C structure, selects it
7525for structure layout field randomization; a compile-time hardening technique. A
7526"seed" value, is specified via the `-frandomize-layout-seed=` command line flag.
7527For example:
7528
7529```bash
7530SEED=`od -A n -t x8 -N 32 /dev/urandom | tr -d ' \n'`
7531make ... CFLAGS="-frandomize-layout-seed=$SEED" ...
7532```
7533
7534You can also supply the seed in a file with `-frandomize-layout-seed-file=`.
7535For example:
7536
7537```bash
7538od -A n -t x8 -N 32 /dev/urandom | tr -d ' \n' > /tmp/seed_file.txt
7539make ... CFLAGS="-frandomize-layout-seed-file=/tmp/seed_file.txt" ...
7540```
7541
7542The randomization is deterministic based for a given seed, so the entire
7543program should be compiled with the same seed, but keep the seed safe
7544otherwise.
7545
7546The attribute `no_randomize_layout`, when attached to a C structure,
7547instructs the compiler that this structure should not have its field layout
7548randomized.)reST";
7549
7550static const char AttrDoc_ReadOnlyPlacement[] = R"reST(This attribute is attached to a structure, class or union declaration.
7551
7552: When attached to a record declaration/definition, it checks if all instances
7553 of this type can be placed in the read-only data segment of the program. If it
7554 finds an instance that can not be placed in a read-only segment, the compiler
7555 emits a warning at the source location where the type was used.
7556
7557 Examples:
7558 \* `struct __attribute__((enforce_read_only_placement)) Foo;`
7559 \* `struct __attribute__((enforce_read_only_placement)) Bar { ... };`
7560
7561 Both `Foo` and `Bar` types have the `enforce_read_only_placement` attribute.
7562
7563 The goal of introducing this attribute is to assist developers with writing secure
7564 code. A `const`-qualified global is generally placed in the read-only section
7565 of the memory that has additional run time protection from malicious writes. By
7566 attaching this attribute to a declaration, the developer can express the intent
7567 to place all instances of the annotated type in the read-only program memory.
7568
7569 Note 1: The attribute doesn't guarantee that the object will be placed in the
7570 read-only data segment as it does not instruct the compiler to ensure such
7571 a placement. It emits a warning if something in the code can be proven to prevent
7572 an instance from being placed in the read-only data segment.
7573
7574 Note 2: Currently, clang only checks if all global declarations of a given type 'T'
7575 are `const`-qualified. The following conditions would also prevent the data to be
7576 put into read only segment, but the corresponding warnings are not yet implemented.
7577
7578 1. An instance of type `T` is allocated on the heap/stack.
7579 2. Type `T` defines/inherits a mutable field.
7580 3. Type `T` defines/inherits non-constexpr constructor(s) for initialization.
7581 4. A field of type `T` is defined by type `Q`, which does not bear the
7582 `enforce_read_only_placement` attribute.
7583 5. A type `Q` inherits from type `T` and it does not have the
7584 `enforce_read_only_placement` attribute.)reST";
7585
7586static const char AttrDoc_ReentrantCapability[] = R"reST(No documentation.)reST";
7587
7588static const char AttrDoc_RegCall[] = R"reST(On x86 targets, this attribute changes the calling convention to
7589[\_\_regcall][__regcall] convention. This convention aims to pass as many arguments
7590as possible in registers. It also tries to utilize registers for the
7591return value whenever it is possible.
7592
7593[__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";
7594
7595static const char AttrDoc_Reinitializes[] = R"reST(The `reinitializes` attribute can be applied to a non-static, non-const C++
7596member function to indicate that this member function reinitializes the entire
7597object to a known state, independent of the previous state of the object.
7598
7599This attribute can be interpreted by static analyzers that warn about uses of an
7600object that has been left in an indeterminate state by a move operation. If a
7601member function marked with the `reinitializes` attribute is called on a
7602moved-from object, the analyzer can conclude that the object is no longer in an
7603indeterminate state.
7604
7605A typical example where this attribute would be used is on functions that clear
7606a container class:
7607
7608```c++
7609template <class T>
7610class Container {
7611public:
7612 ...
7613 [[clang::reinitializes]] void Clear();
7614 ...
7615};
7616```)reST";
7617
7618static const char AttrDoc_ReleaseCapability[] = R"reST(Marks a function as releasing a capability.)reST";
7619
7620static const char AttrDoc_ReleaseHandle[] = R"reST(If a function parameter is annotated with `release_handle(tag)` it is assumed to
7621close the handle. It is also assumed to require an open handle to work with. The
7622attribute requires a string literal argument to identify the handle being released.
7623
7624```c++
7625zx_status_t zx_handle_close(zx_handle_t handle [[clang::release_handle("tag")]]);
7626```)reST";
7627
7628static const char AttrDoc_ReqdWorkGroupSize[] = R"reST(No documentation.)reST";
7629
7630static const char AttrDoc_RequiresCapability[] = R"reST(No documentation.)reST";
7631
7632static const char AttrDoc_Restrict[] = R"reST(The `malloc` attribute has two forms with different functionality. The first
7633is when it is used without arguments, where it marks that a function acts like
7634a system memory allocation function, returning a pointer to allocated storage
7635that does not alias storage from any other object accessible to the caller.
7636
7637The second form is when `malloc` takes one or two arguments. The first
7638argument names a function that should be associated with this function as its
7639deallocation function. When this form is used, it enables the compiler to
7640diagnose when the incorrect deallocation function is used with this variable.
7641However the associated warning, spelled `-Wmismatched-dealloc` in GCC, is not
7642yet implemented in clang.)reST";
7643
7644static const char AttrDoc_Retain[] = R"reST(This attribute, when attached to a function or variable definition, prevents
7645section garbage collection in the linker. It does not prevent other discard
7646mechanisms, such as archive member selection, and COMDAT group resolution.
7647
7648If the compiler does not emit the definition, e.g. because it was not used in
7649the translation unit or the compiler was able to eliminate all of the uses,
7650this attribute has no effect. This attribute is typically combined with the
7651`used` attribute to force the definition to be emitted and preserved into the
7652final linked image.
7653
7654This attribute is only necessary on ELF targets; other targets prevent section
7655garbage collection by the linker when using the `used` attribute alone.
7656Using the attributes together should result in consistent behavior across
7657targets.
7658
7659This attribute requires the linker to support the `SHF_GNU_RETAIN` extension.
7660This support is available in GNU `ld` and `gold` as of binutils 2.36, as
7661well as in `ld.lld` 13.)reST";
7662
7663static const char AttrDoc_ReturnTypestate[] = R"reST(The `return_typestate` attribute can be applied to functions or parameters.
7664When applied to a function the attribute specifies the state of the returned
7665value. The function's body is checked to ensure that it always returns a value
7666in the specified state. On the caller side, values returned by the annotated
7667function are initialized to the given state.
7668
7669When applied to a function parameter it modifies the state of an argument after
7670a call to the function returns. The function's body is checked to ensure that
7671the parameter is in the expected state before returning.)reST";
7672
7673static const char AttrDoc_ReturnsNonNull[] = R"reST(The `returns_nonnull` attribute indicates that a particular function (or
7674Objective-C method) always returns a non-null pointer. For example, a
7675particular system `malloc` might be defined to terminate a process when
7676memory is not available rather than returning a null pointer:
7677
7678```c
7679extern void * malloc (size_t size) __attribute__((returns_nonnull));
7680```
7681
7682The `returns_nonnull` attribute implies that returning a null pointer is
7683undefined behavior, which the optimizer may take advantage of. The `_Nonnull`
7684type qualifier indicates that a pointer cannot be null in a more general manner
7685(because it is part of the type system) and does not imply undefined behavior,
7686making it more widely applicable)reST";
7687
7688static const char AttrDoc_ReturnsTwice[] = R"reST(No documentation.)reST";
7689
7690static const char AttrDoc_RootSignature[] = R"reST(The `RootSignature` attribute applies to HLSL entry functions to define what
7691types of resources are bound to the graphics pipeline.
7692
7693For details about the use and specification of Root Signatures please see here:
7694<https://learn.microsoft.com/en-us/windows/win32/direct3d12/root-signatures>)reST";
7695
7696static const char AttrDoc_SPtr[] = R"reST(The `__sptr` qualifier specifies that a 32-bit pointer should be sign
7697extended when converted to a 64-bit pointer.)reST";
7698
7699static const char AttrDoc_SYCLConstantAddressSpace[] = R"reST(.. note::
7700
7701 These attributes are intended for use in the implementation of SYCL run-time
7702 libraries and should not be used in any other context.
7703 Programmers writing code intended to conform to the SYCL specification should
7704 use the address space facilities specified in the following sections of the
7705 SYCL 2020 specification.
7706
7707 * `4.7.2, "Buffers" <SYCL-2020-4.7.2_>`_
7708 * `4.7.6, "Accessors" <SYCL-2020-4.7.6_>`_.
7709 * `4.7.7, "Address space classes" <SYCL-2020-4.7.7_>`_.
7710 * `F.7, "sycl_khr_static_addrspace_cast" <SYCL-2020-F.7_>`_.
7711 * `F.8, "sycl_khr_dynamic_addrspace_cast" <SYCL-2020-F.8_>`_.
7712
7713The SYCL address space attributes listed below correspond to the five address
7714spaces described by
7715`SYCL 2020 section 3.8.2, "SYCL device memory model" <SYCL-2020-3.8.2_>`_ and
7716`SYCL 2020 section 4.7.7, "Address space classes" <SYCL-2020-4.7.7_>`_.
7717
7718.. list-table::
7719 :header-rows: 1
7720
7721 * - Address space attribute
7722 - SYCL address space
7723 - Description
7724 * - ``[[clang::sycl_global]]``
7725 - global
7726 - A memory region accessible by all work-items executing on a device.
7727 * - ``[[clang::sycl_local]]``
7728 - local
7729 - A memory region accessible by all work-items of a single work-group.
7730 * - ``[[clang::sycl_private]]``
7731 - private
7732 - A memory region that is private to a single work-item.
7733 * - ``[[clang::sycl_generic]]``
7734 - generic
7735 - A virtual memory region from which the global, local, and private memory
7736 regions may all be accessed.
7737 * - ``[[clang::sycl_constant]]``
7738 - constant
7739 - (*deprecated*) A memory region that holds constant data for an executing
7740 kernel.
7741
7742The SYCL address space attributes are type attributes that may be applied to
7743non-function non-reference types to specify an address space qualified type.
7744
7745A type with a SYCL address space qualifier is a distinct type from the
7746otherwise unattributed type. For example, ``int *`` and ``int [[clang::sycl_global]]*``
7747designate distinct pointer types which participate in overload resolution and
7748template specialization.
7749
7750The top-level type of a variable declaration cannot have a SYCL address space
7751qualifier. For example:
7752
7753.. code-block:: c++
7754
7755 int [[clang::sycl_global]] gv; // error: the top-level type has an address space qualifier.
7756 int [[clang::sycl_global]] *pgi; // ok; the address space qualifier is on the pointee type.
7757
7758Conversions between SYCL address space attributed types are permitted as
7759follows.
7760
7761* Types attributed with the global, local, or private address space attributes
7762 are implicitly convertible to matching types with the generic address space
7763 attribute.
7764
7765The mapping of SYCL address spaces to physical address spaces is target
7766dependent.
7767
7768For OpenCL device targets, the SYCL address space attributes are aligned with
7769the `OpenCL address space attributes <attr-opencl-addrspace_>`_ such that, e.g.,
7770``int [[clang::sycl_global]]*`` and ``int [[clang::opencl_global]]*`` specify
7771distinct types both of which map to the same underlying address space.
7772Corresponding SYCL and OpenCL address space attributed types are implicitly
7773convertible; other conversions are permitted as described above; e.g.,
7774``int [[clang::sycl_global]]*`` is implicitly convertible to
7775``int [[clang::opencl_generic]]*``.
7776
7777.. _attr-opencl-addrspace:
7778 https://clang.llvm.org/docs/AttributeReference.html#opencl-address-spaces
7779.. _SYCL-2020-3.8.2:
7780 https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#_sycl_device_memory_model
7781.. _SYCL-2020-4.7.2:
7782 https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#subsec:buffers
7783.. _SYCL-2020-4.7.6:
7784 https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#subsec:accessors
7785.. _SYCL-2020-4.7.7:
7786 https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#_address_space_classes
7787.. _SYCL-2020-F.7:
7788 https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#sec:khr-static-addrspace-cast
7789.. _SYCL-2020-F.8:
7790 https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#sec:khr-dynamic-addrspace-cast)reST";
7791
7792static const char AttrDoc_SYCLExternal[] = R"reST(The `sycl_external` attribute indicates that a function defined in another
7793translation unit may be called by a device function defined in the current
7794translation unit or, if defined in the current translation unit, the function
7795may be called by device functions defined in other translation units.
7796The attribute is intended for use in the implementation of the `SYCL_EXTERNAL`
7797macro as specified in section 5.10.1, "SYCL functions and member functions
7798linkage", of the SYCL 2020 specification.
7799
7800The attribute only appertains to functions and only those that meet the
7801following requirements:
7802
7803- Has external linkage
7804- Is not explicitly defined as deleted (the function may be an explicitly
7805 defaulted function that is defined as deleted)
7806
7807The attribute shall be present on the first declaration of a function and
7808may optionally be present on subsequent declarations.
7809
7810When compiling for a SYCL device target that does not support the generic
7811address space, the function shall not specify a raw pointer or reference type
7812as the return type or as a parameter type.
7813See section 5.10, "SYCL offline linking", of the SYCL 2020 specification.
7814The following examples demonstrate the use of this attribute:
7815
7816```c++
7817[[clang::sycl_external]] void Foo(); // Ok.
7818
7819[[clang::sycl_external]] void Bar() { /* ... */ } // Ok.
7820
7821[[clang::sycl_external]] extern void Baz(); // Ok.
7822
7823[[clang::sycl_external]] static void Quux() { /* ... */ } // error: Quux() has internal linkage.
7824```)reST";
7825
7826static const char AttrDoc_SYCLGenericAddressSpace[] = R"reST(.. note::
7827
7828 These attributes are intended for use in the implementation of SYCL run-time
7829 libraries and should not be used in any other context.
7830 Programmers writing code intended to conform to the SYCL specification should
7831 use the address space facilities specified in the following sections of the
7832 SYCL 2020 specification.
7833
7834 * `4.7.2, "Buffers" <SYCL-2020-4.7.2_>`_
7835 * `4.7.6, "Accessors" <SYCL-2020-4.7.6_>`_.
7836 * `4.7.7, "Address space classes" <SYCL-2020-4.7.7_>`_.
7837 * `F.7, "sycl_khr_static_addrspace_cast" <SYCL-2020-F.7_>`_.
7838 * `F.8, "sycl_khr_dynamic_addrspace_cast" <SYCL-2020-F.8_>`_.
7839
7840The SYCL address space attributes listed below correspond to the five address
7841spaces described by
7842`SYCL 2020 section 3.8.2, "SYCL device memory model" <SYCL-2020-3.8.2_>`_ and
7843`SYCL 2020 section 4.7.7, "Address space classes" <SYCL-2020-4.7.7_>`_.
7844
7845.. list-table::
7846 :header-rows: 1
7847
7848 * - Address space attribute
7849 - SYCL address space
7850 - Description
7851 * - ``[[clang::sycl_global]]``
7852 - global
7853 - A memory region accessible by all work-items executing on a device.
7854 * - ``[[clang::sycl_local]]``
7855 - local
7856 - A memory region accessible by all work-items of a single work-group.
7857 * - ``[[clang::sycl_private]]``
7858 - private
7859 - A memory region that is private to a single work-item.
7860 * - ``[[clang::sycl_generic]]``
7861 - generic
7862 - A virtual memory region from which the global, local, and private memory
7863 regions may all be accessed.
7864 * - ``[[clang::sycl_constant]]``
7865 - constant
7866 - (*deprecated*) A memory region that holds constant data for an executing
7867 kernel.
7868
7869The SYCL address space attributes are type attributes that may be applied to
7870non-function non-reference types to specify an address space qualified type.
7871
7872A type with a SYCL address space qualifier is a distinct type from the
7873otherwise unattributed type. For example, ``int *`` and ``int [[clang::sycl_global]]*``
7874designate distinct pointer types which participate in overload resolution and
7875template specialization.
7876
7877The top-level type of a variable declaration cannot have a SYCL address space
7878qualifier. For example:
7879
7880.. code-block:: c++
7881
7882 int [[clang::sycl_global]] gv; // error: the top-level type has an address space qualifier.
7883 int [[clang::sycl_global]] *pgi; // ok; the address space qualifier is on the pointee type.
7884
7885Conversions between SYCL address space attributed types are permitted as
7886follows.
7887
7888* Types attributed with the global, local, or private address space attributes
7889 are implicitly convertible to matching types with the generic address space
7890 attribute.
7891
7892The mapping of SYCL address spaces to physical address spaces is target
7893dependent.
7894
7895For OpenCL device targets, the SYCL address space attributes are aligned with
7896the `OpenCL address space attributes <attr-opencl-addrspace_>`_ such that, e.g.,
7897``int [[clang::sycl_global]]*`` and ``int [[clang::opencl_global]]*`` specify
7898distinct types both of which map to the same underlying address space.
7899Corresponding SYCL and OpenCL address space attributed types are implicitly
7900convertible; other conversions are permitted as described above; e.g.,
7901``int [[clang::sycl_global]]*`` is implicitly convertible to
7902``int [[clang::opencl_generic]]*``.
7903
7904.. _attr-opencl-addrspace:
7905 https://clang.llvm.org/docs/AttributeReference.html#opencl-address-spaces
7906.. _SYCL-2020-3.8.2:
7907 https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#_sycl_device_memory_model
7908.. _SYCL-2020-4.7.2:
7909 https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#subsec:buffers
7910.. _SYCL-2020-4.7.6:
7911 https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#subsec:accessors
7912.. _SYCL-2020-4.7.7:
7913 https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#_address_space_classes
7914.. _SYCL-2020-F.7:
7915 https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#sec:khr-static-addrspace-cast
7916.. _SYCL-2020-F.8:
7917 https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#sec:khr-dynamic-addrspace-cast)reST";
7918
7919static const char AttrDoc_SYCLGlobalAddressSpace[] = R"reST(.. note::
7920
7921 These attributes are intended for use in the implementation of SYCL run-time
7922 libraries and should not be used in any other context.
7923 Programmers writing code intended to conform to the SYCL specification should
7924 use the address space facilities specified in the following sections of the
7925 SYCL 2020 specification.
7926
7927 * `4.7.2, "Buffers" <SYCL-2020-4.7.2_>`_
7928 * `4.7.6, "Accessors" <SYCL-2020-4.7.6_>`_.
7929 * `4.7.7, "Address space classes" <SYCL-2020-4.7.7_>`_.
7930 * `F.7, "sycl_khr_static_addrspace_cast" <SYCL-2020-F.7_>`_.
7931 * `F.8, "sycl_khr_dynamic_addrspace_cast" <SYCL-2020-F.8_>`_.
7932
7933The SYCL address space attributes listed below correspond to the five address
7934spaces described by
7935`SYCL 2020 section 3.8.2, "SYCL device memory model" <SYCL-2020-3.8.2_>`_ and
7936`SYCL 2020 section 4.7.7, "Address space classes" <SYCL-2020-4.7.7_>`_.
7937
7938.. list-table::
7939 :header-rows: 1
7940
7941 * - Address space attribute
7942 - SYCL address space
7943 - Description
7944 * - ``[[clang::sycl_global]]``
7945 - global
7946 - A memory region accessible by all work-items executing on a device.
7947 * - ``[[clang::sycl_local]]``
7948 - local
7949 - A memory region accessible by all work-items of a single work-group.
7950 * - ``[[clang::sycl_private]]``
7951 - private
7952 - A memory region that is private to a single work-item.
7953 * - ``[[clang::sycl_generic]]``
7954 - generic
7955 - A virtual memory region from which the global, local, and private memory
7956 regions may all be accessed.
7957 * - ``[[clang::sycl_constant]]``
7958 - constant
7959 - (*deprecated*) A memory region that holds constant data for an executing
7960 kernel.
7961
7962The SYCL address space attributes are type attributes that may be applied to
7963non-function non-reference types to specify an address space qualified type.
7964
7965A type with a SYCL address space qualifier is a distinct type from the
7966otherwise unattributed type. For example, ``int *`` and ``int [[clang::sycl_global]]*``
7967designate distinct pointer types which participate in overload resolution and
7968template specialization.
7969
7970The top-level type of a variable declaration cannot have a SYCL address space
7971qualifier. For example:
7972
7973.. code-block:: c++
7974
7975 int [[clang::sycl_global]] gv; // error: the top-level type has an address space qualifier.
7976 int [[clang::sycl_global]] *pgi; // ok; the address space qualifier is on the pointee type.
7977
7978Conversions between SYCL address space attributed types are permitted as
7979follows.
7980
7981* Types attributed with the global, local, or private address space attributes
7982 are implicitly convertible to matching types with the generic address space
7983 attribute.
7984
7985The mapping of SYCL address spaces to physical address spaces is target
7986dependent.
7987
7988For OpenCL device targets, the SYCL address space attributes are aligned with
7989the `OpenCL address space attributes <attr-opencl-addrspace_>`_ such that, e.g.,
7990``int [[clang::sycl_global]]*`` and ``int [[clang::opencl_global]]*`` specify
7991distinct types both of which map to the same underlying address space.
7992Corresponding SYCL and OpenCL address space attributed types are implicitly
7993convertible; other conversions are permitted as described above; e.g.,
7994``int [[clang::sycl_global]]*`` is implicitly convertible to
7995``int [[clang::opencl_generic]]*``.
7996
7997.. _attr-opencl-addrspace:
7998 https://clang.llvm.org/docs/AttributeReference.html#opencl-address-spaces
7999.. _SYCL-2020-3.8.2:
8000 https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#_sycl_device_memory_model
8001.. _SYCL-2020-4.7.2:
8002 https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#subsec:buffers
8003.. _SYCL-2020-4.7.6:
8004 https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#subsec:accessors
8005.. _SYCL-2020-4.7.7:
8006 https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#_address_space_classes
8007.. _SYCL-2020-F.7:
8008 https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#sec:khr-static-addrspace-cast
8009.. _SYCL-2020-F.8:
8010 https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#sec:khr-dynamic-addrspace-cast)reST";
8011
8012static const char AttrDoc_SYCLKernel[] = R"reST(The `sycl_kernel` attribute specifies that a function template will be used
8013to outline device code and to generate an OpenCL kernel.
8014Here is a code example of the SYCL program, which demonstrates the compiler's
8015outlining job:
8016
8017```c++
8018int foo(int x) { return ++x; }
8019
8020using namespace cl::sycl;
8021queue Q;
8022buffer<int, 1> a(range<1>{1024});
8023Q.submit([&](handler& cgh) {
8024 auto A = a.get_access<access::mode::write>(cgh);
8025 cgh.parallel_for<init_a>(range<1>{1024}, [=](id<1> index) {
8026 A[index] = index[0] + foo(42);
8027 });
8028}
8029```
8030
8031A C++ function object passed to the `parallel_for` is called a "SYCL kernel".
8032A SYCL kernel defines the entry point to the "device part" of the code. The
8033compiler will emit all symbols accessible from a "kernel". In this code
8034example, the compiler will emit "foo" function. More details about the
8035compilation of functions for the device part can be found in the SYCL 1.2.1
8036specification Section 6.4.
8037To show to the compiler entry point to the "device part" of the code, the SYCL
8038runtime can use the `sycl_kernel` attribute in the following way:
8039
8040```c++
8041namespace cl {
8042namespace sycl {
8043class handler {
8044 template <typename KernelName, typename KernelType/*, ...*/>
8045 __attribute__((sycl_kernel)) void sycl_kernel_function(KernelType KernelFuncObj) {
8046 // ...
8047 KernelFuncObj();
8048 }
8049
8050 template <typename KernelName, typename KernelType, int Dims>
8051 void parallel_for(range<Dims> NumWorkItems, KernelType KernelFunc) {
8052#ifdef __SYCL_DEVICE_ONLY__
8053 sycl_kernel_function<KernelName, KernelType, Dims>(KernelFunc);
8054#else
8055 // Host implementation
8056#endif
8057 }
8058};
8059} // namespace sycl
8060} // namespace cl
8061```
8062
8063The compiler will also generate an OpenCL kernel using the function marked with
8064the `sycl_kernel` attribute.
8065Here is the list of SYCL device compiler expectations with regard to the
8066function marked with the `sycl_kernel` attribute:
8067
8068- The function must be a template with at least two type template parameters.
8069 The compiler generates an OpenCL kernel and uses the first template parameter
8070 as a unique name for the generated OpenCL kernel. The host application uses
8071 this unique name to invoke the OpenCL kernel generated for the SYCL kernel
8072 specialized by this name and second template parameter `KernelType` (which
8073 might be an unnamed function object type).
8074- The function must have at least one parameter. The first parameter is
8075 required to be a function object type (named or unnamed i.e. lambda). The
8076 compiler uses function object type fields to generate OpenCL kernel
8077 parameters.
8078- The function must return void. The compiler reuses the body of marked functions to
8079 generate the OpenCL kernel body, and the OpenCL kernel must return `void`.
8080
8081The SYCL kernel in the previous code sample meets these expectations.)reST";
8082
8083static const char AttrDoc_SYCLKernelEntryPoint[] = R"reST(The `sycl_kernel_entry_point` attribute facilitates the launch of a SYCL
8084kernel and the generation of an offload kernel entry point, sometimes called
8085a SYCL kernel caller function, suitable for invoking a SYCL kernel on an
8086offload device. The attribute is intended for use in the implementation of
8087SYCL kernel invocation functions like the `single_task` and `parallel_for`
8088member functions of the `sycl::handler` class specified in section 4.9.4,
8089"Command group `handler` class", of the SYCL 2020 specification.
8090
8091The attribute requires a single type argument that meets the requirements for
8092a SYCL kernel name as described in section 5.2, "Naming of kernels", of the
8093SYCL 2020 specification. A unique kernel name type is required for each
8094function declared with the attribute. The attribute may not first appear on a
8095declaration that follows a definition of the function.
8096
8097The attribute only appertains to functions and only those that meet the
8098following requirements.
8099
8100- Has a non-deduced `void` return type.
8101- Is not a constructor or destructor.
8102- Is not a non-static member function with an explicit object parameter.
8103- Is not a C variadic function.
8104- Is not a coroutine.
8105- Is not defined as deleted or as defaulted.
8106- Is not defined with a function try block.
8107- Is not declared with the `constexpr` or `consteval` specifiers.
8108- Is not declared with the `[[noreturn]]` attribute.
8109
8110Use in the implementation of a SYCL kernel invocation function might look as
8111follows.
8112
8113```c++
8114namespace sycl {
8115class handler {
8116 template<typename KernelName, typename... Ts>
8117 void sycl_kernel_launch(const char* kernelSymbol, Ts&&... kernelArgs) {
8118 // This code will run on the host and is responsible for calling functions
8119 // appropriate for the desired offload backend (OpenCL, CUDA, HIP,
8120 // Level Zero, etc...) to copy the kernel arguments denoted by kernelArgs
8121 // to a device and to schedule an invocation of the offload kernel entry
8122 // point denoted by kernelSymbol with the copied arguments.
8123 }
8124
8125 template<typename KernelName, typename KernelType>
8126 [[ clang::sycl_kernel_entry_point(KernelName) ]]
8127 void kernel_entry_point(KernelType kernelFunc) {
8128 // This code will run on the device. The call to kernelFunc() invokes
8129 // the SYCL kernel.
8130 kernelFunc();
8131 }
8132
8133public:
8134 template<typename KernelName, typename KernelType>
8135 void single_task(const KernelType& kernelFunc) {
8136 // This code will run on the host. kernel_entry_point() is called to
8137 // trigger generation of an offload kernel entry point and to schedule
8138 // an invocation of it on a device with kernelFunc (a SYCL kernel object)
8139 // passed as a kernel argument. This call will result in an implicit call
8140 // to sycl_kernel_launch() with the symbol name for the generated offload
8141 // kernel entry point passed as the first function argument followed by
8142 // kernelFunc.
8143 kernel_entry_point<KernelName>(kernelFunc);
8144 }
8145};
8146} // namespace sycl
8147```
8148
8149A SYCL kernel object is a callable object of class type that is constructed on
8150a host, often via a lambda expression, and then passed to a SYCL kernel
8151invocation function to be executed on an offload device. The `kernelFunc`
8152parameters in the example code above correspond to SYCL kernel objects.
8153
8154A SYCL kernel object type is required to satisfy the device copyability
8155requirements specified in section 3.13.1, "Device copyable", of the SYCL 2020
8156specification. Additionally, any data members of the kernel object type are
8157required to satisfy section 4.12.4, "Rules for parameter passing to kernels".
8158For most types, these rules require that the type is trivially copyable.
8159However, the SYCL specification mandates that certain special SYCL types, such
8160as `sycl::accessor` and `sycl::stream`, be device copyable even if they are
8161not trivially copyable. These types require special handling because they cannot
8162necessarily be copied to device memory as if by `memcpy()`.
8163
8164The SYCL kernel object and its data members constitute the parameters of an
8165offload kernel. An offload kernel consists of an offload entry point function
8166and the set of all functions and variables that are directly or indirectly used
8167by the entry point function.
8168
8169A SYCL kernel invocation function is responsible for performing the following
8170tasks (likely with the help of an offload backend like OpenCL):
8171
81721. Identifying the offload kernel entry point to be used for the SYCL kernel.
81732. Validating that the SYCL kernel object type and its data members meet the
8174 SYCL device copyability and kernel parameter requirements noted above.
81753. Copying the SYCL kernel object and any other kernel arguments to device
8176 memory including any special handling required for SYCL special types.
81774. Initiating execution of the offload kernel entry point.
8178
8179The offload kernel entry point for a SYCL kernel performs the following tasks:
8180
81811. Calling the `operator()` member function of the SYCL kernel object.
8182
8183The `sycl_kernel_entry_point` attribute facilitates or automates these tasks
8184by providing generation of an offload kernel entry point with a unique symbol
8185name, type checking of kernel argument requirements, and initiation of kernel
8186execution via synthesized calls to a `sycl_kernel_launch` template.
8187
8188A function declared with the `sycl_kernel_entry_point` attribute specifies
8189the parameters and body of an offload entry point function. Consider the
8190following call to the `single_task()` SYCL kernel invocation function assuming
8191an implementation similar to the one shown above.
8192
8193```c++
8194struct S { int i; };
8195void f(sycl::handler &handler, sycl::stream &sout, S s) {
8196 handler.single_task<struct KN>([=] {
8197 sout << "The value of s.i is " << s.i << "\n";
8198 });
8199}
8200```
8201
8202The SYCL kernel object is the result of the lambda expression. The call to
8203`kernel_entry_point()` via the call to `single_task()` triggers the
8204generation of an offload kernel entry point function that looks approximately
8205as follows.
8206
8207```c++
8208void sycl-kernel-caller-for-KN(kernel-type kernelFunc) {
8209 kernelFunc();
8210}
8211```
8212
8213There are a few items worthy of note:
8214
82151. `sycl-kernel-caller-for-KN` is an exposition only name; the actual name
8216 generated for an entry point is an implementation detail and subject to
8217 change. However, the name will incorporate the SYCL kernel name, `KN`,
8218 that was passed as the `KernelName` template parameter to
8219 `single_task()` and eventually provided as the argument to the
8220 `sycl_kernel_entry_point` attribute in order to ensure that a unique
8221 name is generated for each entry point. There is a one-to-one correspondence
8222 between SYCL kernel names and offload kernel entry points.
82232. The SYCL kernel is a lambda closure type and therefore has no name;
8224 `kernel-type` is substituted above and corresponds to the `KernelType`
8225 template parameter deduced in the call to `single_task()`.
82263. The parameter and the call to `kernelFunc()` in the function body
8227 correspond to the definition of `kernel_entry_point()` as called by
8228 `single_task()`.
82294. The parameter is type checked for conformance with the SYCL device
8230 copyability and kernel parameter requirements.
8231
8232Within `single_task()`, the call to `kernel_entry_point()` is effectively
8233replaced with a synthesized call to a ''sycl_kernel_launch\`\` template that
8234looks approximately as follows.
8235
8236```c++
8237sycl_kernel_launch<KN>("sycl-kernel-caller-for-KN", kernelFunc);
8238```
8239
8240There are a few items worthy of note:
8241
82421. Lookup for the `sycl_kernel_launch` template is performed as if from the
8243 body of the (possibly instantiated) definition of `kernel_entry_point()`.
8244 If name lookup or overload resolution fails, the program is ill-formed.
8245 If the selected overload is a non-static member function, then `this` is
8246 passed as the implicit object parameter.
82472. Function arguments passed to `sycl_kernel_launch()` are passed
8248 as if by `std::move(x)`.
82493. The `sycl_kernel_launch` template is expected to be provided by the SYCL
8250 library implementation. It is responsible for copying the kernel arguments
8251 to device memory and for scheduling execution of the generated offload
8252 kernel entry point identified by the symbol name passed as the first
8253 function argument. `sycl-kernel-caller-for-KN` is substituted above for
8254 the actual symbol name that would be generated for the offload kernel entry
8255 point.
8256
8257It is not necessary for a function declared with the `sycl_kernel_entry_point`
8258attribute to be called for the offload kernel entry point to be emitted. For
8259inline functions and function templates, any ODR-use will suffice. For other
8260functions, an ODR-use is not required; the offload kernel entry point will be
8261emitted if the function is defined. In any case, a call to the function is
8262required for the synthesized call to `sycl_kernel_launch()` to occur.
8263
8264A function declared with the `sycl_kernel_entry_point` attribute may include
8265an exception specification. If a non-throwing exception specification is
8266present, an exception propagating from the implicit call to the
8267`sycl_kernel_launch` template will result in a call to `std::terminate()`.
8268Otherwise, such an exception will propagate normally.
8269
8270Functions declared with the `sycl_kernel_entry_point` attribute are not
8271limited to the simple example shown above. They may have additional template
8272parameters, declare additional function parameters, and have complex control
8273flow in the function body. The function must abide by the language feature
8274restrictions described in section 5.4, "Language restrictions for device
8275functions" in the SYCL 2020 specification. If the function is a non-static
8276member function, `this` shall not be used in a potentially evaluated
8277expression.)reST";
8278
8279static const char AttrDoc_SYCLLocalAddressSpace[] = R"reST(.. note::
8280
8281 These attributes are intended for use in the implementation of SYCL run-time
8282 libraries and should not be used in any other context.
8283 Programmers writing code intended to conform to the SYCL specification should
8284 use the address space facilities specified in the following sections of the
8285 SYCL 2020 specification.
8286
8287 * `4.7.2, "Buffers" <SYCL-2020-4.7.2_>`_
8288 * `4.7.6, "Accessors" <SYCL-2020-4.7.6_>`_.
8289 * `4.7.7, "Address space classes" <SYCL-2020-4.7.7_>`_.
8290 * `F.7, "sycl_khr_static_addrspace_cast" <SYCL-2020-F.7_>`_.
8291 * `F.8, "sycl_khr_dynamic_addrspace_cast" <SYCL-2020-F.8_>`_.
8292
8293The SYCL address space attributes listed below correspond to the five address
8294spaces described by
8295`SYCL 2020 section 3.8.2, "SYCL device memory model" <SYCL-2020-3.8.2_>`_ and
8296`SYCL 2020 section 4.7.7, "Address space classes" <SYCL-2020-4.7.7_>`_.
8297
8298.. list-table::
8299 :header-rows: 1
8300
8301 * - Address space attribute
8302 - SYCL address space
8303 - Description
8304 * - ``[[clang::sycl_global]]``
8305 - global
8306 - A memory region accessible by all work-items executing on a device.
8307 * - ``[[clang::sycl_local]]``
8308 - local
8309 - A memory region accessible by all work-items of a single work-group.
8310 * - ``[[clang::sycl_private]]``
8311 - private
8312 - A memory region that is private to a single work-item.
8313 * - ``[[clang::sycl_generic]]``
8314 - generic
8315 - A virtual memory region from which the global, local, and private memory
8316 regions may all be accessed.
8317 * - ``[[clang::sycl_constant]]``
8318 - constant
8319 - (*deprecated*) A memory region that holds constant data for an executing
8320 kernel.
8321
8322The SYCL address space attributes are type attributes that may be applied to
8323non-function non-reference types to specify an address space qualified type.
8324
8325A type with a SYCL address space qualifier is a distinct type from the
8326otherwise unattributed type. For example, ``int *`` and ``int [[clang::sycl_global]]*``
8327designate distinct pointer types which participate in overload resolution and
8328template specialization.
8329
8330The top-level type of a variable declaration cannot have a SYCL address space
8331qualifier. For example:
8332
8333.. code-block:: c++
8334
8335 int [[clang::sycl_global]] gv; // error: the top-level type has an address space qualifier.
8336 int [[clang::sycl_global]] *pgi; // ok; the address space qualifier is on the pointee type.
8337
8338Conversions between SYCL address space attributed types are permitted as
8339follows.
8340
8341* Types attributed with the global, local, or private address space attributes
8342 are implicitly convertible to matching types with the generic address space
8343 attribute.
8344
8345The mapping of SYCL address spaces to physical address spaces is target
8346dependent.
8347
8348For OpenCL device targets, the SYCL address space attributes are aligned with
8349the `OpenCL address space attributes <attr-opencl-addrspace_>`_ such that, e.g.,
8350``int [[clang::sycl_global]]*`` and ``int [[clang::opencl_global]]*`` specify
8351distinct types both of which map to the same underlying address space.
8352Corresponding SYCL and OpenCL address space attributed types are implicitly
8353convertible; other conversions are permitted as described above; e.g.,
8354``int [[clang::sycl_global]]*`` is implicitly convertible to
8355``int [[clang::opencl_generic]]*``.
8356
8357.. _attr-opencl-addrspace:
8358 https://clang.llvm.org/docs/AttributeReference.html#opencl-address-spaces
8359.. _SYCL-2020-3.8.2:
8360 https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#_sycl_device_memory_model
8361.. _SYCL-2020-4.7.2:
8362 https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#subsec:buffers
8363.. _SYCL-2020-4.7.6:
8364 https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#subsec:accessors
8365.. _SYCL-2020-4.7.7:
8366 https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#_address_space_classes
8367.. _SYCL-2020-F.7:
8368 https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#sec:khr-static-addrspace-cast
8369.. _SYCL-2020-F.8:
8370 https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#sec:khr-dynamic-addrspace-cast)reST";
8371
8372static const char AttrDoc_SYCLPrivateAddressSpace[] = R"reST(.. note::
8373
8374 These attributes are intended for use in the implementation of SYCL run-time
8375 libraries and should not be used in any other context.
8376 Programmers writing code intended to conform to the SYCL specification should
8377 use the address space facilities specified in the following sections of the
8378 SYCL 2020 specification.
8379
8380 * `4.7.2, "Buffers" <SYCL-2020-4.7.2_>`_
8381 * `4.7.6, "Accessors" <SYCL-2020-4.7.6_>`_.
8382 * `4.7.7, "Address space classes" <SYCL-2020-4.7.7_>`_.
8383 * `F.7, "sycl_khr_static_addrspace_cast" <SYCL-2020-F.7_>`_.
8384 * `F.8, "sycl_khr_dynamic_addrspace_cast" <SYCL-2020-F.8_>`_.
8385
8386The SYCL address space attributes listed below correspond to the five address
8387spaces described by
8388`SYCL 2020 section 3.8.2, "SYCL device memory model" <SYCL-2020-3.8.2_>`_ and
8389`SYCL 2020 section 4.7.7, "Address space classes" <SYCL-2020-4.7.7_>`_.
8390
8391.. list-table::
8392 :header-rows: 1
8393
8394 * - Address space attribute
8395 - SYCL address space
8396 - Description
8397 * - ``[[clang::sycl_global]]``
8398 - global
8399 - A memory region accessible by all work-items executing on a device.
8400 * - ``[[clang::sycl_local]]``
8401 - local
8402 - A memory region accessible by all work-items of a single work-group.
8403 * - ``[[clang::sycl_private]]``
8404 - private
8405 - A memory region that is private to a single work-item.
8406 * - ``[[clang::sycl_generic]]``
8407 - generic
8408 - A virtual memory region from which the global, local, and private memory
8409 regions may all be accessed.
8410 * - ``[[clang::sycl_constant]]``
8411 - constant
8412 - (*deprecated*) A memory region that holds constant data for an executing
8413 kernel.
8414
8415The SYCL address space attributes are type attributes that may be applied to
8416non-function non-reference types to specify an address space qualified type.
8417
8418A type with a SYCL address space qualifier is a distinct type from the
8419otherwise unattributed type. For example, ``int *`` and ``int [[clang::sycl_global]]*``
8420designate distinct pointer types which participate in overload resolution and
8421template specialization.
8422
8423The top-level type of a variable declaration cannot have a SYCL address space
8424qualifier. For example:
8425
8426.. code-block:: c++
8427
8428 int [[clang::sycl_global]] gv; // error: the top-level type has an address space qualifier.
8429 int [[clang::sycl_global]] *pgi; // ok; the address space qualifier is on the pointee type.
8430
8431Conversions between SYCL address space attributed types are permitted as
8432follows.
8433
8434* Types attributed with the global, local, or private address space attributes
8435 are implicitly convertible to matching types with the generic address space
8436 attribute.
8437
8438The mapping of SYCL address spaces to physical address spaces is target
8439dependent.
8440
8441For OpenCL device targets, the SYCL address space attributes are aligned with
8442the `OpenCL address space attributes <attr-opencl-addrspace_>`_ such that, e.g.,
8443``int [[clang::sycl_global]]*`` and ``int [[clang::opencl_global]]*`` specify
8444distinct types both of which map to the same underlying address space.
8445Corresponding SYCL and OpenCL address space attributed types are implicitly
8446convertible; other conversions are permitted as described above; e.g.,
8447``int [[clang::sycl_global]]*`` is implicitly convertible to
8448``int [[clang::opencl_generic]]*``.
8449
8450.. _attr-opencl-addrspace:
8451 https://clang.llvm.org/docs/AttributeReference.html#opencl-address-spaces
8452.. _SYCL-2020-3.8.2:
8453 https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#_sycl_device_memory_model
8454.. _SYCL-2020-4.7.2:
8455 https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#subsec:buffers
8456.. _SYCL-2020-4.7.6:
8457 https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#subsec:accessors
8458.. _SYCL-2020-4.7.7:
8459 https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#_address_space_classes
8460.. _SYCL-2020-F.7:
8461 https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#sec:khr-static-addrspace-cast
8462.. _SYCL-2020-F.8:
8463 https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html#sec:khr-dynamic-addrspace-cast)reST";
8464
8465static const char AttrDoc_SYCLSpecialClass[] = R"reST(SYCL defines some special classes (accessor, sampler, and stream) which require
8466specific handling during the generation of the SPIR entry point.
8467The `__attribute__((sycl_special_class))` attribute is used in SYCL
8468headers to indicate that a class or a struct needs a specific handling when
8469it is passed from host to device.
8470Special classes will have a mandatory `__init` method and an optional
8471`__finalize` method (the `__finalize` method is used only with the
8472`stream` type). Kernel parameters types are extract from the `__init` method
8473parameters. The kernel function arguments list is derived from the
8474arguments of the `__init` method. The arguments of the `__init` method are
8475copied into the kernel function argument list and the `__init` and
8476`__finalize` methods are called at the beginning and the end of the kernel,
8477respectively.
8478The `__init` and `__finalize` methods must be defined inside the
8479special class.
8480Please note that this is an attribute that is used as an internal
8481implementation detail and not intended to be used by external users.
8482
8483The syntax of the attribute is as follows:
8484
8485```text
8486class __attribute__((sycl_special_class)) accessor {};
8487class [[clang::sycl_special_class]] accessor {};
8488```
8489
8490This is a code example that illustrates the use of the attribute:
8491
8492```c++
8493class __attribute__((sycl_special_class)) SpecialType {
8494 int F1;
8495 int F2;
8496 void __init(int f1) {
8497 F1 = f1;
8498 F2 = f1;
8499 }
8500 void __finalize() {}
8501public:
8502 SpecialType() = default;
8503 int getF2() const { return F2; }
8504};
8505
8506int main () {
8507 SpecialType T;
8508 cgh.single_task([=] {
8509 T.getF2();
8510 });
8511}
8512```
8513
8514This would trigger the following kernel entry point in the AST:
8515
8516```c++
8517void __sycl_kernel(int f1) {
8518 SpecialType T;
8519 T.__init(f1);
8520 ...
8521 T.__finalize()
8522}
8523```)reST";
8524
8525static const char AttrDoc_ScopedLockable[] = R"reST(No documentation.)reST";
8526
8527static const char AttrDoc_Section[] = R"reST(The `section` attribute allows you to specify a specific section a
8528global variable or function should be in after translation.)reST";
8529
8530static const char AttrDoc_SelectAny[] = R"reST(This attribute appertains to a global symbol, causing it to have a weak
8531definition (
8532[linkonce](https://llvm.org/docs/LangRef.html#linkage-types)
8533), allowing the linker to select any definition.
8534
8535For more information see
8536[gcc documentation](https://gcc.gnu.org/onlinedocs/gcc-7.2.0/gcc/Microsoft-Windows-Variable-Attributes.html)
8537or [msvc documentation](https://docs.microsoft.com/pl-pl/cpp/cpp/selectany).)reST";
8538
8539static const char AttrDoc_Sentinel[] = R"reST(The `sentinel` attribute can be applied to variadic functions and pointers to
8540variadic functions, to diagnose each function call that does not pass a
8541sentinel value (a null pointer constant) as the last argument to the function
8542call. The attribute accepts two optional arguments: the first argument is the
8543position of the expected sentinel value, starting from the last parameter. The
8544second argument describes whether the last fixed parameter is treated as a
8545valid sentinel value when set to '1'.
8546All arguments described above default to '0' when elided.
8547The attribute is also supported with blocks and in Objective-C.
8548
8549```c
8550void foo(const char*, ...) __attribute__((sentinel));
8551void bar(int, ...) __attribute__((sentinel(1)));
8552void baz(const char*, const char*, ...) __attribute__((sentinel(0, 1)));
8553
8554void example() {
8555 foo("Example", (void*)0);
8556 foo("Another", "example", NULL);
8557 foo("Missing", "sentinel"); // Not OK
8558
8559 bar(1, 2, NULL, 3); // OK: sentinel value at the 2nd to last position
8560 bar(1, 2, 3, nullptr, 4); // OK: `nullptr` is valid in C23
8561 bar(1, 2, 3, 4, NULL); // Not OK
8562
8563 baz("Test", "with", "multiple", "args", NULL);
8564 baz("One", NULL); // OK: last fixed parameter is a valid sentinel
8565
8566 void (*ptr) (int arg, ...) __attribute__ ((__sentinel__));
8567 ptr(1, 2, 3, NULL);
8568}
8569```
8570
8571```c++
8572struct Ty {
8573 int value;
8574
8575 template<typename T>
8576 auto&& foo(T&& val, ...) __attribute__((sentinel(1))) {
8577 return std::forward<T>(val);
8578 }
8579
8580 template<class Self>
8581 auto&& bar(this Self&& self, ...) __attribute__((sentinel(1))) {
8582 return std::forward<Self>(self).value;
8583 }
8584};
8585
8586void example2() {
8587 auto sty = Ty{};
8588 sty.foo(1, nullptr, 3);
8589 sty.bar(1, nullptr, 3);
8590
8591 auto lmbd = [](int a, ...) __attribute__((sentinel)) {};
8592 lmbd(1, 2, nullptr);
8593}
8594```)reST";
8595
8596static const char AttrDoc_SetTypestate[] = R"reST(Annotate methods that transition an object into a new state with
8597`__attribute__((set_typestate(new_state)))`. The new state must be
8598unconsumed, consumed, or unknown.)reST";
8599
8600static const char AttrDoc_SizedBy[] = R"reST(The `sized_by` attribute is applied to a pointer to indicate that the pointer
8601points to memory containing at least the number of *bytes* given by the
8602attribute's argument. It is closely related to `counted_by`; the difference is
8603that `counted_by` counts the number of *elements* of the pointee type, whereas
8604`sized_by` counts the number of *bytes*. This makes `sized_by` the natural
8605choice for `void *` and other byte buffers.
8606
8607This attribute is used by {doc}`-fbounds-safety <BoundsSafety>` to propagate
8608bounds information on API surfaces without any ABI changes. This attribute is
8609also used to improve the results of the array bound sanitizer and the
8610`__builtin_dynamic_object_size` builtin.
8611
8612The argument is an expression of integer type, following the same rules as the
8613argument of `counted_by`. Unlike `counted_by`, `sized_by` cannot be
8614applied to a C99 flexible array member; it applies to pointers only. For
8615example:
8616
8617```c
8618struct object {
8619 unsigned long size;
8620 void *data __attribute__((sized_by(size)));
8621};
8622```
8623
8624A pointer annotated with `sized_by` must have a size of zero when it is null.
8625This requirement is currently only enforced when compiling with
8626{doc}`-fbounds-safety <BoundsSafety>` (see {ref}`Current status of
8627-fbounds-safety support in upstream Clang <bounds-safety-current-upstream-status>`). Use
8628`sized_by_or_null` for a pointer that may be null while carrying a nonzero
8629size.
8630
8631#### Keeping pointer and size in sync
8632
8633The `sized_by` attribute establishes a relationship between the annotated
8634pointer and its size: the pointer must point to at least `size` bytes.
8635Assigning to only one of them can break this relationship.
8636Without {doc}`-fbounds-safety <BoundsSafety>`, it is the programmer's
8637responsibility to ensure the pointer and size remain in sync. With
8638`-fbounds-safety` it is automatically enforced. For example:
8639
8640```c
8641struct buffer {
8642 uint8_t *buf __attribute__((sized_by(size)));
8643 size_t size;
8644};
8645
8646void grow(struct buffer *b, size_t new_size) {
8647 // b->buf isn't updated. The underlying memory pointed to by b->buf might be
8648 // smaller than new_size which would contradict the sized_by attribute.
8649 // Compile error with -fbounds-safety but allowed without -fbounds-safety.
8650 b->size = new_size;
8651}
8652```
8653
8654Updating both together - so that `buf` points to `size` bytes - keeps
8655the attribute true. For example:
8656
8657```c
8658void grow(struct buffer *b, size_t new_size) {
8659 // Allowed by -fbounds-safety
8660 uint8_t *new_buf = malloc(new_size);
8661 // -fbounds-safety enforces that the `new_buf` points to at least `new_size`
8662 // bytes at runtime. Without -fbounds-safety nothing enforces this.
8663 b->buf = new_buf;
8664 b->size = new_size;
8665}
8666```
8667
8668#### Incomplete and variable-length pointees
8669
8670`sized_by` is typically applied to `void *` or a pointer to a byte-sized
8671type, but it may be used with any pointee type. Two situations call for this,
8672both of which rule out counting fixed-size elements:
8673
8674First, the pointee type may be incomplete, such as an opaque type. Its element
8675size is then unavailable, so `counted_by` cannot be used, whereas `sized_by`
8676bounds the memory in bytes and imposes no completeness requirement.
8677
8678Second, the buffer may hold variable-length elements, so there is no fixed
8679element size to count, even though the total byte size is well defined. For
8680example, a buffer might pack together several structures that each end in a
8681flexible array member of differing length:
8682
8683```c
8684struct var_len {
8685 int fam_size;
8686 char data[] __attribute__((counted_by(fam_size)));
8687};
8688
8689struct buffer_view {
8690 int byte_size;
8691 struct var_len *buf __attribute__((sized_by(byte_size)));
8692};
8693```
8694
8695Here `counted_by` cannot be applied to `buf` because its pointee is a
8696variable-length structure, but `sized_by` bounds the whole region in bytes;
8697the region is traversed by advancing a byte offset rather than by indexing
8698elements.)reST";
8699
8700static const char AttrDoc_SizedByOrNull[] = R"reST(The `sized_by_or_null` attribute is applied to a pointer to indicate that, if
8701the pointer is non-null, it points to memory containing at least the number of
8702*bytes* given by the attribute's argument. If the pointer is null, the value of
8703the argument is ignored and the pointer points to zero bytes.
8704
8705The `sized_by_or_null` attribute is identical to `sized_by` except in how
8706it treats null pointers. Whereas `sized_by` requires a null pointer to have a
8707size of zero, `sized_by_or_null` allows the pointer to be null regardless of
8708the value of the size. This supports the common idiom where a pointer is either
8709null or points to memory containing at least the given number of bytes.
8710
8711Currently only {doc}`-fbounds-safety <BoundsSafety>` makes use of the
8712distinction between `sized_by_or_null` and `sized_by` (see
8713{ref}`Current status of -fbounds-safety support in upstream Clang
8714<bounds-safety-current-upstream-status>`).)reST";
8715
8716static const char AttrDoc_SpeculativeLoadHardening[] = R"reST(This attribute can be applied to a function declaration in order to indicate
8717that [Speculative Load Hardening][slh]
8718should be enabled for the function body. This can also be applied to a method
8719in Objective C. This attribute will take precedence over the command line flag
8720in the case where {option}`-mno-speculative-load-hardening` is specified.
8721
8722[slh]: https://llvm.org/docs/SpeculativeLoadHardening.html
8723
8724Speculative Load Hardening is a best-effort mitigation against
8725information leak attacks that make use of control flow
8726miss-speculation - specifically miss-speculation of whether a branch
8727is taken or not. Typically vulnerabilities enabling such attacks are
8728classified as "Spectre variant #1". Notably, this does not attempt to
8729mitigate against miss-speculation of branch target, classified as
8730"Spectre variant #2" vulnerabilities.
8731
8732When inlining, the attribute is sticky. Inlining a function that
8733carries this attribute will cause the caller to gain the
8734attribute. This is intended to provide a maximally conservative model
8735where the code in a function annotated with this attribute will always
8736(even after inlining) end up hardened.)reST";
8737
8738static const char AttrDoc_StackProtectorIgnore[] = R"reST(The `stack_protector_ignore` attribute skips analysis of the given local
8739variable when determining if a function should use a stack protector.
8740
8741The `-fstack-protector` option uses a heuristic to only add stack protectors
8742to functions which contain variables or buffers over some size threshold. This
8743attribute overrides that heuristic for the attached variable, opting
8744them out. If this results in no variables or buffers remaining over the stack
8745protector threshold, then the function will no longer use a stack protector.)reST";
8746
8747static const char AttrDoc_StandaloneDebug[] = R"reST(The `standalone_debug` attribute causes debug info to be emitted for a record
8748type regardless of the debug info optimizations that are enabled with
8749-fno-standalone-debug. This attribute only has an effect when debug info
8750optimizations are enabled (e.g. with -fno-standalone-debug), and is C++-only.)reST";
8751
8752static const char AttrDoc_StdCall[] = R"reST(On 32-bit x86 targets, this attribute changes the calling convention of a
8753function to clear parameters off of the stack on return. This convention does
8754not support variadic calls or unprototyped functions in C, and has no effect on
8755x86_64 targets. This calling convention is used widely by the Windows API and
8756COM applications. See the documentation for [\_\_stdcall][__stdcall] on MSDN.
8757
8758[__stdcall]: http://msdn.microsoft.com/en-us/library/zxk0tw93.aspx)reST";
8759
8760static const char AttrDoc_StrictFP[] = R"reST()reST";
8761
8762static const char AttrDoc_StrictGuardStackCheck[] = R"reST(Clang supports the Microsoft style `__declspec((strict_gs_check))` attribute
8763which upgrades the stack protector check from `-fstack-protector` to
8764`-fstack-protector-strong`.
8765
8766For example, it upgrades the stack protector for the function `foo` to
8767`-fstack-protector-strong` but function `bar` will still be built with the
8768stack protector with the `-fstack-protector` option.
8769
8770```c
8771__declspec((strict_gs_check))
8772int foo(int x); // stack protection will be upgraded for foo.
8773
8774int bar(int y); // bar can be built with the standard stack protector checks.
8775```)reST";
8776
8777static const char AttrDoc_Suppress[] = R"reST(The `suppress` attribute suppresses unwanted warnings coming from static
8778analysis tools such as the Clang Static Analyzer. The tool will not report
8779any issues in source code annotated with the attribute.
8780
8781The attribute cannot be used to suppress traditional Clang warnings, because
8782many such warnings are emitted before the attribute is fully parsed.
8783Consider using `#pragma clang diagnostic` to control such diagnostics,
8784as described in
8785{ref}`Controlling Diagnostics via Pragmas <pragma-gcc-diagnostic>`.
8786
8787The `suppress` attribute can be placed on an individual statement in order to
8788suppress warnings about undesirable behavior occurring at that statement:
8789
8790```c++
8791int foo() {
8792 int *x = nullptr;
8793 ...
8794 [[clang::suppress]]
8795 return *x; // null pointer dereference warning suppressed here
8796}
8797```
8798
8799Putting the attribute on a compound statement suppresses all warnings in scope:
8800
8801```c++
8802int foo() {
8803 [[clang::suppress]] {
8804 int *x = nullptr;
8805 ...
8806 return *x; // warnings suppressed in the entire scope
8807 }
8808}
8809```
8810
8811The attribute can also be placed on entire declarations of functions, classes,
8812variables, member variables, and so on, to suppress warnings related
8813to the declarations themselves. When used this way, the attribute additionally
8814suppresses all warnings in the lexical scope of the declaration:
8815
8816```c++
8817class [[clang::suppress]] C {
8818 int foo() {
8819 int *x = nullptr;
8820 ...
8821 return *x; // warnings suppressed in the entire class scope
8822 }
8823
8824 int bar();
8825};
8826
8827int C::bar() {
8828 int *x = nullptr;
8829 ...
8830 return *x; // warning NOT suppressed! - not lexically nested in 'class C{}'
8831}
8832```
8833
8834Some static analysis warnings are accompanied by one or more notes, and the
8835line of code against which the warning is emitted isn't necessarily the best
8836for suppression purposes. In such cases the tools are allowed to implement
8837additional ways to suppress specific warnings based on the attribute attached
8838to a note location.
8839
8840For example, the Clang Static Analyzer suppresses memory leak warnings when
8841the suppression attribute is placed at the allocation site (highlited by
8842a "note: memory is allocated"), which may be different from the line of code
8843at which the program "loses track" of the pointer (where the warning
8844is ultimately emitted):
8845
8846```c
8847int bar1(bool coin_flip) {
8848 __attribute__((suppress))
8849 int *result = (int *)malloc(sizeof(int));
8850 if (coin_flip)
8851 return 1; // warning about this leak path is suppressed
8852
8853 return *result; // warning about this leak path is also suppressed
8854}
8855
8856int bar2(bool coin_flip) {
8857 int *result = (int *)malloc(sizeof(int));
8858 if (coin_flip)
8859 return 1; // leak warning on this path NOT suppressed
8860
8861 __attribute__((suppress))
8862 return *result; // leak warning is suppressed only on this path
8863}
8864```
8865
8866When written as `[[gsl::suppress]]`, this attribute suppresses specific
8867clang-tidy diagnostics for rules of the [C++ Core Guidelines][c++ core guidelines] in a portable
8868way. The attribute can be attached to declarations, statements, and at
8869namespace scope.
8870
8871```c++
8872[[gsl::suppress("Rh-public")]]
8873void f_() {
8874 int *p;
8875 [[gsl::suppress("type")]] {
8876 p = reinterpret_cast<int*>(7);
8877 }
8878}
8879namespace N {
8880 [[clang::suppress("type", "bounds")]];
8881 ...
8882}
8883```
8884
8885[c++ core guidelines]: https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#inforce-enforcement)reST";
8886
8887static const char AttrDoc_SwiftAsync[] = R"reST(The `swift_async` attribute specifies if and how a particular function or
8888Objective-C method is imported into a swift async method. For instance:
8889
8890```objc
8891@interface MyClass : NSObject
8892-(void)notActuallyAsync:(int)p1 withCompletionHandler:(void (^)())handler
8893 __attribute__((swift_async(none)));
8894
8895-(void)actuallyAsync:(int)p1 callThisAsync:(void (^)())fun
8896 __attribute__((swift_async(swift_private, 1)));
8897@end
8898```
8899
8900Here, `notActuallyAsync:withCompletionHandler` would have been imported as
8901`async` (because it's last parameter's selector piece is
8902`withCompletionHandler`) if not for the `swift_async(none)` attribute.
8903Conversely, `actuallyAsync:callThisAsync` wouldn't have been imported as
8904`async` if not for the `swift_async` attribute because it doesn't match the
8905naming convention.
8906
8907When using `swift_async` to enable importing, the first argument to the
8908attribute is either `swift_private` or `not_swift_private` to indicate
8909whether the function/method is private to the current framework, and the second
8910argument is the index of the completion handler parameter.)reST";
8911
8912static const char AttrDoc_SwiftAsyncCall[] = R"reST(The `swiftasynccall` attribute indicates that a function is
8913compatible with the low-level conventions of Swift async functions,
8914provided it declares the right formal arguments.
8915
8916In most respects, this is similar to the `swiftcall` attribute, except for
8917the following:
8918
8919- A parameter may be marked `swift_async_context`, `swift_context`
8920 or `swift_indirect_result` (with the same restrictions on parameter
8921 ordering as `swiftcall`) but the parameter attribute
8922 `swift_error_result` is not permitted.
8923- A `swiftasynccall` function must have return type `void`.
8924- Within a `swiftasynccall` function, a call to a `swiftasynccall`
8925 function that is the immediate operand of a `return` statement is
8926 guaranteed to be performed as a tail call. This syntax is allowed even
8927 in C as an extension (a call to a void-returning function cannot be a
8928 return operand in standard C). If something in the calling function would
8929 semantically be performed after a guaranteed tail call, such as the
8930 non-trivial destruction of a local variable or temporary,
8931 then the program is ill-formed.
8932
8933Query for this attribute with `__has_attribute(swiftasynccall)`. Query if
8934the target supports the calling convention with
8935`__has_extension(swiftasynccc)`.
8936
8937Since this attribute follows the Swift async calling convention, it is
8938considered ABI-unstable except on targets where the Swift project
8939has declared ABI stability. Users are responsible for ensuring that
8940calls and definitions of functions with this attribute are compiled
8941with compatible compilers. Note that different operating systems
8942on the same architecture may use different ABIs and therefore may
8943have different standards for ABI stability.)reST";
8944
8945static const char AttrDoc_SwiftAsyncContext[] = R"reST(The `swift_async_context` attribute marks a parameter of a `swiftasynccall`
8946function as having the special asynchronous context-parameter ABI treatment.
8947
8948If the function is not `swiftasynccall`, this attribute only generates
8949extended frame information.
8950
8951A context parameter must have pointer or reference type.)reST";
8952
8953static const char AttrDoc_SwiftAsyncError[] = R"reST(The `swift_async_error` attribute specifies how an error state will be
8954represented in a swift async method. It's a bit analogous to the `swift_error`
8955attribute for the generated async method. The `swift_async_error` attribute
8956can indicate a variety of different ways of representing an error.
8957
8958- `__attribute__((swift_async_error(zero_argument, N)))`, specifies that the
8959 async method is considered to have failed if the Nth argument to the
8960 completion handler is zero.
8961- `__attribute__((swift_async_error(nonzero_argument, N)))`, specifies that
8962 the async method is considered to have failed if the Nth argument to the
8963 completion handler is non-zero.
8964- `__attribute__((swift_async_error(nonnull_error)))`, specifies that the
8965 async method is considered to have failed if the `NSError *` argument to the
8966 completion handler is non-null.
8967- `__attribute__((swift_async_error(none)))`, specifies that the async method
8968 cannot fail.
8969
8970For instance:
8971
8972```objc
8973@interface MyClass : NSObject
8974-(void)asyncMethod:(void (^)(char, int, float))handler
8975 __attribute__((swift_async(swift_private, 1)))
8976 __attribute__((swift_async_error(zero_argument, 2)));
8977@end
8978```
8979
8980Here, the `swift_async` attribute specifies that `handler` is the completion
8981handler for this method, and the `swift_async_error` attribute specifies that
8982the `int` parameter is the one that represents the error.)reST";
8983
8984static const char AttrDoc_SwiftAsyncName[] = R"reST(The `swift_async_name` attribute provides the name of the `async` overload for
8985the given declaration in Swift. If this attribute is absent, the name is
8986transformed according to the algorithm built into the Swift compiler.
8987
8988The argument is a string literal that contains the Swift name of the function or
8989method. The name may be a compound Swift name. The function or method with such
8990an attribute must have more than zero parameters, as its last parameter is
8991assumed to be a callback that's eliminated in the Swift `async` name.
8992
8993```objc
8994@interface URL
8995+ (void) loadContentsFrom:(URL *)url callback:(void (^)(NSData *))data __attribute__((__swift_async_name__("URL.loadContentsFrom(_:)")))
8996@end
8997```)reST";
8998
8999static const char AttrDoc_SwiftAttr[] = R"reST(The `swift_attr` provides a Swift-specific annotation for the declaration
9000or type to which the attribute appertains to. It can be used on any declaration
9001or type in Clang. This kind of annotation is ignored by Clang as it doesn't have any
9002semantic meaning in languages supported by Clang. The Swift compiler can
9003interpret these annotations according to its own rules when importing C or
9004Objective-C declarations.)reST";
9005
9006static const char AttrDoc_SwiftBridge[] = R"reST(The `swift_bridge` attribute indicates that the declaration to which the
9007attribute appertains is bridged to the named Swift type.
9008
9009```objc
9010__attribute__((__objc_root__))
9011@interface Base
9012- (instancetype)init;
9013@end
9014
9015__attribute__((__swift_bridge__("BridgedI")))
9016@interface I : Base
9017@end
9018```
9019
9020In this example, the Objective-C interface `I` will be made available to Swift
9021with the name `BridgedI`. It would be possible for the compiler to refer to
9022`I` still in order to bridge the type back to Objective-C.)reST";
9023
9024static const char AttrDoc_SwiftBridgedTypedef[] = R"reST(The `swift_bridged_typedef` attribute indicates that when the typedef to which
9025the attribute appertains is imported into Swift, it should refer to the bridged
9026Swift type (e.g. Swift's `String`) rather than the Objective-C type as written
9027(e.g. `NSString`).
9028
9029```objc
9030@interface NSString;
9031typedef NSString *AliasedString __attribute__((__swift_bridged_typedef__));
9032
9033extern void acceptsAliasedString(AliasedString _Nonnull parameter);
9034```
9035
9036In this case, the function `acceptsAliasedString` will be imported into Swift
9037as a function which accepts a `String` type parameter.)reST";
9038
9039static const char AttrDoc_SwiftCall[] = R"reST(The `swiftcall` attribute indicates that a function should be called
9040using the Swift calling convention for a function or function pointer.
9041
9042The lowering for the Swift calling convention, as described by the Swift
9043ABI documentation, occurs in multiple phases. The first, "high-level"
9044phase breaks down the formal parameters and results into innately direct
9045and indirect components, adds implicit parameters for the generic
9046signature, and assigns the context and error ABI treatments to parameters
9047where applicable. The second phase breaks down the direct parameters
9048and results from the first phase and assigns them to registers or the
9049stack. The `swiftcall` convention only handles this second phase of
9050lowering; the C function type must accurately reflect the results
9051of the first phase, as follows:
9052
9053- Results classified as indirect by high-level lowering should be
9054 represented as parameters with the `swift_indirect_result` attribute.
9055
9056- Results classified as direct by high-level lowering should be represented
9057 as follows:
9058
9059 - First, remove any empty direct results.
9060 - If there are no direct results, the C result type should be `void`.
9061 - If there is one direct result, the C result type should be a type with
9062 the exact layout of that result type.
9063 - If there are a multiple direct results, the C result type should be
9064 a struct type with the exact layout of a tuple of those results.
9065
9066- Parameters classified as indirect by high-level lowering should be
9067 represented as parameters of pointer type.
9068
9069- Parameters classified as direct by high-level lowering should be
9070 omitted if they are empty types; otherwise, they should be represented
9071 as a parameter type with a layout exactly matching the layout of the
9072 Swift parameter type.
9073
9074- The context parameter, if present, should be represented as a trailing
9075 parameter with the `swift_context` attribute.
9076
9077- The error result parameter, if present, should be represented as a
9078 trailing parameter (always following a context parameter) with the
9079 `swift_error_result` attribute.
9080
9081`swiftcall` does not support variadic arguments or unprototyped functions.
9082
9083The parameter ABI treatment attributes are aspects of the function type.
9084A function type which applies an ABI treatment attribute to a
9085parameter is a different type from an otherwise-identical function type
9086that does not. A single parameter may not have multiple ABI treatment
9087attributes.
9088
9089Support for this feature is target-dependent, although it should be
9090supported on every target that Swift supports. Query for this attribute
9091with `__has_attribute(swiftcall)`. Query if the target supports the
9092calling convention with `__has_extension(swiftcc)`. This implies
9093support for the `swift_context`, `swift_error_result`, and
9094`swift_indirect_result` attributes.
9095
9096Since this attribute follows the Swift calling convention, it is
9097considered ABI-unstable except on targets where the Swift project
9098has declared ABI stability. Users are responsible for ensuring that
9099calls and definitions of functions with this attribute are compiled
9100with compatible compilers. Note that different operating systems
9101on the same architecture may use different ABIs and therefore may
9102have different standards for ABI stability.)reST";
9103
9104static const char AttrDoc_SwiftContext[] = R"reST(The `swift_context` attribute marks a parameter of a `swiftcall`
9105or `swiftasynccall` function as having the special context-parameter
9106ABI treatment.
9107
9108This treatment generally passes the context value in a special register
9109which is normally callee-preserved.
9110
9111A `swift_context` parameter must either be the last parameter or must be
9112followed by a `swift_error_result` parameter (which itself must always be
9113the last parameter).
9114
9115A context parameter must have pointer or reference type.)reST";
9116
9117static const char AttrDoc_SwiftError[] = R"reST(The `swift_error` attribute controls whether a particular function (or
9118Objective-C method) is imported into Swift as a throwing function, and if so,
9119which dynamic convention it uses.
9120
9121All of these conventions except `none` require the function to have an error
9122parameter. Currently, the error parameter is always the last parameter of type
9123`NSError**` or `CFErrorRef*`. Swift will remove the error parameter from
9124the imported API. When calling the API, Swift will always pass a valid address
9125initialized to a null pointer.
9126
9127- `swift_error(none)` means that the function should not be imported as
9128 throwing. The error parameter and result type will be imported normally.
9129- `swift_error(null_result)` means that calls to the function should be
9130 considered to have thrown if they return a null value. The return type must be
9131 a pointer type, and it will be imported into Swift with a non-optional type.
9132 This is the default error convention for Objective-C methods that return
9133 pointers.
9134- `swift_error(zero_result)` means that calls to the function should be
9135 considered to have thrown if they return a zero result. The return type must be
9136 an integral type. If the return type would have been imported as `Bool`, it
9137 is instead imported as `Void`. This is the default error convention for
9138 Objective-C methods that return a type that would be imported as `Bool`.
9139- `swift_error(nonzero_result)` means that calls to the function should be
9140 considered to have thrown if they return a non-zero result. The return type must
9141 be an integral type. If the return type would have been imported as `Bool`,
9142 it is instead imported as `Void`.
9143- `swift_error(nonnull_error)` means that calls to the function should be
9144 considered to have thrown if they leave a non-null error in the error parameter.
9145 The return type is left unmodified.)reST";
9146
9147static const char AttrDoc_SwiftErrorResult[] = R"reST(The `swift_error_result` attribute marks a parameter of a `swiftcall`
9148function as having the special error-result ABI treatment.
9149
9150This treatment generally passes the underlying error value in and out of
9151the function through a special register which is normally callee-preserved.
9152This is modeled in C by pretending that the register is addressable memory:
9153
9154- The caller appears to pass the address of a variable of pointer type.
9155 The current value of this variable is copied into the register before
9156 the call; if the call returns normally, the value is copied back into the
9157 variable.
9158- The callee appears to receive the address of a variable. This address
9159 is actually a hidden location in its own stack, initialized with the
9160 value of the register upon entry. When the function returns normally,
9161 the value in that hidden location is written back to the register.
9162
9163A `swift_error_result` parameter must be the last parameter, and it must be
9164preceded by a `swift_context` parameter.
9165
9166A `swift_error_result` parameter must have type `T**` or `T*&` for some
9167type T. Note that no qualifiers are permitted on the intermediate level.
9168
9169It is undefined behavior if the caller does not pass a pointer or
9170reference to a valid object.
9171
9172The standard convention is that the error value itself (that is, the
9173value stored in the apparent argument) will be null upon function entry,
9174but this is not enforced by the ABI.)reST";
9175
9176static const char AttrDoc_SwiftImportAsNonGeneric[] = R"reST()reST";
9177
9178static const char AttrDoc_SwiftImportPropertyAsAccessors[] = R"reST()reST";
9179
9180static const char AttrDoc_SwiftIndirectResult[] = R"reST(The `swift_indirect_result` attribute marks a parameter of a `swiftcall`
9181or `swiftasynccall` function as having the special indirect-result ABI
9182treatment.
9183
9184This treatment gives the parameter the target's normal indirect-result
9185ABI treatment, which may involve passing it differently from an ordinary
9186parameter. However, only the first indirect result will receive this
9187treatment. Furthermore, low-level lowering may decide that a direct result
9188must be returned indirectly; if so, this will take priority over the
9189`swift_indirect_result` parameters.
9190
9191A `swift_indirect_result` parameter must either be the first parameter or
9192follow another `swift_indirect_result` parameter.
9193
9194A `swift_indirect_result` parameter must have type `T*` or `T&` for
9195some object type `T`. If `T` is a complete type at the point of
9196definition of a function, it is undefined behavior if the argument
9197value does not point to storage of adequate size and alignment for a
9198value of type `T`.
9199
9200Making indirect results explicit in the signature allows C functions to
9201directly construct objects into them without relying on language
9202optimizations like C++'s named return value optimization (NRVO).)reST";
9203
9204static const char AttrDoc_SwiftName[] = R"reST(The `swift_name` attribute provides the name of the declaration in Swift. If
9205this attribute is absent, the name is transformed according to the algorithm
9206built into the Swift compiler.
9207
9208The argument is a string literal that contains the Swift name of the function,
9209variable, or type. When renaming a function, the name may be a compound Swift
9210name. For a type, enum constant, property, or variable declaration, the name
9211must be a simple or qualified identifier.
9212
9213```objc
9214@interface URL
9215- (void) initWithString:(NSString *)s __attribute__((__swift_name__("URL.init(_:)")))
9216@end
9217
9218void __attribute__((__swift_name__("squareRoot()"))) sqrt(double v) {
9219}
9220```)reST";
9221
9222static const char AttrDoc_SwiftNewType[] = R"reST(The `swift_newtype` attribute indicates that the typedef to which the
9223attribute appertains is imported as a new Swift type of the typedef's name.
9224Previously, the attribute was spelt `swift_wrapper`. While the behaviour of
9225the attribute is identical with either spelling, `swift_wrapper` is
9226deprecated, only exists for compatibility purposes, and should not be used in
9227new code.
9228
9229- `swift_newtype(struct)` means that a Swift struct will be created for this
9230 typedef.
9231
9232- `swift_newtype(enum)` means that a Swift enum will be created for this
9233 typedef.
9234
9235 ```c
9236 // Import UIFontTextStyle as an enum type, with enumerated values being
9237 // constants.
9238 typedef NSString * UIFontTextStyle __attribute__((__swift_newtype__(enum)));
9239
9240 // Import UIFontDescriptorFeatureKey as a structure type, with enumerated
9241 // values being members of the type structure.
9242 typedef NSString * UIFontDescriptorFeatureKey __attribute__((__swift_newtype__(struct)));
9243 ```)reST";
9244
9245static const char AttrDoc_SwiftNullability[] = R"reST()reST";
9246
9247static const char AttrDoc_SwiftObjCMembers[] = R"reST(This attribute indicates that Swift subclasses and members of Swift extensions
9248of this class will be implicitly marked with the `@objcMembers` Swift
9249attribute, exposing them back to Objective-C.)reST";
9250
9251static const char AttrDoc_SwiftPrivate[] = R"reST(Declarations marked with the `swift_private` attribute are hidden from the
9252framework client but are still made available for use within the framework or
9253Swift SDK overlay.
9254
9255The purpose of this attribute is to permit a more idomatic implementation of
9256declarations in Swift while hiding the non-idiomatic one.)reST";
9257
9258static const char AttrDoc_SwiftType[] = R"reST()reST";
9259
9260static const char AttrDoc_SwiftVersionedAddition[] = R"reST()reST";
9261
9262static const char AttrDoc_SwiftVersionedRemoval[] = R"reST()reST";
9263
9264static const char AttrDoc_SysVABI[] = R"reST(On Windows x86_64 targets, this attribute changes the calling convention of a
9265function to match the default convention used on Sys V targets such as Linux,
9266Mac, and BSD. This attribute has no effect on other targets.)reST";
9267
9268static const char AttrDoc_TLSModel[] = R"reST(The `tls_model` attribute allows you to specify which thread-local storage
9269model to use. It accepts the following strings:
9270
9271- global-dynamic
9272- local-dynamic
9273- initial-exec
9274- local-exec
9275
9276TLS models are mutually exclusive.)reST";
9277
9278static const char AttrDoc_Target[] = R"reST(Clang supports the GNU style `__attribute__((target("OPTIONS")))` attribute.
9279This attribute may be attached to a function definition and instructs
9280the backend to use different code generation options than were passed on the
9281command line.
9282
9283The current set of options correspond to the existing "subtarget features" for
9284the target with or without a "-mno-" in front corresponding to the absence
9285of the feature, as well as `arch="CPU"` which will change the default "CPU"
9286for the function.
9287
9288For X86, the attribute also allows `tune="CPU"` to optimize the generated
9289code for the given CPU without changing the available instructions.
9290
9291For AArch64, `arch="Arch"` will set the architecture, similar to the -march
9292command line options. `cpu="CPU"` can be used to select a specific cpu,
9293as per the `-mcpu` option, similarly for `tune=`. The attribute also allows the
9294"branch-protection=\<args>" option, where the permissible arguments and their
9295effect on code generation are the same as for the command-line option
9296`-mbranch-protection`.
9297
9298Example "subtarget features" from the x86 backend include: "mmx", "sse", "sse4.2",
9299"avx", "xop" and largely correspond to the machine specific options handled by
9300the front end.
9301
9302Note that this attribute does not apply transitively to nested functions such
9303as blocks or C++ lambdas.
9304
9305Additionally, this attribute supports function multiversioning for ELF based
9306x86/x86-64 targets, which can be used to create multiple implementations of the
9307same function that will be resolved at runtime based on the priority of their
9308`target` attribute strings. A function is considered a multiversioned function
9309if either two declarations of the function have different `target` attribute
9310strings, or if it has a `target` attribute string of `default`. For
9311example:
9312
9313```c++
9314__attribute__((target("arch=atom")))
9315void foo() {} // will be called on 'atom' processors.
9316__attribute__((target("default")))
9317void foo() {} // will be called on any other processors.
9318```
9319
9320All multiversioned functions must contain a `default` (fallback)
9321implementation, otherwise usages of the function are considered invalid.
9322Additionally, a function may not become multiversioned after its first use.)reST";
9323
9324static const char AttrDoc_TargetClones[] = R"reST(Clang supports the `target_clones("OPTIONS")` attribute. This attribute may be
9325attached to a function declaration and causes function multiversioning, where
9326multiple versions of the function will be emitted with different code
9327generation options. Additionally, these versions will be resolved at runtime
9328based on the priority of their attribute options. All `target_clone` functions
9329are considered multiversioned functions.
9330
9331For AArch64 target:
9332The attribute contains comma-separated strings of target features joined by "+"
9333sign. For example:
9334
9335```c++
9336__attribute__((target_clones("sha2+memtag", "fcma+sve2-pmull128")))
9337void foo() {}
9338```
9339
9340For every multiversioned function a `default` (fallback) implementation
9341always generated if not specified directly.
9342
9343For x86/x86-64 targets:
9344All multiversioned functions must contain a `default` (fallback)
9345implementation, otherwise usages of the function are considered invalid.
9346Additionally, a function may not become multiversioned after its first use.
9347
9348The options to `target_clones` can either be a target-specific architecture
9349(specified as `arch=CPU`), or one of a list of subtarget features.
9350
9351Example "subtarget features" from the x86 backend include: "mmx", "sse", "sse4.2",
9352"avx", "xop" and largely correspond to the machine specific options handled by
9353the front end.
9354
9355The versions can either be listed as a comma-separated sequence of string
9356literals or as a single string literal containing a comma-separated list of
9357versions. For compatibility with GCC, the two formats can be mixed. For
9358example, the following will emit 4 versions of the function:
9359
9360```c++
9361__attribute__((target_clones("arch=atom,avx2","arch=ivybridge","default")))
9362void foo() {}
9363```
9364
9365For targets that support the GNU indirect function (IFUNC) feature, dispatch
9366is performed by emitting an indirect function that is resolved to the appropriate
9367target clone at load time. The indirect function is given the name the
9368multiversioned function would have if it had been declared without the attribute.
9369For backward compatibility with earlier Clang releases, a function alias with an
9370`.ifunc` suffix is also emitted. The `.ifunc` suffixed symbol is a deprecated
9371feature and support for it may be removed in the future.
9372
9373For PowerPC targets, `target_clones` is supported on AIX only. Only CPU
9374(specified as `cpu=CPU`) and `default` options are allowed. IFUNC is supported
9375on AIX in Clang, so dispatch is implemented similar to other targets using IFUNC.
9376An FMV function that is only declared in a translation unit is treated as a
9377non-FMV. The resolver and the function clones are given internal linkage.)reST";
9378
9379static const char AttrDoc_TargetVersion[] = R"reST(For AArch64 target clang supports function multiversioning by
9380`__attribute__((target_version("OPTIONS")))` attribute. When applied to a
9381function it instructs compiler to emit multiple function versions based on
9382`target_version` attribute strings, which resolved at runtime depend on their
9383priority and target features availability. One of the versions is always
9384( implicitly or explicitly ) the `default` (fallback). Attribute strings can
9385contain dependent features names joined by the "+" sign.
9386
9387For targets that support the GNU indirect function (IFUNC) feature, dispatch
9388is performed by emitting an indirect function that is resolved to the appropriate
9389target clone at load time. The indirect function is given the name the
9390multiversioned function would have if it had been declared without the attribute.
9391For backward compatibility with earlier Clang releases, a function alias with an
9392`.ifunc` suffix is also emitted. The `.ifunc` suffixed symbol is a deprecated
9393feature and support for it may be removed in the future.)reST";
9394
9395static const char AttrDoc_TestTypestate[] = R"reST(Use `__attribute__((test_typestate(tested_state)))` to indicate that a method
9396returns true if the object is in the specified state..)reST";
9397
9398static const char AttrDoc_ThisCall[] = R"reST(On 32-bit x86 targets, this attribute changes the calling convention of a
9399function to use ECX for the first parameter (typically the implicit `this`
9400parameter of C++ methods) and clear parameters off of the stack on return. This
9401convention does not support variadic calls or unprototyped functions in C, and
9402has no effect on x86_64 targets. See the documentation for [\_\_thiscall][__thiscall] on
9403MSDN.
9404
9405[__thiscall]: http://msdn.microsoft.com/en-us/library/ek8tkfbw.aspx)reST";
9406
9407static const char AttrDoc_Thread[] = R"reST(The `__declspec(thread)` attribute declares a variable with thread local
9408storage. It is available under the `-fms-extensions` flag for MSVC
9409compatibility. See the documentation for [\_\_declspec(thread)][__declspec(thread)] on MSDN.
9410
9411In Clang, `__declspec(thread)` is generally equivalent in functionality to the
9412GNU `__thread` keyword. The variable must not have a destructor and must have
9413a constant initializer, if any. The attribute only applies to variables
9414declared with static storage duration, such as globals, class static data
9415members, and static locals.
9416
9417[__declspec(thread)]: http://msdn.microsoft.com/en-us/library/9w1sdazb.aspx)reST";
9418
9419static const char AttrDoc_TransparentUnion[] = R"reST(This attribute can be applied to a union to change the behavior of calls to
9420functions that have an argument with a transparent union type. The compiler
9421behavior is changed in the following manner:
9422
9423- A value whose type is any member of the transparent union can be passed as an
9424 argument without the need to cast that value.
9425- The argument is passed to the function using the calling convention of the
9426 first member of the transparent union. Consequently, all the members of the
9427 transparent union should have the same calling convention as its first member.
9428
9429Transparent unions are not supported in C++.)reST";
9430
9431static const char AttrDoc_TrivialABI[] = R"reST(The `trivial_abi` attribute can be applied to a C++ class, struct, or union.
9432It instructs the compiler to pass and return the type using the C ABI for the
9433underlying type when the type would otherwise be considered non-trivial for the
9434purpose of calls.
9435A class annotated with `trivial_abi` can have non-trivial destructors or
9436copy/move constructors without automatically becoming non-trivial for the
9437purposes of calls. For example:
9438
9439```c++
9440// A is trivial for the purposes of calls because `trivial_abi` makes the
9441// user-provided special functions trivial.
9442struct __attribute__((trivial_abi)) A {
9443 ~A();
9444 A(const A &);
9445 A(A &&);
9446 int x;
9447};
9448
9449// B's destructor and copy/move constructor are considered trivial for the
9450// purpose of calls because A is trivial.
9451struct B {
9452 A a;
9453};
9454```
9455
9456If a type is trivial for the purposes of calls, has a non-trivial destructor,
9457and is passed as an argument by value, the convention is that the callee will
9458destroy the object before returning. The lifetime of the copy of the parameter
9459in the caller ends without a destructor call when the call begins.
9460
9461If a type is trivial for the purpose of calls, it is assumed to be trivially
9462relocatable for the purpose of `__is_trivially_relocatable` and
9463`__builtin_is_cpp_trivially_relocatable`.
9464When a type marked with `[[trivial_abi]]` is used as a function argument,
9465the compiler may omit the call to the copy constructor.
9466Thus, side effects of the copy constructor are potentially not performed.
9467For example, objects that contain pointers to themselves or otherwise depend
9468on their address (or the address or their subobjects) should not be declared
9469`[[trivial_abi]]`.
9470
9471Attribute `trivial_abi` has no effect in the following cases:
9472
9473- The class directly declares a virtual base or virtual methods.
9474
9475- Copy constructors and move constructors of the class are all deleted.
9476
9477- The class has a base class that is non-trivial for the purposes of calls.
9478
9479- The class has a non-static data member whose type is non-trivial for the
9480 purposes of calls, which includes:
9481
9482 - classes that are non-trivial for the purposes of calls
9483 - \_\_weak-qualified types in Objective-C++
9484 - arrays of any of the above)reST";
9485
9486static const char AttrDoc_TryAcquireCapability[] = R"reST(Marks a function that attempts to acquire a capability. This function may fail to
9487actually acquire the capability; they accept a Boolean value determining
9488whether acquiring the capability means success (true), or failing to acquire
9489the capability means success (false).)reST";
9490
9491static const char AttrDoc_TypeNonNull[] = R"reST(The `_Nonnull` nullability qualifier indicates that null is not a meaningful
9492value for a value of the `_Nonnull` pointer type. For example, given a
9493declaration such as:
9494
9495```c
9496int fetch(int * _Nonnull ptr);
9497```
9498
9499a caller of `fetch` should not provide a null value, and the compiler will
9500produce a warning if it sees a literal null value passed to `fetch`. Note
9501that, unlike the declaration attribute `nonnull`, the presence of
9502`_Nonnull` does not imply that passing null is undefined behavior: `fetch`
9503is free to consider null undefined behavior or (perhaps for
9504backward-compatibility reasons) defensively handle null.)reST";
9505
9506static const char AttrDoc_TypeNullUnspecified[] = R"reST(The `_Null_unspecified` nullability qualifier indicates that neither the
9507`_Nonnull` nor `_Nullable` qualifiers make sense for a particular pointer
9508type. It is used primarily to indicate that the role of null with specific
9509pointers in a nullability-annotated header is unclear, e.g., due to
9510overly-complex implementations or historical factors with a long-lived API.)reST";
9511
9512static const char AttrDoc_TypeNullable[] = R"reST(The `_Nullable` nullability qualifier indicates that a value of the
9513`_Nullable` pointer type can be null. For example, given:
9514
9515```c
9516int fetch_or_zero(int * _Nullable ptr);
9517```
9518
9519a caller of `fetch_or_zero` can provide null.
9520
9521The `_Nullable` attribute on classes indicates that the given class can
9522represent null values, and so the `_Nullable`, `_Nonnull` etc qualifiers
9523make sense for this type. For example:
9524
9525```c
9526class _Nullable ArenaPointer { ... };
9527
9528ArenaPointer _Nonnull x = ...;
9529ArenaPointer _Nullable y = nullptr;
9530```)reST";
9531
9532static const char AttrDoc_TypeNullableResult[] = R"reST(The `_Nullable_result` nullability qualifier means that a value of the
9533`_Nullable_result` pointer can be `nil`, just like `_Nullable`. Where this
9534attribute differs from `_Nullable` is when it's used on a parameter to a
9535completion handler in a Swift async method. For instance, here:
9536
9537```objc
9538-(void)fetchSomeDataWithID:(int)identifier
9539 completionHandler:(void (^)(Data *_Nullable_result result, NSError *error))completionHandler;
9540```
9541
9542This method asynchronously calls `completionHandler` when the data is
9543available, or calls it with an error. `_Nullable_result` indicates to the
9544Swift importer that this is the uncommon case where `result` can get `nil`
9545even if no error has occurred, and will therefore import it as a Swift optional
9546type. Otherwise, if `result` was annotated with `_Nullable`, the Swift
9547importer will assume that `result` will always be non-nil unless an error
9548occurred.)reST";
9549
9550static const char AttrDoc_TypeTagForDatatype[] = R"reST(When declaring a variable, use
9551`__attribute__((type_tag_for_datatype(kind, type)))` to create a type tag that
9552is tied to the `type` argument given to the attribute.
9553
9554In the attribute prototype above:
9555: - `kind` is an identifier that should be used when annotating all applicable
9556 type tags.
9557 - `type` indicates the name of the type.
9558
9559Clang supports annotating type tags of two forms.
9560
9561- **Type tag that is a reference to a declared identifier.**
9562 Use `__attribute__((type_tag_for_datatype(kind, type)))` when declaring that
9563 identifier:
9564
9565 ```c++
9566 typedef int MPI_Datatype;
9567 extern struct mpi_datatype mpi_datatype_int
9568 __attribute__(( type_tag_for_datatype(mpi,int) ));
9569 #define MPI_INT ((MPI_Datatype) &mpi_datatype_int)
9570 // &mpi_datatype_int is a type tag. It is tied to type "int".
9571 ```
9572
9573- **Type tag that is an integral literal.**
9574 Declare a `static const` variable with an initializer value and attach
9575 `__attribute__((type_tag_for_datatype(kind, type)))` on that declaration:
9576
9577 ```c++
9578 typedef int MPI_Datatype;
9579 static const MPI_Datatype mpi_datatype_int
9580 __attribute__(( type_tag_for_datatype(mpi,int) )) = 42;
9581 #define MPI_INT ((MPI_Datatype) 42)
9582 // The number 42 is a type tag. It is tied to type "int".
9583 ```
9584
9585The `type_tag_for_datatype` attribute also accepts an optional third argument
9586that determines how the type of the function argument specified by either
9587`arg_idx` or `ptr_idx` is compared against the type associated with the type
9588tag. (Recall that for the `argument_with_type_tag` attribute, the type of the
9589function argument specified by `arg_idx` is compared against the type
9590associated with the type tag. Also recall that for the `pointer_with_type_tag`
9591attribute, the pointee type of the function argument specified by `ptr_idx` is
9592compared against the type associated with the type tag.) There are two supported
9593values for this optional third argument:
9594
9595- `layout_compatible` will cause types to be compared according to
9596 layout-compatibility rules (In C++11 [class.mem] p 17, 18, see the
9597 layout-compatibility rules for two standard-layout struct types and for two
9598 standard-layout union types). This is useful when creating a type tag
9599 associated with a struct or union type. For example:
9600
9601 ```c++
9602 /* In mpi.h */
9603 typedef int MPI_Datatype;
9604 struct internal_mpi_double_int { double d; int i; };
9605 extern struct mpi_datatype mpi_datatype_double_int
9606 __attribute__(( type_tag_for_datatype(mpi,
9607 struct internal_mpi_double_int, layout_compatible) ));
9608
9609 #define MPI_DOUBLE_INT ((MPI_Datatype) &mpi_datatype_double_int)
9610
9611 int MPI_Send(void *buf, int count, MPI_Datatype datatype, ...)
9612 __attribute__(( pointer_with_type_tag(mpi,1,3) ));
9613
9614 /* In user code */
9615 struct my_pair { double a; int b; };
9616 struct my_pair *buffer;
9617 MPI_Send(buffer, 1, MPI_DOUBLE_INT /*, ... */); // no warning because the
9618 // layout of my_pair is
9619 // compatible with that of
9620 // internal_mpi_double_int
9621
9622 struct my_int_pair { int a; int b; }
9623 struct my_int_pair *buffer2;
9624 MPI_Send(buffer2, 1, MPI_DOUBLE_INT /*, ... */); // warning because the
9625 // layout of my_int_pair
9626 // does not match that of
9627 // internal_mpi_double_int
9628 ```
9629
9630- `must_be_null` specifies that the function argument specified by either
9631 `arg_idx` (for the `argument_with_type_tag` attribute) or `ptr_idx` (for
9632 the `pointer_with_type_tag` attribute) should be a null pointer constant.
9633 The second argument to the `type_tag_for_datatype` attribute is ignored. For
9634 example:
9635
9636 ```c++
9637 /* In mpi.h */
9638 typedef int MPI_Datatype;
9639 extern struct mpi_datatype mpi_datatype_null
9640 __attribute__(( type_tag_for_datatype(mpi, void, must_be_null) ));
9641
9642 #define MPI_DATATYPE_NULL ((MPI_Datatype) &mpi_datatype_null)
9643 int MPI_Send(void *buf, int count, MPI_Datatype datatype, ...)
9644 __attribute__(( pointer_with_type_tag(mpi,1,3) ));
9645
9646 /* In user code */
9647 struct my_pair { double a; int b; };
9648 struct my_pair *buffer;
9649 MPI_Send(buffer, 1, MPI_DATATYPE_NULL /*, ... */); // warning: MPI_DATATYPE_NULL
9650 // was specified but buffer
9651 // is not a null pointer
9652 ```)reST";
9653
9654static const char AttrDoc_TypeVisibility[] = R"reST(The `type_visibility` attribute allows the visibility of a type and its vague
9655linkage objects (vtable, typeinfo, typeinfo name) to be controlled separately from
9656the visibility of functions and data members of the type.
9657
9658For example, this can be used to give default visibility to the typeinfo and the vtable
9659of a type while still keeping hidden visibility on its member functions and static data
9660members.
9661
9662This attribute can only be applied to types and namespaces.
9663
9664If both `visibility` and `type_visibility` are applied to a type or a namespace, the
9665visibility specified with the `type_visibility` attribute overrides the visibility
9666provided with the regular `visibility` attribute.)reST";
9667
9668static const char AttrDoc_UPtr[] = R"reST(The `__uptr` qualifier specifies that a 32-bit pointer should be zero
9669extended when converted to a 64-bit pointer.)reST";
9670
9671static const char AttrDoc_Unavailable[] = R"reST(No documentation.)reST";
9672
9673static const char AttrDoc_Uninitialized[] = R"reST(The command-line parameter `-ftrivial-auto-var-init=*` can be used to
9674initialize trivial automatic stack variables. By default, trivial automatic
9675stack variables are uninitialized. This attribute is used to override the
9676command-line parameter, forcing variables to remain uninitialized. It has no
9677semantic meaning in that using uninitialized values is undefined behavior,
9678it rather documents the programmer's intent.)reST";
9679
9680static const char AttrDoc_Unlikely[] = R"reST(The `likely` and `unlikely` attributes are used as compiler hints.
9681The attributes are used to aid the compiler to determine which branch is
9682likely or unlikely to be taken. This is done by marking the branch substatement
9683with one of the two attributes.
9684
9685It isn't allowed to annotate a single statement with both `likely` and
9686`unlikely`. Annotating the `true` and `false` branch of an `if`
9687statement with the same likelihood attribute will result in a diagnostic and
9688the attributes are ignored on both branches.
9689
9690In a `switch` statement it's allowed to annotate multiple `case` labels
9691or the `default` label with the same likelihood attribute. This makes
9692\* all labels without an attribute have a neutral likelihood,
9693\* all labels marked `[[likely]]` have an equally positive likelihood, and
9694\* all labels marked `[[unlikely]]` have an equally negative likelihood.
9695The neutral likelihood is the more likely of path execution than the negative
9696likelihood. The positive likelihood is the more likely of path of execution
9697than the neutral likelihood.
9698
9699These attributes have no effect on the generated code when using
9700PGO (Profile-Guided Optimization) or at optimization level 0.
9701
9702In Clang, the attributes will be ignored if they're not placed on
9703\* the `case` or `default` label of a `switch` statement,
9704\* or on the substatement of an `if` or `else` statement,
9705\* or on the substatement of an `for` or `while` statement.
9706The C++ Standard recommends to honor them on every statement in the
9707path of execution, but that can be confusing:
9708
9709```c++
9710if (b) {
9711 [[unlikely]] --b; // Per the standard this is in the path of
9712 // execution, so this branch should be considered
9713 // unlikely. However, Clang ignores the attribute
9714 // here since it is not on the substatement.
9715}
9716
9717if (b) {
9718 --b;
9719 if(b)
9720 return;
9721 [[unlikely]] --b; // Not in the path of execution,
9722} // the branch has no likelihood information.
9723
9724if (b) {
9725 --b;
9726 foo(b);
9727 // Whether or not the next statement is in the path of execution depends
9728 // on the declaration of foo():
9729 // In the path of execution: void foo(int);
9730 // Not in the path of execution: [[noreturn]] void foo(int);
9731 // This means the likelihood of the branch depends on the declaration
9732 // of foo().
9733 [[unlikely]] --b;
9734}
9735```
9736
9737Below are some example usages of the likelihood attributes and their effects:
9738
9739```c++
9740if (b) [[likely]] { // Placement on the first statement in the branch.
9741 // The compiler will optimize to execute the code here.
9742} else {
9743}
9744
9745if (b)
9746 [[unlikely]] b++; // Placement on the first statement in the branch.
9747else {
9748 // The compiler will optimize to execute the code here.
9749}
9750
9751if (b) {
9752 [[unlikely]] b++; // Placement on the second statement in the branch.
9753} // The attribute will be ignored.
9754
9755if (b) [[likely]] {
9756 [[unlikely]] b++; // No contradiction since the second attribute
9757} // is ignored.
9758
9759if (b)
9760 ;
9761else [[likely]] {
9762 // The compiler will optimize to execute the code here.
9763}
9764
9765if (b)
9766 ;
9767else
9768 // The compiler will optimize to execute the next statement.
9769 [[likely]] b = f();
9770
9771if (b) [[likely]]; // Both branches are likely. A diagnostic is issued
9772else [[likely]]; // and the attributes are ignored.
9773
9774if (b)
9775 [[likely]] int i = 5; // Issues a diagnostic since the attribute
9776 // isn't allowed on a declaration.
9777
9778switch (i) {
9779 [[likely]] case 1: // This value is likely
9780 ...
9781 break;
9782
9783 [[unlikely]] case 2: // This value is unlikely
9784 ...
9785 [[fallthrough]];
9786
9787 case 3: // No likelihood attribute
9788 ...
9789 [[likely]] break; // No effect
9790
9791 case 4: [[likely]] { // attribute on substatement has no effect
9792 ...
9793 break;
9794 }
9795
9796 [[unlikely]] default: // All other values are unlikely
9797 ...
9798 break;
9799}
9800
9801switch (i) {
9802 [[likely]] case 0: // This value and code path is likely
9803 ...
9804 [[fallthrough]];
9805
9806 case 1: // No likelihood attribute, code path is neutral
9807 break; // falling through has no effect on the likelihood
9808
9809 case 2: // No likelihood attribute, code path is neutral
9810 [[fallthrough]];
9811
9812 [[unlikely]] default: // This value and code path are both unlikely
9813 break;
9814}
9815
9816for(int i = 0; i != size; ++i) [[likely]] {
9817 ... // The loop is the likely path of execution
9818}
9819
9820for(const auto &E : Elements) [[likely]] {
9821 ... // The loop is the likely path of execution
9822}
9823
9824while(i != size) [[unlikely]] {
9825 ... // The loop is the unlikely path of execution
9826} // The generated code will optimize to skip the loop body
9827
9828while(true) [[unlikely]] {
9829 ... // The attribute has no effect
9830} // Clang elides the comparison and generates an infinite
9831 // loop
9832```)reST";
9833
9834static const char AttrDoc_UnsafeBufferUsage[] = R"reST(The attribute `[[clang::unsafe_buffer_usage]]` should be placed on functions
9835that need to be avoided as they are prone to buffer overflows or unsafe buffer
9836struct fields. It is designed to work together with the off-by-default compiler
9837warning `-Wunsafe-buffer-usage` to help codebases transition away from raw pointer
9838based buffer management, in favor of safer abstractions such as C++20 `std::span`.
9839The attribute causes `-Wunsafe-buffer-usage` to warn on every use of the function or
9840the field it is attached to, and it may also lead to emission of automatic fix-it
9841hints which would help the user replace the use of unsafe functions(/fields) with safe
9842alternatives, though the attribute can be used even when the fix can't be automated.
9843
9844- Attribute attached to functions: The attribute suppresses all
9845 `-Wunsafe-buffer-usage` warnings within the function it is attached to, as the
9846 function is now classified as unsafe. The attribute should be used carefully, as it
9847 will silence all unsafe operation warnings inside the function; including any new
9848 unsafe operations introduced in the future.
9849
9850 The attribute is warranted even if the only way a function can overflow
9851 the buffer is by violating the function's preconditions. For example, it
9852 would make sense to put the attribute on function `foo()` below because
9853 passing an incorrect size parameter would cause a buffer overflow:
9854
9855 ```c++
9856 [[clang::unsafe_buffer_usage]]
9857 void foo(int *buf, size_t size) {
9858 for (size_t i = 0; i < size; ++i) {
9859 buf[i] = i;
9860 }
9861 }
9862 ```
9863
9864 The attribute is NOT warranted when the function uses safe abstractions,
9865 assuming that these abstractions weren't misused outside the function.
9866 For example, function `bar()` below doesn't need the attribute,
9867 because assuming that the container `buf` is well-formed (has size that
9868 fits the original buffer it refers to), overflow cannot occur:
9869
9870 ```c++
9871 void bar(std::span<int> buf) {
9872 for (size_t i = 0; i < buf.size(); ++i) {
9873 buf[i] = i;
9874 }
9875 }
9876 ```
9877
9878 In this case function `bar()` enables the user to keep the buffer
9879 "containerized" in a span for as long as possible. On the other hand,
9880 Function `foo()` in the previous example may have internal
9881 consistency, but by accepting a raw buffer it requires the user to unwrap
9882 their span, which is undesirable according to the programming model
9883 behind `-Wunsafe-buffer-usage`.
9884
9885 The attribute is warranted when a function accepts a raw buffer only to
9886 immediately put it into a span:
9887
9888 ```c++
9889 [[clang::unsafe_buffer_usage]]
9890 void baz(int *buf, size_t size) {
9891 std::span<int> sp{ buf, size };
9892 for (size_t i = 0; i < sp.size(); ++i) {
9893 sp[i] = i;
9894 }
9895 }
9896 ```
9897
9898 In this case `baz()` does not contain any unsafe operations, but the awkward
9899 parameter type causes the caller to unwrap the span unnecessarily.
9900 Note that regardless of the attribute, code inside `baz()` isn't flagged
9901 by `-Wunsafe-buffer-usage` as unsafe. It is definitely undesirable,
9902 but if `baz()` is on an API surface, there is no way to improve it
9903 to make it as safe as `bar()` without breaking the source and binary
9904 compatibility with existing users of the function. In such cases
9905 the proper solution would be to create a different function (possibly
9906 an overload of `baz()`) that accepts a safe container like `bar()`,
9907 and then use the attribute on the original `baz()` to help the users
9908 update their code to use the new function.
9909
9910- Attribute attached to fields: The attribute should only be attached to
9911 struct fields, if the fields can not be updated to a safe type with bounds
9912 check, such as std::span. In other words, the buffers prone to unsafe accesses
9913 should always be updated to use safe containers/views and attaching the attribute
9914 must be last resort when such an update is infeasible.
9915
9916 The attribute can be placed on individual fields or a set of them as shown below.
9917
9918 ```c++
9919 struct A {
9920 [[clang::unsafe_buffer_usage]]
9921 int *ptr1;
9922
9923 [[clang::unsafe_buffer_usage]]
9924 int *ptr2, buf[10];
9925
9926 [[clang::unsafe_buffer_usage]]
9927 size_t sz;
9928 };
9929 ```
9930
9931 Here, every read/write to the fields ptr1, ptr2, buf and sz will trigger a warning
9932 that the field has been explcitly marked as unsafe due to unsafe-buffer operations.)reST";
9933
9934static const char AttrDoc_Unused[] = R"reST(When passing the `-Wunused` flag to Clang, entities that are unused by the
9935program may be diagnosed. The `[[maybe_unused]]` (or
9936`__attribute__((unused))`) attribute can be used to silence such diagnostics
9937when the entity cannot be removed. For instance, a local variable may exist
9938solely for use in an `assert()` statement, which makes the local variable
9939unused when `NDEBUG` is defined.
9940
9941The attribute may be applied to the declaration of a class, a typedef, a
9942variable, a function or method, a function parameter, an enumeration, an
9943enumerator, a non-static data member, or a label.
9944
9945```c++
9946#include <cassert>
9947
9948[[maybe_unused]] void f([[maybe_unused]] bool thing1,
9949 [[maybe_unused]] bool thing2) {
9950 [[maybe_unused]] bool b = thing1 && thing2;
9951 assert(b);
9952}
9953```)reST";
9954
9955static const char AttrDoc_UseHandle[] = R"reST(A function taking a handle by value might close the handle. If a function
9956parameter is annotated with `use_handle(tag)` it is assumed to not to change
9957the state of the handle. It is also assumed to require an open handle to work with.
9958The attribute requires a string literal argument to identify the handle being used.
9959
9960```c++
9961zx_status_t zx_port_wait(zx_handle_t handle [[clang::use_handle("zircon")]],
9962 zx_time_t deadline,
9963 zx_port_packet_t* packet);
9964```)reST";
9965
9966static const char AttrDoc_Used[] = R"reST(This attribute, when attached to a function or variable definition, indicates
9967that there may be references to the entity which are not apparent in the source
9968code. For example, it may be referenced from inline `asm`, or it may be
9969found through a dynamic symbol or section lookup.
9970
9971The compiler must emit the definition even if it appears to be unused, and it
9972must not apply optimizations which depend on fully understanding how the entity
9973is used.
9974
9975Whether this attribute has any effect on the linker depends on the target and
9976the linker. Most linkers support the feature of section garbage collection
9977(`--gc-sections`), also known as "dead stripping" (`ld64 -dead_strip`) or
9978discarding unreferenced sections (`link.exe /OPT:REF`). On COFF and Mach-O
9979targets (Windows and Apple platforms), the `used` attribute prevents symbols
9980from being removed by linker section GC. On ELF targets, it has no effect on its
9981own, and the linker may remove the definition if it is not otherwise referenced.
9982This linker GC can be avoided by also adding the `retain` attribute. Note
9983that `retain` requires special support from the linker; see that attribute's
9984documentation for further information.)reST";
9985
9986static const char AttrDoc_UsingIfExists[] = R"reST(The `using_if_exists` attribute applies to a using-declaration. It allows
9987programmers to import a declaration that potentially does not exist, instead
9988deferring any errors to the point of use. For instance:
9989
9990```c++
9991namespace empty_namespace {};
9992__attribute__((using_if_exists))
9993using empty_namespace::does_not_exist; // no error!
9994
9995does_not_exist x; // error: use of unresolved 'using_if_exists'
9996```
9997
9998The C++ spelling of the attribute (`[[clang::using_if_exists]]`) is also
9999supported as a clang extension, since ISO C++ doesn't support attributes in this
10000position. If the entity referred to by the using-declaration is found by name
10001lookup, the attribute has no effect. This attribute is useful for libraries
10002(primarily, libc++) that wish to redeclare a set of declarations in another
10003namespace, when the availability of those declarations is difficult or
10004impossible to detect at compile time with the preprocessor.)reST";
10005
10006static const char AttrDoc_Uuid[] = R"reST(No documentation.)reST";
10007
10008static const char AttrDoc_VTablePointerAuthentication[] = R"reST(No documentation.)reST";
10009
10010static const char AttrDoc_VecReturn[] = R"reST(No documentation.)reST";
10011
10012static const char AttrDoc_VecTypeHint[] = R"reST(No documentation.)reST";
10013
10014static const char AttrDoc_VectorCall[] = R"reST(On 32-bit x86 *and* x86_64 targets, this attribute changes the calling
10015convention of a function to pass vector parameters in SSE registers.
10016
10017On 32-bit x86 targets, this calling convention is similar to `__fastcall`.
10018The first two integer parameters are passed in ECX and EDX. Subsequent integer
10019parameters are passed in memory, and callee clears the stack. On x86_64
10020targets, the callee does *not* clear the stack, and integer parameters are
10021passed in RCX, RDX, R8, and R9 as is done for the default Windows x64 calling
10022convention.
10023
10024On both 32-bit x86 and x86_64 targets, vector and floating point arguments are
10025passed in XMM0-XMM5. Homogeneous vector aggregates of up to four elements are
10026passed in sequential SSE registers if enough are available. If AVX is enabled,
10027256 bit vectors are passed in YMM0-YMM5. Any vector or aggregate type that
10028cannot be passed in registers for any reason is passed by reference, which
10029allows the caller to align the parameter memory.
10030
10031See the documentation for [\_\_vectorcall][__vectorcall] on MSDN for more details.
10032
10033[__vectorcall]: http://msdn.microsoft.com/en-us/library/dn375768.aspx)reST";
10034
10035static const char AttrDoc_Visibility[] = R"reST(No documentation.)reST";
10036
10037static const char AttrDoc_WarnUnused[] = R"reST(The `warn_unused` attribute can be placed on the declaration of a structure or union type.
10038When 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.
10039Those constructor or destructor invocations are not considered a use if the type is declared with the `warn_unused` attribute.
10040The variable is considered used if it is named outside of its declaration.
10041
10042This 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.
10043
10044```c++
10045struct [[gnu::warn_unused]] S {
10046 S();
10047 ~S();
10048};
10049
10050struct T {
10051 T();
10052 ~T();
10053 };
10054
10055 int func() {
10056 S s1; // -Wunused-variable warning
10057 S s2; // No -Wunused-variable warning because of the member access expression below
10058 S s3; // No -Wunused-variable warning because of the sizeof operand below
10059 T t; // No -Wunused-variable warning
10060
10061 s2.~S();
10062 return sizeof(s3);
10063 }
10064```)reST";
10065
10066static const char AttrDoc_WarnUnusedResult[] = R"reST(Clang supports the ability to diagnose when the results of a function call
10067expression are discarded under suspicious circumstances. A diagnostic is
10068generated when a function or its return type is marked with `[[nodiscard]]`
10069(or `__attribute__((warn_unused_result))`) and the function call appears as a
10070potentially-evaluated discarded-value expression that is not explicitly cast to
10071`void`.
10072
10073A string literal may optionally be provided to the attribute, which will be
10074reproduced in any resulting diagnostics. Redeclarations using different forms
10075of the attribute (with or without the string literal or with different string
10076literal contents) are allowed. If there are redeclarations of the entity with
10077differing string literals, it is unspecified which one will be used by Clang
10078in any resulting diagnostics.
10079
10080```c++
10081struct [[nodiscard]] error_info { /*...*/ };
10082error_info enable_missile_safety_mode();
10083
10084void launch_missiles();
10085void test_missiles() {
10086 enable_missile_safety_mode(); // diagnoses
10087 launch_missiles();
10088}
10089error_info &foo();
10090void f() { foo(); } // Does not diagnose, error_info is a reference.
10091```
10092
10093Additionally, discarded temporaries resulting from a call to a constructor
10094marked with `[[nodiscard]]` or a constructor of a type marked
10095`[[nodiscard]]` will also diagnose. This also applies to type conversions that
10096use the annotated `[[nodiscard]]` constructor or result in an annotated type.
10097
10098```c++
10099struct [[nodiscard]] marked_type {/*..*/ };
10100struct marked_ctor {
10101 [[nodiscard]] marked_ctor();
10102 marked_ctor(int);
10103};
10104
10105struct S {
10106 operator marked_type() const;
10107 [[nodiscard]] operator int() const;
10108};
10109
10110void usages() {
10111 marked_type(); // diagnoses.
10112 marked_ctor(); // diagnoses.
10113 marked_ctor(3); // Does not diagnose, int constructor isn't marked nodiscard.
10114
10115 S s;
10116 static_cast<marked_type>(s); // diagnoses
10117 (int)s; // diagnoses
10118}
10119```)reST";
10120
10121static const char AttrDoc_Weak[] = R"reST(In supported output formats the `weak` attribute can be used to
10122specify that a variable or function should be emitted as a symbol with
10123`weak` (if a definition) or `extern_weak` (if a declaration of an
10124external symbol) [linkage](https://llvm.org/docs/LangRef.html#linkage-types).
10125
10126If there is a non-weak definition of the symbol the linker will select
10127that over the weak. They must have same type and alignment (variables
10128must also have the same size), but may have a different value.
10129
10130If there are multiple weak definitions of same symbol, but no non-weak
10131definition, they should have same type, size, alignment and value, the
10132linker will select one of them (see also [selectany] attribute).
10133
10134If the `weak` attribute is applied to a `const` qualified variable
10135definition that variable is no longer consider a compiletime constant
10136as its value can change during linking (or dynamic linking). This
10137means that it can e.g no longer be part of an initializer expression.
10138
10139```c
10140const int ANSWER __attribute__ ((weak)) = 42;
10141
10142/* This function may be replaced link-time */
10143__attribute__ ((weak)) void debug_log(const char *msg)
10144{
10145 fprintf(stderr, "DEBUG: %s\n", msg);
10146}
10147
10148int main(int argc, const char **argv)
10149{
10150 debug_log ("Starting up...");
10151
10152 /* This may print something else than "6 * 7 = 42",
10153 if there is a non-weak definition of "ANSWER" in
10154 an object linked in */
10155 printf("6 * 7 = %d\n", ANSWER);
10156
10157 return 0;
10158 }
10159```
10160
10161If an external declaration is marked weak and that symbol does not
10162exist during linking (possibly dynamic) the address of the symbol will
10163evaluate to NULL.
10164
10165```c
10166void may_not_exist(void) __attribute__ ((weak));
10167
10168int main(int argc, const char **argv)
10169{
10170 if (may_not_exist) {
10171 may_not_exist();
10172 } else {
10173 printf("Function did not exist\n");
10174 }
10175 return 0;
10176}
10177```)reST";
10178
10179static const char AttrDoc_WeakImport[] = R"reST(No documentation.)reST";
10180
10181static const char AttrDoc_WeakRef[] = R"reST(No documentation.)reST";
10182
10183static const char AttrDoc_WebAssemblyExportName[] = R"reST(Clang supports the `__attribute__((export_name(<name>)))`
10184attribute for the WebAssembly target. This attribute may be attached to a
10185function declaration, where it modifies how the symbol is to be exported
10186from the linked WebAssembly.
10187
10188WebAssembly functions are exported via string name. By default when a symbol
10189is exported, the export name for C/C++ symbols are the same as their C/C++
10190symbol names. This attribute can be used to override the default behavior, and
10191request a specific string name be used instead.)reST";
10192
10193static const char AttrDoc_WebAssemblyFuncref[] = R"reST(Clang supports the `__attribute__((export_name(<name>)))`
10194attribute for the WebAssembly target. This attribute may be attached to a
10195function declaration, where it modifies how the symbol is to be exported
10196from the linked WebAssembly.
10197
10198WebAssembly functions are exported via string name. By default when a symbol
10199is exported, the export name for C/C++ symbols are the same as their C/C++
10200symbol names. This attribute can be used to override the default behavior, and
10201request a specific string name be used instead.)reST";
10202
10203static const char AttrDoc_WebAssemblyImportModule[] = R"reST(Clang supports the `__attribute__((import_module(<module_name>)))`
10204attribute for the WebAssembly target. This attribute may be attached to a
10205function declaration, where it modifies how the symbol is to be imported
10206within the WebAssembly linking environment.
10207
10208WebAssembly imports use a two-level namespace scheme, consisting of a module
10209name, which typically identifies a module from which to import, and a field
10210name, which typically identifies a field from that module to import. By
10211default, module names for C/C++ symbols are assigned automatically by the
10212linker. This attribute can be used to override the default behavior, and
10213request a specific module name be used instead.)reST";
10214
10215static const char AttrDoc_WebAssemblyImportName[] = R"reST(Clang supports the `__attribute__((import_name(<name>)))`
10216attribute for the WebAssembly target. This attribute may be attached to a
10217function declaration, where it modifies how the symbol is to be imported
10218within the WebAssembly linking environment.
10219
10220WebAssembly imports use a two-level namespace scheme, consisting of a module
10221name, which typically identifies a module from which to import, and a field
10222name, which typically identifies a field from that module to import. By
10223default, field names for C/C++ symbols are the same as their C/C++ symbol
10224names. This attribute can be used to override the default behavior, and
10225request a specific field name be used instead.)reST";
10226
10227static const char AttrDoc_WorkGroupSizeHint[] = R"reST(No documentation.)reST";
10228
10229static const char AttrDoc_X86ForceAlignArgPointer[] = R"reST(Use this attribute to force stack alignment.
10230
10231Legacy x86 code uses 4-byte stack alignment. Newer aligned SSE instructions
10232(like 'movaps') that work with the stack require operands to be 16-byte aligned.
10233This attribute realigns the stack in the function prologue to make sure the
10234stack can be used with SSE instructions.
10235
10236Note that the x86_64 ABI forces 16-byte stack alignment at the call site.
10237Because of this, 'force_align_arg_pointer' is not needed on x86_64, except in
10238rare cases where the caller does not align the stack properly (e.g. flow
10239jumps from i386 arch code).
10240
10241```c
10242__attribute__ ((force_align_arg_pointer))
10243void f () {
10244 ...
10245}
10246```)reST";
10247
10248static const char AttrDoc_XRayInstrument[] = R"reST(`__attribute__((xray_always_instrument))` or
10249`[[clang::xray_always_instrument]]` is used to mark member functions (in C++),
10250methods (in Objective C), and free functions (in C, C++, and Objective C) to be
10251instrumented with XRay. This will cause the function to always have space at
10252the beginning and exit points to allow for runtime patching.
10253
10254Conversely, `__attribute__((xray_never_instrument))` or
10255`[[clang::xray_never_instrument]]` will inhibit the insertion of these
10256instrumentation points.
10257
10258If a function has neither of these attributes, they become subject to the XRay
10259heuristics used to determine whether a function should be instrumented or
10260otherwise.
10261
10262`__attribute__((xray_log_args(N)))` or `[[clang::xray_log_args(N)]]` is
10263used to preserve N function arguments for the logging function. Currently,
10264only N==1 is supported.)reST";
10265
10266static const char AttrDoc_XRayLogArgs[] = R"reST(`__attribute__((xray_always_instrument))` or
10267`[[clang::xray_always_instrument]]` is used to mark member functions (in C++),
10268methods (in Objective C), and free functions (in C, C++, and Objective C) to be
10269instrumented with XRay. This will cause the function to always have space at
10270the beginning and exit points to allow for runtime patching.
10271
10272Conversely, `__attribute__((xray_never_instrument))` or
10273`[[clang::xray_never_instrument]]` will inhibit the insertion of these
10274instrumentation points.
10275
10276If a function has neither of these attributes, they become subject to the XRay
10277heuristics used to determine whether a function should be instrumented or
10278otherwise.
10279
10280`__attribute__((xray_log_args(N)))` or `[[clang::xray_log_args(N)]]` is
10281used to preserve N function arguments for the logging function. Currently,
10282only N==1 is supported.)reST";
10283
10284static const char AttrDoc_ZeroCallUsedRegs[] = R"reST(This attribute, when attached to a function, causes the compiler to zero a
10285subset of all call-used registers before the function returns. It's used to
10286increase program security by either mitigating [Return-Oriented Programming][return-oriented programming]
10287(ROP) attacks or preventing information leakage through registers.
10288
10289The term "call-used" means registers which are not guaranteed to be preserved
10290unchanged for the caller by the current calling convention. This could also be
10291described as "caller-saved" or "not callee-saved".
10292
10293The `choice` parameters gives the programmer flexibility to choose the subset
10294of the call-used registers to be zeroed:
10295
10296- `skip` doesn't zero any call-used registers. This choice overrides any
10297 command-line arguments.
10298- `used` only zeros call-used registers used in the function. By `used`, we
10299 mean a register whose contents have been set or referenced in the function.
10300- `used-gpr` only zeros call-used GPR registers used in the function.
10301- `used-arg` only zeros call-used registers used to pass arguments to the
10302 function.
10303- `used-gpr-arg` only zeros call-used GPR registers used to pass arguments to
10304 the function.
10305- `all` zeros all call-used registers.
10306- `all-gpr` zeros all call-used GPR registers.
10307- `all-arg` zeros all call-used registers used to pass arguments to the
10308 function.
10309- `all-gpr-arg` zeros all call-used GPR registers used to pass arguments to
10310 the function.
10311
10312The default for the attribute is controlled by the `-fzero-call-used-regs`
10313flag.
10314
10315[return-oriented programming]: https://en.wikipedia.org/wiki/Return-oriented_programming)reST";
10316