Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 1 | ========================= |
| 2 | Clang Language Extensions |
| 3 | ========================= |
| 4 | |
| 5 | .. contents:: |
| 6 | :local: |
Sean Silva | 13d43fe | 2013-01-02 21:09:58 +0000 | [diff] [blame] | 7 | :depth: 1 |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 8 | |
Sean Silva | f380e0e | 2013-01-02 21:03:11 +0000 | [diff] [blame] | 9 | .. toctree:: |
| 10 | :hidden: |
| 11 | |
| 12 | ObjectiveCLiterals |
| 13 | BlockLanguageSpec |
Michael Gottesman | 6fd5846 | 2013-01-07 22:24:45 +0000 | [diff] [blame] | 14 | Block-ABI-Apple |
DeLesley Hutchins | c51e08c | 2014-02-18 19:42:01 +0000 | [diff] [blame^] | 15 | AutomaticReferenceCounting |
Sean Silva | f380e0e | 2013-01-02 21:03:11 +0000 | [diff] [blame] | 16 | |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 17 | Introduction |
| 18 | ============ |
| 19 | |
| 20 | This document describes the language extensions provided by Clang. In addition |
| 21 | to the language extensions listed here, Clang aims to support a broad range of |
| 22 | GCC extensions. Please see the `GCC manual |
| 23 | <http://gcc.gnu.org/onlinedocs/gcc/C-Extensions.html>`_ for more information on |
| 24 | these extensions. |
| 25 | |
| 26 | .. _langext-feature_check: |
| 27 | |
| 28 | Feature Checking Macros |
| 29 | ======================= |
| 30 | |
| 31 | Language extensions can be very useful, but only if you know you can depend on |
| 32 | them. In order to allow fine-grain features checks, we support three builtin |
| 33 | function-like macros. This allows you to directly test for a feature in your |
| 34 | code without having to resort to something like autoconf or fragile "compiler |
| 35 | version checks". |
| 36 | |
| 37 | ``__has_builtin`` |
| 38 | ----------------- |
| 39 | |
| 40 | This function-like macro takes a single identifier argument that is the name of |
| 41 | a builtin function. It evaluates to 1 if the builtin is supported or 0 if not. |
| 42 | It can be used like this: |
| 43 | |
| 44 | .. code-block:: c++ |
| 45 | |
| 46 | #ifndef __has_builtin // Optional of course. |
| 47 | #define __has_builtin(x) 0 // Compatibility with non-clang compilers. |
| 48 | #endif |
| 49 | |
| 50 | ... |
| 51 | #if __has_builtin(__builtin_trap) |
| 52 | __builtin_trap(); |
| 53 | #else |
| 54 | abort(); |
| 55 | #endif |
| 56 | ... |
| 57 | |
| 58 | .. _langext-__has_feature-__has_extension: |
| 59 | |
| 60 | ``__has_feature`` and ``__has_extension`` |
| 61 | ----------------------------------------- |
| 62 | |
| 63 | These function-like macros take a single identifier argument that is the name |
| 64 | of a feature. ``__has_feature`` evaluates to 1 if the feature is both |
| 65 | supported by Clang and standardized in the current language standard or 0 if |
| 66 | not (but see :ref:`below <langext-has-feature-back-compat>`), while |
| 67 | ``__has_extension`` evaluates to 1 if the feature is supported by Clang in the |
| 68 | current language (either as a language extension or a standard language |
| 69 | feature) or 0 if not. They can be used like this: |
| 70 | |
| 71 | .. code-block:: c++ |
| 72 | |
| 73 | #ifndef __has_feature // Optional of course. |
| 74 | #define __has_feature(x) 0 // Compatibility with non-clang compilers. |
| 75 | #endif |
| 76 | #ifndef __has_extension |
| 77 | #define __has_extension __has_feature // Compatibility with pre-3.0 compilers. |
| 78 | #endif |
| 79 | |
| 80 | ... |
| 81 | #if __has_feature(cxx_rvalue_references) |
| 82 | // This code will only be compiled with the -std=c++11 and -std=gnu++11 |
| 83 | // options, because rvalue references are only standardized in C++11. |
| 84 | #endif |
| 85 | |
| 86 | #if __has_extension(cxx_rvalue_references) |
| 87 | // This code will be compiled with the -std=c++11, -std=gnu++11, -std=c++98 |
| 88 | // and -std=gnu++98 options, because rvalue references are supported as a |
| 89 | // language extension in C++98. |
| 90 | #endif |
| 91 | |
| 92 | .. _langext-has-feature-back-compat: |
| 93 | |
| 94 | For backwards compatibility reasons, ``__has_feature`` can also be used to test |
| 95 | for support for non-standardized features, i.e. features not prefixed ``c_``, |
| 96 | ``cxx_`` or ``objc_``. |
| 97 | |
| 98 | Another use of ``__has_feature`` is to check for compiler features not related |
Sean Silva | 173d252 | 2013-01-02 13:07:47 +0000 | [diff] [blame] | 99 | to the language standard, such as e.g. :doc:`AddressSanitizer |
| 100 | <AddressSanitizer>`. |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 101 | |
| 102 | If the ``-pedantic-errors`` option is given, ``__has_extension`` is equivalent |
| 103 | to ``__has_feature``. |
| 104 | |
| 105 | The feature tag is described along with the language feature below. |
| 106 | |
| 107 | The feature name or extension name can also be specified with a preceding and |
| 108 | following ``__`` (double underscore) to avoid interference from a macro with |
| 109 | the same name. For instance, ``__cxx_rvalue_references__`` can be used instead |
| 110 | of ``cxx_rvalue_references``. |
| 111 | |
| 112 | ``__has_attribute`` |
| 113 | ------------------- |
| 114 | |
| 115 | This function-like macro takes a single identifier argument that is the name of |
Aaron Ballman | a4bb4b9 | 2014-01-09 23:11:13 +0000 | [diff] [blame] | 116 | an attribute. It evaluates to 1 if the attribute is supported by the current |
| 117 | compilation target, or 0 if not. It can be used like this: |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 118 | |
| 119 | .. code-block:: c++ |
| 120 | |
| 121 | #ifndef __has_attribute // Optional of course. |
| 122 | #define __has_attribute(x) 0 // Compatibility with non-clang compilers. |
| 123 | #endif |
| 124 | |
| 125 | ... |
| 126 | #if __has_attribute(always_inline) |
| 127 | #define ALWAYS_INLINE __attribute__((always_inline)) |
| 128 | #else |
| 129 | #define ALWAYS_INLINE |
| 130 | #endif |
| 131 | ... |
| 132 | |
| 133 | The attribute name can also be specified with a preceding and following ``__`` |
| 134 | (double underscore) to avoid interference from a macro with the same name. For |
| 135 | instance, ``__always_inline__`` can be used instead of ``always_inline``. |
| 136 | |
Aaron Ballman | a4bb4b9 | 2014-01-09 23:11:13 +0000 | [diff] [blame] | 137 | |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 138 | Include File Checking Macros |
| 139 | ============================ |
| 140 | |
| 141 | Not all developments systems have the same include files. The |
| 142 | :ref:`langext-__has_include` and :ref:`langext-__has_include_next` macros allow |
| 143 | you to check for the existence of an include file before doing a possibly |
Dmitri Gribenko | 764ea24 | 2013-01-17 17:04:54 +0000 | [diff] [blame] | 144 | failing ``#include`` directive. Include file checking macros must be used |
| 145 | as expressions in ``#if`` or ``#elif`` preprocessing directives. |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 146 | |
| 147 | .. _langext-__has_include: |
| 148 | |
| 149 | ``__has_include`` |
| 150 | ----------------- |
| 151 | |
| 152 | This function-like macro takes a single file name string argument that is the |
| 153 | name of an include file. It evaluates to 1 if the file can be found using the |
| 154 | include paths, or 0 otherwise: |
| 155 | |
| 156 | .. code-block:: c++ |
| 157 | |
| 158 | // Note the two possible file name string formats. |
| 159 | #if __has_include("myinclude.h") && __has_include(<stdint.h>) |
| 160 | # include "myinclude.h" |
| 161 | #endif |
| 162 | |
Richard Smith | ccfc9ff | 2013-07-11 00:27:05 +0000 | [diff] [blame] | 163 | To test for this feature, use ``#if defined(__has_include)``: |
| 164 | |
| 165 | .. code-block:: c++ |
| 166 | |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 167 | // To avoid problem with non-clang compilers not having this macro. |
Richard Smith | ccfc9ff | 2013-07-11 00:27:05 +0000 | [diff] [blame] | 168 | #if defined(__has_include) |
| 169 | #if __has_include("myinclude.h") |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 170 | # include "myinclude.h" |
| 171 | #endif |
Richard Smith | ccfc9ff | 2013-07-11 00:27:05 +0000 | [diff] [blame] | 172 | #endif |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 173 | |
| 174 | .. _langext-__has_include_next: |
| 175 | |
| 176 | ``__has_include_next`` |
| 177 | ---------------------- |
| 178 | |
| 179 | This function-like macro takes a single file name string argument that is the |
| 180 | name of an include file. It is like ``__has_include`` except that it looks for |
| 181 | the second instance of the given file found in the include paths. It evaluates |
| 182 | to 1 if the second instance of the file can be found using the include paths, |
| 183 | or 0 otherwise: |
| 184 | |
| 185 | .. code-block:: c++ |
| 186 | |
| 187 | // Note the two possible file name string formats. |
| 188 | #if __has_include_next("myinclude.h") && __has_include_next(<stdint.h>) |
| 189 | # include_next "myinclude.h" |
| 190 | #endif |
| 191 | |
| 192 | // To avoid problem with non-clang compilers not having this macro. |
Richard Smith | ccfc9ff | 2013-07-11 00:27:05 +0000 | [diff] [blame] | 193 | #if defined(__has_include_next) |
| 194 | #if __has_include_next("myinclude.h") |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 195 | # include_next "myinclude.h" |
| 196 | #endif |
Richard Smith | ccfc9ff | 2013-07-11 00:27:05 +0000 | [diff] [blame] | 197 | #endif |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 198 | |
| 199 | Note that ``__has_include_next``, like the GNU extension ``#include_next`` |
| 200 | directive, is intended for use in headers only, and will issue a warning if |
| 201 | used in the top-level compilation file. A warning will also be issued if an |
| 202 | absolute path is used in the file argument. |
| 203 | |
| 204 | ``__has_warning`` |
| 205 | ----------------- |
| 206 | |
| 207 | This function-like macro takes a string literal that represents a command line |
| 208 | option for a warning and returns true if that is a valid warning option. |
| 209 | |
| 210 | .. code-block:: c++ |
| 211 | |
| 212 | #if __has_warning("-Wformat") |
| 213 | ... |
| 214 | #endif |
| 215 | |
| 216 | Builtin Macros |
| 217 | ============== |
| 218 | |
| 219 | ``__BASE_FILE__`` |
| 220 | Defined to a string that contains the name of the main input file passed to |
| 221 | Clang. |
| 222 | |
| 223 | ``__COUNTER__`` |
| 224 | Defined to an integer value that starts at zero and is incremented each time |
| 225 | the ``__COUNTER__`` macro is expanded. |
| 226 | |
| 227 | ``__INCLUDE_LEVEL__`` |
| 228 | Defined to an integral value that is the include depth of the file currently |
| 229 | being translated. For the main file, this value is zero. |
| 230 | |
| 231 | ``__TIMESTAMP__`` |
| 232 | Defined to the date and time of the last modification of the current source |
| 233 | file. |
| 234 | |
| 235 | ``__clang__`` |
| 236 | Defined when compiling with Clang |
| 237 | |
| 238 | ``__clang_major__`` |
| 239 | Defined to the major marketing version number of Clang (e.g., the 2 in |
| 240 | 2.0.1). Note that marketing version numbers should not be used to check for |
| 241 | language features, as different vendors use different numbering schemes. |
| 242 | Instead, use the :ref:`langext-feature_check`. |
| 243 | |
| 244 | ``__clang_minor__`` |
| 245 | Defined to the minor version number of Clang (e.g., the 0 in 2.0.1). Note |
| 246 | that marketing version numbers should not be used to check for language |
| 247 | features, as different vendors use different numbering schemes. Instead, use |
| 248 | the :ref:`langext-feature_check`. |
| 249 | |
| 250 | ``__clang_patchlevel__`` |
| 251 | Defined to the marketing patch level of Clang (e.g., the 1 in 2.0.1). |
| 252 | |
| 253 | ``__clang_version__`` |
| 254 | Defined to a string that captures the Clang marketing version, including the |
| 255 | Subversion tag or revision number, e.g., "``1.5 (trunk 102332)``". |
| 256 | |
| 257 | .. _langext-vectors: |
| 258 | |
| 259 | Vectors and Extended Vectors |
| 260 | ============================ |
| 261 | |
| 262 | Supports the GCC, OpenCL, AltiVec and NEON vector extensions. |
| 263 | |
| 264 | OpenCL vector types are created using ``ext_vector_type`` attribute. It |
| 265 | support for ``V.xyzw`` syntax and other tidbits as seen in OpenCL. An example |
| 266 | is: |
| 267 | |
| 268 | .. code-block:: c++ |
| 269 | |
| 270 | typedef float float4 __attribute__((ext_vector_type(4))); |
| 271 | typedef float float2 __attribute__((ext_vector_type(2))); |
| 272 | |
| 273 | float4 foo(float2 a, float2 b) { |
| 274 | float4 c; |
| 275 | c.xz = a; |
| 276 | c.yw = b; |
| 277 | return c; |
| 278 | } |
| 279 | |
| 280 | Query for this feature with ``__has_extension(attribute_ext_vector_type)``. |
| 281 | |
| 282 | Giving ``-faltivec`` option to clang enables support for AltiVec vector syntax |
| 283 | and functions. For example: |
| 284 | |
| 285 | .. code-block:: c++ |
| 286 | |
| 287 | vector float foo(vector int a) { |
| 288 | vector int b; |
| 289 | b = vec_add(a, a) + a; |
| 290 | return (vector float)b; |
| 291 | } |
| 292 | |
| 293 | NEON vector types are created using ``neon_vector_type`` and |
| 294 | ``neon_polyvector_type`` attributes. For example: |
| 295 | |
| 296 | .. code-block:: c++ |
| 297 | |
| 298 | typedef __attribute__((neon_vector_type(8))) int8_t int8x8_t; |
| 299 | typedef __attribute__((neon_polyvector_type(16))) poly8_t poly8x16_t; |
| 300 | |
| 301 | int8x8_t foo(int8x8_t a) { |
| 302 | int8x8_t v; |
| 303 | v = a; |
| 304 | return v; |
| 305 | } |
| 306 | |
| 307 | Vector Literals |
| 308 | --------------- |
| 309 | |
| 310 | Vector literals can be used to create vectors from a set of scalars, or |
| 311 | vectors. Either parentheses or braces form can be used. In the parentheses |
| 312 | form the number of literal values specified must be one, i.e. referring to a |
| 313 | scalar value, or must match the size of the vector type being created. If a |
| 314 | single scalar literal value is specified, the scalar literal value will be |
| 315 | replicated to all the components of the vector type. In the brackets form any |
| 316 | number of literals can be specified. For example: |
| 317 | |
| 318 | .. code-block:: c++ |
| 319 | |
| 320 | typedef int v4si __attribute__((__vector_size__(16))); |
| 321 | typedef float float4 __attribute__((ext_vector_type(4))); |
| 322 | typedef float float2 __attribute__((ext_vector_type(2))); |
| 323 | |
| 324 | v4si vsi = (v4si){1, 2, 3, 4}; |
| 325 | float4 vf = (float4)(1.0f, 2.0f, 3.0f, 4.0f); |
| 326 | vector int vi1 = (vector int)(1); // vi1 will be (1, 1, 1, 1). |
| 327 | vector int vi2 = (vector int){1}; // vi2 will be (1, 0, 0, 0). |
| 328 | vector int vi3 = (vector int)(1, 2); // error |
| 329 | vector int vi4 = (vector int){1, 2}; // vi4 will be (1, 2, 0, 0). |
| 330 | vector int vi5 = (vector int)(1, 2, 3, 4); |
| 331 | float4 vf = (float4)((float2)(1.0f, 2.0f), (float2)(3.0f, 4.0f)); |
| 332 | |
| 333 | Vector Operations |
| 334 | ----------------- |
| 335 | |
| 336 | The table below shows the support for each operation by vector extension. A |
| 337 | dash indicates that an operation is not accepted according to a corresponding |
| 338 | specification. |
| 339 | |
| 340 | ============================== ====== ======= === ==== |
| 341 | Opeator OpenCL AltiVec GCC NEON |
| 342 | ============================== ====== ======= === ==== |
| 343 | [] yes yes yes -- |
| 344 | unary operators +, -- yes yes yes -- |
| 345 | ++, -- -- yes yes yes -- |
| 346 | +,--,*,/,% yes yes yes -- |
| 347 | bitwise operators &,|,^,~ yes yes yes -- |
| 348 | >>,<< yes yes yes -- |
| 349 | !, &&, || no -- -- -- |
| 350 | ==, !=, >, <, >=, <= yes yes -- -- |
| 351 | = yes yes yes yes |
| 352 | :? yes -- -- -- |
| 353 | sizeof yes yes yes yes |
| 354 | ============================== ====== ======= === ==== |
| 355 | |
| 356 | See also :ref:`langext-__builtin_shufflevector`. |
| 357 | |
| 358 | Messages on ``deprecated`` and ``unavailable`` Attributes |
| 359 | ========================================================= |
| 360 | |
| 361 | An optional string message can be added to the ``deprecated`` and |
| 362 | ``unavailable`` attributes. For example: |
| 363 | |
| 364 | .. code-block:: c++ |
| 365 | |
| 366 | void explode(void) __attribute__((deprecated("extremely unsafe, use 'combust' instead!!!"))); |
| 367 | |
| 368 | If the deprecated or unavailable declaration is used, the message will be |
| 369 | incorporated into the appropriate diagnostic: |
| 370 | |
| 371 | .. code-block:: c++ |
| 372 | |
| 373 | harmless.c:4:3: warning: 'explode' is deprecated: extremely unsafe, use 'combust' instead!!! |
| 374 | [-Wdeprecated-declarations] |
| 375 | explode(); |
| 376 | ^ |
| 377 | |
| 378 | Query for this feature with |
| 379 | ``__has_extension(attribute_deprecated_with_message)`` and |
| 380 | ``__has_extension(attribute_unavailable_with_message)``. |
| 381 | |
| 382 | Attributes on Enumerators |
| 383 | ========================= |
| 384 | |
| 385 | Clang allows attributes to be written on individual enumerators. This allows |
| 386 | enumerators to be deprecated, made unavailable, etc. The attribute must appear |
| 387 | after the enumerator name and before any initializer, like so: |
| 388 | |
| 389 | .. code-block:: c++ |
| 390 | |
| 391 | enum OperationMode { |
| 392 | OM_Invalid, |
| 393 | OM_Normal, |
| 394 | OM_Terrified __attribute__((deprecated)), |
| 395 | OM_AbortOnError __attribute__((deprecated)) = 4 |
| 396 | }; |
| 397 | |
| 398 | Attributes on the ``enum`` declaration do not apply to individual enumerators. |
| 399 | |
| 400 | Query for this feature with ``__has_extension(enumerator_attributes)``. |
| 401 | |
| 402 | 'User-Specified' System Frameworks |
| 403 | ================================== |
| 404 | |
| 405 | Clang provides a mechanism by which frameworks can be built in such a way that |
| 406 | they will always be treated as being "system frameworks", even if they are not |
| 407 | present in a system framework directory. This can be useful to system |
| 408 | framework developers who want to be able to test building other applications |
| 409 | with development builds of their framework, including the manner in which the |
| 410 | compiler changes warning behavior for system headers. |
| 411 | |
| 412 | Framework developers can opt-in to this mechanism by creating a |
| 413 | "``.system_framework``" file at the top-level of their framework. That is, the |
| 414 | framework should have contents like: |
| 415 | |
| 416 | .. code-block:: none |
| 417 | |
| 418 | .../TestFramework.framework |
| 419 | .../TestFramework.framework/.system_framework |
| 420 | .../TestFramework.framework/Headers |
| 421 | .../TestFramework.framework/Headers/TestFramework.h |
| 422 | ... |
| 423 | |
| 424 | Clang will treat the presence of this file as an indicator that the framework |
| 425 | should be treated as a system framework, regardless of how it was found in the |
| 426 | framework search path. For consistency, we recommend that such files never be |
| 427 | included in installed versions of the framework. |
| 428 | |
| 429 | Availability attribute |
| 430 | ====================== |
| 431 | |
| 432 | Clang introduces the ``availability`` attribute, which can be placed on |
| 433 | declarations to describe the lifecycle of that declaration relative to |
| 434 | operating system versions. Consider the function declaration for a |
| 435 | hypothetical function ``f``: |
| 436 | |
| 437 | .. code-block:: c++ |
| 438 | |
| 439 | void f(void) __attribute__((availability(macosx,introduced=10.4,deprecated=10.6,obsoleted=10.7))); |
| 440 | |
| 441 | The availability attribute states that ``f`` was introduced in Mac OS X 10.4, |
| 442 | deprecated in Mac OS X 10.6, and obsoleted in Mac OS X 10.7. This information |
| 443 | is used by Clang to determine when it is safe to use ``f``: for example, if |
| 444 | Clang is instructed to compile code for Mac OS X 10.5, a call to ``f()`` |
| 445 | succeeds. If Clang is instructed to compile code for Mac OS X 10.6, the call |
| 446 | succeeds but Clang emits a warning specifying that the function is deprecated. |
| 447 | Finally, if Clang is instructed to compile code for Mac OS X 10.7, the call |
| 448 | fails because ``f()`` is no longer available. |
| 449 | |
Douglas Gregor | 250ee63 | 2013-01-16 01:12:31 +0000 | [diff] [blame] | 450 | The availability attribute is a comma-separated list starting with the |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 451 | platform name and then including clauses specifying important milestones in the |
| 452 | declaration's lifetime (in any order) along with additional information. Those |
| 453 | clauses can be: |
| 454 | |
| 455 | introduced=\ *version* |
| 456 | The first version in which this declaration was introduced. |
| 457 | |
| 458 | deprecated=\ *version* |
| 459 | The first version in which this declaration was deprecated, meaning that |
| 460 | users should migrate away from this API. |
| 461 | |
| 462 | obsoleted=\ *version* |
| 463 | The first version in which this declaration was obsoleted, meaning that it |
| 464 | was removed completely and can no longer be used. |
| 465 | |
| 466 | unavailable |
| 467 | This declaration is never available on this platform. |
| 468 | |
| 469 | message=\ *string-literal* |
| 470 | Additional message text that Clang will provide when emitting a warning or |
| 471 | error about use of a deprecated or obsoleted declaration. Useful to direct |
| 472 | users to replacement APIs. |
| 473 | |
| 474 | Multiple availability attributes can be placed on a declaration, which may |
| 475 | correspond to different platforms. Only the availability attribute with the |
| 476 | platform corresponding to the target platform will be used; any others will be |
| 477 | ignored. If no availability attribute specifies availability for the current |
| 478 | target platform, the availability attributes are ignored. Supported platforms |
| 479 | are: |
| 480 | |
| 481 | ``ios`` |
| 482 | Apple's iOS operating system. The minimum deployment target is specified by |
| 483 | the ``-mios-version-min=*version*`` or ``-miphoneos-version-min=*version*`` |
| 484 | command-line arguments. |
| 485 | |
| 486 | ``macosx`` |
| 487 | Apple's Mac OS X operating system. The minimum deployment target is |
| 488 | specified by the ``-mmacosx-version-min=*version*`` command-line argument. |
| 489 | |
| 490 | A declaration can be used even when deploying back to a platform version prior |
| 491 | to when the declaration was introduced. When this happens, the declaration is |
| 492 | `weakly linked |
| 493 | <https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPFrameworks/Concepts/WeakLinking.html>`_, |
| 494 | as if the ``weak_import`` attribute were added to the declaration. A |
| 495 | weakly-linked declaration may or may not be present a run-time, and a program |
| 496 | can determine whether the declaration is present by checking whether the |
| 497 | address of that declaration is non-NULL. |
| 498 | |
Dmitri Gribenko | fb5b224 | 2013-01-16 01:17:05 +0000 | [diff] [blame] | 499 | If there are multiple declarations of the same entity, the availability |
Douglas Gregor | 250ee63 | 2013-01-16 01:12:31 +0000 | [diff] [blame] | 500 | attributes must either match on a per-platform basis or later |
| 501 | declarations must not have availability attributes for that |
| 502 | platform. For example: |
| 503 | |
| 504 | .. code-block:: c |
| 505 | |
| 506 | void g(void) __attribute__((availability(macosx,introduced=10.4))); |
| 507 | void g(void) __attribute__((availability(macosx,introduced=10.4))); // okay, matches |
| 508 | void g(void) __attribute__((availability(ios,introduced=4.0))); // okay, adds a new platform |
| 509 | void g(void); // okay, inherits both macosx and ios availability from above. |
| 510 | void g(void) __attribute__((availability(macosx,introduced=10.5))); // error: mismatch |
| 511 | |
| 512 | When one method overrides another, the overriding method can be more widely available than the overridden method, e.g.,: |
| 513 | |
| 514 | .. code-block:: objc |
| 515 | |
| 516 | @interface A |
| 517 | - (id)method __attribute__((availability(macosx,introduced=10.4))); |
| 518 | - (id)method2 __attribute__((availability(macosx,introduced=10.4))); |
| 519 | @end |
| 520 | |
| 521 | @interface B : A |
| 522 | - (id)method __attribute__((availability(macosx,introduced=10.3))); // okay: method moved into base class later |
| 523 | - (id)method __attribute__((availability(macosx,introduced=10.5))); // error: this method was available via the base class in 10.4 |
| 524 | @end |
| 525 | |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 526 | Checks for Standard Language Features |
| 527 | ===================================== |
| 528 | |
| 529 | The ``__has_feature`` macro can be used to query if certain standard language |
| 530 | features are enabled. The ``__has_extension`` macro can be used to query if |
| 531 | language features are available as an extension when compiling for a standard |
| 532 | which does not provide them. The features which can be tested are listed here. |
| 533 | |
| 534 | C++98 |
| 535 | ----- |
| 536 | |
| 537 | The features listed below are part of the C++98 standard. These features are |
| 538 | enabled by default when compiling C++ code. |
| 539 | |
| 540 | C++ exceptions |
| 541 | ^^^^^^^^^^^^^^ |
| 542 | |
| 543 | Use ``__has_feature(cxx_exceptions)`` to determine if C++ exceptions have been |
| 544 | enabled. For example, compiling code with ``-fno-exceptions`` disables C++ |
| 545 | exceptions. |
| 546 | |
| 547 | C++ RTTI |
| 548 | ^^^^^^^^ |
| 549 | |
| 550 | Use ``__has_feature(cxx_rtti)`` to determine if C++ RTTI has been enabled. For |
| 551 | example, compiling code with ``-fno-rtti`` disables the use of RTTI. |
| 552 | |
| 553 | C++11 |
| 554 | ----- |
| 555 | |
| 556 | The features listed below are part of the C++11 standard. As a result, all |
| 557 | these features are enabled with the ``-std=c++11`` or ``-std=gnu++11`` option |
| 558 | when compiling C++ code. |
| 559 | |
| 560 | C++11 SFINAE includes access control |
| 561 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 562 | |
| 563 | Use ``__has_feature(cxx_access_control_sfinae)`` or |
| 564 | ``__has_extension(cxx_access_control_sfinae)`` to determine whether |
| 565 | access-control errors (e.g., calling a private constructor) are considered to |
| 566 | be template argument deduction errors (aka SFINAE errors), per `C++ DR1170 |
| 567 | <http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1170>`_. |
| 568 | |
| 569 | C++11 alias templates |
| 570 | ^^^^^^^^^^^^^^^^^^^^^ |
| 571 | |
| 572 | Use ``__has_feature(cxx_alias_templates)`` or |
| 573 | ``__has_extension(cxx_alias_templates)`` to determine if support for C++11's |
| 574 | alias declarations and alias templates is enabled. |
| 575 | |
| 576 | C++11 alignment specifiers |
| 577 | ^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 578 | |
| 579 | Use ``__has_feature(cxx_alignas)`` or ``__has_extension(cxx_alignas)`` to |
| 580 | determine if support for alignment specifiers using ``alignas`` is enabled. |
| 581 | |
| 582 | C++11 attributes |
| 583 | ^^^^^^^^^^^^^^^^ |
| 584 | |
| 585 | Use ``__has_feature(cxx_attributes)`` or ``__has_extension(cxx_attributes)`` to |
| 586 | determine if support for attribute parsing with C++11's square bracket notation |
| 587 | is enabled. |
| 588 | |
| 589 | C++11 generalized constant expressions |
| 590 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 591 | |
| 592 | Use ``__has_feature(cxx_constexpr)`` to determine if support for generalized |
| 593 | constant expressions (e.g., ``constexpr``) is enabled. |
| 594 | |
| 595 | C++11 ``decltype()`` |
| 596 | ^^^^^^^^^^^^^^^^^^^^ |
| 597 | |
| 598 | Use ``__has_feature(cxx_decltype)`` or ``__has_extension(cxx_decltype)`` to |
| 599 | determine if support for the ``decltype()`` specifier is enabled. C++11's |
| 600 | ``decltype`` does not require type-completeness of a function call expression. |
| 601 | Use ``__has_feature(cxx_decltype_incomplete_return_types)`` or |
| 602 | ``__has_extension(cxx_decltype_incomplete_return_types)`` to determine if |
| 603 | support for this feature is enabled. |
| 604 | |
| 605 | C++11 default template arguments in function templates |
| 606 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 607 | |
| 608 | Use ``__has_feature(cxx_default_function_template_args)`` or |
| 609 | ``__has_extension(cxx_default_function_template_args)`` to determine if support |
| 610 | for default template arguments in function templates is enabled. |
| 611 | |
| 612 | C++11 ``default``\ ed functions |
| 613 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 614 | |
| 615 | Use ``__has_feature(cxx_defaulted_functions)`` or |
| 616 | ``__has_extension(cxx_defaulted_functions)`` to determine if support for |
| 617 | defaulted function definitions (with ``= default``) is enabled. |
| 618 | |
| 619 | C++11 delegating constructors |
| 620 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 621 | |
| 622 | Use ``__has_feature(cxx_delegating_constructors)`` to determine if support for |
| 623 | delegating constructors is enabled. |
| 624 | |
| 625 | C++11 ``deleted`` functions |
| 626 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 627 | |
| 628 | Use ``__has_feature(cxx_deleted_functions)`` or |
| 629 | ``__has_extension(cxx_deleted_functions)`` to determine if support for deleted |
| 630 | function definitions (with ``= delete``) is enabled. |
| 631 | |
| 632 | C++11 explicit conversion functions |
| 633 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 634 | |
| 635 | Use ``__has_feature(cxx_explicit_conversions)`` to determine if support for |
| 636 | ``explicit`` conversion functions is enabled. |
| 637 | |
| 638 | C++11 generalized initializers |
| 639 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 640 | |
| 641 | Use ``__has_feature(cxx_generalized_initializers)`` to determine if support for |
| 642 | generalized initializers (using braced lists and ``std::initializer_list``) is |
| 643 | enabled. |
| 644 | |
| 645 | C++11 implicit move constructors/assignment operators |
| 646 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 647 | |
| 648 | Use ``__has_feature(cxx_implicit_moves)`` to determine if Clang will implicitly |
| 649 | generate move constructors and move assignment operators where needed. |
| 650 | |
| 651 | C++11 inheriting constructors |
| 652 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 653 | |
| 654 | Use ``__has_feature(cxx_inheriting_constructors)`` to determine if support for |
Richard Smith | 25b555a | 2013-04-19 17:00:31 +0000 | [diff] [blame] | 655 | inheriting constructors is enabled. |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 656 | |
| 657 | C++11 inline namespaces |
| 658 | ^^^^^^^^^^^^^^^^^^^^^^^ |
| 659 | |
| 660 | Use ``__has_feature(cxx_inline_namespaces)`` or |
| 661 | ``__has_extension(cxx_inline_namespaces)`` to determine if support for inline |
| 662 | namespaces is enabled. |
| 663 | |
| 664 | C++11 lambdas |
| 665 | ^^^^^^^^^^^^^ |
| 666 | |
| 667 | Use ``__has_feature(cxx_lambdas)`` or ``__has_extension(cxx_lambdas)`` to |
| 668 | determine if support for lambdas is enabled. |
| 669 | |
| 670 | C++11 local and unnamed types as template arguments |
| 671 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 672 | |
| 673 | Use ``__has_feature(cxx_local_type_template_args)`` or |
| 674 | ``__has_extension(cxx_local_type_template_args)`` to determine if support for |
| 675 | local and unnamed types as template arguments is enabled. |
| 676 | |
| 677 | C++11 noexcept |
| 678 | ^^^^^^^^^^^^^^ |
| 679 | |
| 680 | Use ``__has_feature(cxx_noexcept)`` or ``__has_extension(cxx_noexcept)`` to |
| 681 | determine if support for noexcept exception specifications is enabled. |
| 682 | |
| 683 | C++11 in-class non-static data member initialization |
| 684 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 685 | |
| 686 | Use ``__has_feature(cxx_nonstatic_member_init)`` to determine whether in-class |
| 687 | initialization of non-static data members is enabled. |
| 688 | |
| 689 | C++11 ``nullptr`` |
| 690 | ^^^^^^^^^^^^^^^^^ |
| 691 | |
| 692 | Use ``__has_feature(cxx_nullptr)`` or ``__has_extension(cxx_nullptr)`` to |
| 693 | determine if support for ``nullptr`` is enabled. |
| 694 | |
| 695 | C++11 ``override control`` |
| 696 | ^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 697 | |
| 698 | Use ``__has_feature(cxx_override_control)`` or |
| 699 | ``__has_extension(cxx_override_control)`` to determine if support for the |
| 700 | override control keywords is enabled. |
| 701 | |
| 702 | C++11 reference-qualified functions |
| 703 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 704 | |
| 705 | Use ``__has_feature(cxx_reference_qualified_functions)`` or |
| 706 | ``__has_extension(cxx_reference_qualified_functions)`` to determine if support |
| 707 | for reference-qualified functions (e.g., member functions with ``&`` or ``&&`` |
| 708 | applied to ``*this``) is enabled. |
| 709 | |
| 710 | C++11 range-based ``for`` loop |
| 711 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 712 | |
| 713 | Use ``__has_feature(cxx_range_for)`` or ``__has_extension(cxx_range_for)`` to |
| 714 | determine if support for the range-based for loop is enabled. |
| 715 | |
| 716 | C++11 raw string literals |
| 717 | ^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 718 | |
| 719 | Use ``__has_feature(cxx_raw_string_literals)`` to determine if support for raw |
| 720 | string literals (e.g., ``R"x(foo\bar)x"``) is enabled. |
| 721 | |
| 722 | C++11 rvalue references |
| 723 | ^^^^^^^^^^^^^^^^^^^^^^^ |
| 724 | |
| 725 | Use ``__has_feature(cxx_rvalue_references)`` or |
| 726 | ``__has_extension(cxx_rvalue_references)`` to determine if support for rvalue |
| 727 | references is enabled. |
| 728 | |
| 729 | C++11 ``static_assert()`` |
| 730 | ^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 731 | |
| 732 | Use ``__has_feature(cxx_static_assert)`` or |
| 733 | ``__has_extension(cxx_static_assert)`` to determine if support for compile-time |
| 734 | assertions using ``static_assert`` is enabled. |
| 735 | |
Richard Smith | 25b555a | 2013-04-19 17:00:31 +0000 | [diff] [blame] | 736 | C++11 ``thread_local`` |
| 737 | ^^^^^^^^^^^^^^^^^^^^^^ |
| 738 | |
| 739 | Use ``__has_feature(cxx_thread_local)`` to determine if support for |
| 740 | ``thread_local`` variables is enabled. |
| 741 | |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 742 | C++11 type inference |
| 743 | ^^^^^^^^^^^^^^^^^^^^ |
| 744 | |
| 745 | Use ``__has_feature(cxx_auto_type)`` or ``__has_extension(cxx_auto_type)`` to |
| 746 | determine C++11 type inference is supported using the ``auto`` specifier. If |
| 747 | this is disabled, ``auto`` will instead be a storage class specifier, as in C |
| 748 | or C++98. |
| 749 | |
| 750 | C++11 strongly typed enumerations |
| 751 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 752 | |
| 753 | Use ``__has_feature(cxx_strong_enums)`` or |
| 754 | ``__has_extension(cxx_strong_enums)`` to determine if support for strongly |
| 755 | typed, scoped enumerations is enabled. |
| 756 | |
| 757 | C++11 trailing return type |
| 758 | ^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 759 | |
| 760 | Use ``__has_feature(cxx_trailing_return)`` or |
| 761 | ``__has_extension(cxx_trailing_return)`` to determine if support for the |
| 762 | alternate function declaration syntax with trailing return type is enabled. |
| 763 | |
| 764 | C++11 Unicode string literals |
| 765 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 766 | |
| 767 | Use ``__has_feature(cxx_unicode_literals)`` to determine if support for Unicode |
| 768 | string literals is enabled. |
| 769 | |
| 770 | C++11 unrestricted unions |
| 771 | ^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 772 | |
| 773 | Use ``__has_feature(cxx_unrestricted_unions)`` to determine if support for |
| 774 | unrestricted unions is enabled. |
| 775 | |
| 776 | C++11 user-defined literals |
| 777 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 778 | |
| 779 | Use ``__has_feature(cxx_user_literals)`` to determine if support for |
| 780 | user-defined literals is enabled. |
| 781 | |
| 782 | C++11 variadic templates |
| 783 | ^^^^^^^^^^^^^^^^^^^^^^^^ |
| 784 | |
| 785 | Use ``__has_feature(cxx_variadic_templates)`` or |
| 786 | ``__has_extension(cxx_variadic_templates)`` to determine if support for |
| 787 | variadic templates is enabled. |
| 788 | |
Richard Smith | 0a71542 | 2013-05-07 19:32:56 +0000 | [diff] [blame] | 789 | C++1y |
| 790 | ----- |
| 791 | |
| 792 | The features listed below are part of the committee draft for the C++1y |
| 793 | standard. As a result, all these features are enabled with the ``-std=c++1y`` |
| 794 | or ``-std=gnu++1y`` option when compiling C++ code. |
| 795 | |
| 796 | C++1y binary literals |
| 797 | ^^^^^^^^^^^^^^^^^^^^^ |
| 798 | |
| 799 | Use ``__has_feature(cxx_binary_literals)`` or |
| 800 | ``__has_extension(cxx_binary_literals)`` to determine whether |
| 801 | binary literals (for instance, ``0b10010``) are recognized. Clang supports this |
| 802 | feature as an extension in all language modes. |
| 803 | |
| 804 | C++1y contextual conversions |
| 805 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 806 | |
| 807 | Use ``__has_feature(cxx_contextual_conversions)`` or |
| 808 | ``__has_extension(cxx_contextual_conversions)`` to determine if the C++1y rules |
| 809 | are used when performing an implicit conversion for an array bound in a |
| 810 | *new-expression*, the operand of a *delete-expression*, an integral constant |
Richard Smith | c0f7b81 | 2013-07-24 17:41:31 +0000 | [diff] [blame] | 811 | expression, or a condition in a ``switch`` statement. |
Richard Smith | 0a71542 | 2013-05-07 19:32:56 +0000 | [diff] [blame] | 812 | |
| 813 | C++1y decltype(auto) |
| 814 | ^^^^^^^^^^^^^^^^^^^^ |
| 815 | |
| 816 | Use ``__has_feature(cxx_decltype_auto)`` or |
| 817 | ``__has_extension(cxx_decltype_auto)`` to determine if support |
| 818 | for the ``decltype(auto)`` placeholder type is enabled. |
| 819 | |
| 820 | C++1y default initializers for aggregates |
| 821 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 822 | |
| 823 | Use ``__has_feature(cxx_aggregate_nsdmi)`` or |
| 824 | ``__has_extension(cxx_aggregate_nsdmi)`` to determine if support |
| 825 | for default initializers in aggregate members is enabled. |
| 826 | |
| 827 | C++1y generalized lambda capture |
| 828 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 829 | |
Richard Smith | 4fb0972 | 2013-07-24 17:51:13 +0000 | [diff] [blame] | 830 | Use ``__has_feature(cxx_init_capture)`` or |
| 831 | ``__has_extension(cxx_init_capture)`` to determine if support for |
| 832 | lambda captures with explicit initializers is enabled |
Richard Smith | 0a71542 | 2013-05-07 19:32:56 +0000 | [diff] [blame] | 833 | (for instance, ``[n(0)] { return ++n; }``). |
Richard Smith | 0a71542 | 2013-05-07 19:32:56 +0000 | [diff] [blame] | 834 | |
| 835 | C++1y generic lambdas |
| 836 | ^^^^^^^^^^^^^^^^^^^^^ |
| 837 | |
| 838 | Use ``__has_feature(cxx_generic_lambda)`` or |
| 839 | ``__has_extension(cxx_generic_lambda)`` to determine if support for generic |
| 840 | (polymorphic) lambdas is enabled |
| 841 | (for instance, ``[] (auto x) { return x + 1; }``). |
Richard Smith | 0a71542 | 2013-05-07 19:32:56 +0000 | [diff] [blame] | 842 | |
| 843 | C++1y relaxed constexpr |
| 844 | ^^^^^^^^^^^^^^^^^^^^^^^ |
| 845 | |
| 846 | Use ``__has_feature(cxx_relaxed_constexpr)`` or |
| 847 | ``__has_extension(cxx_relaxed_constexpr)`` to determine if variable |
| 848 | declarations, local variable modification, and control flow constructs |
| 849 | are permitted in ``constexpr`` functions. |
Richard Smith | 0a71542 | 2013-05-07 19:32:56 +0000 | [diff] [blame] | 850 | |
| 851 | C++1y return type deduction |
| 852 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 853 | |
| 854 | Use ``__has_feature(cxx_return_type_deduction)`` or |
| 855 | ``__has_extension(cxx_return_type_deduction)`` to determine if support |
| 856 | for return type deduction for functions (using ``auto`` as a return type) |
| 857 | is enabled. |
Richard Smith | 0a71542 | 2013-05-07 19:32:56 +0000 | [diff] [blame] | 858 | |
| 859 | C++1y runtime-sized arrays |
| 860 | ^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 861 | |
| 862 | Use ``__has_feature(cxx_runtime_array)`` or |
| 863 | ``__has_extension(cxx_runtime_array)`` to determine if support |
| 864 | for arrays of runtime bound (a restricted form of variable-length arrays) |
| 865 | is enabled. |
| 866 | Clang's implementation of this feature is incomplete. |
| 867 | |
| 868 | C++1y variable templates |
| 869 | ^^^^^^^^^^^^^^^^^^^^^^^^ |
| 870 | |
| 871 | Use ``__has_feature(cxx_variable_templates)`` or |
| 872 | ``__has_extension(cxx_variable_templates)`` to determine if support for |
| 873 | templated variable declarations is enabled. |
Richard Smith | 0a71542 | 2013-05-07 19:32:56 +0000 | [diff] [blame] | 874 | |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 875 | C11 |
| 876 | --- |
| 877 | |
| 878 | The features listed below are part of the C11 standard. As a result, all these |
| 879 | features are enabled with the ``-std=c11`` or ``-std=gnu11`` option when |
| 880 | compiling C code. Additionally, because these features are all |
| 881 | backward-compatible, they are available as extensions in all language modes. |
| 882 | |
| 883 | C11 alignment specifiers |
| 884 | ^^^^^^^^^^^^^^^^^^^^^^^^ |
| 885 | |
| 886 | Use ``__has_feature(c_alignas)`` or ``__has_extension(c_alignas)`` to determine |
| 887 | if support for alignment specifiers using ``_Alignas`` is enabled. |
| 888 | |
| 889 | C11 atomic operations |
| 890 | ^^^^^^^^^^^^^^^^^^^^^ |
| 891 | |
| 892 | Use ``__has_feature(c_atomic)`` or ``__has_extension(c_atomic)`` to determine |
| 893 | if support for atomic types using ``_Atomic`` is enabled. Clang also provides |
| 894 | :ref:`a set of builtins <langext-__c11_atomic>` which can be used to implement |
| 895 | the ``<stdatomic.h>`` operations on ``_Atomic`` types. |
| 896 | |
| 897 | C11 generic selections |
| 898 | ^^^^^^^^^^^^^^^^^^^^^^ |
| 899 | |
| 900 | Use ``__has_feature(c_generic_selections)`` or |
| 901 | ``__has_extension(c_generic_selections)`` to determine if support for generic |
| 902 | selections is enabled. |
| 903 | |
| 904 | As an extension, the C11 generic selection expression is available in all |
| 905 | languages supported by Clang. The syntax is the same as that given in the C11 |
| 906 | standard. |
| 907 | |
| 908 | In C, type compatibility is decided according to the rules given in the |
| 909 | appropriate standard, but in C++, which lacks the type compatibility rules used |
| 910 | in C, types are considered compatible only if they are equivalent. |
| 911 | |
| 912 | C11 ``_Static_assert()`` |
| 913 | ^^^^^^^^^^^^^^^^^^^^^^^^ |
| 914 | |
| 915 | Use ``__has_feature(c_static_assert)`` or ``__has_extension(c_static_assert)`` |
| 916 | to determine if support for compile-time assertions using ``_Static_assert`` is |
| 917 | enabled. |
| 918 | |
Richard Smith | 25b555a | 2013-04-19 17:00:31 +0000 | [diff] [blame] | 919 | C11 ``_Thread_local`` |
| 920 | ^^^^^^^^^^^^^^^^^^^^^ |
| 921 | |
Ed Schouten | 401aeba | 2013-09-14 16:17:20 +0000 | [diff] [blame] | 922 | Use ``__has_feature(c_thread_local)`` or ``__has_extension(c_thread_local)`` |
| 923 | to determine if support for ``_Thread_local`` variables is enabled. |
Richard Smith | 25b555a | 2013-04-19 17:00:31 +0000 | [diff] [blame] | 924 | |
Alp Toker | 64197b9 | 2014-01-18 21:49:02 +0000 | [diff] [blame] | 925 | Checks for Type Trait Primitives |
| 926 | ================================ |
| 927 | |
| 928 | Type trait primitives are special builtin constant expressions that can be used |
| 929 | by the standard C++ library to facilitate or simplify the implementation of |
| 930 | user-facing type traits in the <type_traits> header. |
| 931 | |
| 932 | They are not intended to be used directly by user code because they are |
| 933 | implementation-defined and subject to change -- as such they're tied closely to |
| 934 | the supported set of system headers, currently: |
| 935 | |
| 936 | * LLVM's own libc++ |
| 937 | * GNU libstdc++ |
| 938 | * The Microsoft standard C++ library |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 939 | |
| 940 | Clang supports the `GNU C++ type traits |
| 941 | <http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html>`_ and a subset of the |
| 942 | `Microsoft Visual C++ Type traits |
Alp Toker | 64197b9 | 2014-01-18 21:49:02 +0000 | [diff] [blame] | 943 | <http://msdn.microsoft.com/en-us/library/ms177194(v=VS.100).aspx>`_. |
| 944 | |
| 945 | Feature detection is supported only for some of the primitives at present. User |
| 946 | code should not use these checks because they bear no direct relation to the |
| 947 | actual set of type traits supported by the C++ standard library. |
| 948 | |
| 949 | For type trait ``__X``, ``__has_extension(X)`` indicates the presence of the |
| 950 | type trait primitive in the compiler. A simplistic usage example as might be |
| 951 | seen in standard C++ headers follows: |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 952 | |
| 953 | .. code-block:: c++ |
| 954 | |
| 955 | #if __has_extension(is_convertible_to) |
| 956 | template<typename From, typename To> |
| 957 | struct is_convertible_to { |
| 958 | static const bool value = __is_convertible_to(From, To); |
| 959 | }; |
| 960 | #else |
Alp Toker | 64197b9 | 2014-01-18 21:49:02 +0000 | [diff] [blame] | 961 | // Emulate type trait for compatibility with other compilers. |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 962 | #endif |
| 963 | |
Alp Toker | 64197b9 | 2014-01-18 21:49:02 +0000 | [diff] [blame] | 964 | The following type trait primitives are supported by Clang: |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 965 | |
| 966 | * ``__has_nothrow_assign`` (GNU, Microsoft) |
| 967 | * ``__has_nothrow_copy`` (GNU, Microsoft) |
| 968 | * ``__has_nothrow_constructor`` (GNU, Microsoft) |
| 969 | * ``__has_trivial_assign`` (GNU, Microsoft) |
| 970 | * ``__has_trivial_copy`` (GNU, Microsoft) |
| 971 | * ``__has_trivial_constructor`` (GNU, Microsoft) |
| 972 | * ``__has_trivial_destructor`` (GNU, Microsoft) |
| 973 | * ``__has_virtual_destructor`` (GNU, Microsoft) |
| 974 | * ``__is_abstract`` (GNU, Microsoft) |
| 975 | * ``__is_base_of`` (GNU, Microsoft) |
| 976 | * ``__is_class`` (GNU, Microsoft) |
| 977 | * ``__is_convertible_to`` (Microsoft) |
| 978 | * ``__is_empty`` (GNU, Microsoft) |
| 979 | * ``__is_enum`` (GNU, Microsoft) |
| 980 | * ``__is_interface_class`` (Microsoft) |
| 981 | * ``__is_pod`` (GNU, Microsoft) |
| 982 | * ``__is_polymorphic`` (GNU, Microsoft) |
| 983 | * ``__is_union`` (GNU, Microsoft) |
| 984 | * ``__is_literal(type)``: Determines whether the given type is a literal type |
| 985 | * ``__is_final``: Determines whether the given type is declared with a |
| 986 | ``final`` class-virt-specifier. |
| 987 | * ``__underlying_type(type)``: Retrieves the underlying type for a given |
| 988 | ``enum`` type. This trait is required to implement the C++11 standard |
| 989 | library. |
| 990 | * ``__is_trivially_assignable(totype, fromtype)``: Determines whether a value |
| 991 | of type ``totype`` can be assigned to from a value of type ``fromtype`` such |
| 992 | that no non-trivial functions are called as part of that assignment. This |
| 993 | trait is required to implement the C++11 standard library. |
| 994 | * ``__is_trivially_constructible(type, argtypes...)``: Determines whether a |
| 995 | value of type ``type`` can be direct-initialized with arguments of types |
| 996 | ``argtypes...`` such that no non-trivial functions are called as part of |
| 997 | that initialization. This trait is required to implement the C++11 standard |
| 998 | library. |
Alp Toker | 73287bf | 2014-01-20 00:24:09 +0000 | [diff] [blame] | 999 | * ``__is_destructible`` (MSVC 2013): partially implemented |
| 1000 | * ``__is_nothrow_destructible`` (MSVC 2013): partially implemented |
| 1001 | * ``__is_nothrow_assignable`` (MSVC 2013, clang) |
| 1002 | * ``__is_constructible`` (MSVC 2013, clang) |
| 1003 | * ``__is_nothrow_constructible`` (MSVC 2013, clang) |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 1004 | |
| 1005 | Blocks |
| 1006 | ====== |
| 1007 | |
| 1008 | The syntax and high level language feature description is in |
Michael Gottesman | 6fd5846 | 2013-01-07 22:24:45 +0000 | [diff] [blame] | 1009 | :doc:`BlockLanguageSpec<BlockLanguageSpec>`. Implementation and ABI details for |
| 1010 | the clang implementation are in :doc:`Block-ABI-Apple<Block-ABI-Apple>`. |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 1011 | |
| 1012 | Query for this feature with ``__has_extension(blocks)``. |
| 1013 | |
| 1014 | Objective-C Features |
| 1015 | ==================== |
| 1016 | |
| 1017 | Related result types |
| 1018 | -------------------- |
| 1019 | |
| 1020 | According to Cocoa conventions, Objective-C methods with certain names |
| 1021 | ("``init``", "``alloc``", etc.) always return objects that are an instance of |
| 1022 | the receiving class's type. Such methods are said to have a "related result |
| 1023 | type", meaning that a message send to one of these methods will have the same |
| 1024 | static type as an instance of the receiver class. For example, given the |
| 1025 | following classes: |
| 1026 | |
| 1027 | .. code-block:: objc |
| 1028 | |
| 1029 | @interface NSObject |
| 1030 | + (id)alloc; |
| 1031 | - (id)init; |
| 1032 | @end |
| 1033 | |
| 1034 | @interface NSArray : NSObject |
| 1035 | @end |
| 1036 | |
| 1037 | and this common initialization pattern |
| 1038 | |
| 1039 | .. code-block:: objc |
| 1040 | |
| 1041 | NSArray *array = [[NSArray alloc] init]; |
| 1042 | |
| 1043 | the type of the expression ``[NSArray alloc]`` is ``NSArray*`` because |
| 1044 | ``alloc`` implicitly has a related result type. Similarly, the type of the |
| 1045 | expression ``[[NSArray alloc] init]`` is ``NSArray*``, since ``init`` has a |
| 1046 | related result type and its receiver is known to have the type ``NSArray *``. |
| 1047 | If neither ``alloc`` nor ``init`` had a related result type, the expressions |
| 1048 | would have had type ``id``, as declared in the method signature. |
| 1049 | |
| 1050 | A method with a related result type can be declared by using the type |
| 1051 | ``instancetype`` as its result type. ``instancetype`` is a contextual keyword |
| 1052 | that is only permitted in the result type of an Objective-C method, e.g. |
| 1053 | |
| 1054 | .. code-block:: objc |
| 1055 | |
| 1056 | @interface A |
| 1057 | + (instancetype)constructAnA; |
| 1058 | @end |
| 1059 | |
| 1060 | The related result type can also be inferred for some methods. To determine |
| 1061 | whether a method has an inferred related result type, the first word in the |
| 1062 | camel-case selector (e.g., "``init``" in "``initWithObjects``") is considered, |
| 1063 | and the method will have a related result type if its return type is compatible |
| 1064 | with the type of its class and if: |
| 1065 | |
| 1066 | * the first word is "``alloc``" or "``new``", and the method is a class method, |
| 1067 | or |
| 1068 | |
| 1069 | * the first word is "``autorelease``", "``init``", "``retain``", or "``self``", |
| 1070 | and the method is an instance method. |
| 1071 | |
| 1072 | If a method with a related result type is overridden by a subclass method, the |
| 1073 | subclass method must also return a type that is compatible with the subclass |
| 1074 | type. For example: |
| 1075 | |
| 1076 | .. code-block:: objc |
| 1077 | |
| 1078 | @interface NSString : NSObject |
| 1079 | - (NSUnrelated *)init; // incorrect usage: NSUnrelated is not NSString or a superclass of NSString |
| 1080 | @end |
| 1081 | |
| 1082 | Related result types only affect the type of a message send or property access |
| 1083 | via the given method. In all other respects, a method with a related result |
| 1084 | type is treated the same way as method that returns ``id``. |
| 1085 | |
| 1086 | Use ``__has_feature(objc_instancetype)`` to determine whether the |
| 1087 | ``instancetype`` contextual keyword is available. |
| 1088 | |
| 1089 | Automatic reference counting |
| 1090 | ---------------------------- |
| 1091 | |
Sean Silva | 173d252 | 2013-01-02 13:07:47 +0000 | [diff] [blame] | 1092 | Clang provides support for :doc:`automated reference counting |
| 1093 | <AutomaticReferenceCounting>` in Objective-C, which eliminates the need |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 1094 | for manual ``retain``/``release``/``autorelease`` message sends. There are two |
| 1095 | feature macros associated with automatic reference counting: |
| 1096 | ``__has_feature(objc_arc)`` indicates the availability of automated reference |
| 1097 | counting in general, while ``__has_feature(objc_arc_weak)`` indicates that |
| 1098 | automated reference counting also includes support for ``__weak`` pointers to |
| 1099 | Objective-C objects. |
| 1100 | |
Sean Silva | 173d252 | 2013-01-02 13:07:47 +0000 | [diff] [blame] | 1101 | .. _objc-fixed-enum: |
| 1102 | |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 1103 | Enumerations with a fixed underlying type |
| 1104 | ----------------------------------------- |
| 1105 | |
| 1106 | Clang provides support for C++11 enumerations with a fixed underlying type |
| 1107 | within Objective-C. For example, one can write an enumeration type as: |
| 1108 | |
| 1109 | .. code-block:: c++ |
| 1110 | |
| 1111 | typedef enum : unsigned char { Red, Green, Blue } Color; |
| 1112 | |
| 1113 | This specifies that the underlying type, which is used to store the enumeration |
| 1114 | value, is ``unsigned char``. |
| 1115 | |
| 1116 | Use ``__has_feature(objc_fixed_enum)`` to determine whether support for fixed |
| 1117 | underlying types is available in Objective-C. |
| 1118 | |
| 1119 | Interoperability with C++11 lambdas |
| 1120 | ----------------------------------- |
| 1121 | |
| 1122 | Clang provides interoperability between C++11 lambdas and blocks-based APIs, by |
| 1123 | permitting a lambda to be implicitly converted to a block pointer with the |
| 1124 | corresponding signature. For example, consider an API such as ``NSArray``'s |
| 1125 | array-sorting method: |
| 1126 | |
| 1127 | .. code-block:: objc |
| 1128 | |
| 1129 | - (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr; |
| 1130 | |
| 1131 | ``NSComparator`` is simply a typedef for the block pointer ``NSComparisonResult |
| 1132 | (^)(id, id)``, and parameters of this type are generally provided with block |
| 1133 | literals as arguments. However, one can also use a C++11 lambda so long as it |
| 1134 | provides the same signature (in this case, accepting two parameters of type |
| 1135 | ``id`` and returning an ``NSComparisonResult``): |
| 1136 | |
| 1137 | .. code-block:: objc |
| 1138 | |
| 1139 | NSArray *array = @[@"string 1", @"string 21", @"string 12", @"String 11", |
| 1140 | @"String 02"]; |
| 1141 | const NSStringCompareOptions comparisonOptions |
| 1142 | = NSCaseInsensitiveSearch | NSNumericSearch | |
| 1143 | NSWidthInsensitiveSearch | NSForcedOrderingSearch; |
| 1144 | NSLocale *currentLocale = [NSLocale currentLocale]; |
| 1145 | NSArray *sorted |
| 1146 | = [array sortedArrayUsingComparator:[=](id s1, id s2) -> NSComparisonResult { |
| 1147 | NSRange string1Range = NSMakeRange(0, [s1 length]); |
| 1148 | return [s1 compare:s2 options:comparisonOptions |
| 1149 | range:string1Range locale:currentLocale]; |
| 1150 | }]; |
| 1151 | NSLog(@"sorted: %@", sorted); |
| 1152 | |
| 1153 | This code relies on an implicit conversion from the type of the lambda |
| 1154 | expression (an unnamed, local class type called the *closure type*) to the |
| 1155 | corresponding block pointer type. The conversion itself is expressed by a |
| 1156 | conversion operator in that closure type that produces a block pointer with the |
| 1157 | same signature as the lambda itself, e.g., |
| 1158 | |
| 1159 | .. code-block:: objc |
| 1160 | |
| 1161 | operator NSComparisonResult (^)(id, id)() const; |
| 1162 | |
| 1163 | This conversion function returns a new block that simply forwards the two |
| 1164 | parameters to the lambda object (which it captures by copy), then returns the |
| 1165 | result. The returned block is first copied (with ``Block_copy``) and then |
| 1166 | autoreleased. As an optimization, if a lambda expression is immediately |
| 1167 | converted to a block pointer (as in the first example, above), then the block |
| 1168 | is not copied and autoreleased: rather, it is given the same lifetime as a |
| 1169 | block literal written at that point in the program, which avoids the overhead |
| 1170 | of copying a block to the heap in the common case. |
| 1171 | |
| 1172 | The conversion from a lambda to a block pointer is only available in |
| 1173 | Objective-C++, and not in C++ with blocks, due to its use of Objective-C memory |
| 1174 | management (autorelease). |
| 1175 | |
| 1176 | Object Literals and Subscripting |
| 1177 | -------------------------------- |
| 1178 | |
Sean Silva | 173d252 | 2013-01-02 13:07:47 +0000 | [diff] [blame] | 1179 | Clang provides support for :doc:`Object Literals and Subscripting |
| 1180 | <ObjectiveCLiterals>` in Objective-C, which simplifies common Objective-C |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 1181 | programming patterns, makes programs more concise, and improves the safety of |
| 1182 | container creation. There are several feature macros associated with object |
| 1183 | literals and subscripting: ``__has_feature(objc_array_literals)`` tests the |
| 1184 | availability of array literals; ``__has_feature(objc_dictionary_literals)`` |
| 1185 | tests the availability of dictionary literals; |
| 1186 | ``__has_feature(objc_subscripting)`` tests the availability of object |
| 1187 | subscripting. |
| 1188 | |
| 1189 | Objective-C Autosynthesis of Properties |
| 1190 | --------------------------------------- |
| 1191 | |
| 1192 | Clang provides support for autosynthesis of declared properties. Using this |
| 1193 | feature, clang provides default synthesis of those properties not declared |
| 1194 | @dynamic and not having user provided backing getter and setter methods. |
| 1195 | ``__has_feature(objc_default_synthesize_properties)`` checks for availability |
| 1196 | of this feature in version of clang being used. |
| 1197 | |
Jordan Rose | 32e9489 | 2012-12-15 00:37:01 +0000 | [diff] [blame] | 1198 | .. _langext-objc_method_family: |
| 1199 | |
Ted Kremenek | c3481f4 | 2013-10-23 22:14:59 +0000 | [diff] [blame] | 1200 | |
Ted Kremenek | 7f7a483 | 2013-10-23 22:41:52 +0000 | [diff] [blame] | 1201 | Objective-C requiring a call to ``super`` in an override |
| 1202 | -------------------------------------------------------- |
Ted Kremenek | f2ee81d | 2013-10-23 22:15:01 +0000 | [diff] [blame] | 1203 | |
Ted Kremenek | 7f7a483 | 2013-10-23 22:41:52 +0000 | [diff] [blame] | 1204 | Some Objective-C classes allow a subclass to override a particular method in a |
Warren Hunt | e0bc980 | 2013-10-24 00:59:24 +0000 | [diff] [blame] | 1205 | parent class but expect that the overriding method also calls the overridden |
| 1206 | method in the parent class. For these cases, we provide an attribute to |
| 1207 | designate that a method requires a "call to ``super``" in the overriding |
| 1208 | method in the subclass. |
Ted Kremenek | f2ee81d | 2013-10-23 22:15:01 +0000 | [diff] [blame] | 1209 | |
Warren Hunt | e0bc980 | 2013-10-24 00:59:24 +0000 | [diff] [blame] | 1210 | **Usage**: ``__attribute__((objc_requires_super))``. This attribute can only |
| 1211 | be placed at the end of a method declaration: |
Ted Kremenek | f2ee81d | 2013-10-23 22:15:01 +0000 | [diff] [blame] | 1212 | |
| 1213 | .. code-block:: objc |
| 1214 | |
| 1215 | - (void)foo __attribute__((objc_requires_super)); |
| 1216 | |
Warren Hunt | e0bc980 | 2013-10-24 00:59:24 +0000 | [diff] [blame] | 1217 | This attribute can only be applied the method declarations within a class, and |
| 1218 | not a protocol. Currently this attribute does not enforce any placement of |
| 1219 | where the call occurs in the overriding method (such as in the case of |
| 1220 | ``-dealloc`` where the call must appear at the end). It checks only that it |
| 1221 | exists. |
Ted Kremenek | f2ee81d | 2013-10-23 22:15:01 +0000 | [diff] [blame] | 1222 | |
| 1223 | Note that on both OS X and iOS that the Foundation framework provides a |
Ted Kremenek | 620cde3 | 2013-10-23 22:25:59 +0000 | [diff] [blame] | 1224 | convenience macro ``NS_REQUIRES_SUPER`` that provides syntactic sugar for this |
Ted Kremenek | f2ee81d | 2013-10-23 22:15:01 +0000 | [diff] [blame] | 1225 | attribute: |
| 1226 | |
| 1227 | .. code-block:: objc |
| 1228 | |
| 1229 | - (void)foo NS_REQUIRES_SUPER; |
| 1230 | |
| 1231 | This macro is conditionally defined depending on the compiler's support for |
| 1232 | this attribute. If the compiler does not support the attribute the macro |
| 1233 | expands to nothing. |
| 1234 | |
| 1235 | Operationally, when a method has this annotation the compiler will warn if the |
| 1236 | implementation of an override in a subclass does not call super. For example: |
| 1237 | |
| 1238 | .. code-block:: objc |
| 1239 | |
| 1240 | warning: method possibly missing a [super AnnotMeth] call |
| 1241 | - (void) AnnotMeth{}; |
| 1242 | ^ |
| 1243 | |
Ted Kremenek | c3481f4 | 2013-10-23 22:14:59 +0000 | [diff] [blame] | 1244 | Objective-C Method Families |
| 1245 | --------------------------- |
Jordan Rose | 32e9489 | 2012-12-15 00:37:01 +0000 | [diff] [blame] | 1246 | |
| 1247 | Many methods in Objective-C have conventional meanings determined by their |
| 1248 | selectors. It is sometimes useful to be able to mark a method as having a |
| 1249 | particular conventional meaning despite not having the right selector, or as |
| 1250 | not having the conventional meaning that its selector would suggest. For these |
| 1251 | use cases, we provide an attribute to specifically describe the "method family" |
| 1252 | that a method belongs to. |
| 1253 | |
| 1254 | **Usage**: ``__attribute__((objc_method_family(X)))``, where ``X`` is one of |
| 1255 | ``none``, ``alloc``, ``copy``, ``init``, ``mutableCopy``, or ``new``. This |
| 1256 | attribute can only be placed at the end of a method declaration: |
| 1257 | |
| 1258 | .. code-block:: objc |
| 1259 | |
| 1260 | - (NSString *)initMyStringValue __attribute__((objc_method_family(none))); |
| 1261 | |
| 1262 | Users who do not wish to change the conventional meaning of a method, and who |
| 1263 | merely want to document its non-standard retain and release semantics, should |
| 1264 | use the :ref:`retaining behavior attributes <langext-objc-retain-release>` |
| 1265 | described below. |
| 1266 | |
| 1267 | Query for this feature with ``__has_attribute(objc_method_family)``. |
| 1268 | |
| 1269 | .. _langext-objc-retain-release: |
| 1270 | |
| 1271 | Objective-C retaining behavior attributes |
| 1272 | ----------------------------------------- |
| 1273 | |
| 1274 | In Objective-C, functions and methods are generally assumed to follow the |
| 1275 | `Cocoa Memory Management |
| 1276 | <http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html>`_ |
| 1277 | conventions for ownership of object arguments and |
| 1278 | return values. However, there are exceptions, and so Clang provides attributes |
| 1279 | to allow these exceptions to be documented. This are used by ARC and the |
| 1280 | `static analyzer <http://clang-analyzer.llvm.org>`_ Some exceptions may be |
| 1281 | better described using the :ref:`objc_method_family |
| 1282 | <langext-objc_method_family>` attribute instead. |
| 1283 | |
| 1284 | **Usage**: The ``ns_returns_retained``, ``ns_returns_not_retained``, |
| 1285 | ``ns_returns_autoreleased``, ``cf_returns_retained``, and |
| 1286 | ``cf_returns_not_retained`` attributes can be placed on methods and functions |
| 1287 | that return Objective-C or CoreFoundation objects. They are commonly placed at |
| 1288 | the end of a function prototype or method declaration: |
| 1289 | |
| 1290 | .. code-block:: objc |
| 1291 | |
| 1292 | id foo() __attribute__((ns_returns_retained)); |
| 1293 | |
| 1294 | - (NSString *)bar:(int)x __attribute__((ns_returns_retained)); |
| 1295 | |
| 1296 | The ``*_returns_retained`` attributes specify that the returned object has a +1 |
| 1297 | retain count. The ``*_returns_not_retained`` attributes specify that the return |
| 1298 | object has a +0 retain count, even if the normal convention for its selector |
| 1299 | would be +1. ``ns_returns_autoreleased`` specifies that the returned object is |
| 1300 | +0, but is guaranteed to live at least as long as the next flush of an |
| 1301 | autorelease pool. |
| 1302 | |
| 1303 | **Usage**: The ``ns_consumed`` and ``cf_consumed`` attributes can be placed on |
| 1304 | an parameter declaration; they specify that the argument is expected to have a |
| 1305 | +1 retain count, which will be balanced in some way by the function or method. |
| 1306 | The ``ns_consumes_self`` attribute can only be placed on an Objective-C |
| 1307 | method; it specifies that the method expects its ``self`` parameter to have a |
| 1308 | +1 retain count, which it will balance in some way. |
| 1309 | |
| 1310 | .. code-block:: objc |
| 1311 | |
| 1312 | void foo(__attribute__((ns_consumed)) NSString *string); |
| 1313 | |
| 1314 | - (void) bar __attribute__((ns_consumes_self)); |
| 1315 | - (void) baz:(id) __attribute__((ns_consumed)) x; |
| 1316 | |
| 1317 | Further examples of these attributes are available in the static analyzer's `list of annotations for analysis |
| 1318 | <http://clang-analyzer.llvm.org/annotations.html#cocoa_mem>`_. |
| 1319 | |
| 1320 | Query for these features with ``__has_attribute(ns_consumed)``, |
| 1321 | ``__has_attribute(ns_returns_retained)``, etc. |
| 1322 | |
| 1323 | |
Ted Kremenek | 84342d6 | 2013-10-15 04:28:42 +0000 | [diff] [blame] | 1324 | Objective-C++ ABI: protocol-qualifier mangling of parameters |
| 1325 | ------------------------------------------------------------ |
| 1326 | |
| 1327 | Starting with LLVM 3.4, Clang produces a new mangling for parameters whose |
| 1328 | type is a qualified-``id`` (e.g., ``id<Foo>``). This mangling allows such |
| 1329 | parameters to be differentiated from those with the regular unqualified ``id`` |
| 1330 | type. |
| 1331 | |
| 1332 | This was a non-backward compatible mangling change to the ABI. This change |
| 1333 | allows proper overloading, and also prevents mangling conflicts with template |
| 1334 | parameters of protocol-qualified type. |
| 1335 | |
| 1336 | Query the presence of this new mangling with |
| 1337 | ``__has_feature(objc_protocol_qualifier_mangling)``. |
| 1338 | |
Nick Lewycky | 35a6ef4 | 2014-01-11 02:50:57 +0000 | [diff] [blame] | 1339 | .. _langext-overloading: |
| 1340 | |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 1341 | Function Overloading in C |
| 1342 | ========================= |
| 1343 | |
| 1344 | Clang provides support for C++ function overloading in C. Function overloading |
| 1345 | in C is introduced using the ``overloadable`` attribute. For example, one |
| 1346 | might provide several overloaded versions of a ``tgsin`` function that invokes |
| 1347 | the appropriate standard function computing the sine of a value with ``float``, |
| 1348 | ``double``, or ``long double`` precision: |
| 1349 | |
| 1350 | .. code-block:: c |
| 1351 | |
| 1352 | #include <math.h> |
| 1353 | float __attribute__((overloadable)) tgsin(float x) { return sinf(x); } |
| 1354 | double __attribute__((overloadable)) tgsin(double x) { return sin(x); } |
| 1355 | long double __attribute__((overloadable)) tgsin(long double x) { return sinl(x); } |
| 1356 | |
| 1357 | Given these declarations, one can call ``tgsin`` with a ``float`` value to |
| 1358 | receive a ``float`` result, with a ``double`` to receive a ``double`` result, |
| 1359 | etc. Function overloading in C follows the rules of C++ function overloading |
| 1360 | to pick the best overload given the call arguments, with a few C-specific |
| 1361 | semantics: |
| 1362 | |
| 1363 | * Conversion from ``float`` or ``double`` to ``long double`` is ranked as a |
| 1364 | floating-point promotion (per C99) rather than as a floating-point conversion |
| 1365 | (as in C++). |
| 1366 | |
| 1367 | * A conversion from a pointer of type ``T*`` to a pointer of type ``U*`` is |
| 1368 | considered a pointer conversion (with conversion rank) if ``T`` and ``U`` are |
| 1369 | compatible types. |
| 1370 | |
| 1371 | * A conversion from type ``T`` to a value of type ``U`` is permitted if ``T`` |
| 1372 | and ``U`` are compatible types. This conversion is given "conversion" rank. |
| 1373 | |
| 1374 | The declaration of ``overloadable`` functions is restricted to function |
| 1375 | declarations and definitions. Most importantly, if any function with a given |
| 1376 | name is given the ``overloadable`` attribute, then all function declarations |
| 1377 | and definitions with that name (and in that scope) must have the |
| 1378 | ``overloadable`` attribute. This rule even applies to redeclarations of |
| 1379 | functions whose original declaration had the ``overloadable`` attribute, e.g., |
| 1380 | |
| 1381 | .. code-block:: c |
| 1382 | |
| 1383 | int f(int) __attribute__((overloadable)); |
| 1384 | float f(float); // error: declaration of "f" must have the "overloadable" attribute |
| 1385 | |
| 1386 | int g(int) __attribute__((overloadable)); |
| 1387 | int g(int) { } // error: redeclaration of "g" must also have the "overloadable" attribute |
| 1388 | |
| 1389 | Functions marked ``overloadable`` must have prototypes. Therefore, the |
| 1390 | following code is ill-formed: |
| 1391 | |
| 1392 | .. code-block:: c |
| 1393 | |
| 1394 | int h() __attribute__((overloadable)); // error: h does not have a prototype |
| 1395 | |
| 1396 | However, ``overloadable`` functions are allowed to use a ellipsis even if there |
| 1397 | are no named parameters (as is permitted in C++). This feature is particularly |
| 1398 | useful when combined with the ``unavailable`` attribute: |
| 1399 | |
| 1400 | .. code-block:: c++ |
| 1401 | |
| 1402 | void honeypot(...) __attribute__((overloadable, unavailable)); // calling me is an error |
| 1403 | |
| 1404 | Functions declared with the ``overloadable`` attribute have their names mangled |
| 1405 | according to the same rules as C++ function names. For example, the three |
| 1406 | ``tgsin`` functions in our motivating example get the mangled names |
| 1407 | ``_Z5tgsinf``, ``_Z5tgsind``, and ``_Z5tgsine``, respectively. There are two |
| 1408 | caveats to this use of name mangling: |
| 1409 | |
| 1410 | * Future versions of Clang may change the name mangling of functions overloaded |
| 1411 | in C, so you should not depend on an specific mangling. To be completely |
| 1412 | safe, we strongly urge the use of ``static inline`` with ``overloadable`` |
| 1413 | functions. |
| 1414 | |
| 1415 | * The ``overloadable`` attribute has almost no meaning when used in C++, |
| 1416 | because names will already be mangled and functions are already overloadable. |
| 1417 | However, when an ``overloadable`` function occurs within an ``extern "C"`` |
| 1418 | linkage specification, it's name *will* be mangled in the same way as it |
| 1419 | would in C. |
| 1420 | |
| 1421 | Query for this feature with ``__has_extension(attribute_overloadable)``. |
| 1422 | |
Nick Lewycky | 35a6ef4 | 2014-01-11 02:50:57 +0000 | [diff] [blame] | 1423 | Controlling Overload Resolution |
| 1424 | =============================== |
| 1425 | |
| 1426 | Clang introduces the ``enable_if`` attribute, which can be placed on function |
| 1427 | declarations to control which overload is selected based on the values of the |
| 1428 | function's arguments. When combined with the |
Nick Lewycky | ed91da7 | 2014-01-18 02:29:10 +0000 | [diff] [blame] | 1429 | :ref:`overloadable<langext-overloading>` attribute, this feature is also |
Nick Lewycky | 35a6ef4 | 2014-01-11 02:50:57 +0000 | [diff] [blame] | 1430 | available in C. |
| 1431 | |
| 1432 | .. code-block:: c++ |
| 1433 | |
Nick Lewycky | b9737cd | 2014-01-15 06:34:12 +0000 | [diff] [blame] | 1434 | int isdigit(int c); |
Nick Lewycky | b05a844 | 2014-01-28 06:20:56 +0000 | [diff] [blame] | 1435 | 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"))); |
Nick Lewycky | 35a6ef4 | 2014-01-11 02:50:57 +0000 | [diff] [blame] | 1436 | |
| 1437 | void foo(char c) { |
Nick Lewycky | b9737cd | 2014-01-15 06:34:12 +0000 | [diff] [blame] | 1438 | isdigit(c); |
Nick Lewycky | 35a6ef4 | 2014-01-11 02:50:57 +0000 | [diff] [blame] | 1439 | isdigit(10); |
| 1440 | isdigit(-10); // results in a compile-time error. |
| 1441 | } |
| 1442 | |
| 1443 | The enable_if attribute takes two arguments, the first is an expression written |
| 1444 | in terms of the function parameters, the second is a string explaining why this |
| 1445 | overload candidate could not be selected to be displayed in diagnostics. The |
| 1446 | expression is part of the function signature for the purposes of determining |
| 1447 | whether it is a redeclaration (following the rules used when determining |
| 1448 | whether a C++ template specialization is ODR-equivalent), but is not part of |
| 1449 | the type. |
| 1450 | |
Nick Lewycky | 8993f26 | 2014-01-28 07:03:46 +0000 | [diff] [blame] | 1451 | The enable_if expression is evaluated as if it were the body of a |
| 1452 | bool-returning constexpr function declared with the arguments of the function |
| 1453 | it is being applied to, then called with the parameters at the callsite. If the |
| 1454 | result is false or could not be determined through constant expression |
| 1455 | evaluation, then this overload will not be chosen and the provided string may |
| 1456 | be used in a diagnostic if the compile fails as a result. |
Nick Lewycky | 35a6ef4 | 2014-01-11 02:50:57 +0000 | [diff] [blame] | 1457 | |
| 1458 | Because the enable_if expression is an unevaluated context, there are no global |
| 1459 | state changes, nor the ability to pass information from the enable_if |
| 1460 | expression to the function body. For example, suppose we want calls to |
| 1461 | strnlen(strbuf, maxlen) to resolve to strnlen_chk(strbuf, maxlen, size of |
| 1462 | strbuf) only if the size of strbuf can be determined: |
| 1463 | |
| 1464 | .. code-block:: c++ |
| 1465 | |
| 1466 | __attribute__((always_inline)) |
| 1467 | static inline size_t strnlen(const char *s, size_t maxlen) |
| 1468 | __attribute__((overloadable)) |
| 1469 | __attribute__((enable_if(__builtin_object_size(s, 0) != -1))), |
| 1470 | "chosen when the buffer size is known but 'maxlen' is not"))) |
| 1471 | { |
| 1472 | return strnlen_chk(s, maxlen, __builtin_object_size(s, 0)); |
| 1473 | } |
| 1474 | |
| 1475 | Multiple enable_if attributes may be applied to a single declaration. In this |
| 1476 | case, the enable_if expressions are evaluated from left to right in the |
| 1477 | following manner. First, the candidates whose enable_if expressions evaluate to |
| 1478 | false or cannot be evaluated are discarded. If the remaining candidates do not |
| 1479 | share ODR-equivalent enable_if expressions, the overload resolution is |
| 1480 | ambiguous. Otherwise, enable_if overload resolution continues with the next |
| 1481 | enable_if attribute on the candidates that have not been discarded and have |
| 1482 | remaining enable_if attributes. In this way, we pick the most specific |
| 1483 | overload out of a number of viable overloads using enable_if. |
| 1484 | |
| 1485 | .. code-block:: c++ |
Nick Lewycky | 9c8754f | 2014-01-15 08:33:00 +0000 | [diff] [blame] | 1486 | |
Nick Lewycky | 35a6ef4 | 2014-01-11 02:50:57 +0000 | [diff] [blame] | 1487 | void f() __attribute__((enable_if(true, ""))); // #1 |
| 1488 | void f() __attribute__((enable_if(true, ""))) __attribute__((enable_if(true, ""))); // #2 |
| 1489 | |
| 1490 | void g(int i, int j) __attribute__((enable_if(i, ""))); // #1 |
| 1491 | void g(int i, int j) __attribute__((enable_if(j, ""))) __attribute__((enable_if(true))); // #2 |
| 1492 | |
| 1493 | In this example, a call to f() is always resolved to #2, as the first enable_if |
| 1494 | expression is ODR-equivalent for both declarations, but #1 does not have another |
| 1495 | enable_if expression to continue evaluating, so the next round of evaluation has |
| 1496 | only a single candidate. In a call to g(1, 1), the call is ambiguous even though |
| 1497 | #2 has more enable_if attributes, because the first enable_if expressions are |
| 1498 | not ODR-equivalent. |
| 1499 | |
| 1500 | Query for this feature with ``__has_attribute(enable_if)``. |
| 1501 | |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 1502 | Initializer lists for complex numbers in C |
| 1503 | ========================================== |
| 1504 | |
| 1505 | clang supports an extension which allows the following in C: |
| 1506 | |
| 1507 | .. code-block:: c++ |
| 1508 | |
| 1509 | #include <math.h> |
| 1510 | #include <complex.h> |
| 1511 | complex float x = { 1.0f, INFINITY }; // Init to (1, Inf) |
| 1512 | |
| 1513 | This construct is useful because there is no way to separately initialize the |
| 1514 | real and imaginary parts of a complex variable in standard C, given that clang |
| 1515 | does not support ``_Imaginary``. (Clang also supports the ``__real__`` and |
| 1516 | ``__imag__`` extensions from gcc, which help in some cases, but are not usable |
| 1517 | in static initializers.) |
| 1518 | |
| 1519 | Note that this extension does not allow eliding the braces; the meaning of the |
| 1520 | following two lines is different: |
| 1521 | |
| 1522 | .. code-block:: c++ |
| 1523 | |
| 1524 | complex float x[] = { { 1.0f, 1.0f } }; // [0] = (1, 1) |
| 1525 | complex float x[] = { 1.0f, 1.0f }; // [0] = (1, 0), [1] = (1, 0) |
| 1526 | |
| 1527 | This extension also works in C++ mode, as far as that goes, but does not apply |
| 1528 | to the C++ ``std::complex``. (In C++11, list initialization allows the same |
| 1529 | syntax to be used with ``std::complex`` with the same meaning.) |
| 1530 | |
| 1531 | Builtin Functions |
| 1532 | ================= |
| 1533 | |
| 1534 | Clang supports a number of builtin library functions with the same syntax as |
| 1535 | GCC, including things like ``__builtin_nan``, ``__builtin_constant_p``, |
| 1536 | ``__builtin_choose_expr``, ``__builtin_types_compatible_p``, |
| 1537 | ``__sync_fetch_and_add``, etc. In addition to the GCC builtins, Clang supports |
| 1538 | a number of builtins that GCC does not, which are listed here. |
| 1539 | |
| 1540 | Please note that Clang does not and will not support all of the GCC builtins |
| 1541 | for vector operations. Instead of using builtins, you should use the functions |
| 1542 | defined in target-specific header files like ``<xmmintrin.h>``, which define |
| 1543 | portable wrappers for these. Many of the Clang versions of these functions are |
| 1544 | implemented directly in terms of :ref:`extended vector support |
| 1545 | <langext-vectors>` instead of builtins, in order to reduce the number of |
| 1546 | builtins that we need to implement. |
| 1547 | |
| 1548 | ``__builtin_readcyclecounter`` |
| 1549 | ------------------------------ |
| 1550 | |
| 1551 | ``__builtin_readcyclecounter`` is used to access the cycle counter register (or |
| 1552 | a similar low-latency, high-accuracy clock) on those targets that support it. |
| 1553 | |
| 1554 | **Syntax**: |
| 1555 | |
| 1556 | .. code-block:: c++ |
| 1557 | |
| 1558 | __builtin_readcyclecounter() |
| 1559 | |
| 1560 | **Example of Use**: |
| 1561 | |
| 1562 | .. code-block:: c++ |
| 1563 | |
| 1564 | unsigned long long t0 = __builtin_readcyclecounter(); |
| 1565 | do_something(); |
| 1566 | unsigned long long t1 = __builtin_readcyclecounter(); |
| 1567 | unsigned long long cycles_to_do_something = t1 - t0; // assuming no overflow |
| 1568 | |
| 1569 | **Description**: |
| 1570 | |
| 1571 | The ``__builtin_readcyclecounter()`` builtin returns the cycle counter value, |
| 1572 | which may be either global or process/thread-specific depending on the target. |
| 1573 | As the backing counters often overflow quickly (on the order of seconds) this |
| 1574 | should only be used for timing small intervals. When not supported by the |
| 1575 | target, the return value is always zero. This builtin takes no arguments and |
| 1576 | produces an unsigned long long result. |
| 1577 | |
Tim Northover | bfe2e5f7 | 2013-05-23 19:14:12 +0000 | [diff] [blame] | 1578 | Query for this feature with ``__has_builtin(__builtin_readcyclecounter)``. Note |
| 1579 | that even if present, its use may depend on run-time privilege or other OS |
| 1580 | controlled state. |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 1581 | |
| 1582 | .. _langext-__builtin_shufflevector: |
| 1583 | |
| 1584 | ``__builtin_shufflevector`` |
| 1585 | --------------------------- |
| 1586 | |
| 1587 | ``__builtin_shufflevector`` is used to express generic vector |
| 1588 | permutation/shuffle/swizzle operations. This builtin is also very important |
| 1589 | for the implementation of various target-specific header files like |
| 1590 | ``<xmmintrin.h>``. |
| 1591 | |
| 1592 | **Syntax**: |
| 1593 | |
| 1594 | .. code-block:: c++ |
| 1595 | |
| 1596 | __builtin_shufflevector(vec1, vec2, index1, index2, ...) |
| 1597 | |
| 1598 | **Examples**: |
| 1599 | |
| 1600 | .. code-block:: c++ |
| 1601 | |
Craig Topper | 50ad5b7 | 2013-08-03 17:40:38 +0000 | [diff] [blame] | 1602 | // identity operation - return 4-element vector v1. |
| 1603 | __builtin_shufflevector(v1, v1, 0, 1, 2, 3) |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 1604 | |
| 1605 | // "Splat" element 0 of V1 into a 4-element result. |
| 1606 | __builtin_shufflevector(V1, V1, 0, 0, 0, 0) |
| 1607 | |
| 1608 | // Reverse 4-element vector V1. |
| 1609 | __builtin_shufflevector(V1, V1, 3, 2, 1, 0) |
| 1610 | |
| 1611 | // Concatenate every other element of 4-element vectors V1 and V2. |
| 1612 | __builtin_shufflevector(V1, V2, 0, 2, 4, 6) |
| 1613 | |
| 1614 | // Concatenate every other element of 8-element vectors V1 and V2. |
| 1615 | __builtin_shufflevector(V1, V2, 0, 2, 4, 6, 8, 10, 12, 14) |
| 1616 | |
Craig Topper | 50ad5b7 | 2013-08-03 17:40:38 +0000 | [diff] [blame] | 1617 | // Shuffle v1 with some elements being undefined |
| 1618 | __builtin_shufflevector(v1, v1, 3, -1, 1, -1) |
| 1619 | |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 1620 | **Description**: |
| 1621 | |
| 1622 | The first two arguments to ``__builtin_shufflevector`` are vectors that have |
| 1623 | the same element type. The remaining arguments are a list of integers that |
| 1624 | specify the elements indices of the first two vectors that should be extracted |
| 1625 | and returned in a new vector. These element indices are numbered sequentially |
| 1626 | starting with the first vector, continuing into the second vector. Thus, if |
| 1627 | ``vec1`` is a 4-element vector, index 5 would refer to the second element of |
Craig Topper | 50ad5b7 | 2013-08-03 17:40:38 +0000 | [diff] [blame] | 1628 | ``vec2``. An index of -1 can be used to indicate that the corresponding element |
| 1629 | in the returned vector is a don't care and can be optimized by the backend. |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 1630 | |
| 1631 | The result of ``__builtin_shufflevector`` is a vector with the same element |
| 1632 | type as ``vec1``/``vec2`` but that has an element count equal to the number of |
| 1633 | indices specified. |
| 1634 | |
| 1635 | Query for this feature with ``__has_builtin(__builtin_shufflevector)``. |
| 1636 | |
Hal Finkel | c4d7c82 | 2013-09-18 03:29:45 +0000 | [diff] [blame] | 1637 | ``__builtin_convertvector`` |
| 1638 | --------------------------- |
| 1639 | |
| 1640 | ``__builtin_convertvector`` is used to express generic vector |
| 1641 | type-conversion operations. The input vector and the output vector |
| 1642 | type must have the same number of elements. |
| 1643 | |
| 1644 | **Syntax**: |
| 1645 | |
| 1646 | .. code-block:: c++ |
| 1647 | |
| 1648 | __builtin_convertvector(src_vec, dst_vec_type) |
| 1649 | |
| 1650 | **Examples**: |
| 1651 | |
| 1652 | .. code-block:: c++ |
| 1653 | |
| 1654 | typedef double vector4double __attribute__((__vector_size__(32))); |
| 1655 | typedef float vector4float __attribute__((__vector_size__(16))); |
| 1656 | typedef short vector4short __attribute__((__vector_size__(8))); |
| 1657 | vector4float vf; vector4short vs; |
| 1658 | |
| 1659 | // convert from a vector of 4 floats to a vector of 4 doubles. |
| 1660 | __builtin_convertvector(vf, vector4double) |
| 1661 | // equivalent to: |
| 1662 | (vector4double) { (double) vf[0], (double) vf[1], (double) vf[2], (double) vf[3] } |
| 1663 | |
| 1664 | // convert from a vector of 4 shorts to a vector of 4 floats. |
| 1665 | __builtin_convertvector(vs, vector4float) |
| 1666 | // equivalent to: |
| 1667 | (vector4float) { (float) vf[0], (float) vf[1], (float) vf[2], (float) vf[3] } |
| 1668 | |
| 1669 | **Description**: |
| 1670 | |
| 1671 | The first argument to ``__builtin_convertvector`` is a vector, and the second |
| 1672 | argument is a vector type with the same number of elements as the first |
| 1673 | argument. |
| 1674 | |
| 1675 | The result of ``__builtin_convertvector`` is a vector with the same element |
| 1676 | type as the second argument, with a value defined in terms of the action of a |
| 1677 | C-style cast applied to each element of the first argument. |
| 1678 | |
| 1679 | Query for this feature with ``__has_builtin(__builtin_convertvector)``. |
| 1680 | |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 1681 | ``__builtin_unreachable`` |
| 1682 | ------------------------- |
| 1683 | |
| 1684 | ``__builtin_unreachable`` is used to indicate that a specific point in the |
| 1685 | program cannot be reached, even if the compiler might otherwise think it can. |
| 1686 | This is useful to improve optimization and eliminates certain warnings. For |
| 1687 | example, without the ``__builtin_unreachable`` in the example below, the |
| 1688 | compiler assumes that the inline asm can fall through and prints a "function |
| 1689 | declared '``noreturn``' should not return" warning. |
| 1690 | |
| 1691 | **Syntax**: |
| 1692 | |
| 1693 | .. code-block:: c++ |
| 1694 | |
| 1695 | __builtin_unreachable() |
| 1696 | |
| 1697 | **Example of use**: |
| 1698 | |
| 1699 | .. code-block:: c++ |
| 1700 | |
| 1701 | void myabort(void) __attribute__((noreturn)); |
| 1702 | void myabort(void) { |
| 1703 | asm("int3"); |
| 1704 | __builtin_unreachable(); |
| 1705 | } |
| 1706 | |
| 1707 | **Description**: |
| 1708 | |
| 1709 | The ``__builtin_unreachable()`` builtin has completely undefined behavior. |
| 1710 | Since it has undefined behavior, it is a statement that it is never reached and |
| 1711 | the optimizer can take advantage of this to produce better code. This builtin |
| 1712 | takes no arguments and produces a void result. |
| 1713 | |
| 1714 | Query for this feature with ``__has_builtin(__builtin_unreachable)``. |
| 1715 | |
| 1716 | ``__sync_swap`` |
| 1717 | --------------- |
| 1718 | |
| 1719 | ``__sync_swap`` is used to atomically swap integers or pointers in memory. |
| 1720 | |
| 1721 | **Syntax**: |
| 1722 | |
| 1723 | .. code-block:: c++ |
| 1724 | |
| 1725 | type __sync_swap(type *ptr, type value, ...) |
| 1726 | |
| 1727 | **Example of Use**: |
| 1728 | |
| 1729 | .. code-block:: c++ |
| 1730 | |
| 1731 | int old_value = __sync_swap(&value, new_value); |
| 1732 | |
| 1733 | **Description**: |
| 1734 | |
| 1735 | The ``__sync_swap()`` builtin extends the existing ``__sync_*()`` family of |
| 1736 | atomic intrinsics to allow code to atomically swap the current value with the |
| 1737 | new value. More importantly, it helps developers write more efficient and |
| 1738 | correct code by avoiding expensive loops around |
| 1739 | ``__sync_bool_compare_and_swap()`` or relying on the platform specific |
| 1740 | implementation details of ``__sync_lock_test_and_set()``. The |
| 1741 | ``__sync_swap()`` builtin is a full barrier. |
| 1742 | |
Richard Smith | 6cbd65d | 2013-07-11 02:27:57 +0000 | [diff] [blame] | 1743 | ``__builtin_addressof`` |
| 1744 | ----------------------- |
| 1745 | |
| 1746 | ``__builtin_addressof`` performs the functionality of the built-in ``&`` |
| 1747 | operator, ignoring any ``operator&`` overload. This is useful in constant |
| 1748 | expressions in C++11, where there is no other way to take the address of an |
| 1749 | object that overloads ``operator&``. |
| 1750 | |
| 1751 | **Example of use**: |
| 1752 | |
| 1753 | .. code-block:: c++ |
| 1754 | |
| 1755 | template<typename T> constexpr T *addressof(T &value) { |
| 1756 | return __builtin_addressof(value); |
| 1757 | } |
| 1758 | |
Michael Gottesman | c5cc9f1 | 2013-01-13 04:35:31 +0000 | [diff] [blame] | 1759 | Multiprecision Arithmetic Builtins |
| 1760 | ---------------------------------- |
| 1761 | |
| 1762 | Clang provides a set of builtins which expose multiprecision arithmetic in a |
| 1763 | manner amenable to C. They all have the following form: |
| 1764 | |
| 1765 | .. code-block:: c |
| 1766 | |
| 1767 | unsigned x = ..., y = ..., carryin = ..., carryout; |
| 1768 | unsigned sum = __builtin_addc(x, y, carryin, &carryout); |
| 1769 | |
| 1770 | Thus one can form a multiprecision addition chain in the following manner: |
| 1771 | |
| 1772 | .. code-block:: c |
| 1773 | |
| 1774 | unsigned *x, *y, *z, carryin=0, carryout; |
| 1775 | z[0] = __builtin_addc(x[0], y[0], carryin, &carryout); |
| 1776 | carryin = carryout; |
| 1777 | z[1] = __builtin_addc(x[1], y[1], carryin, &carryout); |
| 1778 | carryin = carryout; |
| 1779 | z[2] = __builtin_addc(x[2], y[2], carryin, &carryout); |
| 1780 | carryin = carryout; |
| 1781 | z[3] = __builtin_addc(x[3], y[3], carryin, &carryout); |
| 1782 | |
| 1783 | The complete list of builtins are: |
| 1784 | |
| 1785 | .. code-block:: c |
| 1786 | |
Michael Gottesman | 1534399 | 2013-06-18 20:40:40 +0000 | [diff] [blame] | 1787 | unsigned char __builtin_addcb (unsigned char x, unsigned char y, unsigned char carryin, unsigned char *carryout); |
Michael Gottesman | c5cc9f1 | 2013-01-13 04:35:31 +0000 | [diff] [blame] | 1788 | unsigned short __builtin_addcs (unsigned short x, unsigned short y, unsigned short carryin, unsigned short *carryout); |
| 1789 | unsigned __builtin_addc (unsigned x, unsigned y, unsigned carryin, unsigned *carryout); |
| 1790 | unsigned long __builtin_addcl (unsigned long x, unsigned long y, unsigned long carryin, unsigned long *carryout); |
| 1791 | unsigned long long __builtin_addcll(unsigned long long x, unsigned long long y, unsigned long long carryin, unsigned long long *carryout); |
Michael Gottesman | 1534399 | 2013-06-18 20:40:40 +0000 | [diff] [blame] | 1792 | unsigned char __builtin_subcb (unsigned char x, unsigned char y, unsigned char carryin, unsigned char *carryout); |
Michael Gottesman | c5cc9f1 | 2013-01-13 04:35:31 +0000 | [diff] [blame] | 1793 | unsigned short __builtin_subcs (unsigned short x, unsigned short y, unsigned short carryin, unsigned short *carryout); |
| 1794 | unsigned __builtin_subc (unsigned x, unsigned y, unsigned carryin, unsigned *carryout); |
| 1795 | unsigned long __builtin_subcl (unsigned long x, unsigned long y, unsigned long carryin, unsigned long *carryout); |
| 1796 | unsigned long long __builtin_subcll(unsigned long long x, unsigned long long y, unsigned long long carryin, unsigned long long *carryout); |
| 1797 | |
Michael Gottesman | 930ecdb | 2013-06-20 23:28:10 +0000 | [diff] [blame] | 1798 | Checked Arithmetic Builtins |
| 1799 | --------------------------- |
| 1800 | |
| 1801 | Clang provides a set of builtins that implement checked arithmetic for security |
| 1802 | critical applications in a manner that is fast and easily expressable in C. As |
| 1803 | an example of their usage: |
| 1804 | |
| 1805 | .. code-block:: c |
| 1806 | |
| 1807 | errorcode_t security_critical_application(...) { |
| 1808 | unsigned x, y, result; |
| 1809 | ... |
| 1810 | if (__builtin_umul_overflow(x, y, &result)) |
| 1811 | return kErrorCodeHackers; |
| 1812 | ... |
| 1813 | use_multiply(result); |
| 1814 | ... |
| 1815 | } |
| 1816 | |
| 1817 | A complete enumeration of the builtins are: |
| 1818 | |
| 1819 | .. code-block:: c |
| 1820 | |
| 1821 | bool __builtin_uadd_overflow (unsigned x, unsigned y, unsigned *sum); |
| 1822 | bool __builtin_uaddl_overflow (unsigned long x, unsigned long y, unsigned long *sum); |
| 1823 | bool __builtin_uaddll_overflow(unsigned long long x, unsigned long long y, unsigned long long *sum); |
| 1824 | bool __builtin_usub_overflow (unsigned x, unsigned y, unsigned *diff); |
| 1825 | bool __builtin_usubl_overflow (unsigned long x, unsigned long y, unsigned long *diff); |
| 1826 | bool __builtin_usubll_overflow(unsigned long long x, unsigned long long y, unsigned long long *diff); |
| 1827 | bool __builtin_umul_overflow (unsigned x, unsigned y, unsigned *prod); |
| 1828 | bool __builtin_umull_overflow (unsigned long x, unsigned long y, unsigned long *prod); |
| 1829 | bool __builtin_umulll_overflow(unsigned long long x, unsigned long long y, unsigned long long *prod); |
| 1830 | bool __builtin_sadd_overflow (int x, int y, int *sum); |
| 1831 | bool __builtin_saddl_overflow (long x, long y, long *sum); |
| 1832 | bool __builtin_saddll_overflow(long long x, long long y, long long *sum); |
| 1833 | bool __builtin_ssub_overflow (int x, int y, int *diff); |
| 1834 | bool __builtin_ssubl_overflow (long x, long y, long *diff); |
| 1835 | bool __builtin_ssubll_overflow(long long x, long long y, long long *diff); |
| 1836 | bool __builtin_smul_overflow (int x, int y, int *prod); |
| 1837 | bool __builtin_smull_overflow (long x, long y, long *prod); |
| 1838 | bool __builtin_smulll_overflow(long long x, long long y, long long *prod); |
| 1839 | |
| 1840 | |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 1841 | .. _langext-__c11_atomic: |
| 1842 | |
| 1843 | __c11_atomic builtins |
| 1844 | --------------------- |
| 1845 | |
| 1846 | Clang provides a set of builtins which are intended to be used to implement |
| 1847 | C11's ``<stdatomic.h>`` header. These builtins provide the semantics of the |
| 1848 | ``_explicit`` form of the corresponding C11 operation, and are named with a |
| 1849 | ``__c11_`` prefix. The supported operations are: |
| 1850 | |
| 1851 | * ``__c11_atomic_init`` |
| 1852 | * ``__c11_atomic_thread_fence`` |
| 1853 | * ``__c11_atomic_signal_fence`` |
| 1854 | * ``__c11_atomic_is_lock_free`` |
| 1855 | * ``__c11_atomic_store`` |
| 1856 | * ``__c11_atomic_load`` |
| 1857 | * ``__c11_atomic_exchange`` |
| 1858 | * ``__c11_atomic_compare_exchange_strong`` |
| 1859 | * ``__c11_atomic_compare_exchange_weak`` |
| 1860 | * ``__c11_atomic_fetch_add`` |
| 1861 | * ``__c11_atomic_fetch_sub`` |
| 1862 | * ``__c11_atomic_fetch_and`` |
| 1863 | * ``__c11_atomic_fetch_or`` |
| 1864 | * ``__c11_atomic_fetch_xor`` |
| 1865 | |
Tim Northover | 6aacd49 | 2013-07-16 09:47:53 +0000 | [diff] [blame] | 1866 | Low-level ARM exclusive memory builtins |
| 1867 | --------------------------------------- |
| 1868 | |
| 1869 | Clang provides overloaded builtins giving direct access to the three key ARM |
| 1870 | instructions for implementing atomic operations. |
| 1871 | |
| 1872 | .. code-block:: c |
Sean Silva | a928c24 | 2013-09-09 19:50:40 +0000 | [diff] [blame] | 1873 | |
Tim Northover | 6aacd49 | 2013-07-16 09:47:53 +0000 | [diff] [blame] | 1874 | T __builtin_arm_ldrex(const volatile T *addr); |
| 1875 | int __builtin_arm_strex(T val, volatile T *addr); |
| 1876 | void __builtin_arm_clrex(void); |
| 1877 | |
| 1878 | The types ``T`` currently supported are: |
| 1879 | * Integer types with width at most 64 bits. |
| 1880 | * Floating-point types |
| 1881 | * Pointer types. |
| 1882 | |
| 1883 | Note that the compiler does not guarantee it will not insert stores which clear |
| 1884 | the exclusive monitor in between an ``ldrex`` and its paired ``strex``. In |
| 1885 | practice this is only usually a risk when the extra store is on the same cache |
| 1886 | line as the variable being modified and Clang will only insert stack stores on |
| 1887 | its own, so it is best not to use these operations on variables with automatic |
| 1888 | storage duration. |
| 1889 | |
| 1890 | Also, loads and stores may be implicit in code written between the ``ldrex`` and |
| 1891 | ``strex``. Clang will not necessarily mitigate the effects of these either, so |
| 1892 | care should be exercised. |
| 1893 | |
| 1894 | For these reasons the higher level atomic primitives should be preferred where |
| 1895 | possible. |
| 1896 | |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 1897 | Non-standard C++11 Attributes |
| 1898 | ============================= |
| 1899 | |
Richard Smith | f6d2d3b | 2013-02-14 00:13:34 +0000 | [diff] [blame] | 1900 | Clang's non-standard C++11 attributes live in the ``clang`` attribute |
| 1901 | namespace. |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 1902 | |
| 1903 | The ``clang::fallthrough`` attribute |
| 1904 | ------------------------------------ |
| 1905 | |
| 1906 | The ``clang::fallthrough`` attribute is used along with the |
| 1907 | ``-Wimplicit-fallthrough`` argument to annotate intentional fall-through |
| 1908 | between switch labels. It can only be applied to a null statement placed at a |
| 1909 | point of execution between any statement and the next switch label. It is |
| 1910 | common to mark these places with a specific comment, but this attribute is |
| 1911 | meant to replace comments with a more strict annotation, which can be checked |
| 1912 | by the compiler. This attribute doesn't change semantics of the code and can |
| 1913 | be used wherever an intended fall-through occurs. It is designed to mimic |
| 1914 | control-flow statements like ``break;``, so it can be placed in most places |
| 1915 | where ``break;`` can, but only if there are no statements on the execution path |
| 1916 | between it and the next switch label. |
| 1917 | |
| 1918 | Here is an example: |
| 1919 | |
| 1920 | .. code-block:: c++ |
| 1921 | |
| 1922 | // compile with -Wimplicit-fallthrough |
| 1923 | switch (n) { |
| 1924 | case 22: |
| 1925 | case 33: // no warning: no statements between case labels |
| 1926 | f(); |
| 1927 | case 44: // warning: unannotated fall-through |
| 1928 | g(); |
| 1929 | [[clang::fallthrough]]; |
| 1930 | case 55: // no warning |
| 1931 | if (x) { |
| 1932 | h(); |
| 1933 | break; |
| 1934 | } |
| 1935 | else { |
| 1936 | i(); |
| 1937 | [[clang::fallthrough]]; |
| 1938 | } |
| 1939 | case 66: // no warning |
| 1940 | p(); |
| 1941 | [[clang::fallthrough]]; // warning: fallthrough annotation does not |
| 1942 | // directly precede case label |
| 1943 | q(); |
| 1944 | case 77: // warning: unannotated fall-through |
| 1945 | r(); |
| 1946 | } |
| 1947 | |
Richard Smith | f6d2d3b | 2013-02-14 00:13:34 +0000 | [diff] [blame] | 1948 | ``gnu::`` attributes |
| 1949 | -------------------- |
| 1950 | |
| 1951 | Clang also supports GCC's ``gnu`` attribute namespace. All GCC attributes which |
| 1952 | are accepted with the ``__attribute__((foo))`` syntax are also accepted as |
| 1953 | ``[[gnu::foo]]``. This only extends to attributes which are specified by GCC |
| 1954 | (see the list of `GCC function attributes |
| 1955 | <http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_, `GCC variable |
| 1956 | attributes <http://gcc.gnu.org/onlinedocs/gcc/Variable-Attributes.html>`_, and |
| 1957 | `GCC type attributes |
Richard Smith | ccfc9ff | 2013-07-11 00:27:05 +0000 | [diff] [blame] | 1958 | <http://gcc.gnu.org/onlinedocs/gcc/Type-Attributes.html>`_). As with the GCC |
Richard Smith | f6d2d3b | 2013-02-14 00:13:34 +0000 | [diff] [blame] | 1959 | implementation, these attributes must appertain to the *declarator-id* in a |
| 1960 | declaration, which means they must go either at the start of the declaration or |
| 1961 | immediately after the name being declared. |
| 1962 | |
| 1963 | For example, this applies the GNU ``unused`` attribute to ``a`` and ``f``, and |
| 1964 | also applies the GNU ``noreturn`` attribute to ``f``. |
| 1965 | |
| 1966 | .. code-block:: c++ |
| 1967 | |
| 1968 | [[gnu::unused]] int a, f [[gnu::noreturn]] (); |
| 1969 | |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 1970 | Target-Specific Extensions |
| 1971 | ========================== |
| 1972 | |
| 1973 | Clang supports some language features conditionally on some targets. |
| 1974 | |
| 1975 | X86/X86-64 Language Extensions |
| 1976 | ------------------------------ |
| 1977 | |
| 1978 | The X86 backend has these language extensions: |
| 1979 | |
| 1980 | Memory references off the GS segment |
| 1981 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1982 | |
| 1983 | Annotating a pointer with address space #256 causes it to be code generated |
| 1984 | relative to the X86 GS segment register, and address space #257 causes it to be |
| 1985 | relative to the X86 FS segment. Note that this is a very very low-level |
| 1986 | feature that should only be used if you know what you're doing (for example in |
| 1987 | an OS kernel). |
| 1988 | |
| 1989 | Here is an example: |
| 1990 | |
| 1991 | .. code-block:: c++ |
| 1992 | |
| 1993 | #define GS_RELATIVE __attribute__((address_space(256))) |
| 1994 | int foo(int GS_RELATIVE *P) { |
| 1995 | return *P; |
| 1996 | } |
| 1997 | |
| 1998 | Which compiles to (on X86-32): |
| 1999 | |
| 2000 | .. code-block:: gas |
| 2001 | |
| 2002 | _foo: |
| 2003 | movl 4(%esp), %eax |
| 2004 | movl %gs:(%eax), %eax |
| 2005 | ret |
| 2006 | |
Tim Northover | a484bc0 | 2013-10-01 14:34:25 +0000 | [diff] [blame] | 2007 | ARM Language Extensions |
| 2008 | ----------------------- |
| 2009 | |
| 2010 | Interrupt attribute |
| 2011 | ^^^^^^^^^^^^^^^^^^^ |
| 2012 | |
Alp Toker | 3b557ba | 2013-12-03 06:53:39 +0000 | [diff] [blame] | 2013 | Clang supports the GNU style ``__attribute__((interrupt("TYPE")))`` attribute on |
| 2014 | ARM targets. This attribute may be attached to a function definition and |
Tim Northover | a484bc0 | 2013-10-01 14:34:25 +0000 | [diff] [blame] | 2015 | instructs the backend to generate appropriate function entry/exit code so that |
| 2016 | it can be used directly as an interrupt service routine. |
| 2017 | |
DeLesley Hutchins | c51e08c | 2014-02-18 19:42:01 +0000 | [diff] [blame^] | 2018 | The parameter passed to the interrupt attribute is optional, but if |
Tim Northover | a484bc0 | 2013-10-01 14:34:25 +0000 | [diff] [blame] | 2019 | provided it must be a string literal with one of the following values: "IRQ", |
| 2020 | "FIQ", "SWI", "ABORT", "UNDEF". |
| 2021 | |
| 2022 | The semantics are as follows: |
| 2023 | |
| 2024 | - If the function is AAPCS, Clang instructs the backend to realign the stack to |
| 2025 | 8 bytes on entry. This is a general requirement of the AAPCS at public |
| 2026 | interfaces, but may not hold when an exception is taken. Doing this allows |
| 2027 | other AAPCS functions to be called. |
| 2028 | - If the CPU is M-class this is all that needs to be done since the architecture |
| 2029 | itself is designed in such a way that functions obeying the normal AAPCS ABI |
| 2030 | constraints are valid exception handlers. |
| 2031 | - If the CPU is not M-class, the prologue and epilogue are modified to save all |
| 2032 | non-banked registers that are used, so that upon return the user-mode state |
| 2033 | will not be corrupted. Note that to avoid unnecessary overhead, only |
| 2034 | general-purpose (integer) registers are saved in this way. If VFP operations |
| 2035 | are needed, that state must be saved manually. |
| 2036 | |
| 2037 | Specifically, interrupt kinds other than "FIQ" will save all core registers |
| 2038 | except "lr" and "sp". "FIQ" interrupts will save r0-r7. |
| 2039 | - If the CPU is not M-class, the return instruction is changed to one of the |
| 2040 | canonical sequences permitted by the architecture for exception return. Where |
| 2041 | possible the function itself will make the necessary "lr" adjustments so that |
| 2042 | the "preferred return address" is selected. |
| 2043 | |
Tim Northover | a77b7b8 | 2013-10-01 14:39:43 +0000 | [diff] [blame] | 2044 | Unfortunately the compiler is unable to make this guarantee for an "UNDEF" |
Tim Northover | a484bc0 | 2013-10-01 14:34:25 +0000 | [diff] [blame] | 2045 | handler, where the offset from "lr" to the preferred return address depends on |
| 2046 | the execution state of the code which generated the exception. In this case |
| 2047 | a sequence equivalent to "movs pc, lr" will be used. |
| 2048 | |
Jordan Rose | 32e9489 | 2012-12-15 00:37:01 +0000 | [diff] [blame] | 2049 | Extensions for Static Analysis |
Dmitri Gribenko | ace09a2 | 2012-12-15 14:25:25 +0000 | [diff] [blame] | 2050 | ============================== |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 2051 | |
| 2052 | Clang supports additional attributes that are useful for documenting program |
Jordan Rose | 32e9489 | 2012-12-15 00:37:01 +0000 | [diff] [blame] | 2053 | invariants and rules for static analysis tools, such as the `Clang Static |
| 2054 | Analyzer <http://clang-analyzer.llvm.org/>`_. These attributes are documented |
| 2055 | in the analyzer's `list of source-level annotations |
| 2056 | <http://clang-analyzer.llvm.org/annotations.html>`_. |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 2057 | |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 2058 | |
Jordan Rose | 32e9489 | 2012-12-15 00:37:01 +0000 | [diff] [blame] | 2059 | Extensions for Dynamic Analysis |
Dmitri Gribenko | ace09a2 | 2012-12-15 14:25:25 +0000 | [diff] [blame] | 2060 | =============================== |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 2061 | |
| 2062 | .. _langext-address_sanitizer: |
| 2063 | |
| 2064 | AddressSanitizer |
| 2065 | ---------------- |
| 2066 | |
| 2067 | Use ``__has_feature(address_sanitizer)`` to check if the code is being built |
Dmitri Gribenko | ace09a2 | 2012-12-15 14:25:25 +0000 | [diff] [blame] | 2068 | with :doc:`AddressSanitizer`. |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 2069 | |
Kostya Serebryany | 4c0fc99 | 2013-02-26 06:58:27 +0000 | [diff] [blame] | 2070 | Use ``__attribute__((no_sanitize_address))`` |
| 2071 | on a function declaration |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 2072 | to specify that address safety instrumentation (e.g. AddressSanitizer) should |
| 2073 | not be applied to that function. |
| 2074 | |
Kostya Serebryany | 4c0fc99 | 2013-02-26 06:58:27 +0000 | [diff] [blame] | 2075 | .. _langext-thread_sanitizer: |
| 2076 | |
| 2077 | ThreadSanitizer |
| 2078 | ---------------- |
| 2079 | |
| 2080 | Use ``__has_feature(thread_sanitizer)`` to check if the code is being built |
| 2081 | with :doc:`ThreadSanitizer`. |
| 2082 | |
| 2083 | Use ``__attribute__((no_sanitize_thread))`` on a function declaration |
| 2084 | to specify that checks for data races on plain (non-atomic) memory accesses |
| 2085 | should not be inserted by ThreadSanitizer. |
Dmitry Vyukov | ae4ea1d | 2013-10-17 08:06:19 +0000 | [diff] [blame] | 2086 | The function is still instrumented by the tool to avoid false positives and |
| 2087 | provide meaningful stack traces. |
Kostya Serebryany | 4c0fc99 | 2013-02-26 06:58:27 +0000 | [diff] [blame] | 2088 | |
| 2089 | .. _langext-memory_sanitizer: |
| 2090 | |
| 2091 | MemorySanitizer |
| 2092 | ---------------- |
| 2093 | Use ``__has_feature(memory_sanitizer)`` to check if the code is being built |
| 2094 | with :doc:`MemorySanitizer`. |
| 2095 | |
| 2096 | Use ``__attribute__((no_sanitize_memory))`` on a function declaration |
| 2097 | to specify that checks for uninitialized memory should not be inserted |
| 2098 | (e.g. by MemorySanitizer). The function may still be instrumented by the tool |
| 2099 | to avoid false positives in other places. |
| 2100 | |
| 2101 | |
DeLesley Hutchins | c51e08c | 2014-02-18 19:42:01 +0000 | [diff] [blame^] | 2102 | Thread Safety Analysis |
| 2103 | ====================== |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 2104 | |
DeLesley Hutchins | c51e08c | 2014-02-18 19:42:01 +0000 | [diff] [blame^] | 2105 | Clang Thread Safety Analysis is a C++ language extension which warns about |
| 2106 | potential race conditions in code. The analysis works very much like a type |
| 2107 | system for multi-threaded programs. In addition to declaring the *type* of |
| 2108 | data (e.g. ``int``, ``float``, etc.), the programmer can (optionally) declare |
| 2109 | how access to that data is controlled in a multi-threaded environment. The |
| 2110 | compiler will then issue warnings whenever code fails to follow obey the |
| 2111 | declared requirements. |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 2112 | |
DeLesley Hutchins | c51e08c | 2014-02-18 19:42:01 +0000 | [diff] [blame^] | 2113 | The complete list of thread safety attributes, along with examples and |
| 2114 | frequently asked questions, can be found in the main documentation: see |
| 2115 | :doc:`ThreadSafetyAnalysis`. |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 2116 | |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 2117 | |
DeLesley Hutchins | c2ecf0d | 2013-08-22 20:44:47 +0000 | [diff] [blame] | 2118 | Consumed Annotation Checking |
| 2119 | ============================ |
| 2120 | |
| 2121 | Clang supports additional attributes for checking basic resource management |
| 2122 | properties, specifically for unique objects that have a single owning reference. |
| 2123 | The following attributes are currently supported, although **the implementation |
| 2124 | for these annotations is currently in development and are subject to change.** |
| 2125 | |
Chris Wailes | 155df71 | 2013-10-21 20:54:06 +0000 | [diff] [blame] | 2126 | ``consumable`` |
| 2127 | -------------- |
DeLesley Hutchins | c2ecf0d | 2013-08-22 20:44:47 +0000 | [diff] [blame] | 2128 | |
Chris Wailes | 155df71 | 2013-10-21 20:54:06 +0000 | [diff] [blame] | 2129 | Each class that uses any of the following annotations must first be marked |
| 2130 | using the consumable attribute. Failure to do so will result in a warning. |
DeLesley Hutchins | c2ecf0d | 2013-08-22 20:44:47 +0000 | [diff] [blame] | 2131 | |
Chris Wailes | 155df71 | 2013-10-21 20:54:06 +0000 | [diff] [blame] | 2132 | ``set_typestate(new_state)`` |
DeLesley Hutchins | c2ecf0d | 2013-08-22 20:44:47 +0000 | [diff] [blame] | 2133 | ---------------------------- |
| 2134 | |
Chris Wailes | 155df71 | 2013-10-21 20:54:06 +0000 | [diff] [blame] | 2135 | Annotate methods that transition an object into a new state with |
| 2136 | ``__attribute__((set_typestate(new_state)))``. The new new state must be |
| 2137 | unconsumed, consumed, or unknown. |
DeLesley Hutchins | c2ecf0d | 2013-08-22 20:44:47 +0000 | [diff] [blame] | 2138 | |
Chris Wailes | 155df71 | 2013-10-21 20:54:06 +0000 | [diff] [blame] | 2139 | ``callable_when(...)`` |
| 2140 | ---------------------- |
DeLesley Hutchins | c2ecf0d | 2013-08-22 20:44:47 +0000 | [diff] [blame] | 2141 | |
Chris Wailes | 155df71 | 2013-10-21 20:54:06 +0000 | [diff] [blame] | 2142 | Use ``__attribute__((callable_when(...)))`` to indicate what states a method |
| 2143 | may be called in. Valid states are unconsumed, consumed, or unknown. Each |
| 2144 | argument to this attribute must be a quoted string. E.g.: |
DeLesley Hutchins | c2ecf0d | 2013-08-22 20:44:47 +0000 | [diff] [blame] | 2145 | |
Chris Wailes | 155df71 | 2013-10-21 20:54:06 +0000 | [diff] [blame] | 2146 | ``__attribute__((callable_when("unconsumed", "unknown")))`` |
| 2147 | |
| 2148 | ``tests_typestate(tested_state)`` |
| 2149 | --------------------------------- |
| 2150 | |
| 2151 | Use ``__attribute__((tests_typestate(tested_state)))`` to indicate that a method |
| 2152 | returns true if the object is in the specified state.. |
| 2153 | |
| 2154 | ``param_typestate(expected_state)`` |
| 2155 | ----------------------------------- |
| 2156 | |
| 2157 | This attribute specifies expectations about function parameters. Calls to an |
| 2158 | function with annotated parameters will issue a warning if the corresponding |
| 2159 | argument isn't in the expected state. The attribute is also used to set the |
| 2160 | initial state of the parameter when analyzing the function's body. |
| 2161 | |
| 2162 | ``return_typestate(ret_state)`` |
| 2163 | ------------------------------- |
| 2164 | |
| 2165 | The ``return_typestate`` attribute can be applied to functions or parameters. |
| 2166 | When applied to a function the attribute specifies the state of the returned |
| 2167 | value. The function's body is checked to ensure that it always returns a value |
| 2168 | in the specified state. On the caller side, values returned by the annotated |
| 2169 | function are initialized to the given state. |
| 2170 | |
| 2171 | If the attribute is applied to a function parameter it modifies the state of |
| 2172 | an argument after a call to the function returns. The function's body is |
| 2173 | checked to ensure that the parameter is in the expected state before returning. |
DeLesley Hutchins | c2ecf0d | 2013-08-22 20:44:47 +0000 | [diff] [blame] | 2174 | |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 2175 | Type Safety Checking |
| 2176 | ==================== |
| 2177 | |
| 2178 | Clang supports additional attributes to enable checking type safety properties |
Richard Smith | 36ee4fc | 2013-07-11 00:34:42 +0000 | [diff] [blame] | 2179 | that can't be enforced by the C type system. Use cases include: |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 2180 | |
| 2181 | * MPI library implementations, where these attributes enable checking that |
Richard Smith | 36ee4fc | 2013-07-11 00:34:42 +0000 | [diff] [blame] | 2182 | the buffer type matches the passed ``MPI_Datatype``; |
| 2183 | * for HDF5 library there is a similar use case to MPI; |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 2184 | * checking types of variadic functions' arguments for functions like |
| 2185 | ``fcntl()`` and ``ioctl()``. |
| 2186 | |
| 2187 | You can detect support for these attributes with ``__has_attribute()``. For |
| 2188 | example: |
| 2189 | |
| 2190 | .. code-block:: c++ |
| 2191 | |
| 2192 | #if defined(__has_attribute) |
| 2193 | # if __has_attribute(argument_with_type_tag) && \ |
| 2194 | __has_attribute(pointer_with_type_tag) && \ |
| 2195 | __has_attribute(type_tag_for_datatype) |
| 2196 | # define ATTR_MPI_PWT(buffer_idx, type_idx) __attribute__((pointer_with_type_tag(mpi,buffer_idx,type_idx))) |
| 2197 | /* ... other macros ... */ |
| 2198 | # endif |
| 2199 | #endif |
| 2200 | |
| 2201 | #if !defined(ATTR_MPI_PWT) |
| 2202 | # define ATTR_MPI_PWT(buffer_idx, type_idx) |
| 2203 | #endif |
| 2204 | |
| 2205 | int MPI_Send(void *buf, int count, MPI_Datatype datatype /*, other args omitted */) |
| 2206 | ATTR_MPI_PWT(1,3); |
| 2207 | |
| 2208 | ``argument_with_type_tag(...)`` |
| 2209 | ------------------------------- |
| 2210 | |
| 2211 | Use ``__attribute__((argument_with_type_tag(arg_kind, arg_idx, |
| 2212 | type_tag_idx)))`` on a function declaration to specify that the function |
| 2213 | accepts a type tag that determines the type of some other argument. |
| 2214 | ``arg_kind`` is an identifier that should be used when annotating all |
| 2215 | applicable type tags. |
| 2216 | |
| 2217 | This attribute is primarily useful for checking arguments of variadic functions |
Richard Smith | 36ee4fc | 2013-07-11 00:34:42 +0000 | [diff] [blame] | 2218 | (``pointer_with_type_tag`` can be used in most non-variadic cases). |
Sean Silva | 709c44d | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 2219 | |
| 2220 | For example: |
| 2221 | |
| 2222 | .. code-block:: c++ |
| 2223 | |
| 2224 | int fcntl(int fd, int cmd, ...) |
| 2225 | __attribute__(( argument_with_type_tag(fcntl,3,2) )); |
| 2226 | |
| 2227 | ``pointer_with_type_tag(...)`` |
| 2228 | ------------------------------ |
| 2229 | |
| 2230 | Use ``__attribute__((pointer_with_type_tag(ptr_kind, ptr_idx, type_tag_idx)))`` |
| 2231 | on a function declaration to specify that the function accepts a type tag that |
| 2232 | determines the pointee type of some other pointer argument. |
| 2233 | |
| 2234 | For example: |
| 2235 | |
| 2236 | .. code-block:: c++ |
| 2237 | |
| 2238 | int MPI_Send(void *buf, int count, MPI_Datatype datatype /*, other args omitted */) |
| 2239 | __attribute__(( pointer_with_type_tag(mpi,1,3) )); |
| 2240 | |
| 2241 | ``type_tag_for_datatype(...)`` |
| 2242 | ------------------------------ |
| 2243 | |
| 2244 | Clang supports annotating type tags of two forms. |
| 2245 | |
| 2246 | * **Type tag that is an expression containing a reference to some declared |
| 2247 | identifier.** Use ``__attribute__((type_tag_for_datatype(kind, type)))`` on a |
| 2248 | declaration with that identifier: |
| 2249 | |
| 2250 | .. code-block:: c++ |
| 2251 | |
| 2252 | extern struct mpi_datatype mpi_datatype_int |
| 2253 | __attribute__(( type_tag_for_datatype(mpi,int) )); |
| 2254 | #define MPI_INT ((MPI_Datatype) &mpi_datatype_int) |
| 2255 | |
| 2256 | * **Type tag that is an integral literal.** Introduce a ``static const`` |
| 2257 | variable with a corresponding initializer value and attach |
| 2258 | ``__attribute__((type_tag_for_datatype(kind, type)))`` on that declaration, |
| 2259 | for example: |
| 2260 | |
| 2261 | .. code-block:: c++ |
| 2262 | |
| 2263 | #define MPI_INT ((MPI_Datatype) 42) |
| 2264 | static const MPI_Datatype mpi_datatype_int |
| 2265 | __attribute__(( type_tag_for_datatype(mpi,int) )) = 42 |
| 2266 | |
| 2267 | The attribute also accepts an optional third argument that determines how the |
| 2268 | expression is compared to the type tag. There are two supported flags: |
| 2269 | |
| 2270 | * ``layout_compatible`` will cause types to be compared according to |
| 2271 | layout-compatibility rules (C++11 [class.mem] p 17, 18). This is |
| 2272 | implemented to support annotating types like ``MPI_DOUBLE_INT``. |
| 2273 | |
| 2274 | For example: |
| 2275 | |
| 2276 | .. code-block:: c++ |
| 2277 | |
| 2278 | /* In mpi.h */ |
| 2279 | struct internal_mpi_double_int { double d; int i; }; |
| 2280 | extern struct mpi_datatype mpi_datatype_double_int |
| 2281 | __attribute__(( type_tag_for_datatype(mpi, struct internal_mpi_double_int, layout_compatible) )); |
| 2282 | |
| 2283 | #define MPI_DOUBLE_INT ((MPI_Datatype) &mpi_datatype_double_int) |
| 2284 | |
| 2285 | /* In user code */ |
| 2286 | struct my_pair { double a; int b; }; |
| 2287 | struct my_pair *buffer; |
| 2288 | MPI_Send(buffer, 1, MPI_DOUBLE_INT /*, ... */); // no warning |
| 2289 | |
| 2290 | struct my_int_pair { int a; int b; } |
| 2291 | struct my_int_pair *buffer2; |
| 2292 | MPI_Send(buffer2, 1, MPI_DOUBLE_INT /*, ... */); // warning: actual buffer element |
| 2293 | // type 'struct my_int_pair' |
| 2294 | // doesn't match specified MPI_Datatype |
| 2295 | |
| 2296 | * ``must_be_null`` specifies that the expression should be a null pointer |
| 2297 | constant, for example: |
| 2298 | |
| 2299 | .. code-block:: c++ |
| 2300 | |
| 2301 | /* In mpi.h */ |
| 2302 | extern struct mpi_datatype mpi_datatype_null |
| 2303 | __attribute__(( type_tag_for_datatype(mpi, void, must_be_null) )); |
| 2304 | |
| 2305 | #define MPI_DATATYPE_NULL ((MPI_Datatype) &mpi_datatype_null) |
| 2306 | |
| 2307 | /* In user code */ |
| 2308 | MPI_Send(buffer, 1, MPI_DATATYPE_NULL /*, ... */); // warning: MPI_DATATYPE_NULL |
| 2309 | // was specified but buffer |
| 2310 | // is not a null pointer |
| 2311 | |
Dmitri Gribenko | dc81f51 | 2013-01-13 16:37:18 +0000 | [diff] [blame] | 2312 | Format String Checking |
| 2313 | ====================== |
| 2314 | |
| 2315 | Clang supports the ``format`` attribute, which indicates that the function |
| 2316 | accepts a ``printf`` or ``scanf``-like format string and corresponding |
| 2317 | arguments or a ``va_list`` that contains these arguments. |
| 2318 | |
| 2319 | Please see `GCC documentation about format attribute |
| 2320 | <http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_ to find details |
| 2321 | about attribute syntax. |
| 2322 | |
| 2323 | Clang implements two kinds of checks with this attribute. |
| 2324 | |
| 2325 | #. Clang checks that the function with the ``format`` attribute is called with |
| 2326 | a format string that uses format specifiers that are allowed, and that |
| 2327 | arguments match the format string. This is the ``-Wformat`` warning, it is |
| 2328 | on by default. |
| 2329 | |
| 2330 | #. Clang checks that the format string argument is a literal string. This is |
| 2331 | the ``-Wformat-nonliteral`` warning, it is off by default. |
| 2332 | |
| 2333 | Clang implements this mostly the same way as GCC, but there is a difference |
| 2334 | for functions that accept a ``va_list`` argument (for example, ``vprintf``). |
| 2335 | GCC does not emit ``-Wformat-nonliteral`` warning for calls to such |
| 2336 | fuctions. Clang does not warn if the format string comes from a function |
Richard Smith | fabbcd9 | 2013-02-14 00:22:00 +0000 | [diff] [blame] | 2337 | parameter, where the function is annotated with a compatible attribute, |
Dmitri Gribenko | dc81f51 | 2013-01-13 16:37:18 +0000 | [diff] [blame] | 2338 | otherwise it warns. For example: |
| 2339 | |
| 2340 | .. code-block:: c |
| 2341 | |
| 2342 | __attribute__((__format__ (__scanf__, 1, 3))) |
| 2343 | void foo(const char* s, char *buf, ...) { |
| 2344 | va_list ap; |
| 2345 | va_start(ap, buf); |
| 2346 | |
| 2347 | vprintf(s, ap); // warning: format string is not a string literal |
| 2348 | } |
| 2349 | |
| 2350 | In this case we warn because ``s`` contains a format string for a |
Richard Smith | fabbcd9 | 2013-02-14 00:22:00 +0000 | [diff] [blame] | 2351 | ``scanf``-like function, but it is passed to a ``printf``-like function. |
Dmitri Gribenko | dc81f51 | 2013-01-13 16:37:18 +0000 | [diff] [blame] | 2352 | |
| 2353 | If the attribute is removed, clang still warns, because the format string is |
| 2354 | not a string literal. |
| 2355 | |
Richard Smith | fabbcd9 | 2013-02-14 00:22:00 +0000 | [diff] [blame] | 2356 | Another example: |
Dmitri Gribenko | dc81f51 | 2013-01-13 16:37:18 +0000 | [diff] [blame] | 2357 | |
Richard Smith | d06a870 | 2013-02-14 00:23:04 +0000 | [diff] [blame] | 2358 | .. code-block:: c |
Dmitri Gribenko | dc81f51 | 2013-01-13 16:37:18 +0000 | [diff] [blame] | 2359 | |
| 2360 | __attribute__((__format__ (__printf__, 1, 3))) |
| 2361 | void foo(const char* s, char *buf, ...) { |
| 2362 | va_list ap; |
| 2363 | va_start(ap, buf); |
| 2364 | |
| 2365 | vprintf(s, ap); // warning |
| 2366 | } |
| 2367 | |
Richard Smith | fabbcd9 | 2013-02-14 00:22:00 +0000 | [diff] [blame] | 2368 | In this case Clang does not warn because the format string ``s`` and |
| 2369 | the corresponding arguments are annotated. If the arguments are |
| 2370 | incorrect, the caller of ``foo`` will receive a warning. |