| 1 |
========================= |
| 2 |
Clang Language Extensions |
| 3 |
========================= |
| 4 |
|
| 5 |
.. contents:: |
| 6 |
:local: |
| 7 |
:depth: 1 |
| 8 |
|
| 9 |
.. toctree:: |
| 10 |
:hidden: |
| 11 |
|
| 12 |
ObjectiveCLiterals |
| 13 |
BlockLanguageSpec |
| 14 |
Block-ABI-Apple |
| 15 |
AutomaticReferenceCounting |
| 16 |
PointerAuthentication |
| 17 |
MatrixTypes |
| 18 |
CXXTypeAwareAllocators |
| 19 |
|
| 20 |
Introduction |
| 21 |
============ |
| 22 |
|
| 23 |
This document describes the language extensions provided by Clang. In addition |
| 24 |
to the language extensions listed here, Clang aims to support a broad range of |
| 25 |
GCC extensions. Please see the `GCC manual |
| 26 |
<https://gcc.gnu.org/onlinedocs/gcc/C-Extensions.html>`_ for more information on |
| 27 |
these extensions. |
| 28 |
|
| 29 |
.. _langext-feature_check: |
| 30 |
|
| 31 |
Feature Checking Macros |
| 32 |
======================= |
| 33 |
|
| 34 |
Language extensions can be very useful, but only if you know you can depend on |
| 35 |
them. In order to allow fine-grained feature checks, we support three builtin |
| 36 |
function-like macros. This allows you to directly test for a feature in your |
| 37 |
code without having to resort to something like autoconf or fragile "compiler |
| 38 |
version checks". |
| 39 |
|
| 40 |
``__has_builtin`` |
| 41 |
----------------- |
| 42 |
|
| 43 |
This function-like macro takes a single identifier argument that is the name of |
| 44 |
a builtin function, a builtin pseudo-function (taking one or more type |
| 45 |
arguments), or a builtin template. |
| 46 |
It evaluates to 1 if the builtin is supported or 0 if not. |
| 47 |
It can be used like this: |
| 48 |
|
| 49 |
.. code-block:: c++ |
| 50 |
|
| 51 |
#ifndef __has_builtin // Optional of course. |
| 52 |
#define __has_builtin(x) 0 // Compatibility with non-clang compilers. |
| 53 |
#endif |
| 54 |
|
| 55 |
... |
| 56 |
#if __has_builtin(__builtin_trap) |
| 57 |
__builtin_trap(); |
| 58 |
#else |
| 59 |
abort(); |
| 60 |
#endif |
| 61 |
... |
| 62 |
|
| 63 |
.. note:: |
| 64 |
|
| 65 |
Prior to Clang 10, ``__has_builtin`` could not be used to detect most builtin |
| 66 |
pseudo-functions. |
| 67 |
|
| 68 |
``__has_builtin`` should not be used to detect support for a builtin macro; |
| 69 |
use ``#ifdef`` instead. |
| 70 |
|
| 71 |
When compiling with target offloading, ``__has_builtin`` only considers the |
| 72 |
currently active target. |
| 73 |
|
| 74 |
``__has_constexpr_builtin`` |
| 75 |
--------------------------- |
| 76 |
|
| 77 |
This function-like macro takes a single identifier argument that is the name of |
| 78 |
a builtin function, a builtin pseudo-function (taking one or more type |
| 79 |
arguments), or a builtin template. |
| 80 |
It evaluates to 1 if the builtin is supported and can be constant evaluated or |
| 81 |
0 if not. It can be used for writing conditionally constexpr code like this: |
| 82 |
|
| 83 |
.. code-block:: c++ |
| 84 |
|
| 85 |
#ifndef __has_constexpr_builtin // Optional of course. |
| 86 |
#define __has_constexpr_builtin(x) 0 // Compatibility with non-clang compilers. |
| 87 |
#endif |
| 88 |
|
| 89 |
... |
| 90 |
#if __has_constexpr_builtin(__builtin_fmax) |
| 91 |
constexpr |
| 92 |
#endif |
| 93 |
double money_fee(double amount) { |
| 94 |
return __builtin_fmax(amount * 0.03, 10.0); |
| 95 |
} |
| 96 |
... |
| 97 |
|
| 98 |
For example, ``__has_constexpr_builtin`` is used in libcxx's implementation of |
| 99 |
the ``<cmath>`` header file to conditionally make a function constexpr whenever |
| 100 |
the constant evaluation of the corresponding builtin (for example, |
| 101 |
``std::fmax`` calls ``__builtin_fmax``) is supported in Clang. |
| 102 |
|
| 103 |
.. _langext-__has_feature-__has_extension: |
| 104 |
|
| 105 |
``__has_feature`` and ``__has_extension`` |
| 106 |
----------------------------------------- |
| 107 |
|
| 108 |
These function-like macros take a single identifier argument that is the name |
| 109 |
of a feature. ``__has_feature`` evaluates to 1 if the feature is both |
| 110 |
supported by Clang and standardized in the current language standard or 0 if |
| 111 |
not (but see :ref:`below <langext-has-feature-back-compat>`), while |
| 112 |
``__has_extension`` evaluates to 1 if the feature is supported by Clang in the |
| 113 |
current language (either as a language extension or a standard language |
| 114 |
feature) or 0 if not. They can be used like this: |
| 115 |
|
| 116 |
.. code-block:: c++ |
| 117 |
|
| 118 |
#ifndef __has_feature // Optional of course. |
| 119 |
#define __has_feature(x) 0 // Compatibility with non-clang compilers. |
| 120 |
#endif |
| 121 |
#ifndef __has_extension |
| 122 |
#define __has_extension __has_feature // Compatibility with pre-3.0 compilers. |
| 123 |
#endif |
| 124 |
|
| 125 |
... |
| 126 |
#if __has_feature(cxx_rvalue_references) |
| 127 |
// This code will only be compiled with the -std=c++11 and -std=gnu++11 |
| 128 |
// options, because rvalue references are only standardized in C++11. |
| 129 |
#endif |
| 130 |
|
| 131 |
#if __has_extension(cxx_rvalue_references) |
| 132 |
// This code will be compiled with the -std=c++11, -std=gnu++11, -std=c++98 |
| 133 |
// and -std=gnu++98 options, because rvalue references are supported as a |
| 134 |
// language extension in C++98. |
| 135 |
#endif |
| 136 |
|
| 137 |
.. _langext-has-feature-back-compat: |
| 138 |
|
| 139 |
For backward compatibility, ``__has_feature`` can also be used to test |
| 140 |
for support for non-standardized features, i.e., features not prefixed ``c_``, |
| 141 |
``cxx_`` or ``objc_``. |
| 142 |
|
| 143 |
Another use of ``__has_feature`` is to check for compiler features not related |
| 144 |
to the language standard, such as :doc:`AddressSanitizer |
| 145 |
<AddressSanitizer>`. |
| 146 |
|
| 147 |
If the ``-pedantic-errors`` option is given, ``__has_extension`` is equivalent |
| 148 |
to ``__has_feature``. |
| 149 |
|
| 150 |
The feature tag is described along with the language feature below. |
| 151 |
|
| 152 |
The feature name or extension name can also be specified with a preceding and |
| 153 |
following ``__`` (double underscore) to avoid interference from a macro with |
| 154 |
the same name. For instance, ``__cxx_rvalue_references__`` can be used instead |
| 155 |
of ``cxx_rvalue_references``. |
| 156 |
|
| 157 |
``__has_cpp_attribute`` |
| 158 |
----------------------- |
| 159 |
|
| 160 |
This function-like macro is available in C++20 by default, and is provided as an |
| 161 |
extension in earlier language standards. It takes a single argument that is the |
| 162 |
name of a double-square-bracket-style attribute. The argument can be either a |
| 163 |
single identifier or a scoped identifier. If the attribute is supported, a |
| 164 |
nonzero value is returned. If the attribute is a standards-based attribute, this |
| 165 |
macro returns a nonzero value based on the year and month in which the attribute |
| 166 |
was voted into the working draft. See `WG21 SD-6 |
| 167 |
<https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations>`_ |
| 168 |
for the list of values returned for standards-based attributes. If the attribute |
| 169 |
is not supported by the current compilation target, this macro evaluates to 0. |
| 170 |
It can be used like this: |
| 171 |
|
| 172 |
.. code-block:: c++ |
| 173 |
|
| 174 |
#ifndef __has_cpp_attribute // For backwards compatibility |
| 175 |
#define __has_cpp_attribute(x) 0 |
| 176 |
#endif |
| 177 |
|
| 178 |
... |
| 179 |
#if __has_cpp_attribute(clang::fallthrough) |
| 180 |
#define FALLTHROUGH [[clang::fallthrough]] |
| 181 |
#else |
| 182 |
#define FALLTHROUGH |
| 183 |
#endif |
| 184 |
... |
| 185 |
|
| 186 |
The attribute scope tokens ``clang`` and ``_Clang`` are interchangeable, as are |
| 187 |
the attribute scope tokens ``gnu`` and ``__gnu__``. Attribute tokens in either |
| 188 |
of these namespaces can be specified with a preceding and following ``__`` |
| 189 |
(double underscore) to avoid interference from a macro with the same name. For |
| 190 |
instance, ``gnu::__const__`` can be used instead of ``gnu::const``. |
| 191 |
|
| 192 |
``__has_c_attribute`` |
| 193 |
--------------------- |
| 194 |
|
| 195 |
This function-like macro takes a single argument that is the name of an |
| 196 |
attribute exposed with the double square-bracket syntax in C mode. The argument |
| 197 |
can either be a single identifier or a scoped identifier. If the attribute is |
| 198 |
supported, a nonzero value is returned. If the attribute is not supported by the |
| 199 |
current compilation target, this macro evaluates to 0. It can be used like this: |
| 200 |
|
| 201 |
.. code-block:: c |
| 202 |
|
| 203 |
#ifndef __has_c_attribute // Optional of course. |
| 204 |
#define __has_c_attribute(x) 0 // Compatibility with non-clang compilers. |
| 205 |
#endif |
| 206 |
|
| 207 |
... |
| 208 |
#if __has_c_attribute(fallthrough) |
| 209 |
#define FALLTHROUGH [[fallthrough]] |
| 210 |
#else |
| 211 |
#define FALLTHROUGH |
| 212 |
#endif |
| 213 |
... |
| 214 |
|
| 215 |
The attribute scope tokens ``clang`` and ``_Clang`` are interchangeable, as are |
| 216 |
the attribute scope tokens ``gnu`` and ``__gnu__``. Attribute tokens in either |
| 217 |
of these namespaces can be specified with a preceding and following ``__`` |
| 218 |
(double underscore) to avoid interference from a macro with the same name. For |
| 219 |
instance, ``gnu::__const__`` can be used instead of ``gnu::const``. |
| 220 |
|
| 221 |
``__has_attribute`` |
| 222 |
------------------- |
| 223 |
|
| 224 |
This function-like macro takes a single identifier argument that is the name of |
| 225 |
a GNU-style attribute. It evaluates to 1 if the attribute is supported by the |
| 226 |
current compilation target, or 0 if not. It can be used like this: |
| 227 |
|
| 228 |
.. code-block:: c++ |
| 229 |
|
| 230 |
#ifndef __has_attribute // Optional of course. |
| 231 |
#define __has_attribute(x) 0 // Compatibility with non-clang compilers. |
| 232 |
#endif |
| 233 |
|
| 234 |
... |
| 235 |
#if __has_attribute(always_inline) |
| 236 |
#define ALWAYS_INLINE __attribute__((always_inline)) |
| 237 |
#else |
| 238 |
#define ALWAYS_INLINE |
| 239 |
#endif |
| 240 |
... |
| 241 |
|
| 242 |
The attribute name can also be specified with a preceding and following ``__`` |
| 243 |
(double underscore) to avoid interference from a macro with the same name. For |
| 244 |
instance, ``__always_inline__`` can be used instead of ``always_inline``. |
| 245 |
|
| 246 |
|
| 247 |
``__has_declspec_attribute`` |
| 248 |
---------------------------- |
| 249 |
|
| 250 |
This function-like macro takes a single identifier argument that is the name of |
| 251 |
an attribute implemented as a Microsoft-style ``__declspec`` attribute. It |
| 252 |
evaluates to 1 if the attribute is supported by the current compilation target, |
| 253 |
or 0 if not. It can be used like this: |
| 254 |
|
| 255 |
.. code-block:: c++ |
| 256 |
|
| 257 |
#ifndef __has_declspec_attribute // Optional of course. |
| 258 |
#define __has_declspec_attribute(x) 0 // Compatibility with non-clang compilers. |
| 259 |
#endif |
| 260 |
|
| 261 |
... |
| 262 |
#if __has_declspec_attribute(dllexport) |
| 263 |
#define DLLEXPORT __declspec(dllexport) |
| 264 |
#else |
| 265 |
#define DLLEXPORT |
| 266 |
#endif |
| 267 |
... |
| 268 |
|
| 269 |
The attribute name can also be specified with a preceding and following ``__`` |
| 270 |
(double underscore) to avoid interference from a macro with the same name. For |
| 271 |
instance, ``__dllexport__`` can be used instead of ``dllexport``. |
| 272 |
|
| 273 |
``__is_identifier`` |
| 274 |
------------------- |
| 275 |
|
| 276 |
This function-like macro takes a single identifier argument that might be either |
| 277 |
a reserved word or a regular identifier. It evaluates to 1 if the argument is just |
| 278 |
a regular identifier and not a reserved word, in the sense that it can then be |
| 279 |
used as the name of a user-defined function or variable. Otherwise it evaluates |
| 280 |
to 0. It can be used like this: |
| 281 |
|
| 282 |
.. code-block:: c++ |
| 283 |
|
| 284 |
... |
| 285 |
#ifdef __is_identifier // Compatibility with non-clang compilers. |
| 286 |
#if __is_identifier(__wchar_t) |
| 287 |
typedef wchar_t __wchar_t; |
| 288 |
#endif |
| 289 |
#endif |
| 290 |
|
| 291 |
__wchar_t WideCharacter; |
| 292 |
... |
| 293 |
|
| 294 |
Include File Checking Macros |
| 295 |
============================ |
| 296 |
|
| 297 |
Not all developments systems have the same include files. The |
| 298 |
:ref:`langext-__has_include` and :ref:`langext-__has_include_next` macros allow |
| 299 |
you to check for the existence of an include file before doing a possibly |
| 300 |
failing ``#include`` directive. Include file checking macros must be used |
| 301 |
as expressions in ``#if`` or ``#elif`` preprocessing directives. |
| 302 |
|
| 303 |
.. _langext-__has_include: |
| 304 |
|
| 305 |
``__has_include`` |
| 306 |
----------------- |
| 307 |
|
| 308 |
This function-like macro takes a single file name string argument that is the |
| 309 |
name of an include file. It evaluates to 1 if the file can be found using the |
| 310 |
include paths, or 0 otherwise: |
| 311 |
|
| 312 |
.. code-block:: c++ |
| 313 |
|
| 314 |
// Note the two possible file name string formats. |
| 315 |
#if __has_include("myinclude.h") && __has_include(<stdint.h>) |
| 316 |
# include "myinclude.h" |
| 317 |
#endif |
| 318 |
|
| 319 |
To test for this feature, use ``#if defined(__has_include)``: |
| 320 |
|
| 321 |
.. code-block:: c++ |
| 322 |
|
| 323 |
// To avoid problems with non-clang compilers not having this macro. |
| 324 |
#if defined(__has_include) |
| 325 |
#if __has_include("myinclude.h") |
| 326 |
# include "myinclude.h" |
| 327 |
#endif |
| 328 |
#endif |
| 329 |
|
| 330 |
.. _langext-__has_include_next: |
| 331 |
|
| 332 |
``__has_include_next`` |
| 333 |
---------------------- |
| 334 |
|
| 335 |
This function-like macro takes a single file name string argument that is the |
| 336 |
name of an include file. It is like ``__has_include`` except that it looks for |
| 337 |
the second instance of the given file found in the include paths. It evaluates |
| 338 |
to 1 if the second instance of the file can be found using the include paths, |
| 339 |
or 0 otherwise: |
| 340 |
|
| 341 |
.. code-block:: c++ |
| 342 |
|
| 343 |
// Note the two possible file name string formats. |
| 344 |
#if __has_include_next("myinclude.h") && __has_include_next(<stdint.h>) |
| 345 |
# include_next "myinclude.h" |
| 346 |
#endif |
| 347 |
|
| 348 |
// To avoid problems with non-clang compilers not having this macro. |
| 349 |
#if defined(__has_include_next) |
| 350 |
#if __has_include_next("myinclude.h") |
| 351 |
# include_next "myinclude.h" |
| 352 |
#endif |
| 353 |
#endif |
| 354 |
|
| 355 |
Note that ``__has_include_next``, like the GNU extension ``#include_next`` |
| 356 |
directive, is intended for use in headers only, and will issue a warning if |
| 357 |
used in the top-level compilation file. A warning will also be issued if an |
| 358 |
absolute path is used in the file argument. |
| 359 |
|
| 360 |
``__has_warning`` |
| 361 |
----------------- |
| 362 |
|
| 363 |
This function-like macro takes a string literal that represents a command line |
| 364 |
option for a warning and returns ``true`` if that is a valid warning option. |
| 365 |
|
| 366 |
.. code-block:: c++ |
| 367 |
|
| 368 |
#if __has_warning("-Wformat") |
| 369 |
... |
| 370 |
#endif |
| 371 |
|
| 372 |
.. _languageextensions-builtin-macros: |
| 373 |
|
| 374 |
Builtin Macros |
| 375 |
============== |
| 376 |
|
| 377 |
``__BASE_FILE__`` |
| 378 |
Defined to a string that contains the name of the main input file passed to |
| 379 |
Clang. |
| 380 |
|
| 381 |
``__FILE_NAME__`` |
| 382 |
Clang-specific extension that functions similar to ``__FILE__`` but only |
| 383 |
renders the last path component (the filename) instead of an |
| 384 |
invocation-dependent full path to that file. |
| 385 |
|
| 386 |
``__COUNTER__`` |
| 387 |
Defined to an integer value that starts at zero and is incremented each time |
| 388 |
the ``__COUNTER__`` macro is expanded. This is a standard feature in C2y but |
| 389 |
is an extension in earlier language modes and in C++. This macro can only be |
| 390 |
expanded 2147483647 times at most. |
| 391 |
|
| 392 |
``__INCLUDE_LEVEL__`` |
| 393 |
Defined to an integral value that is the include depth of the file currently |
| 394 |
being translated. For the main file, this value is zero. |
| 395 |
|
| 396 |
``__TIMESTAMP__`` |
| 397 |
Defined to the date and time of the last modification of the current source |
| 398 |
file. |
| 399 |
|
| 400 |
``__clang__`` |
| 401 |
Defined when compiling with Clang. |
| 402 |
|
| 403 |
``__clang_major__`` |
| 404 |
Defined to the major marketing version number of Clang (e.g., the 2 in |
| 405 |
2.0.1). Note that marketing version numbers should not be used to check for |
| 406 |
language features, as different vendors use different numbering schemes. |
| 407 |
Instead, use the :ref:`langext-feature_check`. |
| 408 |
|
| 409 |
``__clang_minor__`` |
| 410 |
Defined to the minor version number of Clang (e.g., the 0 in 2.0.1). Note |
| 411 |
that marketing version numbers should not be used to check for language |
| 412 |
features, as different vendors use different numbering schemes. Instead, use |
| 413 |
the :ref:`langext-feature_check`. |
| 414 |
|
| 415 |
``__clang_patchlevel__`` |
| 416 |
Defined to the marketing patch level of Clang (e.g., the 1 in 2.0.1). |
| 417 |
|
| 418 |
``__clang_version__`` |
| 419 |
Defined to a string that captures the Clang marketing version, including the |
| 420 |
Subversion tag or revision number, e.g., "``1.5 (trunk 102332)``". |
| 421 |
|
| 422 |
``__clang_literal_encoding__`` |
| 423 |
Defined to a narrow string literal that represents the current encoding of |
| 424 |
narrow string literals, e.g., ``"hello"``. This macro typically expands to |
| 425 |
"UTF-8" (but may change in the future if the |
| 426 |
``-fexec-charset="Encoding-Name"`` option is implemented.) |
| 427 |
|
| 428 |
``__clang_wide_literal_encoding__`` |
| 429 |
Defined to a narrow string literal that represents the current encoding of |
| 430 |
wide string literals, e.g., ``L"hello"``. This macro typically expands to |
| 431 |
"UTF-16" or "UTF-32" (but may change in the future if the |
| 432 |
``-fwide-exec-charset="Encoding-Name"`` option is implemented.) |
| 433 |
|
| 434 |
Implementation-defined keywords |
| 435 |
=============================== |
| 436 |
|
| 437 |
__datasizeof |
| 438 |
------------ |
| 439 |
|
| 440 |
``__datasizeof`` behaves like ``sizeof``, except that it returns the size of the |
| 441 |
type ignoring tail padding. |
| 442 |
|
| 443 |
_BitInt, _ExtInt |
| 444 |
---------------- |
| 445 |
|
| 446 |
Clang supports the C23 ``_BitInt(N)`` feature as an extension in older C modes |
| 447 |
and in C++. This type was previously implemented in Clang with the same |
| 448 |
semantics, but spelled ``_ExtInt(N)``. This spelling has been deprecated in |
| 449 |
favor of the standard type. |
| 450 |
|
| 451 |
Note: the ABI for ``_BitInt(N)`` is still in the process of being stabilized, |
| 452 |
so this type should not yet be used in interfaces that require ABI stability. |
| 453 |
|
| 454 |
C keywords supported in all language modes |
| 455 |
------------------------------------------ |
| 456 |
|
| 457 |
Clang supports ``_Alignas``, ``_Alignof``, ``_Atomic``, ``_Complex``, |
| 458 |
``_Generic``, ``_Imaginary``, ``_Noreturn``, ``_Static_assert``, |
| 459 |
``_Thread_local``, and ``_Float16`` in all language modes with the C semantics. |
| 460 |
|
| 461 |
__alignof, __alignof__ |
| 462 |
---------------------- |
| 463 |
|
| 464 |
``__alignof`` and ``__alignof__`` return, in contrast to ``_Alignof`` and |
| 465 |
``alignof``, the preferred alignment of a type. This may be larger than the |
| 466 |
required alignment for improved performance. |
| 467 |
|
| 468 |
__extension__ |
| 469 |
------------- |
| 470 |
|
| 471 |
``__extension__`` suppresses extension diagnostics in the statement it is |
| 472 |
prepended to. |
| 473 |
|
| 474 |
__auto_type |
| 475 |
----------- |
| 476 |
|
| 477 |
``__auto_type`` behaves the same as ``auto`` in C++11 but is available in all |
| 478 |
language modes. |
| 479 |
|
| 480 |
__imag, __imag__ |
| 481 |
---------------- |
| 482 |
|
| 483 |
``__imag`` and ``__imag__`` can be used to get the imaginary part of a complex |
| 484 |
value. |
| 485 |
|
| 486 |
__real, __real__ |
| 487 |
---------------- |
| 488 |
|
| 489 |
``__real`` and ``__real__`` can be used to get the real part of a complex value. |
| 490 |
|
| 491 |
__asm, __asm__ |
| 492 |
-------------- |
| 493 |
|
| 494 |
``__asm`` and ``__asm__`` are alternate spellings for ``asm``, but available in |
| 495 |
all language modes. |
| 496 |
|
| 497 |
__complex, __complex__ |
| 498 |
---------------------- |
| 499 |
|
| 500 |
``__complex`` and ``__complex__`` are alternate spellings for ``_Complex``. |
| 501 |
|
| 502 |
__const, __const__, __volatile, __volatile__, __restrict, __restrict__ |
| 503 |
---------------------------------------------------------------------- |
| 504 |
|
| 505 |
These are alternate spellings for their non-underscore counterparts, but are |
| 506 |
available in all language modes. |
| 507 |
|
| 508 |
__decltype |
| 509 |
---------- |
| 510 |
|
| 511 |
``__decltype`` is an alternate spelling for ``decltype``, but is also available |
| 512 |
in C++ modes before C++11. |
| 513 |
|
| 514 |
__inline, __inline__ |
| 515 |
-------------------- |
| 516 |
|
| 517 |
``__inline`` and ``__inline__`` are alternate spellings for ``inline``, but are |
| 518 |
available in all language modes. |
| 519 |
|
| 520 |
__nullptr |
| 521 |
--------- |
| 522 |
|
| 523 |
``__nullptr`` is an alternate spelling for ``nullptr``. It is available in all C and C++ language modes. |
| 524 |
|
| 525 |
__signed, __signed__ |
| 526 |
-------------------- |
| 527 |
|
| 528 |
``__signed`` and ``__signed__`` are alternate spellings for ``signed``. |
| 529 |
``__unsigned`` and ``__unsigned__`` are **not** supported. |
| 530 |
|
| 531 |
__typeof, __typeof__, __typeof_unqual, __typeof_unqual__ |
| 532 |
-------------------------------------------------------- |
| 533 |
|
| 534 |
``__typeof`` and ``__typeof__`` are alternate spellings for ``typeof``, but are |
| 535 |
available in all language modes. These spellings result in the operand, |
| 536 |
retaining all qualifiers. |
| 537 |
|
| 538 |
``__typeof_unqual`` and ``__typeof_unqual__`` are alternate spellings for the |
| 539 |
C23 ``typeof_unqual`` type specifier, but are available in all language modes. |
| 540 |
These spellings result in the type of the operand, stripping all qualifiers. |
| 541 |
|
| 542 |
__char16_t, __char32_t |
| 543 |
---------------------- |
| 544 |
|
| 545 |
``__char16_t`` and ``__char32_t`` are alternate spellings for ``char16_t`` and |
| 546 |
``char32_t`` respectively, but are also available in C++ modes before C++11. |
| 547 |
They are only supported in C++. ``__char8_t`` is not available. |
| 548 |
|
| 549 |
.. |
| 550 |
FIXME: This should list all the keyword extensions |
| 551 |
|
| 552 |
.. _langext-vectors: |
| 553 |
|
| 554 |
Vectors and Extended Vectors |
| 555 |
============================ |
| 556 |
|
| 557 |
Supports the GCC, OpenCL, AltiVec, NEON and SVE vector extensions. |
| 558 |
|
| 559 |
OpenCL vector types are created using the ``ext_vector_type`` attribute. It |
| 560 |
supports the ``V.xyzw`` syntax and other tidbits as seen in OpenCL. An example |
| 561 |
is: |
| 562 |
|
| 563 |
.. code-block:: c++ |
| 564 |
|
| 565 |
typedef float float4 __attribute__((ext_vector_type(4))); |
| 566 |
typedef float float2 __attribute__((ext_vector_type(2))); |
| 567 |
|
| 568 |
float4 foo(float2 a, float2 b) { |
| 569 |
float4 c; |
| 570 |
c.xz = a; |
| 571 |
c.yw = b; |
| 572 |
return c; |
| 573 |
} |
| 574 |
|
| 575 |
Query for this feature with ``__has_attribute(ext_vector_type)``. |
| 576 |
|
| 577 |
Giving ``-maltivec`` option to clang enables support for AltiVec vector syntax |
| 578 |
and functions. For example: |
| 579 |
|
| 580 |
.. code-block:: c++ |
| 581 |
|
| 582 |
vector float foo(vector int a) { |
| 583 |
vector int b; |
| 584 |
b = vec_add(a, a) + a; |
| 585 |
return (vector float)b; |
| 586 |
} |
| 587 |
|
| 588 |
NEON vector types are created using ``neon_vector_type`` and |
| 589 |
``neon_polyvector_type`` attributes. For example: |
| 590 |
|
| 591 |
.. code-block:: c++ |
| 592 |
|
| 593 |
typedef __attribute__((neon_vector_type(8))) int8_t int8x8_t; |
| 594 |
typedef __attribute__((neon_polyvector_type(16))) poly8_t poly8x16_t; |
| 595 |
|
| 596 |
int8x8_t foo(int8x8_t a) { |
| 597 |
int8x8_t v; |
| 598 |
v = a; |
| 599 |
return v; |
| 600 |
} |
| 601 |
|
| 602 |
GCC vector types are created using the ``vector_size(N)`` attribute. The |
| 603 |
argument ``N`` specifies the number of bytes that will be allocated for an |
| 604 |
object of this type. The size has to be a multiple of the size of the vector |
| 605 |
element type. For example: |
| 606 |
|
| 607 |
.. code-block:: c++ |
| 608 |
|
| 609 |
// OK: This declares a vector type with four 'int' elements |
| 610 |
typedef int int4 __attribute__((vector_size(4 * sizeof(int)))); |
| 611 |
|
| 612 |
// ERROR: '11' is not a multiple of sizeof(int) |
| 613 |
typedef int int_impossible __attribute__((vector_size(11))); |
| 614 |
|
| 615 |
int4 foo(int4 a) { |
| 616 |
int4 v; |
| 617 |
v = a; |
| 618 |
return v; |
| 619 |
} |
| 620 |
|
| 621 |
|
| 622 |
Boolean Vectors |
| 623 |
--------------- |
| 624 |
|
| 625 |
Clang also supports the ``ext_vector_type`` attribute with boolean element types in |
| 626 |
C and C++. For example: |
| 627 |
|
| 628 |
.. code-block:: c++ |
| 629 |
|
| 630 |
// legal for Clang, error for GCC: |
| 631 |
typedef bool bool4 __attribute__((ext_vector_type(4))); |
| 632 |
// Objects of bool4 type hold 8 bits, sizeof(bool4) == 1 |
| 633 |
|
| 634 |
bool4 foo(bool4 a) { |
| 635 |
bool4 v; |
| 636 |
v = a; |
| 637 |
return v; |
| 638 |
} |
| 639 |
|
| 640 |
|
| 641 |
Boolean vectors are a Clang extension of the ext vector type. Boolean vectors |
| 642 |
are intended, though not guaranteed, to map to vector mask registers. The size |
| 643 |
parameter of a boolean vector type is the number of bits in the vector. The |
| 644 |
boolean vector is dense and each bit in the boolean vector is one vector |
| 645 |
element. Query for this feature with ``__has_feature(ext_vector_type_boolean)``. |
| 646 |
|
| 647 |
The semantics of boolean vectors borrows from C bit-fields with the following |
| 648 |
differences: |
| 649 |
|
| 650 |
* Distinct boolean vectors are always distinct memory objects (there is no |
| 651 |
packing). |
| 652 |
* Only the operators `?:`, `!`, `~`, `|`, `&`, `^` and comparison are allowed on |
| 653 |
boolean vectors. |
| 654 |
* Casting a scalar bool value to a boolean vector type means broadcasting the |
| 655 |
scalar value onto all lanes (same as general ext_vector_type). |
| 656 |
* It is not possible to access or swizzle elements of a boolean vector |
| 657 |
(different than general ext_vector_type). |
| 658 |
|
| 659 |
The size and alignment are both the number of bits rounded up to the next power |
| 660 |
of two, but the alignment is at most the maximum vector alignment of the |
| 661 |
target. |
| 662 |
|
| 663 |
A boolean vector can be used in a ternary `?:` operator to select vector |
| 664 |
elements of a different type. |
| 665 |
|
| 666 |
.. code-block:: c++ |
| 667 |
|
| 668 |
typedef int int4 __attribute__((ext_vector_type(4))); |
| 669 |
typedef bool bool4 __attribute__((ext_vector_type(4))); |
| 670 |
|
| 671 |
int4 blend(bool4 cond, int4 a, int4 b) { return cond ? a : b; } |
| 672 |
|
| 673 |
|
| 674 |
Vector Literals |
| 675 |
--------------- |
| 676 |
|
| 677 |
Vector literals can be used to create vectors from a set of scalars, or |
| 678 |
vectors. Either parentheses or braces form can be used. In the parentheses |
| 679 |
form the number of literal values specified must be one, i.e., referring to a |
| 680 |
scalar value, or must match the size of the vector type being created. If a |
| 681 |
single scalar literal value is specified, the scalar literal value will be |
| 682 |
replicated to all the components of the vector type. In the brackets form any |
| 683 |
number of literals can be specified. For example: |
| 684 |
|
| 685 |
.. code-block:: c++ |
| 686 |
|
| 687 |
typedef int v4si __attribute__((__vector_size__(16))); |
| 688 |
typedef float float4 __attribute__((ext_vector_type(4))); |
| 689 |
typedef float float2 __attribute__((ext_vector_type(2))); |
| 690 |
|
| 691 |
v4si vsi = (v4si){1, 2, 3, 4}; |
| 692 |
float4 vf = (float4)(1.0f, 2.0f, 3.0f, 4.0f); |
| 693 |
vector int vi1 = (vector int)(1); // vi1 will be (1, 1, 1, 1). |
| 694 |
vector int vi2 = (vector int){1}; // vi2 will be (1, 0, 0, 0). |
| 695 |
vector int vi3 = (vector int)(1, 2); // error |
| 696 |
vector int vi4 = (vector int){1, 2}; // vi4 will be (1, 2, 0, 0). |
| 697 |
vector int vi5 = (vector int)(1, 2, 3, 4); |
| 698 |
float4 vf = (float4)((float2)(1.0f, 2.0f), (float2)(3.0f, 4.0f)); |
| 699 |
|
| 700 |
Vector Operations |
| 701 |
----------------- |
| 702 |
|
| 703 |
The table below shows the support for each operation by vector extension. A |
| 704 |
dash indicates that an operation is not accepted according to a corresponding |
| 705 |
specification. |
| 706 |
|
| 707 |
============================== ======= ======= ============= ======= ===== |
| 708 |
Operator OpenCL AltiVec GCC NEON SVE |
| 709 |
============================== ======= ======= ============= ======= ===== |
| 710 |
[] yes yes yes yes yes |
| 711 |
unary operators +, -- yes yes yes yes yes |
| 712 |
++, -- -- yes yes yes no no |
| 713 |
+,--,*,/,% yes yes yes yes yes |
| 714 |
bitwise operators &,|,^,~ yes yes yes yes yes |
| 715 |
>>,<< yes yes yes yes yes |
| 716 |
!, &&, || yes -- yes yes yes |
| 717 |
==, !=, >, <, >=, <= yes yes yes yes yes |
| 718 |
= yes yes yes yes yes |
| 719 |
?: [#]_ yes -- yes yes yes |
| 720 |
sizeof yes yes yes yes yes [#]_ |
| 721 |
C-style cast yes yes yes no no |
| 722 |
reinterpret_cast yes no yes no no |
| 723 |
static_cast yes no yes no no |
| 724 |
const_cast no no no no no |
| 725 |
address &v[i] no no no [#]_ no no |
| 726 |
============================== ======= ======= ============= ======= ===== |
| 727 |
|
| 728 |
See also :ref:`langext-__builtin_shufflevector`, :ref:`langext-__builtin_convertvector`. |
| 729 |
|
| 730 |
.. [#] ternary operator(?:) has different behaviors depending on the condition |
| 731 |
operand's vector type. If the condition is a GNU vector (i.e., ``__vector_size__``), |
| 732 |
a NEON vector or an SVE vector, it's only available in C++ and uses normal bool |
| 733 |
conversions (that is, != 0). |
| 734 |
If it's an extension (OpenCL) vector, it's only available in C and OpenCL C. |
| 735 |
And it selects based on the signedness of the condition operands (OpenCL v1.1 s6.3.9). |
| 736 |
.. [#] sizeof can only be used on vector length specific SVE types. |
| 737 |
.. [#] Clang does not allow the address of an element to be taken while GCC |
| 738 |
allows this. This is intentional for vectors with a boolean element type and |
| 739 |
not implemented otherwise. |
| 740 |
|
| 741 |
Vector Builtins |
| 742 |
--------------- |
| 743 |
|
| 744 |
**Note: The implementation of vector builtins is work-in-progress and incomplete.** |
| 745 |
|
| 746 |
In addition to the operators mentioned above, Clang provides a set of builtins |
| 747 |
to perform additional operations on certain scalar and vector types. |
| 748 |
|
| 749 |
Let ``T`` be one of the following types: |
| 750 |
|
| 751 |
* an integer type (as in C23 6.2.5p22), but excluding enumerated types and ``bool`` |
| 752 |
* the standard floating types ``float`` or ``double`` |
| 753 |
* a half-precision floating point type, if one is supported on the target |
| 754 |
* a vector type. |
| 755 |
|
| 756 |
For scalar types, consider the operation applied to a vector with a single element. |
| 757 |
|
| 758 |
*Vector Size* |
| 759 |
To determine the number of elements in a vector, use ``__builtin_vectorelements()``. |
| 760 |
For fixed-sized vectors, e.g., defined via ``__attribute__((vector_size(N)))`` or ARM |
| 761 |
NEON's vector types (e.g., ``uint16x8_t``), this returns the constant number of |
| 762 |
elements at compile-time. For scalable vectors, e.g., SVE or RISC-V V, the number of |
| 763 |
elements is not known at compile-time and is determined at runtime. This builtin can |
| 764 |
be used, e.g., to increment the loop-counter in vector-type agnostic loops. |
| 765 |
|
| 766 |
*Elementwise Builtins* |
| 767 |
|
| 768 |
Each builtin returns a vector equivalent to applying the specified operation |
| 769 |
elementwise to the input. |
| 770 |
|
| 771 |
Unless specified otherwise operation(±0) = ±0 and operation(±infinity) = ±infinity |
| 772 |
|
| 773 |
The elementwise intrinsics ``__builtin_elementwise_popcount``, |
| 774 |
``__builtin_elementwise_bitreverse``, ``__builtin_elementwise_add_sat``, |
| 775 |
``__builtin_elementwise_sub_sat``, ``__builtin_elementwise_max``, |
| 776 |
``__builtin_elementwise_min``, ``__builtin_elementwise_abs``, |
| 777 |
``__builtin_elementwise_clzg``, ``__builtin_elementwise_ctzg``, and |
| 778 |
``__builtin_elementwise_fma`` can be called in a ``constexpr`` context. |
| 779 |
|
| 780 |
No implicit promotion of integer types takes place. The mixing of integer types |
| 781 |
of different sizes and signs is forbidden in binary and ternary builtins. |
| 782 |
|
| 783 |
============================================== ====================================================================== ========================================= |
| 784 |
Name Operation Supported element types |
| 785 |
============================================== ====================================================================== ========================================= |
| 786 |
T __builtin_elementwise_abs(T x) return the absolute value of a number x; the absolute value of signed integer and floating point types |
| 787 |
the most negative integer remains the most negative integer |
| 788 |
T __builtin_elementwise_fma(T x, T y, T z) fused multiply add, (x * y) + z. floating point types |
| 789 |
T __builtin_elementwise_ceil(T x) return the smallest integral value greater than or equal to x floating point types |
| 790 |
T __builtin_elementwise_sin(T x) return the sine of x interpreted as an angle in radians floating point types |
| 791 |
T __builtin_elementwise_cos(T x) return the cosine of x interpreted as an angle in radians floating point types |
| 792 |
T __builtin_elementwise_tan(T x) return the tangent of x interpreted as an angle in radians floating point types |
| 793 |
T __builtin_elementwise_asin(T x) return the arcsine of x interpreted as an angle in radians floating point types |
| 794 |
T __builtin_elementwise_acos(T x) return the arccosine of x interpreted as an angle in radians floating point types |
| 795 |
T __builtin_elementwise_atan(T x) return the arctangent of x interpreted as an angle in radians floating point types |
| 796 |
T __builtin_elementwise_atan2(T y, T x) return the arctangent of y/x floating point types |
| 797 |
T __builtin_elementwise_sinh(T x) return the hyperbolic sine of angle x in radians floating point types |
| 798 |
T __builtin_elementwise_cosh(T x) return the hyperbolic cosine of angle x in radians floating point types |
| 799 |
T __builtin_elementwise_tanh(T x) return the hyperbolic tangent of angle x in radians floating point types |
| 800 |
T __builtin_elementwise_floor(T x) return the largest integral value less than or equal to x floating point types |
| 801 |
T __builtin_elementwise_log(T x) return the natural logarithm of x floating point types |
| 802 |
T __builtin_elementwise_log2(T x) return the base 2 logarithm of x floating point types |
| 803 |
T __builtin_elementwise_log10(T x) return the base 10 logarithm of x floating point types |
| 804 |
T __builtin_elementwise_popcount(T x) return the number of 1 bits in x integer types |
| 805 |
T __builtin_elementwise_pow(T x, T y) return x raised to the power of y floating point types |
| 806 |
T __builtin_elementwise_bitreverse(T x) return the integer represented after reversing the bits of x integer types |
| 807 |
T __builtin_elementwise_exp(T x) returns the base-e exponential, e^x, of the specified value floating point types |
| 808 |
T __builtin_elementwise_exp2(T x) returns the base-2 exponential, 2^x, of the specified value floating point types |
| 809 |
T __builtin_elementwise_exp10(T x) returns the base-10 exponential, 10^x, of the specified value floating point types |
| 810 |
T __builtin_elementwise_ldexp(T x, IntT y) returns the product of x and 2 raised to the power y. T: floating point types, |
| 811 |
y must be an integer type matching the shape of x. IntT: integer types |
| 812 |
|
| 813 |
T __builtin_elementwise_sqrt(T x) return the square root of a floating-point number floating point types |
| 814 |
T __builtin_elementwise_roundeven(T x) round x to the nearest integer value in floating point format, floating point types |
| 815 |
rounding halfway cases to even (that is, to the nearest value |
| 816 |
that is an even integer), regardless of the current rounding |
| 817 |
direction. |
| 818 |
T __builtin_elementwise_round(T x) round x to the nearest integer value in floating point format, floating point types |
| 819 |
rounding halfway cases away from zero, regardless of the |
| 820 |
current rounding direction. May raise floating-point |
| 821 |
exceptions. |
| 822 |
T __builtin_elementwise_trunc(T x) return the integral value nearest to but no larger in floating point types |
| 823 |
magnitude than x |
| 824 |
|
| 825 |
T __builtin_elementwise_nearbyint(T x) round x to the nearest integer value in floating point format, floating point types |
| 826 |
rounding according to the current rounding direction. |
| 827 |
May not raise the inexact floating-point exception. This is |
| 828 |
treated the same as ``__builtin_elementwise_rint`` unless |
| 829 |
:ref:`FENV_ACCESS is enabled <floating-point-environment>`. |
| 830 |
|
| 831 |
T __builtin_elementwise_rint(T x) round x to the nearest integer value in floating point format, floating point types |
| 832 |
rounding according to the current rounding |
| 833 |
direction. May raise floating-point exceptions. This is treated |
| 834 |
the same as ``__builtin_elementwise_nearbyint`` unless |
| 835 |
:ref:`FENV_ACCESS is enabled <floating-point-environment>`. |
| 836 |
|
| 837 |
T __builtin_elementwise_canonicalize(T x) return the platform specific canonical encoding floating point types |
| 838 |
of a floating-point number |
| 839 |
T __builtin_elementwise_copysign(T x, T y) return the magnitude of x with the sign of y. floating point types |
| 840 |
T __builtin_elementwise_fmod(T x, T y) return the floating-point remainder of (x/y) whose sign floating point types |
| 841 |
matches the sign of x. |
| 842 |
T __builtin_elementwise_max(T x, T y) return x or y, whichever is larger integer and floating point types |
| 843 |
For floating point types, follows semantics of maxNum |
| 844 |
in IEEE 754-2008. See `LangRef |
| 845 |
<http://llvm.org/docs/LangRef.html#llvm-min-intrinsics-comparation>`_ |
| 846 |
for the comparison. |
| 847 |
T __builtin_elementwise_min(T x, T y) return x or y, whichever is smaller integer and floating point types |
| 848 |
For floating point types, follows semantics of minNum |
| 849 |
in IEEE 754-2008. See `LangRef |
| 850 |
<http://llvm.org/docs/LangRef.html#llvm-min-intrinsics-comparation>`_ |
| 851 |
for the comparison. |
| 852 |
T __builtin_elementwise_maxnum(T x, T y) return x or y, whichever is larger. Follows IEEE 754-2008 floating point types |
| 853 |
semantics (maxNum) with +0.0>-0.0. See `LangRef |
| 854 |
<http://llvm.org/docs/LangRef.html#llvm-min-intrinsics-comparation>`_ |
| 855 |
for the comparison. |
| 856 |
T __builtin_elementwise_minnum(T x, T y) return x or y, whichever is smaller. Follows IEEE 754-2008 floating point types |
| 857 |
semantics (minNum) with +0.0>-0.0. See `LangRef |
| 858 |
<http://llvm.org/docs/LangRef.html#llvm-min-intrinsics-comparation>`_ |
| 859 |
for the comparison. |
| 860 |
T __builtin_elementwise_add_sat(T x, T y) return the sum of x and y, clamped to the range of integer types |
| 861 |
representable values for the signed/unsigned integer type. |
| 862 |
T __builtin_elementwise_sub_sat(T x, T y) return the difference of x and y, clamped to the range of integer types |
| 863 |
representable values for the signed/unsigned integer type. |
| 864 |
T __builtin_elementwise_maximum(T x, T y) return x or y, whichever is larger. Follows IEEE 754-2019 floating point types |
| 865 |
semantics, see `LangRef |
| 866 |
<http://llvm.org/docs/LangRef.html#llvm-min-intrinsics-comparation>`_ |
| 867 |
for the comparison. |
| 868 |
T __builtin_elementwise_minimum(T x, T y) return x or y, whichever is smaller. Follows IEEE 754-2019 floating point types |
| 869 |
semantics, see `LangRef |
| 870 |
<http://llvm.org/docs/LangRef.html#llvm-min-intrinsics-comparation>`_ |
| 871 |
for the comparison. |
| 872 |
T __builtin_elementwise_maximumnum(T x, T y) return x or y, whichever is larger. Follows IEEE 754-2019 floating point types |
| 873 |
semantics, see `LangRef |
| 874 |
<http://llvm.org/docs/LangRef.html#llvm-min-intrinsics-comparation>`_ |
| 875 |
for the comparison. |
| 876 |
T __builtin_elementwise_minimumnum(T x, T y) return x or y, whichever is smaller. Follows IEEE 754-2019 floating point types |
| 877 |
semantics, see `LangRef |
| 878 |
<http://llvm.org/docs/LangRef.html#llvm-min-intrinsics-comparation>`_ |
| 879 |
for the comparison. |
| 880 |
T __builtin_elementwise_fshl(T x, T y, T z) perform a funnel shift left. Concatenate x and y (x is the most integer types |
| 881 |
significant bits of the wide value), the combined value is shifted |
| 882 |
left by z (modulo the bit width of the original arguments), |
| 883 |
and the most significant bits are extracted to produce |
| 884 |
a result that is the same size as the original arguments. |
| 885 |
|
| 886 |
T __builtin_elementwise_fshr(T x, T y, T z) perform a funnel shift right. Concatenate x and y (x is the most integer types |
| 887 |
significant bits of the wide value), the combined value is shifted |
| 888 |
right by z (modulo the bit width of the original arguments), |
| 889 |
and the least significant bits are extracted to produce |
| 890 |
a result that is the same size as the original arguments. |
| 891 |
T __builtin_elementwise_clzg(T x[, T y]) return the number of leading 0 bits in the first argument. If integer types |
| 892 |
the first argument is 0 and an optional second argument is provided, |
| 893 |
the second argument is returned. It is undefined behaviour if the |
| 894 |
first argument is 0 and no second argument is provided. |
| 895 |
T __builtin_elementwise_ctzg(T x[, T y]) return the number of trailing 0 bits in the first argument. If integer types |
| 896 |
the first argument is 0 and an optional second argument is provided, |
| 897 |
the second argument is returned. It is undefined behaviour if the |
| 898 |
first argument is 0 and no second argument is provided. |
| 899 |
============================================== ====================================================================== ========================================= |
| 900 |
|
| 901 |
|
| 902 |
*Reduction Builtins* |
| 903 |
|
| 904 |
Each builtin returns a scalar equivalent to applying the specified |
| 905 |
operation(x, y) as recursive even-odd pairwise reduction to all vector |
| 906 |
elements. ``operation(x, y)`` is repeatedly applied to each non-overlapping |
| 907 |
even-odd element pair with indices ``i * 2`` and ``i * 2 + 1`` with |
| 908 |
``i in [0, Number of elements / 2)``. If the number of elements is not a |
| 909 |
power of 2, the vector is widened with neutral elements for the reduction |
| 910 |
at the end to the next power of 2. |
| 911 |
|
| 912 |
These reductions support both fixed-sized and scalable vector types. |
| 913 |
|
| 914 |
The integer reduction intrinsics, including ``__builtin_reduce_max``, |
| 915 |
``__builtin_reduce_min``, ``__builtin_reduce_add``, ``__builtin_reduce_mul``, |
| 916 |
``__builtin_reduce_and``, ``__builtin_reduce_or``, and ``__builtin_reduce_xor``, |
| 917 |
can be called in a ``constexpr`` context. |
| 918 |
|
| 919 |
Example: |
| 920 |
|
| 921 |
.. code-block:: c++ |
| 922 |
|
| 923 |
__builtin_reduce_add([e3, e2, e1, e0]) = __builtin_reduced_add([e3 + e2, e1 + e0]) |
| 924 |
= (e3 + e2) + (e1 + e0) |
| 925 |
|
| 926 |
|
| 927 |
Let ``VT`` be a vector type and ``ET`` the element type of ``VT``. |
| 928 |
|
| 929 |
======================================= ====================================================================== ================================== |
| 930 |
Name Operation Supported element types |
| 931 |
======================================= ====================================================================== ================================== |
| 932 |
ET __builtin_reduce_max(VT a) return the largest element of the vector. The floating point result integer and floating point types |
| 933 |
will always be a number unless all elements of the vector are NaN. |
| 934 |
ET __builtin_reduce_min(VT a) return the smallest element of the vector. The floating point result integer and floating point types |
| 935 |
will always be a number unless all elements of the vector are NaN. |
| 936 |
ET __builtin_reduce_add(VT a) \+ integer types |
| 937 |
ET __builtin_reduce_mul(VT a) \* integer types |
| 938 |
ET __builtin_reduce_and(VT a) & integer types |
| 939 |
ET __builtin_reduce_or(VT a) \| integer types |
| 940 |
ET __builtin_reduce_xor(VT a) ^ integer types |
| 941 |
ET __builtin_reduce_maximum(VT a) return the largest element of the vector. Follows IEEE 754-2019 floating point types |
| 942 |
semantics, see `LangRef |
| 943 |
<http://llvm.org/docs/LangRef.html#llvm-min-intrinsics-comparation>`_ |
| 944 |
for the comparison. |
| 945 |
ET __builtin_reduce_minimum(VT a) return the smallest element of the vector. Follows IEEE 754-2019 floating point types |
| 946 |
semantics, see `LangRef |
| 947 |
<http://llvm.org/docs/LangRef.html#llvm-min-intrinsics-comparation>`_ |
| 948 |
for the comparison. |
| 949 |
======================================= ====================================================================== ================================== |
| 950 |
|
| 951 |
*Masked Builtins* |
| 952 |
|
| 953 |
Each builtin accesses memory according to a provided boolean mask. These are |
| 954 |
provided as ``__builtin_masked_load`` and ``__builtin_masked_store``. The first |
| 955 |
argument is always a boolean mask vector. The ``__builtin_masked_load`` builtin |
| 956 |
takes an optional third vector argument that will be used for the result of the |
| 957 |
masked-off lanes. These builtins assume the memory is unaligned, use |
| 958 |
``__builtin_assume_aligned`` if alignment is desired. |
| 959 |
|
| 960 |
The ``__builtin_masked_expand_load`` and ``__builtin_masked_compress_store`` |
| 961 |
builtins have the same interface but store the result in consecutive indices. |
| 962 |
Effectively this performs the ``if (mask[i]) val[i] = ptr[j++]`` and ``if |
| 963 |
(mask[i]) ptr[j++] = val[i]`` pattern respectively. |
| 964 |
|
| 965 |
The ``__builtin_masked_gather`` and ``__builtin_masked_scatter`` builtins handle |
| 966 |
non-sequential memory access for vector types. These use a base pointer and a |
| 967 |
vector of integer indices to gather memory into a vector type or scatter it to |
| 968 |
separate indices. |
| 969 |
|
| 970 |
Example: |
| 971 |
|
| 972 |
.. code-block:: c++ |
| 973 |
|
| 974 |
using v8b = bool [[clang::ext_vector_type(8)]]; |
| 975 |
using v8i = int [[clang::ext_vector_type(8)]]; |
| 976 |
|
| 977 |
v8i load(v8b mask, int *ptr) { return __builtin_masked_load(mask, ptr); } |
| 978 |
|
| 979 |
v8i load_expand(v8b mask, int *ptr) { |
| 980 |
return __builtin_masked_expand_load(mask, ptr); |
| 981 |
} |
| 982 |
|
| 983 |
void store(v8b mask, v8i val, int *ptr) { |
| 984 |
__builtin_masked_store(mask, val, ptr); |
| 985 |
} |
| 986 |
|
| 987 |
void store_compress(v8b mask, v8i val, int *ptr) { |
| 988 |
__builtin_masked_compress_store(mask, val, ptr); |
| 989 |
} |
| 990 |
|
| 991 |
v8i gather(v8b mask, v8i idx, int *ptr) { |
| 992 |
return __builtin_masked_gather(mask, idx, ptr); |
| 993 |
} |
| 994 |
|
| 995 |
void scatter(v8b mask, v8i val, v8i idx, int *ptr) { |
| 996 |
__builtin_masked_scatter(mask, idx, val, ptr); |
| 997 |
} |
| 998 |
|
| 999 |
|
| 1000 |
Matrix Types |
| 1001 |
============ |
| 1002 |
|
| 1003 |
Clang provides an extension for matrix types, which is currently being |
| 1004 |
implemented. See :ref:`the draft specification <matrixtypes>` for more details. |
| 1005 |
|
| 1006 |
For example, the code below uses the matrix types extension to multiply two 4x4 |
| 1007 |
float matrices and add the result to a third 4x4 matrix. |
| 1008 |
|
| 1009 |
.. code-block:: c++ |
| 1010 |
|
| 1011 |
typedef float m4x4_t __attribute__((matrix_type(4, 4))); |
| 1012 |
|
| 1013 |
m4x4_t f(m4x4_t a, m4x4_t b, m4x4_t c) { |
| 1014 |
return a + b * c; |
| 1015 |
} |
| 1016 |
|
| 1017 |
The matrix type extension also supports operations on a matrix and a scalar. |
| 1018 |
|
| 1019 |
.. code-block:: c++ |
| 1020 |
|
| 1021 |
typedef float m4x4_t __attribute__((matrix_type(4, 4))); |
| 1022 |
|
| 1023 |
m4x4_t f(m4x4_t a) { |
| 1024 |
return (a + 23) * 12; |
| 1025 |
} |
| 1026 |
|
| 1027 |
The matrix type extension supports division on a matrix and a scalar but not on a matrix and a matrix. |
| 1028 |
|
| 1029 |
.. code-block:: c++ |
| 1030 |
|
| 1031 |
typedef float m4x4_t __attribute__((matrix_type(4, 4))); |
| 1032 |
|
| 1033 |
m4x4_t f(m4x4_t a) { |
| 1034 |
a = a / 3.0; |
| 1035 |
return a; |
| 1036 |
} |
| 1037 |
|
| 1038 |
The matrix type extension supports compound assignments for addition, subtraction, and multiplication on matrices |
| 1039 |
and on a matrix and a scalar, provided their types are consistent. |
| 1040 |
|
| 1041 |
.. code-block:: c++ |
| 1042 |
|
| 1043 |
typedef float m4x4_t __attribute__((matrix_type(4, 4))); |
| 1044 |
|
| 1045 |
m4x4_t f(m4x4_t a, m4x4_t b) { |
| 1046 |
a += b; |
| 1047 |
a -= b; |
| 1048 |
a *= b; |
| 1049 |
a += 23; |
| 1050 |
a -= 12; |
| 1051 |
return a; |
| 1052 |
} |
| 1053 |
|
| 1054 |
The matrix type extension supports explicit casts. Implicit type conversion between matrix types is not allowed. |
| 1055 |
|
| 1056 |
.. code-block:: c++ |
| 1057 |
|
| 1058 |
typedef int ix5x5 __attribute__((matrix_type(5, 5))); |
| 1059 |
typedef float fx5x5 __attribute__((matrix_type(5, 5))); |
| 1060 |
|
| 1061 |
fx5x5 f1(ix5x5 i, fx5x5 f) { |
| 1062 |
return (fx5x5) i; |
| 1063 |
} |
| 1064 |
|
| 1065 |
|
| 1066 |
template <typename X> |
| 1067 |
using matrix_4_4 = X __attribute__((matrix_type(4, 4))); |
| 1068 |
|
| 1069 |
void f2() { |
| 1070 |
matrix_5_5<double> d; |
| 1071 |
matrix_5_5<int> i; |
| 1072 |
i = (matrix_5_5<int>)d; |
| 1073 |
i = static_cast<matrix_5_5<int>>(d); |
| 1074 |
} |
| 1075 |
|
| 1076 |
The matrix type extension supports column and row major memory layouts, but not |
| 1077 |
all builtins are supported with row-major layout. The layout defaults to column |
| 1078 |
major and can be specified using `-fmatrix-memory-layout`. To enable column |
| 1079 |
major layout, use `-fmatrix-memory-layout=column-major`, and for row major |
| 1080 |
layout use `-fmatrix-memory-layout=row-major` |
| 1081 |
|
| 1082 |
Half-Precision Floating Point |
| 1083 |
============================= |
| 1084 |
|
| 1085 |
Clang supports three half-precision (16-bit) floating point types: |
| 1086 |
``__fp16``, ``_Float16`` and ``__bf16``. These types are supported |
| 1087 |
in all language modes, but their support differs between targets. |
| 1088 |
A target is said to have "native support" for a type if the target |
| 1089 |
processor offers instructions for directly performing basic arithmetic |
| 1090 |
on that type. In the absence of native support, a type can still be |
| 1091 |
supported if the compiler can emulate arithmetic on the type by promoting |
| 1092 |
to ``float``; see below for more information on this emulation. |
| 1093 |
|
| 1094 |
* ``__fp16`` is supported on all targets. The special semantics of this |
| 1095 |
type mean that no arithmetic is ever performed directly on ``__fp16`` values; |
| 1096 |
see below. |
| 1097 |
|
| 1098 |
* ``_Float16`` is supported on the following targets: |
| 1099 |
|
| 1100 |
* 32-bit ARM (natively on some architecture versions) |
| 1101 |
* 64-bit ARM (AArch64) (natively on ARMv8.2a and above) |
| 1102 |
* AMDGPU (natively) |
| 1103 |
* NVPTX (natively) |
| 1104 |
* SPIR (natively) |
| 1105 |
* X86 (if SSE2 is available; natively if AVX512-FP16 is also available) |
| 1106 |
* RISC-V (natively if Zfh or Zhinx is available) |
| 1107 |
* SystemZ (emulated) |
| 1108 |
* LoongArch (emulated) |
| 1109 |
|
| 1110 |
* ``__bf16`` is supported on the following targets (currently never natively): |
| 1111 |
|
| 1112 |
* 32-bit ARM |
| 1113 |
* 64-bit ARM (AArch64) |
| 1114 |
* RISC-V |
| 1115 |
* X86 (when SSE2 is available) |
| 1116 |
* LoongArch |
| 1117 |
|
| 1118 |
(For X86, SSE2 is available on 64-bit and all recent 32-bit processors.) |
| 1119 |
|
| 1120 |
``__fp16`` and ``_Float16`` both use the binary16 format from IEEE |
| 1121 |
754-2008, which provides a 5-bit exponent and an 11-bit significand |
| 1122 |
(including the implicit leading 1). ``__bf16`` uses the `bfloat16 |
| 1123 |
<https://en.wikipedia.org/wiki/Bfloat16_floating-point_format>`_ format, |
| 1124 |
which provides an 8-bit exponent and an 8-bit significand; this is the same |
| 1125 |
exponent range as `float`, just with greatly reduced precision. |
| 1126 |
|
| 1127 |
``_Float16`` and ``__bf16`` follow the usual rules for arithmetic |
| 1128 |
floating-point types. Most importantly, this means that arithmetic operations |
| 1129 |
on operands of these types are formally performed in the type and produce |
| 1130 |
values of the type. ``__fp16`` does not follow those rules: most operations |
| 1131 |
immediately promote operands of type ``__fp16`` to ``float``, and so |
| 1132 |
arithmetic operations are defined to be performed in ``float`` and so result in |
| 1133 |
a value of type ``float`` (unless further promoted because of other operands). |
| 1134 |
See below for more information on the exact specifications of these types. |
| 1135 |
|
| 1136 |
When compiling arithmetic on ``_Float16`` and ``__bf16`` for a target without |
| 1137 |
native support, Clang will perform the arithmetic in ``float``, inserting |
| 1138 |
extensions and truncations as necessary. This can be done in a way that |
| 1139 |
exactly matches the operation-by-operation behavior of native support, |
| 1140 |
but that can require many extra truncations and extensions. By default, |
| 1141 |
when emulating ``_Float16`` and ``__bf16`` arithmetic using ``float``, Clang |
| 1142 |
does not truncate intermediate operands back to their true type unless the |
| 1143 |
operand is the result of an explicit cast or assignment. This is generally |
| 1144 |
much faster but can generate different results from strict operation-by-operation |
| 1145 |
emulation. Usually the results are more precise. This is permitted by the |
| 1146 |
C and C++ standards under the rules for excess precision in intermediate operands; |
| 1147 |
see the discussion of evaluation formats in the C standard and [expr.pre] in |
| 1148 |
the C++ standard. |
| 1149 |
|
| 1150 |
The use of excess precision can be independently controlled for these two |
| 1151 |
types with the ``-ffloat16-excess-precision=`` and |
| 1152 |
``-fbfloat16-excess-precision=`` options. Valid values include: |
| 1153 |
|
| 1154 |
* ``none``: meaning to perform strict operation-by-operation emulation |
| 1155 |
* ``standard``: meaning that excess precision is permitted under the rules |
| 1156 |
described in the standard, i.e., never across explicit casts or statements |
| 1157 |
* ``fast``: meaning that excess precision is permitted whenever the |
| 1158 |
optimizer sees an opportunity to avoid truncations; currently this has no |
| 1159 |
effect beyond ``standard`` |
| 1160 |
|
| 1161 |
The ``_Float16`` type is an interchange floating type specified in |
| 1162 |
ISO/IEC TS 18661-3:2015 ("Floating-point extensions for C"). It will |
| 1163 |
be supported on more targets as they define ABIs for it. |
| 1164 |
|
| 1165 |
The ``__bf16`` type is a non-standard extension, but it generally follows |
| 1166 |
the rules for arithmetic interchange floating types from ISO/IEC TS |
| 1167 |
18661-3:2015. In previous versions of Clang, it was a storage-only type |
| 1168 |
that forbade arithmetic operations. It will be supported on more targets |
| 1169 |
as they define ABIs for it. |
| 1170 |
|
| 1171 |
The ``__fp16`` type was originally an ARM extension and is specified |
| 1172 |
by the `ARM C Language Extensions <https://github.com/ARM-software/acle/releases>`_. |
| 1173 |
Clang uses the ``binary16`` format from IEEE 754-2008 for ``__fp16``, |
| 1174 |
not the ARM alternative format. Operators that expect arithmetic operands |
| 1175 |
immediately promote ``__fp16`` operands to ``float``. |
| 1176 |
|
| 1177 |
It is recommended that portable code use ``_Float16`` instead of ``__fp16``, |
| 1178 |
as it has been defined by the C standards committee and has behavior that is |
| 1179 |
more familiar to most programmers. |
| 1180 |
|
| 1181 |
Because ``__fp16`` operands are always immediately promoted to ``float``, the |
| 1182 |
common real type of ``__fp16`` and ``_Float16`` for the purposes of the usual |
| 1183 |
arithmetic conversions is ``float``. |
| 1184 |
|
| 1185 |
A literal can be given ``_Float16`` type using the suffix ``f16``. For example, |
| 1186 |
``3.14f16``. |
| 1187 |
|
| 1188 |
Because default argument promotion only applies to the standard floating-point |
| 1189 |
types, ``_Float16`` values are not promoted to ``double`` when passed as variadic |
| 1190 |
or untyped arguments. As a consequence, some caution must be taken when using |
| 1191 |
certain library facilities with ``_Float16``; for example, there is no ``printf`` format |
| 1192 |
specifier for ``_Float16``, and (unlike ``float``) it will not be implicitly promoted to |
| 1193 |
``double`` when passed to ``printf``, so the programmer must explicitly cast it to |
| 1194 |
``double`` before using it with an ``%f`` or similar specifier. |
| 1195 |
|
| 1196 |
Messages on ``deprecated`` and ``unavailable`` Attributes |
| 1197 |
========================================================= |
| 1198 |
|
| 1199 |
An optional string message can be added to the ``deprecated`` and |
| 1200 |
``unavailable`` attributes. For example: |
| 1201 |
|
| 1202 |
.. code-block:: c++ |
| 1203 |
|
| 1204 |
void explode(void) __attribute__((deprecated("extremely unsafe, use 'combust' instead!!!"))); |
| 1205 |
|
| 1206 |
If the deprecated or unavailable declaration is used, the message will be |
| 1207 |
incorporated into the appropriate diagnostic: |
| 1208 |
|
| 1209 |
.. code-block:: none |
| 1210 |
|
| 1211 |
harmless.c:4:3: warning: 'explode' is deprecated: extremely unsafe, use 'combust' instead!!! |
| 1212 |
[-Wdeprecated-declarations] |
| 1213 |
explode(); |
| 1214 |
^ |
| 1215 |
|
| 1216 |
Query for this feature with |
| 1217 |
``__has_extension(attribute_deprecated_with_message)`` and |
| 1218 |
``__has_extension(attribute_unavailable_with_message)``. |
| 1219 |
|
| 1220 |
Attributes on Enumerators |
| 1221 |
========================= |
| 1222 |
|
| 1223 |
Clang allows attributes to be written on individual enumerators. This allows |
| 1224 |
enumerators to be deprecated, made unavailable, etc. The attribute must appear |
| 1225 |
after the enumerator name and before any initializer, like so: |
| 1226 |
|
| 1227 |
.. code-block:: c++ |
| 1228 |
|
| 1229 |
enum OperationMode { |
| 1230 |
OM_Invalid, |
| 1231 |
OM_Normal, |
| 1232 |
OM_Terrified __attribute__((deprecated)), |
| 1233 |
OM_AbortOnError __attribute__((deprecated)) = 4 |
| 1234 |
}; |
| 1235 |
|
| 1236 |
Attributes on the ``enum`` declaration do not apply to individual enumerators. |
| 1237 |
|
| 1238 |
Query for this feature with ``__has_extension(enumerator_attributes)``. |
| 1239 |
|
| 1240 |
C++11 Attributes on using-declarations |
| 1241 |
====================================== |
| 1242 |
|
| 1243 |
Clang allows C++-style ``[[]]`` attributes to be written on using-declarations. |
| 1244 |
For instance: |
| 1245 |
|
| 1246 |
.. code-block:: c++ |
| 1247 |
|
| 1248 |
[[clang::using_if_exists]] using foo::bar; |
| 1249 |
using foo::baz [[clang::using_if_exists]]; |
| 1250 |
|
| 1251 |
You can test for support for this extension with |
| 1252 |
``__has_extension(cxx_attributes_on_using_declarations)``. |
| 1253 |
|
| 1254 |
'User-Specified' System Frameworks |
| 1255 |
================================== |
| 1256 |
|
| 1257 |
Clang provides a mechanism by which frameworks can be built in such a way that |
| 1258 |
they will always be treated as being "system frameworks", even if they are not |
| 1259 |
present in a system framework directory. This can be useful to system |
| 1260 |
framework developers who want to be able to test building other applications |
| 1261 |
with development builds of their framework, including the manner in which the |
| 1262 |
compiler changes warning behavior for system headers. |
| 1263 |
|
| 1264 |
Framework developers can opt-in to this mechanism by creating a |
| 1265 |
"``.system_framework``" file at the top-level of their framework. That is, the |
| 1266 |
framework should have contents like: |
| 1267 |
|
| 1268 |
.. code-block:: none |
| 1269 |
|
| 1270 |
.../TestFramework.framework |
| 1271 |
.../TestFramework.framework/.system_framework |
| 1272 |
.../TestFramework.framework/Headers |
| 1273 |
.../TestFramework.framework/Headers/TestFramework.h |
| 1274 |
... |
| 1275 |
|
| 1276 |
Clang will treat the presence of this file as an indicator that the framework |
| 1277 |
should be treated as a system framework, regardless of how it was found in the |
| 1278 |
framework search path. For consistency, we recommend that such files never be |
| 1279 |
included in installed versions of the framework. |
| 1280 |
|
| 1281 |
Checks for Standard Language Features |
| 1282 |
===================================== |
| 1283 |
|
| 1284 |
The ``__has_feature`` macro can be used to query if certain standard language |
| 1285 |
features are enabled. The ``__has_extension`` macro can be used to query if |
| 1286 |
language features are available as an extension when compiling for a standard |
| 1287 |
which does not provide them. The features which can be tested are listed here. |
| 1288 |
|
| 1289 |
Since Clang 3.4, the C++ SD-6 feature test macros are also supported. |
| 1290 |
These are macros with names of the form ``__cpp_<feature_name>``, and are |
| 1291 |
intended to be a portable way to query the supported features of the compiler. |
| 1292 |
See `the C++ status page <https://clang.llvm.org/cxx_status.html#ts>`_ for |
| 1293 |
information on the version of SD-6 supported by each Clang release, and the |
| 1294 |
macros provided by that revision of the recommendations. |
| 1295 |
|
| 1296 |
C++98 |
| 1297 |
----- |
| 1298 |
|
| 1299 |
The features listed below are part of the C++98 standard. These features are |
| 1300 |
enabled by default when compiling C++ code. |
| 1301 |
|
| 1302 |
C++ exceptions |
| 1303 |
^^^^^^^^^^^^^^ |
| 1304 |
|
| 1305 |
Use ``__has_feature(cxx_exceptions)`` to determine if C++ exceptions have been |
| 1306 |
enabled. For example, compiling code with ``-fno-exceptions`` disables C++ |
| 1307 |
exceptions. |
| 1308 |
|
| 1309 |
C++ RTTI |
| 1310 |
^^^^^^^^ |
| 1311 |
|
| 1312 |
Use ``__has_feature(cxx_rtti)`` to determine if C++ RTTI has been enabled. For |
| 1313 |
example, compiling code with ``-fno-rtti`` disables the use of RTTI. |
| 1314 |
|
| 1315 |
C++11 |
| 1316 |
----- |
| 1317 |
|
| 1318 |
The features listed below are part of the C++11 standard. As a result, all |
| 1319 |
these features are enabled with the ``-std=c++11`` or ``-std=gnu++11`` option |
| 1320 |
when compiling C++ code. |
| 1321 |
|
| 1322 |
C++11 SFINAE includes access control |
| 1323 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1324 |
|
| 1325 |
Use ``__has_feature(cxx_access_control_sfinae)`` or |
| 1326 |
``__has_extension(cxx_access_control_sfinae)`` to determine whether |
| 1327 |
access-control errors (e.g., calling a private constructor) are considered to |
| 1328 |
be template argument deduction errors (aka SFINAE errors), per `C++ DR1170 |
| 1329 |
<http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1170>`_. |
| 1330 |
|
| 1331 |
C++11 alias templates |
| 1332 |
^^^^^^^^^^^^^^^^^^^^^ |
| 1333 |
|
| 1334 |
Use ``__has_feature(cxx_alias_templates)`` or |
| 1335 |
``__has_extension(cxx_alias_templates)`` to determine if support for C++11's |
| 1336 |
alias declarations and alias templates is enabled. |
| 1337 |
|
| 1338 |
C++11 alignment specifiers |
| 1339 |
^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1340 |
|
| 1341 |
Use ``__has_feature(cxx_alignas)`` or ``__has_extension(cxx_alignas)`` to |
| 1342 |
determine if support for alignment specifiers using ``alignas`` is enabled. |
| 1343 |
|
| 1344 |
Use ``__has_feature(cxx_alignof)`` or ``__has_extension(cxx_alignof)`` to |
| 1345 |
determine if support for the ``alignof`` keyword is enabled. |
| 1346 |
|
| 1347 |
C++11 attributes |
| 1348 |
^^^^^^^^^^^^^^^^ |
| 1349 |
|
| 1350 |
Use ``__has_feature(cxx_attributes)`` or ``__has_extension(cxx_attributes)`` to |
| 1351 |
determine if support for attribute parsing with C++11's square bracket notation |
| 1352 |
is enabled. |
| 1353 |
|
| 1354 |
C++11 generalized constant expressions |
| 1355 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1356 |
|
| 1357 |
Use ``__has_feature(cxx_constexpr)`` to determine if support for generalized |
| 1358 |
constant expressions (e.g., ``constexpr``) is enabled. |
| 1359 |
|
| 1360 |
C++11 ``decltype()`` |
| 1361 |
^^^^^^^^^^^^^^^^^^^^ |
| 1362 |
|
| 1363 |
Use ``__has_feature(cxx_decltype)`` or ``__has_extension(cxx_decltype)`` to |
| 1364 |
determine if support for the ``decltype()`` specifier is enabled. C++11's |
| 1365 |
``decltype`` does not require type-completeness of a function call expression. |
| 1366 |
Use ``__has_feature(cxx_decltype_incomplete_return_types)`` or |
| 1367 |
``__has_extension(cxx_decltype_incomplete_return_types)`` to determine if |
| 1368 |
support for this feature is enabled. |
| 1369 |
|
| 1370 |
C++11 default template arguments in function templates |
| 1371 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1372 |
|
| 1373 |
Use ``__has_feature(cxx_default_function_template_args)`` or |
| 1374 |
``__has_extension(cxx_default_function_template_args)`` to determine if support |
| 1375 |
for default template arguments in function templates is enabled. |
| 1376 |
|
| 1377 |
C++11 ``default``\ ed functions |
| 1378 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1379 |
|
| 1380 |
Use ``__has_feature(cxx_defaulted_functions)`` or |
| 1381 |
``__has_extension(cxx_defaulted_functions)`` to determine if support for |
| 1382 |
defaulted function definitions (with ``= default``) is enabled. |
| 1383 |
|
| 1384 |
C++11 delegating constructors |
| 1385 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1386 |
|
| 1387 |
Use ``__has_feature(cxx_delegating_constructors)`` to determine if support for |
| 1388 |
delegating constructors is enabled. |
| 1389 |
|
| 1390 |
C++11 ``deleted`` functions |
| 1391 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1392 |
|
| 1393 |
Use ``__has_feature(cxx_deleted_functions)`` or |
| 1394 |
``__has_extension(cxx_deleted_functions)`` to determine if support for deleted |
| 1395 |
function definitions (with ``= delete``) is enabled. |
| 1396 |
|
| 1397 |
C++11 explicit conversion functions |
| 1398 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1399 |
|
| 1400 |
Use ``__has_feature(cxx_explicit_conversions)`` to determine if support for |
| 1401 |
``explicit`` conversion functions is enabled. |
| 1402 |
|
| 1403 |
C++11 generalized initializers |
| 1404 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1405 |
|
| 1406 |
Use ``__has_feature(cxx_generalized_initializers)`` to determine if support for |
| 1407 |
generalized initializers (using braced lists and ``std::initializer_list``) is |
| 1408 |
enabled. |
| 1409 |
|
| 1410 |
C++11 implicit move constructors/assignment operators |
| 1411 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1412 |
|
| 1413 |
Use ``__has_feature(cxx_implicit_moves)`` to determine if Clang will implicitly |
| 1414 |
generate move constructors and move assignment operators where needed. |
| 1415 |
|
| 1416 |
C++11 inheriting constructors |
| 1417 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1418 |
|
| 1419 |
Use ``__has_feature(cxx_inheriting_constructors)`` to determine if support for |
| 1420 |
inheriting constructors is enabled. |
| 1421 |
|
| 1422 |
C++11 inline namespaces |
| 1423 |
^^^^^^^^^^^^^^^^^^^^^^^ |
| 1424 |
|
| 1425 |
Use ``__has_feature(cxx_inline_namespaces)`` or |
| 1426 |
``__has_extension(cxx_inline_namespaces)`` to determine if support for inline |
| 1427 |
namespaces is enabled. |
| 1428 |
|
| 1429 |
C++11 lambdas |
| 1430 |
^^^^^^^^^^^^^ |
| 1431 |
|
| 1432 |
Use ``__has_feature(cxx_lambdas)`` or ``__has_extension(cxx_lambdas)`` to |
| 1433 |
determine if support for lambdas is enabled. |
| 1434 |
|
| 1435 |
C++11 local and unnamed types as template arguments |
| 1436 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1437 |
|
| 1438 |
Use ``__has_feature(cxx_local_type_template_args)`` or |
| 1439 |
``__has_extension(cxx_local_type_template_args)`` to determine if support for |
| 1440 |
local and unnamed types as template arguments is enabled. |
| 1441 |
|
| 1442 |
C++11 noexcept |
| 1443 |
^^^^^^^^^^^^^^ |
| 1444 |
|
| 1445 |
Use ``__has_feature(cxx_noexcept)`` or ``__has_extension(cxx_noexcept)`` to |
| 1446 |
determine if support for noexcept exception specifications is enabled. |
| 1447 |
|
| 1448 |
C++11 in-class non-static data member initialization |
| 1449 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1450 |
|
| 1451 |
Use ``__has_feature(cxx_nonstatic_member_init)`` to determine whether in-class |
| 1452 |
initialization of non-static data members is enabled. |
| 1453 |
|
| 1454 |
C++11 ``nullptr`` |
| 1455 |
^^^^^^^^^^^^^^^^^ |
| 1456 |
|
| 1457 |
Use ``__has_feature(cxx_nullptr)`` or ``__has_extension(cxx_nullptr)`` to |
| 1458 |
determine if support for ``nullptr`` is enabled. |
| 1459 |
|
| 1460 |
C++11 ``override control`` |
| 1461 |
^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1462 |
|
| 1463 |
Use ``__has_feature(cxx_override_control)`` or |
| 1464 |
``__has_extension(cxx_override_control)`` to determine if support for the |
| 1465 |
override control keywords is enabled. |
| 1466 |
|
| 1467 |
C++11 reference-qualified functions |
| 1468 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1469 |
|
| 1470 |
Use ``__has_feature(cxx_reference_qualified_functions)`` or |
| 1471 |
``__has_extension(cxx_reference_qualified_functions)`` to determine if support |
| 1472 |
for reference-qualified functions (e.g., member functions with ``&`` or ``&&`` |
| 1473 |
applied to ``*this``) is enabled. |
| 1474 |
|
| 1475 |
C++11 range-based ``for`` loop |
| 1476 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1477 |
|
| 1478 |
Use ``__has_feature(cxx_range_for)`` or ``__has_extension(cxx_range_for)`` to |
| 1479 |
determine if support for the range-based for loop is enabled. |
| 1480 |
|
| 1481 |
C++11 raw string literals |
| 1482 |
^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1483 |
|
| 1484 |
Use ``__has_feature(cxx_raw_string_literals)`` to determine if support for raw |
| 1485 |
string literals (e.g., ``R"x(foo\bar)x"``) is enabled. |
| 1486 |
|
| 1487 |
C++11 rvalue references |
| 1488 |
^^^^^^^^^^^^^^^^^^^^^^^ |
| 1489 |
|
| 1490 |
Use ``__has_feature(cxx_rvalue_references)`` or |
| 1491 |
``__has_extension(cxx_rvalue_references)`` to determine if support for rvalue |
| 1492 |
references is enabled. |
| 1493 |
|
| 1494 |
C++11 ``static_assert()`` |
| 1495 |
^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1496 |
|
| 1497 |
Use ``__has_feature(cxx_static_assert)`` or |
| 1498 |
``__has_extension(cxx_static_assert)`` to determine if support for compile-time |
| 1499 |
assertions using ``static_assert`` is enabled. |
| 1500 |
|
| 1501 |
C++11 ``thread_local`` |
| 1502 |
^^^^^^^^^^^^^^^^^^^^^^ |
| 1503 |
|
| 1504 |
Use ``__has_feature(cxx_thread_local)`` to determine if support for |
| 1505 |
``thread_local`` variables is enabled. |
| 1506 |
|
| 1507 |
C++11 type inference |
| 1508 |
^^^^^^^^^^^^^^^^^^^^ |
| 1509 |
|
| 1510 |
Use ``__has_feature(cxx_auto_type)`` or ``__has_extension(cxx_auto_type)`` to |
| 1511 |
determine C++11 type inference is supported using the ``auto`` specifier. If |
| 1512 |
this is disabled, ``auto`` will instead be a storage class specifier, as in C |
| 1513 |
or C++98. |
| 1514 |
|
| 1515 |
C++11 strongly typed enumerations |
| 1516 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1517 |
|
| 1518 |
Use ``__has_feature(cxx_strong_enums)`` or |
| 1519 |
``__has_extension(cxx_strong_enums)`` to determine if support for strongly |
| 1520 |
typed, scoped enumerations is enabled. |
| 1521 |
|
| 1522 |
C++11 trailing return type |
| 1523 |
^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1524 |
|
| 1525 |
Use ``__has_feature(cxx_trailing_return)`` or |
| 1526 |
``__has_extension(cxx_trailing_return)`` to determine if support for the |
| 1527 |
alternate function declaration syntax with trailing return type is enabled. |
| 1528 |
|
| 1529 |
C++11 Unicode string literals |
| 1530 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1531 |
|
| 1532 |
Use ``__has_feature(cxx_unicode_literals)`` to determine if support for Unicode |
| 1533 |
string literals is enabled. |
| 1534 |
|
| 1535 |
C++11 unrestricted unions |
| 1536 |
^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1537 |
|
| 1538 |
Use ``__has_feature(cxx_unrestricted_unions)`` to determine if support for |
| 1539 |
unrestricted unions is enabled. |
| 1540 |
|
| 1541 |
C++11 user-defined literals |
| 1542 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1543 |
|
| 1544 |
Use ``__has_feature(cxx_user_literals)`` to determine if support for |
| 1545 |
user-defined literals is enabled. |
| 1546 |
|
| 1547 |
C++11 variadic templates |
| 1548 |
^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1549 |
|
| 1550 |
Use ``__has_feature(cxx_variadic_templates)`` or |
| 1551 |
``__has_extension(cxx_variadic_templates)`` to determine if support for |
| 1552 |
variadic templates is enabled. |
| 1553 |
|
| 1554 |
C++14 |
| 1555 |
----- |
| 1556 |
|
| 1557 |
The features listed below are part of the C++14 standard. As a result, all |
| 1558 |
these features are enabled with the ``-std=C++14`` or ``-std=gnu++14`` option |
| 1559 |
when compiling C++ code. |
| 1560 |
|
| 1561 |
C++14 binary literals |
| 1562 |
^^^^^^^^^^^^^^^^^^^^^ |
| 1563 |
|
| 1564 |
Use ``__has_feature(cxx_binary_literals)`` or |
| 1565 |
``__has_extension(cxx_binary_literals)`` to determine whether |
| 1566 |
binary literals (for instance, ``0b10010``) are recognized. Clang supports this |
| 1567 |
feature as an extension in all language modes. |
| 1568 |
|
| 1569 |
C++14 contextual conversions |
| 1570 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1571 |
|
| 1572 |
Use ``__has_feature(cxx_contextual_conversions)`` or |
| 1573 |
``__has_extension(cxx_contextual_conversions)`` to determine if the C++14 rules |
| 1574 |
are used when performing an implicit conversion for an array bound in a |
| 1575 |
*new-expression*, the operand of a *delete-expression*, an integral constant |
| 1576 |
expression, or a condition in a ``switch`` statement. |
| 1577 |
|
| 1578 |
C++14 decltype(auto) |
| 1579 |
^^^^^^^^^^^^^^^^^^^^ |
| 1580 |
|
| 1581 |
Use ``__has_feature(cxx_decltype_auto)`` or |
| 1582 |
``__has_extension(cxx_decltype_auto)`` to determine if support |
| 1583 |
for the ``decltype(auto)`` placeholder type is enabled. |
| 1584 |
|
| 1585 |
C++14 default initializers for aggregates |
| 1586 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1587 |
|
| 1588 |
Use ``__has_feature(cxx_aggregate_nsdmi)`` or |
| 1589 |
``__has_extension(cxx_aggregate_nsdmi)`` to determine if support |
| 1590 |
for default initializers in aggregate members is enabled. |
| 1591 |
|
| 1592 |
C++14 digit separators |
| 1593 |
^^^^^^^^^^^^^^^^^^^^^^ |
| 1594 |
|
| 1595 |
Use ``__cpp_digit_separators`` to determine if support for digit separators |
| 1596 |
using single quotes (for instance, ``10'000``) is enabled. At this time, there |
| 1597 |
is no corresponding ``__has_feature`` name. |
| 1598 |
|
| 1599 |
C++14 generalized lambda capture |
| 1600 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1601 |
|
| 1602 |
Use ``__has_feature(cxx_init_captures)`` or |
| 1603 |
``__has_extension(cxx_init_captures)`` to determine if support for |
| 1604 |
lambda captures with explicit initializers is enabled |
| 1605 |
(for instance, ``[n(0)] { return ++n; }``). |
| 1606 |
|
| 1607 |
C++14 generic lambdas |
| 1608 |
^^^^^^^^^^^^^^^^^^^^^ |
| 1609 |
|
| 1610 |
Use ``__has_feature(cxx_generic_lambdas)`` or |
| 1611 |
``__has_extension(cxx_generic_lambdas)`` to determine if support for generic |
| 1612 |
(polymorphic) lambdas is enabled |
| 1613 |
(for instance, ``[] (auto x) { return x + 1; }``). |
| 1614 |
|
| 1615 |
C++14 relaxed constexpr |
| 1616 |
^^^^^^^^^^^^^^^^^^^^^^^ |
| 1617 |
|
| 1618 |
Use ``__has_feature(cxx_relaxed_constexpr)`` or |
| 1619 |
``__has_extension(cxx_relaxed_constexpr)`` to determine if variable |
| 1620 |
declarations, local variable modification, and control flow constructs |
| 1621 |
are permitted in ``constexpr`` functions. |
| 1622 |
|
| 1623 |
C++14 return type deduction |
| 1624 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1625 |
|
| 1626 |
Use ``__has_feature(cxx_return_type_deduction)`` or |
| 1627 |
``__has_extension(cxx_return_type_deduction)`` to determine if support |
| 1628 |
for return type deduction for functions (using ``auto`` as a return type) |
| 1629 |
is enabled. |
| 1630 |
|
| 1631 |
C++14 runtime-sized arrays |
| 1632 |
^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1633 |
|
| 1634 |
Use ``__has_feature(cxx_runtime_array)`` or |
| 1635 |
``__has_extension(cxx_runtime_array)`` to determine if support |
| 1636 |
for arrays of runtime bound (a restricted form of variable-length arrays) |
| 1637 |
is enabled. |
| 1638 |
Clang's implementation of this feature is incomplete. |
| 1639 |
|
| 1640 |
C++14 variable templates |
| 1641 |
^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1642 |
|
| 1643 |
Use ``__has_feature(cxx_variable_templates)`` or |
| 1644 |
``__has_extension(cxx_variable_templates)`` to determine if support for |
| 1645 |
templated variable declarations is enabled. |
| 1646 |
|
| 1647 |
C++ type aware allocators |
| 1648 |
^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1649 |
|
| 1650 |
Use ``__has_extension(cxx_type_aware_allocators)`` to determine the existence of |
| 1651 |
support for the future C++2d type aware allocator feature. For full details, see |
| 1652 |
:doc:`C++ Type Aware Allocators <CXXTypeAwareAllocators>` for additional details. |
| 1653 |
|
| 1654 |
C11 |
| 1655 |
--- |
| 1656 |
|
| 1657 |
The features listed below are part of the C11 standard. As a result, all these |
| 1658 |
features are enabled with the ``-std=c11`` or ``-std=gnu11`` option when |
| 1659 |
compiling C code. Additionally, because these features are all |
| 1660 |
backward-compatible, they are available as extensions in all language modes. |
| 1661 |
|
| 1662 |
C11 alignment specifiers |
| 1663 |
^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1664 |
|
| 1665 |
Use ``__has_feature(c_alignas)`` or ``__has_extension(c_alignas)`` to determine |
| 1666 |
if support for alignment specifiers using ``_Alignas`` is enabled. |
| 1667 |
|
| 1668 |
Use ``__has_feature(c_alignof)`` or ``__has_extension(c_alignof)`` to determine |
| 1669 |
if support for the ``_Alignof`` keyword is enabled. |
| 1670 |
|
| 1671 |
C11 atomic operations |
| 1672 |
^^^^^^^^^^^^^^^^^^^^^ |
| 1673 |
|
| 1674 |
Use ``__has_feature(c_atomic)`` or ``__has_extension(c_atomic)`` to determine |
| 1675 |
if support for atomic types using ``_Atomic`` is enabled. Clang also provides |
| 1676 |
:ref:`a set of builtins <langext-__c11_atomic>` which can be used to implement |
| 1677 |
the ``<stdatomic.h>`` operations on ``_Atomic`` types. Use |
| 1678 |
``__has_include(<stdatomic.h>)`` to determine if C11's ``<stdatomic.h>`` header |
| 1679 |
is available. |
| 1680 |
|
| 1681 |
Clang will use the system's ``<stdatomic.h>`` header when one is available, and |
| 1682 |
will otherwise use its own. When using its own, implementations of the atomic |
| 1683 |
operations are provided as macros. In the cases where C11 also requires a real |
| 1684 |
function, this header provides only the declaration of that function (along |
| 1685 |
with a shadowing macro implementation), and you must link to a library which |
| 1686 |
provides a definition of the function if you use it instead of the macro. |
| 1687 |
|
| 1688 |
C11 generic selections |
| 1689 |
^^^^^^^^^^^^^^^^^^^^^^ |
| 1690 |
|
| 1691 |
Use ``__has_feature(c_generic_selections)`` or |
| 1692 |
``__has_extension(c_generic_selections)`` to determine if support for generic |
| 1693 |
selections is enabled. |
| 1694 |
|
| 1695 |
As an extension, the C11 generic selection expression is available in all |
| 1696 |
languages supported by Clang. The syntax is the same as that given in the C11 |
| 1697 |
standard. |
| 1698 |
|
| 1699 |
In C, type compatibility is decided according to the rules given in the |
| 1700 |
appropriate standard, but in C++, which lacks the type compatibility rules used |
| 1701 |
in C, types are considered compatible only if they are equivalent. |
| 1702 |
|
| 1703 |
Clang also supports an extended form of ``_Generic`` with a controlling type |
| 1704 |
rather than a controlling expression. Unlike with a controlling expression, a |
| 1705 |
controlling type argument does not undergo any conversions and thus is suitable |
| 1706 |
for use when trying to match qualified types, incomplete types, or function |
| 1707 |
types. Variable-length array types lack the necessary compile-time information |
| 1708 |
to resolve which association they match with and thus are not allowed as a |
| 1709 |
controlling type argument. |
| 1710 |
|
| 1711 |
Use ``__has_extension(c_generic_selection_with_controlling_type)`` to determine |
| 1712 |
if support for this extension is enabled. |
| 1713 |
|
| 1714 |
C11 ``_Static_assert()`` |
| 1715 |
^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1716 |
|
| 1717 |
Use ``__has_feature(c_static_assert)`` or ``__has_extension(c_static_assert)`` |
| 1718 |
to determine if support for compile-time assertions using ``_Static_assert`` is |
| 1719 |
enabled. |
| 1720 |
|
| 1721 |
C11 ``_Thread_local`` |
| 1722 |
^^^^^^^^^^^^^^^^^^^^^ |
| 1723 |
|
| 1724 |
Use ``__has_feature(c_thread_local)`` or ``__has_extension(c_thread_local)`` |
| 1725 |
to determine if support for ``_Thread_local`` variables is enabled. |
| 1726 |
|
| 1727 |
C2y |
| 1728 |
--- |
| 1729 |
|
| 1730 |
The features listed below are part of the C2y standard. As a result, all these |
| 1731 |
features are enabled with the ``-std=c2y`` or ``-std=gnu2y`` option when |
| 1732 |
compiling C code. |
| 1733 |
|
| 1734 |
C2y ``_Countof`` |
| 1735 |
^^^^^^^^^^^^^^^^ |
| 1736 |
|
| 1737 |
Use ``__has_feature(c_countof)`` (in C2y or later mode) or |
| 1738 |
``__has_extension(c_countof)`` (in C23 or earlier mode) to determine if support |
| 1739 |
for the ``_Countof`` operator is enabled. This feature is not available in C++ |
| 1740 |
mode. |
| 1741 |
|
| 1742 |
|
| 1743 |
Modules |
| 1744 |
------- |
| 1745 |
|
| 1746 |
Use ``__has_feature(modules)`` to determine if Modules have been enabled. |
| 1747 |
For example, compiling code with ``-fmodules`` enables the use of Modules. |
| 1748 |
|
| 1749 |
More information can be found `here <https://clang.llvm.org/docs/Modules.html>`_. |
| 1750 |
|
| 1751 |
Language Extensions Back-ported to Previous Standards |
| 1752 |
===================================================== |
| 1753 |
|
| 1754 |
============================================= ================================ ============= ============= |
| 1755 |
Feature Feature Test Macro Introduced In Backported To |
| 1756 |
============================================= ================================ ============= ============= |
| 1757 |
variadic templates __cpp_variadic_templates C++11 C++03 |
| 1758 |
Alias templates __cpp_alias_templates C++11 C++03 |
| 1759 |
Non-static data member initializers __cpp_nsdmi C++11 C++03 |
| 1760 |
Range-based ``for`` loop __cpp_range_based_for C++11 C++03 |
| 1761 |
RValue references __cpp_rvalue_references C++11 C++03 |
| 1762 |
Attributes __cpp_attributes C++11 C++03 |
| 1763 |
Lambdas __cpp_lambdas C++11 C++03 |
| 1764 |
Generalized lambda captures __cpp_init_captures C++14 C++03 |
| 1765 |
Generic lambda expressions __cpp_generic_lambdas C++14 C++03 |
| 1766 |
variable templates __cpp_variable_templates C++14 C++03 |
| 1767 |
Binary literals __cpp_binary_literals C++14 C++03 |
| 1768 |
Relaxed constexpr __cpp_constexpr C++14 C++11 |
| 1769 |
Static assert with no message __cpp_static_assert >= 201411L C++17 C++11 |
| 1770 |
Pack expansion in generalized lambda-capture __cpp_init_captures C++17 C++03 |
| 1771 |
``if constexpr`` __cpp_if_constexpr C++17 C++11 |
| 1772 |
fold expressions __cpp_fold_expressions C++17 C++03 |
| 1773 |
Lambda capture of \*this by value __cpp_capture_star_this C++17 C++03 |
| 1774 |
Attributes on enums __cpp_enumerator_attributes C++17 C++03 |
| 1775 |
Guaranteed copy elision __cpp_guaranteed_copy_elision C++17 C++03 |
| 1776 |
Hexadecimal floating literals __cpp_hex_float C++17 C++03 |
| 1777 |
``inline`` variables __cpp_inline_variables C++17 C++03 |
| 1778 |
Attributes on namespaces __cpp_namespace_attributes C++17 C++11 |
| 1779 |
Structured bindings __cpp_structured_bindings C++17 C++03 |
| 1780 |
template template arguments __cpp_template_template_args C++17 C++03 |
| 1781 |
Familiar template syntax for generic lambdas __cpp_generic_lambdas C++20 C++03 |
| 1782 |
``static operator[]`` __cpp_multidimensional_subscript C++20 C++03 |
| 1783 |
Designated initializers __cpp_designated_initializers C++20 C++03 |
| 1784 |
Conditional ``explicit`` __cpp_conditional_explicit C++20 C++03 |
| 1785 |
``using enum`` __cpp_using_enum C++20 C++03 |
| 1786 |
``if consteval`` __cpp_if_consteval C++23 C++20 |
| 1787 |
``static operator()`` __cpp_static_call_operator C++23 C++03 |
| 1788 |
Attributes on Lambda-Expressions C++23 C++11 |
| 1789 |
Attributes on Structured Bindings __cpp_structured_bindings C++26 C++03 |
| 1790 |
Packs in Structured Bindings __cpp_structured_bindings C++26 C++03 |
| 1791 |
Structured binding declaration as a condition __cpp_structured_bindings C++26 C++98 |
| 1792 |
Static assert with user-generated message __cpp_static_assert >= 202306L C++26 C++11 |
| 1793 |
Pack Indexing __cpp_pack_indexing C++26 C++03 |
| 1794 |
``= delete ("should have a reason");`` __cpp_deleted_function C++26 C++03 |
| 1795 |
Variadic Friends __cpp_variadic_friend C++26 C++03 |
| 1796 |
Trivial Relocatability __cpp_trivial_relocatability C++26 C++03 |
| 1797 |
--------------------------------------------- -------------------------------- ------------- ------------- |
| 1798 |
Designated initializers (N494) C99 C89 |
| 1799 |
``_Complex`` (N693) C99 C89, C++ |
| 1800 |
``_Bool`` (N815) C99 C89 |
| 1801 |
Variable-length arrays (N683) C99 C89, C++ |
| 1802 |
Flexible array members C99 C89, C++ |
| 1803 |
static and type quals in arrays C99 C89 |
| 1804 |
``long long`` (N601) C99 C89 |
| 1805 |
Hexadecimal floating constants (N308) C99 C89 |
| 1806 |
Compound literals (N716) C99 C89, C++ |
| 1807 |
``//`` comments (N644) C99 C89 |
| 1808 |
Mixed declarations and code (N740) C99 C89 |
| 1809 |
init-statement in for (N740) C99 C89 |
| 1810 |
Variadic macros (N707) C99 C89 |
| 1811 |
Empty macro arguments (N570) C99 C89 |
| 1812 |
Trailing comma in enum declaration C99 C89 |
| 1813 |
Implicit ``return 0`` in ``main`` C99 C89 |
| 1814 |
``__func__`` (N611) C99 C89 |
| 1815 |
``_Generic`` (N1441) C11 C89, C++ |
| 1816 |
``_Static_assert`` (N1330) C11 C89, C++ |
| 1817 |
``_Atomic`` (N1485) C11 C89, C++ |
| 1818 |
``_Thread_local`` (N1364) C11 C89, C++ |
| 1819 |
Array & element qualification (N2607) C23 C89 |
| 1820 |
Attributes (N2335) C23 C89 |
| 1821 |
``#embed`` (N3017) C23 C89, C++ |
| 1822 |
Enum with fixed underlying type (N3030) C23 C89 |
| 1823 |
``#warning`` (N2686) C23 C89 |
| 1824 |
``_BitInt`` (N3035) C23 C89, C++ |
| 1825 |
Binary literals (N2549) C23 C89 |
| 1826 |
Unnamed parameters in a function definition C23 C89 |
| 1827 |
Free positioning of labels (N2508) C23 C89 |
| 1828 |
``#elifdef`` (N2645) C23 C89 |
| 1829 |
``__has_include`` (N2799) C23 C89 |
| 1830 |
Octal literals prefixed with ``0o`` or ``0O`` C2y C89, C++ |
| 1831 |
``_Countof`` (N3369, N3469) C2y C89 |
| 1832 |
``_Generic`` with a type operand (N3260) C2y C89, C++ |
| 1833 |
``++``/``--`` on ``_Complex`` value (N3259) C2y C89, C++ |
| 1834 |
``__COUNTER__`` (N3457) C2y C89, C++ |
| 1835 |
============================================= ================================ ============= ============= |
| 1836 |
|
| 1837 |
Builtin type aliases |
| 1838 |
==================== |
| 1839 |
|
| 1840 |
Clang provides a few builtin aliases to improve the throughput of certain metaprogramming facilities. |
| 1841 |
|
| 1842 |
__builtin_common_type |
| 1843 |
--------------------- |
| 1844 |
|
| 1845 |
.. code-block:: c++ |
| 1846 |
|
| 1847 |
template <template <class... Args> class BaseTemplate, |
| 1848 |
template <class TypeMember> class HasTypeMember, |
| 1849 |
class HasNoTypeMember, |
| 1850 |
class... Ts> |
| 1851 |
using __builtin_common_type = ...; |
| 1852 |
|
| 1853 |
This alias is used for implementing ``std::common_type``. If ``std::common_type`` should contain a ``type`` member, |
| 1854 |
it is an alias to ``HasTypeMember<TheCommonType>``. Otherwise it is an alias to ``HasNoTypeMember``. The |
| 1855 |
``BaseTemplate`` is usually ``std::common_type``. ``Ts`` are the arguments to ``std::common_type``. |
| 1856 |
|
| 1857 |
__type_pack_element |
| 1858 |
------------------- |
| 1859 |
|
| 1860 |
.. code-block:: c++ |
| 1861 |
|
| 1862 |
template <std::size_t Index, class... Ts> |
| 1863 |
using __type_pack_element = ...; |
| 1864 |
|
| 1865 |
This alias returns the type at ``Index`` in the parameter pack ``Ts``. |
| 1866 |
|
| 1867 |
__make_integer_seq |
| 1868 |
------------------ |
| 1869 |
|
| 1870 |
.. code-block:: c++ |
| 1871 |
|
| 1872 |
template <template <class IntSeqT, IntSeqT... Ints> class IntSeq, class T, T N> |
| 1873 |
using __make_integer_seq = ...; |
| 1874 |
|
| 1875 |
This alias returns ``IntSeq`` instantiated with ``IntSeqT = T``and ``Ints`` being the pack ``0, ..., N - 1``. |
| 1876 |
|
| 1877 |
__builtin_dedup_pack |
| 1878 |
-------------------- |
| 1879 |
|
| 1880 |
.. code-block:: c++ |
| 1881 |
|
| 1882 |
template <class... Ts> |
| 1883 |
using __builtin_dedup_pack = ...; |
| 1884 |
|
| 1885 |
This alias takes a template parameter pack ``Ts`` and produces a new unexpanded pack containing the unique types |
| 1886 |
from ``Ts``, with the order of the first occurrence of each type preserved. |
| 1887 |
It is useful in template metaprogramming to normalize type lists. |
| 1888 |
|
| 1889 |
The resulting pack can be expanded in contexts like template argument lists or base specifiers. |
| 1890 |
|
| 1891 |
**Example of Use**: |
| 1892 |
|
| 1893 |
.. code-block:: c++ |
| 1894 |
|
| 1895 |
template <typename...> struct TypeList; |
| 1896 |
|
| 1897 |
// The resulting type is TypeList<int, double, char> |
| 1898 |
template <typename ...ExtraTypes> |
| 1899 |
using MyTypeList = TypeList<__builtin_dedup_pack<int, double, int, char, double, ExtraTypes...>...>; |
| 1900 |
|
| 1901 |
**Limitations**: |
| 1902 |
|
| 1903 |
* This builtin can only be used inside a template. |
| 1904 |
* The resulting pack is currently only supported for expansion in template argument lists and base specifiers. |
| 1905 |
* This builtin cannot be assigned to a template template parameter. |
| 1906 |
|
| 1907 |
|
| 1908 |
Type Trait Primitives |
| 1909 |
===================== |
| 1910 |
|
| 1911 |
Type trait primitives are special builtin constant expressions that can be used |
| 1912 |
by the standard C++ library to facilitate or simplify the implementation of |
| 1913 |
user-facing type traits in the ``<type_traits>`` header. |
| 1914 |
|
| 1915 |
They are not intended to be used directly by user code because they are |
| 1916 |
implementation-defined and subject to change -- as such they're tied closely to |
| 1917 |
the supported set of system headers, currently: |
| 1918 |
|
| 1919 |
* LLVM's own libc++ |
| 1920 |
* GNU libstdc++ |
| 1921 |
* The Microsoft standard C++ library |
| 1922 |
|
| 1923 |
Clang supports the `GNU C++ type traits |
| 1924 |
<https://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html>`_ and a subset of the |
| 1925 |
`Microsoft Visual C++ type traits |
| 1926 |
<https://msdn.microsoft.com/en-us/library/ms177194(v=VS.100).aspx>`_, |
| 1927 |
as well as nearly all of the |
| 1928 |
`Embarcadero C++ type traits |
| 1929 |
<http://docwiki.embarcadero.com/RADStudio/Rio/en/Type_Trait_Functions_(C%2B%2B11)_Index>`_. |
| 1930 |
|
| 1931 |
The following type trait primitives are supported by Clang. Those traits marked |
| 1932 |
(C++) provide implementations for type traits specified by the C++ standard; |
| 1933 |
``__X(...)`` has the same semantics and constraints as the corresponding |
| 1934 |
``std::X_t<...>`` or ``std::X_v<...>`` type trait. |
| 1935 |
|
| 1936 |
* ``__array_rank(type)`` (Embarcadero): |
| 1937 |
Returns the number of levels of array in the type ``type``: |
| 1938 |
``0`` if ``type`` is not an array type, and |
| 1939 |
``__array_rank(element) + 1`` if ``type`` is an array of ``element``. |
| 1940 |
* ``__array_extent(type, dim)`` (Embarcadero): |
| 1941 |
The ``dim``'th array bound in the type ``type``, or ``0`` if |
| 1942 |
``dim >= __array_rank(type)``. |
| 1943 |
* ``__builtin_is_implicit_lifetime`` (C++, GNU, Microsoft) |
| 1944 |
* ``__builtin_is_virtual_base_of`` (C++, GNU, Microsoft) |
| 1945 |
* ``__can_pass_in_regs`` (C++) |
| 1946 |
Returns whether a class can be passed in registers under the current |
| 1947 |
ABI. This type can only be applied to unqualified class types. |
| 1948 |
This is not a portable type trait. |
| 1949 |
* ``__has_nothrow_assign`` (GNU, Microsoft, Embarcadero): |
| 1950 |
Deprecated, use ``__is_nothrow_assignable`` instead. |
| 1951 |
* ``__has_nothrow_move_assign`` (GNU, Microsoft): |
| 1952 |
Deprecated, use ``__is_nothrow_assignable`` instead. |
| 1953 |
* ``__has_nothrow_copy`` (GNU, Microsoft): |
| 1954 |
Deprecated, use ``__is_nothrow_constructible`` instead. |
| 1955 |
* ``__has_nothrow_constructor`` (GNU, Microsoft): |
| 1956 |
Deprecated, use ``__is_nothrow_constructible`` instead. |
| 1957 |
* ``__has_trivial_assign`` (GNU, Microsoft, Embarcadero): |
| 1958 |
Deprecated, use ``__is_trivially_assignable`` instead. |
| 1959 |
* ``__has_trivial_move_assign`` (GNU, Microsoft): |
| 1960 |
Deprecated, use ``__is_trivially_assignable`` instead. |
| 1961 |
* ``__has_trivial_copy`` (GNU, Microsoft): |
| 1962 |
Deprecated, use ``__is_trivially_copyable`` instead. |
| 1963 |
* ``__has_trivial_constructor`` (GNU, Microsoft): |
| 1964 |
Deprecated, use ``__is_trivially_constructible`` instead. |
| 1965 |
* ``__has_trivial_move_constructor`` (GNU, Microsoft): |
| 1966 |
Deprecated, use ``__is_trivially_constructible`` instead. |
| 1967 |
* ``__has_trivial_destructor`` (GNU, Microsoft, Embarcadero): |
| 1968 |
Deprecated, use ``__is_trivially_destructible`` instead. |
| 1969 |
* ``__has_unique_object_representations`` (C++, GNU) |
| 1970 |
* ``__has_virtual_destructor`` (C++, GNU, Microsoft, Embarcadero) |
| 1971 |
* ``__is_abstract`` (C++, GNU, Microsoft, Embarcadero) |
| 1972 |
* ``__is_aggregate`` (C++, GNU, Microsoft) |
| 1973 |
* ``__is_arithmetic`` (C++, Embarcadero) |
| 1974 |
* ``__is_array`` (C++, Embarcadero) |
| 1975 |
* ``__is_assignable`` (C++, MSVC 2015) |
| 1976 |
* ``__is_base_of`` (C++, GNU, Microsoft, Embarcadero) |
| 1977 |
* ``__is_bounded_array`` (C++, GNU, Microsoft, Embarcadero) |
| 1978 |
* ``__is_class`` (C++, GNU, Microsoft, Embarcadero) |
| 1979 |
* ``__is_complete_type(type)`` (Embarcadero): |
| 1980 |
Return ``true`` if ``type`` is a complete type. |
| 1981 |
Warning: this trait is dangerous because it can return different values at |
| 1982 |
different points in the same program. |
| 1983 |
* ``__is_compound`` (C++, Embarcadero) |
| 1984 |
* ``__is_const`` (C++, Embarcadero) |
| 1985 |
* ``__is_constructible`` (C++, MSVC 2013) |
| 1986 |
* ``__is_convertible`` (C++, Embarcadero) |
| 1987 |
* ``__is_nothrow_convertible`` (C++, GNU) |
| 1988 |
* ``__is_convertible_to`` (Microsoft): |
| 1989 |
Synonym for ``__is_convertible``. |
| 1990 |
* ``__is_destructible`` (C++, MSVC 2013) |
| 1991 |
* ``__is_empty`` (C++, GNU, Microsoft, Embarcadero) |
| 1992 |
* ``__is_enum`` (C++, GNU, Microsoft, Embarcadero) |
| 1993 |
* ``__is_final`` (C++, GNU, Microsoft) |
| 1994 |
* ``__is_floating_point`` (C++, Embarcadero) |
| 1995 |
* ``__is_function`` (C++, Embarcadero) |
| 1996 |
* ``__is_fundamental`` (C++, Embarcadero) |
| 1997 |
* ``__is_integral`` (C++, Embarcadero) |
| 1998 |
* ``__is_interface_class`` (Microsoft): |
| 1999 |
Returns ``false``, even for types defined with ``__interface``. |
| 2000 |
* ``__is_layout_compatible`` (C++, GNU, Microsoft) |
| 2001 |
* ``__is_literal`` (Clang): |
| 2002 |
Synonym for ``__is_literal_type``. |
| 2003 |
* ``__is_literal_type`` (C++, GNU, Microsoft): |
| 2004 |
Note, the corresponding standard trait was deprecated in C++17 |
| 2005 |
and removed in C++20. |
| 2006 |
* ``__is_lvalue_reference`` (C++, Embarcadero) |
| 2007 |
* ``__is_member_object_pointer`` (C++, Embarcadero) |
| 2008 |
* ``__is_member_function_pointer`` (C++, Embarcadero) |
| 2009 |
* ``__is_member_pointer`` (C++, Embarcadero) |
| 2010 |
* ``__is_nothrow_assignable`` (C++, MSVC 2013) |
| 2011 |
* ``__is_nothrow_constructible`` (C++, MSVC 2013) |
| 2012 |
* ``__is_nothrow_destructible`` (C++, MSVC 2013) |
| 2013 |
* ``__is_object`` (C++, Embarcadero) |
| 2014 |
* ``__is_pod`` (C++, GNU, Microsoft, Embarcadero): |
| 2015 |
Note, the corresponding standard trait was deprecated in C++20. |
| 2016 |
* ``__is_pointer`` (C++, Embarcadero) |
| 2017 |
* ``__is_pointer_interconvertible_base_of`` (C++, GNU, Microsoft) |
| 2018 |
* ``__is_polymorphic`` (C++, GNU, Microsoft, Embarcadero) |
| 2019 |
* ``__is_reference`` (C++, Embarcadero) |
| 2020 |
* ``__is_rvalue_reference`` (C++, Embarcadero) |
| 2021 |
* ``__is_same`` (C++, Embarcadero) |
| 2022 |
* ``__is_same_as`` (GCC): Synonym for ``__is_same``. |
| 2023 |
* ``__is_scalar`` (C++, Embarcadero) |
| 2024 |
* ``__is_scoped_enum`` (C++, GNU, Microsoft, Embarcadero) |
| 2025 |
* ``__is_sealed`` (Microsoft): |
| 2026 |
Synonym for ``__is_final``. |
| 2027 |
* ``__is_signed`` (C++, Embarcadero): |
| 2028 |
Returns false for enumeration types, and returns true for floating-point |
| 2029 |
types. Note, before Clang 10, returned true for enumeration types if the |
| 2030 |
underlying type was signed, and returned false for floating-point types. |
| 2031 |
* ``__is_standard_layout`` (C++, GNU, Microsoft, Embarcadero) |
| 2032 |
* ``__is_trivial`` (C++, GNU, Microsoft, Embarcadero) |
| 2033 |
* ``__is_trivially_assignable`` (C++, GNU, Microsoft) |
| 2034 |
* ``__is_trivially_constructible`` (C++, GNU, Microsoft) |
| 2035 |
* ``__is_trivially_copyable`` (C++, GNU, Microsoft) |
| 2036 |
* ``__is_trivially_destructible`` (C++, MSVC 2013) |
| 2037 |
* ``__is_trivially_relocatable`` (Clang) (Deprecated, |
| 2038 |
use ``__builtin_is_cpp_trivially_relocatable`` instead). |
| 2039 |
Returns true if moving an object |
| 2040 |
of the given type, and then destroying the source object, is known to be |
| 2041 |
functionally equivalent to copying the underlying bytes and then dropping the |
| 2042 |
source object on the floor. This is true of trivial types, |
| 2043 |
C++26 relocatable types, and types which |
| 2044 |
were made trivially relocatable via the ``clang::trivial_abi`` attribute. |
| 2045 |
This trait is deprecated and should be replaced by |
| 2046 |
``__builtin_is_cpp_trivially_relocatable``. Note, however, that it is generally |
| 2047 |
unsafe to relocate a C++-relocatable type with ``memcpy`` or ``memmove``; |
| 2048 |
use ``__builtin_trivially_relocate``. |
| 2049 |
* ``__builtin_is_cpp_trivially_relocatable`` (C++): Returns true if an object |
| 2050 |
is trivially relocatable, as defined by the C++26 standard [meta.unary.prop]. |
| 2051 |
Note that when relocating the caller code should ensure that if the object is polymorphic, |
| 2052 |
the dynamic type is of the most derived type. Padding bytes should not be copied. |
| 2053 |
* ``__is_trivially_equality_comparable`` (Clang): Returns true if comparing two |
| 2054 |
objects of the provided type is known to be equivalent to comparing their |
| 2055 |
object representations. Note that types containing padding bytes are never |
| 2056 |
trivially equality comparable. |
| 2057 |
* ``__is_unbounded_array`` (C++, GNU, Microsoft, Embarcadero) |
| 2058 |
* ``__is_union`` (C++, GNU, Microsoft, Embarcadero) |
| 2059 |
* ``__is_unsigned`` (C++, Embarcadero): |
| 2060 |
Returns false for enumeration types. Note, before Clang 13, returned true for |
| 2061 |
enumeration types if the underlying type was unsigned. |
| 2062 |
* ``__is_void`` (C++, Embarcadero) |
| 2063 |
* ``__is_volatile`` (C++, Embarcadero) |
| 2064 |
* ``__reference_binds_to_temporary(T, U)`` (Clang): Determines whether a |
| 2065 |
reference of type ``T`` bound to an expression of type ``U`` would bind to a |
| 2066 |
materialized temporary object. If ``T`` is not a reference type, the result |
| 2067 |
is false. Note this trait will also return false when the initialization of |
| 2068 |
``T`` from ``U`` is ill-formed. |
| 2069 |
Deprecated, use ``__reference_constructs_from_temporary``. |
| 2070 |
* ``__reference_constructs_from_temporary(T, U)`` (C++) |
| 2071 |
Returns true if a reference ``T`` can be direct-initialized from a temporary of type |
| 2072 |
a non-cv-qualified ``U``. |
| 2073 |
* ``__reference_converts_from_temporary(T, U)`` (C++) |
| 2074 |
Returns true if a reference ``T`` can be copy-initialized from a temporary of type |
| 2075 |
a non-cv-qualified ``U``. |
| 2076 |
* ``__underlying_type`` (C++, GNU, Microsoft) |
| 2077 |
* ``__builtin_lt_synthesizes_from_spaceship``, ``__builtin_gt_synthesizes_from_spaceship``, |
| 2078 |
``__builtin_le_synthesizes_from_spaceship``, ``__builtin_ge_synthesizes_from_spaceship`` (Clang): |
| 2079 |
These builtins can be used to determine whether the corresponding operator is synthesized from a spaceship operator. |
| 2080 |
|
| 2081 |
In addition, the following expression traits are supported: |
| 2082 |
|
| 2083 |
* ``__is_lvalue_expr(e)`` (Embarcadero): |
| 2084 |
Returns true if ``e`` is an lvalue expression. |
| 2085 |
Deprecated, use ``__is_lvalue_reference(decltype((e)))`` instead. |
| 2086 |
* ``__is_rvalue_expr(e)`` (Embarcadero): |
| 2087 |
Returns true if ``e`` is a prvalue expression. |
| 2088 |
Deprecated, use ``!__is_reference(decltype((e)))`` instead. |
| 2089 |
|
| 2090 |
There are multiple ways to detect support for a type trait ``__X`` in the |
| 2091 |
compiler, depending on the oldest version of Clang you wish to support. |
| 2092 |
|
| 2093 |
* From Clang 10 onwards, ``__has_builtin(__X)`` can be used. |
| 2094 |
* From Clang 6 onwards, ``!__is_identifier(__X)`` can be used. |
| 2095 |
* From Clang 3 onwards, ``__has_feature(X)`` can be used, but only supports |
| 2096 |
the following traits: |
| 2097 |
|
| 2098 |
* ``__has_nothrow_assign`` |
| 2099 |
* ``__has_nothrow_copy`` |
| 2100 |
* ``__has_nothrow_constructor`` |
| 2101 |
* ``__has_trivial_assign`` |
| 2102 |
* ``__has_trivial_copy`` |
| 2103 |
* ``__has_trivial_constructor`` |
| 2104 |
* ``__has_trivial_destructor`` |
| 2105 |
* ``__has_virtual_destructor`` |
| 2106 |
* ``__is_abstract`` |
| 2107 |
* ``__is_base_of`` |
| 2108 |
* ``__is_class`` |
| 2109 |
* ``__is_constructible`` |
| 2110 |
* ``__is_convertible_to`` |
| 2111 |
* ``__is_empty`` |
| 2112 |
* ``__is_enum`` |
| 2113 |
* ``__is_final`` |
| 2114 |
* ``__is_literal`` |
| 2115 |
* ``__is_standard_layout`` |
| 2116 |
* ``__is_pod`` |
| 2117 |
* ``__is_polymorphic`` |
| 2118 |
* ``__is_sealed`` |
| 2119 |
* ``__is_trivial`` |
| 2120 |
* ``__is_trivially_assignable`` |
| 2121 |
* ``__is_trivially_constructible`` |
| 2122 |
* ``__is_trivially_copyable`` |
| 2123 |
* ``__is_union`` |
| 2124 |
* ``__underlying_type`` |
| 2125 |
|
| 2126 |
A simplistic usage example as might be seen in standard C++ headers follows: |
| 2127 |
|
| 2128 |
.. code-block:: c++ |
| 2129 |
|
| 2130 |
#if __has_builtin(__is_convertible_to) |
| 2131 |
template<typename From, typename To> |
| 2132 |
struct is_convertible_to { |
| 2133 |
static const bool value = __is_convertible_to(From, To); |
| 2134 |
}; |
| 2135 |
#else |
| 2136 |
// Emulate type trait for compatibility with other compilers. |
| 2137 |
#endif |
| 2138 |
|
| 2139 |
|
| 2140 |
.. _builtin_structured_binding_size-doc: |
| 2141 |
|
| 2142 |
__builtin_structured_binding_size (C++) |
| 2143 |
--------------------------------------- |
| 2144 |
|
| 2145 |
The ``__builtin_structured_binding_size(T)`` type trait returns |
| 2146 |
the *structured binding size* ([dcl.struct.bind]) of type ``T`` |
| 2147 |
|
| 2148 |
This is equivalent to the size of the pack ``p`` in ``auto&& [...p] = declval<T&>();``. |
| 2149 |
If the argument cannot be decomposed, ``__builtin_structured_binding_size(T)`` |
| 2150 |
is not a valid expression (``__builtin_structured_binding_size`` is SFINAE-friendly). |
| 2151 |
|
| 2152 |
builtin arrays, builtin SIMD vectors, |
| 2153 |
builtin complex types, *tuple-like* types, and decomposable class types |
| 2154 |
are decomposable types. |
| 2155 |
|
| 2156 |
A type is considered a valid *tuple-like* if ``std::tuple_size_v<T>`` is a valid expression, |
| 2157 |
even if there is no valid ``std::tuple_element`` specialization or suitable |
| 2158 |
``get`` function for that type. |
| 2159 |
|
| 2160 |
.. code-block:: c++ |
| 2161 |
|
| 2162 |
template<std::size_t Idx, typename T> |
| 2163 |
requires (Idx < __builtin_structured_binding_size(T)) |
| 2164 |
decltype(auto) constexpr get_binding(T&& obj) { |
| 2165 |
auto && [...p] = std::forward<T>(obj); |
| 2166 |
return p...[Idx]; |
| 2167 |
} |
| 2168 |
struct S { int a = 0, b = 42; }; |
| 2169 |
static_assert(__builtin_structured_binding_size(S) == 2); |
| 2170 |
static_assert(get_binding<1>(S{}) == 42); |
| 2171 |
|
| 2172 |
|
| 2173 |
Blocks |
| 2174 |
====== |
| 2175 |
|
| 2176 |
The syntax and high-level language feature description is in |
| 2177 |
:doc:`BlockLanguageSpec<BlockLanguageSpec>`. Implementation and ABI details for |
| 2178 |
the clang implementation are in :doc:`Block-ABI-Apple<Block-ABI-Apple>`. |
| 2179 |
|
| 2180 |
Query for this feature with ``__has_extension(blocks)``. |
| 2181 |
|
| 2182 |
ASM Goto with Output Constraints |
| 2183 |
================================ |
| 2184 |
|
| 2185 |
Outputs may be used along any branches from the ``asm goto`` whether the |
| 2186 |
branches are taken or not. |
| 2187 |
|
| 2188 |
Query for this feature with ``__has_extension(gnu_asm_goto_with_outputs)``. |
| 2189 |
|
| 2190 |
Prior to clang-16, the output may only be used safely when the indirect |
| 2191 |
branches are not taken. Query for this difference with |
| 2192 |
``__has_extension(gnu_asm_goto_with_outputs_full)``. |
| 2193 |
|
| 2194 |
When using tied-outputs (i.e., outputs that are inputs and outputs, not just |
| 2195 |
outputs) with the `+r` constraint, there is a hidden input that's created |
| 2196 |
before the label, so numeric references to operands must account for that. |
| 2197 |
|
| 2198 |
.. code-block:: c++ |
| 2199 |
|
| 2200 |
int foo(int x) { |
| 2201 |
// %0 and %1 both refer to x |
| 2202 |
// %l2 refers to err |
| 2203 |
asm goto("# %0 %1 %l2" : "+r"(x) : : : err); |
| 2204 |
return x; |
| 2205 |
err: |
| 2206 |
return -1; |
| 2207 |
} |
| 2208 |
|
| 2209 |
This was changed to match GCC in clang-13; for better portability, symbolic |
| 2210 |
references can be used instead of numeric references. |
| 2211 |
|
| 2212 |
.. code-block:: c++ |
| 2213 |
|
| 2214 |
int foo(int x) { |
| 2215 |
asm goto("# %[x] %l[err]" : [x]"+r"(x) : : : err); |
| 2216 |
return x; |
| 2217 |
err: |
| 2218 |
return -1; |
| 2219 |
} |
| 2220 |
|
| 2221 |
ASM Goto versus Branch Target Enforcement |
| 2222 |
========================================= |
| 2223 |
|
| 2224 |
Some target architectures implement branch target enforcement, by requiring |
| 2225 |
indirect (register-controlled) branch instructions to jump only to locations |
| 2226 |
marked by a special instruction (such as AArch64 ``bti``). |
| 2227 |
|
| 2228 |
The assembler code inside an ``asm goto`` statement is expected not to use a |
| 2229 |
branch instruction of that kind to transfer control to any of its destination |
| 2230 |
labels. Therefore, using a label in an ``asm goto`` statement does not cause |
| 2231 |
clang to put a ``bti`` or equivalent instruction at the label. |
| 2232 |
|
| 2233 |
Constexpr strings in GNU ASM statements |
| 2234 |
======================================= |
| 2235 |
|
| 2236 |
In C++11 mode (and greater), Clang supports specifying the template, |
| 2237 |
constraints, and clobber strings with a parenthesized constant expression |
| 2238 |
producing an object with the following member functions |
| 2239 |
|
| 2240 |
.. code-block:: c++ |
| 2241 |
|
| 2242 |
constexpr const char* data() const; |
| 2243 |
constexpr size_t size() const; |
| 2244 |
|
| 2245 |
such as ``std::string``, ``std::string_view``, ``std::vector<char>``. |
| 2246 |
This mechanism follows the same rules as ``static_assert`` messages in |
| 2247 |
C++26, see ``[dcl.pre]/p12``. |
| 2248 |
|
| 2249 |
Query for this feature with ``__has_extension(gnu_asm_constexpr_strings)``. |
| 2250 |
|
| 2251 |
.. code-block:: c++ |
| 2252 |
|
| 2253 |
int foo() { |
| 2254 |
asm((std::string_view("nop")) ::: (std::string_view("memory"))); |
| 2255 |
} |
| 2256 |
|
| 2257 |
|
| 2258 |
Objective-C Features |
| 2259 |
==================== |
| 2260 |
|
| 2261 |
Related result types |
| 2262 |
-------------------- |
| 2263 |
|
| 2264 |
According to Cocoa conventions, Objective-C methods with certain names |
| 2265 |
("``init``", "``alloc``", etc.) always return objects that are an instance of |
| 2266 |
the receiving class's type. Such methods are said to have a "related result |
| 2267 |
type", meaning that a message send to one of these methods will have the same |
| 2268 |
static type as an instance of the receiver class. For example, given the |
| 2269 |
following classes: |
| 2270 |
|
| 2271 |
.. code-block:: objc |
| 2272 |
|
| 2273 |
@interface NSObject |
| 2274 |
+ (id)alloc; |
| 2275 |
- (id)init; |
| 2276 |
@end |
| 2277 |
|
| 2278 |
@interface NSArray : NSObject |
| 2279 |
@end |
| 2280 |
|
| 2281 |
and this common initialization pattern |
| 2282 |
|
| 2283 |
.. code-block:: objc |
| 2284 |
|
| 2285 |
NSArray *array = [[NSArray alloc] init]; |
| 2286 |
|
| 2287 |
the type of the expression ``[NSArray alloc]`` is ``NSArray*`` because |
| 2288 |
``alloc`` implicitly has a related result type. Similarly, the type of the |
| 2289 |
expression ``[[NSArray alloc] init]`` is ``NSArray*``, since ``init`` has a |
| 2290 |
related result type and its receiver is known to have the type ``NSArray *``. |
| 2291 |
If neither ``alloc`` nor ``init`` had a related result type, the expressions |
| 2292 |
would have had type ``id``, as declared in the method signature. |
| 2293 |
|
| 2294 |
A method with a related result type can be declared by using the type |
| 2295 |
``instancetype`` as its result type. ``instancetype`` is a contextual keyword |
| 2296 |
that is only permitted in the result type of an Objective-C method, e.g. |
| 2297 |
|
| 2298 |
.. code-block:: objc |
| 2299 |
|
| 2300 |
@interface A |
| 2301 |
+ (instancetype)constructAnA; |
| 2302 |
@end |
| 2303 |
|
| 2304 |
The related result type can also be inferred for some methods. To determine |
| 2305 |
whether a method has an inferred related result type, the first word in the |
| 2306 |
camel-case selector (e.g., "``init``" in "``initWithObjects``") is considered, |
| 2307 |
and the method will have a related result type if its return type is compatible |
| 2308 |
with the type of its class and if: |
| 2309 |
|
| 2310 |
* the first word is "``alloc``" or "``new``", and the method is a class method, |
| 2311 |
or |
| 2312 |
|
| 2313 |
* the first word is "``autorelease``", "``init``", "``retain``", or "``self``", |
| 2314 |
and the method is an instance method. |
| 2315 |
|
| 2316 |
If a method with a related result type is overridden by a subclass method, the |
| 2317 |
subclass method must also return a type that is compatible with the subclass |
| 2318 |
type. For example: |
| 2319 |
|
| 2320 |
.. code-block:: objc |
| 2321 |
|
| 2322 |
@interface NSString : NSObject |
| 2323 |
- (NSUnrelated *)init; // incorrect usage: NSUnrelated is not NSString or a superclass of NSString |
| 2324 |
@end |
| 2325 |
|
| 2326 |
Related result types only affect the type of a message send or property access |
| 2327 |
via the given method. In all other respects, a method with a related result |
| 2328 |
type is treated the same way as method that returns ``id``. |
| 2329 |
|
| 2330 |
Use ``__has_feature(objc_instancetype)`` to determine whether the |
| 2331 |
``instancetype`` contextual keyword is available. |
| 2332 |
|
| 2333 |
Automatic reference counting |
| 2334 |
---------------------------- |
| 2335 |
|
| 2336 |
Clang provides support for :doc:`automated reference counting |
| 2337 |
<AutomaticReferenceCounting>` in Objective-C, which eliminates the need |
| 2338 |
for manual ``retain``/``release``/``autorelease`` message sends. There are three |
| 2339 |
feature macros associated with automatic reference counting: |
| 2340 |
``__has_feature(objc_arc)`` indicates the availability of automated reference |
| 2341 |
counting in general, while ``__has_feature(objc_arc_weak)`` indicates that |
| 2342 |
automated reference counting also includes support for ``__weak`` pointers to |
| 2343 |
Objective-C objects. ``__has_feature(objc_arc_fields)`` indicates that C structs |
| 2344 |
are allowed to have fields that are pointers to Objective-C objects managed by |
| 2345 |
automatic reference counting. |
| 2346 |
|
| 2347 |
.. _objc-weak: |
| 2348 |
|
| 2349 |
Weak references |
| 2350 |
--------------- |
| 2351 |
|
| 2352 |
Clang supports ARC-style weak and unsafe references in Objective-C even |
| 2353 |
outside of ARC mode. Weak references must be explicitly enabled with |
| 2354 |
the ``-fobjc-weak`` option; use ``__has_feature((objc_arc_weak))`` |
| 2355 |
to test whether they are enabled. Unsafe references are enabled |
| 2356 |
unconditionally. ARC-style weak and unsafe references cannot be used |
| 2357 |
when Objective-C garbage collection is enabled. |
| 2358 |
|
| 2359 |
Except as noted below, the language rules for the ``__weak`` and |
| 2360 |
``__unsafe_unretained`` qualifiers (and the ``weak`` and |
| 2361 |
``unsafe_unretained`` property attributes) are just as laid out |
| 2362 |
in the :doc:`ARC specification <AutomaticReferenceCounting>`. |
| 2363 |
In particular, note that some classes do not support forming weak |
| 2364 |
references to their instances, and note that special care must be |
| 2365 |
taken when storing weak references in memory where initialization |
| 2366 |
and deinitialization are outside the responsibility of the compiler |
| 2367 |
(such as in ``malloc``-ed memory). |
| 2368 |
|
| 2369 |
Loading from a ``__weak`` variable always implicitly retains the |
| 2370 |
loaded value. In non-ARC modes, this retain is normally balanced |
| 2371 |
by an implicit autorelease. This autorelease can be suppressed |
| 2372 |
by performing the load in the receiver position of a ``-retain`` |
| 2373 |
message send (e.g., ``[weakReference retain]``); note that this performs |
| 2374 |
only a single retain (the retain done when primitively loading from |
| 2375 |
the weak reference). |
| 2376 |
|
| 2377 |
For the most part, ``__unsafe_unretained`` in non-ARC modes is just the |
| 2378 |
default behavior of variables and therefore is not needed. However, |
| 2379 |
it does have an effect on the semantics of block captures: normally, |
| 2380 |
copying a block which captures an Objective-C object or block pointer |
| 2381 |
causes the captured pointer to be retained or copied, respectively, |
| 2382 |
but that behavior is suppressed when the captured variable is qualified |
| 2383 |
with ``__unsafe_unretained``. |
| 2384 |
|
| 2385 |
Note that the ``__weak`` qualifier formerly meant the GC qualifier in |
| 2386 |
all non-ARC modes and was silently ignored outside of GC modes. It now |
| 2387 |
means the ARC-style qualifier in all non-GC modes and is no longer |
| 2388 |
allowed if not enabled by either ``-fobjc-arc`` or ``-fobjc-weak``. |
| 2389 |
It is expected that ``-fobjc-weak`` will eventually be enabled by default |
| 2390 |
in all non-GC Objective-C modes. |
| 2391 |
|
| 2392 |
.. _objc-fixed-enum: |
| 2393 |
|
| 2394 |
Enumerations with a fixed underlying type |
| 2395 |
----------------------------------------- |
| 2396 |
|
| 2397 |
Clang provides support for C++11 enumerations with a fixed underlying type |
| 2398 |
within Objective-C and C `prior to C23 <https://open-std.org/JTC1/SC22/WG14/www/docs/n3030.htm>`_. For example, one can write an enumeration type as: |
| 2399 |
|
| 2400 |
.. code-block:: c++ |
| 2401 |
|
| 2402 |
typedef enum : unsigned char { Red, Green, Blue } Color; |
| 2403 |
|
| 2404 |
This specifies that the underlying type, which is used to store the enumeration |
| 2405 |
value, is ``unsigned char``. |
| 2406 |
|
| 2407 |
Use ``__has_feature(objc_fixed_enum)`` to determine whether support for fixed |
| 2408 |
underlying types is available in Objective-C. |
| 2409 |
|
| 2410 |
Use ``__has_extension(c_fixed_enum)`` to determine whether support for fixed |
| 2411 |
underlying types is available in C prior to C23. This will also report ``true`` in C23 |
| 2412 |
and later modes as the functionality is available even if it's not an extension in |
| 2413 |
those modes. |
| 2414 |
|
| 2415 |
Use ``__has_feature(c_fixed_enum)`` to determine whether support for fixed |
| 2416 |
underlying types is available in C23 and later. |
| 2417 |
|
| 2418 |
Enumerations with no enumerators |
| 2419 |
-------------------------------- |
| 2420 |
|
| 2421 |
Clang provides support for Microsoft extensions to support enumerations with no enumerators. |
| 2422 |
|
| 2423 |
.. code-block:: c++ |
| 2424 |
|
| 2425 |
typedef enum empty { } A; |
| 2426 |
|
| 2427 |
|
| 2428 |
Interoperability with C++11 lambdas |
| 2429 |
----------------------------------- |
| 2430 |
|
| 2431 |
Clang provides interoperability between C++11 lambdas and blocks-based APIs, by |
| 2432 |
permitting a lambda to be implicitly converted to a block pointer with the |
| 2433 |
corresponding signature. For example, consider an API such as ``NSArray``'s |
| 2434 |
array-sorting method: |
| 2435 |
|
| 2436 |
.. code-block:: objc |
| 2437 |
|
| 2438 |
- (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr; |
| 2439 |
|
| 2440 |
``NSComparator`` is simply a typedef for the block pointer ``NSComparisonResult |
| 2441 |
(^)(id, id)``, and parameters of this type are generally provided with block |
| 2442 |
literals as arguments. However, one can also use a C++11 lambda so long as it |
| 2443 |
provides the same signature (in this case, accepting two parameters of type |
| 2444 |
``id`` and returning an ``NSComparisonResult``): |
| 2445 |
|
| 2446 |
.. code-block:: objc |
| 2447 |
|
| 2448 |
NSArray *array = @[@"string 1", @"string 21", @"string 12", @"String 11", |
| 2449 |
@"String 02"]; |
| 2450 |
const NSStringCompareOptions comparisonOptions |
| 2451 |
= NSCaseInsensitiveSearch | NSNumericSearch | |
| 2452 |
NSWidthInsensitiveSearch | NSForcedOrderingSearch; |
| 2453 |
NSLocale *currentLocale = [NSLocale currentLocale]; |
| 2454 |
NSArray *sorted |
| 2455 |
= [array sortedArrayUsingComparator:[=](id s1, id s2) -> NSComparisonResult { |
| 2456 |
NSRange string1Range = NSMakeRange(0, [s1 length]); |
| 2457 |
return [s1 compare:s2 options:comparisonOptions |
| 2458 |
range:string1Range locale:currentLocale]; |
| 2459 |
}]; |
| 2460 |
NSLog(@"sorted: %@", sorted); |
| 2461 |
|
| 2462 |
This code relies on an implicit conversion from the type of the lambda |
| 2463 |
expression (an unnamed, local class type called the *closure type*) to the |
| 2464 |
corresponding block pointer type. The conversion itself is expressed by a |
| 2465 |
conversion operator in that closure type that produces a block pointer with the |
| 2466 |
same signature as the lambda itself, e.g., |
| 2467 |
|
| 2468 |
.. code-block:: objc |
| 2469 |
|
| 2470 |
operator NSComparisonResult (^)(id, id)() const; |
| 2471 |
|
| 2472 |
This conversion function returns a new block that simply forwards the two |
| 2473 |
parameters to the lambda object (which it captures by copy), then returns the |
| 2474 |
result. The returned block is first copied (with ``Block_copy``) and then |
| 2475 |
autoreleased. As an optimization, if a lambda expression is immediately |
| 2476 |
converted to a block pointer (as in the first example, above), then the block |
| 2477 |
is not copied and autoreleased: rather, it is given the same lifetime as a |
| 2478 |
block literal written at that point in the program, which avoids the overhead |
| 2479 |
of copying a block to the heap in the common case. |
| 2480 |
|
| 2481 |
The conversion from a lambda to a block pointer is only available in |
| 2482 |
Objective-C++, and not in C++ with blocks, due to its use of Objective-C memory |
| 2483 |
management (autorelease). |
| 2484 |
|
| 2485 |
Object Literals and Subscripting |
| 2486 |
-------------------------------- |
| 2487 |
|
| 2488 |
Clang provides support for :doc:`Object Literals and Subscripting |
| 2489 |
<ObjectiveCLiterals>` in Objective-C, which simplifies common Objective-C |
| 2490 |
programming patterns, makes programs more concise, and improves the safety of |
| 2491 |
container creation. There are several feature macros associated with object |
| 2492 |
literals and subscripting: ``__has_feature(objc_array_literals)`` tests the |
| 2493 |
availability of array literals; ``__has_feature(objc_dictionary_literals)`` |
| 2494 |
tests the availability of dictionary literals; |
| 2495 |
``__has_feature(objc_subscripting)`` tests the availability of object |
| 2496 |
subscripting. |
| 2497 |
|
| 2498 |
Objective-C Autosynthesis of Properties |
| 2499 |
--------------------------------------- |
| 2500 |
|
| 2501 |
Clang provides support for autosynthesis of declared properties. Using this |
| 2502 |
feature, clang provides default synthesis of those properties not declared |
| 2503 |
@dynamic and not having user-provided backing getter and setter methods. |
| 2504 |
``__has_feature(objc_default_synthesize_properties)`` checks for availability |
| 2505 |
of this feature in version of clang being used. |
| 2506 |
|
| 2507 |
.. _langext-objc-retain-release: |
| 2508 |
|
| 2509 |
Objective-C retaining behavior attributes |
| 2510 |
----------------------------------------- |
| 2511 |
|
| 2512 |
In Objective-C, functions and methods are generally assumed to follow the |
| 2513 |
`Cocoa Memory Management |
| 2514 |
<https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html>`_ |
| 2515 |
conventions for ownership of object arguments and |
| 2516 |
return values. However, there are exceptions, and so Clang provides attributes |
| 2517 |
to allow these exceptions to be documented. These are used by ARC and the |
| 2518 |
`static analyzer <https://clang-analyzer.llvm.org>`_ Some exceptions may be |
| 2519 |
better described using the ``objc_method_family`` attribute instead. |
| 2520 |
|
| 2521 |
**Usage**: The ``ns_returns_retained``, ``ns_returns_not_retained``, |
| 2522 |
``ns_returns_autoreleased``, ``cf_returns_retained``, and |
| 2523 |
``cf_returns_not_retained`` attributes can be placed on methods and functions |
| 2524 |
that return Objective-C or CoreFoundation objects. They are commonly placed at |
| 2525 |
the end of a function prototype or method declaration: |
| 2526 |
|
| 2527 |
.. code-block:: objc |
| 2528 |
|
| 2529 |
id foo() __attribute__((ns_returns_retained)); |
| 2530 |
|
| 2531 |
- (NSString *)bar:(int)x __attribute__((ns_returns_retained)); |
| 2532 |
|
| 2533 |
The ``*_returns_retained`` attributes specify that the returned object has a +1 |
| 2534 |
retain count. The ``*_returns_not_retained`` attributes specify that the return |
| 2535 |
object has a +0 retain count, even if the normal convention for its selector |
| 2536 |
would be +1. ``ns_returns_autoreleased`` specifies that the returned object is |
| 2537 |
+0, but is guaranteed to live at least as long as the next flush of an |
| 2538 |
autorelease pool. |
| 2539 |
|
| 2540 |
**Usage**: The ``ns_consumed`` and ``cf_consumed`` attributes can be placed on |
| 2541 |
a parameter declaration; they specify that the argument is expected to have a |
| 2542 |
+1 retain count, which will be balanced in some way by the function or method. |
| 2543 |
The ``ns_consumes_self`` attribute can only be placed on an Objective-C |
| 2544 |
method; it specifies that the method expects its ``self`` parameter to have a |
| 2545 |
+1 retain count, which it will balance in some way. |
| 2546 |
|
| 2547 |
.. code-block:: objc |
| 2548 |
|
| 2549 |
void foo(__attribute__((ns_consumed)) NSString *string); |
| 2550 |
|
| 2551 |
- (void) bar __attribute__((ns_consumes_self)); |
| 2552 |
- (void) baz:(id) __attribute__((ns_consumed)) x; |
| 2553 |
|
| 2554 |
Further examples of these attributes are available in the static analyzer's |
| 2555 |
`list of annotations for analysis <analyzer/user-docs/Annotations.html#cocoa-mem>`__. |
| 2556 |
|
| 2557 |
Query for these features with ``__has_attribute(ns_consumed)``, |
| 2558 |
``__has_attribute(ns_returns_retained)``, etc. |
| 2559 |
|
| 2560 |
Objective-C @available |
| 2561 |
---------------------- |
| 2562 |
|
| 2563 |
It is possible to use the newest SDK but still build a program that can run on |
| 2564 |
older versions of macOS and iOS by passing ``-mmacos-version-min=`` / |
| 2565 |
``-miphoneos-version-min=``. |
| 2566 |
|
| 2567 |
Before LLVM 5.0, when calling a function that exists only in the OS that's |
| 2568 |
newer than the target OS (as determined by the minimum deployment version), |
| 2569 |
programmers had to carefully check if the function exists at runtime, using |
| 2570 |
null checks for weakly-linked C functions, ``+class`` for Objective-C classes, |
| 2571 |
and ``-respondsToSelector:`` or ``+instancesRespondToSelector:`` for |
| 2572 |
Objective-C methods. If such a check was missed, the program would compile |
| 2573 |
fine, run fine on newer systems, but crash on older systems. |
| 2574 |
|
| 2575 |
As of LLVM 5.0, ``-Wunguarded-availability`` uses the `availability attributes |
| 2576 |
<https://clang.llvm.org/docs/AttributeReference.html#availability>`_ together |
| 2577 |
with the new ``@available()`` keyword to assist with this issue. |
| 2578 |
When a method that's introduced in the OS newer than the target OS is called, a |
| 2579 |
-Wunguarded-availability warning is emitted if that call is not guarded: |
| 2580 |
|
| 2581 |
.. code-block:: objc |
| 2582 |
|
| 2583 |
void my_fun(NSSomeClass* var) { |
| 2584 |
// If fancyNewMethod was added in e.g., macOS 10.12, but the code is |
| 2585 |
// built with -mmacos-version-min=10.11, then this unconditional call |
| 2586 |
// will emit a -Wunguarded-availability warning: |
| 2587 |
[var fancyNewMethod]; |
| 2588 |
} |
| 2589 |
|
| 2590 |
To fix the warning and to avoid the crash on macOS 10.11, wrap it in |
| 2591 |
``if(@available())``: |
| 2592 |
|
| 2593 |
.. code-block:: objc |
| 2594 |
|
| 2595 |
void my_fun(NSSomeClass* var) { |
| 2596 |
if (@available(macOS 10.12, *)) { |
| 2597 |
[var fancyNewMethod]; |
| 2598 |
} else { |
| 2599 |
// Put fallback behavior for old macOS versions (and for non-mac |
| 2600 |
// platforms) here. |
| 2601 |
} |
| 2602 |
} |
| 2603 |
|
| 2604 |
The ``*`` is required and means that platforms not explicitly listed will take |
| 2605 |
the true branch, and the compiler will emit ``-Wunguarded-availability`` |
| 2606 |
warnings for unlisted platforms based on those platform's deployment target. |
| 2607 |
More than one platform can be listed in ``@available()``: |
| 2608 |
|
| 2609 |
.. code-block:: objc |
| 2610 |
|
| 2611 |
void my_fun(NSSomeClass* var) { |
| 2612 |
if (@available(macOS 10.12, iOS 10, *)) { |
| 2613 |
[var fancyNewMethod]; |
| 2614 |
} |
| 2615 |
} |
| 2616 |
|
| 2617 |
If the caller of ``my_fun()`` already checks that ``my_fun()`` is only called |
| 2618 |
on 10.12, then add an `availability attribute |
| 2619 |
<https://clang.llvm.org/docs/AttributeReference.html#availability>`_ to it, |
| 2620 |
which will also suppress the warning and require that calls to my_fun() are |
| 2621 |
checked: |
| 2622 |
|
| 2623 |
.. code-block:: objc |
| 2624 |
|
| 2625 |
API_AVAILABLE(macos(10.12)) void my_fun(NSSomeClass* var) { |
| 2626 |
[var fancyNewMethod]; // Now ok. |
| 2627 |
} |
| 2628 |
|
| 2629 |
``@available()`` is only available in Objective-C code. To use the feature |
| 2630 |
in C and C++ code, use the ``__builtin_available()`` spelling instead. |
| 2631 |
|
| 2632 |
If existing code uses null checks or ``-respondsToSelector:``, it should |
| 2633 |
be changed to use ``@available()`` (or ``__builtin_available``) instead. |
| 2634 |
|
| 2635 |
``-Wunguarded-availability`` is disabled by default, but |
| 2636 |
``-Wunguarded-availability-new``, which only emits this warning for APIs |
| 2637 |
that have been introduced in macOS >= 10.13, iOS >= 11, watchOS >= 4 and |
| 2638 |
tvOS >= 11, is enabled by default. |
| 2639 |
|
| 2640 |
.. _langext-overloading: |
| 2641 |
|
| 2642 |
Objective-C++ ABI: protocol-qualifier mangling of parameters |
| 2643 |
------------------------------------------------------------ |
| 2644 |
|
| 2645 |
Starting with LLVM 3.4, Clang produces a new mangling for parameters whose |
| 2646 |
type is a qualified-``id`` (e.g., ``id<Foo>``). This mangling allows such |
| 2647 |
parameters to be differentiated from those with the regular unqualified ``id`` |
| 2648 |
type. |
| 2649 |
|
| 2650 |
This was a non-backward compatible mangling change to the ABI. This change |
| 2651 |
allows proper overloading, and also prevents mangling conflicts with template |
| 2652 |
parameters of protocol-qualified type. |
| 2653 |
|
| 2654 |
Query the presence of this new mangling with |
| 2655 |
``__has_feature(objc_protocol_qualifier_mangling)``. |
| 2656 |
|
| 2657 |
Initializer lists for complex numbers in C |
| 2658 |
========================================== |
| 2659 |
|
| 2660 |
clang supports an extension which allows the following in C: |
| 2661 |
|
| 2662 |
.. code-block:: c++ |
| 2663 |
|
| 2664 |
#include <math.h> |
| 2665 |
#include <complex.h> |
| 2666 |
complex float x = { 1.0f, INFINITY }; // Init to (1, Inf) |
| 2667 |
|
| 2668 |
This construct is useful because there is no way to separately initialize the |
| 2669 |
real and imaginary parts of a complex variable in standard C, given that clang |
| 2670 |
does not support ``_Imaginary``. (Clang also supports the ``__real__`` and |
| 2671 |
``__imag__`` extensions from gcc, which help in some cases, but are not usable |
| 2672 |
in static initializers.) |
| 2673 |
|
| 2674 |
Note that this extension does not allow eliding the braces; the meaning of the |
| 2675 |
following two lines is different: |
| 2676 |
|
| 2677 |
.. code-block:: c++ |
| 2678 |
|
| 2679 |
complex float x[] = { { 1.0f, 1.0f } }; // [0] = (1, 1) |
| 2680 |
complex float x[] = { 1.0f, 1.0f }; // [0] = (1, 0), [1] = (1, 0) |
| 2681 |
|
| 2682 |
This extension also works in C++ mode, as far as that goes, but does not apply |
| 2683 |
to the C++ ``std::complex``. (In C++11, list initialization allows the same |
| 2684 |
syntax to be used with ``std::complex`` with the same meaning.) |
| 2685 |
|
| 2686 |
For GCC compatibility, ``__builtin_complex(re, im)`` can also be used to |
| 2687 |
construct a complex number from the given real and imaginary components. |
| 2688 |
|
| 2689 |
OpenCL Features |
| 2690 |
=============== |
| 2691 |
|
| 2692 |
Clang supports internal OpenCL extensions documented below. |
| 2693 |
|
| 2694 |
``__cl_clang_bitfields`` |
| 2695 |
-------------------------------- |
| 2696 |
|
| 2697 |
With this extension it is possible to enable bitfields in structs |
| 2698 |
or unions using the OpenCL extension pragma mechanism detailed in |
| 2699 |
`the OpenCL Extension Specification, section 1.2 |
| 2700 |
<https://www.khronos.org/registry/OpenCL/specs/3.0-unified/html/OpenCL_Ext.html#extensions-overview>`_. |
| 2701 |
|
| 2702 |
Use of bitfields in OpenCL kernels can result in reduced portability as struct |
| 2703 |
layout is not guaranteed to be consistent when compiled by different compilers. |
| 2704 |
If structs with bitfields are used as kernel function parameters, it can result |
| 2705 |
in incorrect functionality when the layout is different between the host and |
| 2706 |
device code. |
| 2707 |
|
| 2708 |
**Example of Use**: |
| 2709 |
|
| 2710 |
.. code-block:: c++ |
| 2711 |
|
| 2712 |
#pragma OPENCL EXTENSION __cl_clang_bitfields : enable |
| 2713 |
struct with_bitfield { |
| 2714 |
unsigned int i : 5; // compiled - no diagnostic generated |
| 2715 |
}; |
| 2716 |
|
| 2717 |
#pragma OPENCL EXTENSION __cl_clang_bitfields : disable |
| 2718 |
struct without_bitfield { |
| 2719 |
unsigned int i : 5; // error - bitfields are not supported |
| 2720 |
}; |
| 2721 |
|
| 2722 |
``__cl_clang_function_pointers`` |
| 2723 |
-------------------------------- |
| 2724 |
|
| 2725 |
With this extension it is possible to enable various language features that |
| 2726 |
are relying on function pointers using regular OpenCL extension pragma |
| 2727 |
mechanism detailed in `the OpenCL Extension Specification, |
| 2728 |
section 1.2 |
| 2729 |
<https://www.khronos.org/registry/OpenCL/specs/3.0-unified/html/OpenCL_Ext.html#extensions-overview>`_. |
| 2730 |
|
| 2731 |
In C++ for OpenCL this also enables: |
| 2732 |
|
| 2733 |
- Use of member function pointers; |
| 2734 |
|
| 2735 |
- Unrestricted use of references to functions; |
| 2736 |
|
| 2737 |
- Virtual member functions. |
| 2738 |
|
| 2739 |
Such functionality is not conformant and does not guarantee to compile |
| 2740 |
correctly in any circumstances. It can be used if: |
| 2741 |
|
| 2742 |
- the kernel source does not contain call expressions to (member-) function |
| 2743 |
pointers, or virtual functions. For example, this extension can be used in |
| 2744 |
metaprogramming algorithms to be able to specify/detect types generically. |
| 2745 |
|
| 2746 |
- the generated kernel binary does not contain indirect calls because they |
| 2747 |
are eliminated using compiler optimizations e.g., devirtualization. |
| 2748 |
|
| 2749 |
- the selected target supports the function pointer like functionality e.g. |
| 2750 |
most CPU targets. |
| 2751 |
|
| 2752 |
**Example of Use**: |
| 2753 |
|
| 2754 |
.. code-block:: c++ |
| 2755 |
|
| 2756 |
#pragma OPENCL EXTENSION __cl_clang_function_pointers : enable |
| 2757 |
void foo() |
| 2758 |
{ |
| 2759 |
void (*fp)(); // compiled - no diagnostic generated |
| 2760 |
} |
| 2761 |
|
| 2762 |
#pragma OPENCL EXTENSION __cl_clang_function_pointers : disable |
| 2763 |
void bar() |
| 2764 |
{ |
| 2765 |
void (*fp)(); // error - pointers to function are not allowed |
| 2766 |
} |
| 2767 |
|
| 2768 |
``__cl_clang_variadic_functions`` |
| 2769 |
--------------------------------- |
| 2770 |
|
| 2771 |
With this extension it is possible to enable variadic arguments in functions |
| 2772 |
using regular OpenCL extension pragma mechanism detailed in `the OpenCL |
| 2773 |
Extension Specification, section 1.2 |
| 2774 |
<https://www.khronos.org/registry/OpenCL/specs/3.0-unified/html/OpenCL_Ext.html#extensions-overview>`_. |
| 2775 |
|
| 2776 |
This is not conformant behavior and it can only be used portably when the |
| 2777 |
functions with variadic prototypes do not get generated in binary e.g., the |
| 2778 |
variadic prototype is used to specify a function type with any number of |
| 2779 |
arguments in metaprogramming algorithms in C++ for OpenCL. |
| 2780 |
|
| 2781 |
This extension can also be used when the kernel code is intended for targets |
| 2782 |
supporting the variadic arguments e.g., majority of CPU targets. |
| 2783 |
|
| 2784 |
**Example of Use**: |
| 2785 |
|
| 2786 |
.. code-block:: c++ |
| 2787 |
|
| 2788 |
#pragma OPENCL EXTENSION __cl_clang_variadic_functions : enable |
| 2789 |
void foo(int a, ...); // compiled - no diagnostic generated |
| 2790 |
|
| 2791 |
#pragma OPENCL EXTENSION __cl_clang_variadic_functions : disable |
| 2792 |
void bar(int a, ...); // error - variadic prototype is not allowed |
| 2793 |
|
| 2794 |
``__cl_clang_non_portable_kernel_param_types`` |
| 2795 |
---------------------------------------------- |
| 2796 |
|
| 2797 |
With this extension it is possible to enable the use of some restricted types |
| 2798 |
in kernel parameters specified in `C++ for OpenCL v1.0 s2.4 |
| 2799 |
<https://www.khronos.org/opencl/assets/CXX_for_OpenCL.html#kernel_function>`_. |
| 2800 |
The restrictions can be relaxed using regular OpenCL extension pragma mechanism |
| 2801 |
detailed in `the OpenCL Extension Specification, section 1.2 |
| 2802 |
<https://www.khronos.org/registry/OpenCL/specs/3.0-unified/html/OpenCL_Ext.html#extensions-overview>`_. |
| 2803 |
|
| 2804 |
This is not a conformant behavior and it can only be used when the |
| 2805 |
kernel arguments are not accessed on the host side or the data layout/size |
| 2806 |
between the host and device is known to be compatible. |
| 2807 |
|
| 2808 |
**Example of Use**: |
| 2809 |
|
| 2810 |
.. code-block:: c++ |
| 2811 |
|
| 2812 |
// Plain Old Data type. |
| 2813 |
struct Pod { |
| 2814 |
int a; |
| 2815 |
int b; |
| 2816 |
}; |
| 2817 |
|
| 2818 |
// Not POD type because of the constructor. |
| 2819 |
// Standard layout type because there is only one access control. |
| 2820 |
struct OnlySL { |
| 2821 |
int a; |
| 2822 |
int b; |
| 2823 |
OnlySL() : a(0), b(0) {} |
| 2824 |
}; |
| 2825 |
|
| 2826 |
// Not standard layout type because of two different access controls. |
| 2827 |
struct NotSL { |
| 2828 |
int a; |
| 2829 |
private: |
| 2830 |
int b; |
| 2831 |
}; |
| 2832 |
|
| 2833 |
#pragma OPENCL EXTENSION __cl_clang_non_portable_kernel_param_types : enable |
| 2834 |
kernel void kernel_main( |
| 2835 |
Pod a, |
| 2836 |
|
| 2837 |
OnlySL b, |
| 2838 |
global NotSL *c, |
| 2839 |
global OnlySL *d |
| 2840 |
); |
| 2841 |
#pragma OPENCL EXTENSION __cl_clang_non_portable_kernel_param_types : disable |
| 2842 |
|
| 2843 |
Remove address space builtin function |
| 2844 |
------------------------------------- |
| 2845 |
|
| 2846 |
``__remove_address_space`` allows to derive types in C++ for OpenCL |
| 2847 |
that have address space qualifiers removed. This utility only affects |
| 2848 |
address space qualifiers, therefore, other type qualifiers such as |
| 2849 |
``const`` or ``volatile`` remain unchanged. |
| 2850 |
|
| 2851 |
**Example of Use**: |
| 2852 |
|
| 2853 |
.. code-block:: c++ |
| 2854 |
|
| 2855 |
template<typename T> |
| 2856 |
void foo(T *par){ |
| 2857 |
T var1; // error - local function variable with global address space |
| 2858 |
__private T var2; // error - conflicting address space qualifiers |
| 2859 |
__private __remove_address_space<T>::type var3; // var3 is __private int |
| 2860 |
} |
| 2861 |
|
| 2862 |
void bar(){ |
| 2863 |
__global int* ptr; |
| 2864 |
foo(ptr); |
| 2865 |
} |
| 2866 |
|
| 2867 |
Legacy 1.x atomics with generic address space |
| 2868 |
--------------------------------------------- |
| 2869 |
|
| 2870 |
Clang allows the use of atomic functions from the OpenCL 1.x standards |
| 2871 |
with the generic address space pointer in C++ for OpenCL mode. |
| 2872 |
|
| 2873 |
This is a non-portable feature and might not be supported by all |
| 2874 |
targets. |
| 2875 |
|
| 2876 |
**Example of Use**: |
| 2877 |
|
| 2878 |
.. code-block:: c++ |
| 2879 |
|
| 2880 |
void foo(__generic volatile unsigned int* a) { |
| 2881 |
atomic_add(a, 1); |
| 2882 |
} |
| 2883 |
|
| 2884 |
WebAssembly Features |
| 2885 |
==================== |
| 2886 |
|
| 2887 |
Clang supports the WebAssembly features documented below. For further |
| 2888 |
information related to the semantics of the builtins, please refer to the `WebAssembly Specification <https://webassembly.github.io/spec/core/>`_. |
| 2889 |
In this section, when we refer to reference types, we are referring to |
| 2890 |
WebAssembly reference types, not C++ reference types unless stated |
| 2891 |
otherwise. |
| 2892 |
|
| 2893 |
``__builtin_wasm_table_set`` |
| 2894 |
---------------------------- |
| 2895 |
|
| 2896 |
This builtin function stores a value in a WebAssembly table. |
| 2897 |
It takes three arguments. |
| 2898 |
The first argument is the table to store a value into, the second |
| 2899 |
argument is the index to which to store the value into, and the |
| 2900 |
third argument is a value of reference type to store in the table. |
| 2901 |
It returns nothing. |
| 2902 |
|
| 2903 |
.. code-block:: c++ |
| 2904 |
|
| 2905 |
static __externref_t table[0]; |
| 2906 |
extern __externref_t JSObj; |
| 2907 |
|
| 2908 |
void store(int index) { |
| 2909 |
__builtin_wasm_table_set(table, index, JSObj); |
| 2910 |
} |
| 2911 |
|
| 2912 |
``__builtin_wasm_table_get`` |
| 2913 |
---------------------------- |
| 2914 |
|
| 2915 |
This builtin function is the counterpart to ``__builtin_wasm_table_set`` |
| 2916 |
and loads a value from a WebAssembly table of reference typed values. |
| 2917 |
It takes 2 arguments. |
| 2918 |
The first argument is a table of reference typed values and the |
| 2919 |
second argument is an index from which to load the value. It returns |
| 2920 |
the loaded reference typed value. |
| 2921 |
|
| 2922 |
.. code-block:: c++ |
| 2923 |
|
| 2924 |
static __externref_t table[0]; |
| 2925 |
|
| 2926 |
__externref_t load(int index) { |
| 2927 |
__externref_t Obj = __builtin_wasm_table_get(table, index); |
| 2928 |
return Obj; |
| 2929 |
} |
| 2930 |
|
| 2931 |
``__builtin_wasm_table_size`` |
| 2932 |
----------------------------- |
| 2933 |
|
| 2934 |
This builtin function returns the size of the WebAssembly table. |
| 2935 |
Takes the table as an argument and returns an unsigned integer (``size_t``) |
| 2936 |
with the current table size. |
| 2937 |
|
| 2938 |
.. code-block:: c++ |
| 2939 |
|
| 2940 |
typedef void (*__funcref funcref_t)(); |
| 2941 |
static funcref_t table[0]; |
| 2942 |
|
| 2943 |
size_t getSize() { |
| 2944 |
return __builtin_wasm_table_size(table); |
| 2945 |
} |
| 2946 |
|
| 2947 |
``__builtin_wasm_table_grow`` |
| 2948 |
----------------------------- |
| 2949 |
|
| 2950 |
This builtin function grows the WebAssembly table by a certain amount. |
| 2951 |
Currently, as all WebAssembly tables created in C/C++ are zero-sized, |
| 2952 |
this always needs to be called to grow the table. |
| 2953 |
|
| 2954 |
It takes three arguments. The first argument is the WebAssembly table |
| 2955 |
to grow. The second argument is the reference typed value to store in |
| 2956 |
the new table entries (the initialization value), and the third argument |
| 2957 |
is the amount to grow the table by. It returns the previous table size |
| 2958 |
or -1. It will return -1 if not enough space could be allocated. |
| 2959 |
|
| 2960 |
.. code-block:: c++ |
| 2961 |
|
| 2962 |
typedef void (*__funcref funcref_t)(); |
| 2963 |
static funcref_t table[0]; |
| 2964 |
|
| 2965 |
// grow returns the new table size or -1 on error. |
| 2966 |
int grow(funcref_t fn, int delta) { |
| 2967 |
int prevSize = __builtin_wasm_table_grow(table, fn, delta); |
| 2968 |
if (prevSize == -1) |
| 2969 |
return -1; |
| 2970 |
return prevSize + delta; |
| 2971 |
} |
| 2972 |
|
| 2973 |
``__builtin_wasm_table_fill`` |
| 2974 |
----------------------------- |
| 2975 |
|
| 2976 |
This builtin function sets all the entries of a WebAssembly table to a given |
| 2977 |
reference typed value. It takes four arguments. The first argument is |
| 2978 |
the WebAssembly table, the second argument is the index that starts the |
| 2979 |
range, the third argument is the value to set in the new entries, and |
| 2980 |
the fourth and the last argument is the size of the range. It returns |
| 2981 |
nothing. |
| 2982 |
|
| 2983 |
.. code-block:: c++ |
| 2984 |
|
| 2985 |
static __externref_t table[0]; |
| 2986 |
|
| 2987 |
// resets a table by setting all of its entries to a given value. |
| 2988 |
void reset(__externref_t Obj) { |
| 2989 |
int Size = __builtin_wasm_table_size(table); |
| 2990 |
__builtin_wasm_table_fill(table, 0, Obj, Size); |
| 2991 |
} |
| 2992 |
|
| 2993 |
``__builtin_wasm_table_copy`` |
| 2994 |
----------------------------- |
| 2995 |
|
| 2996 |
This builtin function copies elements from a source WebAssembly table |
| 2997 |
to a possibly overlapping destination region. It takes five arguments. |
| 2998 |
The first argument is the destination WebAssembly table, and the second |
| 2999 |
argument is the source WebAssembly table. The third argument is the |
| 3000 |
destination index from where the copy starts, the fourth argument is the |
| 3001 |
source index from where the copy starts, and the fifth and last argument |
| 3002 |
is the number of elements to copy. It returns nothing. |
| 3003 |
|
| 3004 |
.. code-block:: c++ |
| 3005 |
|
| 3006 |
static __externref_t tableSrc[0]; |
| 3007 |
static __externref_t tableDst[0]; |
| 3008 |
|
| 3009 |
// Copy nelem elements from [src, src + nelem - 1] in tableSrc to |
| 3010 |
// [dst, dst + nelem - 1] in tableDst |
| 3011 |
void copy(int dst, int src, int nelem) { |
| 3012 |
__builtin_wasm_table_copy(tableDst, tableSrc, dst, src, nelem); |
| 3013 |
} |
| 3014 |
|
| 3015 |
|
| 3016 |
Builtin Functions |
| 3017 |
================= |
| 3018 |
|
| 3019 |
Clang supports a number of builtin library functions with the same syntax as |
| 3020 |
GCC, including things like ``__builtin_nan``, ``__builtin_constant_p``, |
| 3021 |
``__builtin_choose_expr``, ``__builtin_types_compatible_p``, |
| 3022 |
``__builtin_assume_aligned``, ``__sync_fetch_and_add``, etc. In addition to |
| 3023 |
the GCC builtins, Clang supports a number of builtins that GCC does not, which |
| 3024 |
are listed here. |
| 3025 |
|
| 3026 |
Please note that Clang does not and will not support all of the GCC builtins |
| 3027 |
for vector operations. Instead of using builtins, you should use the functions |
| 3028 |
defined in target-specific header files like ``<xmmintrin.h>``, which define |
| 3029 |
portable wrappers for these. Many of the Clang versions of these functions are |
| 3030 |
implemented directly in terms of :ref:`extended vector support |
| 3031 |
<langext-vectors>` instead of builtins, in order to reduce the number of |
| 3032 |
builtins that we need to implement. |
| 3033 |
|
| 3034 |
``__builtin_alloca`` |
| 3035 |
-------------------- |
| 3036 |
|
| 3037 |
``__builtin_alloca`` is used to dynamically allocate memory on the stack. Memory |
| 3038 |
is automatically freed upon function termination. |
| 3039 |
|
| 3040 |
**Syntax**: |
| 3041 |
|
| 3042 |
.. code-block:: c++ |
| 3043 |
|
| 3044 |
__builtin_alloca(size_t n) |
| 3045 |
|
| 3046 |
**Example of Use**: |
| 3047 |
|
| 3048 |
.. code-block:: c++ |
| 3049 |
|
| 3050 |
void init(float* data, size_t nbelems); |
| 3051 |
void process(float* data, size_t nbelems); |
| 3052 |
int foo(size_t n) { |
| 3053 |
auto mem = (float*)__builtin_alloca(n * sizeof(float)); |
| 3054 |
init(mem, n); |
| 3055 |
process(mem, n); |
| 3056 |
/* mem is automatically freed at this point */ |
| 3057 |
} |
| 3058 |
|
| 3059 |
**Description**: |
| 3060 |
|
| 3061 |
``__builtin_alloca`` is meant to be used to allocate a dynamic amount of memory |
| 3062 |
on the stack. This amount is subject to stack allocation limits. |
| 3063 |
|
| 3064 |
Query for this feature with ``__has_builtin(__builtin_alloca)``. |
| 3065 |
|
| 3066 |
``__builtin_alloca_with_align`` |
| 3067 |
------------------------------- |
| 3068 |
|
| 3069 |
``__builtin_alloca_with_align`` is used to dynamically allocate memory on the |
| 3070 |
stack while controlling its alignment. Memory is automatically freed upon |
| 3071 |
function termination. |
| 3072 |
|
| 3073 |
|
| 3074 |
**Syntax**: |
| 3075 |
|
| 3076 |
.. code-block:: c++ |
| 3077 |
|
| 3078 |
__builtin_alloca_with_align(size_t n, size_t align) |
| 3079 |
|
| 3080 |
**Example of Use**: |
| 3081 |
|
| 3082 |
.. code-block:: c++ |
| 3083 |
|
| 3084 |
void init(float* data, size_t nbelems); |
| 3085 |
void process(float* data, size_t nbelems); |
| 3086 |
int foo(size_t n) { |
| 3087 |
auto mem = (float*)__builtin_alloca_with_align( |
| 3088 |
n * sizeof(float), |
| 3089 |
CHAR_BIT * alignof(float)); |
| 3090 |
init(mem, n); |
| 3091 |
process(mem, n); |
| 3092 |
/* mem is automatically freed at this point */ |
| 3093 |
} |
| 3094 |
|
| 3095 |
**Description**: |
| 3096 |
|
| 3097 |
``__builtin_alloca_with_align`` is meant to be used to allocate a dynamic amount of memory |
| 3098 |
on the stack. It is similar to ``__builtin_alloca`` but accepts a second |
| 3099 |
argument whose value is the alignment constraint, as a power of 2 in *bits*. |
| 3100 |
|
| 3101 |
Query for this feature with ``__has_builtin(__builtin_alloca_with_align)``. |
| 3102 |
|
| 3103 |
.. _langext-__builtin_assume: |
| 3104 |
|
| 3105 |
``__builtin_assume`` |
| 3106 |
-------------------- |
| 3107 |
|
| 3108 |
``__builtin_assume`` is used to provide the optimizer with a boolean |
| 3109 |
invariant that is defined to be true. |
| 3110 |
|
| 3111 |
**Syntax**: |
| 3112 |
|
| 3113 |
.. code-block:: c++ |
| 3114 |
|
| 3115 |
__builtin_assume(bool) |
| 3116 |
|
| 3117 |
**Example of Use**: |
| 3118 |
|
| 3119 |
.. code-block:: c++ |
| 3120 |
|
| 3121 |
int foo(int x) { |
| 3122 |
__builtin_assume(x != 0); |
| 3123 |
// The optimizer may short-circuit this check using the invariant. |
| 3124 |
if (x == 0) |
| 3125 |
return do_something(); |
| 3126 |
return do_something_else(); |
| 3127 |
} |
| 3128 |
|
| 3129 |
**Description**: |
| 3130 |
|
| 3131 |
The boolean argument to this function is defined to be true. The optimizer may |
| 3132 |
analyze the form of the expression provided as the argument and deduce from |
| 3133 |
that information used to optimize the program. If the condition is violated |
| 3134 |
during execution, the behavior is undefined. The argument itself is never |
| 3135 |
evaluated, so any side effects of the expression will be discarded. |
| 3136 |
|
| 3137 |
Query for this feature with ``__has_builtin(__builtin_assume)``. |
| 3138 |
|
| 3139 |
.. _langext-__builtin_assume_separate_storage: |
| 3140 |
|
| 3141 |
``__builtin_assume_separate_storage`` |
| 3142 |
------------------------------------- |
| 3143 |
|
| 3144 |
``__builtin_assume_separate_storage`` is used to provide the optimizer with the |
| 3145 |
knowledge that its two arguments point to separately allocated objects. |
| 3146 |
|
| 3147 |
**Syntax**: |
| 3148 |
|
| 3149 |
.. code-block:: c++ |
| 3150 |
|
| 3151 |
__builtin_assume_separate_storage(const volatile void *, const volatile void *) |
| 3152 |
|
| 3153 |
**Example of Use**: |
| 3154 |
|
| 3155 |
.. code-block:: c++ |
| 3156 |
|
| 3157 |
int foo(int *x, int *y) { |
| 3158 |
__builtin_assume_separate_storage(x, y); |
| 3159 |
*x = 0; |
| 3160 |
*y = 1; |
| 3161 |
// The optimizer may optimize this to return 0 without reloading from *x. |
| 3162 |
return *x; |
| 3163 |
} |
| 3164 |
|
| 3165 |
**Description**: |
| 3166 |
|
| 3167 |
The arguments to this function are assumed to point into separately allocated |
| 3168 |
storage (either different variable definitions or different dynamic storage |
| 3169 |
allocations). The optimizer may use this fact to aid in alias analysis. If the |
| 3170 |
arguments point into the same storage, the behavior is undefined. Note that the |
| 3171 |
definition of "storage" here refers to the outermost enclosing allocation of any |
| 3172 |
particular object (so for example, it's never correct to call this function |
| 3173 |
passing the addresses of fields in the same struct, elements of the same array, |
| 3174 |
etc.). |
| 3175 |
|
| 3176 |
Query for this feature with ``__has_builtin(__builtin_assume_separate_storage)``. |
| 3177 |
|
| 3178 |
``__builtin_assume_dereferenceable`` |
| 3179 |
------------------------------------- |
| 3180 |
|
| 3181 |
``__builtin_assume_dereferenceable`` is used to provide the optimizer with the |
| 3182 |
knowledge that the pointer argument P is dereferenceable up to at least the |
| 3183 |
specified number of bytes. |
| 3184 |
|
| 3185 |
**Syntax**: |
| 3186 |
|
| 3187 |
.. code-block:: c++ |
| 3188 |
|
| 3189 |
__builtin_assume_dereferenceable(const void *, size_t) |
| 3190 |
|
| 3191 |
**Example of Use**: |
| 3192 |
|
| 3193 |
.. code-block:: c++ |
| 3194 |
|
| 3195 |
int foo(int *x, int y) { |
| 3196 |
__builtin_assume_dereferenceable(x, sizeof(int)); |
| 3197 |
int z = 0; |
| 3198 |
if (y == 1) { |
| 3199 |
// The optimizer may execute the load of x unconditionally due to |
| 3200 |
// __builtin_assume_dereferenceable guaranteeing sizeof(int) bytes can |
| 3201 |
// be loaded speculatively without trapping. |
| 3202 |
z = *x; |
| 3203 |
} |
| 3204 |
return z; |
| 3205 |
} |
| 3206 |
|
| 3207 |
**Description**: |
| 3208 |
|
| 3209 |
The arguments to this function provide a start pointer ``P`` and a size ``S``. |
| 3210 |
``S`` must be at least 1 and a constant. The optimizer may assume that ``S`` |
| 3211 |
bytes are dereferenceable starting at ``P``. Note that this does not necessarily |
| 3212 |
imply that ``P`` is non-null as ``nullptr`` can be dereferenced in some cases. |
| 3213 |
The assumption also does not imply that ``P`` is not dereferenceable past ``S`` |
| 3214 |
bytes. |
| 3215 |
|
| 3216 |
|
| 3217 |
Query for this feature with ``__has_builtin(__builtin_assume_dereferenceable)``. |
| 3218 |
|
| 3219 |
|
| 3220 |
``__builtin_offsetof`` |
| 3221 |
---------------------- |
| 3222 |
|
| 3223 |
``__builtin_offsetof`` is used to implement the ``offsetof`` macro, which |
| 3224 |
calculates the offset (in bytes) to a given member of the given type. |
| 3225 |
|
| 3226 |
**Syntax**: |
| 3227 |
|
| 3228 |
.. code-block:: c++ |
| 3229 |
|
| 3230 |
__builtin_offsetof(type-name, member-designator) |
| 3231 |
|
| 3232 |
**Example of Use**: |
| 3233 |
|
| 3234 |
.. code-block:: c++ |
| 3235 |
|
| 3236 |
struct S { |
| 3237 |
char c; |
| 3238 |
int i; |
| 3239 |
struct T { |
| 3240 |
float f[2]; |
| 3241 |
} t; |
| 3242 |
}; |
| 3243 |
|
| 3244 |
const int offset_to_i = __builtin_offsetof(struct S, i); |
| 3245 |
const int ext1 = __builtin_offsetof(struct U { int i; }, i); // C extension |
| 3246 |
const int offset_to_subobject = __builtin_offsetof(struct S, t.f[1]); |
| 3247 |
|
| 3248 |
**Description**: |
| 3249 |
|
| 3250 |
This builtin is usable in an integer constant expression which returns a value |
| 3251 |
of type ``size_t``. The value returned is the offset in bytes to the subobject |
| 3252 |
designated by the member-designator from the beginning of an object of type |
| 3253 |
``type-name``. Clang extends the required standard functionality in the |
| 3254 |
following way: |
| 3255 |
|
| 3256 |
* In C language modes, the first argument may be the definition of a new type. |
| 3257 |
Any type declared this way is scoped to the nearest scope containing the call |
| 3258 |
to the builtin. |
| 3259 |
|
| 3260 |
Query for this feature with ``__has_builtin(__builtin_offsetof)``. |
| 3261 |
|
| 3262 |
``__builtin_get_vtable_pointer`` |
| 3263 |
-------------------------------- |
| 3264 |
|
| 3265 |
``__builtin_get_vtable_pointer`` loads and authenticates the primary vtable |
| 3266 |
pointer from an instance of a polymorphic C++ class. This builtin is needed |
| 3267 |
for directly loading the vtable pointer when on platforms using |
| 3268 |
:doc:`PointerAuthentication`. |
| 3269 |
|
| 3270 |
**Syntax**: |
| 3271 |
|
| 3272 |
.. code-block:: c++ |
| 3273 |
|
| 3274 |
__builtin_get_vtable_pointer(PolymorphicClass*) |
| 3275 |
|
| 3276 |
**Example of Use**: |
| 3277 |
|
| 3278 |
.. code-block:: c++ |
| 3279 |
|
| 3280 |
struct PolymorphicClass { |
| 3281 |
virtual ~PolymorphicClass(); |
| 3282 |
}; |
| 3283 |
|
| 3284 |
PolymorphicClass anInstance; |
| 3285 |
const void* vtablePointer = __builtin_get_vtable_pointer(&anInstance); |
| 3286 |
|
| 3287 |
**Description**: |
| 3288 |
|
| 3289 |
The ``__builtin_get_vtable_pointer`` builtin loads the primary vtable |
| 3290 |
pointer from a polymorphic C++ type. If the target platform authenticates |
| 3291 |
vtable pointers, this builtin will perform the authentication and produce |
| 3292 |
the underlying raw pointer. The object being queried must be polymorphic, |
| 3293 |
and so must also be a complete type. |
| 3294 |
|
| 3295 |
Query for this feature with ``__has_builtin(__builtin_get_vtable_pointer)``. |
| 3296 |
|
| 3297 |
``__builtin_call_with_static_chain`` |
| 3298 |
------------------------------------ |
| 3299 |
|
| 3300 |
``__builtin_call_with_static_chain`` is used to perform a static call while |
| 3301 |
updating the static chain register. |
| 3302 |
|
| 3303 |
**Syntax**: |
| 3304 |
|
| 3305 |
.. code-block:: c++ |
| 3306 |
|
| 3307 |
T __builtin_call_with_static_chain(T expr, void* ptr) |
| 3308 |
|
| 3309 |
**Example of Use**: |
| 3310 |
|
| 3311 |
.. code-block:: c++ |
| 3312 |
|
| 3313 |
auto v = __builtin_call_with_static_chain(foo(3), foo); |
| 3314 |
|
| 3315 |
**Description**: |
| 3316 |
|
| 3317 |
This builtin returns ``expr`` after checking that ``expr`` is a non-member |
| 3318 |
static call expression. The call to that expression is made while using ``ptr`` |
| 3319 |
as a function pointer stored in a dedicated register to implement *static chain* |
| 3320 |
calling convention, as used by some language to implement closures or nested |
| 3321 |
functions. |
| 3322 |
|
| 3323 |
Query for this feature with ``__has_builtin(__builtin_call_with_static_chain)``. |
| 3324 |
|
| 3325 |
``__builtin_readcyclecounter`` |
| 3326 |
------------------------------ |
| 3327 |
|
| 3328 |
``__builtin_readcyclecounter`` is used to access the cycle counter register (or |
| 3329 |
a similar low-latency, high-accuracy clock) on those targets that support it. |
| 3330 |
|
| 3331 |
**Syntax**: |
| 3332 |
|
| 3333 |
.. code-block:: c++ |
| 3334 |
|
| 3335 |
__builtin_readcyclecounter() |
| 3336 |
|
| 3337 |
**Example of Use**: |
| 3338 |
|
| 3339 |
.. code-block:: c++ |
| 3340 |
|
| 3341 |
unsigned long long t0 = __builtin_readcyclecounter(); |
| 3342 |
do_something(); |
| 3343 |
unsigned long long t1 = __builtin_readcyclecounter(); |
| 3344 |
unsigned long long cycles_to_do_something = t1 - t0; // assuming no overflow |
| 3345 |
|
| 3346 |
**Description**: |
| 3347 |
|
| 3348 |
The ``__builtin_readcyclecounter()`` builtin returns the cycle counter value, |
| 3349 |
which may be either global or process/thread-specific depending on the target. |
| 3350 |
As the backing counters often overflow quickly (on the order of seconds) this |
| 3351 |
should only be used for timing small intervals. When not supported by the |
| 3352 |
target, the return value is always zero. This builtin takes no arguments and |
| 3353 |
produces an unsigned long long result. |
| 3354 |
|
| 3355 |
Query for this feature with ``__has_builtin(__builtin_readcyclecounter)``. Note |
| 3356 |
that even if present, its use may depend on run-time privilege or other OS |
| 3357 |
controlled state. |
| 3358 |
|
| 3359 |
``__builtin_readsteadycounter`` |
| 3360 |
------------------------------- |
| 3361 |
|
| 3362 |
``__builtin_readsteadycounter`` is used to access the fixed frequency counter |
| 3363 |
register (or a similar steady-rate clock) on those targets that support it. |
| 3364 |
The function is similar to ``__builtin_readcyclecounter`` above except that the |
| 3365 |
frequency is fixed, making it suitable for measuring elapsed time. |
| 3366 |
|
| 3367 |
**Syntax**: |
| 3368 |
|
| 3369 |
.. code-block:: c++ |
| 3370 |
|
| 3371 |
__builtin_readsteadycounter() |
| 3372 |
|
| 3373 |
**Example of Use**: |
| 3374 |
|
| 3375 |
.. code-block:: c++ |
| 3376 |
|
| 3377 |
unsigned long long t0 = __builtin_readsteadycounter(); |
| 3378 |
do_something(); |
| 3379 |
unsigned long long t1 = __builtin_readsteadycounter(); |
| 3380 |
unsigned long long secs_to_do_something = (t1 - t0) / tick_rate; |
| 3381 |
|
| 3382 |
**Description**: |
| 3383 |
|
| 3384 |
The ``__builtin_readsteadycounter()`` builtin returns the frequency counter value. |
| 3385 |
When not supported by the target, the return value is always zero. This builtin |
| 3386 |
takes no arguments and produces an unsigned long long result. The builtin does |
| 3387 |
not guarantee any particular frequency, only that it is stable. Knowledge of the |
| 3388 |
counter's true frequency will need to be provided by the user. |
| 3389 |
|
| 3390 |
Query for this feature with ``__has_builtin(__builtin_readsteadycounter)``. |
| 3391 |
|
| 3392 |
``__builtin_cpu_supports`` |
| 3393 |
-------------------------- |
| 3394 |
|
| 3395 |
**Syntax**: |
| 3396 |
|
| 3397 |
.. code-block:: c++ |
| 3398 |
|
| 3399 |
int __builtin_cpu_supports(const char *features); |
| 3400 |
|
| 3401 |
**Example of Use:**: |
| 3402 |
|
| 3403 |
.. code-block:: c++ |
| 3404 |
|
| 3405 |
if (__builtin_cpu_supports("sve")) |
| 3406 |
sve_code(); |
| 3407 |
|
| 3408 |
**Description**: |
| 3409 |
|
| 3410 |
The ``__builtin_cpu_supports`` function detects if the run-time CPU supports |
| 3411 |
features specified in string argument. It returns a positive integer if all |
| 3412 |
features are supported and 0 otherwise. Feature names are target specific. On |
| 3413 |
AArch64, features are combined using ``+`` like this |
| 3414 |
``__builtin_cpu_supports("flagm+sha3+lse+rcpc2+fcma+memtag+bti+sme2")``. |
| 3415 |
If a feature name is not supported, Clang will issue a warning and replace |
| 3416 |
builtin by the constant 0. |
| 3417 |
|
| 3418 |
Query for this feature with ``__has_builtin(__builtin_cpu_supports)``. |
| 3419 |
|
| 3420 |
``__builtin_dump_struct`` |
| 3421 |
------------------------- |
| 3422 |
|
| 3423 |
**Syntax**: |
| 3424 |
|
| 3425 |
.. code-block:: c++ |
| 3426 |
|
| 3427 |
__builtin_dump_struct(&some_struct, some_printf_func, args...); |
| 3428 |
|
| 3429 |
**Examples**: |
| 3430 |
|
| 3431 |
.. code-block:: c++ |
| 3432 |
|
| 3433 |
struct S { |
| 3434 |
int x, y; |
| 3435 |
float f; |
| 3436 |
struct T { |
| 3437 |
int i; |
| 3438 |
} t; |
| 3439 |
}; |
| 3440 |
|
| 3441 |
void func(struct S *s) { |
| 3442 |
__builtin_dump_struct(s, printf); |
| 3443 |
} |
| 3444 |
|
| 3445 |
Example output: |
| 3446 |
|
| 3447 |
.. code-block:: none |
| 3448 |
|
| 3449 |
struct S { |
| 3450 |
int x = 100 |
| 3451 |
int y = 42 |
| 3452 |
float f = 3.141593 |
| 3453 |
struct T t = { |
| 3454 |
int i = 1997 |
| 3455 |
} |
| 3456 |
} |
| 3457 |
|
| 3458 |
.. code-block:: c++ |
| 3459 |
|
| 3460 |
#include <string> |
| 3461 |
struct T { int a, b; }; |
| 3462 |
constexpr void constexpr_sprintf(std::string &out, const char *format, |
| 3463 |
auto ...args) { |
| 3464 |
// ... |
| 3465 |
} |
| 3466 |
constexpr std::string dump_struct(auto &x) { |
| 3467 |
std::string s; |
| 3468 |
__builtin_dump_struct(&x, constexpr_sprintf, s); |
| 3469 |
return s; |
| 3470 |
} |
| 3471 |
static_assert(dump_struct(T{1, 2}) == R"(struct T { |
| 3472 |
int a = 1 |
| 3473 |
int b = 2 |
| 3474 |
} |
| 3475 |
)"); |
| 3476 |
|
| 3477 |
**Description**: |
| 3478 |
|
| 3479 |
The ``__builtin_dump_struct`` function is used to print the fields of a simple |
| 3480 |
structure and their values for debugging purposes. The first argument of the |
| 3481 |
builtin should be a pointer to a complete record type to dump. The second argument ``f`` |
| 3482 |
should be some callable expression, and can be a function object or an overload |
| 3483 |
set. The builtin calls ``f``, passing any further arguments ``args...`` |
| 3484 |
followed by a ``printf``-compatible format string and the corresponding |
| 3485 |
arguments. ``f`` may be called more than once, and ``f`` and ``args`` will be |
| 3486 |
evaluated once per call. In C++, ``f`` may be a template or overload set and |
| 3487 |
resolve to different functions for each call. |
| 3488 |
|
| 3489 |
In the format string, a suitable format specifier will be used for builtin |
| 3490 |
types that Clang knows how to format. This includes standard builtin types, as |
| 3491 |
well as aggregate structures, ``void*`` (printed with ``%p``), and ``const |
| 3492 |
char*`` (printed with ``%s``). A ``*%p`` specifier will be used for a field |
| 3493 |
that Clang doesn't know how to format, and the corresponding argument will be a |
| 3494 |
pointer to the field. This allows a C++ templated formatting function to detect |
| 3495 |
this case and implement custom formatting. A ``*`` will otherwise not precede a |
| 3496 |
format specifier. |
| 3497 |
|
| 3498 |
This builtin does not return a value. |
| 3499 |
|
| 3500 |
This builtin can be used in constant expressions. |
| 3501 |
|
| 3502 |
Query for this feature with ``__has_builtin(__builtin_dump_struct)`` |
| 3503 |
|
| 3504 |
.. _langext-__builtin_shufflevector: |
| 3505 |
|
| 3506 |
``__builtin_shufflevector`` |
| 3507 |
--------------------------- |
| 3508 |
|
| 3509 |
``__builtin_shufflevector`` is used to express generic vector |
| 3510 |
permutation/shuffle/swizzle operations. This builtin is also very important |
| 3511 |
for the implementation of various target-specific header files like |
| 3512 |
``<xmmintrin.h>``. This builtin can be used within constant expressions. |
| 3513 |
|
| 3514 |
**Syntax**: |
| 3515 |
|
| 3516 |
.. code-block:: c++ |
| 3517 |
|
| 3518 |
__builtin_shufflevector(vec1, vec2, index1, index2, ...) |
| 3519 |
|
| 3520 |
**Examples**: |
| 3521 |
|
| 3522 |
.. code-block:: c++ |
| 3523 |
|
| 3524 |
// identity operation - return 4-element vector v1. |
| 3525 |
__builtin_shufflevector(v1, v1, 0, 1, 2, 3) |
| 3526 |
|
| 3527 |
// "Splat" element 0 of V1 into a 4-element result. |
| 3528 |
__builtin_shufflevector(V1, V1, 0, 0, 0, 0) |
| 3529 |
|
| 3530 |
// Reverse 4-element vector V1. |
| 3531 |
__builtin_shufflevector(V1, V1, 3, 2, 1, 0) |
| 3532 |
|
| 3533 |
// Concatenate every other element of 4-element vectors V1 and V2. |
| 3534 |
__builtin_shufflevector(V1, V2, 0, 2, 4, 6) |
| 3535 |
|
| 3536 |
// Concatenate every other element of 8-element vectors V1 and V2. |
| 3537 |
__builtin_shufflevector(V1, V2, 0, 2, 4, 6, 8, 10, 12, 14) |
| 3538 |
|
| 3539 |
// Shuffle v1 with some elements being undefined. Not allowed in constexpr. |
| 3540 |
__builtin_shufflevector(v1, v1, 3, -1, 1, -1) |
| 3541 |
|
| 3542 |
**Description**: |
| 3543 |
|
| 3544 |
The first two arguments to ``__builtin_shufflevector`` are vectors that have |
| 3545 |
the same element type. The remaining arguments are a list of integers that |
| 3546 |
specify the elements indices of the first two vectors that should be extracted |
| 3547 |
and returned in a new vector. These element indices are numbered sequentially |
| 3548 |
starting with the first vector, continuing into the second vector. Thus, if |
| 3549 |
``vec1`` is a 4-element vector, index 5 would refer to the second element of |
| 3550 |
``vec2``. An index of -1 can be used to indicate that the corresponding element |
| 3551 |
in the returned vector is a don't care and can be optimized by the backend. |
| 3552 |
Values of -1 are not supported in constant expressions. |
| 3553 |
|
| 3554 |
The result of ``__builtin_shufflevector`` is a vector with the same element |
| 3555 |
type as ``vec1``/``vec2`` but that has an element count equal to the number of |
| 3556 |
indices specified. |
| 3557 |
|
| 3558 |
Query for this feature with ``__has_builtin(__builtin_shufflevector)``. |
| 3559 |
|
| 3560 |
.. _langext-__builtin_convertvector: |
| 3561 |
|
| 3562 |
``__builtin_convertvector`` |
| 3563 |
--------------------------- |
| 3564 |
|
| 3565 |
``__builtin_convertvector`` is used to express generic vector |
| 3566 |
type-conversion operations. The input vector and the output vector |
| 3567 |
type must have the same number of elements. This builtin can be used within |
| 3568 |
constant expressions. |
| 3569 |
|
| 3570 |
**Syntax**: |
| 3571 |
|
| 3572 |
.. code-block:: c++ |
| 3573 |
|
| 3574 |
__builtin_convertvector(src_vec, dst_vec_type) |
| 3575 |
|
| 3576 |
**Examples**: |
| 3577 |
|
| 3578 |
.. code-block:: c++ |
| 3579 |
|
| 3580 |
typedef double vector4double __attribute__((__vector_size__(32))); |
| 3581 |
typedef float vector4float __attribute__((__vector_size__(16))); |
| 3582 |
typedef short vector4short __attribute__((__vector_size__(8))); |
| 3583 |
vector4float vf; vector4short vs; |
| 3584 |
|
| 3585 |
// convert from a vector of 4 floats to a vector of 4 doubles. |
| 3586 |
__builtin_convertvector(vf, vector4double) |
| 3587 |
// equivalent to: |
| 3588 |
(vector4double) { (double) vf[0], (double) vf[1], (double) vf[2], (double) vf[3] } |
| 3589 |
|
| 3590 |
// convert from a vector of 4 shorts to a vector of 4 floats. |
| 3591 |
__builtin_convertvector(vs, vector4float) |
| 3592 |
// equivalent to: |
| 3593 |
(vector4float) { (float) vs[0], (float) vs[1], (float) vs[2], (float) vs[3] } |
| 3594 |
|
| 3595 |
**Description**: |
| 3596 |
|
| 3597 |
The first argument to ``__builtin_convertvector`` is a vector, and the second |
| 3598 |
argument is a vector type with the same number of elements as the first |
| 3599 |
argument. |
| 3600 |
|
| 3601 |
The result of ``__builtin_convertvector`` is a vector with the same element |
| 3602 |
type as the second argument, with a value defined in terms of the action of a |
| 3603 |
C-style cast applied to each element of the first argument. |
| 3604 |
|
| 3605 |
Query for this feature with ``__has_builtin(__builtin_convertvector)``. |
| 3606 |
|
| 3607 |
``__builtin_bitreverse`` |
| 3608 |
------------------------ |
| 3609 |
|
| 3610 |
* ``__builtin_bitreverse8`` |
| 3611 |
* ``__builtin_bitreverse16`` |
| 3612 |
* ``__builtin_bitreverse32`` |
| 3613 |
* ``__builtin_bitreverse64`` |
| 3614 |
|
| 3615 |
**Syntax**: |
| 3616 |
|
| 3617 |
.. code-block:: c++ |
| 3618 |
|
| 3619 |
__builtin_bitreverse32(x) |
| 3620 |
|
| 3621 |
**Examples**: |
| 3622 |
|
| 3623 |
.. code-block:: c++ |
| 3624 |
|
| 3625 |
uint8_t rev_x = __builtin_bitreverse8(x); |
| 3626 |
uint16_t rev_x = __builtin_bitreverse16(x); |
| 3627 |
uint32_t rev_y = __builtin_bitreverse32(y); |
| 3628 |
uint64_t rev_z = __builtin_bitreverse64(z); |
| 3629 |
|
| 3630 |
**Description**: |
| 3631 |
|
| 3632 |
The '``__builtin_bitreverse``' family of builtins is used to reverse |
| 3633 |
the bitpattern of an integer value; for example, ``0b10110110`` becomes |
| 3634 |
``0b01101101``. These builtins can be used within constant expressions. |
| 3635 |
|
| 3636 |
``__builtin_rotateleft`` |
| 3637 |
------------------------ |
| 3638 |
|
| 3639 |
* ``__builtin_rotateleft8`` |
| 3640 |
* ``__builtin_rotateleft16`` |
| 3641 |
* ``__builtin_rotateleft32`` |
| 3642 |
* ``__builtin_rotateleft64`` |
| 3643 |
|
| 3644 |
**Syntax**: |
| 3645 |
|
| 3646 |
.. code-block:: c++ |
| 3647 |
|
| 3648 |
__builtin_rotateleft32(x, y) |
| 3649 |
|
| 3650 |
**Examples**: |
| 3651 |
|
| 3652 |
.. code-block:: c++ |
| 3653 |
|
| 3654 |
uint8_t rot_x = __builtin_rotateleft8(x, y); |
| 3655 |
uint16_t rot_x = __builtin_rotateleft16(x, y); |
| 3656 |
uint32_t rot_x = __builtin_rotateleft32(x, y); |
| 3657 |
uint64_t rot_x = __builtin_rotateleft64(x, y); |
| 3658 |
|
| 3659 |
**Description**: |
| 3660 |
|
| 3661 |
The '``__builtin_rotateleft``' family of builtins is used to rotate |
| 3662 |
the bits in the first argument by the amount in the second argument. |
| 3663 |
For example, ``0b10000110`` rotated left by 11 becomes ``0b00110100``. |
| 3664 |
The shift value is treated as an unsigned amount modulo the size of |
| 3665 |
the arguments. Both arguments and the result have the bitwidth specified |
| 3666 |
by the name of the builtin. These builtins can be used within constant |
| 3667 |
expressions. |
| 3668 |
|
| 3669 |
``__builtin_rotateright`` |
| 3670 |
------------------------- |
| 3671 |
|
| 3672 |
* ``__builtin_rotateright8`` |
| 3673 |
* ``__builtin_rotateright16`` |
| 3674 |
* ``__builtin_rotateright32`` |
| 3675 |
* ``__builtin_rotateright64`` |
| 3676 |
|
| 3677 |
**Syntax**: |
| 3678 |
|
| 3679 |
.. code-block:: c++ |
| 3680 |
|
| 3681 |
__builtin_rotateright32(x, y) |
| 3682 |
|
| 3683 |
**Examples**: |
| 3684 |
|
| 3685 |
.. code-block:: c++ |
| 3686 |
|
| 3687 |
uint8_t rot_x = __builtin_rotateright8(x, y); |
| 3688 |
uint16_t rot_x = __builtin_rotateright16(x, y); |
| 3689 |
uint32_t rot_x = __builtin_rotateright32(x, y); |
| 3690 |
uint64_t rot_x = __builtin_rotateright64(x, y); |
| 3691 |
|
| 3692 |
**Description**: |
| 3693 |
|
| 3694 |
The '``__builtin_rotateright``' family of builtins is used to rotate |
| 3695 |
the bits in the first argument by the amount in the second argument. |
| 3696 |
For example, ``0b10000110`` rotated right by 3 becomes ``0b11010000``. |
| 3697 |
The shift value is treated as an unsigned amount modulo the size of |
| 3698 |
the arguments. Both arguments and the result have the bitwidth specified |
| 3699 |
by the name of the builtin. These builtins can be used within constant |
| 3700 |
expressions. |
| 3701 |
|
| 3702 |
``__builtin_unreachable`` |
| 3703 |
------------------------- |
| 3704 |
|
| 3705 |
``__builtin_unreachable`` is used to indicate that a specific point in the |
| 3706 |
program cannot be reached, even if the compiler might otherwise think it can. |
| 3707 |
This is useful to improve optimization and eliminates certain warnings. For |
| 3708 |
example, without the ``__builtin_unreachable`` in the example below, the |
| 3709 |
compiler assumes that the inline asm can fall through and prints a "function |
| 3710 |
declared '``noreturn``' should not return" warning. |
| 3711 |
|
| 3712 |
**Syntax**: |
| 3713 |
|
| 3714 |
.. code-block:: c++ |
| 3715 |
|
| 3716 |
__builtin_unreachable() |
| 3717 |
|
| 3718 |
**Example of use**: |
| 3719 |
|
| 3720 |
.. code-block:: c++ |
| 3721 |
|
| 3722 |
void myabort(void) __attribute__((noreturn)); |
| 3723 |
void myabort(void) { |
| 3724 |
asm("int3"); |
| 3725 |
__builtin_unreachable(); |
| 3726 |
} |
| 3727 |
|
| 3728 |
**Description**: |
| 3729 |
|
| 3730 |
The ``__builtin_unreachable()`` builtin has completely undefined behavior. |
| 3731 |
Since it has undefined behavior, it is a statement that it is never reached and |
| 3732 |
the optimizer can take advantage of this to produce better code. This builtin |
| 3733 |
takes no arguments and produces a void result. |
| 3734 |
|
| 3735 |
Query for this feature with ``__has_builtin(__builtin_unreachable)``. |
| 3736 |
|
| 3737 |
``__builtin_unpredictable`` |
| 3738 |
--------------------------- |
| 3739 |
|
| 3740 |
``__builtin_unpredictable`` is used to indicate that a branch condition is |
| 3741 |
unpredictable by hardware mechanisms such as branch prediction logic. |
| 3742 |
|
| 3743 |
**Syntax**: |
| 3744 |
|
| 3745 |
.. code-block:: c++ |
| 3746 |
|
| 3747 |
__builtin_unpredictable(long long) |
| 3748 |
|
| 3749 |
**Example of use**: |
| 3750 |
|
| 3751 |
.. code-block:: c++ |
| 3752 |
|
| 3753 |
if (__builtin_unpredictable(x > 0)) { |
| 3754 |
foo(); |
| 3755 |
} |
| 3756 |
|
| 3757 |
**Description**: |
| 3758 |
|
| 3759 |
The ``__builtin_unpredictable()`` builtin is expected to be used with control |
| 3760 |
flow conditions such as in ``if`` and ``switch`` statements. |
| 3761 |
|
| 3762 |
Query for this feature with ``__has_builtin(__builtin_unpredictable)``. |
| 3763 |
|
| 3764 |
|
| 3765 |
``__builtin_expect`` |
| 3766 |
-------------------- |
| 3767 |
|
| 3768 |
``__builtin_expect`` is used to indicate that the value of an expression is |
| 3769 |
anticipated to be the same as a statically known result. |
| 3770 |
|
| 3771 |
**Syntax**: |
| 3772 |
|
| 3773 |
.. code-block:: c++ |
| 3774 |
|
| 3775 |
long __builtin_expect(long expr, long val) |
| 3776 |
|
| 3777 |
**Example of use**: |
| 3778 |
|
| 3779 |
.. code-block:: c++ |
| 3780 |
|
| 3781 |
if (__builtin_expect(x, 0)) { |
| 3782 |
bar(); |
| 3783 |
} |
| 3784 |
|
| 3785 |
**Description**: |
| 3786 |
|
| 3787 |
The ``__builtin_expect()`` builtin is typically used with control flow |
| 3788 |
conditions such as in ``if`` and ``switch`` statements to help branch |
| 3789 |
prediction. It means that its first argument ``expr`` is expected to take the |
| 3790 |
value of its second argument ``val``. It always returns ``expr``. |
| 3791 |
|
| 3792 |
Query for this feature with ``__has_builtin(__builtin_expect)``. |
| 3793 |
|
| 3794 |
``__builtin_expect_with_probability`` |
| 3795 |
------------------------------------- |
| 3796 |
|
| 3797 |
``__builtin_expect_with_probability`` is similar to ``__builtin_expect`` but it |
| 3798 |
takes a probability as third argument. |
| 3799 |
|
| 3800 |
**Syntax**: |
| 3801 |
|
| 3802 |
.. code-block:: c++ |
| 3803 |
|
| 3804 |
long __builtin_expect_with_probability(long expr, long val, double p) |
| 3805 |
|
| 3806 |
**Example of use**: |
| 3807 |
|
| 3808 |
.. code-block:: c++ |
| 3809 |
|
| 3810 |
if (__builtin_expect_with_probability(x, 0, .3)) { |
| 3811 |
bar(); |
| 3812 |
} |
| 3813 |
|
| 3814 |
**Description**: |
| 3815 |
|
| 3816 |
The ``__builtin_expect_with_probability()`` builtin is typically used with |
| 3817 |
control flow conditions such as in ``if`` and ``switch`` statements to help |
| 3818 |
branch prediction. It means that its first argument ``expr`` is expected to take |
| 3819 |
the value of its second argument ``val`` with probability ``p``. ``p`` must be |
| 3820 |
within ``[0.0 ; 1.0]`` bounds. This builtin always returns the value of ``expr``. |
| 3821 |
|
| 3822 |
Query for this feature with ``__has_builtin(__builtin_expect_with_probability)``. |
| 3823 |
|
| 3824 |
``__builtin_prefetch`` |
| 3825 |
---------------------- |
| 3826 |
|
| 3827 |
``__builtin_prefetch`` is used to communicate with the cache handler to bring |
| 3828 |
data into the cache before it gets used. |
| 3829 |
|
| 3830 |
**Syntax**: |
| 3831 |
|
| 3832 |
.. code-block:: c++ |
| 3833 |
|
| 3834 |
void __builtin_prefetch(const void *addr, int rw=0, int locality=3) |
| 3835 |
|
| 3836 |
**Example of use**: |
| 3837 |
|
| 3838 |
.. code-block:: c++ |
| 3839 |
|
| 3840 |
__builtin_prefetch(a + i); |
| 3841 |
|
| 3842 |
**Description**: |
| 3843 |
|
| 3844 |
The ``__builtin_prefetch(addr, rw, locality)`` builtin is expected to be used to |
| 3845 |
avoid cache misses when the developer has a good understanding of which data |
| 3846 |
are going to be used next. ``addr`` is the address that needs to be brought into |
| 3847 |
the cache. ``rw`` indicates the expected access mode: ``0`` for *read* and ``1`` |
| 3848 |
for *write*. In case of *read write* access, ``1`` is to be used. ``locality`` |
| 3849 |
indicates the expected persistence of data in cache, from ``0`` which means that |
| 3850 |
data can be discarded from cache after its next use to ``3`` which means that |
| 3851 |
data is going to be reused a lot once in cache. ``1`` and ``2`` provide |
| 3852 |
intermediate behavior between these two extremes. |
| 3853 |
|
| 3854 |
Query for this feature with ``__has_builtin(__builtin_prefetch)``. |
| 3855 |
|
| 3856 |
``__sync_swap`` |
| 3857 |
--------------- |
| 3858 |
|
| 3859 |
``__sync_swap`` is used to atomically swap integers or pointers in memory. |
| 3860 |
|
| 3861 |
**Syntax**: |
| 3862 |
|
| 3863 |
.. code-block:: c++ |
| 3864 |
|
| 3865 |
type __sync_swap(type *ptr, type value, ...) |
| 3866 |
|
| 3867 |
**Example of Use**: |
| 3868 |
|
| 3869 |
.. code-block:: c++ |
| 3870 |
|
| 3871 |
int old_value = __sync_swap(&value, new_value); |
| 3872 |
|
| 3873 |
**Description**: |
| 3874 |
|
| 3875 |
The ``__sync_swap()`` builtin extends the existing ``__sync_*()`` family of |
| 3876 |
atomic intrinsics to allow code to atomically swap the current value with the |
| 3877 |
new value. More importantly, it helps developers write more efficient and |
| 3878 |
correct code by avoiding expensive loops around |
| 3879 |
``__sync_bool_compare_and_swap()`` or relying on the platform specific |
| 3880 |
implementation details of ``__sync_lock_test_and_set()``. The |
| 3881 |
``__sync_swap()`` builtin is a full barrier. |
| 3882 |
|
| 3883 |
``__builtin_addressof`` |
| 3884 |
----------------------- |
| 3885 |
|
| 3886 |
``__builtin_addressof`` performs the functionality of the built-in ``&`` |
| 3887 |
operator, ignoring any ``operator&`` overload. This is useful in constant |
| 3888 |
expressions in C++11, where there is no other way to take the address of an |
| 3889 |
object that overloads ``operator&``. Clang automatically adds |
| 3890 |
``[[clang::lifetimebound]]`` to the parameter of ``__builtin_addressof``. |
| 3891 |
|
| 3892 |
**Example of use**: |
| 3893 |
|
| 3894 |
.. code-block:: c++ |
| 3895 |
|
| 3896 |
template<typename T> constexpr T *addressof(T &value) { |
| 3897 |
return __builtin_addressof(value); |
| 3898 |
} |
| 3899 |
|
| 3900 |
``__builtin_function_start`` |
| 3901 |
----------------------------- |
| 3902 |
|
| 3903 |
``__builtin_function_start`` returns the address of a function body. |
| 3904 |
|
| 3905 |
**Syntax**: |
| 3906 |
|
| 3907 |
.. code-block:: c++ |
| 3908 |
|
| 3909 |
void *__builtin_function_start(function) |
| 3910 |
|
| 3911 |
**Example of use**: |
| 3912 |
|
| 3913 |
.. code-block:: c++ |
| 3914 |
|
| 3915 |
void a() {} |
| 3916 |
void *p = __builtin_function_start(a); |
| 3917 |
|
| 3918 |
class A { |
| 3919 |
public: |
| 3920 |
void a(int n); |
| 3921 |
void a(); |
| 3922 |
}; |
| 3923 |
|
| 3924 |
void A::a(int n) {} |
| 3925 |
void A::a() {} |
| 3926 |
|
| 3927 |
void *pa1 = __builtin_function_start((void(A::*)(int)) &A::a); |
| 3928 |
void *pa2 = __builtin_function_start((void(A::*)()) &A::a); |
| 3929 |
|
| 3930 |
**Description**: |
| 3931 |
|
| 3932 |
The ``__builtin_function_start`` builtin accepts an argument that can be |
| 3933 |
constant-evaluated to a function, and returns the address of the function |
| 3934 |
body. This builtin is not supported on all targets. |
| 3935 |
|
| 3936 |
The returned pointer may differ from the normally taken function address |
| 3937 |
and is not safe to call. For example, with ``-fsanitize=cfi``, taking a |
| 3938 |
function address produces a callable pointer to a CFI jump table, while |
| 3939 |
``__builtin_function_start`` returns an address that fails |
| 3940 |
:doc:`cfi-icall<ControlFlowIntegrity>` checks. |
| 3941 |
|
| 3942 |
``__builtin_operator_new`` and ``__builtin_operator_delete`` |
| 3943 |
------------------------------------------------------------ |
| 3944 |
|
| 3945 |
A call to ``__builtin_operator_new(args)`` is exactly the same as a call to |
| 3946 |
``::operator new(args)``, except that it allows certain optimizations |
| 3947 |
that the C++ standard does not permit for a direct function call to |
| 3948 |
``::operator new`` (in particular, removing ``new`` / ``delete`` pairs and |
| 3949 |
merging allocations), and that the call is required to resolve to a |
| 3950 |
`replaceable global allocation function |
| 3951 |
<https://en.cppreference.com/w/cpp/memory/new/operator_new>`_. |
| 3952 |
|
| 3953 |
Likewise, ``__builtin_operator_delete`` is exactly the same as a call to |
| 3954 |
``::operator delete(args)``, except that it permits optimizations |
| 3955 |
and that the call is required to resolve to a |
| 3956 |
`replaceable global deallocation function |
| 3957 |
<https://en.cppreference.com/w/cpp/memory/new/operator_delete>`_. |
| 3958 |
|
| 3959 |
These builtins are intended for use in the implementation of ``std::allocator`` |
| 3960 |
and other similar allocation libraries, and are only available in C++. |
| 3961 |
|
| 3962 |
Query for this feature with ``__has_builtin(__builtin_operator_new)`` or |
| 3963 |
``__has_builtin(__builtin_operator_delete)``: |
| 3964 |
|
| 3965 |
* If the value is at least ``201802L``, the builtins behave as described above. |
| 3966 |
|
| 3967 |
* If the value is non-zero, the builtins may not support calling arbitrary |
| 3968 |
replaceable global (de)allocation functions, but do support calling at least |
| 3969 |
``::operator new(size_t)`` and ``::operator delete(void*)``. |
| 3970 |
|
| 3971 |
|
| 3972 |
``__builtin_trivially_relocate`` |
| 3973 |
----------------------------------- |
| 3974 |
|
| 3975 |
**Syntax**: |
| 3976 |
|
| 3977 |
.. code-block:: c |
| 3978 |
|
| 3979 |
T* __builtin_trivially_relocate(T* dest, T* src, size_t count) |
| 3980 |
|
| 3981 |
Trivially relocates ``count`` objects of relocatable, complete type ``T`` |
| 3982 |
from ``src`` to ``dest`` and returns ``dest``. |
| 3983 |
This builtin is used to implement ``std::trivially_relocate``. |
| 3984 |
|
| 3985 |
``__builtin_invoke`` |
| 3986 |
-------------------- |
| 3987 |
|
| 3988 |
**Syntax**: |
| 3989 |
|
| 3990 |
.. code-block:: c++ |
| 3991 |
|
| 3992 |
template <class Callee, class... Args> |
| 3993 |
decltype(auto) __builtin_invoke(Callee&& callee, Args&&... args); |
| 3994 |
|
| 3995 |
``__builtin_invoke`` is equivalent to ``std::invoke``. |
| 3996 |
|
| 3997 |
``__builtin_preserve_access_index`` |
| 3998 |
----------------------------------- |
| 3999 |
|
| 4000 |
``__builtin_preserve_access_index`` specifies a code section where |
| 4001 |
array subscript access and structure/union member access are relocatable |
| 4002 |
under bpf compile-once run-everywhere framework. Debuginfo (typically |
| 4003 |
with ``-g``) is needed, otherwise, the compiler will exit with an error. |
| 4004 |
The return type for the intrinsic is the same as the type of the |
| 4005 |
argument. |
| 4006 |
|
| 4007 |
**Syntax**: |
| 4008 |
|
| 4009 |
.. code-block:: c |
| 4010 |
|
| 4011 |
type __builtin_preserve_access_index(type arg) |
| 4012 |
|
| 4013 |
**Example of Use**: |
| 4014 |
|
| 4015 |
.. code-block:: c |
| 4016 |
|
| 4017 |
struct t { |
| 4018 |
int i; |
| 4019 |
int j; |
| 4020 |
union { |
| 4021 |
int a; |
| 4022 |
int b; |
| 4023 |
} c[4]; |
| 4024 |
}; |
| 4025 |
struct t *v = ...; |
| 4026 |
int *pb =__builtin_preserve_access_index(&v->c[3].b); |
| 4027 |
__builtin_preserve_access_index(v->j); |
| 4028 |
|
| 4029 |
``__builtin_debugtrap`` |
| 4030 |
----------------------- |
| 4031 |
|
| 4032 |
``__builtin_debugtrap`` causes the program to stop its execution in such a way that a debugger can catch it. |
| 4033 |
|
| 4034 |
**Syntax**: |
| 4035 |
|
| 4036 |
.. code-block:: c++ |
| 4037 |
|
| 4038 |
__builtin_debugtrap() |
| 4039 |
|
| 4040 |
**Description** |
| 4041 |
|
| 4042 |
``__builtin_debugtrap`` is lowered to the ` ``llvm.debugtrap`` <https://llvm.org/docs/LangRef.html#llvm-debugtrap-intrinsic>`_ builtin. It should have the same effect as setting a breakpoint on the line where the builtin is called. |
| 4043 |
|
| 4044 |
Query for this feature with ``__has_builtin(__builtin_debugtrap)``. |
| 4045 |
|
| 4046 |
|
| 4047 |
``__builtin_trap`` |
| 4048 |
------------------ |
| 4049 |
|
| 4050 |
``__builtin_trap`` causes the program to stop its execution abnormally. |
| 4051 |
|
| 4052 |
**Syntax**: |
| 4053 |
|
| 4054 |
.. code-block:: c++ |
| 4055 |
|
| 4056 |
__builtin_trap() |
| 4057 |
|
| 4058 |
**Description** |
| 4059 |
|
| 4060 |
``__builtin_trap`` is lowered to the ` ``llvm.trap`` <https://llvm.org/docs/LangRef.html#llvm-trap-intrinsic>`_ builtin. |
| 4061 |
|
| 4062 |
Query for this feature with ``__has_builtin(__builtin_trap)``. |
| 4063 |
|
| 4064 |
``__builtin_arm_trap`` |
| 4065 |
---------------------- |
| 4066 |
|
| 4067 |
``__builtin_arm_trap`` is an AArch64 extension to ``__builtin_trap`` which also accepts a compile-time constant value, encoded directly into the trap instruction for later inspection. |
| 4068 |
|
| 4069 |
**Syntax**: |
| 4070 |
|
| 4071 |
.. code-block:: c++ |
| 4072 |
|
| 4073 |
__builtin_arm_trap(const unsigned short payload) |
| 4074 |
|
| 4075 |
**Description** |
| 4076 |
|
| 4077 |
``__builtin_arm_trap`` is lowered to the ``llvm.aarch64.break`` builtin, and then to ``brk #payload``. |
| 4078 |
|
| 4079 |
``__builtin_verbose_trap`` |
| 4080 |
-------------------------- |
| 4081 |
|
| 4082 |
``__builtin_verbose_trap`` causes the program to stop its execution abnormally |
| 4083 |
and shows a human-readable description of the reason for the termination when a |
| 4084 |
debugger is attached or in a symbolicated crash log. |
| 4085 |
|
| 4086 |
**Syntax**: |
| 4087 |
|
| 4088 |
.. code-block:: c++ |
| 4089 |
|
| 4090 |
__builtin_verbose_trap(const char *category, const char *reason) |
| 4091 |
|
| 4092 |
**Description** |
| 4093 |
|
| 4094 |
``__builtin_verbose_trap`` is lowered to the ` ``llvm.trap`` <https://llvm.org/docs/LangRef.html#llvm-trap-intrinsic>`_ builtin. |
| 4095 |
Additionally, clang emits debugging information that represents an artificial |
| 4096 |
inline frame whose name encodes the category and reason strings passed to the builtin, |
| 4097 |
prefixed by a "magic" prefix. |
| 4098 |
|
| 4099 |
For example, consider the following code: |
| 4100 |
|
| 4101 |
.. code-block:: c++ |
| 4102 |
|
| 4103 |
void foo(int* p) { |
| 4104 |
if (p == nullptr) |
| 4105 |
__builtin_verbose_trap("check null", "Argument must not be null!"); |
| 4106 |
} |
| 4107 |
|
| 4108 |
The debugging information would look as if it were produced for the following code: |
| 4109 |
|
| 4110 |
.. code-block:: c++ |
| 4111 |
|
| 4112 |
__attribute__((always_inline)) |
| 4113 |
inline void "__clang_trap_msg$check null$Argument must not be null!"() { |
| 4114 |
__builtin_trap(); |
| 4115 |
} |
| 4116 |
|
| 4117 |
void foo(int* p) { |
| 4118 |
if (p == nullptr) |
| 4119 |
"__clang_trap_msg$check null$Argument must not be null!"(); |
| 4120 |
} |
| 4121 |
|
| 4122 |
However, the generated code would not actually contain a call to the artificial |
| 4123 |
function — it only exists in the debugging information. |
| 4124 |
|
| 4125 |
Query for this feature with ``__has_builtin(__builtin_verbose_trap)``. Note that |
| 4126 |
users need to enable debug information to enable this feature. A call to this |
| 4127 |
builtin is equivalent to a call to ``__builtin_trap`` if debug information isn't |
| 4128 |
enabled. |
| 4129 |
|
| 4130 |
The optimizer can merge calls to trap with different messages, which degrades |
| 4131 |
the debugging experience. |
| 4132 |
|
| 4133 |
``__builtin_allow_runtime_check`` |
| 4134 |
--------------------------------- |
| 4135 |
|
| 4136 |
``__builtin_allow_runtime_check`` returns true if the check at the current |
| 4137 |
program location should be executed. It is expected to be used to implement |
| 4138 |
``assert`` like checks which can be safely removed by the optimizer. |
| 4139 |
|
| 4140 |
**Syntax**: |
| 4141 |
|
| 4142 |
.. code-block:: c++ |
| 4143 |
|
| 4144 |
bool __builtin_allow_runtime_check(const char* kind) |
| 4145 |
|
| 4146 |
**Example of use**: |
| 4147 |
|
| 4148 |
.. code-block:: c++ |
| 4149 |
|
| 4150 |
if (__builtin_allow_runtime_check("mycheck") && !ExpensiveCheck()) { |
| 4151 |
abort(); |
| 4152 |
} |
| 4153 |
|
| 4154 |
**Description** |
| 4155 |
|
| 4156 |
``__builtin_allow_runtime_check`` is lowered to the `llvm.allow.runtime.check |
| 4157 |
<https://llvm.org/docs/LangRef.html#llvm-allow-runtime-check-intrinsic>`_ |
| 4158 |
intrinsic. |
| 4159 |
|
| 4160 |
The ``__builtin_allow_runtime_check()`` can be used within control structures |
| 4161 |
like ``if`` to guard expensive runtime checks. The return value is determined |
| 4162 |
by the following compiler options and may differ per call site: |
| 4163 |
|
| 4164 |
* ``-mllvm -lower-allow-check-percentile-cutoff-hot=N``: Disable checks in hot |
| 4165 |
code marked by the profile summary with a hotness cutoff in the range |
| 4166 |
``[0, 999999]`` (a larger N disables more checks). |
| 4167 |
* ``-mllvm -lower-allow-check-random-rate=P``: Keep a check with probability P, |
| 4168 |
a floating point number in the range ``[0.0, 1.0]``. |
| 4169 |
* If both options are specified, a check is disabled if either condition is satisfied. |
| 4170 |
* If neither is specified, all checks are allowed. |
| 4171 |
|
| 4172 |
Parameter ``kind``, currently unused, is a string literal specifying the check |
| 4173 |
kind. Future compiler versions may use this to allow for more granular control, |
| 4174 |
such as applying different hotness cutoffs to different check kinds. |
| 4175 |
|
| 4176 |
Query for this feature with ``__has_builtin(__builtin_allow_runtime_check)``. |
| 4177 |
|
| 4178 |
``__builtin_nondeterministic_value`` |
| 4179 |
------------------------------------ |
| 4180 |
|
| 4181 |
``__builtin_nondeterministic_value`` returns a valid nondeterministic value of the same type as the provided argument. |
| 4182 |
|
| 4183 |
**Syntax**: |
| 4184 |
|
| 4185 |
.. code-block:: c++ |
| 4186 |
|
| 4187 |
type __builtin_nondeterministic_value(type x) |
| 4188 |
|
| 4189 |
**Examples**: |
| 4190 |
|
| 4191 |
.. code-block:: c++ |
| 4192 |
|
| 4193 |
int x = __builtin_nondeterministic_value(x); |
| 4194 |
float y = __builtin_nondeterministic_value(y); |
| 4195 |
__m256i a = __builtin_nondeterministic_value(a); |
| 4196 |
|
| 4197 |
**Description** |
| 4198 |
|
| 4199 |
Each call to ``__builtin_nondeterministic_value`` returns a valid value of the type given by the argument. |
| 4200 |
|
| 4201 |
The types currently supported are: integer types, floating-point types, vector types. |
| 4202 |
|
| 4203 |
Query for this feature with ``__has_builtin(__builtin_nondeterministic_value)``. |
| 4204 |
|
| 4205 |
``__builtin_sycl_unique_stable_name`` |
| 4206 |
------------------------------------- |
| 4207 |
|
| 4208 |
``__builtin_sycl_unique_stable_name()`` is a builtin that takes a type and |
| 4209 |
produces a string literal containing a unique name for the type that is stable |
| 4210 |
across split compilations, mainly to support SYCL/Data Parallel C++ language. |
| 4211 |
|
| 4212 |
In cases where the split compilation needs to share a unique token for a type |
| 4213 |
across the boundary (such as in an offloading situation), this name can be used |
| 4214 |
for lookup purposes, such as in the SYCL Integration Header. |
| 4215 |
|
| 4216 |
The value of this builtin is computed entirely at compile time, so it can be |
| 4217 |
used in constant expressions. This value encodes lambda functions based on a |
| 4218 |
stable numbering order in which they appear in their local declaration contexts. |
| 4219 |
Once this builtin is evaluated in a constexpr context, it is erroneous to use |
| 4220 |
it in an instantiation which changes its value. |
| 4221 |
|
| 4222 |
In order to produce the unique name, the current implementation of the builtin |
| 4223 |
uses Itanium mangling even if the host compilation uses a different name |
| 4224 |
mangling scheme at runtime. The mangler marks all the lambdas required to name |
| 4225 |
the SYCL kernel and emits a stable local ordering of the respective lambdas. |
| 4226 |
The resulting pattern is demanglable. When non-lambda types are passed to the |
| 4227 |
builtin, the mangler emits their usual pattern without any special treatment. |
| 4228 |
|
| 4229 |
**Syntax**: |
| 4230 |
|
| 4231 |
.. code-block:: c |
| 4232 |
|
| 4233 |
// Computes a unique stable name for the given type. |
| 4234 |
constexpr const char * __builtin_sycl_unique_stable_name( type-id ); |
| 4235 |
|
| 4236 |
``__builtin_popcountg`` |
| 4237 |
----------------------- |
| 4238 |
|
| 4239 |
``__builtin_popcountg`` returns the number of 1 bits in the argument. The |
| 4240 |
argument can be of any unsigned integer type or fixed boolean vector. |
| 4241 |
|
| 4242 |
**Syntax**: |
| 4243 |
|
| 4244 |
.. code-block:: c++ |
| 4245 |
|
| 4246 |
int __builtin_popcountg(type x) |
| 4247 |
|
| 4248 |
**Examples**: |
| 4249 |
|
| 4250 |
.. code-block:: c++ |
| 4251 |
|
| 4252 |
unsigned int x = 1; |
| 4253 |
int x_pop = __builtin_popcountg(x); |
| 4254 |
|
| 4255 |
unsigned long y = 3; |
| 4256 |
int y_pop = __builtin_popcountg(y); |
| 4257 |
|
| 4258 |
unsigned _BitInt(128) z = 7; |
| 4259 |
int z_pop = __builtin_popcountg(z); |
| 4260 |
|
| 4261 |
**Description**: |
| 4262 |
|
| 4263 |
``__builtin_popcountg`` is meant to be a type-generic alternative to the |
| 4264 |
``__builtin_popcount{,l,ll}`` builtins, with support for other integer types, |
| 4265 |
such as ``unsigned __int128`` and C23 ``unsigned _BitInt(N)``. |
| 4266 |
|
| 4267 |
``__builtin_clzg`` and ``__builtin_ctzg`` |
| 4268 |
----------------------------------------- |
| 4269 |
|
| 4270 |
``__builtin_clzg`` (respectively ``__builtin_ctzg``) returns the number of |
| 4271 |
leading (respectively trailing) 0 bits in the first argument. The first argument |
| 4272 |
can be of any unsigned integer type or fixed boolean vector. |
| 4273 |
|
| 4274 |
For boolean vectors, these builtins interpret the vector like a bit-field where |
| 4275 |
the ith element of the vector is bit i of the bit-field, counting from the |
| 4276 |
least significant end. ``__builtin_clzg`` returns the number of zero elements at |
| 4277 |
the end of the vector, while ``__builtin_ctzg`` returns the number of zero |
| 4278 |
elements at the start of the vector. |
| 4279 |
|
| 4280 |
If the first argument is 0 and an optional second argument of ``int`` type is |
| 4281 |
provided, then the second argument is returned. If the first argument is 0, but |
| 4282 |
only one argument is provided, then the behavior is undefined. |
| 4283 |
|
| 4284 |
**Syntax**: |
| 4285 |
|
| 4286 |
.. code-block:: c++ |
| 4287 |
|
| 4288 |
int __builtin_clzg(type x[, int fallback]) |
| 4289 |
int __builtin_ctzg(type x[, int fallback]) |
| 4290 |
|
| 4291 |
**Examples**: |
| 4292 |
|
| 4293 |
.. code-block:: c++ |
| 4294 |
|
| 4295 |
unsigned int x = 1; |
| 4296 |
int x_lz = __builtin_clzg(x); |
| 4297 |
int x_tz = __builtin_ctzg(x); |
| 4298 |
|
| 4299 |
unsigned long y = 2; |
| 4300 |
int y_lz = __builtin_clzg(y); |
| 4301 |
int y_tz = __builtin_ctzg(y); |
| 4302 |
|
| 4303 |
unsigned _BitInt(128) z = 4; |
| 4304 |
int z_lz = __builtin_clzg(z); |
| 4305 |
int z_tz = __builtin_ctzg(z); |
| 4306 |
|
| 4307 |
**Description**: |
| 4308 |
|
| 4309 |
``__builtin_clzg`` (respectively ``__builtin_ctzg``) is meant to be a |
| 4310 |
type-generic alternative to the ``__builtin_clz{,l,ll}`` (respectively |
| 4311 |
``__builtin_ctz{,l,ll}``) builtins, with support for other integer types, such |
| 4312 |
as ``unsigned __int128`` and C23 ``unsigned _BitInt(N)``. |
| 4313 |
|
| 4314 |
``__builtin_counted_by_ref`` |
| 4315 |
---------------------------- |
| 4316 |
|
| 4317 |
``__builtin_counted_by_ref`` returns a pointer to the count field from the |
| 4318 |
``counted_by`` attribute. |
| 4319 |
|
| 4320 |
The argument must be a flexible array member or a pointer with the ``counted_by`` |
| 4321 |
attribute. If the argument doesn't have the ``counted_by`` attribute, the builtin |
| 4322 |
returns ``(void *)0``. |
| 4323 |
|
| 4324 |
**Syntax**: |
| 4325 |
|
| 4326 |
.. code-block:: c |
| 4327 |
|
| 4328 |
T *__builtin_counted_by_ref(void *array) |
| 4329 |
|
| 4330 |
**Examples**: |
| 4331 |
|
| 4332 |
.. code-block:: c |
| 4333 |
|
| 4334 |
#define alloc(P, FAM, COUNT) ({ \ |
| 4335 |
size_t __ignored_assignment; \ |
| 4336 |
typeof(P) __p = NULL; \ |
| 4337 |
__p = malloc(MAX(sizeof(*__p), \ |
| 4338 |
sizeof(*__p) + sizeof(*__p->FAM) * COUNT)); \ |
| 4339 |
\ |
| 4340 |
*_Generic( \ |
| 4341 |
__builtin_counted_by_ref(__p->FAM), \ |
| 4342 |
void *: &__ignored_assignment, \ |
| 4343 |
default: __builtin_counted_by_ref(__p->FAM)) = COUNT; \ |
| 4344 |
\ |
| 4345 |
__p; \ |
| 4346 |
}) |
| 4347 |
|
| 4348 |
**Description**: |
| 4349 |
|
| 4350 |
The ``__builtin_counted_by_ref`` builtin allows the programmer to prevent a |
| 4351 |
common error associated with the ``counted_by`` attribute. When using the |
| 4352 |
``counted_by`` attribute, the ``count`` field **must** be set before the |
| 4353 |
flexible array member or pointer can be accessed. Otherwise, the sanitizers may |
| 4354 |
view such accesses as false positives. For instance, it's not uncommon for |
| 4355 |
programmers to initialize the flexible array before setting the ``count`` field: |
| 4356 |
|
| 4357 |
.. code-block:: c |
| 4358 |
|
| 4359 |
struct s { |
| 4360 |
int dummy; |
| 4361 |
short count; |
| 4362 |
long array[] __attribute__((counted_by(count))); |
| 4363 |
}; |
| 4364 |
|
| 4365 |
struct s *ptr = malloc(sizeof(struct s) + sizeof(long) * COUNT); |
| 4366 |
|
| 4367 |
for (int i = 0; i < COUNT; ++i) |
| 4368 |
ptr->array[i] = i; |
| 4369 |
|
| 4370 |
ptr->count = COUNT; |
| 4371 |
|
| 4372 |
Enforcing the rule that ``ptr->count = COUNT;`` must occur after every |
| 4373 |
allocation of a struct with a ``counted_by`` member is prone to failure in large |
| 4374 |
code bases. This builtin mitigates this for allocators (like in Linux) that are |
| 4375 |
implemented in a way where the counter assignment can happen automatically. |
| 4376 |
|
| 4377 |
**Note:** The value returned by ``__builtin_counted_by_ref`` cannot be assigned |
| 4378 |
to a variable, have its address taken, or passed into or returned from a |
| 4379 |
function, because doing so violates bounds safety conventions. |
| 4380 |
|
| 4381 |
.. _builtin_stack_address-doc: |
| 4382 |
|
| 4383 |
``__builtin_stack_address`` |
| 4384 |
--------------------------- |
| 4385 |
|
| 4386 |
``__builtin_stack_address`` returns the address that separates the current |
| 4387 |
function's (i.e. the one calling the builtin) stack space and the region of the |
| 4388 |
stack that may be modified by called functions. The semantics match those of |
| 4389 |
GCC's builtin of the same name. |
| 4390 |
|
| 4391 |
**Syntax**: |
| 4392 |
|
| 4393 |
.. code-block:: c++ |
| 4394 |
|
| 4395 |
void *__builtin_stack_address() |
| 4396 |
|
| 4397 |
**Example**: |
| 4398 |
|
| 4399 |
.. code-block:: c++ |
| 4400 |
|
| 4401 |
void *sp = __builtin_stack_address(); |
| 4402 |
|
| 4403 |
**Description**: |
| 4404 |
|
| 4405 |
The address returned by ``__builtin_stack_address`` identifies the starting |
| 4406 |
address of the stack region that may be used by called functions. |
| 4407 |
|
| 4408 |
On some architectures (e.g. x86), it's sufficient to return the value in the |
| 4409 |
stack pointer register directly. On others (e.g. SPARCv9), adjustments are |
| 4410 |
required to the value of the stack pointer register. |
| 4411 |
``__builtin_stack_address`` performs the necessary adjustments and returns the |
| 4412 |
correct boundary address. |
| 4413 |
|
| 4414 |
Multiprecision Arithmetic Builtins |
| 4415 |
---------------------------------- |
| 4416 |
|
| 4417 |
Clang provides a set of builtins which expose multiprecision arithmetic in a |
| 4418 |
manner amenable to C. They all have the following form: |
| 4419 |
|
| 4420 |
.. code-block:: c |
| 4421 |
|
| 4422 |
unsigned x = ..., y = ..., carryin = ..., carryout; |
| 4423 |
unsigned sum = __builtin_addc(x, y, carryin, &carryout); |
| 4424 |
|
| 4425 |
Thus one can form a multiprecision addition chain in the following manner: |
| 4426 |
|
| 4427 |
.. code-block:: c |
| 4428 |
|
| 4429 |
unsigned *x, *y, *z, carryin=0, carryout; |
| 4430 |
z[0] = __builtin_addc(x[0], y[0], carryin, &carryout); |
| 4431 |
carryin = carryout; |
| 4432 |
z[1] = __builtin_addc(x[1], y[1], carryin, &carryout); |
| 4433 |
carryin = carryout; |
| 4434 |
z[2] = __builtin_addc(x[2], y[2], carryin, &carryout); |
| 4435 |
carryin = carryout; |
| 4436 |
z[3] = __builtin_addc(x[3], y[3], carryin, &carryout); |
| 4437 |
|
| 4438 |
The complete list of builtins are: |
| 4439 |
|
| 4440 |
.. code-block:: c |
| 4441 |
|
| 4442 |
unsigned char __builtin_addcb (unsigned char x, unsigned char y, unsigned char carryin, unsigned char *carryout); |
| 4443 |
unsigned short __builtin_addcs (unsigned short x, unsigned short y, unsigned short carryin, unsigned short *carryout); |
| 4444 |
unsigned __builtin_addc (unsigned x, unsigned y, unsigned carryin, unsigned *carryout); |
| 4445 |
unsigned long __builtin_addcl (unsigned long x, unsigned long y, unsigned long carryin, unsigned long *carryout); |
| 4446 |
unsigned long long __builtin_addcll(unsigned long long x, unsigned long long y, unsigned long long carryin, unsigned long long *carryout); |
| 4447 |
unsigned char __builtin_subcb (unsigned char x, unsigned char y, unsigned char carryin, unsigned char *carryout); |
| 4448 |
unsigned short __builtin_subcs (unsigned short x, unsigned short y, unsigned short carryin, unsigned short *carryout); |
| 4449 |
unsigned __builtin_subc (unsigned x, unsigned y, unsigned carryin, unsigned *carryout); |
| 4450 |
unsigned long __builtin_subcl (unsigned long x, unsigned long y, unsigned long carryin, unsigned long *carryout); |
| 4451 |
unsigned long long __builtin_subcll(unsigned long long x, unsigned long long y, unsigned long long carryin, unsigned long long *carryout); |
| 4452 |
|
| 4453 |
Checked Arithmetic Builtins |
| 4454 |
--------------------------- |
| 4455 |
|
| 4456 |
Clang provides a set of builtins that implement checked arithmetic for security |
| 4457 |
critical applications in a manner that is fast and easily expressible in C. As |
| 4458 |
an example of their usage: |
| 4459 |
|
| 4460 |
.. code-block:: c |
| 4461 |
|
| 4462 |
errorcode_t security_critical_application(...) { |
| 4463 |
unsigned x, y, result; |
| 4464 |
... |
| 4465 |
if (__builtin_mul_overflow(x, y, &result)) |
| 4466 |
return kErrorCodeHackers; |
| 4467 |
... |
| 4468 |
use_multiply(result); |
| 4469 |
... |
| 4470 |
} |
| 4471 |
|
| 4472 |
Clang provides the following checked arithmetic builtins: |
| 4473 |
|
| 4474 |
.. code-block:: c |
| 4475 |
|
| 4476 |
bool __builtin_add_overflow (type1 x, type2 y, type3 *sum); |
| 4477 |
bool __builtin_sub_overflow (type1 x, type2 y, type3 *diff); |
| 4478 |
bool __builtin_mul_overflow (type1 x, type2 y, type3 *prod); |
| 4479 |
bool __builtin_uadd_overflow (unsigned x, unsigned y, unsigned *sum); |
| 4480 |
bool __builtin_uaddl_overflow (unsigned long x, unsigned long y, unsigned long *sum); |
| 4481 |
bool __builtin_uaddll_overflow(unsigned long long x, unsigned long long y, unsigned long long *sum); |
| 4482 |
bool __builtin_usub_overflow (unsigned x, unsigned y, unsigned *diff); |
| 4483 |
bool __builtin_usubl_overflow (unsigned long x, unsigned long y, unsigned long *diff); |
| 4484 |
bool __builtin_usubll_overflow(unsigned long long x, unsigned long long y, unsigned long long *diff); |
| 4485 |
bool __builtin_umul_overflow (unsigned x, unsigned y, unsigned *prod); |
| 4486 |
bool __builtin_umull_overflow (unsigned long x, unsigned long y, unsigned long *prod); |
| 4487 |
bool __builtin_umulll_overflow(unsigned long long x, unsigned long long y, unsigned long long *prod); |
| 4488 |
bool __builtin_sadd_overflow (int x, int y, int *sum); |
| 4489 |
bool __builtin_saddl_overflow (long x, long y, long *sum); |
| 4490 |
bool __builtin_saddll_overflow(long long x, long long y, long long *sum); |
| 4491 |
bool __builtin_ssub_overflow (int x, int y, int *diff); |
| 4492 |
bool __builtin_ssubl_overflow (long x, long y, long *diff); |
| 4493 |
bool __builtin_ssubll_overflow(long long x, long long y, long long *diff); |
| 4494 |
bool __builtin_smul_overflow (int x, int y, int *prod); |
| 4495 |
bool __builtin_smull_overflow (long x, long y, long *prod); |
| 4496 |
bool __builtin_smulll_overflow(long long x, long long y, long long *prod); |
| 4497 |
|
| 4498 |
Each builtin performs the specified mathematical operation on the |
| 4499 |
first two arguments and stores the result in the third argument. If |
| 4500 |
possible, the result will be equal to mathematically-correct result |
| 4501 |
and the builtin will return 0. Otherwise, the builtin will return |
| 4502 |
1 and the result will be equal to the unique value that is equivalent |
| 4503 |
to the mathematically-correct result modulo two raised to the *k* |
| 4504 |
power, where *k* is the number of bits in the result type. The |
| 4505 |
behavior of these builtins is well-defined for all argument values. |
| 4506 |
|
| 4507 |
The first three builtins work generically for operands of any integer type, |
| 4508 |
including boolean types. The operands need not have the same type as each |
| 4509 |
other, or as the result. The other builtins may implicitly promote or |
| 4510 |
convert their operands before performing the operation. |
| 4511 |
|
| 4512 |
Query for this feature with ``__has_builtin(__builtin_add_overflow)``, etc. |
| 4513 |
|
| 4514 |
Floating point builtins |
| 4515 |
--------------------------------------- |
| 4516 |
|
| 4517 |
``__builtin_isfpclass`` |
| 4518 |
----------------------- |
| 4519 |
|
| 4520 |
``__builtin_isfpclass`` is used to test if the specified floating-point values |
| 4521 |
fall into one of the specified floating-point classes. |
| 4522 |
|
| 4523 |
**Syntax**: |
| 4524 |
|
| 4525 |
.. code-block:: c++ |
| 4526 |
|
| 4527 |
int __builtin_isfpclass(fp_type expr, int mask) |
| 4528 |
int_vector __builtin_isfpclass(fp_vector expr, int mask) |
| 4529 |
|
| 4530 |
**Example of use**: |
| 4531 |
|
| 4532 |
.. code-block:: c++ |
| 4533 |
|
| 4534 |
if (__builtin_isfpclass(x, 448)) { |
| 4535 |
// `x` is positive finite value |
| 4536 |
... |
| 4537 |
} |
| 4538 |
|
| 4539 |
**Description**: |
| 4540 |
|
| 4541 |
The ``__builtin_isfpclass()`` builtin is a generalization of functions ``isnan``, |
| 4542 |
``isinf``, ``isfinite`` and some others defined by the C standard. It tests if |
| 4543 |
the floating-point value, specified by the first argument, falls into any of data |
| 4544 |
classes, specified by the second argument. The latter is an integer constant |
| 4545 |
bitmask expression, in which each data class is represented by a bit |
| 4546 |
using the encoding: |
| 4547 |
|
| 4548 |
========== =================== ====================== |
| 4549 |
Mask value Data class Macro |
| 4550 |
========== =================== ====================== |
| 4551 |
0x0001 Signaling NaN __FPCLASS_SNAN |
| 4552 |
0x0002 Quiet NaN __FPCLASS_QNAN |
| 4553 |
0x0004 Negative infinity __FPCLASS_NEGINF |
| 4554 |
0x0008 Negative normal __FPCLASS_NEGNORMAL |
| 4555 |
0x0010 Negative subnormal __FPCLASS_NEGSUBNORMAL |
| 4556 |
0x0020 Negative zero __FPCLASS_NEGZERO |
| 4557 |
0x0040 Positive zero __FPCLASS_POSZERO |
| 4558 |
0x0080 Positive subnormal __FPCLASS_POSSUBNORMAL |
| 4559 |
0x0100 Positive normal __FPCLASS_POSNORMAL |
| 4560 |
0x0200 Positive infinity __FPCLASS_POSINF |
| 4561 |
========== =================== ====================== |
| 4562 |
|
| 4563 |
For convenience preprocessor defines macros for these values. The function |
| 4564 |
returns 1 if ``expr`` falls into one of the specified data classes, 0 otherwise. |
| 4565 |
|
| 4566 |
In the example above the mask value 448 (0x1C0) contains the bits selecting |
| 4567 |
positive zero, positive subnormal and positive normal classes. |
| 4568 |
``__builtin_isfpclass(x, 448)`` would return true only if ``x`` if of any of |
| 4569 |
these data classes. Using suitable mask value, the function can implement any of |
| 4570 |
the standard classification functions, for example, ``__builtin_isfpclass(x, 3)`` |
| 4571 |
is identical to ``isnan``,``__builtin_isfpclass(x, 504)`` - to ``isfinite`` |
| 4572 |
and so on. |
| 4573 |
|
| 4574 |
If the first argument is a vector, the function is equivalent to the set of |
| 4575 |
scalar calls of ``__builtin_isfpclass`` applied to the input elementwise. |
| 4576 |
|
| 4577 |
The result of ``__builtin_isfpclass`` is a boolean value, if the first argument |
| 4578 |
is a scalar, or an integer vector with the same element count as the first |
| 4579 |
argument. The element type in this vector has the same bit length as the |
| 4580 |
element of the first argument type. |
| 4581 |
|
| 4582 |
This function never raises floating-point exceptions and does not canonicalize |
| 4583 |
its input. The floating-point argument is not promoted, its data class is |
| 4584 |
determined based on its representation in its actual semantic type. |
| 4585 |
|
| 4586 |
``__builtin_canonicalize`` |
| 4587 |
-------------------------- |
| 4588 |
|
| 4589 |
.. code-block:: c |
| 4590 |
|
| 4591 |
double __builtin_canonicalize(double); |
| 4592 |
float __builtin_canonicalizef(float); |
| 4593 |
long double __builtin_canonicalizel(long double); |
| 4594 |
|
| 4595 |
Returns the platform specific canonical encoding of a floating point |
| 4596 |
number. This canonicalization is useful for implementing certain |
| 4597 |
numeric primitives such as frexp. See `LLVM canonicalize intrinsic |
| 4598 |
<https://llvm.org/docs/LangRef.html#llvm-canonicalize-intrinsic>`_ for |
| 4599 |
more information on the semantics. |
| 4600 |
|
| 4601 |
``__builtin_flt_rounds`` and ``__builtin_set_flt_rounds`` |
| 4602 |
--------------------------------------------------------- |
| 4603 |
|
| 4604 |
.. code-block:: c |
| 4605 |
|
| 4606 |
int __builtin_flt_rounds(); |
| 4607 |
void __builtin_set_flt_rounds(int); |
| 4608 |
|
| 4609 |
Returns and sets current floating point rounding mode. The encoding of returned |
| 4610 |
values and input parameters is same as the result of FLT_ROUNDS, specified by C |
| 4611 |
standard: |
| 4612 |
- ``0`` - toward zero |
| 4613 |
- ``1`` - to nearest, ties to even |
| 4614 |
- ``2`` - toward positive infinity |
| 4615 |
- ``3`` - toward negative infinity |
| 4616 |
- ``4`` - to nearest, ties away from zero |
| 4617 |
The effect of passing some other value to ``__builtin_flt_rounds`` is |
| 4618 |
implementation-defined. ``__builtin_set_flt_rounds`` is currently only supported |
| 4619 |
to work on x86, x86_64, powerpc, powerpc64, Arm and AArch64 targets. These builtins |
| 4620 |
read and modify the floating-point environment, which is not always allowed and may |
| 4621 |
have unexpected behavior. Please see the section on `Accessing the floating point environment <https://clang.llvm.org/docs/UsersManual.html#accessing-the-floating-point-environment>`_ for more information. |
| 4622 |
|
| 4623 |
String builtins |
| 4624 |
--------------- |
| 4625 |
|
| 4626 |
Clang provides constant expression evaluation support for builtins forms of |
| 4627 |
the following functions from the C standard library headers |
| 4628 |
``<string.h>`` and ``<wchar.h>``: |
| 4629 |
|
| 4630 |
* ``memchr`` |
| 4631 |
* ``memcmp`` (and its deprecated BSD / POSIX alias ``bcmp``) |
| 4632 |
* ``strchr`` |
| 4633 |
* ``strcmp`` |
| 4634 |
* ``strlen`` |
| 4635 |
* ``strncmp`` |
| 4636 |
* ``wcschr`` |
| 4637 |
* ``wcscmp`` |
| 4638 |
* ``wcslen`` |
| 4639 |
* ``wcsncmp`` |
| 4640 |
* ``wmemchr`` |
| 4641 |
* ``wmemcmp`` |
| 4642 |
|
| 4643 |
In each case, the builtin form has the name of the C library function prefixed |
| 4644 |
by ``__builtin_``. Example: |
| 4645 |
|
| 4646 |
.. code-block:: c |
| 4647 |
|
| 4648 |
void *p = __builtin_memchr("foobar", 'b', 5); |
| 4649 |
|
| 4650 |
In addition to the above, one further builtin is provided: |
| 4651 |
|
| 4652 |
.. code-block:: c |
| 4653 |
|
| 4654 |
char *__builtin_char_memchr(const char *haystack, int needle, size_t size); |
| 4655 |
|
| 4656 |
``__builtin_char_memchr(a, b, c)`` is identical to |
| 4657 |
``(char*)__builtin_memchr(a, b, c)`` except that its use is permitted within |
| 4658 |
constant expressions in C++11 onwards (where a cast from ``void*`` to ``char*`` |
| 4659 |
is disallowed in general). |
| 4660 |
|
| 4661 |
Constant evaluation support for the ``__builtin_mem*`` functions is provided |
| 4662 |
only for arrays of ``char``, ``signed char``, ``unsigned char``, or ``char8_t``, |
| 4663 |
despite these functions accepting an argument of type ``const void*``. |
| 4664 |
|
| 4665 |
Support for constant expression evaluation for the above builtins can be detected |
| 4666 |
with ``__has_feature(cxx_constexpr_string_builtins)``. |
| 4667 |
|
| 4668 |
Variadic function builtins |
| 4669 |
-------------------------- |
| 4670 |
|
| 4671 |
Clang provides several builtins for working with variadic functions from the C |
| 4672 |
standard library ``<stdarg.h>`` header: |
| 4673 |
|
| 4674 |
* ``__builtin_va_list`` |
| 4675 |
|
| 4676 |
A predefined typedef for the target-specific ``va_list`` type. It is undefined |
| 4677 |
behavior to use a byte-wise copy of this type produced by calling ``memcpy``, |
| 4678 |
``memmove``, or similar. Valid explicit copies are only produced by calling |
| 4679 |
``va_copy`` or ``__builtin_va_copy``. |
| 4680 |
|
| 4681 |
* ``void __builtin_va_start(__builtin_va_list list, <parameter-name>)`` |
| 4682 |
|
| 4683 |
A builtin function for the target-specific ``va_start`` function-like macro. |
| 4684 |
The ``parameter-name`` argument is the name of the parameter preceding the |
| 4685 |
ellipsis (``...``) in the function signature. Alternatively, in C23 mode or |
| 4686 |
later, it may be the integer literal ``0`` if there is no parameter preceding |
| 4687 |
the ellipsis. This function initializes the given ``__builtin_va_list`` object. |
| 4688 |
It is undefined behavior to call this function on an already initialized |
| 4689 |
``__builtin_va_list`` object. |
| 4690 |
|
| 4691 |
* ``void __builtin_c23_va_start(__builtin_va_list list, ...)`` |
| 4692 |
|
| 4693 |
A builtin function for the target-specific ``va_start`` function-like macro, |
| 4694 |
available only in C23 and later. The builtin accepts zero or one argument for |
| 4695 |
the ellipsis (``...``). If such an argument is provided, it should be the name |
| 4696 |
of the parameter preceding the ellipsis, which is used for compatibility with |
| 4697 |
C versions before C23. It is an error to provide two or more variadic arguments. |
| 4698 |
This function initializes the given ``__builtin_va_list`` object. It is |
| 4699 |
undefined behavior to call this function on an already initialized |
| 4700 |
``__builtin_va_list`` object. |
| 4701 |
|
| 4702 |
* ``void __builtin_va_end(__builtin_va_list list)`` |
| 4703 |
|
| 4704 |
A builtin function for the target-specific ``va_end`` function-like macro. This |
| 4705 |
function finalizes the given ``__builtin_va_list`` object such that it is no |
| 4706 |
longer usable unless re-initialized with a call to ``__builtin_va_start`` or |
| 4707 |
``__builtin_va_copy``. It is undefined behavior to call this function with a |
| 4708 |
``list`` that has not been initialized by either ``__builtin_va_start`` or |
| 4709 |
``__builtin_va_copy``. |
| 4710 |
|
| 4711 |
* ``<type-name> __builtin_va_arg(__builtin_va_list list, <type-name>)`` |
| 4712 |
|
| 4713 |
A builtin function for the target-specific ``va_arg`` function-like macro. This |
| 4714 |
function returns the value of the next variadic argument to the call. It is |
| 4715 |
undefined behavior to call this builtin when there is no next variadic argument |
| 4716 |
to retrieve or if the next variadic argument does not have a type compatible |
| 4717 |
with the given ``type-name``. The return type of the function is the |
| 4718 |
``type-name`` given as the second argument. It is undefined behavior to call |
| 4719 |
this function with a ``list`` that has not been initialized by either |
| 4720 |
``__builtin_va_start`` or ``__builtin_va_copy``. |
| 4721 |
|
| 4722 |
* ``void __builtin_va_copy(__builtin_va_list dest, __builtin_va_list src)`` |
| 4723 |
|
| 4724 |
A builtin function for the target-specific ``va_copy`` function-like macro. |
| 4725 |
This function initializes ``dest`` as a copy of ``src``. It is undefined |
| 4726 |
behavior to call this function with an already initialized ``dest`` argument. |
| 4727 |
|
| 4728 |
Memory builtins |
| 4729 |
--------------- |
| 4730 |
|
| 4731 |
Clang provides constant expression evaluation support for builtin forms of the |
| 4732 |
following functions from the C standard library headers |
| 4733 |
``<string.h>`` and ``<wchar.h>``: |
| 4734 |
|
| 4735 |
* ``memcpy`` |
| 4736 |
* ``memmove`` |
| 4737 |
* ``wmemcpy`` |
| 4738 |
* ``wmemmove`` |
| 4739 |
|
| 4740 |
In each case, the builtin form has the name of the C library function prefixed |
| 4741 |
by ``__builtin_``. |
| 4742 |
|
| 4743 |
Constant evaluation support is only provided when the source and destination |
| 4744 |
are pointers to arrays with the same trivially copyable element type, and the |
| 4745 |
given size is an exact multiple of the element size that is no greater than |
| 4746 |
the number of elements accessible through the source and destination operands. |
| 4747 |
|
| 4748 |
Guaranteed inlined copy |
| 4749 |
^^^^^^^^^^^^^^^^^^^^^^^ |
| 4750 |
|
| 4751 |
.. code-block:: c |
| 4752 |
|
| 4753 |
void __builtin_memcpy_inline(void *dst, const void *src, size_t size); |
| 4754 |
|
| 4755 |
|
| 4756 |
``__builtin_memcpy_inline`` has been designed as a building block for efficient |
| 4757 |
``memcpy`` implementations. It is identical to ``__builtin_memcpy`` but also |
| 4758 |
guarantees not to call any external functions. See LLVM IR `llvm.memcpy.inline |
| 4759 |
<https://llvm.org/docs/LangRef.html#llvm-memcpy-inline-intrinsic>`_ intrinsic |
| 4760 |
for more information. |
| 4761 |
|
| 4762 |
This is useful to implement a custom version of ``memcpy``, implement a |
| 4763 |
``libc`` memcpy or work around the absence of a ``libc``. |
| 4764 |
|
| 4765 |
Note that the `size` argument must be a compile time constant. |
| 4766 |
|
| 4767 |
Note that this intrinsic cannot yet be called in a ``constexpr`` context. |
| 4768 |
|
| 4769 |
Guaranteed inlined memset |
| 4770 |
^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 4771 |
|
| 4772 |
.. code-block:: c |
| 4773 |
|
| 4774 |
void __builtin_memset_inline(void *dst, int value, size_t size); |
| 4775 |
|
| 4776 |
|
| 4777 |
``__builtin_memset_inline`` has been designed as a building block for efficient |
| 4778 |
``memset`` implementations. It is identical to ``__builtin_memset`` but also |
| 4779 |
guarantees not to call any external functions. See LLVM IR `llvm.memset.inline |
| 4780 |
<https://llvm.org/docs/LangRef.html#llvm-memset-inline-intrinsic>`_ intrinsic |
| 4781 |
for more information. |
| 4782 |
|
| 4783 |
This is useful to implement a custom version of ``memset``, implement a |
| 4784 |
``libc`` memset or work around the absence of a ``libc``. |
| 4785 |
|
| 4786 |
Note that the `size` argument must be a compile time constant. |
| 4787 |
|
| 4788 |
Note that this intrinsic cannot yet be called in a ``constexpr`` context. |
| 4789 |
|
| 4790 |
``__is_bitwise_cloneable`` |
| 4791 |
-------------------------- |
| 4792 |
|
| 4793 |
A type trait is used to check whether a type can be safely copied by memcpy. |
| 4794 |
|
| 4795 |
**Syntax**: |
| 4796 |
|
| 4797 |
.. code-block:: c++ |
| 4798 |
|
| 4799 |
bool __is_bitwise_cloneable(Type) |
| 4800 |
|
| 4801 |
**Description**: |
| 4802 |
|
| 4803 |
Objects of bitwise cloneable types can be bitwise copied by memcpy/memmove. The |
| 4804 |
Clang compiler warrants that this behavior is well defined, and won't be |
| 4805 |
broken by compiler optimizations and sanitizers. |
| 4806 |
|
| 4807 |
For implicit-lifetime types, the lifetime of the new object is implicitly |
| 4808 |
started after the copy. For other types (e.g., classes with virtual methods), |
| 4809 |
the lifetime isn't started, and using the object results in undefined behavior |
| 4810 |
according to the C++ Standard. |
| 4811 |
|
| 4812 |
This builtin can be used in constant expressions. |
| 4813 |
|
| 4814 |
Atomic Min/Max builtins with memory ordering |
| 4815 |
-------------------------------------------- |
| 4816 |
|
| 4817 |
There are two atomic builtins with min/max in-memory comparison and swap. |
| 4818 |
The syntax and semantics are similar to GCC-compatible __atomic_* builtins. |
| 4819 |
|
| 4820 |
* ``__atomic_fetch_min`` |
| 4821 |
* ``__atomic_fetch_max`` |
| 4822 |
|
| 4823 |
The builtins work with signed and unsigned integers and require to specify memory ordering. |
| 4824 |
The return value is the original value that was stored in memory before comparison. |
| 4825 |
|
| 4826 |
Clang provides two additional atomic builtins with incrementing behavior. These |
| 4827 |
builtins perform an unsigned increment or decrement modulo a wrap-around value. |
| 4828 |
|
| 4829 |
* ``__atomic_fetch_uinc`` |
| 4830 |
* ``__atomic_fetch_udec`` |
| 4831 |
|
| 4832 |
See the LLVM IR `atomicrmw <https://llvm.org/docs/LangRef.html#atomicrmw-instruction>`_ |
| 4833 |
instruction for the complete semantics of uinc_wrap and udec_wrap. |
| 4834 |
|
| 4835 |
Atomic memory scopes are designed to assist optimizations for systems with |
| 4836 |
several levels of memory hierarchy like GPUs. The following memory scopes are |
| 4837 |
currently supported: |
| 4838 |
|
| 4839 |
|
| 4840 |
Example: |
| 4841 |
|
| 4842 |
.. code-block:: c |
| 4843 |
|
| 4844 |
unsigned int val = __atomic_fetch_min(unsigned int *pi, unsigned int ui, __ATOMIC_RELAXED); |
| 4845 |
|
| 4846 |
The third argument is one of the memory ordering specifiers ``__ATOMIC_RELAXED``, |
| 4847 |
``__ATOMIC_CONSUME``, ``__ATOMIC_ACQUIRE``, ``__ATOMIC_RELEASE``, |
| 4848 |
``__ATOMIC_ACQ_REL``, or ``__ATOMIC_SEQ_CST`` following C++11 memory model semantics. |
| 4849 |
|
| 4850 |
In terms of acquire-release ordering barriers these two operations are always |
| 4851 |
considered as operations with *load-store* semantics, even when the original value |
| 4852 |
is not actually modified after comparison. |
| 4853 |
|
| 4854 |
.. _langext-__c11_atomic: |
| 4855 |
|
| 4856 |
__c11_atomic builtins |
| 4857 |
--------------------- |
| 4858 |
|
| 4859 |
Clang provides a set of builtins which are intended to be used to implement |
| 4860 |
C11's ``<stdatomic.h>`` header. These builtins provide the semantics of the |
| 4861 |
``_explicit`` form of the corresponding C11 operation, and are named with a |
| 4862 |
``__c11_`` prefix. The supported operations, and the differences from |
| 4863 |
the corresponding C11 operations, are: |
| 4864 |
|
| 4865 |
* ``__c11_atomic_init`` |
| 4866 |
* ``__c11_atomic_thread_fence`` |
| 4867 |
* ``__c11_atomic_signal_fence`` |
| 4868 |
* ``__c11_atomic_is_lock_free`` (The argument is the size of the |
| 4869 |
``_Atomic(...)`` object, instead of its address) |
| 4870 |
* ``__c11_atomic_store`` |
| 4871 |
* ``__c11_atomic_load`` |
| 4872 |
* ``__c11_atomic_exchange`` |
| 4873 |
* ``__c11_atomic_compare_exchange_strong`` |
| 4874 |
* ``__c11_atomic_compare_exchange_weak`` |
| 4875 |
* ``__c11_atomic_fetch_add`` |
| 4876 |
* ``__c11_atomic_fetch_sub`` |
| 4877 |
* ``__c11_atomic_fetch_and`` |
| 4878 |
* ``__c11_atomic_fetch_or`` |
| 4879 |
* ``__c11_atomic_fetch_xor`` |
| 4880 |
* ``__c11_atomic_fetch_nand`` (Nand is not presented in ``<stdatomic.h>``) |
| 4881 |
* ``__c11_atomic_fetch_max`` |
| 4882 |
* ``__c11_atomic_fetch_min`` |
| 4883 |
|
| 4884 |
The macros ``__ATOMIC_RELAXED``, ``__ATOMIC_CONSUME``, ``__ATOMIC_ACQUIRE``, |
| 4885 |
``__ATOMIC_RELEASE``, ``__ATOMIC_ACQ_REL``, and ``__ATOMIC_SEQ_CST`` are |
| 4886 |
provided, with values corresponding to the enumerators of C11's |
| 4887 |
``memory_order`` enumeration. |
| 4888 |
|
| 4889 |
(Note that Clang additionally provides GCC-compatible ``__atomic_*`` |
| 4890 |
builtins and OpenCL 2.0 ``__opencl_atomic_*`` builtins. The OpenCL 2.0 |
| 4891 |
atomic builtins are an explicit form of the corresponding OpenCL 2.0 |
| 4892 |
builtin function, and are named with a ``__opencl_`` prefix. The macros |
| 4893 |
``__OPENCL_MEMORY_SCOPE_WORK_ITEM``, ``__OPENCL_MEMORY_SCOPE_WORK_GROUP``, |
| 4894 |
``__OPENCL_MEMORY_SCOPE_DEVICE``, ``__OPENCL_MEMORY_SCOPE_ALL_SVM_DEVICES``, |
| 4895 |
and ``__OPENCL_MEMORY_SCOPE_SUB_GROUP`` are provided, with values |
| 4896 |
corresponding to the enumerators of OpenCL's ``memory_scope`` enumeration.) |
| 4897 |
|
| 4898 |
__scoped_atomic builtins |
| 4899 |
------------------------ |
| 4900 |
|
| 4901 |
Clang provides a set of atomics taking a memory scope argument. These atomics |
| 4902 |
are identical to the standard GNU / GCC atomic builtins but taking an extra |
| 4903 |
memory scope argument. These are designed to be a generic alternative to the |
| 4904 |
``__opencl_atomic_*`` builtin functions for targets that support atomic memory |
| 4905 |
scopes. |
| 4906 |
|
| 4907 |
* ``__MEMORY_SCOPE_SYSTEM`` |
| 4908 |
* ``__MEMORY_SCOPE_DEVICE`` |
| 4909 |
* ``__MEMORY_SCOPE_WRKGRP`` |
| 4910 |
* ``__MEMORY_SCOPE_CLUSTR`` |
| 4911 |
* ``__MEMORY_SCOPE_WVFRNT`` |
| 4912 |
* ``__MEMORY_SCOPE_SINGLE`` |
| 4913 |
|
| 4914 |
This controls whether or not the atomic operation is ordered with respect to the |
| 4915 |
whole system, the current device, an OpenCL workgroup, wavefront, or just a |
| 4916 |
single thread. If these are used on a target that does not support atomic |
| 4917 |
scopes, then they will behave exactly as the standard GNU atomic builtins. |
| 4918 |
|
| 4919 |
Low-level ARM exclusive memory builtins |
| 4920 |
--------------------------------------- |
| 4921 |
|
| 4922 |
Clang provides overloaded builtins giving direct access to the three key ARM |
| 4923 |
instructions for implementing atomic operations. |
| 4924 |
|
| 4925 |
.. code-block:: c |
| 4926 |
|
| 4927 |
T __builtin_arm_ldrex(const volatile T *addr); |
| 4928 |
T __builtin_arm_ldaex(const volatile T *addr); |
| 4929 |
int __builtin_arm_strex(T val, volatile T *addr); |
| 4930 |
int __builtin_arm_stlex(T val, volatile T *addr); |
| 4931 |
void __builtin_arm_clrex(void); |
| 4932 |
|
| 4933 |
The types ``T`` currently supported are: |
| 4934 |
|
| 4935 |
* Integer types with width at most 64 bits (or 128 bits on AArch64). |
| 4936 |
* Floating-point types |
| 4937 |
* Pointer types. |
| 4938 |
|
| 4939 |
Note that the compiler does not guarantee it will not insert stores which clear |
| 4940 |
the exclusive monitor in between an ``ldrex`` type operation and its paired |
| 4941 |
``strex``. In practice this is only usually a risk when the extra store is on |
| 4942 |
the same cache line as the variable being modified and Clang will only insert |
| 4943 |
stack stores on its own, so it is best not to use these operations on variables |
| 4944 |
with automatic storage duration. |
| 4945 |
|
| 4946 |
Also, loads and stores may be implicit in code written between the ``ldrex`` and |
| 4947 |
``strex``. Clang will not necessarily mitigate the effects of these either, so |
| 4948 |
care should be exercised. |
| 4949 |
|
| 4950 |
For these reasons the higher level atomic primitives should be preferred where |
| 4951 |
possible. |
| 4952 |
|
| 4953 |
Non-temporal load/store builtins |
| 4954 |
-------------------------------- |
| 4955 |
|
| 4956 |
Clang provides overloaded builtins allowing generation of non-temporal memory |
| 4957 |
accesses. |
| 4958 |
|
| 4959 |
.. code-block:: c |
| 4960 |
|
| 4961 |
T __builtin_nontemporal_load(T *addr); |
| 4962 |
void __builtin_nontemporal_store(T value, T *addr); |
| 4963 |
|
| 4964 |
The types ``T`` currently supported are: |
| 4965 |
|
| 4966 |
* Integer types. |
| 4967 |
* Floating-point types. |
| 4968 |
* Vector types. |
| 4969 |
|
| 4970 |
Note that the compiler does not guarantee that non-temporal loads or stores |
| 4971 |
will be used. |
| 4972 |
|
| 4973 |
C++ Coroutines support builtins |
| 4974 |
-------------------------------- |
| 4975 |
|
| 4976 |
.. warning:: |
| 4977 |
This is a work in progress. Compatibility across Clang/LLVM releases is not |
| 4978 |
guaranteed. |
| 4979 |
|
| 4980 |
Clang provides experimental builtins to support C++ Coroutines as defined by |
| 4981 |
https://wg21.link/P0057. The following four are intended to be used by the |
| 4982 |
standard library to implement the ``std::coroutine_handle`` type. |
| 4983 |
|
| 4984 |
**Syntax**: |
| 4985 |
|
| 4986 |
.. code-block:: c |
| 4987 |
|
| 4988 |
void __builtin_coro_resume(void *addr); |
| 4989 |
void __builtin_coro_destroy(void *addr); |
| 4990 |
bool __builtin_coro_done(void *addr); |
| 4991 |
void *__builtin_coro_promise(void *addr, int alignment, bool from_promise) |
| 4992 |
|
| 4993 |
**Example of use**: |
| 4994 |
|
| 4995 |
.. code-block:: c++ |
| 4996 |
|
| 4997 |
template <> struct coroutine_handle<void> { |
| 4998 |
void resume() const { __builtin_coro_resume(ptr); } |
| 4999 |
void destroy() const { __builtin_coro_destroy(ptr); } |
| 5000 |
bool done() const { return __builtin_coro_done(ptr); } |
| 5001 |
// ... |
| 5002 |
protected: |
| 5003 |
void *ptr; |
| 5004 |
}; |
| 5005 |
|
| 5006 |
template <typename Promise> struct coroutine_handle : coroutine_handle<> { |
| 5007 |
// ... |
| 5008 |
Promise &promise() const { |
| 5009 |
return *reinterpret_cast<Promise *>( |
| 5010 |
__builtin_coro_promise(ptr, alignof(Promise), /*from-promise=*/false)); |
| 5011 |
} |
| 5012 |
static coroutine_handle from_promise(Promise &promise) { |
| 5013 |
coroutine_handle p; |
| 5014 |
p.ptr = __builtin_coro_promise(&promise, alignof(Promise), |
| 5015 |
/*from-promise=*/true); |
| 5016 |
return p; |
| 5017 |
} |
| 5018 |
}; |
| 5019 |
|
| 5020 |
|
| 5021 |
Other coroutine builtins are either for internal clang use or for use during |
| 5022 |
development of the coroutine feature. See `Coroutines in LLVM |
| 5023 |
<https://llvm.org/docs/Coroutines.html#intrinsics>`_ for |
| 5024 |
more information on their semantics. Note that builtins matching the intrinsics |
| 5025 |
that take token as the first parameter (llvm.coro.begin, llvm.coro.alloc, |
| 5026 |
llvm.coro.free and llvm.coro.suspend) omit the token parameter and fill it to |
| 5027 |
an appropriate value during the emission. |
| 5028 |
|
| 5029 |
**Syntax**: |
| 5030 |
|
| 5031 |
.. code-block:: c |
| 5032 |
|
| 5033 |
size_t __builtin_coro_size() |
| 5034 |
void *__builtin_coro_frame() |
| 5035 |
void *__builtin_coro_free(void *coro_frame) |
| 5036 |
|
| 5037 |
void *__builtin_coro_id(int align, void *promise, void *fnaddr, void *parts) |
| 5038 |
bool __builtin_coro_alloc() |
| 5039 |
void *__builtin_coro_begin(void *memory) |
| 5040 |
void __builtin_coro_end(void *coro_frame, bool unwind) |
| 5041 |
char __builtin_coro_suspend(bool final) |
| 5042 |
|
| 5043 |
Note that there is no builtin matching the `llvm.coro.save` intrinsic. LLVM |
| 5044 |
automatically will insert one if the first argument to `llvm.coro.suspend` is |
| 5045 |
token `none`. If a user calls `__builtin_suspend`, clang will insert `token none` |
| 5046 |
as the first argument to the intrinsic. |
| 5047 |
|
| 5048 |
Source location builtins |
| 5049 |
------------------------ |
| 5050 |
|
| 5051 |
Clang provides builtins to support C++ standard library implementation |
| 5052 |
of ``std::source_location`` as specified in C++20. With the exception |
| 5053 |
of ``__builtin_COLUMN``, ``__builtin_FILE_NAME`` and ``__builtin_FUNCSIG``, |
| 5054 |
these builtins are also implemented by GCC. |
| 5055 |
|
| 5056 |
**Syntax**: |
| 5057 |
|
| 5058 |
.. code-block:: c |
| 5059 |
|
| 5060 |
const char *__builtin_FILE(); |
| 5061 |
const char *__builtin_FILE_NAME(); // Clang only |
| 5062 |
const char *__builtin_FUNCTION(); |
| 5063 |
const char *__builtin_FUNCSIG(); // Microsoft |
| 5064 |
unsigned __builtin_LINE(); |
| 5065 |
unsigned __builtin_COLUMN(); // Clang only |
| 5066 |
const std::source_location::__impl *__builtin_source_location(); |
| 5067 |
|
| 5068 |
**Example of use**: |
| 5069 |
|
| 5070 |
.. code-block:: c++ |
| 5071 |
|
| 5072 |
void my_assert(bool pred, int line = __builtin_LINE(), // Captures line of caller |
| 5073 |
const char* file = __builtin_FILE(), |
| 5074 |
const char* function = __builtin_FUNCTION()) { |
| 5075 |
if (pred) return; |
| 5076 |
printf("%s:%d assertion failed in function %s\n", file, line, function); |
| 5077 |
std::abort(); |
| 5078 |
} |
| 5079 |
|
| 5080 |
struct MyAggregateType { |
| 5081 |
int x; |
| 5082 |
int line = __builtin_LINE(); // captures line where aggregate initialization occurs |
| 5083 |
}; |
| 5084 |
static_assert(MyAggregateType{42}.line == __LINE__); |
| 5085 |
|
| 5086 |
struct MyClassType { |
| 5087 |
int line = __builtin_LINE(); // captures line of the constructor used during initialization |
| 5088 |
constexpr MyClassType(int) { assert(line == __LINE__); } |
| 5089 |
}; |
| 5090 |
|
| 5091 |
**Description**: |
| 5092 |
|
| 5093 |
The builtins ``__builtin_LINE``, ``__builtin_FUNCTION``, ``__builtin_FUNCSIG``, |
| 5094 |
``__builtin_FILE`` and ``__builtin_FILE_NAME`` return the values, at the |
| 5095 |
"invocation point", for ``__LINE__``, ``__FUNCTION__``, ``__FUNCSIG__``, |
| 5096 |
``__FILE__`` and ``__FILE_NAME__`` respectively. ``__builtin_COLUMN`` similarly |
| 5097 |
returns the column, though there is no corresponding macro. These builtins are |
| 5098 |
constant expressions. |
| 5099 |
|
| 5100 |
When the builtins appear as part of a default function argument the invocation |
| 5101 |
point is the location of the caller. When the builtins appear as part of a |
| 5102 |
default member initializer, the invocation point is the location of the |
| 5103 |
constructor or aggregate initialization used to create the object. Otherwise |
| 5104 |
the invocation point is the same as the location of the builtin. |
| 5105 |
|
| 5106 |
When the invocation point of ``__builtin_FUNCTION`` is not a function scope, the |
| 5107 |
empty string is returned. |
| 5108 |
|
| 5109 |
The builtin ``__builtin_COLUMN`` returns the offset from the start of the line, |
| 5110 |
beginning from column 1. `This may differ from other implementations. |
| 5111 |
<https://eel.is/c++draft/support.srcloc#tab:support.srcloc.current-row-3-column-2-sentence-2>`_ |
| 5112 |
|
| 5113 |
The builtin ``__builtin_source_location`` returns a pointer to constant static |
| 5114 |
data of type ``std::source_location::__impl``. This type must have already been |
| 5115 |
defined, and must contain exactly four fields: ``const char *_M_file_name``, |
| 5116 |
``const char *_M_function_name``, ``<any-integral-type> _M_line``, and |
| 5117 |
``<any-integral-type> _M_column``. The fields will be populated in the same |
| 5118 |
manner as the above four builtins, except that ``_M_function_name`` is populated |
| 5119 |
with ``__PRETTY_FUNCTION__`` rather than ``__FUNCTION__``. |
| 5120 |
|
| 5121 |
|
| 5122 |
Alignment builtins |
| 5123 |
------------------ |
| 5124 |
Clang provides builtins to support checking and adjusting alignment of |
| 5125 |
pointers and integers. |
| 5126 |
These builtins can be used to avoid relying on implementation-defined behavior |
| 5127 |
of arithmetic on integers derived from pointers. |
| 5128 |
Additionally, these builtins retain type information and, unlike bitwise |
| 5129 |
arithmetic, they can perform semantic checking on the alignment value. |
| 5130 |
|
| 5131 |
**Syntax**: |
| 5132 |
|
| 5133 |
.. code-block:: c |
| 5134 |
|
| 5135 |
Type __builtin_align_up(Type value, size_t alignment); |
| 5136 |
Type __builtin_align_down(Type value, size_t alignment); |
| 5137 |
bool __builtin_is_aligned(Type value, size_t alignment); |
| 5138 |
|
| 5139 |
|
| 5140 |
**Example of use**: |
| 5141 |
|
| 5142 |
.. code-block:: c++ |
| 5143 |
|
| 5144 |
char* global_alloc_buffer; |
| 5145 |
void* my_aligned_allocator(size_t alloc_size, size_t alignment) { |
| 5146 |
char* result = __builtin_align_up(global_alloc_buffer, alignment); |
| 5147 |
// result now contains the value of global_alloc_buffer rounded up to the |
| 5148 |
// next multiple of alignment. |
| 5149 |
global_alloc_buffer = result + alloc_size; |
| 5150 |
return result; |
| 5151 |
} |
| 5152 |
|
| 5153 |
void* get_start_of_page(void* ptr) { |
| 5154 |
return __builtin_align_down(ptr, PAGE_SIZE); |
| 5155 |
} |
| 5156 |
|
| 5157 |
void example(char* buffer) { |
| 5158 |
if (__builtin_is_aligned(buffer, 64)) { |
| 5159 |
do_fast_aligned_copy(buffer); |
| 5160 |
} else { |
| 5161 |
do_unaligned_copy(buffer); |
| 5162 |
} |
| 5163 |
} |
| 5164 |
|
| 5165 |
// In addition to pointers, the builtins can also be used on integer types |
| 5166 |
// and are evaluatable inside constant expressions. |
| 5167 |
static_assert(__builtin_align_up(123, 64) == 128, ""); |
| 5168 |
static_assert(__builtin_align_down(123u, 64) == 64u, ""); |
| 5169 |
static_assert(!__builtin_is_aligned(123, 64), ""); |
| 5170 |
|
| 5171 |
|
| 5172 |
**Description**: |
| 5173 |
|
| 5174 |
The builtins ``__builtin_align_up``, ``__builtin_align_down``, return their |
| 5175 |
first argument aligned up/down to the next multiple of the second argument. |
| 5176 |
If the value is already sufficiently aligned, it is returned unchanged. |
| 5177 |
The builtin ``__builtin_is_aligned`` returns whether the first argument is |
| 5178 |
aligned to a multiple of the second argument. |
| 5179 |
All of these builtins expect the alignment to be expressed as a number of bytes. |
| 5180 |
|
| 5181 |
These builtins can be used for all integer types as well as (non-function) |
| 5182 |
pointer types. For pointer types, these builtins operate in terms of the integer |
| 5183 |
address of the pointer and return a new pointer of the same type (including |
| 5184 |
qualifiers such as ``const``) with an adjusted address. |
| 5185 |
When aligning pointers up or down, the resulting value must be within the same |
| 5186 |
underlying allocation or one past the end (see C17 6.5.6p8, C++ [expr.add]). |
| 5187 |
This means that arbitrary integer values stored in pointer-type variables must |
| 5188 |
not be passed to these builtins. For those use cases, the builtins can still be |
| 5189 |
used, but the operation must be performed on the pointer cast to ``uintptr_t``. |
| 5190 |
|
| 5191 |
If Clang can determine that the alignment is not a power of two at compile time, |
| 5192 |
it will result in a compilation failure. If the alignment argument is not a |
| 5193 |
power of two at run time, the behavior of these builtins is undefined. |
| 5194 |
|
| 5195 |
Non-standard C++11 Attributes |
| 5196 |
============================= |
| 5197 |
|
| 5198 |
Clang's non-standard C++11 attributes live in the ``clang`` attribute |
| 5199 |
namespace. |
| 5200 |
|
| 5201 |
Clang supports GCC's ``gnu`` attribute namespace. All GCC attributes which |
| 5202 |
are accepted with the ``__attribute__((foo))`` syntax are also accepted as |
| 5203 |
``[[gnu::foo]]``. This only extends to attributes which are specified by GCC |
| 5204 |
(see the list of `GCC function attributes |
| 5205 |
<https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_, `GCC variable |
| 5206 |
attributes <https://gcc.gnu.org/onlinedocs/gcc/Variable-Attributes.html>`_, and |
| 5207 |
`GCC type attributes |
| 5208 |
<https://gcc.gnu.org/onlinedocs/gcc/Type-Attributes.html>`_). As with the GCC |
| 5209 |
implementation, these attributes must appertain to the *declarator-id* in a |
| 5210 |
declaration, which means they must go either at the start of the declaration or |
| 5211 |
immediately after the name being declared. |
| 5212 |
|
| 5213 |
For example, this applies the GNU ``unused`` attribute to ``a`` and ``f``, and |
| 5214 |
also applies the GNU ``noreturn`` attribute to ``f``. |
| 5215 |
|
| 5216 |
Examples: |
| 5217 |
.. code-block:: c++ |
| 5218 |
|
| 5219 |
[[gnu::unused]] int a, f [[gnu::noreturn]] (); |
| 5220 |
|
| 5221 |
Target-Specific Extensions |
| 5222 |
========================== |
| 5223 |
|
| 5224 |
Clang supports some language features conditionally on some targets. |
| 5225 |
|
| 5226 |
AMDGPU Language Extensions |
| 5227 |
-------------------------- |
| 5228 |
|
| 5229 |
__builtin_amdgcn_fence |
| 5230 |
^^^^^^^^^^^^^^^^^^^^^^ |
| 5231 |
|
| 5232 |
``__builtin_amdgcn_fence`` emits a fence. |
| 5233 |
|
| 5234 |
* ``unsigned`` atomic ordering, e.g., ``__ATOMIC_ACQUIRE`` |
| 5235 |
* ``const char *`` synchronization scope, e.g., ``workgroup`` |
| 5236 |
* Zero or more ``const char *`` address spaces names. |
| 5237 |
|
| 5238 |
The address spaces arguments must be one of the following string literals: |
| 5239 |
|
| 5240 |
* ``"local"`` |
| 5241 |
* ``"global"`` |
| 5242 |
|
| 5243 |
If one or more address space name are provided, the code generator will attempt |
| 5244 |
to emit potentially faster instructions that order access to at least those |
| 5245 |
address spaces. |
| 5246 |
Emitting such instructions may not always be possible and the compiler is free |
| 5247 |
to fence more aggressively. |
| 5248 |
|
| 5249 |
If no address spaces names are provided, all address spaces are fenced. |
| 5250 |
|
| 5251 |
.. code-block:: c++ |
| 5252 |
|
| 5253 |
// Fence all address spaces. |
| 5254 |
__builtin_amdgcn_fence(__ATOMIC_SEQ_CST, "workgroup"); |
| 5255 |
__builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "agent"); |
| 5256 |
|
| 5257 |
// Fence only requested address spaces. |
| 5258 |
__builtin_amdgcn_fence(__ATOMIC_SEQ_CST, "workgroup", "local") |
| 5259 |
__builtin_amdgcn_fence(__ATOMIC_SEQ_CST, "workgroup", "local", "global") |
| 5260 |
|
| 5261 |
__builtin_amdgcn_ballot_w{32,64} |
| 5262 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 5263 |
|
| 5264 |
``__builtin_amdgcn_ballot_w{32,64}`` returns a bitmask that contains its |
| 5265 |
boolean argument as a bit for every lane of the current wave that is currently |
| 5266 |
active (i.e., that is converged with the executing thread), and a 0 bit for |
| 5267 |
every lane that is not active. |
| 5268 |
|
| 5269 |
The result is uniform, i.e., it is the same in every active thread of the wave. |
| 5270 |
|
| 5271 |
__builtin_amdgcn_inverse_ballot_w{32,64} |
| 5272 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 5273 |
|
| 5274 |
Given a wave-uniform bitmask, ``__builtin_amdgcn_inverse_ballot_w{32,64}(mask)`` |
| 5275 |
returns the bit at the position of the current lane. It is almost equivalent to |
| 5276 |
``(mask & (1 << lane_id)) != 0``, except that its behavior is only defined if |
| 5277 |
the given mask has the same value for all active lanes of the current wave. |
| 5278 |
|
| 5279 |
ARM/AArch64 Language Extensions |
| 5280 |
------------------------------- |
| 5281 |
|
| 5282 |
Memory Barrier Intrinsics |
| 5283 |
^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 5284 |
Clang implements the ``__dmb``, ``__dsb`` and ``__isb`` intrinsics as defined |
| 5285 |
in the `Arm C Language Extensions |
| 5286 |
<https://github.com/ARM-software/acle/releases>`_. |
| 5287 |
Note that these intrinsics are implemented as motion barriers that block |
| 5288 |
reordering of memory accesses and side effect instructions. Other instructions |
| 5289 |
like simple arithmetic may be reordered around the intrinsic. If you expect to |
| 5290 |
have no reordering at all, use inline assembly instead. |
| 5291 |
|
| 5292 |
Pointer Authentication |
| 5293 |
^^^^^^^^^^^^^^^^^^^^^^ |
| 5294 |
See :doc:`PointerAuthentication`. |
| 5295 |
|
| 5296 |
X86/X86-64 Language Extensions |
| 5297 |
------------------------------ |
| 5298 |
|
| 5299 |
The X86 backend has these language extensions: |
| 5300 |
|
| 5301 |
Memory references to specified segments |
| 5302 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 5303 |
|
| 5304 |
Annotating a pointer with address space #256 causes it to be code generated |
| 5305 |
relative to the X86 GS segment register, address space #257 causes it to be |
| 5306 |
relative to the X86 FS segment, and address space #258 causes it to be |
| 5307 |
relative to the X86 SS segment. Note that this is a very very low-level |
| 5308 |
feature that should only be used if you know what you're doing (for example in |
| 5309 |
an OS kernel). |
| 5310 |
|
| 5311 |
Here is an example: |
| 5312 |
|
| 5313 |
.. code-block:: c++ |
| 5314 |
|
| 5315 |
#define GS_RELATIVE __attribute__((address_space(256))) |
| 5316 |
int foo(int GS_RELATIVE *P) { |
| 5317 |
return *P; |
| 5318 |
} |
| 5319 |
|
| 5320 |
Which compiles to (on X86-32): |
| 5321 |
|
| 5322 |
.. code-block:: gas |
| 5323 |
|
| 5324 |
_foo: |
| 5325 |
movl 4(%esp), %eax |
| 5326 |
movl %gs:(%eax), %eax |
| 5327 |
ret |
| 5328 |
|
| 5329 |
You can also use the GCC compatibility macros ``__seg_fs`` and ``__seg_gs`` for |
| 5330 |
the same purpose. The preprocessor symbols ``__SEG_FS`` and ``__SEG_GS`` |
| 5331 |
indicate their support. |
| 5332 |
|
| 5333 |
PowerPC Language Extensions |
| 5334 |
--------------------------- |
| 5335 |
|
| 5336 |
Set the Floating Point Rounding Mode |
| 5337 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 5338 |
PowerPC64/PowerPC64le supports the builtin function ``__builtin_setrnd`` to set |
| 5339 |
the floating point rounding mode. This function will use the least significant |
| 5340 |
two bits of integer argument to set the floating point rounding mode. |
| 5341 |
|
| 5342 |
.. code-block:: c++ |
| 5343 |
|
| 5344 |
double __builtin_setrnd(int mode); |
| 5345 |
|
| 5346 |
The effective values for mode are: |
| 5347 |
|
| 5348 |
- 0 - round to nearest |
| 5349 |
- 1 - round to zero |
| 5350 |
- 2 - round to +infinity |
| 5351 |
- 3 - round to -infinity |
| 5352 |
|
| 5353 |
Note that the mode argument will modulo 4, so if the integer argument is greater |
| 5354 |
than 3, it will only use the least significant two bits of the mode. |
| 5355 |
Namely, ``__builtin_setrnd(102))`` is equal to ``__builtin_setrnd(2)``. |
| 5356 |
|
| 5357 |
PowerPC cache builtins |
| 5358 |
^^^^^^^^^^^^^^^^^^^^^^ |
| 5359 |
|
| 5360 |
The PowerPC architecture specifies instructions implementing cache operations. |
| 5361 |
Clang provides builtins that give direct programmer access to these cache |
| 5362 |
instructions. |
| 5363 |
|
| 5364 |
Currently the following builtins are implemented in clang: |
| 5365 |
|
| 5366 |
``__builtin_dcbf`` copies the contents of a modified block from the data cache |
| 5367 |
to main memory and flushes the copy from the data cache. |
| 5368 |
|
| 5369 |
**Syntax**: |
| 5370 |
|
| 5371 |
.. code-block:: c |
| 5372 |
|
| 5373 |
void __dcbf(const void* addr); /* Data Cache Block Flush */ |
| 5374 |
|
| 5375 |
**Example of Use**: |
| 5376 |
|
| 5377 |
.. code-block:: c |
| 5378 |
|
| 5379 |
int a = 1; |
| 5380 |
__builtin_dcbf (&a); |
| 5381 |
|
| 5382 |
Extensions for Static Analysis |
| 5383 |
============================== |
| 5384 |
|
| 5385 |
Clang supports additional attributes that are useful for documenting program |
| 5386 |
invariants and rules for static analysis tools, such as the `Clang Static |
| 5387 |
Analyzer <https://clang-analyzer.llvm.org/>`_. These attributes are documented |
| 5388 |
in the analyzer's `list of annotations for analysis |
| 5389 |
<analyzer/user-docs/Annotations.html>`__. |
| 5390 |
|
| 5391 |
|
| 5392 |
Extensions for Dynamic Analysis |
| 5393 |
=============================== |
| 5394 |
|
| 5395 |
Use ``__has_feature(address_sanitizer)`` to check if the code is being built |
| 5396 |
with :doc:`AddressSanitizer`. |
| 5397 |
|
| 5398 |
Use ``__has_feature(thread_sanitizer)`` to check if the code is being built |
| 5399 |
with :doc:`ThreadSanitizer`. |
| 5400 |
|
| 5401 |
Use ``__has_feature(memory_sanitizer)`` to check if the code is being built |
| 5402 |
with :doc:`MemorySanitizer`. |
| 5403 |
|
| 5404 |
Use ``__has_feature(dataflow_sanitizer)`` to check if the code is being built |
| 5405 |
with :doc:`DataFlowSanitizer`. |
| 5406 |
|
| 5407 |
Use ``__has_feature(safe_stack)`` to check if the code is being built |
| 5408 |
with :doc:`SafeStack`. |
| 5409 |
|
| 5410 |
|
| 5411 |
Extensions for selectively disabling optimization |
| 5412 |
================================================= |
| 5413 |
|
| 5414 |
Clang provides a mechanism for selectively disabling optimizations in functions |
| 5415 |
and methods. |
| 5416 |
|
| 5417 |
To disable optimizations in a single function definition, the GNU-style or C++11 |
| 5418 |
non-standard attribute ``optnone`` can be used. |
| 5419 |
|
| 5420 |
.. code-block:: c++ |
| 5421 |
|
| 5422 |
// The following functions will not be optimized. |
| 5423 |
// GNU-style attribute |
| 5424 |
__attribute__((optnone)) int foo() { |
| 5425 |
// ... code |
| 5426 |
} |
| 5427 |
// C++11 attribute |
| 5428 |
[[clang::optnone]] int bar() { |
| 5429 |
// ... code |
| 5430 |
} |
| 5431 |
|
| 5432 |
To facilitate disabling optimization for a range of function definitions, a |
| 5433 |
range-based pragma is provided. Its syntax is ``#pragma clang optimize`` |
| 5434 |
followed by ``off`` or ``on``. |
| 5435 |
|
| 5436 |
All function definitions in the region between an ``off`` and the following |
| 5437 |
``on`` will be decorated with the ``optnone`` attribute unless doing so would |
| 5438 |
conflict with explicit attributes already present on the function (e.g., the |
| 5439 |
ones that control inlining). |
| 5440 |
|
| 5441 |
.. code-block:: c++ |
| 5442 |
|
| 5443 |
#pragma clang optimize off |
| 5444 |
// This function will be decorated with optnone. |
| 5445 |
int foo() { |
| 5446 |
// ... code |
| 5447 |
} |
| 5448 |
|
| 5449 |
// optnone conflicts with always_inline, so bar() will not be decorated. |
| 5450 |
__attribute__((always_inline)) int bar() { |
| 5451 |
// ... code |
| 5452 |
} |
| 5453 |
#pragma clang optimize on |
| 5454 |
|
| 5455 |
If no ``on`` is found to close an ``off`` region, the end of the region is the |
| 5456 |
end of the compilation unit. |
| 5457 |
|
| 5458 |
Note that a stray ``#pragma clang optimize on`` does not selectively enable |
| 5459 |
additional optimizations when compiling at low optimization levels. This feature |
| 5460 |
can only be used to selectively disable optimizations. |
| 5461 |
|
| 5462 |
The pragma has an effect on functions only at the point of their definition; for |
| 5463 |
function templates, this means that the state of the pragma at the point of an |
| 5464 |
instantiation is not necessarily relevant. Consider the following example: |
| 5465 |
|
| 5466 |
.. code-block:: c++ |
| 5467 |
|
| 5468 |
template<typename T> T twice(T t) { |
| 5469 |
return 2 * t; |
| 5470 |
} |
| 5471 |
|
| 5472 |
#pragma clang optimize off |
| 5473 |
template<typename T> T thrice(T t) { |
| 5474 |
return 3 * t; |
| 5475 |
} |
| 5476 |
|
| 5477 |
int container(int a, int b) { |
| 5478 |
return twice(a) + thrice(b); |
| 5479 |
} |
| 5480 |
#pragma clang optimize on |
| 5481 |
|
| 5482 |
In this example, the definition of the template function ``twice`` is outside |
| 5483 |
the pragma region, whereas the definition of ``thrice`` is inside the region. |
| 5484 |
The ``container`` function is also in the region and will not be optimized, but |
| 5485 |
it causes the instantiation of ``twice`` and ``thrice`` with an ``int`` type; of |
| 5486 |
these two instantiations, ``twice`` will be optimized (because its definition |
| 5487 |
was outside the region) and ``thrice`` will not be optimized. |
| 5488 |
|
| 5489 |
Clang also implements MSVC's range-based pragma, |
| 5490 |
``#pragma optimize("[optimization-list]", on | off)``. At the moment, Clang only |
| 5491 |
supports an empty optimization list, whereas MSVC supports the arguments, ``s``, |
| 5492 |
``g``, ``t``, and ``y``. Currently, the implementation of ``pragma optimize`` behaves |
| 5493 |
the same as ``#pragma clang optimize``. All functions |
| 5494 |
between ``off`` and ``on`` will be decorated with the ``optnone`` attribute. |
| 5495 |
|
| 5496 |
.. code-block:: c++ |
| 5497 |
|
| 5498 |
#pragma optimize("", off) |
| 5499 |
// This function will be decorated with optnone. |
| 5500 |
void f1() {} |
| 5501 |
|
| 5502 |
#pragma optimize("", on) |
| 5503 |
// This function will be optimized with whatever was specified on |
| 5504 |
// the commandline. |
| 5505 |
void f2() {} |
| 5506 |
|
| 5507 |
// This will warn with Clang's current implementation. |
| 5508 |
#pragma optimize("g", on) |
| 5509 |
void f3() {} |
| 5510 |
|
| 5511 |
For MSVC, an empty optimization list and ``off`` parameter will turn off |
| 5512 |
all optimizations, ``s``, ``g``, ``t``, and ``y``. An empty optimization and |
| 5513 |
``on`` parameter will reset the optimizations to the ones specified on the |
| 5514 |
commandline. |
| 5515 |
|
| 5516 |
.. list-table:: Parameters (unsupported by Clang) |
| 5517 |
|
| 5518 |
* - Parameter |
| 5519 |
- Type of optimization |
| 5520 |
* - g |
| 5521 |
- Deprecated |
| 5522 |
* - s or t |
| 5523 |
- Short or fast sequences of machine code |
| 5524 |
* - y |
| 5525 |
- Enable frame pointers |
| 5526 |
|
| 5527 |
Extensions for loop hint optimizations |
| 5528 |
====================================== |
| 5529 |
|
| 5530 |
The ``#pragma clang loop`` directive is used to specify hints for optimizing the |
| 5531 |
subsequent for, while, do-while, or c++11 range-based for loop. The directive |
| 5532 |
provides options for vectorization, interleaving, predication, unrolling and |
| 5533 |
distribution. Loop hints can be specified before any loop and will be ignored if |
| 5534 |
the optimization is not safe to apply. |
| 5535 |
|
| 5536 |
There are loop hints that control transformations (e.g., vectorization, loop |
| 5537 |
unrolling) and there are loop hints that set transformation options (e.g. |
| 5538 |
``vectorize_width``, ``unroll_count``). Pragmas setting transformation options |
| 5539 |
imply the transformation is enabled, as if it were enabled via the corresponding |
| 5540 |
transformation pragma (e.g., ``vectorize(enable)``). If the transformation is |
| 5541 |
disabled (e.g., ``vectorize(disable)``), that takes precedence over |
| 5542 |
transformations option pragmas implying that transformation. |
| 5543 |
|
| 5544 |
Vectorization, Interleaving, and Predication |
| 5545 |
-------------------------------------------- |
| 5546 |
|
| 5547 |
A vectorized loop performs multiple iterations of the original loop |
| 5548 |
in parallel using vector instructions. The instruction set of the target |
| 5549 |
processor determines which vector instructions are available and their vector |
| 5550 |
widths. This restricts the types of loops that can be vectorized. The vectorizer |
| 5551 |
automatically determines if the loop is safe and profitable to vectorize. A |
| 5552 |
vector instruction cost model is used to select the vector width. |
| 5553 |
|
| 5554 |
Interleaving multiple loop iterations allows modern processors to further |
| 5555 |
improve instruction-level parallelism (ILP) using advanced hardware features, |
| 5556 |
such as multiple execution units and out-of-order execution. The vectorizer uses |
| 5557 |
a cost model that depends on the register pressure and generated code size to |
| 5558 |
select the interleaving count. |
| 5559 |
|
| 5560 |
Vectorization is enabled by ``vectorize(enable)`` and interleaving is enabled |
| 5561 |
by ``interleave(enable)``. This is useful when compiling with ``-Os`` to |
| 5562 |
manually enable vectorization or interleaving. |
| 5563 |
|
| 5564 |
.. code-block:: c++ |
| 5565 |
|
| 5566 |
#pragma clang loop vectorize(enable) |
| 5567 |
#pragma clang loop interleave(enable) |
| 5568 |
for(...) { |
| 5569 |
... |
| 5570 |
} |
| 5571 |
|
| 5572 |
The vector width is specified by |
| 5573 |
``vectorize_width(_value_[, fixed|scalable])``, where _value_ is a positive |
| 5574 |
integer and the type of vectorization can be specified with an optional |
| 5575 |
second parameter. The default for the second parameter is 'fixed' and |
| 5576 |
refers to fixed width vectorization, whereas 'scalable' indicates the |
| 5577 |
compiler should use scalable vectors instead. Another use of vectorize_width |
| 5578 |
is ``vectorize_width(fixed|scalable)`` where the user can hint at the type |
| 5579 |
of vectorization to use without specifying the exact width. In both variants |
| 5580 |
of the pragma the vectorizer may decide to fall back on fixed width |
| 5581 |
vectorization if the target does not support scalable vectors. |
| 5582 |
|
| 5583 |
The interleave count is specified by ``interleave_count(_value_)``, where |
| 5584 |
_value_ is a positive integer. This is useful for specifying the optimal |
| 5585 |
width/count of the set of target architectures supported by your application. |
| 5586 |
|
| 5587 |
.. code-block:: c++ |
| 5588 |
|
| 5589 |
#pragma clang loop vectorize_width(2) |
| 5590 |
#pragma clang loop interleave_count(2) |
| 5591 |
for(...) { |
| 5592 |
... |
| 5593 |
} |
| 5594 |
|
| 5595 |
Specifying a width/count of 1 disables the optimization, and is equivalent to |
| 5596 |
``vectorize(disable)`` or ``interleave(disable)``. |
| 5597 |
|
| 5598 |
Vector predication is enabled by ``vectorize_predicate(enable)``, for example: |
| 5599 |
|
| 5600 |
.. code-block:: c++ |
| 5601 |
|
| 5602 |
#pragma clang loop vectorize(enable) |
| 5603 |
#pragma clang loop vectorize_predicate(enable) |
| 5604 |
for(...) { |
| 5605 |
... |
| 5606 |
} |
| 5607 |
|
| 5608 |
This predicates (masks) all instructions in the loop, which allows the scalar |
| 5609 |
remainder loop (the tail) to be folded into the main vectorized loop. This |
| 5610 |
might be more efficient when vector predication is efficiently supported by the |
| 5611 |
target platform. |
| 5612 |
|
| 5613 |
Loop Unrolling |
| 5614 |
-------------- |
| 5615 |
|
| 5616 |
Unrolling a loop reduces the loop control overhead and exposes more |
| 5617 |
opportunities for ILP. Loops can be fully or partially unrolled. Full unrolling |
| 5618 |
eliminates the loop and replaces it with an enumerated sequence of loop |
| 5619 |
iterations. Full unrolling is only possible if the loop trip count is known at |
| 5620 |
compile time. Partial unrolling replicates the loop body within the loop and |
| 5621 |
reduces the trip count. |
| 5622 |
|
| 5623 |
If ``unroll(enable)`` is specified the unroller will attempt to fully unroll the |
| 5624 |
loop if the trip count is known at compile time. If the fully unrolled code size |
| 5625 |
is greater than an internal limit the loop will be partially unrolled up to this |
| 5626 |
limit. If the trip count is not known at compile time the loop will be partially |
| 5627 |
unrolled with a heuristically chosen unroll factor. |
| 5628 |
|
| 5629 |
.. code-block:: c++ |
| 5630 |
|
| 5631 |
#pragma clang loop unroll(enable) |
| 5632 |
for(...) { |
| 5633 |
... |
| 5634 |
} |
| 5635 |
|
| 5636 |
If ``unroll(full)`` is specified the unroller will attempt to fully unroll the |
| 5637 |
loop if the trip count is known at compile time identically to |
| 5638 |
``unroll(enable)``. However, with ``unroll(full)`` the loop will not be unrolled |
| 5639 |
if the loop count is not known at compile time. |
| 5640 |
|
| 5641 |
.. code-block:: c++ |
| 5642 |
|
| 5643 |
#pragma clang loop unroll(full) |
| 5644 |
for(...) { |
| 5645 |
... |
| 5646 |
} |
| 5647 |
|
| 5648 |
The unroll count can be specified explicitly with ``unroll_count(_value_)`` where |
| 5649 |
_value_ is a positive integer. If this value is greater than the trip count the |
| 5650 |
loop will be fully unrolled. Otherwise the loop is partially unrolled subject |
| 5651 |
to the same code size limit as with ``unroll(enable)``. |
| 5652 |
|
| 5653 |
.. code-block:: c++ |
| 5654 |
|
| 5655 |
#pragma clang loop unroll_count(8) |
| 5656 |
for(...) { |
| 5657 |
... |
| 5658 |
} |
| 5659 |
|
| 5660 |
Unrolling of a loop can be prevented by specifying ``unroll(disable)``. |
| 5661 |
|
| 5662 |
Loop unroll parameters can be controlled by options |
| 5663 |
`-mllvm -unroll-count=n` and `-mllvm -pragma-unroll-threshold=n`. |
| 5664 |
|
| 5665 |
Loop Distribution |
| 5666 |
----------------- |
| 5667 |
|
| 5668 |
Loop Distribution allows splitting a loop into multiple loops. This is |
| 5669 |
beneficial for example when the entire loop cannot be vectorized but some of the |
| 5670 |
resulting loops can. |
| 5671 |
|
| 5672 |
If ``distribute(enable))`` is specified and the loop has memory dependencies |
| 5673 |
that inhibit vectorization, the compiler will attempt to isolate the offending |
| 5674 |
operations into a new loop. This optimization is not enabled by default, only |
| 5675 |
loops marked with the pragma are considered. |
| 5676 |
|
| 5677 |
.. code-block:: c++ |
| 5678 |
|
| 5679 |
#pragma clang loop distribute(enable) |
| 5680 |
for (i = 0; i < N; ++i) { |
| 5681 |
S1: A[i + 1] = A[i] + B[i]; |
| 5682 |
S2: C[i] = D[i] * E[i]; |
| 5683 |
} |
| 5684 |
|
| 5685 |
This loop will be split into two loops between statements S1 and S2. The |
| 5686 |
second loop containing S2 will be vectorized. |
| 5687 |
|
| 5688 |
Loop Distribution is currently not enabled by default in the optimizer because |
| 5689 |
it can hurt performance in some cases. For example, instruction-level |
| 5690 |
parallelism could be reduced by sequentializing the execution of the |
| 5691 |
statements S1 and S2 above. |
| 5692 |
|
| 5693 |
If Loop Distribution is turned on globally with |
| 5694 |
``-mllvm -enable-loop-distribution``, specifying ``distribute(disable)`` can |
| 5695 |
be used the disable it on a per-loop basis. |
| 5696 |
|
| 5697 |
Additional Information |
| 5698 |
---------------------- |
| 5699 |
|
| 5700 |
For convenience multiple loop hints can be specified on a single line. |
| 5701 |
|
| 5702 |
.. code-block:: c++ |
| 5703 |
|
| 5704 |
#pragma clang loop vectorize_width(4) interleave_count(8) |
| 5705 |
for(...) { |
| 5706 |
... |
| 5707 |
} |
| 5708 |
|
| 5709 |
If an optimization cannot be applied any hints that apply to it will be ignored. |
| 5710 |
For example, the hint ``vectorize_width(4)`` is ignored if the loop is not |
| 5711 |
proven safe to vectorize. To identify and diagnose optimization issues use |
| 5712 |
`-Rpass`, `-Rpass-missed`, and `-Rpass-analysis` command line options. See the |
| 5713 |
user guide for details. |
| 5714 |
|
| 5715 |
Extensions to specify floating-point flags |
| 5716 |
==================================================== |
| 5717 |
|
| 5718 |
The ``#pragma clang fp`` pragma allows floating-point options to be specified |
| 5719 |
for a section of the source code. This pragma can only appear at file scope or |
| 5720 |
at the start of a compound statement (excluding comments). When using within a |
| 5721 |
compound statement, the pragma is active within the scope of the compound |
| 5722 |
statement. |
| 5723 |
|
| 5724 |
Currently, the following settings can be controlled with this pragma: |
| 5725 |
|
| 5726 |
``#pragma clang fp reassociate`` allows control over the reassociation |
| 5727 |
of floating point expressions. When enabled, this pragma allows the expression |
| 5728 |
``x + (y + z)`` to be reassociated as ``(x + y) + z``. |
| 5729 |
Reassociation can also occur across multiple statements. |
| 5730 |
This pragma can be used to disable reassociation when it is otherwise |
| 5731 |
enabled for the translation unit with the ``-fassociative-math`` flag. |
| 5732 |
The pragma can take two values: ``on`` and ``off``. |
| 5733 |
|
| 5734 |
.. code-block:: c++ |
| 5735 |
|
| 5736 |
float f(float x, float y, float z) |
| 5737 |
{ |
| 5738 |
// Enable floating point reassociation across statements |
| 5739 |
#pragma clang fp reassociate(on) |
| 5740 |
float t = x + y; |
| 5741 |
float v = t + z; |
| 5742 |
} |
| 5743 |
|
| 5744 |
``#pragma clang fp reciprocal`` allows control over using reciprocal |
| 5745 |
approximations in floating point expressions. When enabled, this |
| 5746 |
pragma allows the expression ``x / y`` to be approximated as ``x * |
| 5747 |
(1.0 / y)``. This pragma can be used to disable reciprocal |
| 5748 |
approximation when it is otherwise enabled for the translation unit |
| 5749 |
with the ``-freciprocal-math`` flag or other fast-math options. The |
| 5750 |
pragma can take two values: ``on`` and ``off``. |
| 5751 |
|
| 5752 |
.. code-block:: c++ |
| 5753 |
|
| 5754 |
float f(float x, float y) |
| 5755 |
{ |
| 5756 |
// Enable floating point reciprocal approximation |
| 5757 |
#pragma clang fp reciprocal(on) |
| 5758 |
return x / y; |
| 5759 |
} |
| 5760 |
|
| 5761 |
``#pragma clang fp contract`` specifies whether the compiler should |
| 5762 |
contract a multiply and an addition (or subtraction) into a fused FMA |
| 5763 |
operation when supported by the target. |
| 5764 |
|
| 5765 |
The pragma can take three values: ``on``, ``fast`` and ``off``. The ``on`` |
| 5766 |
option is identical to using ``#pragma STDC FP_CONTRACT(ON)`` and it allows |
| 5767 |
fusion as specified the language standard. The ``fast`` option allows fusion |
| 5768 |
in cases when the language standard does not make this possible (e.g., across |
| 5769 |
statements in C). |
| 5770 |
|
| 5771 |
.. code-block:: c++ |
| 5772 |
|
| 5773 |
for(...) { |
| 5774 |
#pragma clang fp contract(fast) |
| 5775 |
a = b[i] * c[i]; |
| 5776 |
d[i] += a; |
| 5777 |
} |
| 5778 |
|
| 5779 |
|
| 5780 |
The pragma can also be used with ``off`` which turns FP contraction off for a |
| 5781 |
section of the code. This can be useful when fast contraction is otherwise |
| 5782 |
enabled for the translation unit with the ``-ffp-contract=fast-honor-pragmas`` flag. |
| 5783 |
Note that ``-ffp-contract=fast`` will override pragmas to fuse multiply and |
| 5784 |
addition across statements regardless of any controlling pragmas. |
| 5785 |
|
| 5786 |
``#pragma clang fp exceptions`` specifies floating point exception behavior. It |
| 5787 |
may take one of the values: ``ignore``, ``maytrap`` or ``strict``. Meaning of |
| 5788 |
these values is same as for `constrained floating point intrinsics <http://llvm.org/docs/LangRef.html#constrained-floating-point-intrinsics>`_. |
| 5789 |
|
| 5790 |
.. code-block:: c++ |
| 5791 |
|
| 5792 |
{ |
| 5793 |
// Preserve floating point exceptions |
| 5794 |
#pragma clang fp exceptions(strict) |
| 5795 |
z = x + y; |
| 5796 |
if (fetestexcept(FE_OVERFLOW)) |
| 5797 |
... |
| 5798 |
} |
| 5799 |
|
| 5800 |
A ``#pragma clang fp`` pragma may contain any number of options: |
| 5801 |
|
| 5802 |
.. code-block:: c++ |
| 5803 |
|
| 5804 |
void func(float *dest, float a, float b) { |
| 5805 |
#pragma clang fp exceptions(maytrap) contract(fast) reassociate(on) |
| 5806 |
... |
| 5807 |
} |
| 5808 |
|
| 5809 |
``#pragma clang fp eval_method`` allows floating-point behavior to be specified |
| 5810 |
for a section of the source code. This pragma can appear at file or namespace |
| 5811 |
scope, or at the start of a compound statement (excluding comments). |
| 5812 |
The pragma is active within the scope of the compound statement. |
| 5813 |
|
| 5814 |
When ``pragma clang fp eval_method(source)`` is enabled, the section of code |
| 5815 |
governed by the pragma behaves as though the command-line option |
| 5816 |
``-ffp-eval-method=source`` is enabled. Rounds intermediate results to |
| 5817 |
source-defined precision. |
| 5818 |
|
| 5819 |
When ``pragma clang fp eval_method(double)`` is enabled, the section of code |
| 5820 |
governed by the pragma behaves as though the command-line option |
| 5821 |
``-ffp-eval-method=double`` is enabled. Rounds intermediate results to |
| 5822 |
``double`` precision. |
| 5823 |
|
| 5824 |
When ``pragma clang fp eval_method(extended)`` is enabled, the section of code |
| 5825 |
governed by the pragma behaves as though the command-line option |
| 5826 |
``-ffp-eval-method=extended`` is enabled. Rounds intermediate results to |
| 5827 |
target-dependent ``long double`` precision. In Win32 programming, for instance, |
| 5828 |
the long double data type maps to the double, 64-bit precision data type. |
| 5829 |
|
| 5830 |
The full syntax this pragma supports is |
| 5831 |
``#pragma clang fp eval_method(source|double|extended)``. |
| 5832 |
|
| 5833 |
.. code-block:: c++ |
| 5834 |
|
| 5835 |
for(...) { |
| 5836 |
// The compiler will use long double as the floating-point evaluation |
| 5837 |
// method. |
| 5838 |
#pragma clang fp eval_method(extended) |
| 5839 |
a = b[i] * c[i] + e; |
| 5840 |
} |
| 5841 |
|
| 5842 |
Note: ``math.h`` defines the typedefs ``float_t`` and ``double_t`` based on the active |
| 5843 |
evaluation method at the point where the header is included, not where the |
| 5844 |
typedefs are used. Because of this, it is unwise to combine these typedefs with |
| 5845 |
``#pragma clang fp eval_method``. To catch obvious bugs, Clang will emit an |
| 5846 |
error for any references to these typedefs within the scope of this pragma; |
| 5847 |
however, this is not a fool-proof protection, and programmers must take care. |
| 5848 |
|
| 5849 |
The ``#pragma float_control`` pragma allows precise floating-point |
| 5850 |
semantics and floating-point exception behavior to be specified |
| 5851 |
for a section of the source code. This pragma can only appear at file or |
| 5852 |
namespace scope, within a language linkage specification or at the start of a |
| 5853 |
compound statement (excluding comments). When used within a compound statement, |
| 5854 |
the pragma is active within the scope of the compound statement. This pragma |
| 5855 |
is modeled after a Microsoft pragma with the same spelling and syntax. For |
| 5856 |
pragmas specified at file or namespace scope, or within a language linkage |
| 5857 |
specification, a stack is supported so that the ``pragma float_control`` |
| 5858 |
settings can be pushed or popped. |
| 5859 |
|
| 5860 |
When ``pragma float_control(precise, on)`` is enabled, the section of code |
| 5861 |
governed by the pragma uses precise floating point semantics, effectively |
| 5862 |
``-ffast-math`` is disabled and ``-ffp-contract=on`` |
| 5863 |
(fused multiply add) is enabled. This pragma enables ``-fmath-errno``. |
| 5864 |
|
| 5865 |
When ``pragma float_control(precise, off)`` is enabled, unsafe-floating point |
| 5866 |
optimizations are enabled in the section of code governed by the pragma. |
| 5867 |
Effectively ``-ffast-math`` is enabled and ``-ffp-contract=fast``. This pragma |
| 5868 |
disables ``-fmath-errno``. |
| 5869 |
|
| 5870 |
When ``pragma float_control(except, on)`` is enabled, the section of code |
| 5871 |
governed by the pragma behaves as though the command-line option |
| 5872 |
``-ffp-exception-behavior=strict`` is enabled, |
| 5873 |
when ``pragma float_control(except, off)`` is enabled, the section of code |
| 5874 |
governed by the pragma behaves as though the command-line option |
| 5875 |
``-ffp-exception-behavior=ignore`` is enabled. |
| 5876 |
|
| 5877 |
The full syntax this pragma supports is |
| 5878 |
``float_control(except|precise, on|off [, push])`` and |
| 5879 |
``float_control(push|pop)``. |
| 5880 |
The ``push`` and ``pop`` forms, including using ``push`` as the optional |
| 5881 |
third argument, can only occur at file scope. |
| 5882 |
|
| 5883 |
.. code-block:: c++ |
| 5884 |
|
| 5885 |
for(...) { |
| 5886 |
// This block will be compiled with -fno-fast-math and -ffp-contract=on |
| 5887 |
#pragma float_control(precise, on) |
| 5888 |
a = b[i] * c[i] + e; |
| 5889 |
} |
| 5890 |
|
| 5891 |
Extensions for controlling atomic code generation |
| 5892 |
================================================= |
| 5893 |
|
| 5894 |
The ``[[clang::atomic]]`` statement attribute enables users to control how |
| 5895 |
atomic operations are lowered in LLVM IR by conveying additional metadata to |
| 5896 |
the backend. The primary goal is to allow users to specify certain options, |
| 5897 |
like whether the affected atomic operations might be used with specific types of memory or |
| 5898 |
whether to ignore denormal mode correctness in floating-point operations, |
| 5899 |
without affecting the correctness of code that does not rely on these properties. |
| 5900 |
|
| 5901 |
In LLVM, lowering of atomic operations (e.g., ``atomicrmw``) can differ based |
| 5902 |
on the target's capabilities. Some backends support native atomic instructions |
| 5903 |
only for certain operation types or alignments, or only in specific memory |
| 5904 |
regions. Likewise, floating-point atomic instructions may or may not respect |
| 5905 |
IEEE denormal requirements. When the user is unconcerned about denormal-mode |
| 5906 |
compliance (for performance reasons) or knows that certain atomic operations |
| 5907 |
will not be performed on a particular type of memory, extra hints are needed to |
| 5908 |
tell the backend how to proceed. |
| 5909 |
|
| 5910 |
A classic example is an architecture where floating-point atomic add does not |
| 5911 |
fully conform to IEEE denormal-mode handling. If the user does not mind ignoring |
| 5912 |
that aspect, they would prefer to emit a faster hardware atomic instruction, |
| 5913 |
rather than a fallback or CAS loop. Conversely, on certain GPUs (e.g., AMDGPU), |
| 5914 |
memory accessed via PCIe may only support a subset of atomic operations. To ensure |
| 5915 |
correct and efficient lowering, the compiler must know whether the user needs |
| 5916 |
the atomic operations to work with that type of memory. |
| 5917 |
|
| 5918 |
The allowed atomic attribute values are now ``remote_memory``, ``fine_grained_memory``, |
| 5919 |
and ``ignore_denormal_mode``, each optionally prefixed with ``no_``. The meanings |
| 5920 |
are as follows: |
| 5921 |
|
| 5922 |
- ``remote_memory`` means atomic operations may be performed on remote |
| 5923 |
memory, i.e., memory accessed through off-chip interconnects (e.g., PCIe). |
| 5924 |
On ROCm platforms using HIP, remote memory refers to memory accessed via |
| 5925 |
PCIe and is subject to specific atomic operation support. See |
| 5926 |
`ROCm PCIe Atomics <https://rocm.docs.amd.com/en/latest/conceptual/ |
| 5927 |
pcie-atomics.html>`_ for further details. Prefixing with ``no_remote_memory`` indicates that |
| 5928 |
atomic operations should not be performed on remote memory. |
| 5929 |
- ``fine_grained_memory`` means atomic operations may be performed on fine-grained |
| 5930 |
memory, i.e., memory regions that support fine-grained coherence, where updates to |
| 5931 |
memory are visible to other parts of the system even while modifications are ongoing. |
| 5932 |
For example, in HIP, fine-grained coherence ensures that host and device share |
| 5933 |
up-to-date data without explicit synchronization (see |
| 5934 |
`HIP Definition <https://rocm.docs.amd.com/projects/HIP/en/docs-6.3.3/how-to/hip_runtime_api/memory_management/coherence_control.html#coherence-control>`_). |
| 5935 |
Similarly, OpenCL 2.0 provides fine-grained synchronization in shared virtual memory |
| 5936 |
allocations, allowing concurrent modifications by host and device (see |
| 5937 |
`OpenCL 2.0 Overview <https://www.intel.com/content/www/us/en/developer/articles/technical/opencl-20-shared-virtual-memory-overview.html>`_). |
| 5938 |
Prefixing with ``no_fine_grained_memory`` indicates that atomic operations should not |
| 5939 |
be performed on fine-grained memory. |
| 5940 |
- ``ignore_denormal_mode`` means that atomic operations are allowed to ignore |
| 5941 |
correctness for denormal mode in floating-point operations, potentially improving |
| 5942 |
performance on architectures that handle denormals inefficiently. The negated form, |
| 5943 |
if specified as ``no_ignore_denormal_mode``, would enforce strict denormal mode |
| 5944 |
correctness. |
| 5945 |
|
| 5946 |
Any unspecified option is inherited from the global defaults, which can be set |
| 5947 |
by a compiler flag or the target's built-in defaults. |
| 5948 |
|
| 5949 |
Within the same atomic attribute, duplicate and conflicting values are accepted, |
| 5950 |
and the last of any conflicting values wins. Multiple atomic attributes are |
| 5951 |
allowed for the same compound statement, and the last atomic attribute wins. |
| 5952 |
|
| 5953 |
Without any atomic metadata, LLVM IR defaults to conservative settings for |
| 5954 |
correctness: atomic operations enforce denormal mode correctness and are assumed |
| 5955 |
to potentially use remote and fine-grained memory (i.e., the equivalent of |
| 5956 |
``remote_memory``, ``fine_grained_memory``, and ``no_ignore_denormal_mode``). |
| 5957 |
|
| 5958 |
The attribute may be applied only to a compound statement and looks like: |
| 5959 |
|
| 5960 |
.. code-block:: c++ |
| 5961 |
|
| 5962 |
[[clang::atomic(remote_memory, fine_grained_memory, ignore_denormal_mode)]] |
| 5963 |
{ |
| 5964 |
// Atomic instructions in this block carry extra metadata reflecting |
| 5965 |
// these user-specified options. |
| 5966 |
} |
| 5967 |
|
| 5968 |
A new compiler option now globally sets the defaults for these atomic-lowering |
| 5969 |
options. The command-line format has changed to: |
| 5970 |
|
| 5971 |
.. code-block:: console |
| 5972 |
|
| 5973 |
$ clang -fatomic-remote-memory -fno-atomic-fine-grained-memory -fatomic-ignore-denormal-mode file.cpp |
| 5974 |
|
| 5975 |
Each option has a corresponding flag: |
| 5976 |
``-fatomic-remote-memory`` / ``-fno-atomic-remote-memory``, |
| 5977 |
``-fatomic-fine-grained-memory`` / ``-fno-atomic-fine-grained-memory``, |
| 5978 |
and ``-fatomic-ignore-denormal-mode`` / ``-fno-atomic-ignore-denormal-mode``. |
| 5979 |
|
| 5980 |
Code using the ``[[clang::atomic]]`` attribute can then selectively override |
| 5981 |
the command-line defaults on a per-block basis. For instance: |
| 5982 |
|
| 5983 |
.. code-block:: c++ |
| 5984 |
|
| 5985 |
// Suppose the global defaults assume: |
| 5986 |
// remote_memory, fine_grained_memory, and no_ignore_denormal_mode |
| 5987 |
// (for conservative correctness) |
| 5988 |
|
| 5989 |
void example() { |
| 5990 |
// Locally override the settings: disable remote_memory and enable |
| 5991 |
// fine_grained_memory. |
| 5992 |
[[clang::atomic(no_remote_memory, fine_grained_memory)]] |
| 5993 |
{ |
| 5994 |
// In this block: |
| 5995 |
// - Atomic operations are not performed on remote memory. |
| 5996 |
// - Atomic operations are performed on fine-grained memory. |
| 5997 |
// - The setting for denormal mode remains as the global default |
| 5998 |
// (typically no_ignore_denormal_mode, enforcing strict denormal mode correctness). |
| 5999 |
// ... |
| 6000 |
} |
| 6001 |
} |
| 6002 |
|
| 6003 |
Function bodies do not accept statement attributes, so this will not work: |
| 6004 |
|
| 6005 |
.. code-block:: c++ |
| 6006 |
|
| 6007 |
void func() [[clang::atomic(remote_memory)]] { // Wrong: applies to function type |
| 6008 |
} |
| 6009 |
|
| 6010 |
Use the attribute on a compound statement within the function: |
| 6011 |
|
| 6012 |
.. code-block:: c++ |
| 6013 |
|
| 6014 |
void func() { |
| 6015 |
[[clang::atomic(remote_memory)]] |
| 6016 |
{ |
| 6017 |
// Atomic operations in this block carry the specified metadata. |
| 6018 |
} |
| 6019 |
} |
| 6020 |
|
| 6021 |
The ``[[clang::atomic]]`` attribute affects only the code generation of atomic |
| 6022 |
instructions within the annotated compound statement. Clang attaches target-specific |
| 6023 |
metadata to those atomic instructions in the emitted LLVM IR to guide backend lowering. |
| 6024 |
This metadata is fixed at the Clang code generation phase and is not modified by later |
| 6025 |
LLVM passes (such as function inlining). |
| 6026 |
|
| 6027 |
For example, consider: |
| 6028 |
|
| 6029 |
.. code-block:: cpp |
| 6030 |
|
| 6031 |
inline void func() { |
| 6032 |
[[clang::atomic(remote_memory)]] |
| 6033 |
{ |
| 6034 |
// Atomic instructions lowered with metadata. |
| 6035 |
} |
| 6036 |
} |
| 6037 |
|
| 6038 |
void foo() { |
| 6039 |
[[clang::atomic(no_remote_memory)]] |
| 6040 |
{ |
| 6041 |
func(); // Inlined by LLVM, but the metadata from 'func()' remains unchanged. |
| 6042 |
} |
| 6043 |
} |
| 6044 |
|
| 6045 |
Although current usage focuses on AMDGPU, the mechanism is general. Other |
| 6046 |
backends can ignore or implement their own responses to these flags if desired. |
| 6047 |
If a target does not understand or enforce these hints, the IR remains valid, |
| 6048 |
and the resulting program is still correct (although potentially less optimized |
| 6049 |
for that user's needs). |
| 6050 |
|
| 6051 |
Specifying an attribute for multiple declarations (#pragma clang attribute) |
| 6052 |
=========================================================================== |
| 6053 |
|
| 6054 |
The ``#pragma clang attribute`` directive can be used to apply an attribute to |
| 6055 |
multiple declarations. The ``#pragma clang attribute push`` variation of the |
| 6056 |
directive pushes a new "scope" of ``#pragma clang attribute`` that attributes |
| 6057 |
can be added to. The ``#pragma clang attribute (...)`` variation adds an |
| 6058 |
attribute to that scope, and the ``#pragma clang attribute pop`` variation pops |
| 6059 |
the scope. You can also use ``#pragma clang attribute push (...)``, which is a |
| 6060 |
shorthand for when you want to add one attribute to a new scope. Multiple push |
| 6061 |
directives can be nested inside each other. |
| 6062 |
|
| 6063 |
The attributes that are used in the ``#pragma clang attribute`` directives |
| 6064 |
can be written using the GNU-style syntax: |
| 6065 |
|
| 6066 |
.. code-block:: c++ |
| 6067 |
|
| 6068 |
#pragma clang attribute push (__attribute__((annotate("custom"))), apply_to = function) |
| 6069 |
|
| 6070 |
void function(); // The function now has the annotate("custom") attribute |
| 6071 |
|
| 6072 |
#pragma clang attribute pop |
| 6073 |
|
| 6074 |
The attributes can also be written using the C++11 style syntax: |
| 6075 |
|
| 6076 |
.. code-block:: c++ |
| 6077 |
|
| 6078 |
#pragma clang attribute push ([[noreturn]], apply_to = function) |
| 6079 |
|
| 6080 |
void function(); // The function now has the [[noreturn]] attribute |
| 6081 |
|
| 6082 |
#pragma clang attribute pop |
| 6083 |
|
| 6084 |
The ``__declspec`` style syntax is also supported: |
| 6085 |
|
| 6086 |
.. code-block:: c++ |
| 6087 |
|
| 6088 |
#pragma clang attribute push (__declspec(dllexport), apply_to = function) |
| 6089 |
|
| 6090 |
void function(); // The function now has the __declspec(dllexport) attribute |
| 6091 |
|
| 6092 |
#pragma clang attribute pop |
| 6093 |
|
| 6094 |
A single push directive can contain multiple attributes, however, |
| 6095 |
only one syntax style can be used within a single directive: |
| 6096 |
|
| 6097 |
.. code-block:: c++ |
| 6098 |
|
| 6099 |
#pragma clang attribute push ([[noreturn, noinline]], apply_to = function) |
| 6100 |
|
| 6101 |
void function1(); // The function now has the [[noreturn]] and [[noinline]] attributes |
| 6102 |
|
| 6103 |
#pragma clang attribute pop |
| 6104 |
|
| 6105 |
#pragma clang attribute push (__attribute((noreturn, noinline)), apply_to = function) |
| 6106 |
|
| 6107 |
void function2(); // The function now has the __attribute((noreturn)) and __attribute((noinline)) attributes |
| 6108 |
|
| 6109 |
#pragma clang attribute pop |
| 6110 |
|
| 6111 |
Because multiple push directives can be nested, if you're writing a macro that |
| 6112 |
expands to ``_Pragma("clang attribute")`` it's good hygiene (though not |
| 6113 |
required) to add a namespace to your push/pop directives. A pop directive with a |
| 6114 |
namespace will pop the innermost push that has that same namespace. This will |
| 6115 |
ensure that another macro's ``pop`` won't inadvertently pop your attribute. Note |
| 6116 |
that an ``pop`` without a namespace will pop the innermost ``push`` without a |
| 6117 |
namespace. ``push``es with a namespace can only be popped by ``pop`` with the |
| 6118 |
same namespace. For instance: |
| 6119 |
|
| 6120 |
.. code-block:: c++ |
| 6121 |
|
| 6122 |
#define ASSUME_NORETURN_BEGIN _Pragma("clang attribute AssumeNoreturn.push ([[noreturn]], apply_to = function)") |
| 6123 |
#define ASSUME_NORETURN_END _Pragma("clang attribute AssumeNoreturn.pop") |
| 6124 |
|
| 6125 |
#define ASSUME_UNAVAILABLE_BEGIN _Pragma("clang attribute Unavailable.push (__attribute__((unavailable)), apply_to=function)") |
| 6126 |
#define ASSUME_UNAVAILABLE_END _Pragma("clang attribute Unavailable.pop") |
| 6127 |
|
| 6128 |
|
| 6129 |
ASSUME_NORETURN_BEGIN |
| 6130 |
ASSUME_UNAVAILABLE_BEGIN |
| 6131 |
void function(); // function has [[noreturn]] and __attribute__((unavailable)) |
| 6132 |
ASSUME_NORETURN_END |
| 6133 |
void other_function(); // function has __attribute__((unavailable)) |
| 6134 |
ASSUME_UNAVAILABLE_END |
| 6135 |
|
| 6136 |
Without the namespaces on the macros, ``other_function`` will be annotated with |
| 6137 |
``[[noreturn]]`` instead of ``__attribute__((unavailable))``. This may seem like |
| 6138 |
a contrived example, but its very possible for this kind of situation to appear |
| 6139 |
in real code if the pragmas are spread out across a large file. You can test if |
| 6140 |
your version of clang supports namespaces on ``#pragma clang attribute`` with |
| 6141 |
``__has_extension(pragma_clang_attribute_namespaces)``. |
| 6142 |
|
| 6143 |
Subject Match Rules |
| 6144 |
------------------- |
| 6145 |
|
| 6146 |
The set of declarations that receive a single attribute from the attribute stack |
| 6147 |
depends on the subject match rules that were specified in the pragma. Subject |
| 6148 |
match rules are specified after the attribute. The compiler expects an |
| 6149 |
identifier that corresponds to the subject set specifier. The ``apply_to`` |
| 6150 |
specifier is currently the only supported subject set specifier. It allows you |
| 6151 |
to specify match rules that form a subset of the attribute's allowed subject |
| 6152 |
set, i.e., the compiler doesn't require all of the attribute's subjects. For |
| 6153 |
example, an attribute like ``[[nodiscard]]`` whose subject set includes |
| 6154 |
``enum``, ``record`` and ``hasType(functionType)``, requires the presence of at |
| 6155 |
least one of these rules after ``apply_to``: |
| 6156 |
|
| 6157 |
.. code-block:: c++ |
| 6158 |
|
| 6159 |
#pragma clang attribute push([[nodiscard]], apply_to = enum) |
| 6160 |
|
| 6161 |
enum Enum1 { A1, B1 }; // The enum will receive [[nodiscard]] |
| 6162 |
|
| 6163 |
struct Record1 { }; // The struct will *not* receive [[nodiscard]] |
| 6164 |
|
| 6165 |
#pragma clang attribute pop |
| 6166 |
|
| 6167 |
#pragma clang attribute push([[nodiscard]], apply_to = any(record, enum)) |
| 6168 |
|
| 6169 |
enum Enum2 { A2, B2 }; // The enum will receive [[nodiscard]] |
| 6170 |
|
| 6171 |
struct Record2 { }; // The struct *will* receive [[nodiscard]] |
| 6172 |
|
| 6173 |
#pragma clang attribute pop |
| 6174 |
|
| 6175 |
// This is an error, since [[nodiscard]] can't be applied to namespaces: |
| 6176 |
#pragma clang attribute push([[nodiscard]], apply_to = any(record, namespace)) |
| 6177 |
|
| 6178 |
#pragma clang attribute pop |
| 6179 |
|
| 6180 |
Multiple match rules can be specified using the ``any`` match rule, as shown |
| 6181 |
in the example above. The ``any`` rule applies attributes to all declarations |
| 6182 |
that are matched by at least one of the rules in the ``any``. It doesn't nest |
| 6183 |
and can't be used inside the other match rules. Redundant match rules or rules |
| 6184 |
that conflict with one another should not be used inside of ``any``. Failing to |
| 6185 |
specify a rule within the ``any`` rule results in an error. |
| 6186 |
|
| 6187 |
Clang supports the following match rules: |
| 6188 |
|
| 6189 |
- ``function``: Can be used to apply attributes to functions. This includes C++ |
| 6190 |
member functions, static functions, operators, and constructors/destructors. |
| 6191 |
|
| 6192 |
- ``function(is_member)``: Can be used to apply attributes to C++ member |
| 6193 |
functions. This includes members like static functions, operators, and |
| 6194 |
constructors/destructors. |
| 6195 |
|
| 6196 |
- ``hasType(functionType)``: Can be used to apply attributes to functions, C++ |
| 6197 |
member functions, and variables/fields whose type is a function pointer. It |
| 6198 |
does not apply attributes to Objective-C methods or blocks. |
| 6199 |
|
| 6200 |
- ``type_alias``: Can be used to apply attributes to ``typedef`` declarations |
| 6201 |
and C++11 type aliases. |
| 6202 |
|
| 6203 |
- ``record``: Can be used to apply attributes to ``struct``, ``class``, and |
| 6204 |
``union`` declarations. |
| 6205 |
|
| 6206 |
- ``record(unless(is_union))``: Can be used to apply attributes only to |
| 6207 |
``struct`` and ``class`` declarations. |
| 6208 |
|
| 6209 |
- ``enum``: Can be used to apply attributes to enumeration declarations. |
| 6210 |
|
| 6211 |
- ``enum_constant``: Can be used to apply attributes to enumerators. |
| 6212 |
|
| 6213 |
- ``variable``: Can be used to apply attributes to variables, including |
| 6214 |
local variables, parameters, global variables, and static member variables. |
| 6215 |
It does not apply attributes to instance member variables or Objective-C |
| 6216 |
ivars. |
| 6217 |
|
| 6218 |
- ``variable(is_thread_local)``: Can be used to apply attributes to thread-local |
| 6219 |
variables only. |
| 6220 |
|
| 6221 |
- ``variable(is_global)``: Can be used to apply attributes to global variables |
| 6222 |
only. |
| 6223 |
|
| 6224 |
- ``variable(is_local)``: Can be used to apply attributes to local variables |
| 6225 |
only. |
| 6226 |
|
| 6227 |
- ``variable(is_parameter)``: Can be used to apply attributes to parameters |
| 6228 |
only. |
| 6229 |
|
| 6230 |
- ``variable(unless(is_parameter))``: Can be used to apply attributes to all |
| 6231 |
the variables that are not parameters. |
| 6232 |
|
| 6233 |
- ``field``: Can be used to apply attributes to non-static member variables |
| 6234 |
in a record. This includes Objective-C ivars. |
| 6235 |
|
| 6236 |
- ``namespace``: Can be used to apply attributes to ``namespace`` declarations. |
| 6237 |
|
| 6238 |
- ``objc_interface``: Can be used to apply attributes to ``@interface`` |
| 6239 |
declarations. |
| 6240 |
|
| 6241 |
- ``objc_protocol``: Can be used to apply attributes to ``@protocol`` |
| 6242 |
declarations. |
| 6243 |
|
| 6244 |
- ``objc_category``: Can be used to apply attributes to category declarations, |
| 6245 |
including class extensions. |
| 6246 |
|
| 6247 |
- ``objc_method``: Can be used to apply attributes to Objective-C methods, |
| 6248 |
including instance and class methods. Implicit methods like implicit property |
| 6249 |
getters and setters do not receive the attribute. |
| 6250 |
|
| 6251 |
- ``objc_method(is_instance)``: Can be used to apply attributes to Objective-C |
| 6252 |
instance methods. |
| 6253 |
|
| 6254 |
- ``objc_property``: Can be used to apply attributes to ``@property`` |
| 6255 |
declarations. |
| 6256 |
|
| 6257 |
- ``block``: Can be used to apply attributes to block declarations. This does |
| 6258 |
not include variables/fields of block pointer type. |
| 6259 |
|
| 6260 |
The use of ``unless`` in match rules is currently restricted to a strict set of |
| 6261 |
sub-rules that are used by the supported attributes. That means that even though |
| 6262 |
``variable(unless(is_parameter))`` is a valid match rule, |
| 6263 |
``variable(unless(is_thread_local))`` is not. |
| 6264 |
|
| 6265 |
Supported Attributes |
| 6266 |
-------------------- |
| 6267 |
|
| 6268 |
Not all attributes can be used with the ``#pragma clang attribute`` directive. |
| 6269 |
Notably, statement attributes like ``[[fallthrough]]`` or type attributes |
| 6270 |
like ``address_space`` aren't supported by this directive. You can determine |
| 6271 |
whether or not an attribute is supported by the pragma by referring to the |
| 6272 |
:doc:`individual documentation for that attribute <AttributeReference>`. |
| 6273 |
|
| 6274 |
The attributes are applied to all matching declarations individually, even when |
| 6275 |
the attribute is semantically incorrect. The attributes that aren't applied to |
| 6276 |
any declaration are not verified semantically. |
| 6277 |
|
| 6278 |
Specifying section names for global objects (#pragma clang section) |
| 6279 |
=================================================================== |
| 6280 |
|
| 6281 |
The ``#pragma clang section`` directive provides a means to assign section-names |
| 6282 |
to global variables, functions and static variables. |
| 6283 |
|
| 6284 |
The section names can be specified as: |
| 6285 |
|
| 6286 |
.. code-block:: c++ |
| 6287 |
|
| 6288 |
#pragma clang section bss="myBSS" data="myData" rodata="myRodata" relro="myRelro" text="myText" |
| 6289 |
|
| 6290 |
The section names can be reverted back to default name by supplying an empty |
| 6291 |
string to the section kind, for example: |
| 6292 |
|
| 6293 |
.. code-block:: c++ |
| 6294 |
|
| 6295 |
#pragma clang section bss="" data="" text="" rodata="" relro="" |
| 6296 |
|
| 6297 |
The ``#pragma clang section`` directive obeys the following rules: |
| 6298 |
|
| 6299 |
* The pragma applies to all global variable, statics and function declarations |
| 6300 |
from the pragma to the end of the translation unit. |
| 6301 |
|
| 6302 |
* The pragma clang section is enabled automatically, without need of any flags. |
| 6303 |
|
| 6304 |
* This feature is only defined to work sensibly for ELF, Mach-O and COFF targets. |
| 6305 |
|
| 6306 |
* If section name is specified through _attribute_((section("myname"))), then |
| 6307 |
the attribute name gains precedence. |
| 6308 |
|
| 6309 |
* Global variables that are initialized to zero will be placed in the named |
| 6310 |
bss section, if one is present. |
| 6311 |
|
| 6312 |
* The ``#pragma clang section`` directive does not try to infer section-kind |
| 6313 |
from the name. For example, naming a section "``.bss.mySec``" does NOT mean |
| 6314 |
it will be a bss section name. |
| 6315 |
|
| 6316 |
* The decision about which section-kind applies to each global is taken in the back-end. |
| 6317 |
Once the section-kind is known, appropriate section name, as specified by the user using |
| 6318 |
``#pragma clang section`` directive, is applied to that global. |
| 6319 |
|
| 6320 |
Specifying Linker Options on ELF Targets |
| 6321 |
======================================== |
| 6322 |
|
| 6323 |
The ``#pragma comment(lib, ...)`` directive is supported on all ELF targets. |
| 6324 |
The second parameter is the library name (without the traditional Unix prefix of |
| 6325 |
``lib``). This allows you to provide an implicit link of dependent libraries. |
| 6326 |
|
| 6327 |
Evaluating Object Size |
| 6328 |
====================== |
| 6329 |
|
| 6330 |
Clang supports the builtins ``__builtin_object_size`` and |
| 6331 |
``__builtin_dynamic_object_size``. The semantics are compatible with GCC's |
| 6332 |
builtins of the same names, but the details are slightly different. |
| 6333 |
|
| 6334 |
.. code-block:: c |
| 6335 |
|
| 6336 |
size_t __builtin_[dynamic_]object_size(const void *ptr, int type) |
| 6337 |
|
| 6338 |
Returns the number of accessible bytes ``n`` past ``ptr``. The value returned |
| 6339 |
depends on ``type``, which is required to be an integer constant between 0 and |
| 6340 |
3: |
| 6341 |
|
| 6342 |
* If ``type & 2 == 0``, the least ``n`` is returned such that accesses to |
| 6343 |
``(const char*)ptr + n`` and beyond are known to be out of bounds. This is |
| 6344 |
``(size_t)-1`` if no better bound is known. |
| 6345 |
* If ``type & 2 == 2``, the greatest ``n`` is returned such that accesses to |
| 6346 |
``(const char*)ptr + i`` are known to be in bounds, for 0 <= ``i`` < ``n``. |
| 6347 |
This is ``(size_t)0`` if no better bound is known. |
| 6348 |
|
| 6349 |
.. code-block:: c |
| 6350 |
|
| 6351 |
char small[10], large[100]; |
| 6352 |
bool cond; |
| 6353 |
// Returns 100: writes of more than 100 bytes are known to be out of bounds. |
| 6354 |
int n100 = __builtin_object_size(cond ? small : large, 0); |
| 6355 |
// Returns 10: writes of 10 or fewer bytes are known to be in bounds. |
| 6356 |
int n10 = __builtin_object_size(cond ? small : large, 2); |
| 6357 |
|
| 6358 |
* If ``type & 1 == 0``, pointers are considered to be in bounds if they point |
| 6359 |
into the same storage as ``ptr`` -- that is, the same stack object, global |
| 6360 |
variable, or heap allocation. |
| 6361 |
* If ``type & 1 == 1``, pointers are considered to be in bounds if they point |
| 6362 |
to the same subobject that ``ptr`` points to. If ``ptr`` points to an array |
| 6363 |
element, other elements of the same array, but not of enclosing arrays, are |
| 6364 |
considered in bounds. |
| 6365 |
|
| 6366 |
.. code-block:: c |
| 6367 |
|
| 6368 |
struct X { char a, b, c; } x; |
| 6369 |
static_assert(__builtin_object_size(&x, 0) == 3); |
| 6370 |
static_assert(__builtin_object_size(&x.b, 0) == 2); |
| 6371 |
static_assert(__builtin_object_size(&x.b, 1) == 1); |
| 6372 |
|
| 6373 |
.. code-block:: c |
| 6374 |
|
| 6375 |
char a[10][10][10]; |
| 6376 |
static_assert(__builtin_object_size(&a, 1) == 1000); |
| 6377 |
static_assert(__builtin_object_size(&a[1], 1) == 900); |
| 6378 |
static_assert(__builtin_object_size(&a[1][1], 1) == 90); |
| 6379 |
static_assert(__builtin_object_size(&a[1][1][1], 1) == 9); |
| 6380 |
|
| 6381 |
The values returned by this builtin are a best effort conservative approximation |
| 6382 |
of the correct answers. When ``type & 2 == 0``, the true value is less than or |
| 6383 |
equal to the value returned by the builtin, and when ``type & 2 == 1``, the true |
| 6384 |
value is greater than or equal to the value returned by the builtin. |
| 6385 |
|
| 6386 |
For ``__builtin_object_size``, the value is determined entirely at compile time. |
| 6387 |
With optimization enabled, better results will be produced, especially when the |
| 6388 |
call to ``__builtin_object_size`` is in a different function from the formation |
| 6389 |
of the pointer. Unlike in GCC, enabling optimization in Clang does not allow |
| 6390 |
more information about subobjects to be determined, so the ``type & 1 == 1`` |
| 6391 |
case will often give imprecise results when used across a function call boundary |
| 6392 |
even when optimization is enabled. |
| 6393 |
|
| 6394 |
`The pass_object_size and pass_dynamic_object_size attributes <https://clang.llvm.org/docs/AttributeReference.html#pass-object-size-pass-dynamic-object-size>`_ |
| 6395 |
can be used to invisibly pass the object size for a pointer parameter alongside |
| 6396 |
the pointer in a function call. This allows more precise object sizes to be |
| 6397 |
determined both when building without optimizations and in the ``type & 1 == 1`` |
| 6398 |
case. |
| 6399 |
|
| 6400 |
For ``__builtin_dynamic_object_size``, the result is not limited to being a |
| 6401 |
compile time constant. Instead, a small amount of runtime evaluation is |
| 6402 |
permitted to determine the size of the object, in order to give a more precise |
| 6403 |
result. ``__builtin_dynamic_object_size`` is meant to be used as a drop-in |
| 6404 |
replacement for ``__builtin_object_size`` in libraries that support it. For |
| 6405 |
instance, here is a program that ``__builtin_dynamic_object_size`` will make |
| 6406 |
safer: |
| 6407 |
|
| 6408 |
.. code-block:: c |
| 6409 |
|
| 6410 |
void copy_into_buffer(size_t size) { |
| 6411 |
char* buffer = malloc(size); |
| 6412 |
strlcpy(buffer, "some string", strlen("some string")); |
| 6413 |
// Previous line preprocesses to: |
| 6414 |
// __builtin___strlcpy_chk(buffer, "some string", strlen("some string"), __builtin_object_size(buffer, 0)) |
| 6415 |
} |
| 6416 |
|
| 6417 |
Since the size of ``buffer`` can't be known at compile time, Clang will fold |
| 6418 |
``__builtin_object_size(buffer, 0)`` into ``-1``. However, if this was written |
| 6419 |
as ``__builtin_dynamic_object_size(buffer, 0)``, Clang will fold it into |
| 6420 |
``size``, providing some extra runtime safety. |
| 6421 |
|
| 6422 |
Deprecating Macros |
| 6423 |
================== |
| 6424 |
|
| 6425 |
Clang supports the pragma ``#pragma clang deprecated``, which can be used to |
| 6426 |
provide deprecation warnings for macro uses. For example: |
| 6427 |
|
| 6428 |
.. code-block:: c |
| 6429 |
|
| 6430 |
#define MIN(x, y) x < y ? x : y |
| 6431 |
#pragma clang deprecated(MIN, "use std::min instead") |
| 6432 |
|
| 6433 |
int min(int a, int b) { |
| 6434 |
return MIN(a, b); // warning: MIN is deprecated: use std::min instead |
| 6435 |
} |
| 6436 |
|
| 6437 |
``#pragma clang deprecated`` should be preferred for this purpose over |
| 6438 |
``#pragma GCC warning`` because the warning can be controlled with |
| 6439 |
``-Wdeprecated``. |
| 6440 |
|
| 6441 |
Restricted Expansion Macros |
| 6442 |
=========================== |
| 6443 |
|
| 6444 |
Clang supports the pragma ``#pragma clang restrict_expansion``, which can be |
| 6445 |
used restrict macro expansion in headers. This can be valuable when providing |
| 6446 |
headers with ABI stability requirements. Any expansion of the annotated macro |
| 6447 |
processed by the preprocessor after the ``#pragma`` annotation will log a |
| 6448 |
warning. Redefining the macro or undefining the macro will not be diagnosed, nor |
| 6449 |
will expansion of the macro within the main source file. For example: |
| 6450 |
|
| 6451 |
.. code-block:: c |
| 6452 |
|
| 6453 |
#define TARGET_ARM 1 |
| 6454 |
#pragma clang restrict_expansion(TARGET_ARM, "<reason>") |
| 6455 |
|
| 6456 |
/// Foo.h |
| 6457 |
struct Foo { |
| 6458 |
#if TARGET_ARM // warning: TARGET_ARM is marked unsafe in headers: <reason> |
| 6459 |
uint32_t X; |
| 6460 |
#else |
| 6461 |
uint64_t X; |
| 6462 |
#endif |
| 6463 |
}; |
| 6464 |
|
| 6465 |
/// main.c |
| 6466 |
#include "foo.h" |
| 6467 |
#if TARGET_ARM // No warning in main source file |
| 6468 |
X_TYPE uint32_t |
| 6469 |
#else |
| 6470 |
X_TYPE uint64_t |
| 6471 |
#endif |
| 6472 |
|
| 6473 |
This warning is controlled by ``-Wpedantic-macros``. |
| 6474 |
|
| 6475 |
Final Macros |
| 6476 |
============ |
| 6477 |
|
| 6478 |
Clang supports the pragma ``#pragma clang final``, which can be used to |
| 6479 |
mark macros as final, meaning they cannot be undef'd or re-defined. For example: |
| 6480 |
|
| 6481 |
.. code-block:: c |
| 6482 |
|
| 6483 |
#define FINAL_MACRO 1 |
| 6484 |
#pragma clang final(FINAL_MACRO) |
| 6485 |
|
| 6486 |
#define FINAL_MACRO // warning: FINAL_MACRO is marked final and should not be redefined |
| 6487 |
#undef FINAL_MACRO // warning: FINAL_MACRO is marked final and should not be undefined |
| 6488 |
|
| 6489 |
This is useful for enforcing system-provided macros that should not be altered |
| 6490 |
in user headers or code. This is controlled by ``-Wpedantic-macros``. Final |
| 6491 |
macros will always warn on redefinition, including situations with identical |
| 6492 |
bodies and in system headers. |
| 6493 |
|
| 6494 |
Line Control |
| 6495 |
============ |
| 6496 |
|
| 6497 |
Clang supports an extension for source line control, which takes the |
| 6498 |
form of a preprocessor directive starting with an unsigned integral |
| 6499 |
constant. In addition to the standard ``#line`` directive, this form |
| 6500 |
allows control of an include stack and header file type, which is used |
| 6501 |
in issuing diagnostics. These lines are emitted in preprocessed |
| 6502 |
output. |
| 6503 |
|
| 6504 |
.. code-block:: c |
| 6505 |
|
| 6506 |
# <line:number> <filename:string> <header-type:numbers> |
| 6507 |
|
| 6508 |
The filename is optional, and if unspecified indicates no change in |
| 6509 |
source filename. The header-type is an optional, whitespace-delimited, |
| 6510 |
sequence of magic numbers as follows. |
| 6511 |
|
| 6512 |
* ``1:`` Push the current source file name onto the include stack and |
| 6513 |
enter a new file. |
| 6514 |
|
| 6515 |
* ``2``: Pop the include stack and return to the specified file. If |
| 6516 |
the filename is ``""``, the name popped from the include stack is |
| 6517 |
used. Otherwise there is no requirement that the specified filename |
| 6518 |
matches the current source when originally pushed. |
| 6519 |
|
| 6520 |
* ``3``: Enter a system-header region. System headers often contain |
| 6521 |
implementation-specific source that would normally emit a diagnostic. |
| 6522 |
|
| 6523 |
* ``4``: Enter an implicit ``extern "C"`` region. This is not required on |
| 6524 |
modern systems where system headers are C++-aware. |
| 6525 |
|
| 6526 |
At most a single ``1`` or ``2`` can be present, and values must be in |
| 6527 |
ascending order. |
| 6528 |
|
| 6529 |
Examples are: |
| 6530 |
|
| 6531 |
.. code-block:: c |
| 6532 |
|
| 6533 |
# 57 // Advance (or return) to line 57 of the current source file |
| 6534 |
# 57 "frob" // Set to line 57 of "frob" |
| 6535 |
# 1 "foo.h" 1 // Enter "foo.h" at line 1 |
| 6536 |
# 59 "main.c" 2 // Leave current include and return to "main.c" |
| 6537 |
# 1 "/usr/include/stdio.h" 1 3 // Enter a system header |
| 6538 |
# 60 "" 2 // return to "main.c" |
| 6539 |
# 1 "/usr/ancient/header.h" 1 4 // Enter an implicit extern "C" header |
| 6540 |
|
| 6541 |
Intrinsics Support within Constant Expressions |
| 6542 |
============================================== |
| 6543 |
|
| 6544 |
The following builtin intrinsics can be used in constant expressions: |
| 6545 |
|
| 6546 |
* ``__builtin_addcb`` |
| 6547 |
* ``__builtin_addcs`` |
| 6548 |
* ``__builtin_addc`` |
| 6549 |
* ``__builtin_addcl`` |
| 6550 |
* ``__builtin_addcll`` |
| 6551 |
* ``__builtin_bitreverse8`` |
| 6552 |
* ``__builtin_bitreverse16`` |
| 6553 |
* ``__builtin_bitreverse32`` |
| 6554 |
* ``__builtin_bitreverse64`` |
| 6555 |
* ``__builtin_bswap16`` |
| 6556 |
* ``__builtin_bswap32`` |
| 6557 |
* ``__builtin_bswap64`` |
| 6558 |
* ``__builtin_clrsb`` |
| 6559 |
* ``__builtin_clrsbl`` |
| 6560 |
* ``__builtin_clrsbll`` |
| 6561 |
* ``__builtin_clz`` |
| 6562 |
* ``__builtin_clzl`` |
| 6563 |
* ``__builtin_clzll`` |
| 6564 |
* ``__builtin_clzs`` |
| 6565 |
* ``__builtin_clzg`` |
| 6566 |
* ``__builtin_ctz`` |
| 6567 |
* ``__builtin_ctzl`` |
| 6568 |
* ``__builtin_ctzll`` |
| 6569 |
* ``__builtin_ctzs`` |
| 6570 |
* ``__builtin_ctzg`` |
| 6571 |
* ``__builtin_ffs`` |
| 6572 |
* ``__builtin_ffsl`` |
| 6573 |
* ``__builtin_ffsll`` |
| 6574 |
* ``__builtin_fmax`` |
| 6575 |
* ``__builtin_fmin`` |
| 6576 |
* ``__builtin_fpclassify`` |
| 6577 |
* ``__builtin_inf`` |
| 6578 |
* ``__builtin_isinf`` |
| 6579 |
* ``__builtin_isinf_sign`` |
| 6580 |
* ``__builtin_isfinite`` |
| 6581 |
* ``__builtin_isnan`` |
| 6582 |
* ``__builtin_isnormal`` |
| 6583 |
* ``__builtin_nan`` |
| 6584 |
* ``__builtin_nans`` |
| 6585 |
* ``__builtin_parity`` |
| 6586 |
* ``__builtin_parityl`` |
| 6587 |
* ``__builtin_parityll`` |
| 6588 |
* ``__builtin_popcount`` |
| 6589 |
* ``__builtin_popcountl`` |
| 6590 |
* ``__builtin_popcountll`` |
| 6591 |
* ``__builtin_popcountg`` |
| 6592 |
* ``__builtin_rotateleft8`` |
| 6593 |
* ``__builtin_rotateleft16`` |
| 6594 |
* ``__builtin_rotateleft32`` |
| 6595 |
* ``__builtin_rotateleft64`` |
| 6596 |
* ``__builtin_rotateright8`` |
| 6597 |
* ``__builtin_rotateright16`` |
| 6598 |
* ``__builtin_rotateright32`` |
| 6599 |
* ``__builtin_rotateright64`` |
| 6600 |
* ``__builtin_subcb`` |
| 6601 |
* ``__builtin_subcs`` |
| 6602 |
* ``__builtin_subc`` |
| 6603 |
* ``__builtin_subcl`` |
| 6604 |
* ``__builtin_subcll`` |
| 6605 |
|
| 6606 |
The following x86-specific intrinsics can be used in constant expressions: |
| 6607 |
|
| 6608 |
* ``_addcarry_u32`` |
| 6609 |
* ``_addcarry_u64`` |
| 6610 |
* ``_bit_scan_forward`` |
| 6611 |
* ``_bit_scan_reverse`` |
| 6612 |
* ``__bsfd`` |
| 6613 |
* ``__bsfq`` |
| 6614 |
* ``__bsrd`` |
| 6615 |
* ``__bsrq`` |
| 6616 |
* ``__bswap`` |
| 6617 |
* ``__bswapd`` |
| 6618 |
* ``__bswap64`` |
| 6619 |
* ``__bswapq`` |
| 6620 |
* ``_castf32_u32`` |
| 6621 |
* ``_castf64_u64`` |
| 6622 |
* ``_castu32_f32`` |
| 6623 |
* ``_castu64_f64`` |
| 6624 |
* ``__lzcnt16`` |
| 6625 |
* ``__lzcnt`` |
| 6626 |
* ``__lzcnt64`` |
| 6627 |
* ``_mm_popcnt_u32`` |
| 6628 |
* ``_mm_popcnt_u64`` |
| 6629 |
* ``_popcnt32`` |
| 6630 |
* ``_popcnt64`` |
| 6631 |
* ``__popcntd`` |
| 6632 |
* ``__popcntq`` |
| 6633 |
* ``__popcnt16`` |
| 6634 |
* ``__popcnt`` |
| 6635 |
* ``__popcnt64`` |
| 6636 |
* ``__rolb`` |
| 6637 |
* ``__rolw`` |
| 6638 |
* ``__rold`` |
| 6639 |
* ``__rolq`` |
| 6640 |
* ``__rorb`` |
| 6641 |
* ``__rorw`` |
| 6642 |
* ``__rord`` |
| 6643 |
* ``__rorq`` |
| 6644 |
* ``_rotl`` |
| 6645 |
* ``_rotr`` |
| 6646 |
* ``_rotwl`` |
| 6647 |
* ``_rotwr`` |
| 6648 |
* ``_lrotl`` |
| 6649 |
* ``_lrotr`` |
| 6650 |
* ``_subborrow_u32`` |
| 6651 |
* ``_subborrow_u64`` |
| 6652 |
|
| 6653 |
Debugging the Compiler |
| 6654 |
====================== |
| 6655 |
|
| 6656 |
Clang supports a number of pragma directives that help debugging the compiler itself. |
| 6657 |
Syntax is the following: `#pragma clang __debug <command> <arguments>`. |
| 6658 |
Note, all of debugging pragmas are subject to change. |
| 6659 |
|
| 6660 |
`dump` |
| 6661 |
------ |
| 6662 |
Accepts either a single identifier or an expression. When a single identifier is passed, |
| 6663 |
the lookup results for the identifier are printed to `stderr`. When an expression is passed, |
| 6664 |
the AST for the expression is printed to `stderr`. The expression is an unevaluated operand, |
| 6665 |
so things like overload resolution and template instantiations are performed, |
| 6666 |
but the expression has no runtime effects. |
| 6667 |
Type- and value-dependent expressions are not supported yet. |
| 6668 |
|
| 6669 |
This facility is designed to aid with testing name lookup machinery. |
| 6670 |
|
| 6671 |
Predefined Macros |
| 6672 |
================= |
| 6673 |
|
| 6674 |
`__GCC_DESTRUCTIVE_SIZE` and `__GCC_CONSTRUCTIVE_SIZE` |
| 6675 |
------------------------------------------------------ |
| 6676 |
Specify the mimum offset between two objects to avoid false sharing and the |
| 6677 |
maximum size of contiguous memory to promote true sharing, respectively. These |
| 6678 |
macros are predefined in all C and C++ language modes, but can be redefined on |
| 6679 |
the command line with ``-D`` to specify different values as needed or can be |
| 6680 |
undefined on the command line with ``-U`` to disable support for the feature. |
| 6681 |
|
| 6682 |
**Note: the values the macros expand to are not guaranteed to be stable. They |
| 6683 |
are are affected by architectures and CPU tuning flags, can change between |
| 6684 |
releases of Clang and will not match the values defined by other compilers such |
| 6685 |
as GCC.** |
| 6686 |
|
| 6687 |
Compiling different TUs depending on these flags (including use of |
| 6688 |
``std::hardware_constructive_interference`` or |
| 6689 |
``std::hardware_destructive_interference``) with different compilers, macro |
| 6690 |
definitions, or architecture flags will lead to ODR violations and should be |
| 6691 |
avoided. |
| 6692 |
|
| 6693 |
``#embed`` Parameters |
| 6694 |
===================== |
| 6695 |
|
| 6696 |
``clang::offset`` |
| 6697 |
----------------- |
| 6698 |
The ``clang::offset`` embed parameter may appear zero or one time in the |
| 6699 |
embed parameter sequence. Its preprocessor argument clause shall be present and |
| 6700 |
have the form: |
| 6701 |
|
| 6702 |
..code-block: text |
| 6703 |
|
| 6704 |
( constant-expression ) |
| 6705 |
|
| 6706 |
and shall be an integer constant expression. The integer constant expression |
| 6707 |
shall not evaluate to a value less than 0. The token ``defined`` shall not |
| 6708 |
appear within the constant expression. |
| 6709 |
|
| 6710 |
The offset will be used when reading the contents of the embedded resource to |
| 6711 |
specify the starting offset to begin embedding from. The resources is treated |
| 6712 |
as being empty if the specified offset is larger than the number of bytes in |
| 6713 |
the resource. The offset will be applied *before* any ``limit`` parameters are |
| 6714 |
applied. |
| 6715 |
|
| 6716 |
Union and aggregate initialization in C |
| 6717 |
======================================= |
| 6718 |
|
| 6719 |
In C23 (N2900), when an object is initialized from initializer ``= {}``, all |
| 6720 |
elements of arrays, all members of structs, and the first members of unions are |
| 6721 |
empty-initialized recursively. In addition, all padding bits are initialized to |
| 6722 |
zero. |
| 6723 |
|
| 6724 |
Clang guarantees the following behaviors: |
| 6725 |
|
| 6726 |
* ``1:`` Clang supports initializer ``= {}`` mentioned above in all C |
| 6727 |
standards. |
| 6728 |
|
| 6729 |
* ``2:`` When unions are initialized from initializer ``= {}``, bytes outside |
| 6730 |
of the first members of unions are also initialized to zero. |
| 6731 |
|
| 6732 |
* ``3:`` When unions, structures and arrays are initialized from initializer |
| 6733 |
``= { initializer-list }``, all members not explicitly initialized in |
| 6734 |
the initializer list are empty-initialized recursively. In addition, all |
| 6735 |
padding bits are initialized to zero. |
| 6736 |
|
| 6737 |
Currently, the above extension only applies to C source code, not C++. |
| 6738 |
|
| 6739 |
|
| 6740 |
Empty Objects in C |
| 6741 |
================== |
| 6742 |
The declaration of a structure or union type which has no named members is |
| 6743 |
undefined behavior (C23 and earlier) or implementation-defined behavior (C2y). |
| 6744 |
Clang allows the declaration of a structure or union type with no named members |
| 6745 |
in all C language modes. `sizeof` for such a type returns `0`, which is |
| 6746 |
different behavior than in C++ (where the size of such an object is typically |
| 6747 |
`1`). |
| 6748 |
|
| 6749 |
|
| 6750 |
Qualified function types in C |
| 6751 |
============================= |
| 6752 |
Declaring a function with a qualified type in C is undefined behavior (C23 and |
| 6753 |
earlier) or implementation-defined behavior (C2y). Clang allows a function type |
| 6754 |
to be specified with the ``const`` and ``volatile`` qualifiers, but ignores the |
| 6755 |
qualifications. |
| 6756 |
|
| 6757 |
.. code-block:: c |
| 6758 |
|
| 6759 |
typedef int f(void); |
| 6760 |
const volatile f func; // Qualifier on function type has no effect. |
| 6761 |
|
| 6762 |
|
| 6763 |
Note, Clang does not allow an ``_Atomic`` function type because |
| 6764 |
of explicit constraints against atomically qualified (arrays and) function |
| 6765 |
types. |
| 6766 |
|
| 6767 |
|
| 6768 |
Underspecified Object Declarations in C |
| 6769 |
======================================= |
| 6770 |
|
| 6771 |
C23 introduced the notion of `underspecified object declarations <https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3006.htm>`_ |
| 6772 |
(note, the final standards text is different from WG14 N3006 due to changes |
| 6773 |
during national body comment review). When an object is declared with the |
| 6774 |
``constexpr`` storage class specifier or has a deduced type (with the ``auto`` |
| 6775 |
specifier), it is said to be "underspecified". Underspecified declarations have |
| 6776 |
different requirements than non-underspecified declarations. In particular, the |
| 6777 |
identifier being declared cannot be used in its initialization. e.g., |
| 6778 |
|
| 6779 |
.. code-block:: c |
| 6780 |
|
| 6781 |
auto x = x; // Invalid |
| 6782 |
constexpr int y = y; // Invalid |
| 6783 |
|
| 6784 |
The standard leaves it implementation-defined whether an underspecified |
| 6785 |
declaration may introduce additional identifiers as part of the declaration. |
| 6786 |
|
| 6787 |
Clang allows additional identifiers to be declared in the following cases: |
| 6788 |
|
| 6789 |
* A compound literal may introduce a new type. e.g., |
| 6790 |
|
| 6791 |
.. code-block:: c |
| 6792 |
|
| 6793 |
auto x = (struct S { int x, y; }){ 1, 2 }; // Accepted by Clang |
| 6794 |
constexpr int i = (struct T { int x; }){ 1 }.x; // Accepted by Clang |
| 6795 |
|
| 6796 |
* The type specifier for a ``constexpr`` declaration may define a new type. |
| 6797 |
e.g., |
| 6798 |
|
| 6799 |
.. code-block:: c |
| 6800 |
|
| 6801 |
constexpr struct S { int x; } s = { 1 }; // Accepted by Clang |
| 6802 |
|
| 6803 |
* A function declarator may be declared with parameters, including parameters |
| 6804 |
which introduce a new type. e.g., |
| 6805 |
|
| 6806 |
.. code-block:: c |
| 6807 |
|
| 6808 |
constexpr int (*fp)(int x) = nullptr; // Accepted by Clang |
| 6809 |
auto f = (void (*)(struct S { int x; } s))nullptr; // Accepted by Clang |
| 6810 |
|
| 6811 |
* The initializer may contain a GNU statement expression which defines new |
| 6812 |
types or objects. e.g., |
| 6813 |
|
| 6814 |
.. code-block:: c |
| 6815 |
|
| 6816 |
constexpr int i = ({ // Accepted by Clang |
| 6817 |
constexpr int x = 12; |
| 6818 |
constexpr struct S { int x; } s = { x }; |
| 6819 |
s.x; |
| 6820 |
}); |
| 6821 |
auto x = ({ struct S { int x; } s = { 0 }; s; }); // Accepted by Clang |
| 6822 |
|
| 6823 |
Clang intentionally does not implement the changed scoping rules from C23 |
| 6824 |
for underspecified declarations. Doing so would significantly complicate the |
| 6825 |
implementation in order to get reasonable diagnostic behavior and also means |
| 6826 |
Clang fails to reject some code that should be rejected. e.g., |
| 6827 |
|
| 6828 |
.. code-block:: c |
| 6829 |
|
| 6830 |
// This should be rejected because 'x' is not in scope within the initializer |
| 6831 |
// of an underspecified declaration. Clang accepts because it treats the scope |
| 6832 |
// of the identifier as beginning immediately after the declarator, same as with |
| 6833 |
// a non-underspecified declaration. |
| 6834 |
constexpr int x = sizeof(x); |
| 6835 |
|
| 6836 |
// Clang rejects this code with a diagnostic about using the variable within its |
| 6837 |
// own initializer rather than rejecting the code with an undeclared identifier |
| 6838 |
// diagnostic. |
| 6839 |
auto x = x; |