LanguageExtensions.rst 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930
  1. =========================
  2. Clang Language Extensions
  3. =========================
  4. .. contents::
  5. :local:
  6. :depth: 1
  7. .. toctree::
  8. :hidden:
  9. BlockLanguageSpec
  10. Block-ABI-Apple
  11. Introduction
  12. ============
  13. NOTE: this document applies to the original Clang project, not the DirectX
  14. Compiler. It's made available for informational purposes only.
  15. This document describes the language extensions provided by Clang. In addition
  16. to the language extensions listed here, Clang aims to support a broad range of
  17. GCC extensions. Please see the `GCC manual
  18. <http://gcc.gnu.org/onlinedocs/gcc/C-Extensions.html>`_ for more information on
  19. these extensions.
  20. .. _langext-feature_check:
  21. Feature Checking Macros
  22. =======================
  23. Language extensions can be very useful, but only if you know you can depend on
  24. them. In order to allow fine-grain features checks, we support three builtin
  25. function-like macros. This allows you to directly test for a feature in your
  26. code without having to resort to something like autoconf or fragile "compiler
  27. version checks".
  28. ``__has_builtin``
  29. -----------------
  30. This function-like macro takes a single identifier argument that is the name of
  31. a builtin function. It evaluates to 1 if the builtin is supported or 0 if not.
  32. It can be used like this:
  33. .. code-block:: c++
  34. #ifndef __has_builtin // Optional of course.
  35. #define __has_builtin(x) 0 // Compatibility with non-clang compilers.
  36. #endif
  37. ...
  38. #if __has_builtin(__builtin_trap)
  39. __builtin_trap();
  40. #else
  41. abort();
  42. #endif
  43. ...
  44. .. _langext-__has_feature-__has_extension:
  45. ``__has_feature`` and ``__has_extension``
  46. -----------------------------------------
  47. These function-like macros take a single identifier argument that is the name
  48. of a feature. ``__has_feature`` evaluates to 1 if the feature is both
  49. supported by Clang and standardized in the current language standard or 0 if
  50. not (but see :ref:`below <langext-has-feature-back-compat>`), while
  51. ``__has_extension`` evaluates to 1 if the feature is supported by Clang in the
  52. current language (either as a language extension or a standard language
  53. feature) or 0 if not. They can be used like this:
  54. .. code-block:: c++
  55. #ifndef __has_feature // Optional of course.
  56. #define __has_feature(x) 0 // Compatibility with non-clang compilers.
  57. #endif
  58. #ifndef __has_extension
  59. #define __has_extension __has_feature // Compatibility with pre-3.0 compilers.
  60. #endif
  61. ...
  62. #if __has_feature(cxx_rvalue_references)
  63. // This code will only be compiled with the -std=c++11 and -std=gnu++11
  64. // options, because rvalue references are only standardized in C++11.
  65. #endif
  66. #if __has_extension(cxx_rvalue_references)
  67. // This code will be compiled with the -std=c++11, -std=gnu++11, -std=c++98
  68. // and -std=gnu++98 options, because rvalue references are supported as a
  69. // language extension in C++98.
  70. #endif
  71. .. _langext-has-feature-back-compat:
  72. For backward compatibility, ``__has_feature`` can also be used to test
  73. for support for non-standardized features, i.e. features not prefixed ``c_``,
  74. ``cxx_`` or ``objc_``.
  75. Another use of ``__has_feature`` is to check for compiler features not related
  76. to the language standard, such as e.g. :doc:`AddressSanitizer
  77. <AddressSanitizer>`.
  78. If the ``-pedantic-errors`` option is given, ``__has_extension`` is equivalent
  79. to ``__has_feature``.
  80. The feature tag is described along with the language feature below.
  81. The feature name or extension name can also be specified with a preceding and
  82. following ``__`` (double underscore) to avoid interference from a macro with
  83. the same name. For instance, ``__cxx_rvalue_references__`` can be used instead
  84. of ``cxx_rvalue_references``.
  85. ``__has_cpp_attribute``
  86. -----------------------
  87. This function-like macro takes a single argument that is the name of a
  88. C++11-style attribute. The argument can either be a single identifier, or a
  89. scoped identifier. If the attribute is supported, a nonzero value is returned.
  90. If the attribute is a standards-based attribute, this macro returns a nonzero
  91. value based on the year and month in which the attribute was voted into the
  92. working draft. If the attribute is not supported by the current compliation
  93. target, this macro evaluates to 0. It can be used like this:
  94. .. code-block:: c++
  95. #ifndef __has_cpp_attribute // Optional of course.
  96. #define __has_cpp_attribute(x) 0 // Compatibility with non-clang compilers.
  97. #endif
  98. ...
  99. #if __has_cpp_attribute(clang::fallthrough)
  100. #define FALLTHROUGH [[clang::fallthrough]]
  101. #else
  102. #define FALLTHROUGH
  103. #endif
  104. ...
  105. The attribute identifier (but not scope) can also be specified with a preceding
  106. and following ``__`` (double underscore) to avoid interference from a macro with
  107. the same name. For instance, ``gnu::__const__`` can be used instead of
  108. ``gnu::const``.
  109. ``__has_attribute``
  110. -------------------
  111. This function-like macro takes a single identifier argument that is the name of
  112. a GNU-style attribute. It evaluates to 1 if the attribute is supported by the
  113. current compilation target, or 0 if not. It can be used like this:
  114. .. code-block:: c++
  115. #ifndef __has_attribute // Optional of course.
  116. #define __has_attribute(x) 0 // Compatibility with non-clang compilers.
  117. #endif
  118. ...
  119. #if __has_attribute(always_inline)
  120. #define ALWAYS_INLINE __attribute__((always_inline))
  121. #else
  122. #define ALWAYS_INLINE
  123. #endif
  124. ...
  125. The attribute name can also be specified with a preceding and following ``__``
  126. (double underscore) to avoid interference from a macro with the same name. For
  127. instance, ``__always_inline__`` can be used instead of ``always_inline``.
  128. ``__has_declspec_attribute``
  129. ----------------------------
  130. This function-like macro takes a single identifier argument that is the name of
  131. an attribute implemented as a Microsoft-style ``__declspec`` attribute. It
  132. evaluates to 1 if the attribute is supported by the current compilation target,
  133. or 0 if not. It can be used like this:
  134. .. code-block:: c++
  135. #ifndef __has_declspec_attribute // Optional of course.
  136. #define __has_declspec_attribute(x) 0 // Compatibility with non-clang compilers.
  137. #endif
  138. ...
  139. #if __has_declspec_attribute(dllexport)
  140. #define DLLEXPORT __declspec(dllexport)
  141. #else
  142. #define DLLEXPORT
  143. #endif
  144. ...
  145. The attribute name can also be specified with a preceding and following ``__``
  146. (double underscore) to avoid interference from a macro with the same name. For
  147. instance, ``__dllexport__`` can be used instead of ``dllexport``.
  148. ``__is_identifier``
  149. -------------------
  150. This function-like macro takes a single identifier argument that might be either
  151. a reserved word or a regular identifier. It evaluates to 1 if the argument is just
  152. a regular identifier and not a reserved word, in the sense that it can then be
  153. used as the name of a user-defined function or variable. Otherwise it evaluates
  154. to 0. It can be used like this:
  155. .. code-block:: c++
  156. ...
  157. #ifdef __is_identifier // Compatibility with non-clang compilers.
  158. #if __is_identifier(__wchar_t)
  159. typedef wchar_t __wchar_t;
  160. #endif
  161. #endif
  162. __wchar_t WideCharacter;
  163. ...
  164. Include File Checking Macros
  165. ============================
  166. Not all developments systems have the same include files. The
  167. :ref:`langext-__has_include` and :ref:`langext-__has_include_next` macros allow
  168. you to check for the existence of an include file before doing a possibly
  169. failing ``#include`` directive. Include file checking macros must be used
  170. as expressions in ``#if`` or ``#elif`` preprocessing directives.
  171. .. _langext-__has_include:
  172. ``__has_include``
  173. -----------------
  174. This function-like macro takes a single file name string argument that is the
  175. name of an include file. It evaluates to 1 if the file can be found using the
  176. include paths, or 0 otherwise:
  177. .. code-block:: c++
  178. // Note the two possible file name string formats.
  179. #if __has_include("myinclude.h") && __has_include(<stdint.h>)
  180. # include "myinclude.h"
  181. #endif
  182. To test for this feature, use ``#if defined(__has_include)``:
  183. .. code-block:: c++
  184. // To avoid problem with non-clang compilers not having this macro.
  185. #if defined(__has_include)
  186. #if __has_include("myinclude.h")
  187. # include "myinclude.h"
  188. #endif
  189. #endif
  190. .. _langext-__has_include_next:
  191. ``__has_include_next``
  192. ----------------------
  193. This function-like macro takes a single file name string argument that is the
  194. name of an include file. It is like ``__has_include`` except that it looks for
  195. the second instance of the given file found in the include paths. It evaluates
  196. to 1 if the second instance of the file can be found using the include paths,
  197. or 0 otherwise:
  198. .. code-block:: c++
  199. // Note the two possible file name string formats.
  200. #if __has_include_next("myinclude.h") && __has_include_next(<stdint.h>)
  201. # include_next "myinclude.h"
  202. #endif
  203. // To avoid problem with non-clang compilers not having this macro.
  204. #if defined(__has_include_next)
  205. #if __has_include_next("myinclude.h")
  206. # include_next "myinclude.h"
  207. #endif
  208. #endif
  209. Note that ``__has_include_next``, like the GNU extension ``#include_next``
  210. directive, is intended for use in headers only, and will issue a warning if
  211. used in the top-level compilation file. A warning will also be issued if an
  212. absolute path is used in the file argument.
  213. ``__has_warning``
  214. -----------------
  215. This function-like macro takes a string literal that represents a command line
  216. option for a warning and returns true if that is a valid warning option.
  217. .. code-block:: c++
  218. #if __has_warning("-Wformat")
  219. ...
  220. #endif
  221. Builtin Macros
  222. ==============
  223. ``__BASE_FILE__``
  224. Defined to a string that contains the name of the main input file passed to
  225. Clang.
  226. ``__COUNTER__``
  227. Defined to an integer value that starts at zero and is incremented each time
  228. the ``__COUNTER__`` macro is expanded.
  229. ``__INCLUDE_LEVEL__``
  230. Defined to an integral value that is the include depth of the file currently
  231. being translated. For the main file, this value is zero.
  232. ``__TIMESTAMP__``
  233. Defined to the date and time of the last modification of the current source
  234. file.
  235. ``__clang__``
  236. Defined when compiling with Clang
  237. ``__clang_major__``
  238. Defined to the major marketing version number of Clang (e.g., the 2 in
  239. 2.0.1). Note that marketing version numbers should not be used to check for
  240. language features, as different vendors use different numbering schemes.
  241. Instead, use the :ref:`langext-feature_check`.
  242. ``__clang_minor__``
  243. Defined to the minor version number of Clang (e.g., the 0 in 2.0.1). Note
  244. that marketing version numbers should not be used to check for language
  245. features, as different vendors use different numbering schemes. Instead, use
  246. the :ref:`langext-feature_check`.
  247. ``__clang_patchlevel__``
  248. Defined to the marketing patch level of Clang (e.g., the 1 in 2.0.1).
  249. ``__clang_version__``
  250. Defined to a string that captures the Clang marketing version, including the
  251. Subversion tag or revision number, e.g., "``1.5 (trunk 102332)``".
  252. .. _langext-vectors:
  253. Vectors and Extended Vectors
  254. ============================
  255. Supports the GCC, OpenCL, AltiVec and NEON vector extensions.
  256. OpenCL vector types are created using ``ext_vector_type`` attribute. It
  257. support for ``V.xyzw`` syntax and other tidbits as seen in OpenCL. An example
  258. is:
  259. .. code-block:: c++
  260. typedef float float4 __attribute__((ext_vector_type(4)));
  261. typedef float float2 __attribute__((ext_vector_type(2)));
  262. float4 foo(float2 a, float2 b) {
  263. float4 c;
  264. c.xz = a;
  265. c.yw = b;
  266. return c;
  267. }
  268. Query for this feature with ``__has_extension(attribute_ext_vector_type)``.
  269. Giving ``-faltivec`` option to clang enables support for AltiVec vector syntax
  270. and functions. For example:
  271. .. code-block:: c++
  272. vector float foo(vector int a) {
  273. vector int b;
  274. b = vec_add(a, a) + a;
  275. return (vector float)b;
  276. }
  277. NEON vector types are created using ``neon_vector_type`` and
  278. ``neon_polyvector_type`` attributes. For example:
  279. .. code-block:: c++
  280. typedef __attribute__((neon_vector_type(8))) int8_t int8x8_t;
  281. typedef __attribute__((neon_polyvector_type(16))) poly8_t poly8x16_t;
  282. int8x8_t foo(int8x8_t a) {
  283. int8x8_t v;
  284. v = a;
  285. return v;
  286. }
  287. Vector Literals
  288. ---------------
  289. Vector literals can be used to create vectors from a set of scalars, or
  290. vectors. Either parentheses or braces form can be used. In the parentheses
  291. form the number of literal values specified must be one, i.e. referring to a
  292. scalar value, or must match the size of the vector type being created. If a
  293. single scalar literal value is specified, the scalar literal value will be
  294. replicated to all the components of the vector type. In the brackets form any
  295. number of literals can be specified. For example:
  296. .. code-block:: c++
  297. typedef int v4si __attribute__((__vector_size__(16)));
  298. typedef float float4 __attribute__((ext_vector_type(4)));
  299. typedef float float2 __attribute__((ext_vector_type(2)));
  300. v4si vsi = (v4si){1, 2, 3, 4};
  301. float4 vf = (float4)(1.0f, 2.0f, 3.0f, 4.0f);
  302. vector int vi1 = (vector int)(1); // vi1 will be (1, 1, 1, 1).
  303. vector int vi2 = (vector int){1}; // vi2 will be (1, 0, 0, 0).
  304. vector int vi3 = (vector int)(1, 2); // error
  305. vector int vi4 = (vector int){1, 2}; // vi4 will be (1, 2, 0, 0).
  306. vector int vi5 = (vector int)(1, 2, 3, 4);
  307. float4 vf = (float4)((float2)(1.0f, 2.0f), (float2)(3.0f, 4.0f));
  308. Vector Operations
  309. -----------------
  310. The table below shows the support for each operation by vector extension. A
  311. dash indicates that an operation is not accepted according to a corresponding
  312. specification.
  313. ============================== ======= ======= ======= =======
  314. Opeator OpenCL AltiVec GCC NEON
  315. ============================== ======= ======= ======= =======
  316. [] yes yes yes --
  317. unary operators +, -- yes yes yes --
  318. ++, -- -- yes yes yes --
  319. +,--,*,/,% yes yes yes --
  320. bitwise operators &,|,^,~ yes yes yes --
  321. >>,<< yes yes yes --
  322. !, &&, || yes -- -- --
  323. ==, !=, >, <, >=, <= yes yes -- --
  324. = yes yes yes yes
  325. :? yes -- -- --
  326. sizeof yes yes yes yes
  327. C-style cast yes yes yes no
  328. reinterpret_cast yes no yes no
  329. static_cast yes no yes no
  330. const_cast no no no no
  331. ============================== ======= ======= ======= =======
  332. See also :ref:`langext-__builtin_shufflevector`, :ref:`langext-__builtin_convertvector`.
  333. Messages on ``deprecated`` and ``unavailable`` Attributes
  334. =========================================================
  335. An optional string message can be added to the ``deprecated`` and
  336. ``unavailable`` attributes. For example:
  337. .. code-block:: c++
  338. void explode(void) __attribute__((deprecated("extremely unsafe, use 'combust' instead!!!")));
  339. If the deprecated or unavailable declaration is used, the message will be
  340. incorporated into the appropriate diagnostic:
  341. .. code-block:: c++
  342. harmless.c:4:3: warning: 'explode' is deprecated: extremely unsafe, use 'combust' instead!!!
  343. [-Wdeprecated-declarations]
  344. explode();
  345. ^
  346. Query for this feature with
  347. ``__has_extension(attribute_deprecated_with_message)`` and
  348. ``__has_extension(attribute_unavailable_with_message)``.
  349. Attributes on Enumerators
  350. =========================
  351. Clang allows attributes to be written on individual enumerators. This allows
  352. enumerators to be deprecated, made unavailable, etc. The attribute must appear
  353. after the enumerator name and before any initializer, like so:
  354. .. code-block:: c++
  355. enum OperationMode {
  356. OM_Invalid,
  357. OM_Normal,
  358. OM_Terrified __attribute__((deprecated)),
  359. OM_AbortOnError __attribute__((deprecated)) = 4
  360. };
  361. Attributes on the ``enum`` declaration do not apply to individual enumerators.
  362. Query for this feature with ``__has_extension(enumerator_attributes)``.
  363. 'User-Specified' System Frameworks
  364. ==================================
  365. Clang provides a mechanism by which frameworks can be built in such a way that
  366. they will always be treated as being "system frameworks", even if they are not
  367. present in a system framework directory. This can be useful to system
  368. framework developers who want to be able to test building other applications
  369. with development builds of their framework, including the manner in which the
  370. compiler changes warning behavior for system headers.
  371. Framework developers can opt-in to this mechanism by creating a
  372. "``.system_framework``" file at the top-level of their framework. That is, the
  373. framework should have contents like:
  374. .. code-block:: none
  375. .../TestFramework.framework
  376. .../TestFramework.framework/.system_framework
  377. .../TestFramework.framework/Headers
  378. .../TestFramework.framework/Headers/TestFramework.h
  379. ...
  380. Clang will treat the presence of this file as an indicator that the framework
  381. should be treated as a system framework, regardless of how it was found in the
  382. framework search path. For consistency, we recommend that such files never be
  383. included in installed versions of the framework.
  384. Checks for Standard Language Features
  385. =====================================
  386. The ``__has_feature`` macro can be used to query if certain standard language
  387. features are enabled. The ``__has_extension`` macro can be used to query if
  388. language features are available as an extension when compiling for a standard
  389. which does not provide them. The features which can be tested are listed here.
  390. Since Clang 3.4, the C++ SD-6 feature test macros are also supported.
  391. These are macros with names of the form ``__cpp_<feature_name>``, and are
  392. intended to be a portable way to query the supported features of the compiler.
  393. See `the C++ status page <http://clang.llvm.org/cxx_status.html#ts>`_ for
  394. information on the version of SD-6 supported by each Clang release, and the
  395. macros provided by that revision of the recommendations.
  396. C++98
  397. -----
  398. The features listed below are part of the C++98 standard. These features are
  399. enabled by default when compiling C++ code.
  400. C++ exceptions
  401. ^^^^^^^^^^^^^^
  402. Use ``__has_feature(cxx_exceptions)`` to determine if C++ exceptions have been
  403. enabled. For example, compiling code with ``-fno-exceptions`` disables C++
  404. exceptions.
  405. C++ RTTI
  406. ^^^^^^^^
  407. Use ``__has_feature(cxx_rtti)`` to determine if C++ RTTI has been enabled. For
  408. example, compiling code with ``-fno-rtti`` disables the use of RTTI.
  409. C++11
  410. -----
  411. The features listed below are part of the C++11 standard. As a result, all
  412. these features are enabled with the ``-std=c++11`` or ``-std=gnu++11`` option
  413. when compiling C++ code.
  414. C++11 SFINAE includes access control
  415. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  416. Use ``__has_feature(cxx_access_control_sfinae)`` or
  417. ``__has_extension(cxx_access_control_sfinae)`` to determine whether
  418. access-control errors (e.g., calling a private constructor) are considered to
  419. be template argument deduction errors (aka SFINAE errors), per `C++ DR1170
  420. <http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1170>`_.
  421. C++11 alias templates
  422. ^^^^^^^^^^^^^^^^^^^^^
  423. Use ``__has_feature(cxx_alias_templates)`` or
  424. ``__has_extension(cxx_alias_templates)`` to determine if support for C++11's
  425. alias declarations and alias templates is enabled.
  426. C++11 alignment specifiers
  427. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  428. Use ``__has_feature(cxx_alignas)`` or ``__has_extension(cxx_alignas)`` to
  429. determine if support for alignment specifiers using ``alignas`` is enabled.
  430. Use ``__has_feature(cxx_alignof)`` or ``__has_extension(cxx_alignof)`` to
  431. determine if support for the ``alignof`` keyword is enabled.
  432. C++11 attributes
  433. ^^^^^^^^^^^^^^^^
  434. Use ``__has_feature(cxx_attributes)`` or ``__has_extension(cxx_attributes)`` to
  435. determine if support for attribute parsing with C++11's square bracket notation
  436. is enabled.
  437. C++11 generalized constant expressions
  438. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  439. Use ``__has_feature(cxx_constexpr)`` to determine if support for generalized
  440. constant expressions (e.g., ``constexpr``) is enabled.
  441. C++11 ``decltype()``
  442. ^^^^^^^^^^^^^^^^^^^^
  443. Use ``__has_feature(cxx_decltype)`` or ``__has_extension(cxx_decltype)`` to
  444. determine if support for the ``decltype()`` specifier is enabled. C++11's
  445. ``decltype`` does not require type-completeness of a function call expression.
  446. Use ``__has_feature(cxx_decltype_incomplete_return_types)`` or
  447. ``__has_extension(cxx_decltype_incomplete_return_types)`` to determine if
  448. support for this feature is enabled.
  449. C++11 default template arguments in function templates
  450. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  451. Use ``__has_feature(cxx_default_function_template_args)`` or
  452. ``__has_extension(cxx_default_function_template_args)`` to determine if support
  453. for default template arguments in function templates is enabled.
  454. C++11 ``default``\ ed functions
  455. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  456. Use ``__has_feature(cxx_defaulted_functions)`` or
  457. ``__has_extension(cxx_defaulted_functions)`` to determine if support for
  458. defaulted function definitions (with ``= default``) is enabled.
  459. C++11 delegating constructors
  460. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  461. Use ``__has_feature(cxx_delegating_constructors)`` to determine if support for
  462. delegating constructors is enabled.
  463. C++11 ``deleted`` functions
  464. ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  465. Use ``__has_feature(cxx_deleted_functions)`` or
  466. ``__has_extension(cxx_deleted_functions)`` to determine if support for deleted
  467. function definitions (with ``= delete``) is enabled.
  468. C++11 explicit conversion functions
  469. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  470. Use ``__has_feature(cxx_explicit_conversions)`` to determine if support for
  471. ``explicit`` conversion functions is enabled.
  472. C++11 generalized initializers
  473. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  474. Use ``__has_feature(cxx_generalized_initializers)`` to determine if support for
  475. generalized initializers (using braced lists and ``std::initializer_list``) is
  476. enabled.
  477. C++11 implicit move constructors/assignment operators
  478. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  479. Use ``__has_feature(cxx_implicit_moves)`` to determine if Clang will implicitly
  480. generate move constructors and move assignment operators where needed.
  481. C++11 inheriting constructors
  482. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  483. Use ``__has_feature(cxx_inheriting_constructors)`` to determine if support for
  484. inheriting constructors is enabled.
  485. C++11 inline namespaces
  486. ^^^^^^^^^^^^^^^^^^^^^^^
  487. Use ``__has_feature(cxx_inline_namespaces)`` or
  488. ``__has_extension(cxx_inline_namespaces)`` to determine if support for inline
  489. namespaces is enabled.
  490. C++11 lambdas
  491. ^^^^^^^^^^^^^
  492. Use ``__has_feature(cxx_lambdas)`` or ``__has_extension(cxx_lambdas)`` to
  493. determine if support for lambdas is enabled.
  494. C++11 local and unnamed types as template arguments
  495. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  496. Use ``__has_feature(cxx_local_type_template_args)`` or
  497. ``__has_extension(cxx_local_type_template_args)`` to determine if support for
  498. local and unnamed types as template arguments is enabled.
  499. C++11 noexcept
  500. ^^^^^^^^^^^^^^
  501. Use ``__has_feature(cxx_noexcept)`` or ``__has_extension(cxx_noexcept)`` to
  502. determine if support for noexcept exception specifications is enabled.
  503. C++11 in-class non-static data member initialization
  504. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  505. Use ``__has_feature(cxx_nonstatic_member_init)`` to determine whether in-class
  506. initialization of non-static data members is enabled.
  507. C++11 ``nullptr``
  508. ^^^^^^^^^^^^^^^^^
  509. Use ``__has_feature(cxx_nullptr)`` or ``__has_extension(cxx_nullptr)`` to
  510. determine if support for ``nullptr`` is enabled.
  511. C++11 ``override control``
  512. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  513. Use ``__has_feature(cxx_override_control)`` or
  514. ``__has_extension(cxx_override_control)`` to determine if support for the
  515. override control keywords is enabled.
  516. C++11 reference-qualified functions
  517. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  518. Use ``__has_feature(cxx_reference_qualified_functions)`` or
  519. ``__has_extension(cxx_reference_qualified_functions)`` to determine if support
  520. for reference-qualified functions (e.g., member functions with ``&`` or ``&&``
  521. applied to ``*this``) is enabled.
  522. C++11 range-based ``for`` loop
  523. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  524. Use ``__has_feature(cxx_range_for)`` or ``__has_extension(cxx_range_for)`` to
  525. determine if support for the range-based for loop is enabled.
  526. C++11 raw string literals
  527. ^^^^^^^^^^^^^^^^^^^^^^^^^
  528. Use ``__has_feature(cxx_raw_string_literals)`` to determine if support for raw
  529. string literals (e.g., ``R"x(foo\bar)x"``) is enabled.
  530. C++11 rvalue references
  531. ^^^^^^^^^^^^^^^^^^^^^^^
  532. Use ``__has_feature(cxx_rvalue_references)`` or
  533. ``__has_extension(cxx_rvalue_references)`` to determine if support for rvalue
  534. references is enabled.
  535. C++11 ``static_assert()``
  536. ^^^^^^^^^^^^^^^^^^^^^^^^^
  537. Use ``__has_feature(cxx_static_assert)`` or
  538. ``__has_extension(cxx_static_assert)`` to determine if support for compile-time
  539. assertions using ``static_assert`` is enabled.
  540. C++11 ``thread_local``
  541. ^^^^^^^^^^^^^^^^^^^^^^
  542. Use ``__has_feature(cxx_thread_local)`` to determine if support for
  543. ``thread_local`` variables is enabled.
  544. C++11 type inference
  545. ^^^^^^^^^^^^^^^^^^^^
  546. Use ``__has_feature(cxx_auto_type)`` or ``__has_extension(cxx_auto_type)`` to
  547. determine C++11 type inference is supported using the ``auto`` specifier. If
  548. this is disabled, ``auto`` will instead be a storage class specifier, as in C
  549. or C++98.
  550. C++11 strongly typed enumerations
  551. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  552. Use ``__has_feature(cxx_strong_enums)`` or
  553. ``__has_extension(cxx_strong_enums)`` to determine if support for strongly
  554. typed, scoped enumerations is enabled.
  555. C++11 trailing return type
  556. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  557. Use ``__has_feature(cxx_trailing_return)`` or
  558. ``__has_extension(cxx_trailing_return)`` to determine if support for the
  559. alternate function declaration syntax with trailing return type is enabled.
  560. C++11 Unicode string literals
  561. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  562. Use ``__has_feature(cxx_unicode_literals)`` to determine if support for Unicode
  563. string literals is enabled.
  564. C++11 unrestricted unions
  565. ^^^^^^^^^^^^^^^^^^^^^^^^^
  566. Use ``__has_feature(cxx_unrestricted_unions)`` to determine if support for
  567. unrestricted unions is enabled.
  568. C++11 user-defined literals
  569. ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  570. Use ``__has_feature(cxx_user_literals)`` to determine if support for
  571. user-defined literals is enabled.
  572. C++11 variadic templates
  573. ^^^^^^^^^^^^^^^^^^^^^^^^
  574. Use ``__has_feature(cxx_variadic_templates)`` or
  575. ``__has_extension(cxx_variadic_templates)`` to determine if support for
  576. variadic templates is enabled.
  577. C++1y
  578. -----
  579. The features listed below are part of the committee draft for the C++1y
  580. standard. As a result, all these features are enabled with the ``-std=c++1y``
  581. or ``-std=gnu++1y`` option when compiling C++ code.
  582. C++1y binary literals
  583. ^^^^^^^^^^^^^^^^^^^^^
  584. Use ``__has_feature(cxx_binary_literals)`` or
  585. ``__has_extension(cxx_binary_literals)`` to determine whether
  586. binary literals (for instance, ``0b10010``) are recognized. Clang supports this
  587. feature as an extension in all language modes.
  588. C++1y contextual conversions
  589. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  590. Use ``__has_feature(cxx_contextual_conversions)`` or
  591. ``__has_extension(cxx_contextual_conversions)`` to determine if the C++1y rules
  592. are used when performing an implicit conversion for an array bound in a
  593. *new-expression*, the operand of a *delete-expression*, an integral constant
  594. expression, or a condition in a ``switch`` statement.
  595. C++1y decltype(auto)
  596. ^^^^^^^^^^^^^^^^^^^^
  597. Use ``__has_feature(cxx_decltype_auto)`` or
  598. ``__has_extension(cxx_decltype_auto)`` to determine if support
  599. for the ``decltype(auto)`` placeholder type is enabled.
  600. C++1y default initializers for aggregates
  601. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  602. Use ``__has_feature(cxx_aggregate_nsdmi)`` or
  603. ``__has_extension(cxx_aggregate_nsdmi)`` to determine if support
  604. for default initializers in aggregate members is enabled.
  605. C++1y digit separators
  606. ^^^^^^^^^^^^^^^^^^^^^^
  607. Use ``__cpp_digit_separators`` to determine if support for digit separators
  608. using single quotes (for instance, ``10'000``) is enabled. At this time, there
  609. is no corresponding ``__has_feature`` name
  610. C++1y generalized lambda capture
  611. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  612. Use ``__has_feature(cxx_init_captures)`` or
  613. ``__has_extension(cxx_init_captures)`` to determine if support for
  614. lambda captures with explicit initializers is enabled
  615. (for instance, ``[n(0)] { return ++n; }``).
  616. C++1y generic lambdas
  617. ^^^^^^^^^^^^^^^^^^^^^
  618. Use ``__has_feature(cxx_generic_lambdas)`` or
  619. ``__has_extension(cxx_generic_lambdas)`` to determine if support for generic
  620. (polymorphic) lambdas is enabled
  621. (for instance, ``[] (auto x) { return x + 1; }``).
  622. C++1y relaxed constexpr
  623. ^^^^^^^^^^^^^^^^^^^^^^^
  624. Use ``__has_feature(cxx_relaxed_constexpr)`` or
  625. ``__has_extension(cxx_relaxed_constexpr)`` to determine if variable
  626. declarations, local variable modification, and control flow constructs
  627. are permitted in ``constexpr`` functions.
  628. C++1y return type deduction
  629. ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  630. Use ``__has_feature(cxx_return_type_deduction)`` or
  631. ``__has_extension(cxx_return_type_deduction)`` to determine if support
  632. for return type deduction for functions (using ``auto`` as a return type)
  633. is enabled.
  634. C++1y runtime-sized arrays
  635. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  636. Use ``__has_feature(cxx_runtime_array)`` or
  637. ``__has_extension(cxx_runtime_array)`` to determine if support
  638. for arrays of runtime bound (a restricted form of variable-length arrays)
  639. is enabled.
  640. Clang's implementation of this feature is incomplete.
  641. C++1y variable templates
  642. ^^^^^^^^^^^^^^^^^^^^^^^^
  643. Use ``__has_feature(cxx_variable_templates)`` or
  644. ``__has_extension(cxx_variable_templates)`` to determine if support for
  645. templated variable declarations is enabled.
  646. C11
  647. ---
  648. The features listed below are part of the C11 standard. As a result, all these
  649. features are enabled with the ``-std=c11`` or ``-std=gnu11`` option when
  650. compiling C code. Additionally, because these features are all
  651. backward-compatible, they are available as extensions in all language modes.
  652. C11 alignment specifiers
  653. ^^^^^^^^^^^^^^^^^^^^^^^^
  654. Use ``__has_feature(c_alignas)`` or ``__has_extension(c_alignas)`` to determine
  655. if support for alignment specifiers using ``_Alignas`` is enabled.
  656. Use ``__has_feature(c_alignof)`` or ``__has_extension(c_alignof)`` to determine
  657. if support for the ``_Alignof`` keyword is enabled.
  658. C11 atomic operations
  659. ^^^^^^^^^^^^^^^^^^^^^
  660. Use ``__has_feature(c_atomic)`` or ``__has_extension(c_atomic)`` to determine
  661. if support for atomic types using ``_Atomic`` is enabled. Clang also provides
  662. :ref:`a set of builtins <langext-__c11_atomic>` which can be used to implement
  663. the ``<stdatomic.h>`` operations on ``_Atomic`` types. Use
  664. ``__has_include(<stdatomic.h>)`` to determine if C11's ``<stdatomic.h>`` header
  665. is available.
  666. Clang will use the system's ``<stdatomic.h>`` header when one is available, and
  667. will otherwise use its own. When using its own, implementations of the atomic
  668. operations are provided as macros. In the cases where C11 also requires a real
  669. function, this header provides only the declaration of that function (along
  670. with a shadowing macro implementation), and you must link to a library which
  671. provides a definition of the function if you use it instead of the macro.
  672. C11 generic selections
  673. ^^^^^^^^^^^^^^^^^^^^^^
  674. Use ``__has_feature(c_generic_selections)`` or
  675. ``__has_extension(c_generic_selections)`` to determine if support for generic
  676. selections is enabled.
  677. As an extension, the C11 generic selection expression is available in all
  678. languages supported by Clang. The syntax is the same as that given in the C11
  679. standard.
  680. In C, type compatibility is decided according to the rules given in the
  681. appropriate standard, but in C++, which lacks the type compatibility rules used
  682. in C, types are considered compatible only if they are equivalent.
  683. C11 ``_Static_assert()``
  684. ^^^^^^^^^^^^^^^^^^^^^^^^
  685. Use ``__has_feature(c_static_assert)`` or ``__has_extension(c_static_assert)``
  686. to determine if support for compile-time assertions using ``_Static_assert`` is
  687. enabled.
  688. C11 ``_Thread_local``
  689. ^^^^^^^^^^^^^^^^^^^^^
  690. Use ``__has_feature(c_thread_local)`` or ``__has_extension(c_thread_local)``
  691. to determine if support for ``_Thread_local`` variables is enabled.
  692. Modules
  693. -------
  694. Use ``__has_feature(modules)`` to determine if Modules have been enabled.
  695. For example, compiling code with ``-fmodules`` enables the use of Modules.
  696. More information could be found `here <http://clang.llvm.org/docs/Modules.html>`_.
  697. Checks for Type Trait Primitives
  698. ================================
  699. Type trait primitives are special builtin constant expressions that can be used
  700. by the standard C++ library to facilitate or simplify the implementation of
  701. user-facing type traits in the <type_traits> header.
  702. They are not intended to be used directly by user code because they are
  703. implementation-defined and subject to change -- as such they're tied closely to
  704. the supported set of system headers, currently:
  705. * LLVM's own libc++
  706. * GNU libstdc++
  707. * The Microsoft standard C++ library
  708. Clang supports the `GNU C++ type traits
  709. <http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html>`_ and a subset of the
  710. `Microsoft Visual C++ Type traits
  711. <http://msdn.microsoft.com/en-us/library/ms177194(v=VS.100).aspx>`_.
  712. Feature detection is supported only for some of the primitives at present. User
  713. code should not use these checks because they bear no direct relation to the
  714. actual set of type traits supported by the C++ standard library.
  715. For type trait ``__X``, ``__has_extension(X)`` indicates the presence of the
  716. type trait primitive in the compiler. A simplistic usage example as might be
  717. seen in standard C++ headers follows:
  718. .. code-block:: c++
  719. #if __has_extension(is_convertible_to)
  720. template<typename From, typename To>
  721. struct is_convertible_to {
  722. static const bool value = __is_convertible_to(From, To);
  723. };
  724. #else
  725. // Emulate type trait for compatibility with other compilers.
  726. #endif
  727. The following type trait primitives are supported by Clang:
  728. * ``__has_nothrow_assign`` (GNU, Microsoft)
  729. * ``__has_nothrow_copy`` (GNU, Microsoft)
  730. * ``__has_nothrow_constructor`` (GNU, Microsoft)
  731. * ``__has_trivial_assign`` (GNU, Microsoft)
  732. * ``__has_trivial_copy`` (GNU, Microsoft)
  733. * ``__has_trivial_constructor`` (GNU, Microsoft)
  734. * ``__has_trivial_destructor`` (GNU, Microsoft)
  735. * ``__has_virtual_destructor`` (GNU, Microsoft)
  736. * ``__is_abstract`` (GNU, Microsoft)
  737. * ``__is_base_of`` (GNU, Microsoft)
  738. * ``__is_class`` (GNU, Microsoft)
  739. * ``__is_convertible_to`` (Microsoft)
  740. * ``__is_empty`` (GNU, Microsoft)
  741. * ``__is_enum`` (GNU, Microsoft)
  742. * ``__is_interface_class`` (Microsoft)
  743. * ``__is_pod`` (GNU, Microsoft)
  744. * ``__is_polymorphic`` (GNU, Microsoft)
  745. * ``__is_union`` (GNU, Microsoft)
  746. * ``__is_literal(type)``: Determines whether the given type is a literal type
  747. * ``__is_final``: Determines whether the given type is declared with a
  748. ``final`` class-virt-specifier.
  749. * ``__underlying_type(type)``: Retrieves the underlying type for a given
  750. ``enum`` type. This trait is required to implement the C++11 standard
  751. library.
  752. * ``__is_trivially_assignable(totype, fromtype)``: Determines whether a value
  753. of type ``totype`` can be assigned to from a value of type ``fromtype`` such
  754. that no non-trivial functions are called as part of that assignment. This
  755. trait is required to implement the C++11 standard library.
  756. * ``__is_trivially_constructible(type, argtypes...)``: Determines whether a
  757. value of type ``type`` can be direct-initialized with arguments of types
  758. ``argtypes...`` such that no non-trivial functions are called as part of
  759. that initialization. This trait is required to implement the C++11 standard
  760. library.
  761. * ``__is_destructible`` (MSVC 2013): partially implemented
  762. * ``__is_nothrow_destructible`` (MSVC 2013): partially implemented
  763. * ``__is_nothrow_assignable`` (MSVC 2013, clang)
  764. * ``__is_constructible`` (MSVC 2013, clang)
  765. * ``__is_nothrow_constructible`` (MSVC 2013, clang)
  766. Blocks
  767. ======
  768. The syntax and high level language feature description is in
  769. :doc:`BlockLanguageSpec<BlockLanguageSpec>`. Implementation and ABI details for
  770. the clang implementation are in :doc:`Block-ABI-Apple<Block-ABI-Apple>`.
  771. Query for this feature with ``__has_extension(blocks)``.
  772. Objective-C Features
  773. ====================
  774. Related result types
  775. --------------------
  776. According to Cocoa conventions, Objective-C methods with certain names
  777. ("``init``", "``alloc``", etc.) always return objects that are an instance of
  778. the receiving class's type. Such methods are said to have a "related result
  779. type", meaning that a message send to one of these methods will have the same
  780. static type as an instance of the receiver class. For example, given the
  781. following classes:
  782. .. code-block:: objc
  783. @interface NSObject
  784. + (id)alloc;
  785. - (id)init;
  786. @end
  787. @interface NSArray : NSObject
  788. @end
  789. and this common initialization pattern
  790. .. code-block:: objc
  791. NSArray *array = [[NSArray alloc] init];
  792. the type of the expression ``[NSArray alloc]`` is ``NSArray*`` because
  793. ``alloc`` implicitly has a related result type. Similarly, the type of the
  794. expression ``[[NSArray alloc] init]`` is ``NSArray*``, since ``init`` has a
  795. related result type and its receiver is known to have the type ``NSArray *``.
  796. If neither ``alloc`` nor ``init`` had a related result type, the expressions
  797. would have had type ``id``, as declared in the method signature.
  798. A method with a related result type can be declared by using the type
  799. ``instancetype`` as its result type. ``instancetype`` is a contextual keyword
  800. that is only permitted in the result type of an Objective-C method, e.g.
  801. .. code-block:: objc
  802. @interface A
  803. + (instancetype)constructAnA;
  804. @end
  805. The related result type can also be inferred for some methods. To determine
  806. whether a method has an inferred related result type, the first word in the
  807. camel-case selector (e.g., "``init``" in "``initWithObjects``") is considered,
  808. and the method will have a related result type if its return type is compatible
  809. with the type of its class and if:
  810. * the first word is "``alloc``" or "``new``", and the method is a class method,
  811. or
  812. * the first word is "``autorelease``", "``init``", "``retain``", or "``self``",
  813. and the method is an instance method.
  814. If a method with a related result type is overridden by a subclass method, the
  815. subclass method must also return a type that is compatible with the subclass
  816. type. For example:
  817. .. code-block:: objc
  818. @interface NSString : NSObject
  819. - (NSUnrelated *)init; // incorrect usage: NSUnrelated is not NSString or a superclass of NSString
  820. @end
  821. Related result types only affect the type of a message send or property access
  822. via the given method. In all other respects, a method with a related result
  823. type is treated the same way as method that returns ``id``.
  824. Use ``__has_feature(objc_instancetype)`` to determine whether the
  825. ``instancetype`` contextual keyword is available.
  826. Enumerations with a fixed underlying type
  827. -----------------------------------------
  828. Clang provides support for C++11 enumerations with a fixed underlying type
  829. within Objective-C. For example, one can write an enumeration type as:
  830. .. code-block:: c++
  831. typedef enum : unsigned char { Red, Green, Blue } Color;
  832. This specifies that the underlying type, which is used to store the enumeration
  833. value, is ``unsigned char``.
  834. Use ``__has_feature(objc_fixed_enum)`` to determine whether support for fixed
  835. underlying types is available in Objective-C.
  836. Interoperability with C++11 lambdas
  837. -----------------------------------
  838. Clang provides interoperability between C++11 lambdas and blocks-based APIs, by
  839. permitting a lambda to be implicitly converted to a block pointer with the
  840. corresponding signature. For example, consider an API such as ``NSArray``'s
  841. array-sorting method:
  842. .. code-block:: objc
  843. - (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr;
  844. ``NSComparator`` is simply a typedef for the block pointer ``NSComparisonResult
  845. (^)(id, id)``, and parameters of this type are generally provided with block
  846. literals as arguments. However, one can also use a C++11 lambda so long as it
  847. provides the same signature (in this case, accepting two parameters of type
  848. ``id`` and returning an ``NSComparisonResult``):
  849. .. code-block:: objc
  850. NSArray *array = @[@"string 1", @"string 21", @"string 12", @"String 11",
  851. @"String 02"];
  852. const NSStringCompareOptions comparisonOptions
  853. = NSCaseInsensitiveSearch | NSNumericSearch |
  854. NSWidthInsensitiveSearch | NSForcedOrderingSearch;
  855. NSLocale *currentLocale = [NSLocale currentLocale];
  856. NSArray *sorted
  857. = [array sortedArrayUsingComparator:[=](id s1, id s2) -> NSComparisonResult {
  858. NSRange string1Range = NSMakeRange(0, [s1 length]);
  859. return [s1 compare:s2 options:comparisonOptions
  860. range:string1Range locale:currentLocale];
  861. }];
  862. NSLog(@"sorted: %@", sorted);
  863. This code relies on an implicit conversion from the type of the lambda
  864. expression (an unnamed, local class type called the *closure type*) to the
  865. corresponding block pointer type. The conversion itself is expressed by a
  866. conversion operator in that closure type that produces a block pointer with the
  867. same signature as the lambda itself, e.g.,
  868. .. code-block:: objc
  869. operator NSComparisonResult (^)(id, id)() const;
  870. This conversion function returns a new block that simply forwards the two
  871. parameters to the lambda object (which it captures by copy), then returns the
  872. result. The returned block is first copied (with ``Block_copy``) and then
  873. autoreleased. As an optimization, if a lambda expression is immediately
  874. converted to a block pointer (as in the first example, above), then the block
  875. is not copied and autoreleased: rather, it is given the same lifetime as a
  876. block literal written at that point in the program, which avoids the overhead
  877. of copying a block to the heap in the common case.
  878. The conversion from a lambda to a block pointer is only available in
  879. Objective-C++, and not in C++ with blocks, due to its use of Objective-C memory
  880. management (autorelease).
  881. Initializer lists for complex numbers in C
  882. ==========================================
  883. clang supports an extension which allows the following in C:
  884. .. code-block:: c++
  885. #include <math.h>
  886. #include <complex.h>
  887. complex float x = { 1.0f, INFINITY }; // Init to (1, Inf)
  888. This construct is useful because there is no way to separately initialize the
  889. real and imaginary parts of a complex variable in standard C, given that clang
  890. does not support ``_Imaginary``. (Clang also supports the ``__real__`` and
  891. ``__imag__`` extensions from gcc, which help in some cases, but are not usable
  892. in static initializers.)
  893. Note that this extension does not allow eliding the braces; the meaning of the
  894. following two lines is different:
  895. .. code-block:: c++
  896. complex float x[] = { { 1.0f, 1.0f } }; // [0] = (1, 1)
  897. complex float x[] = { 1.0f, 1.0f }; // [0] = (1, 0), [1] = (1, 0)
  898. This extension also works in C++ mode, as far as that goes, but does not apply
  899. to the C++ ``std::complex``. (In C++11, list initialization allows the same
  900. syntax to be used with ``std::complex`` with the same meaning.)
  901. Builtin Functions
  902. =================
  903. Clang supports a number of builtin library functions with the same syntax as
  904. GCC, including things like ``__builtin_nan``, ``__builtin_constant_p``,
  905. ``__builtin_choose_expr``, ``__builtin_types_compatible_p``,
  906. ``__builtin_assume_aligned``, ``__sync_fetch_and_add``, etc. In addition to
  907. the GCC builtins, Clang supports a number of builtins that GCC does not, which
  908. are listed here.
  909. Please note that Clang does not and will not support all of the GCC builtins
  910. for vector operations. Instead of using builtins, you should use the functions
  911. defined in target-specific header files like ``<xmmintrin.h>``, which define
  912. portable wrappers for these. Many of the Clang versions of these functions are
  913. implemented directly in terms of :ref:`extended vector support
  914. <langext-vectors>` instead of builtins, in order to reduce the number of
  915. builtins that we need to implement.
  916. ``__builtin_assume``
  917. ------------------------------
  918. ``__builtin_assume`` is used to provide the optimizer with a boolean
  919. invariant that is defined to be true.
  920. **Syntax**:
  921. .. code-block:: c++
  922. __builtin_assume(bool)
  923. **Example of Use**:
  924. .. code-block:: c++
  925. int foo(int x) {
  926. __builtin_assume(x != 0);
  927. // The optimizer may short-circuit this check using the invariant.
  928. if (x == 0)
  929. return do_something();
  930. return do_something_else();
  931. }
  932. **Description**:
  933. The boolean argument to this function is defined to be true. The optimizer may
  934. analyze the form of the expression provided as the argument and deduce from
  935. that information used to optimize the program. If the condition is violated
  936. during execution, the behavior is undefined. The argument itself is never
  937. evaluated, so any side effects of the expression will be discarded.
  938. Query for this feature with ``__has_builtin(__builtin_assume)``.
  939. ``__builtin_readcyclecounter``
  940. ------------------------------
  941. ``__builtin_readcyclecounter`` is used to access the cycle counter register (or
  942. a similar low-latency, high-accuracy clock) on those targets that support it.
  943. **Syntax**:
  944. .. code-block:: c++
  945. __builtin_readcyclecounter()
  946. **Example of Use**:
  947. .. code-block:: c++
  948. unsigned long long t0 = __builtin_readcyclecounter();
  949. do_something();
  950. unsigned long long t1 = __builtin_readcyclecounter();
  951. unsigned long long cycles_to_do_something = t1 - t0; // assuming no overflow
  952. **Description**:
  953. The ``__builtin_readcyclecounter()`` builtin returns the cycle counter value,
  954. which may be either global or process/thread-specific depending on the target.
  955. As the backing counters often overflow quickly (on the order of seconds) this
  956. should only be used for timing small intervals. When not supported by the
  957. target, the return value is always zero. This builtin takes no arguments and
  958. produces an unsigned long long result.
  959. Query for this feature with ``__has_builtin(__builtin_readcyclecounter)``. Note
  960. that even if present, its use may depend on run-time privilege or other OS
  961. controlled state.
  962. .. _langext-__builtin_shufflevector:
  963. ``__builtin_shufflevector``
  964. ---------------------------
  965. ``__builtin_shufflevector`` is used to express generic vector
  966. permutation/shuffle/swizzle operations. This builtin is also very important
  967. for the implementation of various target-specific header files like
  968. ``<xmmintrin.h>``.
  969. **Syntax**:
  970. .. code-block:: c++
  971. __builtin_shufflevector(vec1, vec2, index1, index2, ...)
  972. **Examples**:
  973. .. code-block:: c++
  974. // identity operation - return 4-element vector v1.
  975. __builtin_shufflevector(v1, v1, 0, 1, 2, 3)
  976. // "Splat" element 0 of V1 into a 4-element result.
  977. __builtin_shufflevector(V1, V1, 0, 0, 0, 0)
  978. // Reverse 4-element vector V1.
  979. __builtin_shufflevector(V1, V1, 3, 2, 1, 0)
  980. // Concatenate every other element of 4-element vectors V1 and V2.
  981. __builtin_shufflevector(V1, V2, 0, 2, 4, 6)
  982. // Concatenate every other element of 8-element vectors V1 and V2.
  983. __builtin_shufflevector(V1, V2, 0, 2, 4, 6, 8, 10, 12, 14)
  984. // Shuffle v1 with some elements being undefined
  985. __builtin_shufflevector(v1, v1, 3, -1, 1, -1)
  986. **Description**:
  987. The first two arguments to ``__builtin_shufflevector`` are vectors that have
  988. the same element type. The remaining arguments are a list of integers that
  989. specify the elements indices of the first two vectors that should be extracted
  990. and returned in a new vector. These element indices are numbered sequentially
  991. starting with the first vector, continuing into the second vector. Thus, if
  992. ``vec1`` is a 4-element vector, index 5 would refer to the second element of
  993. ``vec2``. An index of -1 can be used to indicate that the corresponding element
  994. in the returned vector is a don't care and can be optimized by the backend.
  995. The result of ``__builtin_shufflevector`` is a vector with the same element
  996. type as ``vec1``/``vec2`` but that has an element count equal to the number of
  997. indices specified.
  998. Query for this feature with ``__has_builtin(__builtin_shufflevector)``.
  999. .. _langext-__builtin_convertvector:
  1000. ``__builtin_convertvector``
  1001. ---------------------------
  1002. ``__builtin_convertvector`` is used to express generic vector
  1003. type-conversion operations. The input vector and the output vector
  1004. type must have the same number of elements.
  1005. **Syntax**:
  1006. .. code-block:: c++
  1007. __builtin_convertvector(src_vec, dst_vec_type)
  1008. **Examples**:
  1009. .. code-block:: c++
  1010. typedef double vector4double __attribute__((__vector_size__(32)));
  1011. typedef float vector4float __attribute__((__vector_size__(16)));
  1012. typedef short vector4short __attribute__((__vector_size__(8)));
  1013. vector4float vf; vector4short vs;
  1014. // convert from a vector of 4 floats to a vector of 4 doubles.
  1015. __builtin_convertvector(vf, vector4double)
  1016. // equivalent to:
  1017. (vector4double) { (double) vf[0], (double) vf[1], (double) vf[2], (double) vf[3] }
  1018. // convert from a vector of 4 shorts to a vector of 4 floats.
  1019. __builtin_convertvector(vs, vector4float)
  1020. // equivalent to:
  1021. (vector4float) { (float) vs[0], (float) vs[1], (float) vs[2], (float) vs[3] }
  1022. **Description**:
  1023. The first argument to ``__builtin_convertvector`` is a vector, and the second
  1024. argument is a vector type with the same number of elements as the first
  1025. argument.
  1026. The result of ``__builtin_convertvector`` is a vector with the same element
  1027. type as the second argument, with a value defined in terms of the action of a
  1028. C-style cast applied to each element of the first argument.
  1029. Query for this feature with ``__has_builtin(__builtin_convertvector)``.
  1030. ``__builtin_unreachable``
  1031. -------------------------
  1032. ``__builtin_unreachable`` is used to indicate that a specific point in the
  1033. program cannot be reached, even if the compiler might otherwise think it can.
  1034. This is useful to improve optimization and eliminates certain warnings. For
  1035. example, without the ``__builtin_unreachable`` in the example below, the
  1036. compiler assumes that the inline asm can fall through and prints a "function
  1037. declared '``noreturn``' should not return" warning.
  1038. **Syntax**:
  1039. .. code-block:: c++
  1040. __builtin_unreachable()
  1041. **Example of use**:
  1042. .. code-block:: c++
  1043. void myabort(void) __attribute__((noreturn));
  1044. void myabort(void) {
  1045. asm("int3");
  1046. __builtin_unreachable();
  1047. }
  1048. **Description**:
  1049. The ``__builtin_unreachable()`` builtin has completely undefined behavior.
  1050. Since it has undefined behavior, it is a statement that it is never reached and
  1051. the optimizer can take advantage of this to produce better code. This builtin
  1052. takes no arguments and produces a void result.
  1053. Query for this feature with ``__has_builtin(__builtin_unreachable)``.
  1054. ``__sync_swap``
  1055. ---------------
  1056. ``__sync_swap`` is used to atomically swap integers or pointers in memory.
  1057. **Syntax**:
  1058. .. code-block:: c++
  1059. type __sync_swap(type *ptr, type value, ...)
  1060. **Example of Use**:
  1061. .. code-block:: c++
  1062. int old_value = __sync_swap(&value, new_value);
  1063. **Description**:
  1064. The ``__sync_swap()`` builtin extends the existing ``__sync_*()`` family of
  1065. atomic intrinsics to allow code to atomically swap the current value with the
  1066. new value. More importantly, it helps developers write more efficient and
  1067. correct code by avoiding expensive loops around
  1068. ``__sync_bool_compare_and_swap()`` or relying on the platform specific
  1069. implementation details of ``__sync_lock_test_and_set()``. The
  1070. ``__sync_swap()`` builtin is a full barrier.
  1071. ``__builtin_addressof``
  1072. -----------------------
  1073. ``__builtin_addressof`` performs the functionality of the built-in ``&``
  1074. operator, ignoring any ``operator&`` overload. This is useful in constant
  1075. expressions in C++11, where there is no other way to take the address of an
  1076. object that overloads ``operator&``.
  1077. **Example of use**:
  1078. .. code-block:: c++
  1079. template<typename T> constexpr T *addressof(T &value) {
  1080. return __builtin_addressof(value);
  1081. }
  1082. ``__builtin_operator_new`` and ``__builtin_operator_delete``
  1083. ------------------------------------------------------------
  1084. ``__builtin_operator_new`` allocates memory just like a non-placement non-class
  1085. *new-expression*. This is exactly like directly calling the normal
  1086. non-placement ``::operator new``, except that it allows certain optimizations
  1087. that the C++ standard does not permit for a direct function call to
  1088. ``::operator new`` (in particular, removing ``new`` / ``delete`` pairs and
  1089. merging allocations).
  1090. Likewise, ``__builtin_operator_delete`` deallocates memory just like a
  1091. non-class *delete-expression*, and is exactly like directly calling the normal
  1092. ``::operator delete``, except that it permits optimizations. Only the unsized
  1093. form of ``__builtin_operator_delete`` is currently available.
  1094. These builtins are intended for use in the implementation of ``std::allocator``
  1095. and other similar allocation libraries, and are only available in C++.
  1096. Multiprecision Arithmetic Builtins
  1097. ----------------------------------
  1098. Clang provides a set of builtins which expose multiprecision arithmetic in a
  1099. manner amenable to C. They all have the following form:
  1100. .. code-block:: c
  1101. unsigned x = ..., y = ..., carryin = ..., carryout;
  1102. unsigned sum = __builtin_addc(x, y, carryin, &carryout);
  1103. Thus one can form a multiprecision addition chain in the following manner:
  1104. .. code-block:: c
  1105. unsigned *x, *y, *z, carryin=0, carryout;
  1106. z[0] = __builtin_addc(x[0], y[0], carryin, &carryout);
  1107. carryin = carryout;
  1108. z[1] = __builtin_addc(x[1], y[1], carryin, &carryout);
  1109. carryin = carryout;
  1110. z[2] = __builtin_addc(x[2], y[2], carryin, &carryout);
  1111. carryin = carryout;
  1112. z[3] = __builtin_addc(x[3], y[3], carryin, &carryout);
  1113. The complete list of builtins are:
  1114. .. code-block:: c
  1115. unsigned char __builtin_addcb (unsigned char x, unsigned char y, unsigned char carryin, unsigned char *carryout);
  1116. unsigned short __builtin_addcs (unsigned short x, unsigned short y, unsigned short carryin, unsigned short *carryout);
  1117. unsigned __builtin_addc (unsigned x, unsigned y, unsigned carryin, unsigned *carryout);
  1118. unsigned long __builtin_addcl (unsigned long x, unsigned long y, unsigned long carryin, unsigned long *carryout);
  1119. unsigned long long __builtin_addcll(unsigned long long x, unsigned long long y, unsigned long long carryin, unsigned long long *carryout);
  1120. unsigned char __builtin_subcb (unsigned char x, unsigned char y, unsigned char carryin, unsigned char *carryout);
  1121. unsigned short __builtin_subcs (unsigned short x, unsigned short y, unsigned short carryin, unsigned short *carryout);
  1122. unsigned __builtin_subc (unsigned x, unsigned y, unsigned carryin, unsigned *carryout);
  1123. unsigned long __builtin_subcl (unsigned long x, unsigned long y, unsigned long carryin, unsigned long *carryout);
  1124. unsigned long long __builtin_subcll(unsigned long long x, unsigned long long y, unsigned long long carryin, unsigned long long *carryout);
  1125. Checked Arithmetic Builtins
  1126. ---------------------------
  1127. Clang provides a set of builtins that implement checked arithmetic for security
  1128. critical applications in a manner that is fast and easily expressable in C. As
  1129. an example of their usage:
  1130. .. code-block:: c
  1131. errorcode_t security_critical_application(...) {
  1132. unsigned x, y, result;
  1133. ...
  1134. if (__builtin_umul_overflow(x, y, &result))
  1135. return kErrorCodeHackers;
  1136. ...
  1137. use_multiply(result);
  1138. ...
  1139. }
  1140. A complete enumeration of the builtins are:
  1141. .. code-block:: c
  1142. bool __builtin_uadd_overflow (unsigned x, unsigned y, unsigned *sum);
  1143. bool __builtin_uaddl_overflow (unsigned long x, unsigned long y, unsigned long *sum);
  1144. bool __builtin_uaddll_overflow(unsigned long long x, unsigned long long y, unsigned long long *sum);
  1145. bool __builtin_usub_overflow (unsigned x, unsigned y, unsigned *diff);
  1146. bool __builtin_usubl_overflow (unsigned long x, unsigned long y, unsigned long *diff);
  1147. bool __builtin_usubll_overflow(unsigned long long x, unsigned long long y, unsigned long long *diff);
  1148. bool __builtin_umul_overflow (unsigned x, unsigned y, unsigned *prod);
  1149. bool __builtin_umull_overflow (unsigned long x, unsigned long y, unsigned long *prod);
  1150. bool __builtin_umulll_overflow(unsigned long long x, unsigned long long y, unsigned long long *prod);
  1151. bool __builtin_sadd_overflow (int x, int y, int *sum);
  1152. bool __builtin_saddl_overflow (long x, long y, long *sum);
  1153. bool __builtin_saddll_overflow(long long x, long long y, long long *sum);
  1154. bool __builtin_ssub_overflow (int x, int y, int *diff);
  1155. bool __builtin_ssubl_overflow (long x, long y, long *diff);
  1156. bool __builtin_ssubll_overflow(long long x, long long y, long long *diff);
  1157. bool __builtin_smul_overflow (int x, int y, int *prod);
  1158. bool __builtin_smull_overflow (long x, long y, long *prod);
  1159. bool __builtin_smulll_overflow(long long x, long long y, long long *prod);
  1160. .. _langext-__c11_atomic:
  1161. __c11_atomic builtins
  1162. ---------------------
  1163. Clang provides a set of builtins which are intended to be used to implement
  1164. C11's ``<stdatomic.h>`` header. These builtins provide the semantics of the
  1165. ``_explicit`` form of the corresponding C11 operation, and are named with a
  1166. ``__c11_`` prefix. The supported operations, and the differences from
  1167. the corresponding C11 operations, are:
  1168. * ``__c11_atomic_init``
  1169. * ``__c11_atomic_thread_fence``
  1170. * ``__c11_atomic_signal_fence``
  1171. * ``__c11_atomic_is_lock_free`` (The argument is the size of the
  1172. ``_Atomic(...)`` object, instead of its address)
  1173. * ``__c11_atomic_store``
  1174. * ``__c11_atomic_load``
  1175. * ``__c11_atomic_exchange``
  1176. * ``__c11_atomic_compare_exchange_strong``
  1177. * ``__c11_atomic_compare_exchange_weak``
  1178. * ``__c11_atomic_fetch_add``
  1179. * ``__c11_atomic_fetch_sub``
  1180. * ``__c11_atomic_fetch_and``
  1181. * ``__c11_atomic_fetch_or``
  1182. * ``__c11_atomic_fetch_xor``
  1183. The macros ``__ATOMIC_RELAXED``, ``__ATOMIC_CONSUME``, ``__ATOMIC_ACQUIRE``,
  1184. ``__ATOMIC_RELEASE``, ``__ATOMIC_ACQ_REL``, and ``__ATOMIC_SEQ_CST`` are
  1185. provided, with values corresponding to the enumerators of C11's
  1186. ``memory_order`` enumeration.
  1187. Low-level ARM exclusive memory builtins
  1188. ---------------------------------------
  1189. Clang provides overloaded builtins giving direct access to the three key ARM
  1190. instructions for implementing atomic operations.
  1191. .. code-block:: c
  1192. T __builtin_arm_ldrex(const volatile T *addr);
  1193. T __builtin_arm_ldaex(const volatile T *addr);
  1194. int __builtin_arm_strex(T val, volatile T *addr);
  1195. int __builtin_arm_stlex(T val, volatile T *addr);
  1196. void __builtin_arm_clrex(void);
  1197. The types ``T`` currently supported are:
  1198. * Integer types with width at most 64 bits (or 128 bits on AArch64).
  1199. * Floating-point types
  1200. * Pointer types.
  1201. Note that the compiler does not guarantee it will not insert stores which clear
  1202. the exclusive monitor in between an ``ldrex`` type operation and its paired
  1203. ``strex``. In practice this is only usually a risk when the extra store is on
  1204. the same cache line as the variable being modified and Clang will only insert
  1205. stack stores on its own, so it is best not to use these operations on variables
  1206. with automatic storage duration.
  1207. Also, loads and stores may be implicit in code written between the ``ldrex`` and
  1208. ``strex``. Clang will not necessarily mitigate the effects of these either, so
  1209. care should be exercised.
  1210. For these reasons the higher level atomic primitives should be preferred where
  1211. possible.
  1212. Non-standard C++11 Attributes
  1213. =============================
  1214. Clang's non-standard C++11 attributes live in the ``clang`` attribute
  1215. namespace.
  1216. Clang supports GCC's ``gnu`` attribute namespace. All GCC attributes which
  1217. are accepted with the ``__attribute__((foo))`` syntax are also accepted as
  1218. ``[[gnu::foo]]``. This only extends to attributes which are specified by GCC
  1219. (see the list of `GCC function attributes
  1220. <http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html>`_, `GCC variable
  1221. attributes <http://gcc.gnu.org/onlinedocs/gcc/Variable-Attributes.html>`_, and
  1222. `GCC type attributes
  1223. <http://gcc.gnu.org/onlinedocs/gcc/Type-Attributes.html>`_). As with the GCC
  1224. implementation, these attributes must appertain to the *declarator-id* in a
  1225. declaration, which means they must go either at the start of the declaration or
  1226. immediately after the name being declared.
  1227. For example, this applies the GNU ``unused`` attribute to ``a`` and ``f``, and
  1228. also applies the GNU ``noreturn`` attribute to ``f``.
  1229. .. code-block:: c++
  1230. [[gnu::unused]] int a, f [[gnu::noreturn]] ();
  1231. Target-Specific Extensions
  1232. ==========================
  1233. Clang supports some language features conditionally on some targets.
  1234. ARM/AArch64 Language Extensions
  1235. -------------------------------
  1236. Memory Barrier Intrinsics
  1237. ^^^^^^^^^^^^^^^^^^^^^^^^^
  1238. Clang implements the ``__dmb``, ``__dsb`` and ``__isb`` intrinsics as defined
  1239. in the `ARM C Language Extensions Release 2.0
  1240. <http://infocenter.arm.com/help/topic/com.arm.doc.ihi0053c/IHI0053C_acle_2_0.pdf>`_.
  1241. Note that these intrinsics are implemented as motion barriers that block
  1242. reordering of memory accesses and side effect instructions. Other instructions
  1243. like simple arithmatic may be reordered around the intrinsic. If you expect to
  1244. have no reordering at all, use inline assembly instead.
  1245. X86/X86-64 Language Extensions
  1246. ------------------------------
  1247. The X86 backend has these language extensions:
  1248. Memory references off the GS segment
  1249. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1250. Annotating a pointer with address space #256 causes it to be code generated
  1251. relative to the X86 GS segment register, and address space #257 causes it to be
  1252. relative to the X86 FS segment. Note that this is a very very low-level
  1253. feature that should only be used if you know what you're doing (for example in
  1254. an OS kernel).
  1255. Here is an example:
  1256. .. code-block:: c++
  1257. #define GS_RELATIVE __attribute__((address_space(256)))
  1258. int foo(int GS_RELATIVE *P) {
  1259. return *P;
  1260. }
  1261. Which compiles to (on X86-32):
  1262. .. code-block:: gas
  1263. _foo:
  1264. movl 4(%esp), %eax
  1265. movl %gs:(%eax), %eax
  1266. ret
  1267. Extensions for Static Analysis
  1268. ==============================
  1269. Clang supports additional attributes that are useful for documenting program
  1270. invariants and rules for static analysis tools, such as the `Clang Static
  1271. Analyzer <http://clang-analyzer.llvm.org/>`_. These attributes are documented
  1272. in the analyzer's `list of source-level annotations
  1273. <http://clang-analyzer.llvm.org/annotations.html>`_.
  1274. Extensions for Dynamic Analysis
  1275. ===============================
  1276. Use ``__has_feature(address_sanitizer)`` to check if the code is being built
  1277. with :doc:`AddressSanitizer`.
  1278. Use ``__has_feature(thread_sanitizer)`` to check if the code is being built
  1279. with :doc:`ThreadSanitizer`.
  1280. Use ``__has_feature(memory_sanitizer)`` to check if the code is being built
  1281. with :doc:`MemorySanitizer`.
  1282. Use ``__has_feature(safe_stack)`` to check if the code is being built
  1283. with :doc:`SafeStack`.
  1284. Extensions for selectively disabling optimization
  1285. =================================================
  1286. Clang provides a mechanism for selectively disabling optimizations in functions
  1287. and methods.
  1288. To disable optimizations in a single function definition, the GNU-style or C++11
  1289. non-standard attribute ``optnone`` can be used.
  1290. .. code-block:: c++
  1291. // The following functions will not be optimized.
  1292. // GNU-style attribute
  1293. __attribute__((optnone)) int foo() {
  1294. // ... code
  1295. }
  1296. // C++11 attribute
  1297. [[clang::optnone]] int bar() {
  1298. // ... code
  1299. }
  1300. To facilitate disabling optimization for a range of function definitions, a
  1301. range-based pragma is provided. Its syntax is ``#pragma clang optimize``
  1302. followed by ``off`` or ``on``.
  1303. All function definitions in the region between an ``off`` and the following
  1304. ``on`` will be decorated with the ``optnone`` attribute unless doing so would
  1305. conflict with explicit attributes already present on the function (e.g. the
  1306. ones that control inlining).
  1307. .. code-block:: c++
  1308. #pragma clang optimize off
  1309. // This function will be decorated with optnone.
  1310. int foo() {
  1311. // ... code
  1312. }
  1313. // optnone conflicts with always_inline, so bar() will not be decorated.
  1314. __attribute__((always_inline)) int bar() {
  1315. // ... code
  1316. }
  1317. #pragma clang optimize on
  1318. If no ``on`` is found to close an ``off`` region, the end of the region is the
  1319. end of the compilation unit.
  1320. Note that a stray ``#pragma clang optimize on`` does not selectively enable
  1321. additional optimizations when compiling at low optimization levels. This feature
  1322. can only be used to selectively disable optimizations.
  1323. The pragma has an effect on functions only at the point of their definition; for
  1324. function templates, this means that the state of the pragma at the point of an
  1325. instantiation is not necessarily relevant. Consider the following example:
  1326. .. code-block:: c++
  1327. template<typename T> T twice(T t) {
  1328. return 2 * t;
  1329. }
  1330. #pragma clang optimize off
  1331. template<typename T> T thrice(T t) {
  1332. return 3 * t;
  1333. }
  1334. int container(int a, int b) {
  1335. return twice(a) + thrice(b);
  1336. }
  1337. #pragma clang optimize on
  1338. In this example, the definition of the template function ``twice`` is outside
  1339. the pragma region, whereas the definition of ``thrice`` is inside the region.
  1340. The ``container`` function is also in the region and will not be optimized, but
  1341. it causes the instantiation of ``twice`` and ``thrice`` with an ``int`` type; of
  1342. these two instantiations, ``twice`` will be optimized (because its definition
  1343. was outside the region) and ``thrice`` will not be optimized.
  1344. Extensions for loop hint optimizations
  1345. ======================================
  1346. The ``#pragma clang loop`` directive is used to specify hints for optimizing the
  1347. subsequent for, while, do-while, or c++11 range-based for loop. The directive
  1348. provides options for vectorization, interleaving, and unrolling. Loop hints can
  1349. be specified before any loop and will be ignored if the optimization is not safe
  1350. to apply.
  1351. Vectorization and Interleaving
  1352. ------------------------------
  1353. A vectorized loop performs multiple iterations of the original loop
  1354. in parallel using vector instructions. The instruction set of the target
  1355. processor determines which vector instructions are available and their vector
  1356. widths. This restricts the types of loops that can be vectorized. The vectorizer
  1357. automatically determines if the loop is safe and profitable to vectorize. A
  1358. vector instruction cost model is used to select the vector width.
  1359. Interleaving multiple loop iterations allows modern processors to further
  1360. improve instruction-level parallelism (ILP) using advanced hardware features,
  1361. such as multiple execution units and out-of-order execution. The vectorizer uses
  1362. a cost model that depends on the register pressure and generated code size to
  1363. select the interleaving count.
  1364. Vectorization is enabled by ``vectorize(enable)`` and interleaving is enabled
  1365. by ``interleave(enable)``. This is useful when compiling with ``-Os`` to
  1366. manually enable vectorization or interleaving.
  1367. .. code-block:: c++
  1368. #pragma clang loop vectorize(enable)
  1369. #pragma clang loop interleave(enable)
  1370. for(...) {
  1371. ...
  1372. }
  1373. The vector width is specified by ``vectorize_width(_value_)`` and the interleave
  1374. count is specified by ``interleave_count(_value_)``, where
  1375. _value_ is a positive integer. This is useful for specifying the optimal
  1376. width/count of the set of target architectures supported by your application.
  1377. .. code-block:: c++
  1378. #pragma clang loop vectorize_width(2)
  1379. #pragma clang loop interleave_count(2)
  1380. for(...) {
  1381. ...
  1382. }
  1383. Specifying a width/count of 1 disables the optimization, and is equivalent to
  1384. ``vectorize(disable)`` or ``interleave(disable)``.
  1385. Loop Unrolling
  1386. --------------
  1387. Unrolling a loop reduces the loop control overhead and exposes more
  1388. opportunities for ILP. Loops can be fully or partially unrolled. Full unrolling
  1389. eliminates the loop and replaces it with an enumerated sequence of loop
  1390. iterations. Full unrolling is only possible if the loop trip count is known at
  1391. compile time. Partial unrolling replicates the loop body within the loop and
  1392. reduces the trip count.
  1393. If ``unroll(full)`` is specified the unroller will attempt to fully unroll the
  1394. loop if the trip count is known at compile time. If the fully unrolled code size
  1395. is greater than an internal limit the loop will be partially unrolled up to this
  1396. limit. If the loop count is not known at compile time the loop will not be
  1397. unrolled.
  1398. .. code-block:: c++
  1399. #pragma clang loop unroll(full)
  1400. for(...) {
  1401. ...
  1402. }
  1403. The unroll count can be specified explicitly with ``unroll_count(_value_)`` where
  1404. _value_ is a positive integer. If this value is greater than the trip count the
  1405. loop will be fully unrolled. Otherwise the loop is partially unrolled subject
  1406. to the same code size limit as with ``unroll(full)``.
  1407. .. code-block:: c++
  1408. #pragma clang loop unroll_count(8)
  1409. for(...) {
  1410. ...
  1411. }
  1412. Unrolling of a loop can be prevented by specifying ``unroll(disable)``.
  1413. Additional Information
  1414. ----------------------
  1415. For convenience multiple loop hints can be specified on a single line.
  1416. .. code-block:: c++
  1417. #pragma clang loop vectorize_width(4) interleave_count(8)
  1418. for(...) {
  1419. ...
  1420. }
  1421. If an optimization cannot be applied any hints that apply to it will be ignored.
  1422. For example, the hint ``vectorize_width(4)`` is ignored if the loop is not
  1423. proven safe to vectorize. To identify and diagnose optimization issues use
  1424. `-Rpass`, `-Rpass-missed`, and `-Rpass-analysis` command line options. See the
  1425. user guide for details.