Sean Silva | 3872b46 | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 1 | ========================= |
| 2 | Clang Language Extensions |
| 3 | ========================= |
| 4 | |
| 5 | .. contents:: |
| 6 | :local: |
| 7 | |
Sean Silva | a0c392d | 2013-01-02 21:03:11 +0000 | [diff] [blame^] | 8 | .. toctree:: |
| 9 | :hidden: |
| 10 | |
| 11 | ObjectiveCLiterals |
| 12 | BlockLanguageSpec |
| 13 | AutomaticReferenceCounting |
| 14 | |
Sean Silva | 3872b46 | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 15 | Introduction |
| 16 | ============ |
| 17 | |
| 18 | This document describes the language extensions provided by Clang. In addition |
| 19 | to the language extensions listed here, Clang aims to support a broad range of |
| 20 | GCC extensions. Please see the `GCC manual |
| 21 | <http://gcc.gnu.org/onlinedocs/gcc/C-Extensions.html>`_ for more information on |
| 22 | these extensions. |
| 23 | |
| 24 | .. _langext-feature_check: |
| 25 | |
| 26 | Feature Checking Macros |
| 27 | ======================= |
| 28 | |
| 29 | Language extensions can be very useful, but only if you know you can depend on |
| 30 | them. In order to allow fine-grain features checks, we support three builtin |
| 31 | function-like macros. This allows you to directly test for a feature in your |
| 32 | code without having to resort to something like autoconf or fragile "compiler |
| 33 | version checks". |
| 34 | |
| 35 | ``__has_builtin`` |
| 36 | ----------------- |
| 37 | |
| 38 | This function-like macro takes a single identifier argument that is the name of |
| 39 | a builtin function. It evaluates to 1 if the builtin is supported or 0 if not. |
| 40 | It can be used like this: |
| 41 | |
| 42 | .. code-block:: c++ |
| 43 | |
| 44 | #ifndef __has_builtin // Optional of course. |
| 45 | #define __has_builtin(x) 0 // Compatibility with non-clang compilers. |
| 46 | #endif |
| 47 | |
| 48 | ... |
| 49 | #if __has_builtin(__builtin_trap) |
| 50 | __builtin_trap(); |
| 51 | #else |
| 52 | abort(); |
| 53 | #endif |
| 54 | ... |
| 55 | |
| 56 | .. _langext-__has_feature-__has_extension: |
| 57 | |
| 58 | ``__has_feature`` and ``__has_extension`` |
| 59 | ----------------------------------------- |
| 60 | |
| 61 | These function-like macros take a single identifier argument that is the name |
| 62 | of a feature. ``__has_feature`` evaluates to 1 if the feature is both |
| 63 | supported by Clang and standardized in the current language standard or 0 if |
| 64 | not (but see :ref:`below <langext-has-feature-back-compat>`), while |
| 65 | ``__has_extension`` evaluates to 1 if the feature is supported by Clang in the |
| 66 | current language (either as a language extension or a standard language |
| 67 | feature) or 0 if not. They can be used like this: |
| 68 | |
| 69 | .. code-block:: c++ |
| 70 | |
| 71 | #ifndef __has_feature // Optional of course. |
| 72 | #define __has_feature(x) 0 // Compatibility with non-clang compilers. |
| 73 | #endif |
| 74 | #ifndef __has_extension |
| 75 | #define __has_extension __has_feature // Compatibility with pre-3.0 compilers. |
| 76 | #endif |
| 77 | |
| 78 | ... |
| 79 | #if __has_feature(cxx_rvalue_references) |
| 80 | // This code will only be compiled with the -std=c++11 and -std=gnu++11 |
| 81 | // options, because rvalue references are only standardized in C++11. |
| 82 | #endif |
| 83 | |
| 84 | #if __has_extension(cxx_rvalue_references) |
| 85 | // This code will be compiled with the -std=c++11, -std=gnu++11, -std=c++98 |
| 86 | // and -std=gnu++98 options, because rvalue references are supported as a |
| 87 | // language extension in C++98. |
| 88 | #endif |
| 89 | |
| 90 | .. _langext-has-feature-back-compat: |
| 91 | |
| 92 | For backwards compatibility reasons, ``__has_feature`` can also be used to test |
| 93 | for support for non-standardized features, i.e. features not prefixed ``c_``, |
| 94 | ``cxx_`` or ``objc_``. |
| 95 | |
| 96 | Another use of ``__has_feature`` is to check for compiler features not related |
Sean Silva | 159cc9e | 2013-01-02 13:07:47 +0000 | [diff] [blame] | 97 | to the language standard, such as e.g. :doc:`AddressSanitizer |
| 98 | <AddressSanitizer>`. |
Sean Silva | 3872b46 | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 99 | |
| 100 | If the ``-pedantic-errors`` option is given, ``__has_extension`` is equivalent |
| 101 | to ``__has_feature``. |
| 102 | |
| 103 | The feature tag is described along with the language feature below. |
| 104 | |
| 105 | The feature name or extension name can also be specified with a preceding and |
| 106 | following ``__`` (double underscore) to avoid interference from a macro with |
| 107 | the same name. For instance, ``__cxx_rvalue_references__`` can be used instead |
| 108 | of ``cxx_rvalue_references``. |
| 109 | |
| 110 | ``__has_attribute`` |
| 111 | ------------------- |
| 112 | |
| 113 | This function-like macro takes a single identifier argument that is the name of |
| 114 | an attribute. It evaluates to 1 if the attribute is supported or 0 if not. It |
| 115 | can be used like this: |
| 116 | |
| 117 | .. code-block:: c++ |
| 118 | |
| 119 | #ifndef __has_attribute // Optional of course. |
| 120 | #define __has_attribute(x) 0 // Compatibility with non-clang compilers. |
| 121 | #endif |
| 122 | |
| 123 | ... |
| 124 | #if __has_attribute(always_inline) |
| 125 | #define ALWAYS_INLINE __attribute__((always_inline)) |
| 126 | #else |
| 127 | #define ALWAYS_INLINE |
| 128 | #endif |
| 129 | ... |
| 130 | |
| 131 | The attribute name can also be specified with a preceding and following ``__`` |
| 132 | (double underscore) to avoid interference from a macro with the same name. For |
| 133 | instance, ``__always_inline__`` can be used instead of ``always_inline``. |
| 134 | |
| 135 | Include File Checking Macros |
| 136 | ============================ |
| 137 | |
| 138 | Not all developments systems have the same include files. The |
| 139 | :ref:`langext-__has_include` and :ref:`langext-__has_include_next` macros allow |
| 140 | you to check for the existence of an include file before doing a possibly |
| 141 | failing ``#include`` directive. |
| 142 | |
| 143 | .. _langext-__has_include: |
| 144 | |
| 145 | ``__has_include`` |
| 146 | ----------------- |
| 147 | |
| 148 | This function-like macro takes a single file name string argument that is the |
| 149 | name of an include file. It evaluates to 1 if the file can be found using the |
| 150 | include paths, or 0 otherwise: |
| 151 | |
| 152 | .. code-block:: c++ |
| 153 | |
| 154 | // Note the two possible file name string formats. |
| 155 | #if __has_include("myinclude.h") && __has_include(<stdint.h>) |
| 156 | # include "myinclude.h" |
| 157 | #endif |
| 158 | |
| 159 | // To avoid problem with non-clang compilers not having this macro. |
| 160 | #if defined(__has_include) && __has_include("myinclude.h") |
| 161 | # include "myinclude.h" |
| 162 | #endif |
| 163 | |
| 164 | To test for this feature, use ``#if defined(__has_include)``. |
| 165 | |
| 166 | .. _langext-__has_include_next: |
| 167 | |
| 168 | ``__has_include_next`` |
| 169 | ---------------------- |
| 170 | |
| 171 | This function-like macro takes a single file name string argument that is the |
| 172 | name of an include file. It is like ``__has_include`` except that it looks for |
| 173 | the second instance of the given file found in the include paths. It evaluates |
| 174 | to 1 if the second instance of the file can be found using the include paths, |
| 175 | or 0 otherwise: |
| 176 | |
| 177 | .. code-block:: c++ |
| 178 | |
| 179 | // Note the two possible file name string formats. |
| 180 | #if __has_include_next("myinclude.h") && __has_include_next(<stdint.h>) |
| 181 | # include_next "myinclude.h" |
| 182 | #endif |
| 183 | |
| 184 | // To avoid problem with non-clang compilers not having this macro. |
| 185 | #if defined(__has_include_next) && __has_include_next("myinclude.h") |
| 186 | # include_next "myinclude.h" |
| 187 | #endif |
| 188 | |
| 189 | Note that ``__has_include_next``, like the GNU extension ``#include_next`` |
| 190 | directive, is intended for use in headers only, and will issue a warning if |
| 191 | used in the top-level compilation file. A warning will also be issued if an |
| 192 | absolute path is used in the file argument. |
| 193 | |
| 194 | ``__has_warning`` |
| 195 | ----------------- |
| 196 | |
| 197 | This function-like macro takes a string literal that represents a command line |
| 198 | option for a warning and returns true if that is a valid warning option. |
| 199 | |
| 200 | .. code-block:: c++ |
| 201 | |
| 202 | #if __has_warning("-Wformat") |
| 203 | ... |
| 204 | #endif |
| 205 | |
| 206 | Builtin Macros |
| 207 | ============== |
| 208 | |
| 209 | ``__BASE_FILE__`` |
| 210 | Defined to a string that contains the name of the main input file passed to |
| 211 | Clang. |
| 212 | |
| 213 | ``__COUNTER__`` |
| 214 | Defined to an integer value that starts at zero and is incremented each time |
| 215 | the ``__COUNTER__`` macro is expanded. |
| 216 | |
| 217 | ``__INCLUDE_LEVEL__`` |
| 218 | Defined to an integral value that is the include depth of the file currently |
| 219 | being translated. For the main file, this value is zero. |
| 220 | |
| 221 | ``__TIMESTAMP__`` |
| 222 | Defined to the date and time of the last modification of the current source |
| 223 | file. |
| 224 | |
| 225 | ``__clang__`` |
| 226 | Defined when compiling with Clang |
| 227 | |
| 228 | ``__clang_major__`` |
| 229 | Defined to the major marketing version number of Clang (e.g., the 2 in |
| 230 | 2.0.1). Note that marketing version numbers should not be used to check for |
| 231 | language features, as different vendors use different numbering schemes. |
| 232 | Instead, use the :ref:`langext-feature_check`. |
| 233 | |
| 234 | ``__clang_minor__`` |
| 235 | Defined to the minor version number of Clang (e.g., the 0 in 2.0.1). Note |
| 236 | that marketing version numbers should not be used to check for language |
| 237 | features, as different vendors use different numbering schemes. Instead, use |
| 238 | the :ref:`langext-feature_check`. |
| 239 | |
| 240 | ``__clang_patchlevel__`` |
| 241 | Defined to the marketing patch level of Clang (e.g., the 1 in 2.0.1). |
| 242 | |
| 243 | ``__clang_version__`` |
| 244 | Defined to a string that captures the Clang marketing version, including the |
| 245 | Subversion tag or revision number, e.g., "``1.5 (trunk 102332)``". |
| 246 | |
| 247 | .. _langext-vectors: |
| 248 | |
| 249 | Vectors and Extended Vectors |
| 250 | ============================ |
| 251 | |
| 252 | Supports the GCC, OpenCL, AltiVec and NEON vector extensions. |
| 253 | |
| 254 | OpenCL vector types are created using ``ext_vector_type`` attribute. It |
| 255 | support for ``V.xyzw`` syntax and other tidbits as seen in OpenCL. An example |
| 256 | is: |
| 257 | |
| 258 | .. code-block:: c++ |
| 259 | |
| 260 | typedef float float4 __attribute__((ext_vector_type(4))); |
| 261 | typedef float float2 __attribute__((ext_vector_type(2))); |
| 262 | |
| 263 | float4 foo(float2 a, float2 b) { |
| 264 | float4 c; |
| 265 | c.xz = a; |
| 266 | c.yw = b; |
| 267 | return c; |
| 268 | } |
| 269 | |
| 270 | Query for this feature with ``__has_extension(attribute_ext_vector_type)``. |
| 271 | |
| 272 | Giving ``-faltivec`` option to clang enables support for AltiVec vector syntax |
| 273 | and functions. For example: |
| 274 | |
| 275 | .. code-block:: c++ |
| 276 | |
| 277 | vector float foo(vector int a) { |
| 278 | vector int b; |
| 279 | b = vec_add(a, a) + a; |
| 280 | return (vector float)b; |
| 281 | } |
| 282 | |
| 283 | NEON vector types are created using ``neon_vector_type`` and |
| 284 | ``neon_polyvector_type`` attributes. For example: |
| 285 | |
| 286 | .. code-block:: c++ |
| 287 | |
| 288 | typedef __attribute__((neon_vector_type(8))) int8_t int8x8_t; |
| 289 | typedef __attribute__((neon_polyvector_type(16))) poly8_t poly8x16_t; |
| 290 | |
| 291 | int8x8_t foo(int8x8_t a) { |
| 292 | int8x8_t v; |
| 293 | v = a; |
| 294 | return v; |
| 295 | } |
| 296 | |
| 297 | Vector Literals |
| 298 | --------------- |
| 299 | |
| 300 | Vector literals can be used to create vectors from a set of scalars, or |
| 301 | vectors. Either parentheses or braces form can be used. In the parentheses |
| 302 | form the number of literal values specified must be one, i.e. referring to a |
| 303 | scalar value, or must match the size of the vector type being created. If a |
| 304 | single scalar literal value is specified, the scalar literal value will be |
| 305 | replicated to all the components of the vector type. In the brackets form any |
| 306 | number of literals can be specified. For example: |
| 307 | |
| 308 | .. code-block:: c++ |
| 309 | |
| 310 | typedef int v4si __attribute__((__vector_size__(16))); |
| 311 | typedef float float4 __attribute__((ext_vector_type(4))); |
| 312 | typedef float float2 __attribute__((ext_vector_type(2))); |
| 313 | |
| 314 | v4si vsi = (v4si){1, 2, 3, 4}; |
| 315 | float4 vf = (float4)(1.0f, 2.0f, 3.0f, 4.0f); |
| 316 | vector int vi1 = (vector int)(1); // vi1 will be (1, 1, 1, 1). |
| 317 | vector int vi2 = (vector int){1}; // vi2 will be (1, 0, 0, 0). |
| 318 | vector int vi3 = (vector int)(1, 2); // error |
| 319 | vector int vi4 = (vector int){1, 2}; // vi4 will be (1, 2, 0, 0). |
| 320 | vector int vi5 = (vector int)(1, 2, 3, 4); |
| 321 | float4 vf = (float4)((float2)(1.0f, 2.0f), (float2)(3.0f, 4.0f)); |
| 322 | |
| 323 | Vector Operations |
| 324 | ----------------- |
| 325 | |
| 326 | The table below shows the support for each operation by vector extension. A |
| 327 | dash indicates that an operation is not accepted according to a corresponding |
| 328 | specification. |
| 329 | |
| 330 | ============================== ====== ======= === ==== |
| 331 | Opeator OpenCL AltiVec GCC NEON |
| 332 | ============================== ====== ======= === ==== |
| 333 | [] yes yes yes -- |
| 334 | unary operators +, -- yes yes yes -- |
| 335 | ++, -- -- yes yes yes -- |
| 336 | +,--,*,/,% yes yes yes -- |
| 337 | bitwise operators &,|,^,~ yes yes yes -- |
| 338 | >>,<< yes yes yes -- |
| 339 | !, &&, || no -- -- -- |
| 340 | ==, !=, >, <, >=, <= yes yes -- -- |
| 341 | = yes yes yes yes |
| 342 | :? yes -- -- -- |
| 343 | sizeof yes yes yes yes |
| 344 | ============================== ====== ======= === ==== |
| 345 | |
| 346 | See also :ref:`langext-__builtin_shufflevector`. |
| 347 | |
| 348 | Messages on ``deprecated`` and ``unavailable`` Attributes |
| 349 | ========================================================= |
| 350 | |
| 351 | An optional string message can be added to the ``deprecated`` and |
| 352 | ``unavailable`` attributes. For example: |
| 353 | |
| 354 | .. code-block:: c++ |
| 355 | |
| 356 | void explode(void) __attribute__((deprecated("extremely unsafe, use 'combust' instead!!!"))); |
| 357 | |
| 358 | If the deprecated or unavailable declaration is used, the message will be |
| 359 | incorporated into the appropriate diagnostic: |
| 360 | |
| 361 | .. code-block:: c++ |
| 362 | |
| 363 | harmless.c:4:3: warning: 'explode' is deprecated: extremely unsafe, use 'combust' instead!!! |
| 364 | [-Wdeprecated-declarations] |
| 365 | explode(); |
| 366 | ^ |
| 367 | |
| 368 | Query for this feature with |
| 369 | ``__has_extension(attribute_deprecated_with_message)`` and |
| 370 | ``__has_extension(attribute_unavailable_with_message)``. |
| 371 | |
| 372 | Attributes on Enumerators |
| 373 | ========================= |
| 374 | |
| 375 | Clang allows attributes to be written on individual enumerators. This allows |
| 376 | enumerators to be deprecated, made unavailable, etc. The attribute must appear |
| 377 | after the enumerator name and before any initializer, like so: |
| 378 | |
| 379 | .. code-block:: c++ |
| 380 | |
| 381 | enum OperationMode { |
| 382 | OM_Invalid, |
| 383 | OM_Normal, |
| 384 | OM_Terrified __attribute__((deprecated)), |
| 385 | OM_AbortOnError __attribute__((deprecated)) = 4 |
| 386 | }; |
| 387 | |
| 388 | Attributes on the ``enum`` declaration do not apply to individual enumerators. |
| 389 | |
| 390 | Query for this feature with ``__has_extension(enumerator_attributes)``. |
| 391 | |
| 392 | 'User-Specified' System Frameworks |
| 393 | ================================== |
| 394 | |
| 395 | Clang provides a mechanism by which frameworks can be built in such a way that |
| 396 | they will always be treated as being "system frameworks", even if they are not |
| 397 | present in a system framework directory. This can be useful to system |
| 398 | framework developers who want to be able to test building other applications |
| 399 | with development builds of their framework, including the manner in which the |
| 400 | compiler changes warning behavior for system headers. |
| 401 | |
| 402 | Framework developers can opt-in to this mechanism by creating a |
| 403 | "``.system_framework``" file at the top-level of their framework. That is, the |
| 404 | framework should have contents like: |
| 405 | |
| 406 | .. code-block:: none |
| 407 | |
| 408 | .../TestFramework.framework |
| 409 | .../TestFramework.framework/.system_framework |
| 410 | .../TestFramework.framework/Headers |
| 411 | .../TestFramework.framework/Headers/TestFramework.h |
| 412 | ... |
| 413 | |
| 414 | Clang will treat the presence of this file as an indicator that the framework |
| 415 | should be treated as a system framework, regardless of how it was found in the |
| 416 | framework search path. For consistency, we recommend that such files never be |
| 417 | included in installed versions of the framework. |
| 418 | |
| 419 | Availability attribute |
| 420 | ====================== |
| 421 | |
| 422 | Clang introduces the ``availability`` attribute, which can be placed on |
| 423 | declarations to describe the lifecycle of that declaration relative to |
| 424 | operating system versions. Consider the function declaration for a |
| 425 | hypothetical function ``f``: |
| 426 | |
| 427 | .. code-block:: c++ |
| 428 | |
| 429 | void f(void) __attribute__((availability(macosx,introduced=10.4,deprecated=10.6,obsoleted=10.7))); |
| 430 | |
| 431 | The availability attribute states that ``f`` was introduced in Mac OS X 10.4, |
| 432 | deprecated in Mac OS X 10.6, and obsoleted in Mac OS X 10.7. This information |
| 433 | is used by Clang to determine when it is safe to use ``f``: for example, if |
| 434 | Clang is instructed to compile code for Mac OS X 10.5, a call to ``f()`` |
| 435 | succeeds. If Clang is instructed to compile code for Mac OS X 10.6, the call |
| 436 | succeeds but Clang emits a warning specifying that the function is deprecated. |
| 437 | Finally, if Clang is instructed to compile code for Mac OS X 10.7, the call |
| 438 | fails because ``f()`` is no longer available. |
| 439 | |
| 440 | The availablility attribute is a comma-separated list starting with the |
| 441 | platform name and then including clauses specifying important milestones in the |
| 442 | declaration's lifetime (in any order) along with additional information. Those |
| 443 | clauses can be: |
| 444 | |
| 445 | introduced=\ *version* |
| 446 | The first version in which this declaration was introduced. |
| 447 | |
| 448 | deprecated=\ *version* |
| 449 | The first version in which this declaration was deprecated, meaning that |
| 450 | users should migrate away from this API. |
| 451 | |
| 452 | obsoleted=\ *version* |
| 453 | The first version in which this declaration was obsoleted, meaning that it |
| 454 | was removed completely and can no longer be used. |
| 455 | |
| 456 | unavailable |
| 457 | This declaration is never available on this platform. |
| 458 | |
| 459 | message=\ *string-literal* |
| 460 | Additional message text that Clang will provide when emitting a warning or |
| 461 | error about use of a deprecated or obsoleted declaration. Useful to direct |
| 462 | users to replacement APIs. |
| 463 | |
| 464 | Multiple availability attributes can be placed on a declaration, which may |
| 465 | correspond to different platforms. Only the availability attribute with the |
| 466 | platform corresponding to the target platform will be used; any others will be |
| 467 | ignored. If no availability attribute specifies availability for the current |
| 468 | target platform, the availability attributes are ignored. Supported platforms |
| 469 | are: |
| 470 | |
| 471 | ``ios`` |
| 472 | Apple's iOS operating system. The minimum deployment target is specified by |
| 473 | the ``-mios-version-min=*version*`` or ``-miphoneos-version-min=*version*`` |
| 474 | command-line arguments. |
| 475 | |
| 476 | ``macosx`` |
| 477 | Apple's Mac OS X operating system. The minimum deployment target is |
| 478 | specified by the ``-mmacosx-version-min=*version*`` command-line argument. |
| 479 | |
| 480 | A declaration can be used even when deploying back to a platform version prior |
| 481 | to when the declaration was introduced. When this happens, the declaration is |
| 482 | `weakly linked |
| 483 | <https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPFrameworks/Concepts/WeakLinking.html>`_, |
| 484 | as if the ``weak_import`` attribute were added to the declaration. A |
| 485 | weakly-linked declaration may or may not be present a run-time, and a program |
| 486 | can determine whether the declaration is present by checking whether the |
| 487 | address of that declaration is non-NULL. |
| 488 | |
| 489 | Checks for Standard Language Features |
| 490 | ===================================== |
| 491 | |
| 492 | The ``__has_feature`` macro can be used to query if certain standard language |
| 493 | features are enabled. The ``__has_extension`` macro can be used to query if |
| 494 | language features are available as an extension when compiling for a standard |
| 495 | which does not provide them. The features which can be tested are listed here. |
| 496 | |
| 497 | C++98 |
| 498 | ----- |
| 499 | |
| 500 | The features listed below are part of the C++98 standard. These features are |
| 501 | enabled by default when compiling C++ code. |
| 502 | |
| 503 | C++ exceptions |
| 504 | ^^^^^^^^^^^^^^ |
| 505 | |
| 506 | Use ``__has_feature(cxx_exceptions)`` to determine if C++ exceptions have been |
| 507 | enabled. For example, compiling code with ``-fno-exceptions`` disables C++ |
| 508 | exceptions. |
| 509 | |
| 510 | C++ RTTI |
| 511 | ^^^^^^^^ |
| 512 | |
| 513 | Use ``__has_feature(cxx_rtti)`` to determine if C++ RTTI has been enabled. For |
| 514 | example, compiling code with ``-fno-rtti`` disables the use of RTTI. |
| 515 | |
| 516 | C++11 |
| 517 | ----- |
| 518 | |
| 519 | The features listed below are part of the C++11 standard. As a result, all |
| 520 | these features are enabled with the ``-std=c++11`` or ``-std=gnu++11`` option |
| 521 | when compiling C++ code. |
| 522 | |
| 523 | C++11 SFINAE includes access control |
| 524 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 525 | |
| 526 | Use ``__has_feature(cxx_access_control_sfinae)`` or |
| 527 | ``__has_extension(cxx_access_control_sfinae)`` to determine whether |
| 528 | access-control errors (e.g., calling a private constructor) are considered to |
| 529 | be template argument deduction errors (aka SFINAE errors), per `C++ DR1170 |
| 530 | <http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1170>`_. |
| 531 | |
| 532 | C++11 alias templates |
| 533 | ^^^^^^^^^^^^^^^^^^^^^ |
| 534 | |
| 535 | Use ``__has_feature(cxx_alias_templates)`` or |
| 536 | ``__has_extension(cxx_alias_templates)`` to determine if support for C++11's |
| 537 | alias declarations and alias templates is enabled. |
| 538 | |
| 539 | C++11 alignment specifiers |
| 540 | ^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 541 | |
| 542 | Use ``__has_feature(cxx_alignas)`` or ``__has_extension(cxx_alignas)`` to |
| 543 | determine if support for alignment specifiers using ``alignas`` is enabled. |
| 544 | |
| 545 | C++11 attributes |
| 546 | ^^^^^^^^^^^^^^^^ |
| 547 | |
| 548 | Use ``__has_feature(cxx_attributes)`` or ``__has_extension(cxx_attributes)`` to |
| 549 | determine if support for attribute parsing with C++11's square bracket notation |
| 550 | is enabled. |
| 551 | |
| 552 | C++11 generalized constant expressions |
| 553 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 554 | |
| 555 | Use ``__has_feature(cxx_constexpr)`` to determine if support for generalized |
| 556 | constant expressions (e.g., ``constexpr``) is enabled. |
| 557 | |
| 558 | C++11 ``decltype()`` |
| 559 | ^^^^^^^^^^^^^^^^^^^^ |
| 560 | |
| 561 | Use ``__has_feature(cxx_decltype)`` or ``__has_extension(cxx_decltype)`` to |
| 562 | determine if support for the ``decltype()`` specifier is enabled. C++11's |
| 563 | ``decltype`` does not require type-completeness of a function call expression. |
| 564 | Use ``__has_feature(cxx_decltype_incomplete_return_types)`` or |
| 565 | ``__has_extension(cxx_decltype_incomplete_return_types)`` to determine if |
| 566 | support for this feature is enabled. |
| 567 | |
| 568 | C++11 default template arguments in function templates |
| 569 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 570 | |
| 571 | Use ``__has_feature(cxx_default_function_template_args)`` or |
| 572 | ``__has_extension(cxx_default_function_template_args)`` to determine if support |
| 573 | for default template arguments in function templates is enabled. |
| 574 | |
| 575 | C++11 ``default``\ ed functions |
| 576 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 577 | |
| 578 | Use ``__has_feature(cxx_defaulted_functions)`` or |
| 579 | ``__has_extension(cxx_defaulted_functions)`` to determine if support for |
| 580 | defaulted function definitions (with ``= default``) is enabled. |
| 581 | |
| 582 | C++11 delegating constructors |
| 583 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 584 | |
| 585 | Use ``__has_feature(cxx_delegating_constructors)`` to determine if support for |
| 586 | delegating constructors is enabled. |
| 587 | |
| 588 | C++11 ``deleted`` functions |
| 589 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 590 | |
| 591 | Use ``__has_feature(cxx_deleted_functions)`` or |
| 592 | ``__has_extension(cxx_deleted_functions)`` to determine if support for deleted |
| 593 | function definitions (with ``= delete``) is enabled. |
| 594 | |
| 595 | C++11 explicit conversion functions |
| 596 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 597 | |
| 598 | Use ``__has_feature(cxx_explicit_conversions)`` to determine if support for |
| 599 | ``explicit`` conversion functions is enabled. |
| 600 | |
| 601 | C++11 generalized initializers |
| 602 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 603 | |
| 604 | Use ``__has_feature(cxx_generalized_initializers)`` to determine if support for |
| 605 | generalized initializers (using braced lists and ``std::initializer_list``) is |
| 606 | enabled. |
| 607 | |
| 608 | C++11 implicit move constructors/assignment operators |
| 609 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 610 | |
| 611 | Use ``__has_feature(cxx_implicit_moves)`` to determine if Clang will implicitly |
| 612 | generate move constructors and move assignment operators where needed. |
| 613 | |
| 614 | C++11 inheriting constructors |
| 615 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 616 | |
| 617 | Use ``__has_feature(cxx_inheriting_constructors)`` to determine if support for |
| 618 | inheriting constructors is enabled. Clang does not currently implement this |
| 619 | feature. |
| 620 | |
| 621 | C++11 inline namespaces |
| 622 | ^^^^^^^^^^^^^^^^^^^^^^^ |
| 623 | |
| 624 | Use ``__has_feature(cxx_inline_namespaces)`` or |
| 625 | ``__has_extension(cxx_inline_namespaces)`` to determine if support for inline |
| 626 | namespaces is enabled. |
| 627 | |
| 628 | C++11 lambdas |
| 629 | ^^^^^^^^^^^^^ |
| 630 | |
| 631 | Use ``__has_feature(cxx_lambdas)`` or ``__has_extension(cxx_lambdas)`` to |
| 632 | determine if support for lambdas is enabled. |
| 633 | |
| 634 | C++11 local and unnamed types as template arguments |
| 635 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 636 | |
| 637 | Use ``__has_feature(cxx_local_type_template_args)`` or |
| 638 | ``__has_extension(cxx_local_type_template_args)`` to determine if support for |
| 639 | local and unnamed types as template arguments is enabled. |
| 640 | |
| 641 | C++11 noexcept |
| 642 | ^^^^^^^^^^^^^^ |
| 643 | |
| 644 | Use ``__has_feature(cxx_noexcept)`` or ``__has_extension(cxx_noexcept)`` to |
| 645 | determine if support for noexcept exception specifications is enabled. |
| 646 | |
| 647 | C++11 in-class non-static data member initialization |
| 648 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 649 | |
| 650 | Use ``__has_feature(cxx_nonstatic_member_init)`` to determine whether in-class |
| 651 | initialization of non-static data members is enabled. |
| 652 | |
| 653 | C++11 ``nullptr`` |
| 654 | ^^^^^^^^^^^^^^^^^ |
| 655 | |
| 656 | Use ``__has_feature(cxx_nullptr)`` or ``__has_extension(cxx_nullptr)`` to |
| 657 | determine if support for ``nullptr`` is enabled. |
| 658 | |
| 659 | C++11 ``override control`` |
| 660 | ^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 661 | |
| 662 | Use ``__has_feature(cxx_override_control)`` or |
| 663 | ``__has_extension(cxx_override_control)`` to determine if support for the |
| 664 | override control keywords is enabled. |
| 665 | |
| 666 | C++11 reference-qualified functions |
| 667 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 668 | |
| 669 | Use ``__has_feature(cxx_reference_qualified_functions)`` or |
| 670 | ``__has_extension(cxx_reference_qualified_functions)`` to determine if support |
| 671 | for reference-qualified functions (e.g., member functions with ``&`` or ``&&`` |
| 672 | applied to ``*this``) is enabled. |
| 673 | |
| 674 | C++11 range-based ``for`` loop |
| 675 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 676 | |
| 677 | Use ``__has_feature(cxx_range_for)`` or ``__has_extension(cxx_range_for)`` to |
| 678 | determine if support for the range-based for loop is enabled. |
| 679 | |
| 680 | C++11 raw string literals |
| 681 | ^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 682 | |
| 683 | Use ``__has_feature(cxx_raw_string_literals)`` to determine if support for raw |
| 684 | string literals (e.g., ``R"x(foo\bar)x"``) is enabled. |
| 685 | |
| 686 | C++11 rvalue references |
| 687 | ^^^^^^^^^^^^^^^^^^^^^^^ |
| 688 | |
| 689 | Use ``__has_feature(cxx_rvalue_references)`` or |
| 690 | ``__has_extension(cxx_rvalue_references)`` to determine if support for rvalue |
| 691 | references is enabled. |
| 692 | |
| 693 | C++11 ``static_assert()`` |
| 694 | ^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 695 | |
| 696 | Use ``__has_feature(cxx_static_assert)`` or |
| 697 | ``__has_extension(cxx_static_assert)`` to determine if support for compile-time |
| 698 | assertions using ``static_assert`` is enabled. |
| 699 | |
| 700 | C++11 type inference |
| 701 | ^^^^^^^^^^^^^^^^^^^^ |
| 702 | |
| 703 | Use ``__has_feature(cxx_auto_type)`` or ``__has_extension(cxx_auto_type)`` to |
| 704 | determine C++11 type inference is supported using the ``auto`` specifier. If |
| 705 | this is disabled, ``auto`` will instead be a storage class specifier, as in C |
| 706 | or C++98. |
| 707 | |
| 708 | C++11 strongly typed enumerations |
| 709 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 710 | |
| 711 | Use ``__has_feature(cxx_strong_enums)`` or |
| 712 | ``__has_extension(cxx_strong_enums)`` to determine if support for strongly |
| 713 | typed, scoped enumerations is enabled. |
| 714 | |
| 715 | C++11 trailing return type |
| 716 | ^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 717 | |
| 718 | Use ``__has_feature(cxx_trailing_return)`` or |
| 719 | ``__has_extension(cxx_trailing_return)`` to determine if support for the |
| 720 | alternate function declaration syntax with trailing return type is enabled. |
| 721 | |
| 722 | C++11 Unicode string literals |
| 723 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 724 | |
| 725 | Use ``__has_feature(cxx_unicode_literals)`` to determine if support for Unicode |
| 726 | string literals is enabled. |
| 727 | |
| 728 | C++11 unrestricted unions |
| 729 | ^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 730 | |
| 731 | Use ``__has_feature(cxx_unrestricted_unions)`` to determine if support for |
| 732 | unrestricted unions is enabled. |
| 733 | |
| 734 | C++11 user-defined literals |
| 735 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 736 | |
| 737 | Use ``__has_feature(cxx_user_literals)`` to determine if support for |
| 738 | user-defined literals is enabled. |
| 739 | |
| 740 | C++11 variadic templates |
| 741 | ^^^^^^^^^^^^^^^^^^^^^^^^ |
| 742 | |
| 743 | Use ``__has_feature(cxx_variadic_templates)`` or |
| 744 | ``__has_extension(cxx_variadic_templates)`` to determine if support for |
| 745 | variadic templates is enabled. |
| 746 | |
| 747 | C11 |
| 748 | --- |
| 749 | |
| 750 | The features listed below are part of the C11 standard. As a result, all these |
| 751 | features are enabled with the ``-std=c11`` or ``-std=gnu11`` option when |
| 752 | compiling C code. Additionally, because these features are all |
| 753 | backward-compatible, they are available as extensions in all language modes. |
| 754 | |
| 755 | C11 alignment specifiers |
| 756 | ^^^^^^^^^^^^^^^^^^^^^^^^ |
| 757 | |
| 758 | Use ``__has_feature(c_alignas)`` or ``__has_extension(c_alignas)`` to determine |
| 759 | if support for alignment specifiers using ``_Alignas`` is enabled. |
| 760 | |
| 761 | C11 atomic operations |
| 762 | ^^^^^^^^^^^^^^^^^^^^^ |
| 763 | |
| 764 | Use ``__has_feature(c_atomic)`` or ``__has_extension(c_atomic)`` to determine |
| 765 | if support for atomic types using ``_Atomic`` is enabled. Clang also provides |
| 766 | :ref:`a set of builtins <langext-__c11_atomic>` which can be used to implement |
| 767 | the ``<stdatomic.h>`` operations on ``_Atomic`` types. |
| 768 | |
| 769 | C11 generic selections |
| 770 | ^^^^^^^^^^^^^^^^^^^^^^ |
| 771 | |
| 772 | Use ``__has_feature(c_generic_selections)`` or |
| 773 | ``__has_extension(c_generic_selections)`` to determine if support for generic |
| 774 | selections is enabled. |
| 775 | |
| 776 | As an extension, the C11 generic selection expression is available in all |
| 777 | languages supported by Clang. The syntax is the same as that given in the C11 |
| 778 | standard. |
| 779 | |
| 780 | In C, type compatibility is decided according to the rules given in the |
| 781 | appropriate standard, but in C++, which lacks the type compatibility rules used |
| 782 | in C, types are considered compatible only if they are equivalent. |
| 783 | |
| 784 | C11 ``_Static_assert()`` |
| 785 | ^^^^^^^^^^^^^^^^^^^^^^^^ |
| 786 | |
| 787 | Use ``__has_feature(c_static_assert)`` or ``__has_extension(c_static_assert)`` |
| 788 | to determine if support for compile-time assertions using ``_Static_assert`` is |
| 789 | enabled. |
| 790 | |
| 791 | Checks for Type Traits |
| 792 | ====================== |
| 793 | |
| 794 | Clang supports the `GNU C++ type traits |
| 795 | <http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html>`_ and a subset of the |
| 796 | `Microsoft Visual C++ Type traits |
| 797 | <http://msdn.microsoft.com/en-us/library/ms177194(v=VS.100).aspx>`_. For each |
| 798 | supported type trait ``__X``, ``__has_extension(X)`` indicates the presence of |
| 799 | the type trait. For example: |
| 800 | |
| 801 | .. code-block:: c++ |
| 802 | |
| 803 | #if __has_extension(is_convertible_to) |
| 804 | template<typename From, typename To> |
| 805 | struct is_convertible_to { |
| 806 | static const bool value = __is_convertible_to(From, To); |
| 807 | }; |
| 808 | #else |
| 809 | // Emulate type trait |
| 810 | #endif |
| 811 | |
| 812 | The following type traits are supported by Clang: |
| 813 | |
| 814 | * ``__has_nothrow_assign`` (GNU, Microsoft) |
| 815 | * ``__has_nothrow_copy`` (GNU, Microsoft) |
| 816 | * ``__has_nothrow_constructor`` (GNU, Microsoft) |
| 817 | * ``__has_trivial_assign`` (GNU, Microsoft) |
| 818 | * ``__has_trivial_copy`` (GNU, Microsoft) |
| 819 | * ``__has_trivial_constructor`` (GNU, Microsoft) |
| 820 | * ``__has_trivial_destructor`` (GNU, Microsoft) |
| 821 | * ``__has_virtual_destructor`` (GNU, Microsoft) |
| 822 | * ``__is_abstract`` (GNU, Microsoft) |
| 823 | * ``__is_base_of`` (GNU, Microsoft) |
| 824 | * ``__is_class`` (GNU, Microsoft) |
| 825 | * ``__is_convertible_to`` (Microsoft) |
| 826 | * ``__is_empty`` (GNU, Microsoft) |
| 827 | * ``__is_enum`` (GNU, Microsoft) |
| 828 | * ``__is_interface_class`` (Microsoft) |
| 829 | * ``__is_pod`` (GNU, Microsoft) |
| 830 | * ``__is_polymorphic`` (GNU, Microsoft) |
| 831 | * ``__is_union`` (GNU, Microsoft) |
| 832 | * ``__is_literal(type)``: Determines whether the given type is a literal type |
| 833 | * ``__is_final``: Determines whether the given type is declared with a |
| 834 | ``final`` class-virt-specifier. |
| 835 | * ``__underlying_type(type)``: Retrieves the underlying type for a given |
| 836 | ``enum`` type. This trait is required to implement the C++11 standard |
| 837 | library. |
| 838 | * ``__is_trivially_assignable(totype, fromtype)``: Determines whether a value |
| 839 | of type ``totype`` can be assigned to from a value of type ``fromtype`` such |
| 840 | that no non-trivial functions are called as part of that assignment. This |
| 841 | trait is required to implement the C++11 standard library. |
| 842 | * ``__is_trivially_constructible(type, argtypes...)``: Determines whether a |
| 843 | value of type ``type`` can be direct-initialized with arguments of types |
| 844 | ``argtypes...`` such that no non-trivial functions are called as part of |
| 845 | that initialization. This trait is required to implement the C++11 standard |
| 846 | library. |
| 847 | |
| 848 | Blocks |
| 849 | ====== |
| 850 | |
| 851 | The syntax and high level language feature description is in |
Dmitri Gribenko | 7b00b84 | 2012-12-20 20:51:59 +0000 | [diff] [blame] | 852 | :doc:`BlockLanguageSpec`. Implementation and ABI details for the clang |
| 853 | implementation are in `Block-ABI-Apple.txt <Block-ABI-Apple.txt>`_. |
Sean Silva | 3872b46 | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 854 | |
| 855 | Query for this feature with ``__has_extension(blocks)``. |
| 856 | |
| 857 | Objective-C Features |
| 858 | ==================== |
| 859 | |
| 860 | Related result types |
| 861 | -------------------- |
| 862 | |
| 863 | According to Cocoa conventions, Objective-C methods with certain names |
| 864 | ("``init``", "``alloc``", etc.) always return objects that are an instance of |
| 865 | the receiving class's type. Such methods are said to have a "related result |
| 866 | type", meaning that a message send to one of these methods will have the same |
| 867 | static type as an instance of the receiver class. For example, given the |
| 868 | following classes: |
| 869 | |
| 870 | .. code-block:: objc |
| 871 | |
| 872 | @interface NSObject |
| 873 | + (id)alloc; |
| 874 | - (id)init; |
| 875 | @end |
| 876 | |
| 877 | @interface NSArray : NSObject |
| 878 | @end |
| 879 | |
| 880 | and this common initialization pattern |
| 881 | |
| 882 | .. code-block:: objc |
| 883 | |
| 884 | NSArray *array = [[NSArray alloc] init]; |
| 885 | |
| 886 | the type of the expression ``[NSArray alloc]`` is ``NSArray*`` because |
| 887 | ``alloc`` implicitly has a related result type. Similarly, the type of the |
| 888 | expression ``[[NSArray alloc] init]`` is ``NSArray*``, since ``init`` has a |
| 889 | related result type and its receiver is known to have the type ``NSArray *``. |
| 890 | If neither ``alloc`` nor ``init`` had a related result type, the expressions |
| 891 | would have had type ``id``, as declared in the method signature. |
| 892 | |
| 893 | A method with a related result type can be declared by using the type |
| 894 | ``instancetype`` as its result type. ``instancetype`` is a contextual keyword |
| 895 | that is only permitted in the result type of an Objective-C method, e.g. |
| 896 | |
| 897 | .. code-block:: objc |
| 898 | |
| 899 | @interface A |
| 900 | + (instancetype)constructAnA; |
| 901 | @end |
| 902 | |
| 903 | The related result type can also be inferred for some methods. To determine |
| 904 | whether a method has an inferred related result type, the first word in the |
| 905 | camel-case selector (e.g., "``init``" in "``initWithObjects``") is considered, |
| 906 | and the method will have a related result type if its return type is compatible |
| 907 | with the type of its class and if: |
| 908 | |
| 909 | * the first word is "``alloc``" or "``new``", and the method is a class method, |
| 910 | or |
| 911 | |
| 912 | * the first word is "``autorelease``", "``init``", "``retain``", or "``self``", |
| 913 | and the method is an instance method. |
| 914 | |
| 915 | If a method with a related result type is overridden by a subclass method, the |
| 916 | subclass method must also return a type that is compatible with the subclass |
| 917 | type. For example: |
| 918 | |
| 919 | .. code-block:: objc |
| 920 | |
| 921 | @interface NSString : NSObject |
| 922 | - (NSUnrelated *)init; // incorrect usage: NSUnrelated is not NSString or a superclass of NSString |
| 923 | @end |
| 924 | |
| 925 | Related result types only affect the type of a message send or property access |
| 926 | via the given method. In all other respects, a method with a related result |
| 927 | type is treated the same way as method that returns ``id``. |
| 928 | |
| 929 | Use ``__has_feature(objc_instancetype)`` to determine whether the |
| 930 | ``instancetype`` contextual keyword is available. |
| 931 | |
| 932 | Automatic reference counting |
| 933 | ---------------------------- |
| 934 | |
Sean Silva | 159cc9e | 2013-01-02 13:07:47 +0000 | [diff] [blame] | 935 | Clang provides support for :doc:`automated reference counting |
| 936 | <AutomaticReferenceCounting>` in Objective-C, which eliminates the need |
Sean Silva | 3872b46 | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 937 | for manual ``retain``/``release``/``autorelease`` message sends. There are two |
| 938 | feature macros associated with automatic reference counting: |
| 939 | ``__has_feature(objc_arc)`` indicates the availability of automated reference |
| 940 | counting in general, while ``__has_feature(objc_arc_weak)`` indicates that |
| 941 | automated reference counting also includes support for ``__weak`` pointers to |
| 942 | Objective-C objects. |
| 943 | |
Sean Silva | 159cc9e | 2013-01-02 13:07:47 +0000 | [diff] [blame] | 944 | .. _objc-fixed-enum: |
| 945 | |
Sean Silva | 3872b46 | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 946 | Enumerations with a fixed underlying type |
| 947 | ----------------------------------------- |
| 948 | |
| 949 | Clang provides support for C++11 enumerations with a fixed underlying type |
| 950 | within Objective-C. For example, one can write an enumeration type as: |
| 951 | |
| 952 | .. code-block:: c++ |
| 953 | |
| 954 | typedef enum : unsigned char { Red, Green, Blue } Color; |
| 955 | |
| 956 | This specifies that the underlying type, which is used to store the enumeration |
| 957 | value, is ``unsigned char``. |
| 958 | |
| 959 | Use ``__has_feature(objc_fixed_enum)`` to determine whether support for fixed |
| 960 | underlying types is available in Objective-C. |
| 961 | |
| 962 | Interoperability with C++11 lambdas |
| 963 | ----------------------------------- |
| 964 | |
| 965 | Clang provides interoperability between C++11 lambdas and blocks-based APIs, by |
| 966 | permitting a lambda to be implicitly converted to a block pointer with the |
| 967 | corresponding signature. For example, consider an API such as ``NSArray``'s |
| 968 | array-sorting method: |
| 969 | |
| 970 | .. code-block:: objc |
| 971 | |
| 972 | - (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr; |
| 973 | |
| 974 | ``NSComparator`` is simply a typedef for the block pointer ``NSComparisonResult |
| 975 | (^)(id, id)``, and parameters of this type are generally provided with block |
| 976 | literals as arguments. However, one can also use a C++11 lambda so long as it |
| 977 | provides the same signature (in this case, accepting two parameters of type |
| 978 | ``id`` and returning an ``NSComparisonResult``): |
| 979 | |
| 980 | .. code-block:: objc |
| 981 | |
| 982 | NSArray *array = @[@"string 1", @"string 21", @"string 12", @"String 11", |
| 983 | @"String 02"]; |
| 984 | const NSStringCompareOptions comparisonOptions |
| 985 | = NSCaseInsensitiveSearch | NSNumericSearch | |
| 986 | NSWidthInsensitiveSearch | NSForcedOrderingSearch; |
| 987 | NSLocale *currentLocale = [NSLocale currentLocale]; |
| 988 | NSArray *sorted |
| 989 | = [array sortedArrayUsingComparator:[=](id s1, id s2) -> NSComparisonResult { |
| 990 | NSRange string1Range = NSMakeRange(0, [s1 length]); |
| 991 | return [s1 compare:s2 options:comparisonOptions |
| 992 | range:string1Range locale:currentLocale]; |
| 993 | }]; |
| 994 | NSLog(@"sorted: %@", sorted); |
| 995 | |
| 996 | This code relies on an implicit conversion from the type of the lambda |
| 997 | expression (an unnamed, local class type called the *closure type*) to the |
| 998 | corresponding block pointer type. The conversion itself is expressed by a |
| 999 | conversion operator in that closure type that produces a block pointer with the |
| 1000 | same signature as the lambda itself, e.g., |
| 1001 | |
| 1002 | .. code-block:: objc |
| 1003 | |
| 1004 | operator NSComparisonResult (^)(id, id)() const; |
| 1005 | |
| 1006 | This conversion function returns a new block that simply forwards the two |
| 1007 | parameters to the lambda object (which it captures by copy), then returns the |
| 1008 | result. The returned block is first copied (with ``Block_copy``) and then |
| 1009 | autoreleased. As an optimization, if a lambda expression is immediately |
| 1010 | converted to a block pointer (as in the first example, above), then the block |
| 1011 | is not copied and autoreleased: rather, it is given the same lifetime as a |
| 1012 | block literal written at that point in the program, which avoids the overhead |
| 1013 | of copying a block to the heap in the common case. |
| 1014 | |
| 1015 | The conversion from a lambda to a block pointer is only available in |
| 1016 | Objective-C++, and not in C++ with blocks, due to its use of Objective-C memory |
| 1017 | management (autorelease). |
| 1018 | |
| 1019 | Object Literals and Subscripting |
| 1020 | -------------------------------- |
| 1021 | |
Sean Silva | 159cc9e | 2013-01-02 13:07:47 +0000 | [diff] [blame] | 1022 | Clang provides support for :doc:`Object Literals and Subscripting |
| 1023 | <ObjectiveCLiterals>` in Objective-C, which simplifies common Objective-C |
Sean Silva | 3872b46 | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 1024 | programming patterns, makes programs more concise, and improves the safety of |
| 1025 | container creation. There are several feature macros associated with object |
| 1026 | literals and subscripting: ``__has_feature(objc_array_literals)`` tests the |
| 1027 | availability of array literals; ``__has_feature(objc_dictionary_literals)`` |
| 1028 | tests the availability of dictionary literals; |
| 1029 | ``__has_feature(objc_subscripting)`` tests the availability of object |
| 1030 | subscripting. |
| 1031 | |
| 1032 | Objective-C Autosynthesis of Properties |
| 1033 | --------------------------------------- |
| 1034 | |
| 1035 | Clang provides support for autosynthesis of declared properties. Using this |
| 1036 | feature, clang provides default synthesis of those properties not declared |
| 1037 | @dynamic and not having user provided backing getter and setter methods. |
| 1038 | ``__has_feature(objc_default_synthesize_properties)`` checks for availability |
| 1039 | of this feature in version of clang being used. |
| 1040 | |
Jordan Rose | 3115f5b6 | 2012-12-15 00:37:01 +0000 | [diff] [blame] | 1041 | .. _langext-objc_method_family: |
| 1042 | |
| 1043 | The ``objc_method_family`` attribute |
| 1044 | ------------------------------------ |
| 1045 | |
| 1046 | Many methods in Objective-C have conventional meanings determined by their |
| 1047 | selectors. It is sometimes useful to be able to mark a method as having a |
| 1048 | particular conventional meaning despite not having the right selector, or as |
| 1049 | not having the conventional meaning that its selector would suggest. For these |
| 1050 | use cases, we provide an attribute to specifically describe the "method family" |
| 1051 | that a method belongs to. |
| 1052 | |
| 1053 | **Usage**: ``__attribute__((objc_method_family(X)))``, where ``X`` is one of |
| 1054 | ``none``, ``alloc``, ``copy``, ``init``, ``mutableCopy``, or ``new``. This |
| 1055 | attribute can only be placed at the end of a method declaration: |
| 1056 | |
| 1057 | .. code-block:: objc |
| 1058 | |
| 1059 | - (NSString *)initMyStringValue __attribute__((objc_method_family(none))); |
| 1060 | |
| 1061 | Users who do not wish to change the conventional meaning of a method, and who |
| 1062 | merely want to document its non-standard retain and release semantics, should |
| 1063 | use the :ref:`retaining behavior attributes <langext-objc-retain-release>` |
| 1064 | described below. |
| 1065 | |
| 1066 | Query for this feature with ``__has_attribute(objc_method_family)``. |
| 1067 | |
| 1068 | .. _langext-objc-retain-release: |
| 1069 | |
| 1070 | Objective-C retaining behavior attributes |
| 1071 | ----------------------------------------- |
| 1072 | |
| 1073 | In Objective-C, functions and methods are generally assumed to follow the |
| 1074 | `Cocoa Memory Management |
| 1075 | <http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html>`_ |
| 1076 | conventions for ownership of object arguments and |
| 1077 | return values. However, there are exceptions, and so Clang provides attributes |
| 1078 | to allow these exceptions to be documented. This are used by ARC and the |
| 1079 | `static analyzer <http://clang-analyzer.llvm.org>`_ Some exceptions may be |
| 1080 | better described using the :ref:`objc_method_family |
| 1081 | <langext-objc_method_family>` attribute instead. |
| 1082 | |
| 1083 | **Usage**: The ``ns_returns_retained``, ``ns_returns_not_retained``, |
| 1084 | ``ns_returns_autoreleased``, ``cf_returns_retained``, and |
| 1085 | ``cf_returns_not_retained`` attributes can be placed on methods and functions |
| 1086 | that return Objective-C or CoreFoundation objects. They are commonly placed at |
| 1087 | the end of a function prototype or method declaration: |
| 1088 | |
| 1089 | .. code-block:: objc |
| 1090 | |
| 1091 | id foo() __attribute__((ns_returns_retained)); |
| 1092 | |
| 1093 | - (NSString *)bar:(int)x __attribute__((ns_returns_retained)); |
| 1094 | |
| 1095 | The ``*_returns_retained`` attributes specify that the returned object has a +1 |
| 1096 | retain count. The ``*_returns_not_retained`` attributes specify that the return |
| 1097 | object has a +0 retain count, even if the normal convention for its selector |
| 1098 | would be +1. ``ns_returns_autoreleased`` specifies that the returned object is |
| 1099 | +0, but is guaranteed to live at least as long as the next flush of an |
| 1100 | autorelease pool. |
| 1101 | |
| 1102 | **Usage**: The ``ns_consumed`` and ``cf_consumed`` attributes can be placed on |
| 1103 | an parameter declaration; they specify that the argument is expected to have a |
| 1104 | +1 retain count, which will be balanced in some way by the function or method. |
| 1105 | The ``ns_consumes_self`` attribute can only be placed on an Objective-C |
| 1106 | method; it specifies that the method expects its ``self`` parameter to have a |
| 1107 | +1 retain count, which it will balance in some way. |
| 1108 | |
| 1109 | .. code-block:: objc |
| 1110 | |
| 1111 | void foo(__attribute__((ns_consumed)) NSString *string); |
| 1112 | |
| 1113 | - (void) bar __attribute__((ns_consumes_self)); |
| 1114 | - (void) baz:(id) __attribute__((ns_consumed)) x; |
| 1115 | |
| 1116 | Further examples of these attributes are available in the static analyzer's `list of annotations for analysis |
| 1117 | <http://clang-analyzer.llvm.org/annotations.html#cocoa_mem>`_. |
| 1118 | |
| 1119 | Query for these features with ``__has_attribute(ns_consumed)``, |
| 1120 | ``__has_attribute(ns_returns_retained)``, etc. |
| 1121 | |
| 1122 | |
Sean Silva | 3872b46 | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 1123 | Function Overloading in C |
| 1124 | ========================= |
| 1125 | |
| 1126 | Clang provides support for C++ function overloading in C. Function overloading |
| 1127 | in C is introduced using the ``overloadable`` attribute. For example, one |
| 1128 | might provide several overloaded versions of a ``tgsin`` function that invokes |
| 1129 | the appropriate standard function computing the sine of a value with ``float``, |
| 1130 | ``double``, or ``long double`` precision: |
| 1131 | |
| 1132 | .. code-block:: c |
| 1133 | |
| 1134 | #include <math.h> |
| 1135 | float __attribute__((overloadable)) tgsin(float x) { return sinf(x); } |
| 1136 | double __attribute__((overloadable)) tgsin(double x) { return sin(x); } |
| 1137 | long double __attribute__((overloadable)) tgsin(long double x) { return sinl(x); } |
| 1138 | |
| 1139 | Given these declarations, one can call ``tgsin`` with a ``float`` value to |
| 1140 | receive a ``float`` result, with a ``double`` to receive a ``double`` result, |
| 1141 | etc. Function overloading in C follows the rules of C++ function overloading |
| 1142 | to pick the best overload given the call arguments, with a few C-specific |
| 1143 | semantics: |
| 1144 | |
| 1145 | * Conversion from ``float`` or ``double`` to ``long double`` is ranked as a |
| 1146 | floating-point promotion (per C99) rather than as a floating-point conversion |
| 1147 | (as in C++). |
| 1148 | |
| 1149 | * A conversion from a pointer of type ``T*`` to a pointer of type ``U*`` is |
| 1150 | considered a pointer conversion (with conversion rank) if ``T`` and ``U`` are |
| 1151 | compatible types. |
| 1152 | |
| 1153 | * A conversion from type ``T`` to a value of type ``U`` is permitted if ``T`` |
| 1154 | and ``U`` are compatible types. This conversion is given "conversion" rank. |
| 1155 | |
| 1156 | The declaration of ``overloadable`` functions is restricted to function |
| 1157 | declarations and definitions. Most importantly, if any function with a given |
| 1158 | name is given the ``overloadable`` attribute, then all function declarations |
| 1159 | and definitions with that name (and in that scope) must have the |
| 1160 | ``overloadable`` attribute. This rule even applies to redeclarations of |
| 1161 | functions whose original declaration had the ``overloadable`` attribute, e.g., |
| 1162 | |
| 1163 | .. code-block:: c |
| 1164 | |
| 1165 | int f(int) __attribute__((overloadable)); |
| 1166 | float f(float); // error: declaration of "f" must have the "overloadable" attribute |
| 1167 | |
| 1168 | int g(int) __attribute__((overloadable)); |
| 1169 | int g(int) { } // error: redeclaration of "g" must also have the "overloadable" attribute |
| 1170 | |
| 1171 | Functions marked ``overloadable`` must have prototypes. Therefore, the |
| 1172 | following code is ill-formed: |
| 1173 | |
| 1174 | .. code-block:: c |
| 1175 | |
| 1176 | int h() __attribute__((overloadable)); // error: h does not have a prototype |
| 1177 | |
| 1178 | However, ``overloadable`` functions are allowed to use a ellipsis even if there |
| 1179 | are no named parameters (as is permitted in C++). This feature is particularly |
| 1180 | useful when combined with the ``unavailable`` attribute: |
| 1181 | |
| 1182 | .. code-block:: c++ |
| 1183 | |
| 1184 | void honeypot(...) __attribute__((overloadable, unavailable)); // calling me is an error |
| 1185 | |
| 1186 | Functions declared with the ``overloadable`` attribute have their names mangled |
| 1187 | according to the same rules as C++ function names. For example, the three |
| 1188 | ``tgsin`` functions in our motivating example get the mangled names |
| 1189 | ``_Z5tgsinf``, ``_Z5tgsind``, and ``_Z5tgsine``, respectively. There are two |
| 1190 | caveats to this use of name mangling: |
| 1191 | |
| 1192 | * Future versions of Clang may change the name mangling of functions overloaded |
| 1193 | in C, so you should not depend on an specific mangling. To be completely |
| 1194 | safe, we strongly urge the use of ``static inline`` with ``overloadable`` |
| 1195 | functions. |
| 1196 | |
| 1197 | * The ``overloadable`` attribute has almost no meaning when used in C++, |
| 1198 | because names will already be mangled and functions are already overloadable. |
| 1199 | However, when an ``overloadable`` function occurs within an ``extern "C"`` |
| 1200 | linkage specification, it's name *will* be mangled in the same way as it |
| 1201 | would in C. |
| 1202 | |
| 1203 | Query for this feature with ``__has_extension(attribute_overloadable)``. |
| 1204 | |
| 1205 | Initializer lists for complex numbers in C |
| 1206 | ========================================== |
| 1207 | |
| 1208 | clang supports an extension which allows the following in C: |
| 1209 | |
| 1210 | .. code-block:: c++ |
| 1211 | |
| 1212 | #include <math.h> |
| 1213 | #include <complex.h> |
| 1214 | complex float x = { 1.0f, INFINITY }; // Init to (1, Inf) |
| 1215 | |
| 1216 | This construct is useful because there is no way to separately initialize the |
| 1217 | real and imaginary parts of a complex variable in standard C, given that clang |
| 1218 | does not support ``_Imaginary``. (Clang also supports the ``__real__`` and |
| 1219 | ``__imag__`` extensions from gcc, which help in some cases, but are not usable |
| 1220 | in static initializers.) |
| 1221 | |
| 1222 | Note that this extension does not allow eliding the braces; the meaning of the |
| 1223 | following two lines is different: |
| 1224 | |
| 1225 | .. code-block:: c++ |
| 1226 | |
| 1227 | complex float x[] = { { 1.0f, 1.0f } }; // [0] = (1, 1) |
| 1228 | complex float x[] = { 1.0f, 1.0f }; // [0] = (1, 0), [1] = (1, 0) |
| 1229 | |
| 1230 | This extension also works in C++ mode, as far as that goes, but does not apply |
| 1231 | to the C++ ``std::complex``. (In C++11, list initialization allows the same |
| 1232 | syntax to be used with ``std::complex`` with the same meaning.) |
| 1233 | |
| 1234 | Builtin Functions |
| 1235 | ================= |
| 1236 | |
| 1237 | Clang supports a number of builtin library functions with the same syntax as |
| 1238 | GCC, including things like ``__builtin_nan``, ``__builtin_constant_p``, |
| 1239 | ``__builtin_choose_expr``, ``__builtin_types_compatible_p``, |
| 1240 | ``__sync_fetch_and_add``, etc. In addition to the GCC builtins, Clang supports |
| 1241 | a number of builtins that GCC does not, which are listed here. |
| 1242 | |
| 1243 | Please note that Clang does not and will not support all of the GCC builtins |
| 1244 | for vector operations. Instead of using builtins, you should use the functions |
| 1245 | defined in target-specific header files like ``<xmmintrin.h>``, which define |
| 1246 | portable wrappers for these. Many of the Clang versions of these functions are |
| 1247 | implemented directly in terms of :ref:`extended vector support |
| 1248 | <langext-vectors>` instead of builtins, in order to reduce the number of |
| 1249 | builtins that we need to implement. |
| 1250 | |
| 1251 | ``__builtin_readcyclecounter`` |
| 1252 | ------------------------------ |
| 1253 | |
| 1254 | ``__builtin_readcyclecounter`` is used to access the cycle counter register (or |
| 1255 | a similar low-latency, high-accuracy clock) on those targets that support it. |
| 1256 | |
| 1257 | **Syntax**: |
| 1258 | |
| 1259 | .. code-block:: c++ |
| 1260 | |
| 1261 | __builtin_readcyclecounter() |
| 1262 | |
| 1263 | **Example of Use**: |
| 1264 | |
| 1265 | .. code-block:: c++ |
| 1266 | |
| 1267 | unsigned long long t0 = __builtin_readcyclecounter(); |
| 1268 | do_something(); |
| 1269 | unsigned long long t1 = __builtin_readcyclecounter(); |
| 1270 | unsigned long long cycles_to_do_something = t1 - t0; // assuming no overflow |
| 1271 | |
| 1272 | **Description**: |
| 1273 | |
| 1274 | The ``__builtin_readcyclecounter()`` builtin returns the cycle counter value, |
| 1275 | which may be either global or process/thread-specific depending on the target. |
| 1276 | As the backing counters often overflow quickly (on the order of seconds) this |
| 1277 | should only be used for timing small intervals. When not supported by the |
| 1278 | target, the return value is always zero. This builtin takes no arguments and |
| 1279 | produces an unsigned long long result. |
| 1280 | |
| 1281 | Query for this feature with ``__has_builtin(__builtin_readcyclecounter)``. |
| 1282 | |
| 1283 | .. _langext-__builtin_shufflevector: |
| 1284 | |
| 1285 | ``__builtin_shufflevector`` |
| 1286 | --------------------------- |
| 1287 | |
| 1288 | ``__builtin_shufflevector`` is used to express generic vector |
| 1289 | permutation/shuffle/swizzle operations. This builtin is also very important |
| 1290 | for the implementation of various target-specific header files like |
| 1291 | ``<xmmintrin.h>``. |
| 1292 | |
| 1293 | **Syntax**: |
| 1294 | |
| 1295 | .. code-block:: c++ |
| 1296 | |
| 1297 | __builtin_shufflevector(vec1, vec2, index1, index2, ...) |
| 1298 | |
| 1299 | **Examples**: |
| 1300 | |
| 1301 | .. code-block:: c++ |
| 1302 | |
| 1303 | // Identity operation - return 4-element vector V1. |
| 1304 | __builtin_shufflevector(V1, V1, 0, 1, 2, 3) |
| 1305 | |
| 1306 | // "Splat" element 0 of V1 into a 4-element result. |
| 1307 | __builtin_shufflevector(V1, V1, 0, 0, 0, 0) |
| 1308 | |
| 1309 | // Reverse 4-element vector V1. |
| 1310 | __builtin_shufflevector(V1, V1, 3, 2, 1, 0) |
| 1311 | |
| 1312 | // Concatenate every other element of 4-element vectors V1 and V2. |
| 1313 | __builtin_shufflevector(V1, V2, 0, 2, 4, 6) |
| 1314 | |
| 1315 | // Concatenate every other element of 8-element vectors V1 and V2. |
| 1316 | __builtin_shufflevector(V1, V2, 0, 2, 4, 6, 8, 10, 12, 14) |
| 1317 | |
| 1318 | **Description**: |
| 1319 | |
| 1320 | The first two arguments to ``__builtin_shufflevector`` are vectors that have |
| 1321 | the same element type. The remaining arguments are a list of integers that |
| 1322 | specify the elements indices of the first two vectors that should be extracted |
| 1323 | and returned in a new vector. These element indices are numbered sequentially |
| 1324 | starting with the first vector, continuing into the second vector. Thus, if |
| 1325 | ``vec1`` is a 4-element vector, index 5 would refer to the second element of |
| 1326 | ``vec2``. |
| 1327 | |
| 1328 | The result of ``__builtin_shufflevector`` is a vector with the same element |
| 1329 | type as ``vec1``/``vec2`` but that has an element count equal to the number of |
| 1330 | indices specified. |
| 1331 | |
| 1332 | Query for this feature with ``__has_builtin(__builtin_shufflevector)``. |
| 1333 | |
| 1334 | ``__builtin_unreachable`` |
| 1335 | ------------------------- |
| 1336 | |
| 1337 | ``__builtin_unreachable`` is used to indicate that a specific point in the |
| 1338 | program cannot be reached, even if the compiler might otherwise think it can. |
| 1339 | This is useful to improve optimization and eliminates certain warnings. For |
| 1340 | example, without the ``__builtin_unreachable`` in the example below, the |
| 1341 | compiler assumes that the inline asm can fall through and prints a "function |
| 1342 | declared '``noreturn``' should not return" warning. |
| 1343 | |
| 1344 | **Syntax**: |
| 1345 | |
| 1346 | .. code-block:: c++ |
| 1347 | |
| 1348 | __builtin_unreachable() |
| 1349 | |
| 1350 | **Example of use**: |
| 1351 | |
| 1352 | .. code-block:: c++ |
| 1353 | |
| 1354 | void myabort(void) __attribute__((noreturn)); |
| 1355 | void myabort(void) { |
| 1356 | asm("int3"); |
| 1357 | __builtin_unreachable(); |
| 1358 | } |
| 1359 | |
| 1360 | **Description**: |
| 1361 | |
| 1362 | The ``__builtin_unreachable()`` builtin has completely undefined behavior. |
| 1363 | Since it has undefined behavior, it is a statement that it is never reached and |
| 1364 | the optimizer can take advantage of this to produce better code. This builtin |
| 1365 | takes no arguments and produces a void result. |
| 1366 | |
| 1367 | Query for this feature with ``__has_builtin(__builtin_unreachable)``. |
| 1368 | |
| 1369 | ``__sync_swap`` |
| 1370 | --------------- |
| 1371 | |
| 1372 | ``__sync_swap`` is used to atomically swap integers or pointers in memory. |
| 1373 | |
| 1374 | **Syntax**: |
| 1375 | |
| 1376 | .. code-block:: c++ |
| 1377 | |
| 1378 | type __sync_swap(type *ptr, type value, ...) |
| 1379 | |
| 1380 | **Example of Use**: |
| 1381 | |
| 1382 | .. code-block:: c++ |
| 1383 | |
| 1384 | int old_value = __sync_swap(&value, new_value); |
| 1385 | |
| 1386 | **Description**: |
| 1387 | |
| 1388 | The ``__sync_swap()`` builtin extends the existing ``__sync_*()`` family of |
| 1389 | atomic intrinsics to allow code to atomically swap the current value with the |
| 1390 | new value. More importantly, it helps developers write more efficient and |
| 1391 | correct code by avoiding expensive loops around |
| 1392 | ``__sync_bool_compare_and_swap()`` or relying on the platform specific |
| 1393 | implementation details of ``__sync_lock_test_and_set()``. The |
| 1394 | ``__sync_swap()`` builtin is a full barrier. |
| 1395 | |
| 1396 | .. _langext-__c11_atomic: |
| 1397 | |
| 1398 | __c11_atomic builtins |
| 1399 | --------------------- |
| 1400 | |
| 1401 | Clang provides a set of builtins which are intended to be used to implement |
| 1402 | C11's ``<stdatomic.h>`` header. These builtins provide the semantics of the |
| 1403 | ``_explicit`` form of the corresponding C11 operation, and are named with a |
| 1404 | ``__c11_`` prefix. The supported operations are: |
| 1405 | |
| 1406 | * ``__c11_atomic_init`` |
| 1407 | * ``__c11_atomic_thread_fence`` |
| 1408 | * ``__c11_atomic_signal_fence`` |
| 1409 | * ``__c11_atomic_is_lock_free`` |
| 1410 | * ``__c11_atomic_store`` |
| 1411 | * ``__c11_atomic_load`` |
| 1412 | * ``__c11_atomic_exchange`` |
| 1413 | * ``__c11_atomic_compare_exchange_strong`` |
| 1414 | * ``__c11_atomic_compare_exchange_weak`` |
| 1415 | * ``__c11_atomic_fetch_add`` |
| 1416 | * ``__c11_atomic_fetch_sub`` |
| 1417 | * ``__c11_atomic_fetch_and`` |
| 1418 | * ``__c11_atomic_fetch_or`` |
| 1419 | * ``__c11_atomic_fetch_xor`` |
| 1420 | |
| 1421 | Non-standard C++11 Attributes |
| 1422 | ============================= |
| 1423 | |
| 1424 | Clang supports one non-standard C++11 attribute. It resides in the ``clang`` |
| 1425 | attribute namespace. |
| 1426 | |
| 1427 | The ``clang::fallthrough`` attribute |
| 1428 | ------------------------------------ |
| 1429 | |
| 1430 | The ``clang::fallthrough`` attribute is used along with the |
| 1431 | ``-Wimplicit-fallthrough`` argument to annotate intentional fall-through |
| 1432 | between switch labels. It can only be applied to a null statement placed at a |
| 1433 | point of execution between any statement and the next switch label. It is |
| 1434 | common to mark these places with a specific comment, but this attribute is |
| 1435 | meant to replace comments with a more strict annotation, which can be checked |
| 1436 | by the compiler. This attribute doesn't change semantics of the code and can |
| 1437 | be used wherever an intended fall-through occurs. It is designed to mimic |
| 1438 | control-flow statements like ``break;``, so it can be placed in most places |
| 1439 | where ``break;`` can, but only if there are no statements on the execution path |
| 1440 | between it and the next switch label. |
| 1441 | |
| 1442 | Here is an example: |
| 1443 | |
| 1444 | .. code-block:: c++ |
| 1445 | |
| 1446 | // compile with -Wimplicit-fallthrough |
| 1447 | switch (n) { |
| 1448 | case 22: |
| 1449 | case 33: // no warning: no statements between case labels |
| 1450 | f(); |
| 1451 | case 44: // warning: unannotated fall-through |
| 1452 | g(); |
| 1453 | [[clang::fallthrough]]; |
| 1454 | case 55: // no warning |
| 1455 | if (x) { |
| 1456 | h(); |
| 1457 | break; |
| 1458 | } |
| 1459 | else { |
| 1460 | i(); |
| 1461 | [[clang::fallthrough]]; |
| 1462 | } |
| 1463 | case 66: // no warning |
| 1464 | p(); |
| 1465 | [[clang::fallthrough]]; // warning: fallthrough annotation does not |
| 1466 | // directly precede case label |
| 1467 | q(); |
| 1468 | case 77: // warning: unannotated fall-through |
| 1469 | r(); |
| 1470 | } |
| 1471 | |
| 1472 | Target-Specific Extensions |
| 1473 | ========================== |
| 1474 | |
| 1475 | Clang supports some language features conditionally on some targets. |
| 1476 | |
| 1477 | X86/X86-64 Language Extensions |
| 1478 | ------------------------------ |
| 1479 | |
| 1480 | The X86 backend has these language extensions: |
| 1481 | |
| 1482 | Memory references off the GS segment |
| 1483 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1484 | |
| 1485 | Annotating a pointer with address space #256 causes it to be code generated |
| 1486 | relative to the X86 GS segment register, and address space #257 causes it to be |
| 1487 | relative to the X86 FS segment. Note that this is a very very low-level |
| 1488 | feature that should only be used if you know what you're doing (for example in |
| 1489 | an OS kernel). |
| 1490 | |
| 1491 | Here is an example: |
| 1492 | |
| 1493 | .. code-block:: c++ |
| 1494 | |
| 1495 | #define GS_RELATIVE __attribute__((address_space(256))) |
| 1496 | int foo(int GS_RELATIVE *P) { |
| 1497 | return *P; |
| 1498 | } |
| 1499 | |
| 1500 | Which compiles to (on X86-32): |
| 1501 | |
| 1502 | .. code-block:: gas |
| 1503 | |
| 1504 | _foo: |
| 1505 | movl 4(%esp), %eax |
| 1506 | movl %gs:(%eax), %eax |
| 1507 | ret |
| 1508 | |
Jordan Rose | 3115f5b6 | 2012-12-15 00:37:01 +0000 | [diff] [blame] | 1509 | Extensions for Static Analysis |
Dmitri Gribenko | 1228d66 | 2012-12-15 14:25:25 +0000 | [diff] [blame] | 1510 | ============================== |
Sean Silva | 3872b46 | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 1511 | |
| 1512 | Clang supports additional attributes that are useful for documenting program |
Jordan Rose | 3115f5b6 | 2012-12-15 00:37:01 +0000 | [diff] [blame] | 1513 | invariants and rules for static analysis tools, such as the `Clang Static |
| 1514 | Analyzer <http://clang-analyzer.llvm.org/>`_. These attributes are documented |
| 1515 | in the analyzer's `list of source-level annotations |
| 1516 | <http://clang-analyzer.llvm.org/annotations.html>`_. |
Sean Silva | 3872b46 | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 1517 | |
Sean Silva | 3872b46 | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 1518 | |
Jordan Rose | 3115f5b6 | 2012-12-15 00:37:01 +0000 | [diff] [blame] | 1519 | Extensions for Dynamic Analysis |
Dmitri Gribenko | 1228d66 | 2012-12-15 14:25:25 +0000 | [diff] [blame] | 1520 | =============================== |
Sean Silva | 3872b46 | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 1521 | |
| 1522 | .. _langext-address_sanitizer: |
| 1523 | |
| 1524 | AddressSanitizer |
| 1525 | ---------------- |
| 1526 | |
| 1527 | Use ``__has_feature(address_sanitizer)`` to check if the code is being built |
Dmitri Gribenko | 1228d66 | 2012-12-15 14:25:25 +0000 | [diff] [blame] | 1528 | with :doc:`AddressSanitizer`. |
Sean Silva | 3872b46 | 2012-12-12 23:44:55 +0000 | [diff] [blame] | 1529 | |
| 1530 | Use ``__attribute__((no_address_safety_analysis))`` on a function declaration |
| 1531 | to specify that address safety instrumentation (e.g. AddressSanitizer) should |
| 1532 | not be applied to that function. |
| 1533 | |
| 1534 | Thread-Safety Annotation Checking |
| 1535 | ================================= |
| 1536 | |
| 1537 | Clang supports additional attributes for checking basic locking policies in |
| 1538 | multithreaded programs. Clang currently parses the following list of |
| 1539 | attributes, although **the implementation for these annotations is currently in |
| 1540 | development.** For more details, see the `GCC implementation |
| 1541 | <http://gcc.gnu.org/wiki/ThreadSafetyAnnotation>`_. |
| 1542 | |
| 1543 | ``no_thread_safety_analysis`` |
| 1544 | ----------------------------- |
| 1545 | |
| 1546 | Use ``__attribute__((no_thread_safety_analysis))`` on a function declaration to |
| 1547 | specify that the thread safety analysis should not be run on that function. |
| 1548 | This attribute provides an escape hatch (e.g. for situations when it is |
| 1549 | difficult to annotate the locking policy). |
| 1550 | |
| 1551 | ``lockable`` |
| 1552 | ------------ |
| 1553 | |
| 1554 | Use ``__attribute__((lockable))`` on a class definition to specify that it has |
| 1555 | a lockable type (e.g. a Mutex class). This annotation is primarily used to |
| 1556 | check consistency. |
| 1557 | |
| 1558 | ``scoped_lockable`` |
| 1559 | ------------------- |
| 1560 | |
| 1561 | Use ``__attribute__((scoped_lockable))`` on a class definition to specify that |
| 1562 | it has a "scoped" lockable type. Objects of this type will acquire the lock |
| 1563 | upon construction and release it upon going out of scope. This annotation is |
| 1564 | primarily used to check consistency. |
| 1565 | |
| 1566 | ``guarded_var`` |
| 1567 | --------------- |
| 1568 | |
| 1569 | Use ``__attribute__((guarded_var))`` on a variable declaration to specify that |
| 1570 | the variable must be accessed while holding some lock. |
| 1571 | |
| 1572 | ``pt_guarded_var`` |
| 1573 | ------------------ |
| 1574 | |
| 1575 | Use ``__attribute__((pt_guarded_var))`` on a pointer declaration to specify |
| 1576 | that the pointer must be dereferenced while holding some lock. |
| 1577 | |
| 1578 | ``guarded_by(l)`` |
| 1579 | ----------------- |
| 1580 | |
| 1581 | Use ``__attribute__((guarded_by(l)))`` on a variable declaration to specify |
| 1582 | that the variable must be accessed while holding lock ``l``. |
| 1583 | |
| 1584 | ``pt_guarded_by(l)`` |
| 1585 | -------------------- |
| 1586 | |
| 1587 | Use ``__attribute__((pt_guarded_by(l)))`` on a pointer declaration to specify |
| 1588 | that the pointer must be dereferenced while holding lock ``l``. |
| 1589 | |
| 1590 | ``acquired_before(...)`` |
| 1591 | ------------------------ |
| 1592 | |
| 1593 | Use ``__attribute__((acquired_before(...)))`` on a declaration of a lockable |
| 1594 | variable to specify that the lock must be acquired before all attribute |
| 1595 | arguments. Arguments must be lockable type, and there must be at least one |
| 1596 | argument. |
| 1597 | |
| 1598 | ``acquired_after(...)`` |
| 1599 | ----------------------- |
| 1600 | |
| 1601 | Use ``__attribute__((acquired_after(...)))`` on a declaration of a lockable |
| 1602 | variable to specify that the lock must be acquired after all attribute |
| 1603 | arguments. Arguments must be lockable type, and there must be at least one |
| 1604 | argument. |
| 1605 | |
| 1606 | ``exclusive_lock_function(...)`` |
| 1607 | -------------------------------- |
| 1608 | |
| 1609 | Use ``__attribute__((exclusive_lock_function(...)))`` on a function declaration |
| 1610 | to specify that the function acquires all listed locks exclusively. This |
| 1611 | attribute takes zero or more arguments: either of lockable type or integers |
| 1612 | indexing into function parameters of lockable type. If no arguments are given, |
| 1613 | the acquired lock is implicitly ``this`` of the enclosing object. |
| 1614 | |
| 1615 | ``shared_lock_function(...)`` |
| 1616 | ----------------------------- |
| 1617 | |
| 1618 | Use ``__attribute__((shared_lock_function(...)))`` on a function declaration to |
| 1619 | specify that the function acquires all listed locks, although the locks may be |
| 1620 | shared (e.g. read locks). This attribute takes zero or more arguments: either |
| 1621 | of lockable type or integers indexing into function parameters of lockable |
| 1622 | type. If no arguments are given, the acquired lock is implicitly ``this`` of |
| 1623 | the enclosing object. |
| 1624 | |
| 1625 | ``exclusive_trylock_function(...)`` |
| 1626 | ----------------------------------- |
| 1627 | |
| 1628 | Use ``__attribute__((exclusive_lock_function(...)))`` on a function declaration |
| 1629 | to specify that the function will try (without blocking) to acquire all listed |
| 1630 | locks exclusively. This attribute takes one or more arguments. The first |
| 1631 | argument is an integer or boolean value specifying the return value of a |
| 1632 | successful lock acquisition. The remaining arugments are either of lockable |
| 1633 | type or integers indexing into function parameters of lockable type. If only |
| 1634 | one argument is given, the acquired lock is implicitly ``this`` of the |
| 1635 | enclosing object. |
| 1636 | |
| 1637 | ``shared_trylock_function(...)`` |
| 1638 | -------------------------------- |
| 1639 | |
| 1640 | Use ``__attribute__((shared_lock_function(...)))`` on a function declaration to |
| 1641 | specify that the function will try (without blocking) to acquire all listed |
| 1642 | locks, although the locks may be shared (e.g. read locks). This attribute |
| 1643 | takes one or more arguments. The first argument is an integer or boolean value |
| 1644 | specifying the return value of a successful lock acquisition. The remaining |
| 1645 | arugments are either of lockable type or integers indexing into function |
| 1646 | parameters of lockable type. If only one argument is given, the acquired lock |
| 1647 | is implicitly ``this`` of the enclosing object. |
| 1648 | |
| 1649 | ``unlock_function(...)`` |
| 1650 | ------------------------ |
| 1651 | |
| 1652 | Use ``__attribute__((unlock_function(...)))`` on a function declaration to |
| 1653 | specify that the function release all listed locks. This attribute takes zero |
| 1654 | or more arguments: either of lockable type or integers indexing into function |
| 1655 | parameters of lockable type. If no arguments are given, the acquired lock is |
| 1656 | implicitly ``this`` of the enclosing object. |
| 1657 | |
| 1658 | ``lock_returned(l)`` |
| 1659 | -------------------- |
| 1660 | |
| 1661 | Use ``__attribute__((lock_returned(l)))`` on a function declaration to specify |
| 1662 | that the function returns lock ``l`` (``l`` must be of lockable type). This |
| 1663 | annotation is used to aid in resolving lock expressions. |
| 1664 | |
| 1665 | ``locks_excluded(...)`` |
| 1666 | ----------------------- |
| 1667 | |
| 1668 | Use ``__attribute__((locks_excluded(...)))`` on a function declaration to |
| 1669 | specify that the function must not be called with the listed locks. Arguments |
| 1670 | must be lockable type, and there must be at least one argument. |
| 1671 | |
| 1672 | ``exclusive_locks_required(...)`` |
| 1673 | --------------------------------- |
| 1674 | |
| 1675 | Use ``__attribute__((exclusive_locks_required(...)))`` on a function |
| 1676 | declaration to specify that the function must be called while holding the |
| 1677 | listed exclusive locks. Arguments must be lockable type, and there must be at |
| 1678 | least one argument. |
| 1679 | |
| 1680 | ``shared_locks_required(...)`` |
| 1681 | ------------------------------ |
| 1682 | |
| 1683 | Use ``__attribute__((shared_locks_required(...)))`` on a function declaration |
| 1684 | to specify that the function must be called while holding the listed shared |
| 1685 | locks. Arguments must be lockable type, and there must be at least one |
| 1686 | argument. |
| 1687 | |
| 1688 | Type Safety Checking |
| 1689 | ==================== |
| 1690 | |
| 1691 | Clang supports additional attributes to enable checking type safety properties |
| 1692 | that can't be enforced by C type system. Usecases include: |
| 1693 | |
| 1694 | * MPI library implementations, where these attributes enable checking that |
| 1695 | buffer type matches the passed ``MPI_Datatype``; |
| 1696 | * for HDF5 library there is a similar usecase as MPI; |
| 1697 | * checking types of variadic functions' arguments for functions like |
| 1698 | ``fcntl()`` and ``ioctl()``. |
| 1699 | |
| 1700 | You can detect support for these attributes with ``__has_attribute()``. For |
| 1701 | example: |
| 1702 | |
| 1703 | .. code-block:: c++ |
| 1704 | |
| 1705 | #if defined(__has_attribute) |
| 1706 | # if __has_attribute(argument_with_type_tag) && \ |
| 1707 | __has_attribute(pointer_with_type_tag) && \ |
| 1708 | __has_attribute(type_tag_for_datatype) |
| 1709 | # define ATTR_MPI_PWT(buffer_idx, type_idx) __attribute__((pointer_with_type_tag(mpi,buffer_idx,type_idx))) |
| 1710 | /* ... other macros ... */ |
| 1711 | # endif |
| 1712 | #endif |
| 1713 | |
| 1714 | #if !defined(ATTR_MPI_PWT) |
| 1715 | # define ATTR_MPI_PWT(buffer_idx, type_idx) |
| 1716 | #endif |
| 1717 | |
| 1718 | int MPI_Send(void *buf, int count, MPI_Datatype datatype /*, other args omitted */) |
| 1719 | ATTR_MPI_PWT(1,3); |
| 1720 | |
| 1721 | ``argument_with_type_tag(...)`` |
| 1722 | ------------------------------- |
| 1723 | |
| 1724 | Use ``__attribute__((argument_with_type_tag(arg_kind, arg_idx, |
| 1725 | type_tag_idx)))`` on a function declaration to specify that the function |
| 1726 | accepts a type tag that determines the type of some other argument. |
| 1727 | ``arg_kind`` is an identifier that should be used when annotating all |
| 1728 | applicable type tags. |
| 1729 | |
| 1730 | This attribute is primarily useful for checking arguments of variadic functions |
| 1731 | (``pointer_with_type_tag`` can be used in most of non-variadic cases). |
| 1732 | |
| 1733 | For example: |
| 1734 | |
| 1735 | .. code-block:: c++ |
| 1736 | |
| 1737 | int fcntl(int fd, int cmd, ...) |
| 1738 | __attribute__(( argument_with_type_tag(fcntl,3,2) )); |
| 1739 | |
| 1740 | ``pointer_with_type_tag(...)`` |
| 1741 | ------------------------------ |
| 1742 | |
| 1743 | Use ``__attribute__((pointer_with_type_tag(ptr_kind, ptr_idx, type_tag_idx)))`` |
| 1744 | on a function declaration to specify that the function accepts a type tag that |
| 1745 | determines the pointee type of some other pointer argument. |
| 1746 | |
| 1747 | For example: |
| 1748 | |
| 1749 | .. code-block:: c++ |
| 1750 | |
| 1751 | int MPI_Send(void *buf, int count, MPI_Datatype datatype /*, other args omitted */) |
| 1752 | __attribute__(( pointer_with_type_tag(mpi,1,3) )); |
| 1753 | |
| 1754 | ``type_tag_for_datatype(...)`` |
| 1755 | ------------------------------ |
| 1756 | |
| 1757 | Clang supports annotating type tags of two forms. |
| 1758 | |
| 1759 | * **Type tag that is an expression containing a reference to some declared |
| 1760 | identifier.** Use ``__attribute__((type_tag_for_datatype(kind, type)))`` on a |
| 1761 | declaration with that identifier: |
| 1762 | |
| 1763 | .. code-block:: c++ |
| 1764 | |
| 1765 | extern struct mpi_datatype mpi_datatype_int |
| 1766 | __attribute__(( type_tag_for_datatype(mpi,int) )); |
| 1767 | #define MPI_INT ((MPI_Datatype) &mpi_datatype_int) |
| 1768 | |
| 1769 | * **Type tag that is an integral literal.** Introduce a ``static const`` |
| 1770 | variable with a corresponding initializer value and attach |
| 1771 | ``__attribute__((type_tag_for_datatype(kind, type)))`` on that declaration, |
| 1772 | for example: |
| 1773 | |
| 1774 | .. code-block:: c++ |
| 1775 | |
| 1776 | #define MPI_INT ((MPI_Datatype) 42) |
| 1777 | static const MPI_Datatype mpi_datatype_int |
| 1778 | __attribute__(( type_tag_for_datatype(mpi,int) )) = 42 |
| 1779 | |
| 1780 | The attribute also accepts an optional third argument that determines how the |
| 1781 | expression is compared to the type tag. There are two supported flags: |
| 1782 | |
| 1783 | * ``layout_compatible`` will cause types to be compared according to |
| 1784 | layout-compatibility rules (C++11 [class.mem] p 17, 18). This is |
| 1785 | implemented to support annotating types like ``MPI_DOUBLE_INT``. |
| 1786 | |
| 1787 | For example: |
| 1788 | |
| 1789 | .. code-block:: c++ |
| 1790 | |
| 1791 | /* In mpi.h */ |
| 1792 | struct internal_mpi_double_int { double d; int i; }; |
| 1793 | extern struct mpi_datatype mpi_datatype_double_int |
| 1794 | __attribute__(( type_tag_for_datatype(mpi, struct internal_mpi_double_int, layout_compatible) )); |
| 1795 | |
| 1796 | #define MPI_DOUBLE_INT ((MPI_Datatype) &mpi_datatype_double_int) |
| 1797 | |
| 1798 | /* In user code */ |
| 1799 | struct my_pair { double a; int b; }; |
| 1800 | struct my_pair *buffer; |
| 1801 | MPI_Send(buffer, 1, MPI_DOUBLE_INT /*, ... */); // no warning |
| 1802 | |
| 1803 | struct my_int_pair { int a; int b; } |
| 1804 | struct my_int_pair *buffer2; |
| 1805 | MPI_Send(buffer2, 1, MPI_DOUBLE_INT /*, ... */); // warning: actual buffer element |
| 1806 | // type 'struct my_int_pair' |
| 1807 | // doesn't match specified MPI_Datatype |
| 1808 | |
| 1809 | * ``must_be_null`` specifies that the expression should be a null pointer |
| 1810 | constant, for example: |
| 1811 | |
| 1812 | .. code-block:: c++ |
| 1813 | |
| 1814 | /* In mpi.h */ |
| 1815 | extern struct mpi_datatype mpi_datatype_null |
| 1816 | __attribute__(( type_tag_for_datatype(mpi, void, must_be_null) )); |
| 1817 | |
| 1818 | #define MPI_DATATYPE_NULL ((MPI_Datatype) &mpi_datatype_null) |
| 1819 | |
| 1820 | /* In user code */ |
| 1821 | MPI_Send(buffer, 1, MPI_DATATYPE_NULL /*, ... */); // warning: MPI_DATATYPE_NULL |
| 1822 | // was specified but buffer |
| 1823 | // is not a null pointer |
| 1824 | |