1..
2  -------------------------------------------------------------------
3  NOTE: This file is automatically generated by running clang-tblgen
4  -gen-attr-docs. Do not edit this file by hand!!
5  -------------------------------------------------------------------
6
7===================
8Attributes in Clang
9===================
10.. contents::
11   :local:
12
13Introduction
14============
15
16This page lists the attributes currently supported by Clang.
17
18Function Attributes
19===================
20
21
22#pragma omp declare simd
23------------------------
24.. csv-table:: Supported Syntaxes
25   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
26
27   "","","","","", "X", ""
28
29The `declare simd` construct can be applied to a function to enable the creation
30of one or more versions that can process multiple arguments using SIMD
31instructions from a single invocation in a SIMD loop. The `declare simd`
32directive is a declarative directive. There may be multiple `declare simd`
33directives for a function. The use of a `declare simd` construct on a function
34enables the creation of SIMD versions of the associated function that can be
35used to process multiple arguments from a single invocation from a SIMD loop
36concurrently.
37The syntax of the `declare simd` construct is as follows:
38
39  .. code-block:: none
40
41    #pragma omp declare simd [clause[[,] clause] ...] new-line
42    [#pragma omp declare simd [clause[[,] clause] ...] new-line]
43    [...]
44    function definition or declaration
45
46where clause is one of the following:
47
48  .. code-block:: none
49
50    simdlen(length)
51    linear(argument-list[:constant-linear-step])
52    aligned(argument-list[:alignment])
53    uniform(argument-list)
54    inbranch
55    notinbranch
56
57
58#pragma omp declare target
59--------------------------
60.. csv-table:: Supported Syntaxes
61   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
62
63   "","","","","", "X", ""
64
65The `declare target` directive specifies that variables and functions are mapped
66to a device for OpenMP offload mechanism.
67
68The syntax of the declare target directive is as follows:
69
70  .. code-block:: c
71
72    #pragma omp declare target new-line
73    declarations-definition-seq
74    #pragma omp end declare target new-line
75
76
77_Noreturn
78---------
79.. csv-table:: Supported Syntaxes
80   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
81
82   "","","","","X", "", ""
83
84A function declared as ``_Noreturn`` shall not return to its caller. The
85compiler will generate a diagnostic for a function declared as ``_Noreturn``
86that appears to be capable of returning to its caller.
87
88
89abi_tag (gnu::abi_tag)
90----------------------
91.. csv-table:: Supported Syntaxes
92   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
93
94   "X","X","","","", "", "X"
95
96The ``abi_tag`` attribute can be applied to a function, variable, class or
97inline namespace declaration to modify the mangled name of the entity. It gives
98the ability to distinguish between different versions of the same entity but
99with different ABI versions supported. For example, a newer version of a class
100could have a different set of data members and thus have a different size. Using
101the ``abi_tag`` attribute, it is possible to have different mangled names for
102a global variable of the class type. Therefore, the old code could keep using
103the old manged name and the new code will use the new mangled name with tags.
104
105
106acquire_capability (acquire_shared_capability, clang::acquire_capability, clang::acquire_shared_capability)
107-----------------------------------------------------------------------------------------------------------
108.. csv-table:: Supported Syntaxes
109   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
110
111   "X","X","","","", "", ""
112
113Marks a function as acquiring a capability.
114
115
116alloc_align (gnu::alloc_align)
117------------------------------
118.. csv-table:: Supported Syntaxes
119   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
120
121   "X","X","","","", "", ""
122
123Use ``__attribute__((alloc_align(<alignment>))`` on a function
124declaration to specify that the return value of the function (which must be a
125pointer type) is at least as aligned as the value of the indicated parameter. The
126parameter is given by its index in the list of formal parameters; the first
127parameter has index 1 unless the function is a C++ non-static member function,
128in which case the first parameter has index 2 to account for the implicit ``this``
129parameter.
130
131.. code-block:: c++
132
133  // The returned pointer has the alignment specified by the first parameter.
134  void *a(size_t align) __attribute__((alloc_align(1)));
135
136  // The returned pointer has the alignment specified by the second parameter.
137  void *b(void *v, size_t align) __attribute__((alloc_align(2)));
138
139  // The returned pointer has the alignment specified by the second visible
140  // parameter, however it must be adjusted for the implicit 'this' parameter.
141  void *Foo::b(void *v, size_t align) __attribute__((alloc_align(3)));
142
143Note that this attribute merely informs the compiler that a function always
144returns a sufficiently aligned pointer. It does not cause the compiler to
145emit code to enforce that alignment.  The behavior is undefined if the returned
146poitner is not sufficiently aligned.
147
148
149alloc_size (gnu::alloc_size)
150----------------------------
151.. csv-table:: Supported Syntaxes
152   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
153
154   "X","X","","","", "", "X"
155
156The ``alloc_size`` attribute can be placed on functions that return pointers in
157order to hint to the compiler how many bytes of memory will be available at the
158returned pointer. ``alloc_size`` takes one or two arguments.
159
160- ``alloc_size(N)`` implies that argument number N equals the number of
161  available bytes at the returned pointer.
162- ``alloc_size(N, M)`` implies that the product of argument number N and
163  argument number M equals the number of available bytes at the returned
164  pointer.
165
166Argument numbers are 1-based.
167
168An example of how to use ``alloc_size``
169
170.. code-block:: c
171
172  void *my_malloc(int a) __attribute__((alloc_size(1)));
173  void *my_calloc(int a, int b) __attribute__((alloc_size(1, 2)));
174
175  int main() {
176    void *const p = my_malloc(100);
177    assert(__builtin_object_size(p, 0) == 100);
178    void *const a = my_calloc(20, 5);
179    assert(__builtin_object_size(a, 0) == 100);
180  }
181
182.. Note:: This attribute works differently in clang than it does in GCC.
183  Specifically, clang will only trace ``const`` pointers (as above); we give up
184  on pointers that are not marked as ``const``. In the vast majority of cases,
185  this is unimportant, because LLVM has support for the ``alloc_size``
186  attribute. However, this may cause mildly unintuitive behavior when used with
187  other attributes, such as ``enable_if``.
188
189
190artificial (gnu::artificial)
191----------------------------
192.. csv-table:: Supported Syntaxes
193   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
194
195   "X","X","","","", "", ""
196
197The ``artificial`` attribute can be applied to an inline function. If such a
198function is inlined, the attribute indicates that debuggers should associate
199the resulting instructions with the call site, rather than with the
200corresponding line within the inlined callee.
201
202
203assert_capability (assert_shared_capability, clang::assert_capability, clang::assert_shared_capability)
204-------------------------------------------------------------------------------------------------------
205.. csv-table:: Supported Syntaxes
206   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
207
208   "X","X","","","", "", ""
209
210Marks a function that dynamically tests whether a capability is held, and halts
211the program if it is not held.
212
213
214assume_aligned (gnu::assume_aligned)
215------------------------------------
216.. csv-table:: Supported Syntaxes
217   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
218
219   "X","X","","","", "", "X"
220
221Use ``__attribute__((assume_aligned(<alignment>[,<offset>]))`` on a function
222declaration to specify that the return value of the function (which must be a
223pointer type) has the specified offset, in bytes, from an address with the
224specified alignment. The offset is taken to be zero if omitted.
225
226.. code-block:: c++
227
228  // The returned pointer value has 32-byte alignment.
229  void *a() __attribute__((assume_aligned (32)));
230
231  // The returned pointer value is 4 bytes greater than an address having
232  // 32-byte alignment.
233  void *b() __attribute__((assume_aligned (32, 4)));
234
235Note that this attribute provides information to the compiler regarding a
236condition that the code already ensures is true. It does not cause the compiler
237to enforce the provided alignment assumption.
238
239
240availability (clang::availability, clang::availability)
241-------------------------------------------------------
242.. csv-table:: Supported Syntaxes
243   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
244
245   "X","X","X","","", "", "X"
246
247The ``availability`` attribute can be placed on declarations to describe the
248lifecycle of that declaration relative to operating system versions.  Consider
249the function declaration for a hypothetical function ``f``:
250
251.. code-block:: c++
252
253  void f(void) __attribute__((availability(macos,introduced=10.4,deprecated=10.6,obsoleted=10.7)));
254
255The availability attribute states that ``f`` was introduced in macOS 10.4,
256deprecated in macOS 10.6, and obsoleted in macOS 10.7.  This information
257is used by Clang to determine when it is safe to use ``f``: for example, if
258Clang is instructed to compile code for macOS 10.5, a call to ``f()``
259succeeds.  If Clang is instructed to compile code for macOS 10.6, the call
260succeeds but Clang emits a warning specifying that the function is deprecated.
261Finally, if Clang is instructed to compile code for macOS 10.7, the call
262fails because ``f()`` is no longer available.
263
264The availability attribute is a comma-separated list starting with the
265platform name and then including clauses specifying important milestones in the
266declaration's lifetime (in any order) along with additional information.  Those
267clauses can be:
268
269introduced=\ *version*
270  The first version in which this declaration was introduced.
271
272deprecated=\ *version*
273  The first version in which this declaration was deprecated, meaning that
274  users should migrate away from this API.
275
276obsoleted=\ *version*
277  The first version in which this declaration was obsoleted, meaning that it
278  was removed completely and can no longer be used.
279
280unavailable
281  This declaration is never available on this platform.
282
283message=\ *string-literal*
284  Additional message text that Clang will provide when emitting a warning or
285  error about use of a deprecated or obsoleted declaration.  Useful to direct
286  users to replacement APIs.
287
288replacement=\ *string-literal*
289  Additional message text that Clang will use to provide Fix-It when emitting
290  a warning about use of a deprecated declaration. The Fix-It will replace
291  the deprecated declaration with the new declaration specified.
292
293Multiple availability attributes can be placed on a declaration, which may
294correspond to different platforms.  Only the availability attribute with the
295platform corresponding to the target platform will be used; any others will be
296ignored.  If no availability attribute specifies availability for the current
297target platform, the availability attributes are ignored.  Supported platforms
298are:
299
300``ios``
301  Apple's iOS operating system.  The minimum deployment target is specified by
302  the ``-mios-version-min=*version*`` or ``-miphoneos-version-min=*version*``
303  command-line arguments.
304
305``macos``
306  Apple's macOS operating system.  The minimum deployment target is
307  specified by the ``-mmacosx-version-min=*version*`` command-line argument.
308  ``macosx`` is supported for backward-compatibility reasons, but it is
309  deprecated.
310
311``tvos``
312  Apple's tvOS operating system.  The minimum deployment target is specified by
313  the ``-mtvos-version-min=*version*`` command-line argument.
314
315``watchos``
316  Apple's watchOS operating system.  The minimum deployment target is specified by
317  the ``-mwatchos-version-min=*version*`` command-line argument.
318
319A declaration can typically be used even when deploying back to a platform
320version prior to when the declaration was introduced.  When this happens, the
321declaration is `weakly linked
322<https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPFrameworks/Concepts/WeakLinking.html>`_,
323as if the ``weak_import`` attribute were added to the declaration.  A
324weakly-linked declaration may or may not be present a run-time, and a program
325can determine whether the declaration is present by checking whether the
326address of that declaration is non-NULL.
327
328The flag ``strict`` disallows using API when deploying back to a
329platform version prior to when the declaration was introduced.  An
330attempt to use such API before its introduction causes a hard error.
331Weakly-linking is almost always a better API choice, since it allows
332users to query availability at runtime.
333
334If there are multiple declarations of the same entity, the availability
335attributes must either match on a per-platform basis or later
336declarations must not have availability attributes for that
337platform. For example:
338
339.. code-block:: c
340
341  void g(void) __attribute__((availability(macos,introduced=10.4)));
342  void g(void) __attribute__((availability(macos,introduced=10.4))); // okay, matches
343  void g(void) __attribute__((availability(ios,introduced=4.0))); // okay, adds a new platform
344  void g(void); // okay, inherits both macos and ios availability from above.
345  void g(void) __attribute__((availability(macos,introduced=10.5))); // error: mismatch
346
347When one method overrides another, the overriding method can be more widely available than the overridden method, e.g.,:
348
349.. code-block:: objc
350
351  @interface A
352  - (id)method __attribute__((availability(macos,introduced=10.4)));
353  - (id)method2 __attribute__((availability(macos,introduced=10.4)));
354  @end
355
356  @interface B : A
357  - (id)method __attribute__((availability(macos,introduced=10.3))); // okay: method moved into base class later
358  - (id)method __attribute__((availability(macos,introduced=10.5))); // error: this method was available via the base class in 10.4
359  @end
360
361Starting with the macOS 10.12 SDK, the ``API_AVAILABLE`` macro from
362``<os/availability.h>`` can simplify the spelling:
363
364.. code-block:: objc
365
366  @interface A
367  - (id)method API_AVAILABLE(macos(10.11)));
368  - (id)otherMethod API_AVAILABLE(macos(10.11), ios(11.0));
369  @end
370
371Also see the documentation for `@available
372<http://clang.llvm.org/docs/LanguageExtensions.html#objective-c-available>`_
373
374
375carries_dependency
376------------------
377.. csv-table:: Supported Syntaxes
378   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
379
380   "X","X","","","", "", "X"
381
382The ``carries_dependency`` attribute specifies dependency propagation into and
383out of functions.
384
385When specified on a function or Objective-C method, the ``carries_dependency``
386attribute means that the return value carries a dependency out of the function,
387so that the implementation need not constrain ordering upon return from that
388function. Implementations of the function and its caller may choose to preserve
389dependencies instead of emitting memory ordering instructions such as fences.
390
391Note, this attribute does not change the meaning of the program, but may result
392in generation of more efficient code.
393
394
395code_seg
396--------
397.. csv-table:: Supported Syntaxes
398   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
399
400   "","","","X","", "", ""
401
402The ``__declspec(code_seg)`` attribute enables the placement of code into separate
403named segments that can be paged or locked in memory individually. This attribute
404is used to control the placement of instantiated templates and compiler-generated
405code. See the documentation for `__declspec(code_seg)`_ on MSDN.
406
407.. _`__declspec(code_seg)`: http://msdn.microsoft.com/en-us/library/dn636922.aspx
408
409
410convergent (clang::convergent, clang::convergent)
411-------------------------------------------------
412.. csv-table:: Supported Syntaxes
413   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
414
415   "X","X","X","","", "", "X"
416
417The ``convergent`` attribute can be placed on a function declaration. It is
418translated into the LLVM ``convergent`` attribute, which indicates that the call
419instructions of a function with this attribute cannot be made control-dependent
420on any additional values.
421
422In languages designed for SPMD/SIMT programming model, e.g. OpenCL or CUDA,
423the call instructions of a function with this attribute must be executed by
424all work items or threads in a work group or sub group.
425
426This attribute is different from ``noduplicate`` because it allows duplicating
427function calls if it can be proved that the duplicated function calls are
428not made control-dependent on any additional values, e.g., unrolling a loop
429executed by all work items.
430
431Sample usage:
432.. code-block:: c
433
434  void convfunc(void) __attribute__((convergent));
435  // Setting it as a C++11 attribute is also valid in a C++ program.
436  // void convfunc(void) [[clang::convergent]];
437
438
439cpu_dispatch (clang::cpu_dispatch, clang::cpu_dispatch)
440-------------------------------------------------------
441.. csv-table:: Supported Syntaxes
442   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
443
444   "X","X","X","","", "", "X"
445
446The ``cpu_specific`` and ``cpu_dispatch`` attributes are used to define and
447resolve multiversioned functions. This form of multiversioning provides a
448mechanism for declaring versions across translation units and manually
449specifying the resolved function list. A specified CPU defines a set of minimum
450features that are required for the function to be called. The result of this is
451that future processors execute the most restrictive version of the function the
452new processor can execute.
453
454Function versions are defined with ``cpu_specific``, which takes one or more CPU
455names as a parameter. For example:
456
457.. code-block:: c
458
459  // Declares and defines the ivybridge version of single_cpu.
460  __attribute__((cpu_specific(ivybridge)))
461  void single_cpu(void){}
462
463  // Declares and defines the atom version of single_cpu.
464  __attribute__((cpu_specific(atom)))
465  void single_cpu(void){}
466
467  // Declares and defines both the ivybridge and atom version of multi_cpu.
468  __attribute__((cpu_specific(ivybridge, atom)))
469  void multi_cpu(void){}
470
471A dispatching (or resolving) function can be declared anywhere in a project's
472source code with ``cpu_dispatch``. This attribute takes one or more CPU names
473as a parameter (like ``cpu_specific``). Functions marked with ``cpu_dispatch``
474are not expected to be defined, only declared. If such a marked function has a
475definition, any side effects of the function are ignored; trivial function
476bodies are permissible for ICC compatibility.
477
478.. code-block:: c
479
480  // Creates a resolver for single_cpu above.
481  __attribute__((cpu_dispatch(ivybridge, atom)))
482  void single_cpu(void){}
483
484  // Creates a resolver for multi_cpu, but adds a 3rd version defined in another
485  // translation unit.
486  __attribute__((cpu_dispatch(ivybridge, atom, sandybridge)))
487  void multi_cpu(void){}
488
489Note that it is possible to have a resolving function that dispatches based on
490more or fewer options than are present in the program. Specifying fewer will
491result in the omitted options not being considered during resolution. Specifying
492a version for resolution that isn't defined in the program will result in a
493linking failure.
494
495It is also possible to specify a CPU name of ``generic`` which will be resolved
496if the executing processor doesn't satisfy the features required in the CPU
497name. The behavior of a program executing on a processor that doesn't satisfy
498any option of a multiversioned function is undefined.
499
500
501cpu_specific (clang::cpu_specific, clang::cpu_specific)
502-------------------------------------------------------
503.. csv-table:: Supported Syntaxes
504   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
505
506   "X","X","X","","", "", "X"
507
508The ``cpu_specific`` and ``cpu_dispatch`` attributes are used to define and
509resolve multiversioned functions. This form of multiversioning provides a
510mechanism for declaring versions across translation units and manually
511specifying the resolved function list. A specified CPU defines a set of minimum
512features that are required for the function to be called. The result of this is
513that future processors execute the most restrictive version of the function the
514new processor can execute.
515
516Function versions are defined with ``cpu_specific``, which takes one or more CPU
517names as a parameter. For example:
518
519.. code-block:: c
520
521  // Declares and defines the ivybridge version of single_cpu.
522  __attribute__((cpu_specific(ivybridge)))
523  void single_cpu(void){}
524
525  // Declares and defines the atom version of single_cpu.
526  __attribute__((cpu_specific(atom)))
527  void single_cpu(void){}
528
529  // Declares and defines both the ivybridge and atom version of multi_cpu.
530  __attribute__((cpu_specific(ivybridge, atom)))
531  void multi_cpu(void){}
532
533A dispatching (or resolving) function can be declared anywhere in a project's
534source code with ``cpu_dispatch``. This attribute takes one or more CPU names
535as a parameter (like ``cpu_specific``). Functions marked with ``cpu_dispatch``
536are not expected to be defined, only declared. If such a marked function has a
537definition, any side effects of the function are ignored; trivial function
538bodies are permissible for ICC compatibility.
539
540.. code-block:: c
541
542  // Creates a resolver for single_cpu above.
543  __attribute__((cpu_dispatch(ivybridge, atom)))
544  void single_cpu(void){}
545
546  // Creates a resolver for multi_cpu, but adds a 3rd version defined in another
547  // translation unit.
548  __attribute__((cpu_dispatch(ivybridge, atom, sandybridge)))
549  void multi_cpu(void){}
550
551Note that it is possible to have a resolving function that dispatches based on
552more or fewer options than are present in the program. Specifying fewer will
553result in the omitted options not being considered during resolution. Specifying
554a version for resolution that isn't defined in the program will result in a
555linking failure.
556
557It is also possible to specify a CPU name of ``generic`` which will be resolved
558if the executing processor doesn't satisfy the features required in the CPU
559name. The behavior of a program executing on a processor that doesn't satisfy
560any option of a multiversioned function is undefined.
561
562
563deprecated (gnu::deprecated)
564----------------------------
565.. csv-table:: Supported Syntaxes
566   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
567
568   "X","X","X","X","", "", ""
569
570The ``deprecated`` attribute can be applied to a function, a variable, or a
571type. This is useful when identifying functions, variables, or types that are
572expected to be removed in a future version of a program.
573
574Consider the function declaration for a hypothetical function ``f``:
575
576.. code-block:: c++
577
578  void f(void) __attribute__((deprecated("message", "replacement")));
579
580When spelled as `__attribute__((deprecated))`, the deprecated attribute can have
581two optional string arguments. The first one is the message to display when
582emitting the warning; the second one enables the compiler to provide a Fix-It
583to replace the deprecated name with a new name. Otherwise, when spelled as
584`[[gnu::deprecated]] or [[deprecated]]`, the attribute can have one optional
585string argument which is the message to display when emitting the warning.
586
587
588diagnose_if
589-----------
590.. csv-table:: Supported Syntaxes
591   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
592
593   "X","","","","", "", ""
594
595The ``diagnose_if`` attribute can be placed on function declarations to emit
596warnings or errors at compile-time if calls to the attributed function meet
597certain user-defined criteria. For example:
598
599.. code-block:: c
600
601  void abs(int a)
602    __attribute__((diagnose_if(a >= 0, "Redundant abs call", "warning")));
603  void must_abs(int a)
604    __attribute__((diagnose_if(a >= 0, "Redundant abs call", "error")));
605
606  int val = abs(1); // warning: Redundant abs call
607  int val2 = must_abs(1); // error: Redundant abs call
608  int val3 = abs(val);
609  int val4 = must_abs(val); // Because run-time checks are not emitted for
610                            // diagnose_if attributes, this executes without
611                            // issue.
612
613
614``diagnose_if`` is closely related to ``enable_if``, with a few key differences:
615
616* Overload resolution is not aware of ``diagnose_if`` attributes: they're
617  considered only after we select the best candidate from a given candidate set.
618* Function declarations that differ only in their ``diagnose_if`` attributes are
619  considered to be redeclarations of the same function (not overloads).
620* If the condition provided to ``diagnose_if`` cannot be evaluated, no
621  diagnostic will be emitted.
622
623Otherwise, ``diagnose_if`` is essentially the logical negation of ``enable_if``.
624
625As a result of bullet number two, ``diagnose_if`` attributes will stack on the
626same function. For example:
627
628.. code-block:: c
629
630  int foo() __attribute__((diagnose_if(1, "diag1", "warning")));
631  int foo() __attribute__((diagnose_if(1, "diag2", "warning")));
632
633  int bar = foo(); // warning: diag1
634                   // warning: diag2
635  int (*fooptr)(void) = foo; // warning: diag1
636                             // warning: diag2
637
638  constexpr int supportsAPILevel(int N) { return N < 5; }
639  int baz(int a)
640    __attribute__((diagnose_if(!supportsAPILevel(10),
641                               "Upgrade to API level 10 to use baz", "error")));
642  int baz(int a)
643    __attribute__((diagnose_if(!a, "0 is not recommended.", "warning")));
644
645  int (*bazptr)(int) = baz; // error: Upgrade to API level 10 to use baz
646  int v = baz(0); // error: Upgrade to API level 10 to use baz
647
648Query for this feature with ``__has_attribute(diagnose_if)``.
649
650
651disable_tail_calls (clang::disable_tail_calls, clang::disable_tail_calls)
652-------------------------------------------------------------------------
653.. csv-table:: Supported Syntaxes
654   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
655
656   "X","X","X","","", "", "X"
657
658The ``disable_tail_calls`` attribute instructs the backend to not perform tail call optimization inside the marked function.
659
660For example:
661
662  .. code-block:: c
663
664    int callee(int);
665
666    int foo(int a) __attribute__((disable_tail_calls)) {
667      return callee(a); // This call is not tail-call optimized.
668    }
669
670Marking virtual functions as ``disable_tail_calls`` is legal.
671
672  .. code-block:: c++
673
674    int callee(int);
675
676    class Base {
677    public:
678      [[clang::disable_tail_calls]] virtual int foo1() {
679        return callee(); // This call is not tail-call optimized.
680      }
681    };
682
683    class Derived1 : public Base {
684    public:
685      int foo1() override {
686        return callee(); // This call is tail-call optimized.
687      }
688    };
689
690
691enable_if
692---------
693.. csv-table:: Supported Syntaxes
694   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
695
696   "X","","","","", "", "X"
697
698.. Note:: Some features of this attribute are experimental. The meaning of
699  multiple enable_if attributes on a single declaration is subject to change in
700  a future version of clang. Also, the ABI is not standardized and the name
701  mangling may change in future versions. To avoid that, use asm labels.
702
703The ``enable_if`` attribute can be placed on function declarations to control
704which overload is selected based on the values of the function's arguments.
705When combined with the ``overloadable`` attribute, this feature is also
706available in C.
707
708.. code-block:: c++
709
710  int isdigit(int c);
711  int isdigit(int c) __attribute__((enable_if(c <= -1 || c > 255, "chosen when 'c' is out of range"))) __attribute__((unavailable("'c' must have the value of an unsigned char or EOF")));
712
713  void foo(char c) {
714    isdigit(c);
715    isdigit(10);
716    isdigit(-10);  // results in a compile-time error.
717  }
718
719The enable_if attribute takes two arguments, the first is an expression written
720in terms of the function parameters, the second is a string explaining why this
721overload candidate could not be selected to be displayed in diagnostics. The
722expression is part of the function signature for the purposes of determining
723whether it is a redeclaration (following the rules used when determining
724whether a C++ template specialization is ODR-equivalent), but is not part of
725the type.
726
727The enable_if expression is evaluated as if it were the body of a
728bool-returning constexpr function declared with the arguments of the function
729it is being applied to, then called with the parameters at the call site. If the
730result is false or could not be determined through constant expression
731evaluation, then this overload will not be chosen and the provided string may
732be used in a diagnostic if the compile fails as a result.
733
734Because the enable_if expression is an unevaluated context, there are no global
735state changes, nor the ability to pass information from the enable_if
736expression to the function body. For example, suppose we want calls to
737strnlen(strbuf, maxlen) to resolve to strnlen_chk(strbuf, maxlen, size of
738strbuf) only if the size of strbuf can be determined:
739
740.. code-block:: c++
741
742  __attribute__((always_inline))
743  static inline size_t strnlen(const char *s, size_t maxlen)
744    __attribute__((overloadable))
745    __attribute__((enable_if(__builtin_object_size(s, 0) != -1))),
746                             "chosen when the buffer size is known but 'maxlen' is not")))
747  {
748    return strnlen_chk(s, maxlen, __builtin_object_size(s, 0));
749  }
750
751Multiple enable_if attributes may be applied to a single declaration. In this
752case, the enable_if expressions are evaluated from left to right in the
753following manner. First, the candidates whose enable_if expressions evaluate to
754false or cannot be evaluated are discarded. If the remaining candidates do not
755share ODR-equivalent enable_if expressions, the overload resolution is
756ambiguous. Otherwise, enable_if overload resolution continues with the next
757enable_if attribute on the candidates that have not been discarded and have
758remaining enable_if attributes. In this way, we pick the most specific
759overload out of a number of viable overloads using enable_if.
760
761.. code-block:: c++
762
763  void f() __attribute__((enable_if(true, "")));  // #1
764  void f() __attribute__((enable_if(true, ""))) __attribute__((enable_if(true, "")));  // #2
765
766  void g(int i, int j) __attribute__((enable_if(i, "")));  // #1
767  void g(int i, int j) __attribute__((enable_if(j, ""))) __attribute__((enable_if(true)));  // #2
768
769In this example, a call to f() is always resolved to #2, as the first enable_if
770expression is ODR-equivalent for both declarations, but #1 does not have another
771enable_if expression to continue evaluating, so the next round of evaluation has
772only a single candidate. In a call to g(1, 1), the call is ambiguous even though
773#2 has more enable_if attributes, because the first enable_if expressions are
774not ODR-equivalent.
775
776Query for this feature with ``__has_attribute(enable_if)``.
777
778Note that functions with one or more ``enable_if`` attributes may not have
779their address taken, unless all of the conditions specified by said
780``enable_if`` are constants that evaluate to ``true``. For example:
781
782.. code-block:: c
783
784  const int TrueConstant = 1;
785  const int FalseConstant = 0;
786  int f(int a) __attribute__((enable_if(a > 0, "")));
787  int g(int a) __attribute__((enable_if(a == 0 || a != 0, "")));
788  int h(int a) __attribute__((enable_if(1, "")));
789  int i(int a) __attribute__((enable_if(TrueConstant, "")));
790  int j(int a) __attribute__((enable_if(FalseConstant, "")));
791
792  void fn() {
793    int (*ptr)(int);
794    ptr = &f; // error: 'a > 0' is not always true
795    ptr = &g; // error: 'a == 0 || a != 0' is not a truthy constant
796    ptr = &h; // OK: 1 is a truthy constant
797    ptr = &i; // OK: 'TrueConstant' is a truthy constant
798    ptr = &j; // error: 'FalseConstant' is a constant, but not truthy
799  }
800
801Because ``enable_if`` evaluation happens during overload resolution,
802``enable_if`` may give unintuitive results when used with templates, depending
803on when overloads are resolved. In the example below, clang will emit a
804diagnostic about no viable overloads for ``foo`` in ``bar``, but not in ``baz``:
805
806.. code-block:: c++
807
808  double foo(int i) __attribute__((enable_if(i > 0, "")));
809  void *foo(int i) __attribute__((enable_if(i <= 0, "")));
810  template <int I>
811  auto bar() { return foo(I); }
812
813  template <typename T>
814  auto baz() { return foo(T::number); }
815
816  struct WithNumber { constexpr static int number = 1; };
817  void callThem() {
818    bar<sizeof(WithNumber)>();
819    baz<WithNumber>();
820  }
821
822This is because, in ``bar``, ``foo`` is resolved prior to template
823instantiation, so the value for ``I`` isn't known (thus, both ``enable_if``
824conditions for ``foo`` fail). However, in ``baz``, ``foo`` is resolved during
825template instantiation, so the value for ``T::number`` is known.
826
827
828external_source_symbol (clang::external_source_symbol, clang::external_source_symbol)
829-------------------------------------------------------------------------------------
830.. csv-table:: Supported Syntaxes
831   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
832
833   "X","X","X","","", "", "X"
834
835The ``external_source_symbol`` attribute specifies that a declaration originates
836from an external source and describes the nature of that source.
837
838The fact that Clang is capable of recognizing declarations that were defined
839externally can be used to provide better tooling support for mixed-language
840projects or projects that rely on auto-generated code. For instance, an IDE that
841uses Clang and that supports mixed-language projects can use this attribute to
842provide a correct 'jump-to-definition' feature. For a concrete example,
843consider a protocol that's defined in a Swift file:
844
845.. code-block:: swift
846
847  @objc public protocol SwiftProtocol {
848    func method()
849  }
850
851This protocol can be used from Objective-C code by including a header file that
852was generated by the Swift compiler. The declarations in that header can use
853the ``external_source_symbol`` attribute to make Clang aware of the fact
854that ``SwiftProtocol`` actually originates from a Swift module:
855
856.. code-block:: objc
857
858  __attribute__((external_source_symbol(language="Swift",defined_in="module")))
859  @protocol SwiftProtocol
860  @required
861  - (void) method;
862  @end
863
864Consequently, when 'jump-to-definition' is performed at a location that
865references ``SwiftProtocol``, the IDE can jump to the original definition in
866the Swift source file rather than jumping to the Objective-C declaration in the
867auto-generated header file.
868
869The ``external_source_symbol`` attribute is a comma-separated list that includes
870clauses that describe the origin and the nature of the particular declaration.
871Those clauses can be:
872
873language=\ *string-literal*
874  The name of the source language in which this declaration was defined.
875
876defined_in=\ *string-literal*
877  The name of the source container in which the declaration was defined. The
878  exact definition of source container is language-specific, e.g. Swift's
879  source containers are modules, so ``defined_in`` should specify the Swift
880  module name.
881
882generated_declaration
883  This declaration was automatically generated by some tool.
884
885The clauses can be specified in any order. The clauses that are listed above are
886all optional, but the attribute has to have at least one clause.
887
888
889flatten (gnu::flatten)
890----------------------
891.. csv-table:: Supported Syntaxes
892   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
893
894   "X","X","","","", "", "X"
895
896The ``flatten`` attribute causes calls within the attributed function to
897be inlined unless it is impossible to do so, for example if the body of the
898callee is unavailable or if the callee has the ``noinline`` attribute.
899
900
901force_align_arg_pointer (gnu::force_align_arg_pointer)
902------------------------------------------------------
903.. csv-table:: Supported Syntaxes
904   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
905
906   "X","X","","","", "", ""
907
908Use this attribute to force stack alignment.
909
910Legacy x86 code uses 4-byte stack alignment. Newer aligned SSE instructions
911(like 'movaps') that work with the stack require operands to be 16-byte aligned.
912This attribute realigns the stack in the function prologue to make sure the
913stack can be used with SSE instructions.
914
915Note that the x86_64 ABI forces 16-byte stack alignment at the call site.
916Because of this, 'force_align_arg_pointer' is not needed on x86_64, except in
917rare cases where the caller does not align the stack properly (e.g. flow
918jumps from i386 arch code).
919
920  .. code-block:: c
921
922    __attribute__ ((force_align_arg_pointer))
923    void f () {
924      ...
925    }
926
927
928format (gnu::format)
929--------------------
930.. csv-table:: Supported Syntaxes
931   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
932
933   "X","X","","","", "", ""
934
935Clang supports the ``format`` attribute, which indicates that the function
936accepts a ``printf`` or ``scanf``-like format string and corresponding
937arguments or a ``va_list`` that contains these arguments.
938
939Please see `GCC documentation about format attribute
940<http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_ to find details
941about attribute syntax.
942
943Clang implements two kinds of checks with this attribute.
944
945#. Clang checks that the function with the ``format`` attribute is called with
946   a format string that uses format specifiers that are allowed, and that
947   arguments match the format string.  This is the ``-Wformat`` warning, it is
948   on by default.
949
950#. Clang checks that the format string argument is a literal string.  This is
951   the ``-Wformat-nonliteral`` warning, it is off by default.
952
953   Clang implements this mostly the same way as GCC, but there is a difference
954   for functions that accept a ``va_list`` argument (for example, ``vprintf``).
955   GCC does not emit ``-Wformat-nonliteral`` warning for calls to such
956   functions.  Clang does not warn if the format string comes from a function
957   parameter, where the function is annotated with a compatible attribute,
958   otherwise it warns.  For example:
959
960   .. code-block:: c
961
962     __attribute__((__format__ (__scanf__, 1, 3)))
963     void foo(const char* s, char *buf, ...) {
964       va_list ap;
965       va_start(ap, buf);
966
967       vprintf(s, ap); // warning: format string is not a string literal
968     }
969
970   In this case we warn because ``s`` contains a format string for a
971   ``scanf``-like function, but it is passed to a ``printf``-like function.
972
973   If the attribute is removed, clang still warns, because the format string is
974   not a string literal.
975
976   Another example:
977
978   .. code-block:: c
979
980     __attribute__((__format__ (__printf__, 1, 3)))
981     void foo(const char* s, char *buf, ...) {
982       va_list ap;
983       va_start(ap, buf);
984
985       vprintf(s, ap); // warning
986     }
987
988   In this case Clang does not warn because the format string ``s`` and
989   the corresponding arguments are annotated.  If the arguments are
990   incorrect, the caller of ``foo`` will receive a warning.
991
992
993ifunc (gnu::ifunc)
994------------------
995.. csv-table:: Supported Syntaxes
996   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
997
998   "X","X","","","", "", "X"
999
1000``__attribute__((ifunc("resolver")))`` is used to mark that the address of a declaration should be resolved at runtime by calling a resolver function.
1001
1002The symbol name of the resolver function is given in quotes.  A function with this name (after mangling) must be defined in the current translation unit; it may be ``static``.  The resolver function should take no arguments and return a pointer.
1003
1004The ``ifunc`` attribute may only be used on a function declaration.  A function declaration with an ``ifunc`` attribute is considered to be a definition of the declared entity.  The entity must not have weak linkage; for example, in C++, it cannot be applied to a declaration if a definition at that location would be considered inline.
1005
1006Not all targets support this attribute.  ELF targets support this attribute when using binutils v2.20.1 or higher and glibc v2.11.1 or higher.  Non-ELF targets currently do not support this attribute.
1007
1008
1009internal_linkage (clang::internal_linkage, clang::internal_linkage)
1010-------------------------------------------------------------------
1011.. csv-table:: Supported Syntaxes
1012   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
1013
1014   "X","X","X","","", "", "X"
1015
1016The ``internal_linkage`` attribute changes the linkage type of the declaration to internal.
1017This is similar to C-style ``static``, but can be used on classes and class methods. When applied to a class definition,
1018this attribute affects all methods and static data members of that class.
1019This can be used to contain the ABI of a C++ library by excluding unwanted class methods from the export tables.
1020
1021
1022interrupt (ARM)
1023---------------
1024.. csv-table:: Supported Syntaxes
1025   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
1026
1027   "X","X","","","", "", ""
1028
1029Clang supports the GNU style ``__attribute__((interrupt("TYPE")))`` attribute on
1030ARM targets. This attribute may be attached to a function definition and
1031instructs the backend to generate appropriate function entry/exit code so that
1032it can be used directly as an interrupt service routine.
1033
1034The parameter passed to the interrupt attribute is optional, but if
1035provided it must be a string literal with one of the following values: "IRQ",
1036"FIQ", "SWI", "ABORT", "UNDEF".
1037
1038The semantics are as follows:
1039
1040- If the function is AAPCS, Clang instructs the backend to realign the stack to
1041  8 bytes on entry. This is a general requirement of the AAPCS at public
1042  interfaces, but may not hold when an exception is taken. Doing this allows
1043  other AAPCS functions to be called.
1044- If the CPU is M-class this is all that needs to be done since the architecture
1045  itself is designed in such a way that functions obeying the normal AAPCS ABI
1046  constraints are valid exception handlers.
1047- If the CPU is not M-class, the prologue and epilogue are modified to save all
1048  non-banked registers that are used, so that upon return the user-mode state
1049  will not be corrupted. Note that to avoid unnecessary overhead, only
1050  general-purpose (integer) registers are saved in this way. If VFP operations
1051  are needed, that state must be saved manually.
1052
1053  Specifically, interrupt kinds other than "FIQ" will save all core registers
1054  except "lr" and "sp". "FIQ" interrupts will save r0-r7.
1055- If the CPU is not M-class, the return instruction is changed to one of the
1056  canonical sequences permitted by the architecture for exception return. Where
1057  possible the function itself will make the necessary "lr" adjustments so that
1058  the "preferred return address" is selected.
1059
1060  Unfortunately the compiler is unable to make this guarantee for an "UNDEF"
1061  handler, where the offset from "lr" to the preferred return address depends on
1062  the execution state of the code which generated the exception. In this case
1063  a sequence equivalent to "movs pc, lr" will be used.
1064
1065
1066interrupt (AVR)
1067---------------
1068.. csv-table:: Supported Syntaxes
1069   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
1070
1071   "X","X","","","", "", "X"
1072
1073Clang supports the GNU style ``__attribute__((interrupt))`` attribute on
1074AVR targets. This attribute may be attached to a function definition and instructs
1075the backend to generate appropriate function entry/exit code so that it can be used
1076directly as an interrupt service routine.
1077
1078On the AVR, the hardware globally disables interrupts when an interrupt is executed.
1079The first instruction of an interrupt handler declared with this attribute is a SEI
1080instruction to re-enable interrupts. See also the signal attribute that
1081does not insert a SEI instruction.
1082
1083
1084interrupt (MIPS)
1085----------------
1086.. csv-table:: Supported Syntaxes
1087   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
1088
1089   "X","X","","","", "", "X"
1090
1091Clang supports the GNU style ``__attribute__((interrupt("ARGUMENT")))`` attribute on
1092MIPS targets. This attribute may be attached to a function definition and instructs
1093the backend to generate appropriate function entry/exit code so that it can be used
1094directly as an interrupt service routine.
1095
1096By default, the compiler will produce a function prologue and epilogue suitable for
1097an interrupt service routine that handles an External Interrupt Controller (eic)
1098generated interrupt. This behaviour can be explicitly requested with the "eic"
1099argument.
1100
1101Otherwise, for use with vectored interrupt mode, the argument passed should be
1102of the form "vector=LEVEL" where LEVEL is one of the following values:
1103"sw0", "sw1", "hw0", "hw1", "hw2", "hw3", "hw4", "hw5". The compiler will
1104then set the interrupt mask to the corresponding level which will mask all
1105interrupts up to and including the argument.
1106
1107The semantics are as follows:
1108
1109- The prologue is modified so that the Exception Program Counter (EPC) and
1110  Status coprocessor registers are saved to the stack. The interrupt mask is
1111  set so that the function can only be interrupted by a higher priority
1112  interrupt. The epilogue will restore the previous values of EPC and Status.
1113
1114- The prologue and epilogue are modified to save and restore all non-kernel
1115  registers as necessary.
1116
1117- The FPU is disabled in the prologue, as the floating pointer registers are not
1118  spilled to the stack.
1119
1120- The function return sequence is changed to use an exception return instruction.
1121
1122- The parameter sets the interrupt mask for the function corresponding to the
1123  interrupt level specified. If no mask is specified the interrupt mask
1124  defaults to "eic".
1125
1126
1127interrupt (RISCV)
1128-----------------
1129.. csv-table:: Supported Syntaxes
1130   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
1131
1132   "X","X","","","", "", "X"
1133
1134Clang supports the GNU style ``__attribute__((interrupt))`` attribute on RISCV
1135targets. This attribute may be attached to a function definition and instructs
1136the backend to generate appropriate function entry/exit code so that it can be
1137used directly as an interrupt service routine.
1138
1139Permissible values for this parameter are ``user``, ``supervisor``,
1140and ``machine``. If there is no parameter, then it defaults to machine.
1141
1142Repeated interrupt attribute on the same declaration will cause a warning
1143to be emitted. In case of repeated declarations, the last one prevails.
1144
1145Refer to:
1146https://gcc.gnu.org/onlinedocs/gcc/RISC-V-Function-Attributes.html
1147https://riscv.org/specifications/privileged-isa/
1148The RISC-V Instruction Set Manual Volume II: Privileged Architecture
1149Version 1.10.
1150
1151
1152kernel
1153------
1154.. csv-table:: Supported Syntaxes
1155   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
1156
1157   "X","","","","", "", "X"
1158
1159``__attribute__((kernel))`` is used to mark a ``kernel`` function in
1160RenderScript.
1161
1162In RenderScript, ``kernel`` functions are used to express data-parallel
1163computations.  The RenderScript runtime efficiently parallelizes ``kernel``
1164functions to run on computational resources such as multi-core CPUs and GPUs.
1165See the RenderScript_ documentation for more information.
1166
1167.. _RenderScript: https://developer.android.com/guide/topics/renderscript/compute.html
1168
1169
1170lifetimebound (clang::lifetimebound)
1171------------------------------------
1172.. csv-table:: Supported Syntaxes
1173   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
1174
1175   "X","X","","","", "", ""
1176
1177The ``lifetimebound`` attribute indicates that a resource owned by
1178a function parameter or implicit object parameter
1179is retained by the return value of the annotated function
1180(or, for a parameter of a constructor, in the value of the constructed object).
1181It is only supported in C++.
1182
1183This attribute provides an experimental implementation of the facility
1184described in the C++ committee paper [http://wg21.link/p0936r0](P0936R0),
1185and is subject to change as the design of the corresponding functionality
1186changes.
1187
1188
1189long_call (gnu::long_call, gnu::far)
1190------------------------------------
1191.. csv-table:: Supported Syntaxes
1192   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
1193
1194   "X","X","","","", "", "X"
1195
1196Clang supports the ``__attribute__((long_call))``, ``__attribute__((far))``,
1197and ``__attribute__((near))`` attributes on MIPS targets. These attributes may
1198only be added to function declarations and change the code generated
1199by the compiler when directly calling the function. The ``near`` attribute
1200allows calls to the function to be made using the ``jal`` instruction, which
1201requires the function to be located in the same naturally aligned 256MB
1202segment as the caller.  The ``long_call`` and ``far`` attributes are synonyms
1203and require the use of a different call sequence that works regardless
1204of the distance between the functions.
1205
1206These attributes have no effect for position-independent code.
1207
1208These attributes take priority over command line switches such
1209as ``-mlong-calls`` and ``-mno-long-calls``.
1210
1211
1212micromips (gnu::micromips)
1213--------------------------
1214.. csv-table:: Supported Syntaxes
1215   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
1216
1217   "X","X","","","", "", "X"
1218
1219Clang supports the GNU style ``__attribute__((micromips))`` and
1220``__attribute__((nomicromips))`` attributes on MIPS targets. These attributes
1221may be attached to a function definition and instructs the backend to generate
1222or not to generate microMIPS code for that function.
1223
1224These attributes override the `-mmicromips` and `-mno-micromips` options
1225on the command line.
1226
1227
1228min_vector_width (clang::min_vector_width, clang::min_vector_width)
1229-------------------------------------------------------------------
1230.. csv-table:: Supported Syntaxes
1231   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
1232
1233   "X","X","X","","", "", "X"
1234
1235Clang supports the ``__attribute__((min_vector_width(width)))`` attribute. This
1236attribute may be attached to a function and informs the backend that this
1237function desires vectors of at least this width to be generated. Target-specific
1238maximum vector widths still apply. This means even if you ask for something
1239larger than the target supports, you will only get what the target supports.
1240This attribute is meant to be a hint to control target heuristics that may
1241generate narrower vectors than what the target hardware supports.
1242
1243This is currently used by the X86 target to allow some CPUs that support 512-bit
1244vectors to be limited to using 256-bit vectors to avoid frequency penalties.
1245This is currently enabled with the ``-prefer-vector-width=256`` command line
1246option. The ``min_vector_width`` attribute can be used to prevent the backend
1247from trying to split vector operations to match the ``prefer-vector-width``. All
1248X86 vector intrinsics from x86intrin.h already set this attribute. Additionally,
1249use of any of the X86-specific vector builtins will implicitly set this
1250attribute on the calling function. The intent is that explicitly writing vector
1251code using the X86 intrinsics will prevent ``prefer-vector-width`` from
1252affecting the code.
1253
1254
1255no_caller_saved_registers (gnu::no_caller_saved_registers)
1256----------------------------------------------------------
1257.. csv-table:: Supported Syntaxes
1258   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
1259
1260   "X","X","","","", "", ""
1261
1262Use this attribute to indicate that the specified function has no
1263caller-saved registers. That is, all registers are callee-saved except for
1264registers used for passing parameters to the function or returning parameters
1265from the function.
1266The compiler saves and restores any modified registers that were not used for
1267passing or returning arguments to the function.
1268
1269The user can call functions specified with the 'no_caller_saved_registers'
1270attribute from an interrupt handler without saving and restoring all
1271call-clobbered registers.
1272
1273Note that 'no_caller_saved_registers' attribute is not a calling convention.
1274In fact, it only overrides the decision of which registers should be saved by
1275the caller, but not how the parameters are passed from the caller to the callee.
1276
1277For example:
1278
1279  .. code-block:: c
1280
1281    __attribute__ ((no_caller_saved_registers, fastcall))
1282    void f (int arg1, int arg2) {
1283      ...
1284    }
1285
1286  In this case parameters 'arg1' and 'arg2' will be passed in registers.
1287  In this case, on 32-bit x86 targets, the function 'f' will use ECX and EDX as
1288  register parameters. However, it will not assume any scratch registers and
1289  should save and restore any modified registers except for ECX and EDX.
1290
1291
1292no_sanitize (clang::no_sanitize, clang::no_sanitize)
1293----------------------------------------------------
1294.. csv-table:: Supported Syntaxes
1295   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
1296
1297   "X","X","X","","", "", "X"
1298
1299Use the ``no_sanitize`` attribute on a function or a global variable
1300declaration to specify that a particular instrumentation or set of
1301instrumentations should not be applied. The attribute takes a list of
1302string literals, which have the same meaning as values accepted by the
1303``-fno-sanitize=`` flag. For example,
1304``__attribute__((no_sanitize("address", "thread")))`` specifies that
1305AddressSanitizer and ThreadSanitizer should not be applied to the
1306function or variable.
1307
1308See :ref:`Controlling Code Generation <controlling-code-generation>` for a
1309full list of supported sanitizer flags.
1310
1311
1312no_sanitize_address (no_address_safety_analysis, gnu::no_address_safety_analysis, gnu::no_sanitize_address)
1313-----------------------------------------------------------------------------------------------------------
1314.. csv-table:: Supported Syntaxes
1315   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
1316
1317   "X","X","X","","", "", "X"
1318
1319.. _langext-address_sanitizer:
1320
1321Use ``__attribute__((no_sanitize_address))`` on a function or a global
1322variable declaration to specify that address safety instrumentation
1323(e.g. AddressSanitizer) should not be applied.
1324
1325
1326no_sanitize_memory
1327------------------
1328.. csv-table:: Supported Syntaxes
1329   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
1330
1331   "X","X","X","","", "", "X"
1332
1333.. _langext-memory_sanitizer:
1334
1335Use ``__attribute__((no_sanitize_memory))`` on a function declaration to
1336specify that checks for uninitialized memory should not be inserted
1337(e.g. by MemorySanitizer). The function may still be instrumented by the tool
1338to avoid false positives in other places.
1339
1340
1341no_sanitize_thread
1342------------------
1343.. csv-table:: Supported Syntaxes
1344   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
1345
1346   "X","X","X","","", "", "X"
1347
1348.. _langext-thread_sanitizer:
1349
1350Use ``__attribute__((no_sanitize_thread))`` on a function declaration to
1351specify that checks for data races on plain (non-atomic) memory accesses should
1352not be inserted by ThreadSanitizer. The function is still instrumented by the
1353tool to avoid false positives and provide meaningful stack traces.
1354
1355
1356no_split_stack (gnu::no_split_stack)
1357------------------------------------
1358.. csv-table:: Supported Syntaxes
1359   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
1360
1361   "X","X","","","", "", "X"
1362
1363The ``no_split_stack`` attribute disables the emission of the split stack
1364preamble for a particular function. It has no effect if ``-fsplit-stack``
1365is not specified.
1366
1367
1368no_stack_protector (clang::no_stack_protector, clang::no_stack_protector)
1369-------------------------------------------------------------------------
1370.. csv-table:: Supported Syntaxes
1371   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
1372
1373   "X","X","X","","", "", "X"
1374
1375Clang supports the ``__attribute__((no_stack_protector))`` attribute which disables
1376the stack protector on the specified function. This attribute is useful for
1377selectively disabling the stack protector on some functions when building with
1378``-fstack-protector`` compiler option.
1379
1380For example, it disables the stack protector for the function ``foo`` but function
1381``bar`` will still be built with the stack protector with the ``-fstack-protector``
1382option.
1383
1384.. code-block:: c
1385
1386    int __attribute__((no_stack_protector))
1387    foo (int x); // stack protection will be disabled for foo.
1388
1389    int bar(int y); // bar can be built with the stack protector.
1390
1391
1392noalias
1393-------
1394.. csv-table:: Supported Syntaxes
1395   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
1396
1397   "","","","X","", "", ""
1398
1399The ``noalias`` attribute indicates that the only memory accesses inside
1400function are loads and stores from objects pointed to by its pointer-typed
1401arguments, with arbitrary offsets.
1402
1403
1404nocf_check (gnu::nocf_check)
1405----------------------------
1406.. csv-table:: Supported Syntaxes
1407   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
1408
1409   "X","X","","","", "", "X"
1410
1411Jump Oriented Programming attacks rely on tampering with addresses used by
1412indirect call / jmp, e.g. redirect control-flow to non-programmer
1413intended bytes in the binary.
1414X86 Supports Indirect Branch Tracking (IBT) as part of Control-Flow
1415Enforcement Technology (CET). IBT instruments ENDBR instructions used to
1416specify valid targets of indirect call / jmp.
1417The ``nocf_check`` attribute has two roles:
14181. Appertains to a function - do not add ENDBR instruction at the beginning of
1419the function.
14202. Appertains to a function pointer - do not track the target function of this
1421pointer (by adding nocf_check prefix to the indirect-call instruction).
1422
1423
1424nodiscard, warn_unused_result, clang::warn_unused_result, gnu::warn_unused_result
1425---------------------------------------------------------------------------------
1426.. csv-table:: Supported Syntaxes
1427   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
1428
1429   "X","X","X","","", "", "X"
1430
1431Clang supports the ability to diagnose when the results of a function call
1432expression are discarded under suspicious circumstances. A diagnostic is
1433generated when a function or its return type is marked with ``[[nodiscard]]``
1434(or ``__attribute__((warn_unused_result))``) and the function call appears as a
1435potentially-evaluated discarded-value expression that is not explicitly cast to
1436`void`.
1437
1438.. code-block: c++
1439  struct [[nodiscard]] error_info { /*...*/ };
1440  error_info enable_missile_safety_mode();
1441
1442  void launch_missiles();
1443  void test_missiles() {
1444    enable_missile_safety_mode(); // diagnoses
1445    launch_missiles();
1446  }
1447  error_info &foo();
1448  void f() { foo(); } // Does not diagnose, error_info is a reference.
1449
1450
1451noduplicate (clang::noduplicate, clang::noduplicate)
1452----------------------------------------------------
1453.. csv-table:: Supported Syntaxes
1454   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
1455
1456   "X","X","X","","", "", "X"
1457
1458The ``noduplicate`` attribute can be placed on function declarations to control
1459whether function calls to this function can be duplicated or not as a result of
1460optimizations. This is required for the implementation of functions with
1461certain special requirements, like the OpenCL "barrier" function, that might
1462need to be run concurrently by all the threads that are executing in lockstep
1463on the hardware. For example this attribute applied on the function
1464"nodupfunc" in the code below avoids that:
1465
1466.. code-block:: c
1467
1468  void nodupfunc() __attribute__((noduplicate));
1469  // Setting it as a C++11 attribute is also valid
1470  // void nodupfunc() [[clang::noduplicate]];
1471  void foo();
1472  void bar();
1473
1474  nodupfunc();
1475  if (a > n) {
1476    foo();
1477  } else {
1478    bar();
1479  }
1480
1481gets possibly modified by some optimizations into code similar to this:
1482
1483.. code-block:: c
1484
1485  if (a > n) {
1486    nodupfunc();
1487    foo();
1488  } else {
1489    nodupfunc();
1490    bar();
1491  }
1492
1493where the call to "nodupfunc" is duplicated and sunk into the two branches
1494of the condition.
1495
1496
1497nomicromips (gnu::nomicromips)
1498------------------------------
1499.. csv-table:: Supported Syntaxes
1500   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
1501
1502   "X","X","","","", "", "X"
1503
1504Clang supports the GNU style ``__attribute__((micromips))`` and
1505``__attribute__((nomicromips))`` attributes on MIPS targets. These attributes
1506may be attached to a function definition and instructs the backend to generate
1507or not to generate microMIPS code for that function.
1508
1509These attributes override the `-mmicromips` and `-mno-micromips` options
1510on the command line.
1511
1512
1513noreturn
1514--------
1515.. csv-table:: Supported Syntaxes
1516   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
1517
1518   "","X","","","", "", "X"
1519
1520A function declared as ``[[noreturn]]`` shall not return to its caller. The
1521compiler will generate a diagnostic for a function declared as ``[[noreturn]]``
1522that appears to be capable of returning to its caller.
1523
1524
1525not_tail_called (clang::not_tail_called, clang::not_tail_called)
1526----------------------------------------------------------------
1527.. csv-table:: Supported Syntaxes
1528   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
1529
1530   "X","X","X","","", "", "X"
1531
1532The ``not_tail_called`` attribute prevents tail-call optimization on statically bound calls. It has no effect on indirect calls. Virtual functions, objective-c methods, and functions marked as ``always_inline`` cannot be marked as ``not_tail_called``.
1533
1534For example, it prevents tail-call optimization in the following case:
1535
1536  .. code-block:: c
1537
1538    int __attribute__((not_tail_called)) foo1(int);
1539
1540    int foo2(int a) {
1541      return foo1(a); // No tail-call optimization on direct calls.
1542    }
1543
1544However, it doesn't prevent tail-call optimization in this case:
1545
1546  .. code-block:: c
1547
1548    int __attribute__((not_tail_called)) foo1(int);
1549
1550    int foo2(int a) {
1551      int (*fn)(int) = &foo1;
1552
1553      // not_tail_called has no effect on an indirect call even if the call can be
1554      // resolved at compile time.
1555      return (*fn)(a);
1556    }
1557
1558Marking virtual functions as ``not_tail_called`` is an error:
1559
1560  .. code-block:: c++
1561
1562    class Base {
1563    public:
1564      // not_tail_called on a virtual function is an error.
1565      [[clang::not_tail_called]] virtual int foo1();
1566
1567      virtual int foo2();
1568
1569      // Non-virtual functions can be marked ``not_tail_called``.
1570      [[clang::not_tail_called]] int foo3();
1571    };
1572
1573    class Derived1 : public Base {
1574    public:
1575      int foo1() override;
1576
1577      // not_tail_called on a virtual function is an error.
1578      [[clang::not_tail_called]] int foo2() override;
1579    };
1580
1581
1582nothrow (gnu::nothrow)
1583----------------------
1584.. csv-table:: Supported Syntaxes
1585   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
1586
1587   "X","X","","X","", "", "X"
1588
1589Clang supports the GNU style ``__attribute__((nothrow))`` and Microsoft style
1590``__declspec(nothrow)`` attribute as an equivalent of `noexcept` on function
1591declarations. This attribute informs the compiler that the annotated function
1592does not throw an exception. This prevents exception-unwinding. This attribute
1593is particularly useful on functions in the C Standard Library that are
1594guaranteed to not throw an exception.
1595
1596
1597objc_boxable (clang::objc_boxable, clang::objc_boxable)
1598-------------------------------------------------------
1599.. csv-table:: Supported Syntaxes
1600   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
1601
1602   "X","X","X","","", "", "X"
1603
1604Structs and unions marked with the ``objc_boxable`` attribute can be used
1605with the Objective-C boxed expression syntax, ``@(...)``.
1606
1607**Usage**: ``__attribute__((objc_boxable))``. This attribute
1608can only be placed on a declaration of a trivially-copyable struct or union:
1609
1610.. code-block:: objc
1611
1612  struct __attribute__((objc_boxable)) some_struct {
1613    int i;
1614  };
1615  union __attribute__((objc_boxable)) some_union {
1616    int i;
1617    float f;
1618  };
1619  typedef struct __attribute__((objc_boxable)) _some_struct some_struct;
1620
1621  // ...
1622
1623  some_struct ss;
1624  NSValue *boxed = @(ss);
1625
1626
1627objc_method_family (clang::objc_method_family, clang::objc_method_family)
1628-------------------------------------------------------------------------
1629.. csv-table:: Supported Syntaxes
1630   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
1631
1632   "X","X","X","","", "", "X"
1633
1634Many methods in Objective-C have conventional meanings determined by their
1635selectors. It is sometimes useful to be able to mark a method as having a
1636particular conventional meaning despite not having the right selector, or as
1637not having the conventional meaning that its selector would suggest. For these
1638use cases, we provide an attribute to specifically describe the "method family"
1639that a method belongs to.
1640
1641**Usage**: ``__attribute__((objc_method_family(X)))``, where ``X`` is one of
1642``none``, ``alloc``, ``copy``, ``init``, ``mutableCopy``, or ``new``.  This
1643attribute can only be placed at the end of a method declaration:
1644
1645.. code-block:: objc
1646
1647  - (NSString *)initMyStringValue __attribute__((objc_method_family(none)));
1648
1649Users who do not wish to change the conventional meaning of a method, and who
1650merely want to document its non-standard retain and release semantics, should
1651use the retaining behavior attributes (``ns_returns_retained``,
1652``ns_returns_not_retained``, etc).
1653
1654Query for this feature with ``__has_attribute(objc_method_family)``.
1655
1656
1657objc_requires_super (clang::objc_requires_super, clang::objc_requires_super)
1658----------------------------------------------------------------------------
1659.. csv-table:: Supported Syntaxes
1660   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
1661
1662   "X","X","X","","", "", "X"
1663
1664Some Objective-C classes allow a subclass to override a particular method in a
1665parent class but expect that the overriding method also calls the overridden
1666method in the parent class. For these cases, we provide an attribute to
1667designate that a method requires a "call to ``super``" in the overriding
1668method in the subclass.
1669
1670**Usage**: ``__attribute__((objc_requires_super))``.  This attribute can only
1671be placed at the end of a method declaration:
1672
1673.. code-block:: objc
1674
1675  - (void)foo __attribute__((objc_requires_super));
1676
1677This attribute can only be applied the method declarations within a class, and
1678not a protocol.  Currently this attribute does not enforce any placement of
1679where the call occurs in the overriding method (such as in the case of
1680``-dealloc`` where the call must appear at the end).  It checks only that it
1681exists.
1682
1683Note that on both OS X and iOS that the Foundation framework provides a
1684convenience macro ``NS_REQUIRES_SUPER`` that provides syntactic sugar for this
1685attribute:
1686
1687.. code-block:: objc
1688
1689  - (void)foo NS_REQUIRES_SUPER;
1690
1691This macro is conditionally defined depending on the compiler's support for
1692this attribute.  If the compiler does not support the attribute the macro
1693expands to nothing.
1694
1695Operationally, when a method has this annotation the compiler will warn if the
1696implementation of an override in a subclass does not call super.  For example:
1697
1698.. code-block:: objc
1699
1700   warning: method possibly missing a [super AnnotMeth] call
1701   - (void) AnnotMeth{};
1702                      ^
1703
1704
1705objc_runtime_name (clang::objc_runtime_name, clang::objc_runtime_name)
1706----------------------------------------------------------------------
1707.. csv-table:: Supported Syntaxes
1708   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
1709
1710   "X","X","X","","", "", "X"
1711
1712By default, the Objective-C interface or protocol identifier is used
1713in the metadata name for that object. The `objc_runtime_name`
1714attribute allows annotated interfaces or protocols to use the
1715specified string argument in the object's metadata name instead of the
1716default name.
1717
1718**Usage**: ``__attribute__((objc_runtime_name("MyLocalName")))``.  This attribute
1719can only be placed before an @protocol or @interface declaration:
1720
1721.. code-block:: objc
1722
1723  __attribute__((objc_runtime_name("MyLocalName")))
1724  @interface Message
1725  @end
1726
1727
1728objc_runtime_visible (clang::objc_runtime_visible, clang::objc_runtime_visible)
1729-------------------------------------------------------------------------------
1730.. csv-table:: Supported Syntaxes
1731   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
1732
1733   "X","X","X","","", "", "X"
1734
1735This attribute specifies that the Objective-C class to which it applies is visible to the Objective-C runtime but not to the linker. Classes annotated with this attribute cannot be subclassed and cannot have categories defined for them.
1736
1737
1738optnone (clang::optnone, clang::optnone)
1739----------------------------------------
1740.. csv-table:: Supported Syntaxes
1741   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
1742
1743   "X","X","X","","", "", "X"
1744
1745The ``optnone`` attribute suppresses essentially all optimizations
1746on a function or method, regardless of the optimization level applied to
1747the compilation unit as a whole.  This is particularly useful when you
1748need to debug a particular function, but it is infeasible to build the
1749entire application without optimization.  Avoiding optimization on the
1750specified function can improve the quality of the debugging information
1751for that function.
1752
1753This attribute is incompatible with the ``always_inline`` and ``minsize``
1754attributes.
1755
1756
1757overloadable (clang::overloadable, clang::overloadable)
1758-------------------------------------------------------
1759.. csv-table:: Supported Syntaxes
1760   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
1761
1762   "X","X","X","","", "", "X"
1763
1764Clang provides support for C++ function overloading in C.  Function overloading
1765in C is introduced using the ``overloadable`` attribute.  For example, one
1766might provide several overloaded versions of a ``tgsin`` function that invokes
1767the appropriate standard function computing the sine of a value with ``float``,
1768``double``, or ``long double`` precision:
1769
1770.. code-block:: c
1771
1772  #include <math.h>
1773  float __attribute__((overloadable)) tgsin(float x) { return sinf(x); }
1774  double __attribute__((overloadable)) tgsin(double x) { return sin(x); }
1775  long double __attribute__((overloadable)) tgsin(long double x) { return sinl(x); }
1776
1777Given these declarations, one can call ``tgsin`` with a ``float`` value to
1778receive a ``float`` result, with a ``double`` to receive a ``double`` result,
1779etc.  Function overloading in C follows the rules of C++ function overloading
1780to pick the best overload given the call arguments, with a few C-specific
1781semantics:
1782
1783* Conversion from ``float`` or ``double`` to ``long double`` is ranked as a
1784  floating-point promotion (per C99) rather than as a floating-point conversion
1785  (as in C++).
1786
1787* A conversion from a pointer of type ``T*`` to a pointer of type ``U*`` is
1788  considered a pointer conversion (with conversion rank) if ``T`` and ``U`` are
1789  compatible types.
1790
1791* A conversion from type ``T`` to a value of type ``U`` is permitted if ``T``
1792  and ``U`` are compatible types.  This conversion is given "conversion" rank.
1793
1794* If no viable candidates are otherwise available, we allow a conversion from a
1795  pointer of type ``T*`` to a pointer of type ``U*``, where ``T`` and ``U`` are
1796  incompatible. This conversion is ranked below all other types of conversions.
1797  Please note: ``U`` lacking qualifiers that are present on ``T`` is sufficient
1798  for ``T`` and ``U`` to be incompatible.
1799
1800The declaration of ``overloadable`` functions is restricted to function
1801declarations and definitions.  If a function is marked with the ``overloadable``
1802attribute, then all declarations and definitions of functions with that name,
1803except for at most one (see the note below about unmarked overloads), must have
1804the ``overloadable`` attribute.  In addition, redeclarations of a function with
1805the ``overloadable`` attribute must have the ``overloadable`` attribute, and
1806redeclarations of a function without the ``overloadable`` attribute must *not*
1807have the ``overloadable`` attribute. e.g.,
1808
1809.. code-block:: c
1810
1811  int f(int) __attribute__((overloadable));
1812  float f(float); // error: declaration of "f" must have the "overloadable" attribute
1813  int f(int); // error: redeclaration of "f" must have the "overloadable" attribute
1814
1815  int g(int) __attribute__((overloadable));
1816  int g(int) { } // error: redeclaration of "g" must also have the "overloadable" attribute
1817
1818  int h(int);
1819  int h(int) __attribute__((overloadable)); // error: declaration of "h" must not
1820                                            // have the "overloadable" attribute
1821
1822Functions marked ``overloadable`` must have prototypes.  Therefore, the
1823following code is ill-formed:
1824
1825.. code-block:: c
1826
1827  int h() __attribute__((overloadable)); // error: h does not have a prototype
1828
1829However, ``overloadable`` functions are allowed to use a ellipsis even if there
1830are no named parameters (as is permitted in C++).  This feature is particularly
1831useful when combined with the ``unavailable`` attribute:
1832
1833.. code-block:: c++
1834
1835  void honeypot(...) __attribute__((overloadable, unavailable)); // calling me is an error
1836
1837Functions declared with the ``overloadable`` attribute have their names mangled
1838according to the same rules as C++ function names.  For example, the three
1839``tgsin`` functions in our motivating example get the mangled names
1840``_Z5tgsinf``, ``_Z5tgsind``, and ``_Z5tgsine``, respectively.  There are two
1841caveats to this use of name mangling:
1842
1843* Future versions of Clang may change the name mangling of functions overloaded
1844  in C, so you should not depend on an specific mangling.  To be completely
1845  safe, we strongly urge the use of ``static inline`` with ``overloadable``
1846  functions.
1847
1848* The ``overloadable`` attribute has almost no meaning when used in C++,
1849  because names will already be mangled and functions are already overloadable.
1850  However, when an ``overloadable`` function occurs within an ``extern "C"``
1851  linkage specification, it's name *will* be mangled in the same way as it
1852  would in C.
1853
1854For the purpose of backwards compatibility, at most one function with the same
1855name as other ``overloadable`` functions may omit the ``overloadable``
1856attribute. In this case, the function without the ``overloadable`` attribute
1857will not have its name mangled.
1858
1859For example:
1860
1861.. code-block:: c
1862
1863  // Notes with mangled names assume Itanium mangling.
1864  int f(int);
1865  int f(double) __attribute__((overloadable));
1866  void foo() {
1867    f(5); // Emits a call to f (not _Z1fi, as it would with an overload that
1868          // was marked with overloadable).
1869    f(1.0); // Emits a call to _Z1fd.
1870  }
1871
1872Support for unmarked overloads is not present in some versions of clang. You may
1873query for it using ``__has_extension(overloadable_unmarked)``.
1874
1875Query for this attribute with ``__has_attribute(overloadable)``.
1876
1877
1878release_capability (release_shared_capability, clang::release_capability, clang::release_shared_capability)
1879-----------------------------------------------------------------------------------------------------------
1880.. csv-table:: Supported Syntaxes
1881   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
1882
1883   "X","X","","","", "", ""
1884
1885Marks a function as releasing a capability.
1886
1887
1888short_call (gnu::short_call, gnu::near)
1889---------------------------------------
1890.. csv-table:: Supported Syntaxes
1891   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
1892
1893   "X","X","","","", "", "X"
1894
1895Clang supports the ``__attribute__((long_call))``, ``__attribute__((far))``,
1896``__attribute__((short__call))``, and ``__attribute__((near))`` attributes
1897on MIPS targets. These attributes may only be added to function declarations
1898and change the code generated by the compiler when directly calling
1899the function. The ``short_call`` and ``near`` attributes are synonyms and
1900allow calls to the function to be made using the ``jal`` instruction, which
1901requires the function to be located in the same naturally aligned 256MB segment
1902as the caller.  The ``long_call`` and ``far`` attributes are synonyms and
1903require the use of a different call sequence that works regardless
1904of the distance between the functions.
1905
1906These attributes have no effect for position-independent code.
1907
1908These attributes take priority over command line switches such
1909as ``-mlong-calls`` and ``-mno-long-calls``.
1910
1911
1912signal (gnu::signal)
1913--------------------
1914.. csv-table:: Supported Syntaxes
1915   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
1916
1917   "X","X","","","", "", "X"
1918
1919Clang supports the GNU style ``__attribute__((signal))`` attribute on
1920AVR targets. This attribute may be attached to a function definition and instructs
1921the backend to generate appropriate function entry/exit code so that it can be used
1922directly as an interrupt service routine.
1923
1924Interrupt handler functions defined with the signal attribute do not re-enable interrupts.
1925
1926
1927target (gnu::target)
1928--------------------
1929.. csv-table:: Supported Syntaxes
1930   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
1931
1932   "X","X","","","", "", "X"
1933
1934Clang supports the GNU style ``__attribute__((target("OPTIONS")))`` attribute.
1935This attribute may be attached to a function definition and instructs
1936the backend to use different code generation options than were passed on the
1937command line.
1938
1939The current set of options correspond to the existing "subtarget features" for
1940the target with or without a "-mno-" in front corresponding to the absence
1941of the feature, as well as ``arch="CPU"`` which will change the default "CPU"
1942for the function.
1943
1944Example "subtarget features" from the x86 backend include: "mmx", "sse", "sse4.2",
1945"avx", "xop" and largely correspond to the machine specific options handled by
1946the front end.
1947
1948Additionally, this attribute supports function multiversioning for ELF based
1949x86/x86-64 targets, which can be used to create multiple implementations of the
1950same function that will be resolved at runtime based on the priority of their
1951``target`` attribute strings. A function is considered a multiversioned function
1952if either two declarations of the function have different ``target`` attribute
1953strings, or if it has a ``target`` attribute string of ``default``.  For
1954example:
1955
1956  .. code-block:: c++
1957
1958    __attribute__((target("arch=atom")))
1959    void foo() {} // will be called on 'atom' processors.
1960    __attribute__((target("default")))
1961    void foo() {} // will be called on any other processors.
1962
1963All multiversioned functions must contain a ``default`` (fallback)
1964implementation, otherwise usages of the function are considered invalid.
1965Additionally, a function may not become multiversioned after its first use.
1966
1967
1968try_acquire_capability (try_acquire_shared_capability, clang::try_acquire_capability, clang::try_acquire_shared_capability)
1969---------------------------------------------------------------------------------------------------------------------------
1970.. csv-table:: Supported Syntaxes
1971   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
1972
1973   "X","X","","","", "", ""
1974
1975Marks a function that attempts to acquire a capability. This function may fail to
1976actually acquire the capability; they accept a Boolean value determining
1977whether acquiring the capability means success (true), or failing to acquire
1978the capability means success (false).
1979
1980
1981xray_always_instrument (clang::xray_always_instrument), xray_never_instrument (clang::xray_never_instrument), xray_log_args (clang::xray_log_args)
1982--------------------------------------------------------------------------------------------------------------------------------------------------
1983.. csv-table:: Supported Syntaxes
1984   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
1985
1986   "X","X","X","","", "", "X"
1987
1988``__attribute__((xray_always_instrument))`` or ``[[clang::xray_always_instrument]]`` is used to mark member functions (in C++), methods (in Objective C), and free functions (in C, C++, and Objective C) to be instrumented with XRay. This will cause the function to always have space at the beginning and exit points to allow for runtime patching.
1989
1990Conversely, ``__attribute__((xray_never_instrument))`` or ``[[clang::xray_never_instrument]]`` will inhibit the insertion of these instrumentation points.
1991
1992If a function has neither of these attributes, they become subject to the XRay heuristics used to determine whether a function should be instrumented or otherwise.
1993
1994``__attribute__((xray_log_args(N)))`` or ``[[clang::xray_log_args(N)]]`` is used to preserve N function arguments for the logging function.  Currently, only N==1 is supported.
1995
1996
1997xray_always_instrument (clang::xray_always_instrument), xray_never_instrument (clang::xray_never_instrument), xray_log_args (clang::xray_log_args)
1998--------------------------------------------------------------------------------------------------------------------------------------------------
1999.. csv-table:: Supported Syntaxes
2000   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
2001
2002   "X","X","X","","", "", "X"
2003
2004``__attribute__((xray_always_instrument))`` or ``[[clang::xray_always_instrument]]`` is used to mark member functions (in C++), methods (in Objective C), and free functions (in C, C++, and Objective C) to be instrumented with XRay. This will cause the function to always have space at the beginning and exit points to allow for runtime patching.
2005
2006Conversely, ``__attribute__((xray_never_instrument))`` or ``[[clang::xray_never_instrument]]`` will inhibit the insertion of these instrumentation points.
2007
2008If a function has neither of these attributes, they become subject to the XRay heuristics used to determine whether a function should be instrumented or otherwise.
2009
2010``__attribute__((xray_log_args(N)))`` or ``[[clang::xray_log_args(N)]]`` is used to preserve N function arguments for the logging function.  Currently, only N==1 is supported.
2011
2012
2013Variable Attributes
2014===================
2015
2016
2017dllexport (gnu::dllexport)
2018--------------------------
2019.. csv-table:: Supported Syntaxes
2020   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
2021
2022   "X","X","","X","", "", "X"
2023
2024The ``__declspec(dllexport)`` attribute declares a variable, function, or
2025Objective-C interface to be exported from the module.  It is available under the
2026``-fdeclspec`` flag for compatibility with various compilers.  The primary use
2027is for COFF object files which explicitly specify what interfaces are available
2028for external use.  See the dllexport_ documentation on MSDN for more
2029information.
2030
2031.. _dllexport: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx
2032
2033
2034dllimport (gnu::dllimport)
2035--------------------------
2036.. csv-table:: Supported Syntaxes
2037   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
2038
2039   "X","X","","X","", "", "X"
2040
2041The ``__declspec(dllimport)`` attribute declares a variable, function, or
2042Objective-C interface to be imported from an external module.  It is available
2043under the ``-fdeclspec`` flag for compatibility with various compilers.  The
2044primary use is for COFF object files which explicitly specify what interfaces
2045are imported from external modules.  See the dllimport_ documentation on MSDN
2046for more information.
2047
2048.. _dllimport: https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx
2049
2050
2051init_seg
2052--------
2053.. csv-table:: Supported Syntaxes
2054   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
2055
2056   "","","","","", "X", ""
2057
2058The attribute applied by ``pragma init_seg()`` controls the section into
2059which global initialization function pointers are emitted.  It is only
2060available with ``-fms-extensions``.  Typically, this function pointer is
2061emitted into ``.CRT$XCU`` on Windows.  The user can change the order of
2062initialization by using a different section name with the same
2063``.CRT$XC`` prefix and a suffix that sorts lexicographically before or
2064after the standard ``.CRT$XCU`` sections.  See the init_seg_
2065documentation on MSDN for more information.
2066
2067.. _init_seg: http://msdn.microsoft.com/en-us/library/7977wcck(v=vs.110).aspx
2068
2069
2070maybe_unused, unused, gnu::unused
2071---------------------------------
2072.. csv-table:: Supported Syntaxes
2073   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
2074
2075   "X","X","X","","", "", ""
2076
2077When passing the ``-Wunused`` flag to Clang, entities that are unused by the
2078program may be diagnosed. The ``[[maybe_unused]]`` (or
2079``__attribute__((unused))``) attribute can be used to silence such diagnostics
2080when the entity cannot be removed. For instance, a local variable may exist
2081solely for use in an ``assert()`` statement, which makes the local variable
2082unused when ``NDEBUG`` is defined.
2083
2084The attribute may be applied to the declaration of a class, a typedef, a
2085variable, a function or method, a function parameter, an enumeration, an
2086enumerator, a non-static data member, or a label.
2087
2088.. code-block: c++
2089  #include <cassert>
2090
2091  [[maybe_unused]] void f([[maybe_unused]] bool thing1,
2092                          [[maybe_unused]] bool thing2) {
2093    [[maybe_unused]] bool b = thing1 && thing2;
2094    assert(b);
2095  }
2096
2097
2098nodebug (gnu::nodebug)
2099----------------------
2100.. csv-table:: Supported Syntaxes
2101   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
2102
2103   "X","X","","","", "", "X"
2104
2105The ``nodebug`` attribute allows you to suppress debugging information for a
2106function or method, or for a variable that is not a parameter or a non-static
2107data member.
2108
2109
2110noescape (clang::noescape, clang::noescape)
2111-------------------------------------------
2112.. csv-table:: Supported Syntaxes
2113   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
2114
2115   "X","X","X","","", "", "X"
2116
2117``noescape`` placed on a function parameter of a pointer type is used to inform
2118the compiler that the pointer cannot escape: that is, no reference to the object
2119the pointer points to that is derived from the parameter value will survive
2120after the function returns. Users are responsible for making sure parameters
2121annotated with ``noescape`` do not actuallly escape.
2122
2123For example:
2124
2125.. code-block:: c
2126
2127  int *gp;
2128
2129  void nonescapingFunc(__attribute__((noescape)) int *p) {
2130    *p += 100; // OK.
2131  }
2132
2133  void escapingFunc(__attribute__((noescape)) int *p) {
2134    gp = p; // Not OK.
2135  }
2136
2137Additionally, when the parameter is a `block pointer
2138<https://clang.llvm.org/docs/BlockLanguageSpec.html>`, the same restriction
2139applies to copies of the block. For example:
2140
2141.. code-block:: c
2142
2143  typedef void (^BlockTy)();
2144  BlockTy g0, g1;
2145
2146  void nonescapingFunc(__attribute__((noescape)) BlockTy block) {
2147    block(); // OK.
2148  }
2149
2150  void escapingFunc(__attribute__((noescape)) BlockTy block) {
2151    g0 = block; // Not OK.
2152    g1 = Block_copy(block); // Not OK either.
2153  }
2154
2155
2156nosvm
2157-----
2158.. csv-table:: Supported Syntaxes
2159   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
2160
2161   "X","","","","", "", "X"
2162
2163OpenCL 2.0 supports the optional ``__attribute__((nosvm))`` qualifier for
2164pointer variable. It informs the compiler that the pointer does not refer
2165to a shared virtual memory region. See OpenCL v2.0 s6.7.2 for details.
2166
2167Since it is not widely used and has been removed from OpenCL 2.1, it is ignored
2168by Clang.
2169
2170
2171pass_object_size (clang::pass_object_size, clang::pass_object_size)
2172-------------------------------------------------------------------
2173.. csv-table:: Supported Syntaxes
2174   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
2175
2176   "X","X","X","","", "", "X"
2177
2178.. Note:: The mangling of functions with parameters that are annotated with
2179  ``pass_object_size`` is subject to change. You can get around this by
2180  using ``__asm__("foo")`` to explicitly name your functions, thus preserving
2181  your ABI; also, non-overloadable C functions with ``pass_object_size`` are
2182  not mangled.
2183
2184The ``pass_object_size(Type)`` attribute can be placed on function parameters to
2185instruct clang to call ``__builtin_object_size(param, Type)`` at each callsite
2186of said function, and implicitly pass the result of this call in as an invisible
2187argument of type ``size_t`` directly after the parameter annotated with
2188``pass_object_size``. Clang will also replace any calls to
2189``__builtin_object_size(param, Type)`` in the function by said implicit
2190parameter.
2191
2192Example usage:
2193
2194.. code-block:: c
2195
2196  int bzero1(char *const p __attribute__((pass_object_size(0))))
2197      __attribute__((noinline)) {
2198    int i = 0;
2199    for (/**/; i < (int)__builtin_object_size(p, 0); ++i) {
2200      p[i] = 0;
2201    }
2202    return i;
2203  }
2204
2205  int main() {
2206    char chars[100];
2207    int n = bzero1(&chars[0]);
2208    assert(n == sizeof(chars));
2209    return 0;
2210  }
2211
2212If successfully evaluating ``__builtin_object_size(param, Type)`` at the
2213callsite is not possible, then the "failed" value is passed in. So, using the
2214definition of ``bzero1`` from above, the following code would exit cleanly:
2215
2216.. code-block:: c
2217
2218  int main2(int argc, char *argv[]) {
2219    int n = bzero1(argv);
2220    assert(n == -1);
2221    return 0;
2222  }
2223
2224``pass_object_size`` plays a part in overload resolution. If two overload
2225candidates are otherwise equally good, then the overload with one or more
2226parameters with ``pass_object_size`` is preferred. This implies that the choice
2227between two identical overloads both with ``pass_object_size`` on one or more
2228parameters will always be ambiguous; for this reason, having two such overloads
2229is illegal. For example:
2230
2231.. code-block:: c++
2232
2233  #define PS(N) __attribute__((pass_object_size(N)))
2234  // OK
2235  void Foo(char *a, char *b); // Overload A
2236  // OK -- overload A has no parameters with pass_object_size.
2237  void Foo(char *a PS(0), char *b PS(0)); // Overload B
2238  // Error -- Same signature (sans pass_object_size) as overload B, and both
2239  // overloads have one or more parameters with the pass_object_size attribute.
2240  void Foo(void *a PS(0), void *b);
2241
2242  // OK
2243  void Bar(void *a PS(0)); // Overload C
2244  // OK
2245  void Bar(char *c PS(1)); // Overload D
2246
2247  void main() {
2248    char known[10], *unknown;
2249    Foo(unknown, unknown); // Calls overload B
2250    Foo(known, unknown); // Calls overload B
2251    Foo(unknown, known); // Calls overload B
2252    Foo(known, known); // Calls overload B
2253
2254    Bar(known); // Calls overload D
2255    Bar(unknown); // Calls overload D
2256  }
2257
2258Currently, ``pass_object_size`` is a bit restricted in terms of its usage:
2259
2260* Only one use of ``pass_object_size`` is allowed per parameter.
2261
2262* It is an error to take the address of a function with ``pass_object_size`` on
2263  any of its parameters. If you wish to do this, you can create an overload
2264  without ``pass_object_size`` on any parameters.
2265
2266* It is an error to apply the ``pass_object_size`` attribute to parameters that
2267  are not pointers. Additionally, any parameter that ``pass_object_size`` is
2268  applied to must be marked ``const`` at its function's definition.
2269
2270
2271require_constant_initialization (clang::require_constant_initialization)
2272------------------------------------------------------------------------
2273.. csv-table:: Supported Syntaxes
2274   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
2275
2276   "X","X","","","", "", "X"
2277
2278This attribute specifies that the variable to which it is attached is intended
2279to have a `constant initializer <http://en.cppreference.com/w/cpp/language/constant_initialization>`_
2280according to the rules of [basic.start.static]. The variable is required to
2281have static or thread storage duration. If the initialization of the variable
2282is not a constant initializer an error will be produced. This attribute may
2283only be used in C++.
2284
2285Note that in C++03 strict constant expression checking is not done. Instead
2286the attribute reports if Clang can emit the variable as a constant, even if it's
2287not technically a 'constant initializer'. This behavior is non-portable.
2288
2289Static storage duration variables with constant initializers avoid hard-to-find
2290bugs caused by the indeterminate order of dynamic initialization. They can also
2291be safely used during dynamic initialization across translation units.
2292
2293This attribute acts as a compile time assertion that the requirements
2294for constant initialization have been met. Since these requirements change
2295between dialects and have subtle pitfalls it's important to fail fast instead
2296of silently falling back on dynamic initialization.
2297
2298.. code-block:: c++
2299
2300  // -std=c++14
2301  #define SAFE_STATIC [[clang::require_constant_initialization]]
2302  struct T {
2303    constexpr T(int) {}
2304    ~T(); // non-trivial
2305  };
2306  SAFE_STATIC T x = {42}; // Initialization OK. Doesn't check destructor.
2307  SAFE_STATIC T y = 42; // error: variable does not have a constant initializer
2308  // copy initialization is not a constant expression on a non-literal type.
2309
2310
2311section (gnu::section, __declspec(allocate))
2312--------------------------------------------
2313.. csv-table:: Supported Syntaxes
2314   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
2315
2316   "X","X","","X","", "", "X"
2317
2318The ``section`` attribute allows you to specify a specific section a
2319global variable or function should be in after translation.
2320
2321
2322swift_context (clang::swift_context, clang::swift_context)
2323----------------------------------------------------------
2324.. csv-table:: Supported Syntaxes
2325   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
2326
2327   "X","X","X","","", "", "X"
2328
2329The ``swift_context`` attribute marks a parameter of a ``swiftcall``
2330function as having the special context-parameter ABI treatment.
2331
2332This treatment generally passes the context value in a special register
2333which is normally callee-preserved.
2334
2335A ``swift_context`` parameter must either be the last parameter or must be
2336followed by a ``swift_error_result`` parameter (which itself must always be
2337the last parameter).
2338
2339A context parameter must have pointer or reference type.
2340
2341
2342swift_error_result (clang::swift_error_result, clang::swift_error_result)
2343-------------------------------------------------------------------------
2344.. csv-table:: Supported Syntaxes
2345   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
2346
2347   "X","X","X","","", "", "X"
2348
2349The ``swift_error_result`` attribute marks a parameter of a ``swiftcall``
2350function as having the special error-result ABI treatment.
2351
2352This treatment generally passes the underlying error value in and out of
2353the function through a special register which is normally callee-preserved.
2354This is modeled in C by pretending that the register is addressable memory:
2355
2356- The caller appears to pass the address of a variable of pointer type.
2357  The current value of this variable is copied into the register before
2358  the call; if the call returns normally, the value is copied back into the
2359  variable.
2360
2361- The callee appears to receive the address of a variable.  This address
2362  is actually a hidden location in its own stack, initialized with the
2363  value of the register upon entry.  When the function returns normally,
2364  the value in that hidden location is written back to the register.
2365
2366A ``swift_error_result`` parameter must be the last parameter, and it must be
2367preceded by a ``swift_context`` parameter.
2368
2369A ``swift_error_result`` parameter must have type ``T**`` or ``T*&`` for some
2370type T.  Note that no qualifiers are permitted on the intermediate level.
2371
2372It is undefined behavior if the caller does not pass a pointer or
2373reference to a valid object.
2374
2375The standard convention is that the error value itself (that is, the
2376value stored in the apparent argument) will be null upon function entry,
2377but this is not enforced by the ABI.
2378
2379
2380swift_indirect_result (clang::swift_indirect_result, clang::swift_indirect_result)
2381----------------------------------------------------------------------------------
2382.. csv-table:: Supported Syntaxes
2383   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
2384
2385   "X","X","X","","", "", "X"
2386
2387The ``swift_indirect_result`` attribute marks a parameter of a ``swiftcall``
2388function as having the special indirect-result ABI treatment.
2389
2390This treatment gives the parameter the target's normal indirect-result
2391ABI treatment, which may involve passing it differently from an ordinary
2392parameter.  However, only the first indirect result will receive this
2393treatment.  Furthermore, low-level lowering may decide that a direct result
2394must be returned indirectly; if so, this will take priority over the
2395``swift_indirect_result`` parameters.
2396
2397A ``swift_indirect_result`` parameter must either be the first parameter or
2398follow another ``swift_indirect_result`` parameter.
2399
2400A ``swift_indirect_result`` parameter must have type ``T*`` or ``T&`` for
2401some object type ``T``.  If ``T`` is a complete type at the point of
2402definition of a function, it is undefined behavior if the argument
2403value does not point to storage of adequate size and alignment for a
2404value of type ``T``.
2405
2406Making indirect results explicit in the signature allows C functions to
2407directly construct objects into them without relying on language
2408optimizations like C++'s named return value optimization (NRVO).
2409
2410
2411swiftcall (clang::swiftcall, clang::swiftcall)
2412----------------------------------------------
2413.. csv-table:: Supported Syntaxes
2414   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
2415
2416   "X","X","X","","", "", ""
2417
2418The ``swiftcall`` attribute indicates that a function should be called
2419using the Swift calling convention for a function or function pointer.
2420
2421The lowering for the Swift calling convention, as described by the Swift
2422ABI documentation, occurs in multiple phases.  The first, "high-level"
2423phase breaks down the formal parameters and results into innately direct
2424and indirect components, adds implicit paraameters for the generic
2425signature, and assigns the context and error ABI treatments to parameters
2426where applicable.  The second phase breaks down the direct parameters
2427and results from the first phase and assigns them to registers or the
2428stack.  The ``swiftcall`` convention only handles this second phase of
2429lowering; the C function type must accurately reflect the results
2430of the first phase, as follows:
2431
2432- Results classified as indirect by high-level lowering should be
2433  represented as parameters with the ``swift_indirect_result`` attribute.
2434
2435- Results classified as direct by high-level lowering should be represented
2436  as follows:
2437
2438  - First, remove any empty direct results.
2439
2440  - If there are no direct results, the C result type should be ``void``.
2441
2442  - If there is one direct result, the C result type should be a type with
2443    the exact layout of that result type.
2444
2445  - If there are a multiple direct results, the C result type should be
2446    a struct type with the exact layout of a tuple of those results.
2447
2448- Parameters classified as indirect by high-level lowering should be
2449  represented as parameters of pointer type.
2450
2451- Parameters classified as direct by high-level lowering should be
2452  omitted if they are empty types; otherwise, they should be represented
2453  as a parameter type with a layout exactly matching the layout of the
2454  Swift parameter type.
2455
2456- The context parameter, if present, should be represented as a trailing
2457  parameter with the ``swift_context`` attribute.
2458
2459- The error result parameter, if present, should be represented as a
2460  trailing parameter (always following a context parameter) with the
2461  ``swift_error_result`` attribute.
2462
2463``swiftcall`` does not support variadic arguments or unprototyped functions.
2464
2465The parameter ABI treatment attributes are aspects of the function type.
2466A function type which which applies an ABI treatment attribute to a
2467parameter is a different type from an otherwise-identical function type
2468that does not.  A single parameter may not have multiple ABI treatment
2469attributes.
2470
2471Support for this feature is target-dependent, although it should be
2472supported on every target that Swift supports.  Query for this support
2473with ``__has_attribute(swiftcall)``.  This implies support for the
2474``swift_context``, ``swift_error_result``, and ``swift_indirect_result``
2475attributes.
2476
2477
2478thread
2479------
2480.. csv-table:: Supported Syntaxes
2481   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
2482
2483   "","","","X","", "", ""
2484
2485The ``__declspec(thread)`` attribute declares a variable with thread local
2486storage.  It is available under the ``-fms-extensions`` flag for MSVC
2487compatibility.  See the documentation for `__declspec(thread)`_ on MSDN.
2488
2489.. _`__declspec(thread)`: http://msdn.microsoft.com/en-us/library/9w1sdazb.aspx
2490
2491In Clang, ``__declspec(thread)`` is generally equivalent in functionality to the
2492GNU ``__thread`` keyword.  The variable must not have a destructor and must have
2493a constant initializer, if any.  The attribute only applies to variables
2494declared with static storage duration, such as globals, class static data
2495members, and static locals.
2496
2497
2498tls_model (gnu::tls_model)
2499--------------------------
2500.. csv-table:: Supported Syntaxes
2501   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
2502
2503   "X","X","","","", "", "X"
2504
2505The ``tls_model`` attribute allows you to specify which thread-local storage
2506model to use. It accepts the following strings:
2507
2508* global-dynamic
2509* local-dynamic
2510* initial-exec
2511* local-exec
2512
2513TLS models are mutually exclusive.
2514
2515
2516trivial_abi (clang::trivial_abi)
2517--------------------------------
2518.. csv-table:: Supported Syntaxes
2519   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
2520
2521   "X","X","","","", "", "X"
2522
2523The ``trivial_abi`` attribute can be applied to a C++ class, struct, or union.
2524It instructs the compiler to pass and return the type using the C ABI for the
2525underlying type when the type would otherwise be considered non-trivial for the
2526purpose of calls.
2527A class annotated with `trivial_abi` can have non-trivial destructors or copy/move constructors without automatically becoming non-trivial for the purposes of calls. For example:
2528
2529  .. code-block:: c++
2530
2531    // A is trivial for the purposes of calls because `trivial_abi` makes the
2532    // user-provided special functions trivial.
2533    struct __attribute__((trivial_abi)) A {
2534      ~A();
2535      A(const A &);
2536      A(A &&);
2537      int x;
2538    };
2539
2540    // B's destructor and copy/move constructor are considered trivial for the
2541    // purpose of calls because A is trivial.
2542    struct B {
2543      A a;
2544    };
2545
2546If a type is trivial for the purposes of calls, has a non-trivial destructor,
2547and is passed as an argument by value, the convention is that the callee will
2548destroy the object before returning.
2549
2550Attribute ``trivial_abi`` has no effect in the following cases:
2551
2552- The class directly declares a virtual base or virtual methods.
2553- The class has a base class that is non-trivial for the purposes of calls.
2554- The class has a non-static data member whose type is non-trivial for the purposes of calls, which includes:
2555
2556  - classes that are non-trivial for the purposes of calls
2557  - __weak-qualified types in Objective-C++
2558  - arrays of any of the above
2559
2560
2561Type Attributes
2562===============
2563
2564
2565__single_inhertiance, __multiple_inheritance, __virtual_inheritance
2566-------------------------------------------------------------------
2567.. csv-table:: Supported Syntaxes
2568   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
2569
2570   "","","","","X", "", ""
2571
2572This collection of keywords is enabled under ``-fms-extensions`` and controls
2573the pointer-to-member representation used on ``*-*-win32`` targets.
2574
2575The ``*-*-win32`` targets utilize a pointer-to-member representation which
2576varies in size and alignment depending on the definition of the underlying
2577class.
2578
2579However, this is problematic when a forward declaration is only available and
2580no definition has been made yet.  In such cases, Clang is forced to utilize the
2581most general representation that is available to it.
2582
2583These keywords make it possible to use a pointer-to-member representation other
2584than the most general one regardless of whether or not the definition will ever
2585be present in the current translation unit.
2586
2587This family of keywords belong between the ``class-key`` and ``class-name``:
2588
2589.. code-block:: c++
2590
2591  struct __single_inheritance S;
2592  int S::*i;
2593  struct S {};
2594
2595This keyword can be applied to class templates but only has an effect when used
2596on full specializations:
2597
2598.. code-block:: c++
2599
2600  template <typename T, typename U> struct __single_inheritance A; // warning: inheritance model ignored on primary template
2601  template <typename T> struct __multiple_inheritance A<T, T>; // warning: inheritance model ignored on partial specialization
2602  template <> struct __single_inheritance A<int, float>;
2603
2604Note that choosing an inheritance model less general than strictly necessary is
2605an error:
2606
2607.. code-block:: c++
2608
2609  struct __multiple_inheritance S; // error: inheritance model does not match definition
2610  int S::*i;
2611  struct S {};
2612
2613
2614align_value
2615-----------
2616.. csv-table:: Supported Syntaxes
2617   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
2618
2619   "X","","","","", "", "X"
2620
2621The align_value attribute can be added to the typedef of a pointer type or the
2622declaration of a variable of pointer or reference type. It specifies that the
2623pointer will point to, or the reference will bind to, only objects with at
2624least the provided alignment. This alignment value must be some positive power
2625of 2.
2626
2627   .. code-block:: c
2628
2629     typedef double * aligned_double_ptr __attribute__((align_value(64)));
2630     void foo(double & x  __attribute__((align_value(128)),
2631              aligned_double_ptr y) { ... }
2632
2633If the pointer value does not have the specified alignment at runtime, the
2634behavior of the program is undefined.
2635
2636
2637empty_bases
2638-----------
2639.. csv-table:: Supported Syntaxes
2640   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
2641
2642   "","","","X","", "", ""
2643
2644The empty_bases attribute permits the compiler to utilize the
2645empty-base-optimization more frequently.
2646This attribute only applies to struct, class, and union types.
2647It is only supported when using the Microsoft C++ ABI.
2648
2649
2650enum_extensibility (clang::enum_extensibility, clang::enum_extensibility)
2651-------------------------------------------------------------------------
2652.. csv-table:: Supported Syntaxes
2653   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
2654
2655   "X","X","X","","", "", "X"
2656
2657Attribute ``enum_extensibility`` is used to distinguish between enum definitions
2658that are extensible and those that are not. The attribute can take either
2659``closed`` or ``open`` as an argument. ``closed`` indicates a variable of the
2660enum type takes a value that corresponds to one of the enumerators listed in the
2661enum definition or, when the enum is annotated with ``flag_enum``, a value that
2662can be constructed using values corresponding to the enumerators. ``open``
2663indicates a variable of the enum type can take any values allowed by the
2664standard and instructs clang to be more lenient when issuing warnings.
2665
2666.. code-block:: c
2667
2668  enum __attribute__((enum_extensibility(closed))) ClosedEnum {
2669    A0, A1
2670  };
2671
2672  enum __attribute__((enum_extensibility(open))) OpenEnum {
2673    B0, B1
2674  };
2675
2676  enum __attribute__((enum_extensibility(closed),flag_enum)) ClosedFlagEnum {
2677    C0 = 1 << 0, C1 = 1 << 1
2678  };
2679
2680  enum __attribute__((enum_extensibility(open),flag_enum)) OpenFlagEnum {
2681    D0 = 1 << 0, D1 = 1 << 1
2682  };
2683
2684  void foo1() {
2685    enum ClosedEnum ce;
2686    enum OpenEnum oe;
2687    enum ClosedFlagEnum cfe;
2688    enum OpenFlagEnum ofe;
2689
2690    ce = A1;           // no warnings
2691    ce = 100;          // warning issued
2692    oe = B1;           // no warnings
2693    oe = 100;          // no warnings
2694    cfe = C0 | C1;     // no warnings
2695    cfe = C0 | C1 | 4; // warning issued
2696    ofe = D0 | D1;     // no warnings
2697    ofe = D0 | D1 | 4; // no warnings
2698  }
2699
2700
2701flag_enum (clang::flag_enum, clang::flag_enum)
2702----------------------------------------------
2703.. csv-table:: Supported Syntaxes
2704   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
2705
2706   "X","X","X","","", "", "X"
2707
2708This attribute can be added to an enumerator to signal to the compiler that it
2709is intended to be used as a flag type. This will cause the compiler to assume
2710that the range of the type includes all of the values that you can get by
2711manipulating bits of the enumerator when issuing warnings.
2712
2713
2714layout_version
2715--------------
2716.. csv-table:: Supported Syntaxes
2717   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
2718
2719   "","","","X","", "", ""
2720
2721The layout_version attribute requests that the compiler utilize the class
2722layout rules of a particular compiler version.
2723This attribute only applies to struct, class, and union types.
2724It is only supported when using the Microsoft C++ ABI.
2725
2726
2727lto_visibility_public (clang::lto_visibility_public, clang::lto_visibility_public)
2728----------------------------------------------------------------------------------
2729.. csv-table:: Supported Syntaxes
2730   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
2731
2732   "X","X","X","","", "", "X"
2733
2734See :doc:`LTOVisibility`.
2735
2736
2737novtable
2738--------
2739.. csv-table:: Supported Syntaxes
2740   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
2741
2742   "","","","X","", "", ""
2743
2744This attribute can be added to a class declaration or definition to signal to
2745the compiler that constructors and destructors will not reference the virtual
2746function table. It is only supported when using the Microsoft C++ ABI.
2747
2748
2749objc_subclassing_restricted (clang::objc_subclassing_restricted, clang::objc_subclassing_restricted)
2750----------------------------------------------------------------------------------------------------
2751.. csv-table:: Supported Syntaxes
2752   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
2753
2754   "X","X","X","","", "", "X"
2755
2756This attribute can be added to an Objective-C ``@interface`` declaration to
2757ensure that this class cannot be subclassed.
2758
2759
2760selectany (gnu::selectany)
2761--------------------------
2762.. csv-table:: Supported Syntaxes
2763   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
2764
2765   "X","X","","X","", "", ""
2766
2767This attribute appertains to a global symbol, causing it to have a weak
2768definition (
2769`linkonce <https://llvm.org/docs/LangRef.html#linkage-types>`_
2770), allowing the linker to select any definition.
2771
2772For more information see
2773`gcc documentation <https://gcc.gnu.org/onlinedocs/gcc-7.2.0/gcc/Microsoft-Windows-Variable-Attributes.html>`_
2774or `msvc documentation <https://docs.microsoft.com/pl-pl/cpp/cpp/selectany>`_.
2775
2776
2777transparent_union (gnu::transparent_union)
2778------------------------------------------
2779.. csv-table:: Supported Syntaxes
2780   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
2781
2782   "X","X","","","", "", ""
2783
2784This attribute can be applied to a union to change the behaviour of calls to
2785functions that have an argument with a transparent union type. The compiler
2786behaviour is changed in the following manner:
2787
2788- A value whose type is any member of the transparent union can be passed as an
2789  argument without the need to cast that value.
2790
2791- The argument is passed to the function using the calling convention of the
2792  first member of the transparent union. Consequently, all the members of the
2793  transparent union should have the same calling convention as its first member.
2794
2795Transparent unions are not supported in C++.
2796
2797
2798Statement Attributes
2799====================
2800
2801
2802#pragma clang loop
2803------------------
2804.. csv-table:: Supported Syntaxes
2805   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
2806
2807   "","","","","", "X", ""
2808
2809The ``#pragma clang loop`` directive allows loop optimization hints to be
2810specified for the subsequent loop. The directive allows vectorization,
2811interleaving, and unrolling to be enabled or disabled. Vector width as well
2812as interleave and unrolling count can be manually specified. See
2813`language extensions
2814<http://clang.llvm.org/docs/LanguageExtensions.html#extensions-for-loop-hint-optimizations>`_
2815for details.
2816
2817
2818#pragma unroll, #pragma nounroll
2819--------------------------------
2820.. csv-table:: Supported Syntaxes
2821   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
2822
2823   "","","","","", "X", ""
2824
2825Loop unrolling optimization hints can be specified with ``#pragma unroll`` and
2826``#pragma nounroll``. The pragma is placed immediately before a for, while,
2827do-while, or c++11 range-based for loop.
2828
2829Specifying ``#pragma unroll`` without a parameter directs the loop unroller to
2830attempt to fully unroll the loop if the trip count is known at compile time and
2831attempt to partially unroll the loop if the trip count is not known at compile
2832time:
2833
2834.. code-block:: c++
2835
2836  #pragma unroll
2837  for (...) {
2838    ...
2839  }
2840
2841Specifying the optional parameter, ``#pragma unroll _value_``, directs the
2842unroller to unroll the loop ``_value_`` times.  The parameter may optionally be
2843enclosed in parentheses:
2844
2845.. code-block:: c++
2846
2847  #pragma unroll 16
2848  for (...) {
2849    ...
2850  }
2851
2852  #pragma unroll(16)
2853  for (...) {
2854    ...
2855  }
2856
2857Specifying ``#pragma nounroll`` indicates that the loop should not be unrolled:
2858
2859.. code-block:: c++
2860
2861  #pragma nounroll
2862  for (...) {
2863    ...
2864  }
2865
2866``#pragma unroll`` and ``#pragma unroll _value_`` have identical semantics to
2867``#pragma clang loop unroll(full)`` and
2868``#pragma clang loop unroll_count(_value_)`` respectively. ``#pragma nounroll``
2869is equivalent to ``#pragma clang loop unroll(disable)``.  See
2870`language extensions
2871<http://clang.llvm.org/docs/LanguageExtensions.html#extensions-for-loop-hint-optimizations>`_
2872for further details including limitations of the unroll hints.
2873
2874
2875__attribute__((intel_reqd_sub_group_size))
2876------------------------------------------
2877.. csv-table:: Supported Syntaxes
2878   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
2879
2880   "X","","","","", "", "X"
2881
2882The optional attribute intel_reqd_sub_group_size can be used to indicate that
2883the kernel must be compiled and executed with the specified subgroup size. When
2884this attribute is present, get_max_sub_group_size() is guaranteed to return the
2885specified integer value. This is important for the correctness of many subgroup
2886algorithms, and in some cases may be used by the compiler to generate more optimal
2887code. See `cl_intel_required_subgroup_size
2888<https://www.khronos.org/registry/OpenCL/extensions/intel/cl_intel_required_subgroup_size.txt>`
2889for details.
2890
2891
2892__attribute__((opencl_unroll_hint))
2893-----------------------------------
2894.. csv-table:: Supported Syntaxes
2895   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
2896
2897   "X","","","","", "", ""
2898
2899The opencl_unroll_hint attribute qualifier can be used to specify that a loop
2900(for, while and do loops) can be unrolled. This attribute qualifier can be
2901used to specify full unrolling or partial unrolling by a specified amount.
2902This is a compiler hint and the compiler may ignore this directive. See
2903`OpenCL v2.0 <https://www.khronos.org/registry/cl/specs/opencl-2.0.pdf>`_
2904s6.11.5 for details.
2905
2906
2907__read_only, __write_only, __read_write (read_only, write_only, read_write)
2908---------------------------------------------------------------------------
2909.. csv-table:: Supported Syntaxes
2910   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
2911
2912   "","","","","X", "", ""
2913
2914The access qualifiers must be used with image object arguments or pipe arguments
2915to declare if they are being read or written by a kernel or function.
2916
2917The read_only/__read_only, write_only/__write_only and read_write/__read_write
2918names are reserved for use as access qualifiers and shall not be used otherwise.
2919
2920.. code-block:: c
2921
2922  kernel void
2923  foo (read_only image2d_t imageA,
2924       write_only image2d_t imageB) {
2925    ...
2926  }
2927
2928In the above example imageA is a read-only 2D image object, and imageB is a
2929write-only 2D image object.
2930
2931The read_write (or __read_write) qualifier can not be used with pipe.
2932
2933More details can be found in the OpenCL C language Spec v2.0, Section 6.6.
2934
2935
2936fallthrough, clang::fallthrough
2937-------------------------------
2938.. csv-table:: Supported Syntaxes
2939   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
2940
2941   "","X","X","","", "", ""
2942
2943The ``fallthrough`` (or ``clang::fallthrough``) attribute is used
2944to annotate intentional fall-through
2945between switch labels.  It can only be applied to a null statement placed at a
2946point of execution between any statement and the next switch label.  It is
2947common to mark these places with a specific comment, but this attribute is
2948meant to replace comments with a more strict annotation, which can be checked
2949by the compiler.  This attribute doesn't change semantics of the code and can
2950be used wherever an intended fall-through occurs.  It is designed to mimic
2951control-flow statements like ``break;``, so it can be placed in most places
2952where ``break;`` can, but only if there are no statements on the execution path
2953between it and the next switch label.
2954
2955By default, Clang does not warn on unannotated fallthrough from one ``switch``
2956case to another. Diagnostics on fallthrough without a corresponding annotation
2957can be enabled with the ``-Wimplicit-fallthrough`` argument.
2958
2959Here is an example:
2960
2961.. code-block:: c++
2962
2963  // compile with -Wimplicit-fallthrough
2964  switch (n) {
2965  case 22:
2966  case 33:  // no warning: no statements between case labels
2967    f();
2968  case 44:  // warning: unannotated fall-through
2969    g();
2970    [[clang::fallthrough]];
2971  case 55:  // no warning
2972    if (x) {
2973      h();
2974      break;
2975    }
2976    else {
2977      i();
2978      [[clang::fallthrough]];
2979    }
2980  case 66:  // no warning
2981    p();
2982    [[clang::fallthrough]]; // warning: fallthrough annotation does not
2983                            //          directly precede case label
2984    q();
2985  case 77:  // warning: unannotated fall-through
2986    r();
2987  }
2988
2989
2990suppress (gsl::suppress)
2991------------------------
2992.. csv-table:: Supported Syntaxes
2993   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
2994
2995   "","X","","","", "", ""
2996
2997The ``[[gsl::suppress]]`` attribute suppresses specific
2998clang-tidy diagnostics for rules of the `C++ Core Guidelines`_ in a portable
2999way. The attribute can be attached to declarations, statements, and at
3000namespace scope.
3001
3002.. code-block:: c++
3003
3004  [[gsl::suppress("Rh-public")]]
3005  void f_() {
3006    int *p;
3007    [[gsl::suppress("type")]] {
3008      p = reinterpret_cast<int*>(7);
3009    }
3010  }
3011  namespace N {
3012    [[clang::suppress("type", "bounds")]];
3013    ...
3014  }
3015
3016.. _`C++ Core Guidelines`: https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#inforce-enforcement
3017
3018
3019AMD GPU Attributes
3020==================
3021
3022
3023amdgpu_flat_work_group_size (clang::amdgpu_flat_work_group_size)
3024----------------------------------------------------------------
3025.. csv-table:: Supported Syntaxes
3026   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
3027
3028   "X","X","","","", "", "X"
3029
3030The flat work-group size is the number of work-items in the work-group size
3031specified when the kernel is dispatched. It is the product of the sizes of the
3032x, y, and z dimension of the work-group.
3033
3034Clang supports the
3035``__attribute__((amdgpu_flat_work_group_size(<min>, <max>)))`` attribute for the
3036AMDGPU target. This attribute may be attached to a kernel function definition
3037and is an optimization hint.
3038
3039``<min>`` parameter specifies the minimum flat work-group size, and ``<max>``
3040parameter specifies the maximum flat work-group size (must be greater than
3041``<min>``) to which all dispatches of the kernel will conform. Passing ``0, 0``
3042as ``<min>, <max>`` implies the default behavior (``128, 256``).
3043
3044If specified, the AMDGPU target backend might be able to produce better machine
3045code for barriers and perform scratch promotion by estimating available group
3046segment size.
3047
3048An error will be given if:
3049  - Specified values violate subtarget specifications;
3050  - Specified values are not compatible with values provided through other
3051    attributes.
3052
3053
3054amdgpu_num_sgpr (clang::amdgpu_num_sgpr)
3055----------------------------------------
3056.. csv-table:: Supported Syntaxes
3057   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
3058
3059   "X","X","","","", "", "X"
3060
3061Clang supports the ``__attribute__((amdgpu_num_sgpr(<num_sgpr>)))`` and
3062``__attribute__((amdgpu_num_vgpr(<num_vgpr>)))`` attributes for the AMDGPU
3063target. These attributes may be attached to a kernel function definition and are
3064an optimization hint.
3065
3066If these attributes are specified, then the AMDGPU target backend will attempt
3067to limit the number of SGPRs and/or VGPRs used to the specified value(s). The
3068number of used SGPRs and/or VGPRs may further be rounded up to satisfy the
3069allocation requirements or constraints of the subtarget. Passing ``0`` as
3070``num_sgpr`` and/or ``num_vgpr`` implies the default behavior (no limits).
3071
3072These attributes can be used to test the AMDGPU target backend. It is
3073recommended that the ``amdgpu_waves_per_eu`` attribute be used to control
3074resources such as SGPRs and VGPRs since it is aware of the limits for different
3075subtargets.
3076
3077An error will be given if:
3078  - Specified values violate subtarget specifications;
3079  - Specified values are not compatible with values provided through other
3080    attributes;
3081  - The AMDGPU target backend is unable to create machine code that can meet the
3082    request.
3083
3084
3085amdgpu_num_vgpr (clang::amdgpu_num_vgpr)
3086----------------------------------------
3087.. csv-table:: Supported Syntaxes
3088   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
3089
3090   "X","X","","","", "", "X"
3091
3092Clang supports the ``__attribute__((amdgpu_num_sgpr(<num_sgpr>)))`` and
3093``__attribute__((amdgpu_num_vgpr(<num_vgpr>)))`` attributes for the AMDGPU
3094target. These attributes may be attached to a kernel function definition and are
3095an optimization hint.
3096
3097If these attributes are specified, then the AMDGPU target backend will attempt
3098to limit the number of SGPRs and/or VGPRs used to the specified value(s). The
3099number of used SGPRs and/or VGPRs may further be rounded up to satisfy the
3100allocation requirements or constraints of the subtarget. Passing ``0`` as
3101``num_sgpr`` and/or ``num_vgpr`` implies the default behavior (no limits).
3102
3103These attributes can be used to test the AMDGPU target backend. It is
3104recommended that the ``amdgpu_waves_per_eu`` attribute be used to control
3105resources such as SGPRs and VGPRs since it is aware of the limits for different
3106subtargets.
3107
3108An error will be given if:
3109  - Specified values violate subtarget specifications;
3110  - Specified values are not compatible with values provided through other
3111    attributes;
3112  - The AMDGPU target backend is unable to create machine code that can meet the
3113    request.
3114
3115
3116amdgpu_waves_per_eu (clang::amdgpu_waves_per_eu)
3117------------------------------------------------
3118.. csv-table:: Supported Syntaxes
3119   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
3120
3121   "X","X","","","", "", "X"
3122
3123A compute unit (CU) is responsible for executing the wavefronts of a work-group.
3124It is composed of one or more execution units (EU), which are responsible for
3125executing the wavefronts. An EU can have enough resources to maintain the state
3126of more than one executing wavefront. This allows an EU to hide latency by
3127switching between wavefronts in a similar way to symmetric multithreading on a
3128CPU. In order to allow the state for multiple wavefronts to fit on an EU, the
3129resources used by a single wavefront have to be limited. For example, the number
3130of SGPRs and VGPRs. Limiting such resources can allow greater latency hiding,
3131but can result in having to spill some register state to memory.
3132
3133Clang supports the ``__attribute__((amdgpu_waves_per_eu(<min>[, <max>])))``
3134attribute for the AMDGPU target. This attribute may be attached to a kernel
3135function definition and is an optimization hint.
3136
3137``<min>`` parameter specifies the requested minimum number of waves per EU, and
3138*optional* ``<max>`` parameter specifies the requested maximum number of waves
3139per EU (must be greater than ``<min>`` if specified). If ``<max>`` is omitted,
3140then there is no restriction on the maximum number of waves per EU other than
3141the one dictated by the hardware for which the kernel is compiled. Passing
3142``0, 0`` as ``<min>, <max>`` implies the default behavior (no limits).
3143
3144If specified, this attribute allows an advanced developer to tune the number of
3145wavefronts that are capable of fitting within the resources of an EU. The AMDGPU
3146target backend can use this information to limit resources, such as number of
3147SGPRs, number of VGPRs, size of available group and private memory segments, in
3148such a way that guarantees that at least ``<min>`` wavefronts and at most
3149``<max>`` wavefronts are able to fit within the resources of an EU. Requesting
3150more wavefronts can hide memory latency but limits available registers which
3151can result in spilling. Requesting fewer wavefronts can help reduce cache
3152thrashing, but can reduce memory latency hiding.
3153
3154This attribute controls the machine code generated by the AMDGPU target backend
3155to ensure it is capable of meeting the requested values. However, when the
3156kernel is executed, there may be other reasons that prevent meeting the request,
3157for example, there may be wavefronts from other kernels executing on the EU.
3158
3159An error will be given if:
3160  - Specified values violate subtarget specifications;
3161  - Specified values are not compatible with values provided through other
3162    attributes;
3163  - The AMDGPU target backend is unable to create machine code that can meet the
3164    request.
3165
3166
3167Calling Conventions
3168===================
3169Clang supports several different calling conventions, depending on the target
3170platform and architecture. The calling convention used for a function determines
3171how parameters are passed, how results are returned to the caller, and other
3172low-level details of calling a function.
3173
3174fastcall (gnu::fastcall, __fastcall, _fastcall)
3175-----------------------------------------------
3176.. csv-table:: Supported Syntaxes
3177   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
3178
3179   "X","X","","","X", "", ""
3180
3181On 32-bit x86 targets, this attribute changes the calling convention of a
3182function to use ECX and EDX as register parameters and clear parameters off of
3183the stack on return. This convention does not support variadic calls or
3184unprototyped functions in C, and has no effect on x86_64 targets. This calling
3185convention is supported primarily for compatibility with existing code. Users
3186seeking register parameters should use the ``regparm`` attribute, which does
3187not require callee-cleanup.  See the documentation for `__fastcall`_ on MSDN.
3188
3189.. _`__fastcall`: http://msdn.microsoft.com/en-us/library/6xa169sk.aspx
3190
3191
3192ms_abi (gnu::ms_abi)
3193--------------------
3194.. csv-table:: Supported Syntaxes
3195   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
3196
3197   "X","X","","","", "", ""
3198
3199On non-Windows x86_64 targets, this attribute changes the calling convention of
3200a function to match the default convention used on Windows x86_64. This
3201attribute has no effect on Windows targets or non-x86_64 targets.
3202
3203
3204pcs (gnu::pcs)
3205--------------
3206.. csv-table:: Supported Syntaxes
3207   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
3208
3209   "X","X","","","", "", ""
3210
3211On ARM targets, this attribute can be used to select calling conventions
3212similar to ``stdcall`` on x86. Valid parameter values are "aapcs" and
3213"aapcs-vfp".
3214
3215
3216preserve_all (clang::preserve_all, clang::preserve_all)
3217-------------------------------------------------------
3218.. csv-table:: Supported Syntaxes
3219   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
3220
3221   "X","X","X","","", "", ""
3222
3223On X86-64 and AArch64 targets, this attribute changes the calling convention of
3224a function. The ``preserve_all`` calling convention attempts to make the code
3225in the caller even less intrusive than the ``preserve_most`` calling convention.
3226This calling convention also behaves identical to the ``C`` calling convention
3227on how arguments and return values are passed, but it uses a different set of
3228caller/callee-saved registers. This removes the burden of saving and
3229recovering a large register set before and after the call in the caller. If
3230the arguments are passed in callee-saved registers, then they will be
3231preserved by the callee across the call. This doesn't apply for values
3232returned in callee-saved registers.
3233
3234- On X86-64 the callee preserves all general purpose registers, except for
3235  R11. R11 can be used as a scratch register. Furthermore it also preserves
3236  all floating-point registers (XMMs/YMMs).
3237
3238The idea behind this convention is to support calls to runtime functions
3239that don't need to call out to any other functions.
3240
3241This calling convention, like the ``preserve_most`` calling convention, will be
3242used by a future version of the Objective-C runtime and should be considered
3243experimental at this time.
3244
3245
3246preserve_most (clang::preserve_most, clang::preserve_most)
3247----------------------------------------------------------
3248.. csv-table:: Supported Syntaxes
3249   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
3250
3251   "X","X","X","","", "", ""
3252
3253On X86-64 and AArch64 targets, this attribute changes the calling convention of
3254a function. The ``preserve_most`` calling convention attempts to make the code
3255in the caller as unintrusive as possible. This convention behaves identically
3256to the ``C`` calling convention on how arguments and return values are passed,
3257but it uses a different set of caller/callee-saved registers. This alleviates
3258the burden of saving and recovering a large register set before and after the
3259call in the caller. If the arguments are passed in callee-saved registers,
3260then they will be preserved by the callee across the call. This doesn't
3261apply for values returned in callee-saved registers.
3262
3263- On X86-64 the callee preserves all general purpose registers, except for
3264  R11. R11 can be used as a scratch register. Floating-point registers
3265  (XMMs/YMMs) are not preserved and need to be saved by the caller.
3266
3267The idea behind this convention is to support calls to runtime functions
3268that have a hot path and a cold path. The hot path is usually a small piece
3269of code that doesn't use many registers. The cold path might need to call out to
3270another function and therefore only needs to preserve the caller-saved
3271registers, which haven't already been saved by the caller. The
3272`preserve_most` calling convention is very similar to the ``cold`` calling
3273convention in terms of caller/callee-saved registers, but they are used for
3274different types of function calls. ``coldcc`` is for function calls that are
3275rarely executed, whereas `preserve_most` function calls are intended to be
3276on the hot path and definitely executed a lot. Furthermore ``preserve_most``
3277doesn't prevent the inliner from inlining the function call.
3278
3279This calling convention will be used by a future version of the Objective-C
3280runtime and should therefore still be considered experimental at this time.
3281Although this convention was created to optimize certain runtime calls to
3282the Objective-C runtime, it is not limited to this runtime and might be used
3283by other runtimes in the future too. The current implementation only
3284supports X86-64 and AArch64, but the intention is to support more architectures
3285in the future.
3286
3287
3288regcall (gnu::regcall, __regcall)
3289---------------------------------
3290.. csv-table:: Supported Syntaxes
3291   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
3292
3293   "X","X","","","X", "", ""
3294
3295On x86 targets, this attribute changes the calling convention to
3296`__regcall`_ convention. This convention aims to pass as many arguments
3297as possible in registers. It also tries to utilize registers for the
3298return value whenever it is possible.
3299
3300.. _`__regcall`: https://software.intel.com/en-us/node/693069
3301
3302
3303regparm (gnu::regparm)
3304----------------------
3305.. csv-table:: Supported Syntaxes
3306   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
3307
3308   "X","X","","","", "", ""
3309
3310On 32-bit x86 targets, the regparm attribute causes the compiler to pass
3311the first three integer parameters in EAX, EDX, and ECX instead of on the
3312stack. This attribute has no effect on variadic functions, and all parameters
3313are passed via the stack as normal.
3314
3315
3316stdcall (gnu::stdcall, __stdcall, _stdcall)
3317-------------------------------------------
3318.. csv-table:: Supported Syntaxes
3319   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
3320
3321   "X","X","","","X", "", ""
3322
3323On 32-bit x86 targets, this attribute changes the calling convention of a
3324function to clear parameters off of the stack on return. This convention does
3325not support variadic calls or unprototyped functions in C, and has no effect on
3326x86_64 targets. This calling convention is used widely by the Windows API and
3327COM applications.  See the documentation for `__stdcall`_ on MSDN.
3328
3329.. _`__stdcall`: http://msdn.microsoft.com/en-us/library/zxk0tw93.aspx
3330
3331
3332thiscall (gnu::thiscall, __thiscall, _thiscall)
3333-----------------------------------------------
3334.. csv-table:: Supported Syntaxes
3335   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
3336
3337   "X","X","","","X", "", ""
3338
3339On 32-bit x86 targets, this attribute changes the calling convention of a
3340function to use ECX for the first parameter (typically the implicit ``this``
3341parameter of C++ methods) and clear parameters off of the stack on return. This
3342convention does not support variadic calls or unprototyped functions in C, and
3343has no effect on x86_64 targets. See the documentation for `__thiscall`_ on
3344MSDN.
3345
3346.. _`__thiscall`: http://msdn.microsoft.com/en-us/library/ek8tkfbw.aspx
3347
3348
3349vectorcall (clang::vectorcall, clang::vectorcall, __vectorcall, _vectorcall)
3350----------------------------------------------------------------------------
3351.. csv-table:: Supported Syntaxes
3352   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
3353
3354   "X","X","X","","X", "", ""
3355
3356On 32-bit x86 *and* x86_64 targets, this attribute changes the calling
3357convention of a function to pass vector parameters in SSE registers.
3358
3359On 32-bit x86 targets, this calling convention is similar to ``__fastcall``.
3360The first two integer parameters are passed in ECX and EDX. Subsequent integer
3361parameters are passed in memory, and callee clears the stack.  On x86_64
3362targets, the callee does *not* clear the stack, and integer parameters are
3363passed in RCX, RDX, R8, and R9 as is done for the default Windows x64 calling
3364convention.
3365
3366On both 32-bit x86 and x86_64 targets, vector and floating point arguments are
3367passed in XMM0-XMM5. Homogeneous vector aggregates of up to four elements are
3368passed in sequential SSE registers if enough are available. If AVX is enabled,
3369256 bit vectors are passed in YMM0-YMM5. Any vector or aggregate type that
3370cannot be passed in registers for any reason is passed by reference, which
3371allows the caller to align the parameter memory.
3372
3373See the documentation for `__vectorcall`_ on MSDN for more details.
3374
3375.. _`__vectorcall`: http://msdn.microsoft.com/en-us/library/dn375768.aspx
3376
3377
3378Consumed Annotation Checking
3379============================
3380Clang supports additional attributes for checking basic resource management
3381properties, specifically for unique objects that have a single owning reference.
3382The following attributes are currently supported, although **the implementation
3383for these annotations is currently in development and are subject to change.**
3384
3385callable_when (clang::callable_when)
3386------------------------------------
3387.. csv-table:: Supported Syntaxes
3388   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
3389
3390   "X","X","","","", "", "X"
3391
3392Use ``__attribute__((callable_when(...)))`` to indicate what states a method
3393may be called in.  Valid states are unconsumed, consumed, or unknown.  Each
3394argument to this attribute must be a quoted string.  E.g.:
3395
3396``__attribute__((callable_when("unconsumed", "unknown")))``
3397
3398
3399consumable (clang::consumable)
3400------------------------------
3401.. csv-table:: Supported Syntaxes
3402   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
3403
3404   "X","X","","","", "", "X"
3405
3406Each ``class`` that uses any of the typestate annotations must first be marked
3407using the ``consumable`` attribute.  Failure to do so will result in a warning.
3408
3409This attribute accepts a single parameter that must be one of the following:
3410``unknown``, ``consumed``, or ``unconsumed``.
3411
3412
3413param_typestate (clang::param_typestate)
3414----------------------------------------
3415.. csv-table:: Supported Syntaxes
3416   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
3417
3418   "X","X","","","", "", "X"
3419
3420This attribute specifies expectations about function parameters.  Calls to an
3421function with annotated parameters will issue a warning if the corresponding
3422argument isn't in the expected state.  The attribute is also used to set the
3423initial state of the parameter when analyzing the function's body.
3424
3425
3426return_typestate (clang::return_typestate)
3427------------------------------------------
3428.. csv-table:: Supported Syntaxes
3429   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
3430
3431   "X","X","","","", "", "X"
3432
3433The ``return_typestate`` attribute can be applied to functions or parameters.
3434When applied to a function the attribute specifies the state of the returned
3435value.  The function's body is checked to ensure that it always returns a value
3436in the specified state.  On the caller side, values returned by the annotated
3437function are initialized to the given state.
3438
3439When applied to a function parameter it modifies the state of an argument after
3440a call to the function returns.  The function's body is checked to ensure that
3441the parameter is in the expected state before returning.
3442
3443
3444set_typestate (clang::set_typestate)
3445------------------------------------
3446.. csv-table:: Supported Syntaxes
3447   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
3448
3449   "X","X","","","", "", "X"
3450
3451Annotate methods that transition an object into a new state with
3452``__attribute__((set_typestate(new_state)))``.  The new state must be
3453unconsumed, consumed, or unknown.
3454
3455
3456test_typestate (clang::test_typestate)
3457--------------------------------------
3458.. csv-table:: Supported Syntaxes
3459   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
3460
3461   "X","X","","","", "", "X"
3462
3463Use ``__attribute__((test_typestate(tested_state)))`` to indicate that a method
3464returns true if the object is in the specified state..
3465
3466
3467Type Safety Checking
3468====================
3469Clang supports additional attributes to enable checking type safety properties
3470that can't be enforced by the C type system. To see warnings produced by these
3471checks, ensure that -Wtype-safety is enabled. Use cases include:
3472
3473* MPI library implementations, where these attributes enable checking that
3474  the buffer type matches the passed ``MPI_Datatype``;
3475* for HDF5 library there is a similar use case to MPI;
3476* checking types of variadic functions' arguments for functions like
3477  ``fcntl()`` and ``ioctl()``.
3478
3479You can detect support for these attributes with ``__has_attribute()``.  For
3480example:
3481
3482.. code-block:: c++
3483
3484  #if defined(__has_attribute)
3485  #  if __has_attribute(argument_with_type_tag) && \
3486        __has_attribute(pointer_with_type_tag) && \
3487        __has_attribute(type_tag_for_datatype)
3488  #    define ATTR_MPI_PWT(buffer_idx, type_idx) __attribute__((pointer_with_type_tag(mpi,buffer_idx,type_idx)))
3489  /* ... other macros ...  */
3490  #  endif
3491  #endif
3492
3493  #if !defined(ATTR_MPI_PWT)
3494  # define ATTR_MPI_PWT(buffer_idx, type_idx)
3495  #endif
3496
3497  int MPI_Send(void *buf, int count, MPI_Datatype datatype /*, other args omitted */)
3498      ATTR_MPI_PWT(1,3);
3499
3500argument_with_type_tag
3501----------------------
3502.. csv-table:: Supported Syntaxes
3503   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
3504
3505   "X","X","X","","", "", ""
3506
3507Use ``__attribute__((argument_with_type_tag(arg_kind, arg_idx,
3508type_tag_idx)))`` on a function declaration to specify that the function
3509accepts a type tag that determines the type of some other argument.
3510
3511This attribute is primarily useful for checking arguments of variadic functions
3512(``pointer_with_type_tag`` can be used in most non-variadic cases).
3513
3514In the attribute prototype above:
3515  * ``arg_kind`` is an identifier that should be used when annotating all
3516    applicable type tags.
3517  * ``arg_idx`` provides the position of a function argument. The expected type of
3518    this function argument will be determined by the function argument specified
3519    by ``type_tag_idx``. In the code example below, "3" means that the type of the
3520    function's third argument will be determined by ``type_tag_idx``.
3521  * ``type_tag_idx`` provides the position of a function argument. This function
3522    argument will be a type tag. The type tag will determine the expected type of
3523    the argument specified by ``arg_idx``. In the code example below, "2" means
3524    that the type tag associated with the function's second argument should agree
3525    with the type of the argument specified by ``arg_idx``.
3526
3527For example:
3528
3529.. code-block:: c++
3530
3531  int fcntl(int fd, int cmd, ...)
3532      __attribute__(( argument_with_type_tag(fcntl,3,2) ));
3533  // The function's second argument will be a type tag; this type tag will
3534  // determine the expected type of the function's third argument.
3535
3536
3537pointer_with_type_tag
3538---------------------
3539.. csv-table:: Supported Syntaxes
3540   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
3541
3542   "X","X","X","","", "", ""
3543
3544Use ``__attribute__((pointer_with_type_tag(ptr_kind, ptr_idx, type_tag_idx)))``
3545on a function declaration to specify that the function accepts a type tag that
3546determines the pointee type of some other pointer argument.
3547
3548In the attribute prototype above:
3549  * ``ptr_kind`` is an identifier that should be used when annotating all
3550    applicable type tags.
3551  * ``ptr_idx`` provides the position of a function argument; this function
3552    argument will have a pointer type. The expected pointee type of this pointer
3553    type will be determined by the function argument specified by
3554    ``type_tag_idx``. In the code example below, "1" means that the pointee type
3555    of the function's first argument will be determined by ``type_tag_idx``.
3556  * ``type_tag_idx`` provides the position of a function argument; this function
3557    argument will be a type tag. The type tag will determine the expected pointee
3558    type of the pointer argument specified by ``ptr_idx``. In the code example
3559    below, "3" means that the type tag associated with the function's third
3560    argument should agree with the pointee type of the pointer argument specified
3561    by ``ptr_idx``.
3562
3563For example:
3564
3565.. code-block:: c++
3566
3567  typedef int MPI_Datatype;
3568  int MPI_Send(void *buf, int count, MPI_Datatype datatype /*, other args omitted */)
3569      __attribute__(( pointer_with_type_tag(mpi,1,3) ));
3570  // The function's 3rd argument will be a type tag; this type tag will
3571  // determine the expected pointee type of the function's 1st argument.
3572
3573
3574type_tag_for_datatype (clang::type_tag_for_datatype, clang::type_tag_for_datatype)
3575----------------------------------------------------------------------------------
3576.. csv-table:: Supported Syntaxes
3577   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
3578
3579   "X","X","X","","", "", ""
3580
3581When declaring a variable, use
3582``__attribute__((type_tag_for_datatype(kind, type)))`` to create a type tag that
3583is tied to the ``type`` argument given to the attribute.
3584
3585In the attribute prototype above:
3586  * ``kind`` is an identifier that should be used when annotating all applicable
3587    type tags.
3588  * ``type`` indicates the name of the type.
3589
3590Clang supports annotating type tags of two forms.
3591
3592  * **Type tag that is a reference to a declared identifier.**
3593    Use ``__attribute__((type_tag_for_datatype(kind, type)))`` when declaring that
3594    identifier:
3595
3596    .. code-block:: c++
3597
3598      typedef int MPI_Datatype;
3599      extern struct mpi_datatype mpi_datatype_int
3600          __attribute__(( type_tag_for_datatype(mpi,int) ));
3601      #define MPI_INT ((MPI_Datatype) &mpi_datatype_int)
3602      // &mpi_datatype_int is a type tag. It is tied to type "int".
3603
3604  * **Type tag that is an integral literal.**
3605    Declare a ``static const`` variable with an initializer value and attach
3606    ``__attribute__((type_tag_for_datatype(kind, type)))`` on that declaration:
3607
3608    .. code-block:: c++
3609
3610      typedef int MPI_Datatype;
3611      static const MPI_Datatype mpi_datatype_int
3612          __attribute__(( type_tag_for_datatype(mpi,int) )) = 42;
3613      #define MPI_INT ((MPI_Datatype) 42)
3614      // The number 42 is a type tag. It is tied to type "int".
3615
3616
3617The ``type_tag_for_datatype`` attribute also accepts an optional third argument
3618that determines how the type of the function argument specified by either
3619``arg_idx`` or ``ptr_idx`` is compared against the type associated with the type
3620tag. (Recall that for the ``argument_with_type_tag`` attribute, the type of the
3621function argument specified by ``arg_idx`` is compared against the type
3622associated with the type tag. Also recall that for the ``pointer_with_type_tag``
3623attribute, the pointee type of the function argument specified by ``ptr_idx`` is
3624compared against the type associated with the type tag.) There are two supported
3625values for this optional third argument:
3626
3627  * ``layout_compatible`` will cause types to be compared according to
3628    layout-compatibility rules (In C++11 [class.mem] p 17, 18, see the
3629    layout-compatibility rules for two standard-layout struct types and for two
3630    standard-layout union types). This is useful when creating a type tag
3631    associated with a struct or union type. For example:
3632
3633    .. code-block:: c++
3634
3635      /* In mpi.h */
3636      typedef int MPI_Datatype;
3637      struct internal_mpi_double_int { double d; int i; };
3638      extern struct mpi_datatype mpi_datatype_double_int
3639          __attribute__(( type_tag_for_datatype(mpi,
3640                          struct internal_mpi_double_int, layout_compatible) ));
3641
3642      #define MPI_DOUBLE_INT ((MPI_Datatype) &mpi_datatype_double_int)
3643
3644      int MPI_Send(void *buf, int count, MPI_Datatype datatype, ...)
3645          __attribute__(( pointer_with_type_tag(mpi,1,3) ));
3646
3647      /* In user code */
3648      struct my_pair { double a; int b; };
3649      struct my_pair *buffer;
3650      MPI_Send(buffer, 1, MPI_DOUBLE_INT /*, ...  */); // no warning because the
3651                                                       // layout of my_pair is
3652                                                       // compatible with that of
3653                                                       // internal_mpi_double_int
3654
3655      struct my_int_pair { int a; int b; }
3656      struct my_int_pair *buffer2;
3657      MPI_Send(buffer2, 1, MPI_DOUBLE_INT /*, ...  */); // warning because the
3658                                                        // layout of my_int_pair
3659                                                        // does not match that of
3660                                                        // internal_mpi_double_int
3661
3662  * ``must_be_null`` specifies that the function argument specified by either
3663    ``arg_idx`` (for the ``argument_with_type_tag`` attribute) or ``ptr_idx`` (for
3664    the ``pointer_with_type_tag`` attribute) should be a null pointer constant.
3665    The second argument to the ``type_tag_for_datatype`` attribute is ignored. For
3666    example:
3667
3668    .. code-block:: c++
3669
3670      /* In mpi.h */
3671      typedef int MPI_Datatype;
3672      extern struct mpi_datatype mpi_datatype_null
3673          __attribute__(( type_tag_for_datatype(mpi, void, must_be_null) ));
3674
3675      #define MPI_DATATYPE_NULL ((MPI_Datatype) &mpi_datatype_null)
3676      int MPI_Send(void *buf, int count, MPI_Datatype datatype, ...)
3677          __attribute__(( pointer_with_type_tag(mpi,1,3) ));
3678
3679      /* In user code */
3680      struct my_pair { double a; int b; };
3681      struct my_pair *buffer;
3682      MPI_Send(buffer, 1, MPI_DATATYPE_NULL /*, ...  */); // warning: MPI_DATATYPE_NULL
3683                                                          // was specified but buffer
3684                                                          // is not a null pointer
3685
3686
3687OpenCL Address Spaces
3688=====================
3689The address space qualifier may be used to specify the region of memory that is
3690used to allocate the object. OpenCL supports the following address spaces:
3691__generic(generic), __global(global), __local(local), __private(private),
3692__constant(constant).
3693
3694  .. code-block:: c
3695
3696    __constant int c = ...;
3697
3698    __generic int* foo(global int* g) {
3699      __local int* l;
3700      private int p;
3701      ...
3702      return l;
3703    }
3704
3705More details can be found in the OpenCL C language Spec v2.0, Section 6.5.
3706
3707constant (__constant)
3708---------------------
3709.. csv-table:: Supported Syntaxes
3710   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
3711
3712   "","","","","X", "", ""
3713
3714The constant address space attribute signals that an object is located in
3715a constant (non-modifiable) memory region. It is available to all work items.
3716Any type can be annotated with the constant address space attribute. Objects
3717with the constant address space qualifier can be declared in any scope and must
3718have an initializer.
3719
3720
3721generic (__generic)
3722-------------------
3723.. csv-table:: Supported Syntaxes
3724   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
3725
3726   "","","","","X", "", ""
3727
3728The generic address space attribute is only available with OpenCL v2.0 and later.
3729It can be used with pointer types. Variables in global and local scope and
3730function parameters in non-kernel functions can have the generic address space
3731type attribute. It is intended to be a placeholder for any other address space
3732except for '__constant' in OpenCL code which can be used with multiple address
3733spaces.
3734
3735
3736global (__global)
3737-----------------
3738.. csv-table:: Supported Syntaxes
3739   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
3740
3741   "","","","","X", "", ""
3742
3743The global address space attribute specifies that an object is allocated in
3744global memory, which is accessible by all work items. The content stored in this
3745memory area persists between kernel executions. Pointer types to the global
3746address space are allowed as function parameters or local variables. Starting
3747with OpenCL v2.0, the global address space can be used with global (program
3748scope) variables and static local variable as well.
3749
3750
3751local (__local)
3752---------------
3753.. csv-table:: Supported Syntaxes
3754   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
3755
3756   "","","","","X", "", ""
3757
3758The local address space specifies that an object is allocated in the local (work
3759group) memory area, which is accessible to all work items in the same work
3760group. The content stored in this memory region is not accessible after
3761the kernel execution ends. In a kernel function scope, any variable can be in
3762the local address space. In other scopes, only pointer types to the local address
3763space are allowed. Local address space variables cannot have an initializer.
3764
3765
3766private (__private)
3767-------------------
3768.. csv-table:: Supported Syntaxes
3769   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
3770
3771   "","","","","X", "", ""
3772
3773The private address space specifies that an object is allocated in the private
3774(work item) memory. Other work items cannot access the same memory area and its
3775content is destroyed after work item execution ends. Local variables can be
3776declared in the private address space. Function arguments are always in the
3777private address space. Kernel function arguments of a pointer or an array type
3778cannot point to the private address space.
3779
3780
3781Nullability Attributes
3782======================
3783Whether a particular pointer may be "null" is an important concern when working with pointers in the C family of languages. The various nullability attributes indicate whether a particular pointer can be null or not, which makes APIs more expressive and can help static analysis tools identify bugs involving null pointers. Clang supports several kinds of nullability attributes: the ``nonnull`` and ``returns_nonnull`` attributes indicate which function or method parameters and result types can never be null, while nullability type qualifiers indicate which pointer types can be null (``_Nullable``) or cannot be null (``_Nonnull``).
3784
3785The nullability (type) qualifiers express whether a value of a given pointer type can be null (the ``_Nullable`` qualifier), doesn't have a defined meaning for null (the ``_Nonnull`` qualifier), or for which the purpose of null is unclear (the ``_Null_unspecified`` qualifier). Because nullability qualifiers are expressed within the type system, they are more general than the ``nonnull`` and ``returns_nonnull`` attributes, allowing one to express (for example) a nullable pointer to an array of nonnull pointers. Nullability qualifiers are written to the right of the pointer to which they apply. For example:
3786
3787  .. code-block:: c
3788
3789    // No meaningful result when 'ptr' is null (here, it happens to be undefined behavior).
3790    int fetch(int * _Nonnull ptr) { return *ptr; }
3791
3792    // 'ptr' may be null.
3793    int fetch_or_zero(int * _Nullable ptr) {
3794      return ptr ? *ptr : 0;
3795    }
3796
3797    // A nullable pointer to non-null pointers to const characters.
3798    const char *join_strings(const char * _Nonnull * _Nullable strings, unsigned n);
3799
3800In Objective-C, there is an alternate spelling for the nullability qualifiers that can be used in Objective-C methods and properties using context-sensitive, non-underscored keywords. For example:
3801
3802  .. code-block:: objective-c
3803
3804    @interface NSView : NSResponder
3805      - (nullable NSView *)ancestorSharedWithView:(nonnull NSView *)aView;
3806      @property (assign, nullable) NSView *superview;
3807      @property (readonly, nonnull) NSArray *subviews;
3808    @end
3809
3810_Nonnull
3811--------
3812.. csv-table:: Supported Syntaxes
3813   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
3814
3815   "","","","","X", "", ""
3816
3817The ``_Nonnull`` nullability qualifier indicates that null is not a meaningful value for a value of the ``_Nonnull`` pointer type. For example, given a declaration such as:
3818
3819  .. code-block:: c
3820
3821    int fetch(int * _Nonnull ptr);
3822
3823a caller of ``fetch`` should not provide a null value, and the compiler will produce a warning if it sees a literal null value passed to ``fetch``. Note that, unlike the declaration attribute ``nonnull``, the presence of ``_Nonnull`` does not imply that passing null is undefined behavior: ``fetch`` is free to consider null undefined behavior or (perhaps for backward-compatibility reasons) defensively handle null.
3824
3825
3826_Null_unspecified
3827-----------------
3828.. csv-table:: Supported Syntaxes
3829   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
3830
3831   "","","","","X", "", ""
3832
3833The ``_Null_unspecified`` nullability qualifier indicates that neither the ``_Nonnull`` nor ``_Nullable`` qualifiers make sense for a particular pointer type. It is used primarily to indicate that the role of null with specific pointers in a nullability-annotated header is unclear, e.g., due to overly-complex implementations or historical factors with a long-lived API.
3834
3835
3836_Nullable
3837---------
3838.. csv-table:: Supported Syntaxes
3839   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
3840
3841   "","","","","X", "", ""
3842
3843The ``_Nullable`` nullability qualifier indicates that a value of the ``_Nullable`` pointer type can be null. For example, given:
3844
3845  .. code-block:: c
3846
3847    int fetch_or_zero(int * _Nullable ptr);
3848
3849a caller of ``fetch_or_zero`` can provide null.
3850
3851
3852nonnull (gnu::nonnull)
3853----------------------
3854.. csv-table:: Supported Syntaxes
3855   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
3856
3857   "X","X","","","", "", ""
3858
3859The ``nonnull`` attribute indicates that some function parameters must not be null, and can be used in several different ways. It's original usage (`from GCC <https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes>`_) is as a function (or Objective-C method) attribute that specifies which parameters of the function are nonnull in a comma-separated list. For example:
3860
3861  .. code-block:: c
3862
3863    extern void * my_memcpy (void *dest, const void *src, size_t len)
3864                    __attribute__((nonnull (1, 2)));
3865
3866Here, the ``nonnull`` attribute indicates that parameters 1 and 2
3867cannot have a null value. Omitting the parenthesized list of parameter indices means that all parameters of pointer type cannot be null:
3868
3869  .. code-block:: c
3870
3871    extern void * my_memcpy (void *dest, const void *src, size_t len)
3872                    __attribute__((nonnull));
3873
3874Clang also allows the ``nonnull`` attribute to be placed directly on a function (or Objective-C method) parameter, eliminating the need to specify the parameter index ahead of type. For example:
3875
3876  .. code-block:: c
3877
3878    extern void * my_memcpy (void *dest __attribute__((nonnull)),
3879                             const void *src __attribute__((nonnull)), size_t len);
3880
3881Note that the ``nonnull`` attribute indicates that passing null to a non-null parameter is undefined behavior, which the optimizer may take advantage of to, e.g., remove null checks. The ``_Nonnull`` type qualifier indicates that a pointer cannot be null in a more general manner (because it is part of the type system) and does not imply undefined behavior, making it more widely applicable.
3882
3883
3884returns_nonnull (gnu::returns_nonnull)
3885--------------------------------------
3886.. csv-table:: Supported Syntaxes
3887   :header: "GNU", "C++11", "C2x", "__declspec", "Keyword", "Pragma", "Pragma clang attribute"
3888
3889   "X","X","","","", "", "X"
3890
3891The ``returns_nonnull`` attribute indicates that a particular function (or Objective-C method) always returns a non-null pointer. For example, a particular system ``malloc`` might be defined to terminate a process when memory is not available rather than returning a null pointer:
3892
3893  .. code-block:: c
3894
3895    extern void * malloc (size_t size) __attribute__((returns_nonnull));
3896
3897The ``returns_nonnull`` attribute implies that returning a null pointer is undefined behavior, which the optimizer may take advantage of. The ``_Nonnull`` type qualifier indicates that a pointer cannot be null in a more general manner (because it is part of the type system) and does not imply undefined behavior, making it more widely applicable
3898
3899
3900