UsersManual.rst 112 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845
  1. ============================
  2. Clang Compiler User's Manual
  3. ============================
  4. .. include:: <isonum.txt>
  5. .. contents::
  6. :local:
  7. Introduction
  8. ============
  9. The Clang Compiler is an open-source compiler for the C family of
  10. programming languages, aiming to be the best in class implementation of
  11. these languages. Clang builds on the LLVM optimizer and code generator,
  12. allowing it to provide high-quality optimization and code generation
  13. support for many targets. For more general information, please see the
  14. `Clang Web Site <http://clang.llvm.org>`_ or the `LLVM Web
  15. Site <http://llvm.org>`_.
  16. This document describes important notes about using Clang as a compiler
  17. for an end-user, documenting the supported features, command line
  18. options, etc. If you are interested in using Clang to build a tool that
  19. processes code, please see :doc:`InternalsManual`. If you are interested in the
  20. `Clang Static Analyzer <http://clang-analyzer.llvm.org>`_, please see its web
  21. page.
  22. Clang is one component in a complete toolchain for C family languages.
  23. A separate document describes the other pieces necessary to
  24. :doc:`assemble a complete toolchain <Toolchain>`.
  25. Clang is designed to support the C family of programming languages,
  26. which includes :ref:`C <c>`, :ref:`Objective-C <objc>`, :ref:`C++ <cxx>`, and
  27. :ref:`Objective-C++ <objcxx>` as well as many dialects of those. For
  28. language-specific information, please see the corresponding language
  29. specific section:
  30. - :ref:`C Language <c>`: K&R C, ANSI C89, ISO C90, ISO C94 (C89+AMD1), ISO
  31. C99 (+TC1, TC2, TC3).
  32. - :ref:`Objective-C Language <objc>`: ObjC 1, ObjC 2, ObjC 2.1, plus
  33. variants depending on base language.
  34. - :ref:`C++ Language <cxx>`
  35. - :ref:`Objective C++ Language <objcxx>`
  36. - :ref:`OpenCL C Language <opencl>`: v1.0, v1.1, v1.2, v2.0.
  37. In addition to these base languages and their dialects, Clang supports a
  38. broad variety of language extensions, which are documented in the
  39. corresponding language section. These extensions are provided to be
  40. compatible with the GCC, Microsoft, and other popular compilers as well
  41. as to improve functionality through Clang-specific features. The Clang
  42. driver and language features are intentionally designed to be as
  43. compatible with the GNU GCC compiler as reasonably possible, easing
  44. migration from GCC to Clang. In most cases, code "just works".
  45. Clang also provides an alternative driver, :ref:`clang-cl`, that is designed
  46. to be compatible with the Visual C++ compiler, cl.exe.
  47. In addition to language specific features, Clang has a variety of
  48. features that depend on what CPU architecture or operating system is
  49. being compiled for. Please see the :ref:`Target-Specific Features and
  50. Limitations <target_features>` section for more details.
  51. The rest of the introduction introduces some basic :ref:`compiler
  52. terminology <terminology>` that is used throughout this manual and
  53. contains a basic :ref:`introduction to using Clang <basicusage>` as a
  54. command line compiler.
  55. .. _terminology:
  56. Terminology
  57. -----------
  58. Front end, parser, backend, preprocessor, undefined behavior,
  59. diagnostic, optimizer
  60. .. _basicusage:
  61. Basic Usage
  62. -----------
  63. Intro to how to use a C compiler for newbies.
  64. compile + link compile then link debug info enabling optimizations
  65. picking a language to use, defaults to C11 by default. Autosenses based
  66. on extension. using a makefile
  67. Command Line Options
  68. ====================
  69. This section is generally an index into other sections. It does not go
  70. into depth on the ones that are covered by other sections. However, the
  71. first part introduces the language selection and other high level
  72. options like :option:`-c`, :option:`-g`, etc.
  73. Options to Control Error and Warning Messages
  74. ---------------------------------------------
  75. .. option:: -Werror
  76. Turn warnings into errors.
  77. .. This is in plain monospaced font because it generates the same label as
  78. .. -Werror, and Sphinx complains.
  79. ``-Werror=foo``
  80. Turn warning "foo" into an error.
  81. .. option:: -Wno-error=foo
  82. Turn warning "foo" into a warning even if :option:`-Werror` is specified.
  83. .. option:: -Wfoo
  84. Enable warning "foo".
  85. See the :doc:`diagnostics reference <DiagnosticsReference>` for a complete
  86. list of the warning flags that can be specified in this way.
  87. .. option:: -Wno-foo
  88. Disable warning "foo".
  89. .. option:: -w
  90. Disable all diagnostics.
  91. .. option:: -Weverything
  92. :ref:`Enable all diagnostics. <diagnostics_enable_everything>`
  93. .. option:: -pedantic
  94. Warn on language extensions.
  95. .. option:: -pedantic-errors
  96. Error on language extensions.
  97. .. option:: -Wsystem-headers
  98. Enable warnings from system headers.
  99. .. option:: -ferror-limit=123
  100. Stop emitting diagnostics after 123 errors have been produced. The default is
  101. 20, and the error limit can be disabled with `-ferror-limit=0`.
  102. .. option:: -ftemplate-backtrace-limit=123
  103. Only emit up to 123 template instantiation notes within the template
  104. instantiation backtrace for a single warning or error. The default is 10, and
  105. the limit can be disabled with `-ftemplate-backtrace-limit=0`.
  106. .. _cl_diag_formatting:
  107. Formatting of Diagnostics
  108. ^^^^^^^^^^^^^^^^^^^^^^^^^
  109. Clang aims to produce beautiful diagnostics by default, particularly for
  110. new users that first come to Clang. However, different people have
  111. different preferences, and sometimes Clang is driven not by a human,
  112. but by a program that wants consistent and easily parsable output. For
  113. these cases, Clang provides a wide range of options to control the exact
  114. output format of the diagnostics that it generates.
  115. .. _opt_fshow-column:
  116. **-f[no-]show-column**
  117. Print column number in diagnostic.
  118. This option, which defaults to on, controls whether or not Clang
  119. prints the column number of a diagnostic. For example, when this is
  120. enabled, Clang will print something like:
  121. ::
  122. test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
  123. #endif bad
  124. ^
  125. //
  126. When this is disabled, Clang will print "test.c:28: warning..." with
  127. no column number.
  128. The printed column numbers count bytes from the beginning of the
  129. line; take care if your source contains multibyte characters.
  130. .. _opt_fshow-source-location:
  131. **-f[no-]show-source-location**
  132. Print source file/line/column information in diagnostic.
  133. This option, which defaults to on, controls whether or not Clang
  134. prints the filename, line number and column number of a diagnostic.
  135. For example, when this is enabled, Clang will print something like:
  136. ::
  137. test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
  138. #endif bad
  139. ^
  140. //
  141. When this is disabled, Clang will not print the "test.c:28:8: "
  142. part.
  143. .. _opt_fcaret-diagnostics:
  144. **-f[no-]caret-diagnostics**
  145. Print source line and ranges from source code in diagnostic.
  146. This option, which defaults to on, controls whether or not Clang
  147. prints the source line, source ranges, and caret when emitting a
  148. diagnostic. For example, when this is enabled, Clang will print
  149. something like:
  150. ::
  151. test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
  152. #endif bad
  153. ^
  154. //
  155. **-f[no-]color-diagnostics**
  156. This option, which defaults to on when a color-capable terminal is
  157. detected, controls whether or not Clang prints diagnostics in color.
  158. When this option is enabled, Clang will use colors to highlight
  159. specific parts of the diagnostic, e.g.,
  160. .. nasty hack to not lose our dignity
  161. .. raw:: html
  162. <pre>
  163. <b><span style="color:black">test.c:28:8: <span style="color:magenta">warning</span>: extra tokens at end of #endif directive [-Wextra-tokens]</span></b>
  164. #endif bad
  165. <span style="color:green">^</span>
  166. <span style="color:green">//</span>
  167. </pre>
  168. When this is disabled, Clang will just print:
  169. ::
  170. test.c:2:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
  171. #endif bad
  172. ^
  173. //
  174. **-fansi-escape-codes**
  175. Controls whether ANSI escape codes are used instead of the Windows Console
  176. API to output colored diagnostics. This option is only used on Windows and
  177. defaults to off.
  178. .. option:: -fdiagnostics-format=clang/msvc/vi
  179. Changes diagnostic output format to better match IDEs and command line tools.
  180. This option controls the output format of the filename, line number,
  181. and column printed in diagnostic messages. The options, and their
  182. affect on formatting a simple conversion diagnostic, follow:
  183. **clang** (default)
  184. ::
  185. t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int'
  186. **msvc**
  187. ::
  188. t.c(3,11) : warning: conversion specifies type 'char *' but the argument has type 'int'
  189. **vi**
  190. ::
  191. t.c +3:11: warning: conversion specifies type 'char *' but the argument has type 'int'
  192. .. _opt_fdiagnostics-show-option:
  193. **-f[no-]diagnostics-show-option**
  194. Enable ``[-Woption]`` information in diagnostic line.
  195. This option, which defaults to on, controls whether or not Clang
  196. prints the associated :ref:`warning group <cl_diag_warning_groups>`
  197. option name when outputting a warning diagnostic. For example, in
  198. this output:
  199. ::
  200. test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
  201. #endif bad
  202. ^
  203. //
  204. Passing **-fno-diagnostics-show-option** will prevent Clang from
  205. printing the [:ref:`-Wextra-tokens <opt_Wextra-tokens>`] information in
  206. the diagnostic. This information tells you the flag needed to enable
  207. or disable the diagnostic, either from the command line or through
  208. :ref:`#pragma GCC diagnostic <pragma_GCC_diagnostic>`.
  209. .. _opt_fdiagnostics-show-category:
  210. .. option:: -fdiagnostics-show-category=none/id/name
  211. Enable printing category information in diagnostic line.
  212. This option, which defaults to "none", controls whether or not Clang
  213. prints the category associated with a diagnostic when emitting it.
  214. Each diagnostic may or many not have an associated category, if it
  215. has one, it is listed in the diagnostic categorization field of the
  216. diagnostic line (in the []'s).
  217. For example, a format string warning will produce these three
  218. renditions based on the setting of this option:
  219. ::
  220. t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat]
  221. t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat,1]
  222. t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat,Format String]
  223. This category can be used by clients that want to group diagnostics
  224. by category, so it should be a high level category. We want dozens
  225. of these, not hundreds or thousands of them.
  226. .. _opt_fsave-optimization-record:
  227. **-fsave-optimization-record**
  228. Write optimization remarks to a YAML file.
  229. This option, which defaults to off, controls whether Clang writes
  230. optimization reports to a YAML file. By recording diagnostics in a file,
  231. using a structured YAML format, users can parse or sort the remarks in a
  232. convenient way.
  233. .. _opt_foptimization-record-file:
  234. **-foptimization-record-file**
  235. Control the file to which optimization reports are written.
  236. When optimization reports are being output (see
  237. :ref:`-fsave-optimization-record <opt_fsave-optimization-record>`), this
  238. option controls the file to which those reports are written.
  239. If this option is not used, optimization records are output to a file named
  240. after the primary file being compiled. If that's "foo.c", for example,
  241. optimization records are output to "foo.opt.yaml".
  242. .. _opt_fdiagnostics-show-hotness:
  243. **-f[no-]diagnostics-show-hotness**
  244. Enable profile hotness information in diagnostic line.
  245. This option controls whether Clang prints the profile hotness associated
  246. with diagnostics in the presence of profile-guided optimization information.
  247. This is currently supported with optimization remarks (see
  248. :ref:`Options to Emit Optimization Reports <rpass>`). The hotness information
  249. allows users to focus on the hot optimization remarks that are likely to be
  250. more relevant for run-time performance.
  251. For example, in this output, the block containing the callsite of `foo` was
  252. executed 3000 times according to the profile data:
  253. ::
  254. s.c:7:10: remark: foo inlined into bar (hotness: 3000) [-Rpass-analysis=inline]
  255. sum += foo(x, x - 2);
  256. ^
  257. This option is implied when
  258. :ref:`-fsave-optimization-record <opt_fsave-optimization-record>` is used.
  259. Otherwise, it defaults to off.
  260. .. _opt_fdiagnostics-hotness-threshold:
  261. **-fdiagnostics-hotness-threshold**
  262. Prevent optimization remarks from being output if they do not have at least
  263. this hotness value.
  264. This option, which defaults to zero, controls the minimum hotness an
  265. optimization remark would need in order to be output by Clang. This is
  266. currently supported with optimization remarks (see :ref:`Options to Emit
  267. Optimization Reports <rpass>`) when profile hotness information in
  268. diagnostics is enabled (see
  269. :ref:`-fdiagnostics-show-hotness <opt_fdiagnostics-show-hotness>`).
  270. .. _opt_fdiagnostics-fixit-info:
  271. **-f[no-]diagnostics-fixit-info**
  272. Enable "FixIt" information in the diagnostics output.
  273. This option, which defaults to on, controls whether or not Clang
  274. prints the information on how to fix a specific diagnostic
  275. underneath it when it knows. For example, in this output:
  276. ::
  277. test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
  278. #endif bad
  279. ^
  280. //
  281. Passing **-fno-diagnostics-fixit-info** will prevent Clang from
  282. printing the "//" line at the end of the message. This information
  283. is useful for users who may not understand what is wrong, but can be
  284. confusing for machine parsing.
  285. .. _opt_fdiagnostics-print-source-range-info:
  286. **-fdiagnostics-print-source-range-info**
  287. Print machine parsable information about source ranges.
  288. This option makes Clang print information about source ranges in a machine
  289. parsable format after the file/line/column number information. The
  290. information is a simple sequence of brace enclosed ranges, where each range
  291. lists the start and end line/column locations. For example, in this output:
  292. ::
  293. exprs.c:47:15:{47:8-47:14}{47:17-47:24}: error: invalid operands to binary expression ('int *' and '_Complex float')
  294. P = (P-42) + Gamma*4;
  295. ~~~~~~ ^ ~~~~~~~
  296. The {}'s are generated by -fdiagnostics-print-source-range-info.
  297. The printed column numbers count bytes from the beginning of the
  298. line; take care if your source contains multibyte characters.
  299. .. option:: -fdiagnostics-parseable-fixits
  300. Print Fix-Its in a machine parseable form.
  301. This option makes Clang print available Fix-Its in a machine
  302. parseable format at the end of diagnostics. The following example
  303. illustrates the format:
  304. ::
  305. fix-it:"t.cpp":{7:25-7:29}:"Gamma"
  306. The range printed is a half-open range, so in this example the
  307. characters at column 25 up to but not including column 29 on line 7
  308. in t.cpp should be replaced with the string "Gamma". Either the
  309. range or the replacement string may be empty (representing strict
  310. insertions and strict erasures, respectively). Both the file name
  311. and the insertion string escape backslash (as "\\\\"), tabs (as
  312. "\\t"), newlines (as "\\n"), double quotes(as "\\"") and
  313. non-printable characters (as octal "\\xxx").
  314. The printed column numbers count bytes from the beginning of the
  315. line; take care if your source contains multibyte characters.
  316. .. option:: -fno-elide-type
  317. Turns off elision in template type printing.
  318. The default for template type printing is to elide as many template
  319. arguments as possible, removing those which are the same in both
  320. template types, leaving only the differences. Adding this flag will
  321. print all the template arguments. If supported by the terminal,
  322. highlighting will still appear on differing arguments.
  323. Default:
  324. ::
  325. t.cc:4:5: note: candidate function not viable: no known conversion from 'vector<map<[...], map<float, [...]>>>' to 'vector<map<[...], map<double, [...]>>>' for 1st argument;
  326. -fno-elide-type:
  327. ::
  328. t.cc:4:5: note: candidate function not viable: no known conversion from 'vector<map<int, map<float, int>>>' to 'vector<map<int, map<double, int>>>' for 1st argument;
  329. .. option:: -fdiagnostics-show-template-tree
  330. Template type diffing prints a text tree.
  331. For diffing large templated types, this option will cause Clang to
  332. display the templates as an indented text tree, one argument per
  333. line, with differences marked inline. This is compatible with
  334. -fno-elide-type.
  335. Default:
  336. ::
  337. t.cc:4:5: note: candidate function not viable: no known conversion from 'vector<map<[...], map<float, [...]>>>' to 'vector<map<[...], map<double, [...]>>>' for 1st argument;
  338. With :option:`-fdiagnostics-show-template-tree`:
  339. ::
  340. t.cc:4:5: note: candidate function not viable: no known conversion for 1st argument;
  341. vector<
  342. map<
  343. [...],
  344. map<
  345. [float != double],
  346. [...]>>>
  347. .. _cl_diag_warning_groups:
  348. Individual Warning Groups
  349. ^^^^^^^^^^^^^^^^^^^^^^^^^
  350. TODO: Generate this from tblgen. Define one anchor per warning group.
  351. .. _opt_wextra-tokens:
  352. .. option:: -Wextra-tokens
  353. Warn about excess tokens at the end of a preprocessor directive.
  354. This option, which defaults to on, enables warnings about extra
  355. tokens at the end of preprocessor directives. For example:
  356. ::
  357. test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
  358. #endif bad
  359. ^
  360. These extra tokens are not strictly conforming, and are usually best
  361. handled by commenting them out.
  362. .. option:: -Wambiguous-member-template
  363. Warn about unqualified uses of a member template whose name resolves to
  364. another template at the location of the use.
  365. This option, which defaults to on, enables a warning in the
  366. following code:
  367. ::
  368. template<typename T> struct set{};
  369. template<typename T> struct trait { typedef const T& type; };
  370. struct Value {
  371. template<typename T> void set(typename trait<T>::type value) {}
  372. };
  373. void foo() {
  374. Value v;
  375. v.set<double>(3.2);
  376. }
  377. C++ [basic.lookup.classref] requires this to be an error, but,
  378. because it's hard to work around, Clang downgrades it to a warning
  379. as an extension.
  380. .. option:: -Wbind-to-temporary-copy
  381. Warn about an unusable copy constructor when binding a reference to a
  382. temporary.
  383. This option enables warnings about binding a
  384. reference to a temporary when the temporary doesn't have a usable
  385. copy constructor. For example:
  386. ::
  387. struct NonCopyable {
  388. NonCopyable();
  389. private:
  390. NonCopyable(const NonCopyable&);
  391. };
  392. void foo(const NonCopyable&);
  393. void bar() {
  394. foo(NonCopyable()); // Disallowed in C++98; allowed in C++11.
  395. }
  396. ::
  397. struct NonCopyable2 {
  398. NonCopyable2();
  399. NonCopyable2(NonCopyable2&);
  400. };
  401. void foo(const NonCopyable2&);
  402. void bar() {
  403. foo(NonCopyable2()); // Disallowed in C++98; allowed in C++11.
  404. }
  405. Note that if ``NonCopyable2::NonCopyable2()`` has a default argument
  406. whose instantiation produces a compile error, that error will still
  407. be a hard error in C++98 mode even if this warning is turned off.
  408. Options to Control Clang Crash Diagnostics
  409. ------------------------------------------
  410. As unbelievable as it may sound, Clang does crash from time to time.
  411. Generally, this only occurs to those living on the `bleeding
  412. edge <http://llvm.org/releases/download.html#svn>`_. Clang goes to great
  413. lengths to assist you in filing a bug report. Specifically, Clang
  414. generates preprocessed source file(s) and associated run script(s) upon
  415. a crash. These files should be attached to a bug report to ease
  416. reproducibility of the failure. Below are the command line options to
  417. control the crash diagnostics.
  418. .. option:: -fno-crash-diagnostics
  419. Disable auto-generation of preprocessed source files during a clang crash.
  420. The -fno-crash-diagnostics flag can be helpful for speeding the process
  421. of generating a delta reduced test case.
  422. Clang is also capable of generating preprocessed source file(s) and associated
  423. run script(s) even without a crash. This is specially useful when trying to
  424. generate a reproducer for warnings or errors while using modules.
  425. .. option:: -gen-reproducer
  426. Generates preprocessed source files, a reproducer script and if relevant, a
  427. cache containing: built module pcm's and all headers needed to rebuilt the
  428. same modules.
  429. .. _rpass:
  430. Options to Emit Optimization Reports
  431. ------------------------------------
  432. Optimization reports trace, at a high-level, all the major decisions
  433. done by compiler transformations. For instance, when the inliner
  434. decides to inline function ``foo()`` into ``bar()``, or the loop unroller
  435. decides to unroll a loop N times, or the vectorizer decides to
  436. vectorize a loop body.
  437. Clang offers a family of flags which the optimizers can use to emit
  438. a diagnostic in three cases:
  439. 1. When the pass makes a transformation (`-Rpass`).
  440. 2. When the pass fails to make a transformation (`-Rpass-missed`).
  441. 3. When the pass determines whether or not to make a transformation
  442. (`-Rpass-analysis`).
  443. NOTE: Although the discussion below focuses on `-Rpass`, the exact
  444. same options apply to `-Rpass-missed` and `-Rpass-analysis`.
  445. Since there are dozens of passes inside the compiler, each of these flags
  446. take a regular expression that identifies the name of the pass which should
  447. emit the associated diagnostic. For example, to get a report from the inliner,
  448. compile the code with:
  449. .. code-block:: console
  450. $ clang -O2 -Rpass=inline code.cc -o code
  451. code.cc:4:25: remark: foo inlined into bar [-Rpass=inline]
  452. int bar(int j) { return foo(j, j - 2); }
  453. ^
  454. Note that remarks from the inliner are identified with `[-Rpass=inline]`.
  455. To request a report from every optimization pass, you should use
  456. `-Rpass=.*` (in fact, you can use any valid POSIX regular
  457. expression). However, do not expect a report from every transformation
  458. made by the compiler. Optimization remarks do not really make sense
  459. outside of the major transformations (e.g., inlining, vectorization,
  460. loop optimizations) and not every optimization pass supports this
  461. feature.
  462. Note that when using profile-guided optimization information, profile hotness
  463. information can be included in the remarks (see
  464. :ref:`-fdiagnostics-show-hotness <opt_fdiagnostics-show-hotness>`).
  465. Current limitations
  466. ^^^^^^^^^^^^^^^^^^^
  467. 1. Optimization remarks that refer to function names will display the
  468. mangled name of the function. Since these remarks are emitted by the
  469. back end of the compiler, it does not know anything about the input
  470. language, nor its mangling rules.
  471. 2. Some source locations are not displayed correctly. The front end has
  472. a more detailed source location tracking than the locations included
  473. in the debug info (e.g., the front end can locate code inside macro
  474. expansions). However, the locations used by `-Rpass` are
  475. translated from debug annotations. That translation can be lossy,
  476. which results in some remarks having no location information.
  477. Other Options
  478. -------------
  479. Clang options that don't fit neatly into other categories.
  480. .. option:: -MV
  481. When emitting a dependency file, use formatting conventions appropriate
  482. for NMake or Jom. Ignored unless another option causes Clang to emit a
  483. dependency file.
  484. When Clang emits a dependency file (e.g., you supplied the -M option)
  485. most filenames can be written to the file without any special formatting.
  486. Different Make tools will treat different sets of characters as "special"
  487. and use different conventions for telling the Make tool that the character
  488. is actually part of the filename. Normally Clang uses backslash to "escape"
  489. a special character, which is the convention used by GNU Make. The -MV
  490. option tells Clang to put double-quotes around the entire filename, which
  491. is the convention used by NMake and Jom.
  492. Language and Target-Independent Features
  493. ========================================
  494. Controlling Errors and Warnings
  495. -------------------------------
  496. Clang provides a number of ways to control which code constructs cause
  497. it to emit errors and warning messages, and how they are displayed to
  498. the console.
  499. Controlling How Clang Displays Diagnostics
  500. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  501. When Clang emits a diagnostic, it includes rich information in the
  502. output, and gives you fine-grain control over which information is
  503. printed. Clang has the ability to print this information, and these are
  504. the options that control it:
  505. #. A file/line/column indicator that shows exactly where the diagnostic
  506. occurs in your code [:ref:`-fshow-column <opt_fshow-column>`,
  507. :ref:`-fshow-source-location <opt_fshow-source-location>`].
  508. #. A categorization of the diagnostic as a note, warning, error, or
  509. fatal error.
  510. #. A text string that describes what the problem is.
  511. #. An option that indicates how to control the diagnostic (for
  512. diagnostics that support it)
  513. [:ref:`-fdiagnostics-show-option <opt_fdiagnostics-show-option>`].
  514. #. A :ref:`high-level category <diagnostics_categories>` for the diagnostic
  515. for clients that want to group diagnostics by class (for diagnostics
  516. that support it)
  517. [:ref:`-fdiagnostics-show-category <opt_fdiagnostics-show-category>`].
  518. #. The line of source code that the issue occurs on, along with a caret
  519. and ranges that indicate the important locations
  520. [:ref:`-fcaret-diagnostics <opt_fcaret-diagnostics>`].
  521. #. "FixIt" information, which is a concise explanation of how to fix the
  522. problem (when Clang is certain it knows)
  523. [:ref:`-fdiagnostics-fixit-info <opt_fdiagnostics-fixit-info>`].
  524. #. A machine-parsable representation of the ranges involved (off by
  525. default)
  526. [:ref:`-fdiagnostics-print-source-range-info <opt_fdiagnostics-print-source-range-info>`].
  527. For more information please see :ref:`Formatting of
  528. Diagnostics <cl_diag_formatting>`.
  529. Diagnostic Mappings
  530. ^^^^^^^^^^^^^^^^^^^
  531. All diagnostics are mapped into one of these 6 classes:
  532. - Ignored
  533. - Note
  534. - Remark
  535. - Warning
  536. - Error
  537. - Fatal
  538. .. _diagnostics_categories:
  539. Diagnostic Categories
  540. ^^^^^^^^^^^^^^^^^^^^^
  541. Though not shown by default, diagnostics may each be associated with a
  542. high-level category. This category is intended to make it possible to
  543. triage builds that produce a large number of errors or warnings in a
  544. grouped way.
  545. Categories are not shown by default, but they can be turned on with the
  546. :ref:`-fdiagnostics-show-category <opt_fdiagnostics-show-category>` option.
  547. When set to "``name``", the category is printed textually in the
  548. diagnostic output. When it is set to "``id``", a category number is
  549. printed. The mapping of category names to category id's can be obtained
  550. by running '``clang --print-diagnostic-categories``'.
  551. Controlling Diagnostics via Command Line Flags
  552. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  553. TODO: -W flags, -pedantic, etc
  554. .. _pragma_gcc_diagnostic:
  555. Controlling Diagnostics via Pragmas
  556. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  557. Clang can also control what diagnostics are enabled through the use of
  558. pragmas in the source code. This is useful for turning off specific
  559. warnings in a section of source code. Clang supports GCC's pragma for
  560. compatibility with existing source code, as well as several extensions.
  561. The pragma may control any warning that can be used from the command
  562. line. Warnings may be set to ignored, warning, error, or fatal. The
  563. following example code will tell Clang or GCC to ignore the -Wall
  564. warnings:
  565. .. code-block:: c
  566. #pragma GCC diagnostic ignored "-Wall"
  567. In addition to all of the functionality provided by GCC's pragma, Clang
  568. also allows you to push and pop the current warning state. This is
  569. particularly useful when writing a header file that will be compiled by
  570. other people, because you don't know what warning flags they build with.
  571. In the below example :option:`-Wextra-tokens` is ignored for only a single line
  572. of code, after which the diagnostics return to whatever state had previously
  573. existed.
  574. .. code-block:: c
  575. #if foo
  576. #endif foo // warning: extra tokens at end of #endif directive
  577. #pragma clang diagnostic push
  578. #pragma clang diagnostic ignored "-Wextra-tokens"
  579. #if foo
  580. #endif foo // no warning
  581. #pragma clang diagnostic pop
  582. The push and pop pragmas will save and restore the full diagnostic state
  583. of the compiler, regardless of how it was set. That means that it is
  584. possible to use push and pop around GCC compatible diagnostics and Clang
  585. will push and pop them appropriately, while GCC will ignore the pushes
  586. and pops as unknown pragmas. It should be noted that while Clang
  587. supports the GCC pragma, Clang and GCC do not support the exact same set
  588. of warnings, so even when using GCC compatible #pragmas there is no
  589. guarantee that they will have identical behaviour on both compilers.
  590. In addition to controlling warnings and errors generated by the compiler, it is
  591. possible to generate custom warning and error messages through the following
  592. pragmas:
  593. .. code-block:: c
  594. // The following will produce warning messages
  595. #pragma message "some diagnostic message"
  596. #pragma GCC warning "TODO: replace deprecated feature"
  597. // The following will produce an error message
  598. #pragma GCC error "Not supported"
  599. These pragmas operate similarly to the ``#warning`` and ``#error`` preprocessor
  600. directives, except that they may also be embedded into preprocessor macros via
  601. the C99 ``_Pragma`` operator, for example:
  602. .. code-block:: c
  603. #define STR(X) #X
  604. #define DEFER(M,...) M(__VA_ARGS__)
  605. #define CUSTOM_ERROR(X) _Pragma(STR(GCC error(X " at line " DEFER(STR,__LINE__))))
  606. CUSTOM_ERROR("Feature not available");
  607. Controlling Diagnostics in System Headers
  608. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  609. Warnings are suppressed when they occur in system headers. By default,
  610. an included file is treated as a system header if it is found in an
  611. include path specified by ``-isystem``, but this can be overridden in
  612. several ways.
  613. The ``system_header`` pragma can be used to mark the current file as
  614. being a system header. No warnings will be produced from the location of
  615. the pragma onwards within the same file.
  616. .. code-block:: c
  617. #if foo
  618. #endif foo // warning: extra tokens at end of #endif directive
  619. #pragma clang system_header
  620. #if foo
  621. #endif foo // no warning
  622. The `--system-header-prefix=` and `--no-system-header-prefix=`
  623. command-line arguments can be used to override whether subsets of an include
  624. path are treated as system headers. When the name in a ``#include`` directive
  625. is found within a header search path and starts with a system prefix, the
  626. header is treated as a system header. The last prefix on the
  627. command-line which matches the specified header name takes precedence.
  628. For instance:
  629. .. code-block:: console
  630. $ clang -Ifoo -isystem bar --system-header-prefix=x/ \
  631. --no-system-header-prefix=x/y/
  632. Here, ``#include "x/a.h"`` is treated as including a system header, even
  633. if the header is found in ``foo``, and ``#include "x/y/b.h"`` is treated
  634. as not including a system header, even if the header is found in
  635. ``bar``.
  636. A ``#include`` directive which finds a file relative to the current
  637. directory is treated as including a system header if the including file
  638. is treated as a system header.
  639. .. _diagnostics_enable_everything:
  640. Enabling All Diagnostics
  641. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  642. In addition to the traditional ``-W`` flags, one can enable **all**
  643. diagnostics by passing :option:`-Weverything`. This works as expected
  644. with
  645. :option:`-Werror`, and also includes the warnings from :option:`-pedantic`.
  646. Note that when combined with :option:`-w` (which disables all warnings), that
  647. flag wins.
  648. Controlling Static Analyzer Diagnostics
  649. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  650. While not strictly part of the compiler, the diagnostics from Clang's
  651. `static analyzer <http://clang-analyzer.llvm.org>`_ can also be
  652. influenced by the user via changes to the source code. See the available
  653. `annotations <http://clang-analyzer.llvm.org/annotations.html>`_ and the
  654. analyzer's `FAQ
  655. page <http://clang-analyzer.llvm.org/faq.html#exclude_code>`_ for more
  656. information.
  657. .. _usersmanual-precompiled-headers:
  658. Precompiled Headers
  659. -------------------
  660. `Precompiled headers <http://en.wikipedia.org/wiki/Precompiled_header>`__
  661. are a general approach employed by many compilers to reduce compilation
  662. time. The underlying motivation of the approach is that it is common for
  663. the same (and often large) header files to be included by multiple
  664. source files. Consequently, compile times can often be greatly improved
  665. by caching some of the (redundant) work done by a compiler to process
  666. headers. Precompiled header files, which represent one of many ways to
  667. implement this optimization, are literally files that represent an
  668. on-disk cache that contains the vital information necessary to reduce
  669. some of the work needed to process a corresponding header file. While
  670. details of precompiled headers vary between compilers, precompiled
  671. headers have been shown to be highly effective at speeding up program
  672. compilation on systems with very large system headers (e.g., Mac OS X).
  673. Generating a PCH File
  674. ^^^^^^^^^^^^^^^^^^^^^
  675. To generate a PCH file using Clang, one invokes Clang with the
  676. `-x <language>-header` option. This mirrors the interface in GCC
  677. for generating PCH files:
  678. .. code-block:: console
  679. $ gcc -x c-header test.h -o test.h.gch
  680. $ clang -x c-header test.h -o test.h.pch
  681. Using a PCH File
  682. ^^^^^^^^^^^^^^^^
  683. A PCH file can then be used as a prefix header when a :option:`-include`
  684. option is passed to ``clang``:
  685. .. code-block:: console
  686. $ clang -include test.h test.c -o test
  687. The ``clang`` driver will first check if a PCH file for ``test.h`` is
  688. available; if so, the contents of ``test.h`` (and the files it includes)
  689. will be processed from the PCH file. Otherwise, Clang falls back to
  690. directly processing the content of ``test.h``. This mirrors the behavior
  691. of GCC.
  692. .. note::
  693. Clang does *not* automatically use PCH files for headers that are directly
  694. included within a source file. For example:
  695. .. code-block:: console
  696. $ clang -x c-header test.h -o test.h.pch
  697. $ cat test.c
  698. #include "test.h"
  699. $ clang test.c -o test
  700. In this example, ``clang`` will not automatically use the PCH file for
  701. ``test.h`` since ``test.h`` was included directly in the source file and not
  702. specified on the command line using :option:`-include`.
  703. Relocatable PCH Files
  704. ^^^^^^^^^^^^^^^^^^^^^
  705. It is sometimes necessary to build a precompiled header from headers
  706. that are not yet in their final, installed locations. For example, one
  707. might build a precompiled header within the build tree that is then
  708. meant to be installed alongside the headers. Clang permits the creation
  709. of "relocatable" precompiled headers, which are built with a given path
  710. (into the build directory) and can later be used from an installed
  711. location.
  712. To build a relocatable precompiled header, place your headers into a
  713. subdirectory whose structure mimics the installed location. For example,
  714. if you want to build a precompiled header for the header ``mylib.h``
  715. that will be installed into ``/usr/include``, create a subdirectory
  716. ``build/usr/include`` and place the header ``mylib.h`` into that
  717. subdirectory. If ``mylib.h`` depends on other headers, then they can be
  718. stored within ``build/usr/include`` in a way that mimics the installed
  719. location.
  720. Building a relocatable precompiled header requires two additional
  721. arguments. First, pass the ``--relocatable-pch`` flag to indicate that
  722. the resulting PCH file should be relocatable. Second, pass
  723. `-isysroot /path/to/build`, which makes all includes for your library
  724. relative to the build directory. For example:
  725. .. code-block:: console
  726. # clang -x c-header --relocatable-pch -isysroot /path/to/build /path/to/build/mylib.h mylib.h.pch
  727. When loading the relocatable PCH file, the various headers used in the
  728. PCH file are found from the system header root. For example, ``mylib.h``
  729. can be found in ``/usr/include/mylib.h``. If the headers are installed
  730. in some other system root, the `-isysroot` option can be used provide
  731. a different system root from which the headers will be based. For
  732. example, `-isysroot /Developer/SDKs/MacOSX10.4u.sdk` will look for
  733. ``mylib.h`` in ``/Developer/SDKs/MacOSX10.4u.sdk/usr/include/mylib.h``.
  734. Relocatable precompiled headers are intended to be used in a limited
  735. number of cases where the compilation environment is tightly controlled
  736. and the precompiled header cannot be generated after headers have been
  737. installed.
  738. .. _controlling-code-generation:
  739. Controlling Code Generation
  740. ---------------------------
  741. Clang provides a number of ways to control code generation. The options
  742. are listed below.
  743. **-f[no-]sanitize=check1,check2,...**
  744. Turn on runtime checks for various forms of undefined or suspicious
  745. behavior.
  746. This option controls whether Clang adds runtime checks for various
  747. forms of undefined or suspicious behavior, and is disabled by
  748. default. If a check fails, a diagnostic message is produced at
  749. runtime explaining the problem. The main checks are:
  750. - .. _opt_fsanitize_address:
  751. ``-fsanitize=address``:
  752. :doc:`AddressSanitizer`, a memory error
  753. detector.
  754. - .. _opt_fsanitize_thread:
  755. ``-fsanitize=thread``: :doc:`ThreadSanitizer`, a data race detector.
  756. - .. _opt_fsanitize_memory:
  757. ``-fsanitize=memory``: :doc:`MemorySanitizer`,
  758. a detector of uninitialized reads. Requires instrumentation of all
  759. program code.
  760. - .. _opt_fsanitize_undefined:
  761. ``-fsanitize=undefined``: :doc:`UndefinedBehaviorSanitizer`,
  762. a fast and compatible undefined behavior checker.
  763. - ``-fsanitize=dataflow``: :doc:`DataFlowSanitizer`, a general data
  764. flow analysis.
  765. - ``-fsanitize=cfi``: :doc:`control flow integrity <ControlFlowIntegrity>`
  766. checks. Requires ``-flto``.
  767. - ``-fsanitize=safe-stack``: :doc:`safe stack <SafeStack>`
  768. protection against stack-based memory corruption errors.
  769. There are more fine-grained checks available: see
  770. the :ref:`list <ubsan-checks>` of specific kinds of
  771. undefined behavior that can be detected and the :ref:`list <cfi-schemes>`
  772. of control flow integrity schemes.
  773. The ``-fsanitize=`` argument must also be provided when linking, in
  774. order to link to the appropriate runtime library.
  775. It is not possible to combine more than one of the ``-fsanitize=address``,
  776. ``-fsanitize=thread``, and ``-fsanitize=memory`` checkers in the same
  777. program.
  778. **-f[no-]sanitize-recover=check1,check2,...**
  779. **-f[no-]sanitize-recover=all**
  780. Controls which checks enabled by ``-fsanitize=`` flag are non-fatal.
  781. If the check is fatal, program will halt after the first error
  782. of this kind is detected and error report is printed.
  783. By default, non-fatal checks are those enabled by
  784. :doc:`UndefinedBehaviorSanitizer`,
  785. except for ``-fsanitize=return`` and ``-fsanitize=unreachable``. Some
  786. sanitizers may not support recovery (or not support it by default
  787. e.g. :doc:`AddressSanitizer`), and always crash the program after the issue
  788. is detected.
  789. Note that the ``-fsanitize-trap`` flag has precedence over this flag.
  790. This means that if a check has been configured to trap elsewhere on the
  791. command line, or if the check traps by default, this flag will not have
  792. any effect unless that sanitizer's trapping behavior is disabled with
  793. ``-fno-sanitize-trap``.
  794. For example, if a command line contains the flags ``-fsanitize=undefined
  795. -fsanitize-trap=undefined``, the flag ``-fsanitize-recover=alignment``
  796. will have no effect on its own; it will need to be accompanied by
  797. ``-fno-sanitize-trap=alignment``.
  798. **-f[no-]sanitize-trap=check1,check2,...**
  799. Controls which checks enabled by the ``-fsanitize=`` flag trap. This
  800. option is intended for use in cases where the sanitizer runtime cannot
  801. be used (for instance, when building libc or a kernel module), or where
  802. the binary size increase caused by the sanitizer runtime is a concern.
  803. This flag is only compatible with :doc:`control flow integrity
  804. <ControlFlowIntegrity>` schemes and :doc:`UndefinedBehaviorSanitizer`
  805. checks other than ``vptr``. If this flag
  806. is supplied together with ``-fsanitize=undefined``, the ``vptr`` sanitizer
  807. will be implicitly disabled.
  808. This flag is enabled by default for sanitizers in the ``cfi`` group.
  809. .. option:: -fsanitize-blacklist=/path/to/blacklist/file
  810. Disable or modify sanitizer checks for objects (source files, functions,
  811. variables, types) listed in the file. See
  812. :doc:`SanitizerSpecialCaseList` for file format description.
  813. .. option:: -fno-sanitize-blacklist
  814. Don't use blacklist file, if it was specified earlier in the command line.
  815. **-f[no-]sanitize-coverage=[type,features,...]**
  816. Enable simple code coverage in addition to certain sanitizers.
  817. See :doc:`SanitizerCoverage` for more details.
  818. **-f[no-]sanitize-stats**
  819. Enable simple statistics gathering for the enabled sanitizers.
  820. See :doc:`SanitizerStats` for more details.
  821. .. option:: -fsanitize-undefined-trap-on-error
  822. Deprecated alias for ``-fsanitize-trap=undefined``.
  823. .. option:: -fsanitize-cfi-cross-dso
  824. Enable cross-DSO control flow integrity checks. This flag modifies
  825. the behavior of sanitizers in the ``cfi`` group to allow checking
  826. of cross-DSO virtual and indirect calls.
  827. .. option:: -fsanitize-cfi-icall-generalize-pointers
  828. Generalize pointers in return and argument types in function type signatures
  829. checked by Control Flow Integrity indirect call checking. See
  830. :doc:`ControlFlowIntegrity` for more details.
  831. .. option:: -fstrict-vtable-pointers
  832. Enable optimizations based on the strict rules for overwriting polymorphic
  833. C++ objects, i.e. the vptr is invariant during an object's lifetime.
  834. This enables better devirtualization. Turned off by default, because it is
  835. still experimental.
  836. .. option:: -ffast-math
  837. Enable fast-math mode. This defines the ``__FAST_MATH__`` preprocessor
  838. macro, and lets the compiler make aggressive, potentially-lossy assumptions
  839. about floating-point math. These include:
  840. * Floating-point math obeys regular algebraic rules for real numbers (e.g.
  841. ``+`` and ``*`` are associative, ``x/y == x * (1/y)``, and
  842. ``(a + b) * c == a * c + b * c``),
  843. * operands to floating-point operations are not equal to ``NaN`` and
  844. ``Inf``, and
  845. * ``+0`` and ``-0`` are interchangeable.
  846. .. option:: -fdenormal-fp-math=[values]
  847. Select which denormal numbers the code is permitted to require.
  848. Valid values are: ``ieee``, ``preserve-sign``, and ``positive-zero``,
  849. which correspond to IEEE 754 denormal numbers, the sign of a
  850. flushed-to-zero number is preserved in the sign of 0, denormals are
  851. flushed to positive zero, respectively.
  852. .. option:: -fwhole-program-vtables
  853. Enable whole-program vtable optimizations, such as single-implementation
  854. devirtualization and virtual constant propagation, for classes with
  855. :doc:`hidden LTO visibility <LTOVisibility>`. Requires ``-flto``.
  856. .. option:: -fno-assume-sane-operator-new
  857. Don't assume that the C++'s new operator is sane.
  858. This option tells the compiler to do not assume that C++'s global
  859. new operator will always return a pointer that does not alias any
  860. other pointer when the function returns.
  861. .. option:: -ftrap-function=[name]
  862. Instruct code generator to emit a function call to the specified
  863. function name for ``__builtin_trap()``.
  864. LLVM code generator translates ``__builtin_trap()`` to a trap
  865. instruction if it is supported by the target ISA. Otherwise, the
  866. builtin is translated into a call to ``abort``. If this option is
  867. set, then the code generator will always lower the builtin to a call
  868. to the specified function regardless of whether the target ISA has a
  869. trap instruction. This option is useful for environments (e.g.
  870. deeply embedded) where a trap cannot be properly handled, or when
  871. some custom behavior is desired.
  872. .. option:: -ftls-model=[model]
  873. Select which TLS model to use.
  874. Valid values are: ``global-dynamic``, ``local-dynamic``,
  875. ``initial-exec`` and ``local-exec``. The default value is
  876. ``global-dynamic``. The compiler may use a different model if the
  877. selected model is not supported by the target, or if a more
  878. efficient model can be used. The TLS model can be overridden per
  879. variable using the ``tls_model`` attribute.
  880. .. option:: -femulated-tls
  881. Select emulated TLS model, which overrides all -ftls-model choices.
  882. In emulated TLS mode, all access to TLS variables are converted to
  883. calls to __emutls_get_address in the runtime library.
  884. .. option:: -mhwdiv=[values]
  885. Select the ARM modes (arm or thumb) that support hardware division
  886. instructions.
  887. Valid values are: ``arm``, ``thumb`` and ``arm,thumb``.
  888. This option is used to indicate which mode (arm or thumb) supports
  889. hardware division instructions. This only applies to the ARM
  890. architecture.
  891. .. option:: -m[no-]crc
  892. Enable or disable CRC instructions.
  893. This option is used to indicate whether CRC instructions are to
  894. be generated. This only applies to the ARM architecture.
  895. CRC instructions are enabled by default on ARMv8.
  896. .. option:: -mgeneral-regs-only
  897. Generate code which only uses the general purpose registers.
  898. This option restricts the generated code to use general registers
  899. only. This only applies to the AArch64 architecture.
  900. .. option:: -mcompact-branches=[values]
  901. Control the usage of compact branches for MIPSR6.
  902. Valid values are: ``never``, ``optimal`` and ``always``.
  903. The default value is ``optimal`` which generates compact branches
  904. when a delay slot cannot be filled. ``never`` disables the usage of
  905. compact branches and ``always`` generates compact branches whenever
  906. possible.
  907. **-f[no-]max-type-align=[number]**
  908. Instruct the code generator to not enforce a higher alignment than the given
  909. number (of bytes) when accessing memory via an opaque pointer or reference.
  910. This cap is ignored when directly accessing a variable or when the pointee
  911. type has an explicit “aligned” attribute.
  912. The value should usually be determined by the properties of the system allocator.
  913. Some builtin types, especially vector types, have very high natural alignments;
  914. when working with values of those types, Clang usually wants to use instructions
  915. that take advantage of that alignment. However, many system allocators do
  916. not promise to return memory that is more than 8-byte or 16-byte-aligned. Use
  917. this option to limit the alignment that the compiler can assume for an arbitrary
  918. pointer, which may point onto the heap.
  919. This option does not affect the ABI alignment of types; the layout of structs and
  920. unions and the value returned by the alignof operator remain the same.
  921. This option can be overridden on a case-by-case basis by putting an explicit
  922. “aligned” alignment on a struct, union, or typedef. For example:
  923. .. code-block:: console
  924. #include <immintrin.h>
  925. // Make an aligned typedef of the AVX-512 16-int vector type.
  926. typedef __v16si __aligned_v16si __attribute__((aligned(64)));
  927. void initialize_vector(__aligned_v16si *v) {
  928. // The compiler may assume that ‘v’ is 64-byte aligned, regardless of the
  929. // value of -fmax-type-align.
  930. }
  931. Profile Guided Optimization
  932. ---------------------------
  933. Profile information enables better optimization. For example, knowing that a
  934. branch is taken very frequently helps the compiler make better decisions when
  935. ordering basic blocks. Knowing that a function ``foo`` is called more
  936. frequently than another function ``bar`` helps the inliner.
  937. Clang supports profile guided optimization with two different kinds of
  938. profiling. A sampling profiler can generate a profile with very low runtime
  939. overhead, or you can build an instrumented version of the code that collects
  940. more detailed profile information. Both kinds of profiles can provide execution
  941. counts for instructions in the code and information on branches taken and
  942. function invocation.
  943. Regardless of which kind of profiling you use, be careful to collect profiles
  944. by running your code with inputs that are representative of the typical
  945. behavior. Code that is not exercised in the profile will be optimized as if it
  946. is unimportant, and the compiler may make poor optimization choices for code
  947. that is disproportionately used while profiling.
  948. Differences Between Sampling and Instrumentation
  949. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  950. Although both techniques are used for similar purposes, there are important
  951. differences between the two:
  952. 1. Profile data generated with one cannot be used by the other, and there is no
  953. conversion tool that can convert one to the other. So, a profile generated
  954. via ``-fprofile-instr-generate`` must be used with ``-fprofile-instr-use``.
  955. Similarly, sampling profiles generated by external profilers must be
  956. converted and used with ``-fprofile-sample-use``.
  957. 2. Instrumentation profile data can be used for code coverage analysis and
  958. optimization.
  959. 3. Sampling profiles can only be used for optimization. They cannot be used for
  960. code coverage analysis. Although it would be technically possible to use
  961. sampling profiles for code coverage, sample-based profiles are too
  962. coarse-grained for code coverage purposes; it would yield poor results.
  963. 4. Sampling profiles must be generated by an external tool. The profile
  964. generated by that tool must then be converted into a format that can be read
  965. by LLVM. The section on sampling profilers describes one of the supported
  966. sampling profile formats.
  967. Using Sampling Profilers
  968. ^^^^^^^^^^^^^^^^^^^^^^^^
  969. Sampling profilers are used to collect runtime information, such as
  970. hardware counters, while your application executes. They are typically
  971. very efficient and do not incur a large runtime overhead. The
  972. sample data collected by the profiler can be used during compilation
  973. to determine what the most executed areas of the code are.
  974. Using the data from a sample profiler requires some changes in the way
  975. a program is built. Before the compiler can use profiling information,
  976. the code needs to execute under the profiler. The following is the
  977. usual build cycle when using sample profilers for optimization:
  978. 1. Build the code with source line table information. You can use all the
  979. usual build flags that you always build your application with. The only
  980. requirement is that you add ``-gline-tables-only`` or ``-g`` to the
  981. command line. This is important for the profiler to be able to map
  982. instructions back to source line locations.
  983. .. code-block:: console
  984. $ clang++ -O2 -gline-tables-only code.cc -o code
  985. 2. Run the executable under a sampling profiler. The specific profiler
  986. you use does not really matter, as long as its output can be converted
  987. into the format that the LLVM optimizer understands. Currently, there
  988. exists a conversion tool for the Linux Perf profiler
  989. (https://perf.wiki.kernel.org/), so these examples assume that you
  990. are using Linux Perf to profile your code.
  991. .. code-block:: console
  992. $ perf record -b ./code
  993. Note the use of the ``-b`` flag. This tells Perf to use the Last Branch
  994. Record (LBR) to record call chains. While this is not strictly required,
  995. it provides better call information, which improves the accuracy of
  996. the profile data.
  997. 3. Convert the collected profile data to LLVM's sample profile format.
  998. This is currently supported via the AutoFDO converter ``create_llvm_prof``.
  999. It is available at http://github.com/google/autofdo. Once built and
  1000. installed, you can convert the ``perf.data`` file to LLVM using
  1001. the command:
  1002. .. code-block:: console
  1003. $ create_llvm_prof --binary=./code --out=code.prof
  1004. This will read ``perf.data`` and the binary file ``./code`` and emit
  1005. the profile data in ``code.prof``. Note that if you ran ``perf``
  1006. without the ``-b`` flag, you need to use ``--use_lbr=false`` when
  1007. calling ``create_llvm_prof``.
  1008. 4. Build the code again using the collected profile. This step feeds
  1009. the profile back to the optimizers. This should result in a binary
  1010. that executes faster than the original one. Note that you are not
  1011. required to build the code with the exact same arguments that you
  1012. used in the first step. The only requirement is that you build the code
  1013. with ``-gline-tables-only`` and ``-fprofile-sample-use``.
  1014. .. code-block:: console
  1015. $ clang++ -O2 -gline-tables-only -fprofile-sample-use=code.prof code.cc -o code
  1016. Sample Profile Formats
  1017. """"""""""""""""""""""
  1018. Since external profilers generate profile data in a variety of custom formats,
  1019. the data generated by the profiler must be converted into a format that can be
  1020. read by the backend. LLVM supports three different sample profile formats:
  1021. 1. ASCII text. This is the easiest one to generate. The file is divided into
  1022. sections, which correspond to each of the functions with profile
  1023. information. The format is described below. It can also be generated from
  1024. the binary or gcov formats using the ``llvm-profdata`` tool.
  1025. 2. Binary encoding. This uses a more efficient encoding that yields smaller
  1026. profile files. This is the format generated by the ``create_llvm_prof`` tool
  1027. in http://github.com/google/autofdo.
  1028. 3. GCC encoding. This is based on the gcov format, which is accepted by GCC. It
  1029. is only interesting in environments where GCC and Clang co-exist. This
  1030. encoding is only generated by the ``create_gcov`` tool in
  1031. http://github.com/google/autofdo. It can be read by LLVM and
  1032. ``llvm-profdata``, but it cannot be generated by either.
  1033. If you are using Linux Perf to generate sampling profiles, you can use the
  1034. conversion tool ``create_llvm_prof`` described in the previous section.
  1035. Otherwise, you will need to write a conversion tool that converts your
  1036. profiler's native format into one of these three.
  1037. Sample Profile Text Format
  1038. """"""""""""""""""""""""""
  1039. This section describes the ASCII text format for sampling profiles. It is,
  1040. arguably, the easiest one to generate. If you are interested in generating any
  1041. of the other two, consult the ``ProfileData`` library in LLVM's source tree
  1042. (specifically, ``include/llvm/ProfileData/SampleProfReader.h``).
  1043. .. code-block:: console
  1044. function1:total_samples:total_head_samples
  1045. offset1[.discriminator]: number_of_samples [fn1:num fn2:num ... ]
  1046. offset2[.discriminator]: number_of_samples [fn3:num fn4:num ... ]
  1047. ...
  1048. offsetN[.discriminator]: number_of_samples [fn5:num fn6:num ... ]
  1049. offsetA[.discriminator]: fnA:num_of_total_samples
  1050. offsetA1[.discriminator]: number_of_samples [fn7:num fn8:num ... ]
  1051. offsetA1[.discriminator]: number_of_samples [fn9:num fn10:num ... ]
  1052. offsetB[.discriminator]: fnB:num_of_total_samples
  1053. offsetB1[.discriminator]: number_of_samples [fn11:num fn12:num ... ]
  1054. This is a nested tree in which the indentation represents the nesting level
  1055. of the inline stack. There are no blank lines in the file. And the spacing
  1056. within a single line is fixed. Additional spaces will result in an error
  1057. while reading the file.
  1058. Any line starting with the '#' character is completely ignored.
  1059. Inlined calls are represented with indentation. The Inline stack is a
  1060. stack of source locations in which the top of the stack represents the
  1061. leaf function, and the bottom of the stack represents the actual
  1062. symbol to which the instruction belongs.
  1063. Function names must be mangled in order for the profile loader to
  1064. match them in the current translation unit. The two numbers in the
  1065. function header specify how many total samples were accumulated in the
  1066. function (first number), and the total number of samples accumulated
  1067. in the prologue of the function (second number). This head sample
  1068. count provides an indicator of how frequently the function is invoked.
  1069. There are two types of lines in the function body.
  1070. - Sampled line represents the profile information of a source location.
  1071. ``offsetN[.discriminator]: number_of_samples [fn5:num fn6:num ... ]``
  1072. - Callsite line represents the profile information of an inlined callsite.
  1073. ``offsetA[.discriminator]: fnA:num_of_total_samples``
  1074. Each sampled line may contain several items. Some are optional (marked
  1075. below):
  1076. a. Source line offset. This number represents the line number
  1077. in the function where the sample was collected. The line number is
  1078. always relative to the line where symbol of the function is
  1079. defined. So, if the function has its header at line 280, the offset
  1080. 13 is at line 293 in the file.
  1081. Note that this offset should never be a negative number. This could
  1082. happen in cases like macros. The debug machinery will register the
  1083. line number at the point of macro expansion. So, if the macro was
  1084. expanded in a line before the start of the function, the profile
  1085. converter should emit a 0 as the offset (this means that the optimizers
  1086. will not be able to associate a meaningful weight to the instructions
  1087. in the macro).
  1088. b. [OPTIONAL] Discriminator. This is used if the sampled program
  1089. was compiled with DWARF discriminator support
  1090. (http://wiki.dwarfstd.org/index.php?title=Path_Discriminators).
  1091. DWARF discriminators are unsigned integer values that allow the
  1092. compiler to distinguish between multiple execution paths on the
  1093. same source line location.
  1094. For example, consider the line of code ``if (cond) foo(); else bar();``.
  1095. If the predicate ``cond`` is true 80% of the time, then the edge
  1096. into function ``foo`` should be considered to be taken most of the
  1097. time. But both calls to ``foo`` and ``bar`` are at the same source
  1098. line, so a sample count at that line is not sufficient. The
  1099. compiler needs to know which part of that line is taken more
  1100. frequently.
  1101. This is what discriminators provide. In this case, the calls to
  1102. ``foo`` and ``bar`` will be at the same line, but will have
  1103. different discriminator values. This allows the compiler to correctly
  1104. set edge weights into ``foo`` and ``bar``.
  1105. c. Number of samples. This is an integer quantity representing the
  1106. number of samples collected by the profiler at this source
  1107. location.
  1108. d. [OPTIONAL] Potential call targets and samples. If present, this
  1109. line contains a call instruction. This models both direct and
  1110. number of samples. For example,
  1111. .. code-block:: console
  1112. 130: 7 foo:3 bar:2 baz:7
  1113. The above means that at relative line offset 130 there is a call
  1114. instruction that calls one of ``foo()``, ``bar()`` and ``baz()``,
  1115. with ``baz()`` being the relatively more frequently called target.
  1116. As an example, consider a program with the call chain ``main -> foo -> bar``.
  1117. When built with optimizations enabled, the compiler may inline the
  1118. calls to ``bar`` and ``foo`` inside ``main``. The generated profile
  1119. could then be something like this:
  1120. .. code-block:: console
  1121. main:35504:0
  1122. 1: _Z3foov:35504
  1123. 2: _Z32bari:31977
  1124. 1.1: 31977
  1125. 2: 0
  1126. This profile indicates that there were a total of 35,504 samples
  1127. collected in main. All of those were at line 1 (the call to ``foo``).
  1128. Of those, 31,977 were spent inside the body of ``bar``. The last line
  1129. of the profile (``2: 0``) corresponds to line 2 inside ``main``. No
  1130. samples were collected there.
  1131. Profiling with Instrumentation
  1132. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1133. Clang also supports profiling via instrumentation. This requires building a
  1134. special instrumented version of the code and has some runtime
  1135. overhead during the profiling, but it provides more detailed results than a
  1136. sampling profiler. It also provides reproducible results, at least to the
  1137. extent that the code behaves consistently across runs.
  1138. Here are the steps for using profile guided optimization with
  1139. instrumentation:
  1140. 1. Build an instrumented version of the code by compiling and linking with the
  1141. ``-fprofile-instr-generate`` option.
  1142. .. code-block:: console
  1143. $ clang++ -O2 -fprofile-instr-generate code.cc -o code
  1144. 2. Run the instrumented executable with inputs that reflect the typical usage.
  1145. By default, the profile data will be written to a ``default.profraw`` file
  1146. in the current directory. You can override that default by using option
  1147. ``-fprofile-instr-generate=`` or by setting the ``LLVM_PROFILE_FILE``
  1148. environment variable to specify an alternate file. If non-default file name
  1149. is specified by both the environment variable and the command line option,
  1150. the environment variable takes precedence. The file name pattern specified
  1151. can include different modifiers: ``%p``, ``%h``, and ``%m``.
  1152. Any instance of ``%p`` in that file name will be replaced by the process
  1153. ID, so that you can easily distinguish the profile output from multiple
  1154. runs.
  1155. .. code-block:: console
  1156. $ LLVM_PROFILE_FILE="code-%p.profraw" ./code
  1157. The modifier ``%h`` can be used in scenarios where the same instrumented
  1158. binary is run in multiple different host machines dumping profile data
  1159. to a shared network based storage. The ``%h`` specifier will be substituted
  1160. with the hostname so that profiles collected from different hosts do not
  1161. clobber each other.
  1162. While the use of ``%p`` specifier can reduce the likelihood for the profiles
  1163. dumped from different processes to clobber each other, such clobbering can still
  1164. happen because of the ``pid`` re-use by the OS. Another side-effect of using
  1165. ``%p`` is that the storage requirement for raw profile data files is greatly
  1166. increased. To avoid issues like this, the ``%m`` specifier can used in the profile
  1167. name. When this specifier is used, the profiler runtime will substitute ``%m``
  1168. with a unique integer identifier associated with the instrumented binary. Additionally,
  1169. multiple raw profiles dumped from different processes that share a file system (can be
  1170. on different hosts) will be automatically merged by the profiler runtime during the
  1171. dumping. If the program links in multiple instrumented shared libraries, each library
  1172. will dump the profile data into its own profile data file (with its unique integer
  1173. id embedded in the profile name). Note that the merging enabled by ``%m`` is for raw
  1174. profile data generated by profiler runtime. The resulting merged "raw" profile data
  1175. file still needs to be converted to a different format expected by the compiler (
  1176. see step 3 below).
  1177. .. code-block:: console
  1178. $ LLVM_PROFILE_FILE="code-%m.profraw" ./code
  1179. 3. Combine profiles from multiple runs and convert the "raw" profile format to
  1180. the input expected by clang. Use the ``merge`` command of the
  1181. ``llvm-profdata`` tool to do this.
  1182. .. code-block:: console
  1183. $ llvm-profdata merge -output=code.profdata code-*.profraw
  1184. Note that this step is necessary even when there is only one "raw" profile,
  1185. since the merge operation also changes the file format.
  1186. 4. Build the code again using the ``-fprofile-instr-use`` option to specify the
  1187. collected profile data.
  1188. .. code-block:: console
  1189. $ clang++ -O2 -fprofile-instr-use=code.profdata code.cc -o code
  1190. You can repeat step 4 as often as you like without regenerating the
  1191. profile. As you make changes to your code, clang may no longer be able to
  1192. use the profile data. It will warn you when this happens.
  1193. Profile generation using an alternative instrumentation method can be
  1194. controlled by the GCC-compatible flags ``-fprofile-generate`` and
  1195. ``-fprofile-use``. Although these flags are semantically equivalent to
  1196. their GCC counterparts, they *do not* handle GCC-compatible profiles.
  1197. They are only meant to implement GCC's semantics with respect to
  1198. profile creation and use.
  1199. .. option:: -fprofile-generate[=<dirname>]
  1200. The ``-fprofile-generate`` and ``-fprofile-generate=`` flags will use
  1201. an alterantive instrumentation method for profile generation. When
  1202. given a directory name, it generates the profile file
  1203. ``default_%m.profraw`` in the directory named ``dirname`` if specified.
  1204. If ``dirname`` does not exist, it will be created at runtime. ``%m`` specifier
  1205. will be substibuted with a unique id documented in step 2 above. In other words,
  1206. with ``-fprofile-generate[=<dirname>]`` option, the "raw" profile data automatic
  1207. merging is turned on by default, so there will no longer any risk of profile
  1208. clobbering from different running processes. For example,
  1209. .. code-block:: console
  1210. $ clang++ -O2 -fprofile-generate=yyy/zzz code.cc -o code
  1211. When ``code`` is executed, the profile will be written to the file
  1212. ``yyy/zzz/default_xxxx.profraw``.
  1213. To generate the profile data file with the compiler readable format, the
  1214. ``llvm-profdata`` tool can be used with the profile directory as the input:
  1215. .. code-block:: console
  1216. $ llvm-profdata merge -output=code.profdata yyy/zzz/
  1217. If the user wants to turn off the auto-merging feature, or simply override the
  1218. the profile dumping path specified at command line, the environment variable
  1219. ``LLVM_PROFILE_FILE`` can still be used to override
  1220. the directory and filename for the profile file at runtime.
  1221. .. option:: -fprofile-use[=<pathname>]
  1222. Without any other arguments, ``-fprofile-use`` behaves identically to
  1223. ``-fprofile-instr-use``. Otherwise, if ``pathname`` is the full path to a
  1224. profile file, it reads from that file. If ``pathname`` is a directory name,
  1225. it reads from ``pathname/default.profdata``.
  1226. Disabling Instrumentation
  1227. ^^^^^^^^^^^^^^^^^^^^^^^^^
  1228. In certain situations, it may be useful to disable profile generation or use
  1229. for specific files in a build, without affecting the main compilation flags
  1230. used for the other files in the project.
  1231. In these cases, you can use the flag ``-fno-profile-instr-generate`` (or
  1232. ``-fno-profile-generate``) to disable profile generation, and
  1233. ``-fno-profile-instr-use`` (or ``-fno-profile-use``) to disable profile use.
  1234. Note that these flags should appear after the corresponding profile
  1235. flags to have an effect.
  1236. Controlling Debug Information
  1237. -----------------------------
  1238. Controlling Size of Debug Information
  1239. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1240. Debug info kind generated by Clang can be set by one of the flags listed
  1241. below. If multiple flags are present, the last one is used.
  1242. .. option:: -g0
  1243. Don't generate any debug info (default).
  1244. .. option:: -gline-tables-only
  1245. Generate line number tables only.
  1246. This kind of debug info allows to obtain stack traces with function names,
  1247. file names and line numbers (by such tools as ``gdb`` or ``addr2line``). It
  1248. doesn't contain any other data (e.g. description of local variables or
  1249. function parameters).
  1250. .. option:: -fstandalone-debug
  1251. Clang supports a number of optimizations to reduce the size of debug
  1252. information in the binary. They work based on the assumption that
  1253. the debug type information can be spread out over multiple
  1254. compilation units. For instance, Clang will not emit type
  1255. definitions for types that are not needed by a module and could be
  1256. replaced with a forward declaration. Further, Clang will only emit
  1257. type info for a dynamic C++ class in the module that contains the
  1258. vtable for the class.
  1259. The **-fstandalone-debug** option turns off these optimizations.
  1260. This is useful when working with 3rd-party libraries that don't come
  1261. with debug information. Note that Clang will never emit type
  1262. information for types that are not referenced at all by the program.
  1263. .. option:: -fno-standalone-debug
  1264. On Darwin **-fstandalone-debug** is enabled by default. The
  1265. **-fno-standalone-debug** option can be used to get to turn on the
  1266. vtable-based optimization described above.
  1267. .. option:: -g
  1268. Generate complete debug info.
  1269. Controlling Macro Debug Info Generation
  1270. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1271. Debug info for C preprocessor macros increases the size of debug information in
  1272. the binary. Macro debug info generated by Clang can be controlled by the flags
  1273. listed below.
  1274. .. option:: -fdebug-macro
  1275. Generate debug info for preprocessor macros. This flag is discarded when
  1276. **-g0** is enabled.
  1277. .. option:: -fno-debug-macro
  1278. Do not generate debug info for preprocessor macros (default).
  1279. Controlling Debugger "Tuning"
  1280. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1281. While Clang generally emits standard DWARF debug info (http://dwarfstd.org),
  1282. different debuggers may know how to take advantage of different specific DWARF
  1283. features. You can "tune" the debug info for one of several different debuggers.
  1284. .. option:: -ggdb, -glldb, -gsce
  1285. Tune the debug info for the ``gdb``, ``lldb``, or Sony PlayStation\ |reg|
  1286. debugger, respectively. Each of these options implies **-g**. (Therefore, if
  1287. you want both **-gline-tables-only** and debugger tuning, the tuning option
  1288. must come first.)
  1289. Comment Parsing Options
  1290. -----------------------
  1291. Clang parses Doxygen and non-Doxygen style documentation comments and attaches
  1292. them to the appropriate declaration nodes. By default, it only parses
  1293. Doxygen-style comments and ignores ordinary comments starting with ``//`` and
  1294. ``/*``.
  1295. .. option:: -Wdocumentation
  1296. Emit warnings about use of documentation comments. This warning group is off
  1297. by default.
  1298. This includes checking that ``\param`` commands name parameters that actually
  1299. present in the function signature, checking that ``\returns`` is used only on
  1300. functions that actually return a value etc.
  1301. .. option:: -Wno-documentation-unknown-command
  1302. Don't warn when encountering an unknown Doxygen command.
  1303. .. option:: -fparse-all-comments
  1304. Parse all comments as documentation comments (including ordinary comments
  1305. starting with ``//`` and ``/*``).
  1306. .. option:: -fcomment-block-commands=[commands]
  1307. Define custom documentation commands as block commands. This allows Clang to
  1308. construct the correct AST for these custom commands, and silences warnings
  1309. about unknown commands. Several commands must be separated by a comma
  1310. *without trailing space*; e.g. ``-fcomment-block-commands=foo,bar`` defines
  1311. custom commands ``\foo`` and ``\bar``.
  1312. It is also possible to use ``-fcomment-block-commands`` several times; e.g.
  1313. ``-fcomment-block-commands=foo -fcomment-block-commands=bar`` does the same
  1314. as above.
  1315. .. _c:
  1316. C Language Features
  1317. ===================
  1318. The support for standard C in clang is feature-complete except for the
  1319. C99 floating-point pragmas.
  1320. Extensions supported by clang
  1321. -----------------------------
  1322. See :doc:`LanguageExtensions`.
  1323. Differences between various standard modes
  1324. ------------------------------------------
  1325. clang supports the -std option, which changes what language mode clang
  1326. uses. The supported modes for C are c89, gnu89, c94, c99, gnu99, c11,
  1327. gnu11, and various aliases for those modes. If no -std option is
  1328. specified, clang defaults to gnu11 mode. Many C99 and C11 features are
  1329. supported in earlier modes as a conforming extension, with a warning. Use
  1330. ``-pedantic-errors`` to request an error if a feature from a later standard
  1331. revision is used in an earlier mode.
  1332. Differences between all ``c*`` and ``gnu*`` modes:
  1333. - ``c*`` modes define "``__STRICT_ANSI__``".
  1334. - Target-specific defines not prefixed by underscores, like "linux",
  1335. are defined in ``gnu*`` modes.
  1336. - Trigraphs default to being off in ``gnu*`` modes; they can be enabled by
  1337. the -trigraphs option.
  1338. - The parser recognizes "asm" and "typeof" as keywords in ``gnu*`` modes;
  1339. the variants "``__asm__``" and "``__typeof__``" are recognized in all
  1340. modes.
  1341. - The Apple "blocks" extension is recognized by default in ``gnu*`` modes
  1342. on some platforms; it can be enabled in any mode with the "-fblocks"
  1343. option.
  1344. - Arrays that are VLA's according to the standard, but which can be
  1345. constant folded by the frontend are treated as fixed size arrays.
  1346. This occurs for things like "int X[(1, 2)];", which is technically a
  1347. VLA. ``c*`` modes are strictly compliant and treat these as VLAs.
  1348. Differences between ``*89`` and ``*99`` modes:
  1349. - The ``*99`` modes default to implementing "inline" as specified in C99,
  1350. while the ``*89`` modes implement the GNU version. This can be
  1351. overridden for individual functions with the ``__gnu_inline__``
  1352. attribute.
  1353. - Digraphs are not recognized in c89 mode.
  1354. - The scope of names defined inside a "for", "if", "switch", "while",
  1355. or "do" statement is different. (example: "``if ((struct x {int
  1356. x;}*)0) {}``".)
  1357. - ``__STDC_VERSION__`` is not defined in ``*89`` modes.
  1358. - "inline" is not recognized as a keyword in c89 mode.
  1359. - "restrict" is not recognized as a keyword in ``*89`` modes.
  1360. - Commas are allowed in integer constant expressions in ``*99`` modes.
  1361. - Arrays which are not lvalues are not implicitly promoted to pointers
  1362. in ``*89`` modes.
  1363. - Some warnings are different.
  1364. Differences between ``*99`` and ``*11`` modes:
  1365. - Warnings for use of C11 features are disabled.
  1366. - ``__STDC_VERSION__`` is defined to ``201112L`` rather than ``199901L``.
  1367. c94 mode is identical to c89 mode except that digraphs are enabled in
  1368. c94 mode (FIXME: And ``__STDC_VERSION__`` should be defined!).
  1369. GCC extensions not implemented yet
  1370. ----------------------------------
  1371. clang tries to be compatible with gcc as much as possible, but some gcc
  1372. extensions are not implemented yet:
  1373. - clang does not support decimal floating point types (``_Decimal32`` and
  1374. friends) or fixed-point types (``_Fract`` and friends); nobody has
  1375. expressed interest in these features yet, so it's hard to say when
  1376. they will be implemented.
  1377. - clang does not support nested functions; this is a complex feature
  1378. which is infrequently used, so it is unlikely to be implemented
  1379. anytime soon. In C++11 it can be emulated by assigning lambda
  1380. functions to local variables, e.g:
  1381. .. code-block:: cpp
  1382. auto const local_function = [&](int parameter) {
  1383. // Do something
  1384. };
  1385. ...
  1386. local_function(1);
  1387. - clang only supports global register variables when the register specified
  1388. is non-allocatable (e.g. the stack pointer). Support for general global
  1389. register variables is unlikely to be implemented soon because it requires
  1390. additional LLVM backend support.
  1391. - clang does not support static initialization of flexible array
  1392. members. This appears to be a rarely used extension, but could be
  1393. implemented pending user demand.
  1394. - clang does not support
  1395. ``__builtin_va_arg_pack``/``__builtin_va_arg_pack_len``. This is
  1396. used rarely, but in some potentially interesting places, like the
  1397. glibc headers, so it may be implemented pending user demand. Note
  1398. that because clang pretends to be like GCC 4.2, and this extension
  1399. was introduced in 4.3, the glibc headers will not try to use this
  1400. extension with clang at the moment.
  1401. - clang does not support the gcc extension for forward-declaring
  1402. function parameters; this has not shown up in any real-world code
  1403. yet, though, so it might never be implemented.
  1404. This is not a complete list; if you find an unsupported extension
  1405. missing from this list, please send an e-mail to cfe-dev. This list
  1406. currently excludes C++; see :ref:`C++ Language Features <cxx>`. Also, this
  1407. list does not include bugs in mostly-implemented features; please see
  1408. the `bug
  1409. tracker <https://bugs.llvm.org/buglist.cgi?quicksearch=product%3Aclang+component%3A-New%2BBugs%2CAST%2CBasic%2CDriver%2CHeaders%2CLLVM%2BCodeGen%2Cparser%2Cpreprocessor%2CSemantic%2BAnalyzer>`_
  1410. for known existing bugs (FIXME: Is there a section for bug-reporting
  1411. guidelines somewhere?).
  1412. Intentionally unsupported GCC extensions
  1413. ----------------------------------------
  1414. - clang does not support the gcc extension that allows variable-length
  1415. arrays in structures. This is for a few reasons: one, it is tricky to
  1416. implement, two, the extension is completely undocumented, and three,
  1417. the extension appears to be rarely used. Note that clang *does*
  1418. support flexible array members (arrays with a zero or unspecified
  1419. size at the end of a structure).
  1420. - clang does not have an equivalent to gcc's "fold"; this means that
  1421. clang doesn't accept some constructs gcc might accept in contexts
  1422. where a constant expression is required, like "x-x" where x is a
  1423. variable.
  1424. - clang does not support ``__builtin_apply`` and friends; this extension
  1425. is extremely obscure and difficult to implement reliably.
  1426. .. _c_ms:
  1427. Microsoft extensions
  1428. --------------------
  1429. clang has support for many extensions from Microsoft Visual C++. To enable these
  1430. extensions, use the ``-fms-extensions`` command-line option. This is the default
  1431. for Windows targets. Clang does not implement every pragma or declspec provided
  1432. by MSVC, but the popular ones, such as ``__declspec(dllexport)`` and ``#pragma
  1433. comment(lib)`` are well supported.
  1434. clang has a ``-fms-compatibility`` flag that makes clang accept enough
  1435. invalid C++ to be able to parse most Microsoft headers. For example, it
  1436. allows `unqualified lookup of dependent base class members
  1437. <http://clang.llvm.org/compatibility.html#dep_lookup_bases>`_, which is
  1438. a common compatibility issue with clang. This flag is enabled by default
  1439. for Windows targets.
  1440. ``-fdelayed-template-parsing`` lets clang delay parsing of function template
  1441. definitions until the end of a translation unit. This flag is enabled by
  1442. default for Windows targets.
  1443. For compatibility with existing code that compiles with MSVC, clang defines the
  1444. ``_MSC_VER`` and ``_MSC_FULL_VER`` macros. These default to the values of 1800
  1445. and 180000000 respectively, making clang look like an early release of Visual
  1446. C++ 2013. The ``-fms-compatibility-version=`` flag overrides these values. It
  1447. accepts a dotted version tuple, such as 19.00.23506. Changing the MSVC
  1448. compatibility version makes clang behave more like that version of MSVC. For
  1449. example, ``-fms-compatibility-version=19`` will enable C++14 features and define
  1450. ``char16_t`` and ``char32_t`` as builtin types.
  1451. .. _cxx:
  1452. C++ Language Features
  1453. =====================
  1454. clang fully implements all of standard C++98 except for exported
  1455. templates (which were removed in C++11), and all of standard C++11
  1456. and the current draft standard for C++1y.
  1457. Controlling implementation limits
  1458. ---------------------------------
  1459. .. option:: -fbracket-depth=N
  1460. Sets the limit for nested parentheses, brackets, and braces to N. The
  1461. default is 256.
  1462. .. option:: -fconstexpr-depth=N
  1463. Sets the limit for recursive constexpr function invocations to N. The
  1464. default is 512.
  1465. .. option:: -ftemplate-depth=N
  1466. Sets the limit for recursively nested template instantiations to N. The
  1467. default is 256.
  1468. .. option:: -foperator-arrow-depth=N
  1469. Sets the limit for iterative calls to 'operator->' functions to N. The
  1470. default is 256.
  1471. .. _objc:
  1472. Objective-C Language Features
  1473. =============================
  1474. .. _objcxx:
  1475. Objective-C++ Language Features
  1476. ===============================
  1477. .. _openmp:
  1478. OpenMP Features
  1479. ===============
  1480. Clang supports all OpenMP 3.1 directives and clauses. In addition, some
  1481. features of OpenMP 4.0 are supported. For example, ``#pragma omp simd``,
  1482. ``#pragma omp for simd``, ``#pragma omp parallel for simd`` directives, extended
  1483. set of atomic constructs, ``proc_bind`` clause for all parallel-based
  1484. directives, ``depend`` clause for ``#pragma omp task`` directive (except for
  1485. array sections), ``#pragma omp cancel`` and ``#pragma omp cancellation point``
  1486. directives, and ``#pragma omp taskgroup`` directive.
  1487. Use `-fopenmp` to enable OpenMP. Support for OpenMP can be disabled with
  1488. `-fno-openmp`.
  1489. Controlling implementation limits
  1490. ---------------------------------
  1491. .. option:: -fopenmp-use-tls
  1492. Controls code generation for OpenMP threadprivate variables. In presence of
  1493. this option all threadprivate variables are generated the same way as thread
  1494. local variables, using TLS support. If `-fno-openmp-use-tls`
  1495. is provided or target does not support TLS, code generation for threadprivate
  1496. variables relies on OpenMP runtime library.
  1497. .. _opencl:
  1498. OpenCL Features
  1499. ===============
  1500. Clang can be used to compile OpenCL kernels for execution on a device
  1501. (e.g. GPU). It is possible to compile the kernel into a binary (e.g. for AMD or
  1502. Nvidia targets) that can be uploaded to run directly on a device (e.g. using
  1503. `clCreateProgramWithBinary
  1504. <https://www.khronos.org/registry/OpenCL/specs/opencl-1.1.pdf#111>`_) or
  1505. into generic bitcode files loadable into other toolchains.
  1506. Compiling to a binary using the default target from the installation can be done
  1507. as follows:
  1508. .. code-block:: console
  1509. $ echo "kernel void k(){}" > test.cl
  1510. $ clang test.cl
  1511. Compiling for a specific target can be done by specifying the triple corresponding
  1512. to the target, for example:
  1513. .. code-block:: console
  1514. $ clang -target nvptx64-unknown-unknown test.cl
  1515. $ clang -target amdgcn-amd-amdhsa-opencl test.cl
  1516. Compiling to bitcode can be done as follows:
  1517. .. code-block:: console
  1518. $ clang -c -emit-llvm test.cl
  1519. This will produce a generic test.bc file that can be used in vendor toolchains
  1520. to perform machine code generation.
  1521. Clang currently supports OpenCL C language standards up to v2.0.
  1522. OpenCL Specific Options
  1523. -----------------------
  1524. Most of the OpenCL build options from `the specification v2.0 section 5.8.4
  1525. <https://www.khronos.org/registry/cl/specs/opencl-2.0.pdf#200>`_ are available.
  1526. Examples:
  1527. .. code-block:: console
  1528. $ clang -cl-std=CL2.0 -cl-single-precision-constant test.cl
  1529. Some extra options are available to support special OpenCL features.
  1530. .. option:: -finclude-default-header
  1531. Loads standard includes during compilations. By default OpenCL headers are not
  1532. loaded and therefore standard library includes are not available. To load them
  1533. automatically a flag has been added to the frontend (see also :ref:`the section
  1534. on the OpenCL Header <opencl_header>`):
  1535. .. code-block:: console
  1536. $ clang -Xclang -finclude-default-header test.cl
  1537. Alternatively ``-include`` or ``-I`` followed by the path to the header location
  1538. can be given manually.
  1539. .. code-block:: console
  1540. $ clang -I<path to clang>/lib/Headers/opencl-c.h test.cl
  1541. In this case the kernel code should contain ``#include <opencl-c.h>`` just as a
  1542. regular C include.
  1543. .. _opencl_cl_ext:
  1544. .. option:: -cl-ext
  1545. Disables support of OpenCL extensions. All OpenCL targets provide a list
  1546. of extensions that they support. Clang allows to amend this using the ``-cl-ext``
  1547. flag with a comma-separated list of extensions prefixed with ``'+'`` or ``'-'``.
  1548. The syntax: ``-cl-ext=<(['-'|'+']<extension>[,])+>``, where extensions
  1549. can be either one of `the OpenCL specification extensions
  1550. <https://www.khronos.org/registry/cl/sdk/2.0/docs/man/xhtml/EXTENSION.html>`_
  1551. or any known vendor extension. Alternatively, ``'all'`` can be used to enable
  1552. or disable all known extensions.
  1553. Example disabling double support for the 64-bit SPIR target:
  1554. .. code-block:: console
  1555. $ clang -cc1 -triple spir64-unknown-unknown -cl-ext=-cl_khr_fp64 test.cl
  1556. Enabling all extensions except double support in R600 AMD GPU can be done using:
  1557. .. code-block:: console
  1558. $ clang -cc1 -triple r600-unknown-unknown -cl-ext=-all,+cl_khr_fp16 test.cl
  1559. .. _opencl_fake_address_space_map:
  1560. .. option:: -ffake-address-space-map
  1561. Overrides the target address space map with a fake map.
  1562. This allows adding explicit address space IDs to the bitcode for non-segmented
  1563. memory architectures that don't have separate IDs for each of the OpenCL
  1564. logical address spaces by default. Passing ``-ffake-address-space-map`` will
  1565. add/override address spaces of the target compiled for with the following values:
  1566. ``1-global``, ``2-constant``, ``3-local``, ``4-generic``. The private address
  1567. space is represented by the absence of an address space attribute in the IR (see
  1568. also :ref:`the section on the address space attribute <opencl_addrsp>`).
  1569. .. code-block:: console
  1570. $ clang -ffake-address-space-map test.cl
  1571. Some other flags used for the compilation for C can also be passed while
  1572. compiling for OpenCL, examples: ``-c``, ``-O<1-4|s>``, ``-o``, ``-emit-llvm``, etc.
  1573. OpenCL Targets
  1574. --------------
  1575. OpenCL targets are derived from the regular Clang target classes. The OpenCL
  1576. specific parts of the target representation provide address space mapping as
  1577. well as a set of supported extensions.
  1578. Specific Targets
  1579. ^^^^^^^^^^^^^^^^
  1580. There is a set of concrete HW architectures that OpenCL can be compiled for.
  1581. - For AMD target:
  1582. .. code-block:: console
  1583. $ clang -target amdgcn-amd-amdhsa-opencl test.cl
  1584. - For Nvidia architectures:
  1585. .. code-block:: console
  1586. $ clang -target nvptx64-unknown-unknown test.cl
  1587. Generic Targets
  1588. ^^^^^^^^^^^^^^^
  1589. - SPIR is available as a generic target to allow portable bitcode to be produced
  1590. that can be used across GPU toolchains. The implementation follows `the SPIR
  1591. specification <https://www.khronos.org/spir>`_. There are two flavors
  1592. available for 32 and 64 bits.
  1593. .. code-block:: console
  1594. $ clang -target spir-unknown-unknown test.cl
  1595. $ clang -target spir64-unknown-unknown test.cl
  1596. All known OpenCL extensions are supported in the SPIR targets. Clang will
  1597. generate SPIR v1.2 compatible IR for OpenCL versions up to 2.0 and SPIR v2.0
  1598. for OpenCL v2.0.
  1599. - x86 is used by some implementations that are x86 compatible and currently
  1600. remains for backwards compatibility (with older implementations prior to
  1601. SPIR target support). For "non-SPMD" targets which cannot spawn multiple
  1602. work-items on the fly using hardware, which covers practically all non-GPU
  1603. devices such as CPUs and DSPs, additional processing is needed for the kernels
  1604. to support multiple work-item execution. For this, a 3rd party toolchain,
  1605. such as for example `POCL <http://portablecl.org/>`_, can be used.
  1606. This target does not support multiple memory segments and, therefore, the fake
  1607. address space map can be added using the :ref:`-ffake-address-space-map
  1608. <opencl_fake_address_space_map>` flag.
  1609. .. _opencl_header:
  1610. OpenCL Header
  1611. -------------
  1612. By default Clang will not include standard headers and therefore OpenCL builtin
  1613. functions and some types (i.e. vectors) are unknown. The default CL header is,
  1614. however, provided in the Clang installation and can be enabled by passing the
  1615. ``-finclude-default-header`` flag to the Clang frontend.
  1616. .. code-block:: console
  1617. $ echo "bool is_wg_uniform(int i){return get_enqueued_local_size(i)==get_local_size(i);}" > test.cl
  1618. $ clang -Xclang -finclude-default-header -cl-std=CL2.0 test.cl
  1619. Because the header is very large and long to parse, PCH (:doc:`PCHInternals`)
  1620. and modules (:doc:`Modules`) are used internally to improve the compilation
  1621. speed.
  1622. To enable modules for OpenCL:
  1623. .. code-block:: console
  1624. $ clang -target spir-unknown-unknown -c -emit-llvm -Xclang -finclude-default-header -fmodules -fimplicit-module-maps -fmodules-cache-path=<path to the generated module> test.cl
  1625. OpenCL Extensions
  1626. -----------------
  1627. All of the ``cl_khr_*`` extensions from `the official OpenCL specification
  1628. <https://www.khronos.org/registry/OpenCL/sdk/2.0/docs/man/xhtml/EXTENSION.html>`_
  1629. up to and including version 2.0 are available and set per target depending on the
  1630. support available in the specific architecture.
  1631. It is possible to alter the default extensions setting per target using
  1632. ``-cl-ext`` flag. (See :ref:`flags description <opencl_cl_ext>` for more details).
  1633. Vendor extensions can be added flexibly by declaring the list of types and
  1634. functions associated with each extensions enclosed within the following
  1635. compiler pragma directives:
  1636. .. code-block:: c
  1637. #pragma OPENCL EXTENSION the_new_extension_name : begin
  1638. // declare types and functions associated with the extension here
  1639. #pragma OPENCL EXTENSION the_new_extension_name : end
  1640. For example, parsing the following code adds ``my_t`` type and ``my_func``
  1641. function to the custom ``my_ext`` extension.
  1642. .. code-block:: c
  1643. #pragma OPENCL EXTENSION my_ext : begin
  1644. typedef struct{
  1645. int a;
  1646. }my_t;
  1647. void my_func(my_t);
  1648. #pragma OPENCL EXTENSION my_ext : end
  1649. Declaring the same types in different vendor extensions is disallowed.
  1650. OpenCL Metadata
  1651. ---------------
  1652. Clang uses metadata to provide additional OpenCL semantics in IR needed for
  1653. backends and OpenCL runtime.
  1654. Each kernel will have function metadata attached to it, specifying the arguments.
  1655. Kernel argument metadata is used to provide source level information for querying
  1656. at runtime, for example using the `clGetKernelArgInfo
  1657. <https://www.khronos.org/registry/OpenCL/specs/opencl-1.2.pdf#167>`_
  1658. call.
  1659. Note that ``-cl-kernel-arg-info`` enables more information about the original CL
  1660. code to be added e.g. kernel parameter names will appear in the OpenCL metadata
  1661. along with other information.
  1662. The IDs used to encode the OpenCL's logical address spaces in the argument info
  1663. metadata follows the SPIR address space mapping as defined in the SPIR
  1664. specification `section 2.2
  1665. <https://www.khronos.org/registry/spir/specs/spir_spec-2.0.pdf#18>`_
  1666. OpenCL-Specific Attributes
  1667. --------------------------
  1668. OpenCL support in Clang contains a set of attribute taken directly from the
  1669. specification as well as additional attributes.
  1670. See also :doc:`AttributeReference`.
  1671. nosvm
  1672. ^^^^^
  1673. Clang supports this attribute to comply to OpenCL v2.0 conformance, but it
  1674. does not have any effect on the IR. For more details reffer to the specification
  1675. `section 6.7.2
  1676. <https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#49>`_
  1677. opencl_unroll_hint
  1678. ^^^^^^^^^^^^^^^^^^
  1679. The implementation of this feature mirrors the unroll hint for C.
  1680. More details on the syntax can be found in the specification
  1681. `section 6.11.5
  1682. <https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#61>`_
  1683. convergent
  1684. ^^^^^^^^^^
  1685. To make sure no invalid optimizations occur for single program multiple data
  1686. (SPMD) / single instruction multiple thread (SIMT) Clang provides attributes that
  1687. can be used for special functions that have cross work item semantics.
  1688. An example is the subgroup operations such as `intel_sub_group_shuffle
  1689. <https://www.khronos.org/registry/cl/extensions/intel/cl_intel_subgroups.txt>`_
  1690. .. code-block:: c
  1691. // Define custom my_sub_group_shuffle(data, c)
  1692. // that makes use of intel_sub_group_shuffle
  1693. r1 = ...
  1694. if (r0) r1 = computeA();
  1695. // Shuffle data from r1 into r3
  1696. // of threads id r2.
  1697. r3 = my_sub_group_shuffle(r1, r2);
  1698. if (r0) r3 = computeB();
  1699. with non-SPMD semantics this is optimized to the following equivalent code:
  1700. .. code-block:: c
  1701. r1 = ...
  1702. if (!r0)
  1703. // Incorrect functionality! The data in r1
  1704. // have not been computed by all threads yet.
  1705. r3 = my_sub_group_shuffle(r1, r2);
  1706. else {
  1707. r1 = computeA();
  1708. r3 = my_sub_group_shuffle(r1, r2);
  1709. r3 = computeB();
  1710. }
  1711. Declaring the function ``my_sub_group_shuffle`` with the convergent attribute
  1712. would prevent this:
  1713. .. code-block:: c
  1714. my_sub_group_shuffle() __attribute__((convergent));
  1715. Using ``convergent`` guarantees correct execution by keeping CFG equivalence
  1716. wrt operations marked as ``convergent``. CFG ``G´`` is equivalent to ``G`` wrt
  1717. node ``Ni`` : ``iff ∀ Nj (i≠j)`` domination and post-domination relations with
  1718. respect to ``Ni`` remain the same in both ``G`` and ``G´``.
  1719. noduplicate
  1720. ^^^^^^^^^^^
  1721. ``noduplicate`` is more restrictive with respect to optimizations than
  1722. ``convergent`` because a convergent function only preserves CFG equivalence.
  1723. This allows some optimizations to happen as long as the control flow remains
  1724. unmodified.
  1725. .. code-block:: c
  1726. for (int i=0; i<4; i++)
  1727. my_sub_group_shuffle()
  1728. can be modified to:
  1729. .. code-block:: c
  1730. my_sub_group_shuffle();
  1731. my_sub_group_shuffle();
  1732. my_sub_group_shuffle();
  1733. my_sub_group_shuffle();
  1734. while using ``noduplicate`` would disallow this. Also ``noduplicate`` doesn't
  1735. have the same safe semantics of CFG as ``convergent`` and can cause changes in
  1736. CFG that modify semantics of the original program.
  1737. ``noduplicate`` is kept for backwards compatibility only and it considered to be
  1738. deprecated for future uses.
  1739. .. _opencl_addrsp:
  1740. address_space
  1741. ^^^^^^^^^^^^^
  1742. Clang has arbitrary address space support using the ``address_space(N)``
  1743. attribute, where ``N`` is an integer number in the range ``0`` to ``16777215``
  1744. (``0xffffffu``).
  1745. An OpenCL implementation provides a list of standard address spaces using
  1746. keywords: ``private``, ``local``, ``global``, and ``generic``. In the AST and
  1747. in the IR local, global, or generic will be represented by the address space
  1748. attribute with the corresponding unique number. Note that private does not have
  1749. any corresponding attribute added and, therefore, is represented by the absence
  1750. of an address space number. The specific IDs for an address space do not have to
  1751. match between the AST and the IR. Typically in the AST address space numbers
  1752. represent logical segments while in the IR they represent physical segments.
  1753. Therefore, machines with flat memory segments can map all AST address space
  1754. numbers to the same physical segment ID or skip address space attribute
  1755. completely while generating the IR. However, if the address space information
  1756. is needed by the IR passes e.g. to improve alias analysis, it is recommended
  1757. to keep it and only lower to reflect physical memory segments in the late
  1758. machine passes.
  1759. OpenCL builtins
  1760. ---------------
  1761. There are some standard OpenCL functions that are implemented as Clang builtins:
  1762. - All pipe functions from `section 6.13.16.2/6.13.16.3
  1763. <https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#160>`_ of
  1764. the OpenCL v2.0 kernel language specification. `
  1765. - Address space qualifier conversion functions ``to_global``/``to_local``/``to_private``
  1766. from `section 6.13.9
  1767. <https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#101>`_.
  1768. - All the ``enqueue_kernel`` functions from `section 6.13.17.1
  1769. <https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#164>`_ and
  1770. enqueue query functions from `section 6.13.17.5
  1771. <https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#171>`_.
  1772. .. _target_features:
  1773. Target-Specific Features and Limitations
  1774. ========================================
  1775. CPU Architectures Features and Limitations
  1776. ------------------------------------------
  1777. X86
  1778. ^^^
  1779. The support for X86 (both 32-bit and 64-bit) is considered stable on
  1780. Darwin (Mac OS X), Linux, FreeBSD, and Dragonfly BSD: it has been tested
  1781. to correctly compile many large C, C++, Objective-C, and Objective-C++
  1782. codebases.
  1783. On ``x86_64-mingw32``, passing i128(by value) is incompatible with the
  1784. Microsoft x64 calling convention. You might need to tweak
  1785. ``WinX86_64ABIInfo::classify()`` in lib/CodeGen/TargetInfo.cpp.
  1786. For the X86 target, clang supports the `-m16` command line
  1787. argument which enables 16-bit code output. This is broadly similar to
  1788. using ``asm(".code16gcc")`` with the GNU toolchain. The generated code
  1789. and the ABI remains 32-bit but the assembler emits instructions
  1790. appropriate for a CPU running in 16-bit mode, with address-size and
  1791. operand-size prefixes to enable 32-bit addressing and operations.
  1792. ARM
  1793. ^^^
  1794. The support for ARM (specifically ARMv6 and ARMv7) is considered stable
  1795. on Darwin (iOS): it has been tested to correctly compile many large C,
  1796. C++, Objective-C, and Objective-C++ codebases. Clang only supports a
  1797. limited number of ARM architectures. It does not yet fully support
  1798. ARMv5, for example.
  1799. PowerPC
  1800. ^^^^^^^
  1801. The support for PowerPC (especially PowerPC64) is considered stable
  1802. on Linux and FreeBSD: it has been tested to correctly compile many
  1803. large C and C++ codebases. PowerPC (32bit) is still missing certain
  1804. features (e.g. PIC code on ELF platforms).
  1805. Other platforms
  1806. ^^^^^^^^^^^^^^^
  1807. clang currently contains some support for other architectures (e.g. Sparc);
  1808. however, significant pieces of code generation are still missing, and they
  1809. haven't undergone significant testing.
  1810. clang contains limited support for the MSP430 embedded processor, but
  1811. both the clang support and the LLVM backend support are highly
  1812. experimental.
  1813. Other platforms are completely unsupported at the moment. Adding the
  1814. minimal support needed for parsing and semantic analysis on a new
  1815. platform is quite easy; see ``lib/Basic/Targets.cpp`` in the clang source
  1816. tree. This level of support is also sufficient for conversion to LLVM IR
  1817. for simple programs. Proper support for conversion to LLVM IR requires
  1818. adding code to ``lib/CodeGen/CGCall.cpp`` at the moment; this is likely to
  1819. change soon, though. Generating assembly requires a suitable LLVM
  1820. backend.
  1821. Operating System Features and Limitations
  1822. -----------------------------------------
  1823. Darwin (Mac OS X)
  1824. ^^^^^^^^^^^^^^^^^
  1825. Thread Sanitizer is not supported.
  1826. Windows
  1827. ^^^^^^^
  1828. Clang has experimental support for targeting "Cygming" (Cygwin / MinGW)
  1829. platforms.
  1830. See also :ref:`Microsoft Extensions <c_ms>`.
  1831. Cygwin
  1832. """"""
  1833. Clang works on Cygwin-1.7.
  1834. MinGW32
  1835. """""""
  1836. Clang works on some mingw32 distributions. Clang assumes directories as
  1837. below;
  1838. - ``C:/mingw/include``
  1839. - ``C:/mingw/lib``
  1840. - ``C:/mingw/lib/gcc/mingw32/4.[3-5].0/include/c++``
  1841. On MSYS, a few tests might fail.
  1842. MinGW-w64
  1843. """""""""
  1844. For 32-bit (i686-w64-mingw32), and 64-bit (x86\_64-w64-mingw32), Clang
  1845. assumes as below;
  1846. - ``GCC versions 4.5.0 to 4.5.3, 4.6.0 to 4.6.2, or 4.7.0 (for the C++ header search path)``
  1847. - ``some_directory/bin/gcc.exe``
  1848. - ``some_directory/bin/clang.exe``
  1849. - ``some_directory/bin/clang++.exe``
  1850. - ``some_directory/bin/../include/c++/GCC_version``
  1851. - ``some_directory/bin/../include/c++/GCC_version/x86_64-w64-mingw32``
  1852. - ``some_directory/bin/../include/c++/GCC_version/i686-w64-mingw32``
  1853. - ``some_directory/bin/../include/c++/GCC_version/backward``
  1854. - ``some_directory/bin/../x86_64-w64-mingw32/include``
  1855. - ``some_directory/bin/../i686-w64-mingw32/include``
  1856. - ``some_directory/bin/../include``
  1857. This directory layout is standard for any toolchain you will find on the
  1858. official `MinGW-w64 website <http://mingw-w64.sourceforge.net>`_.
  1859. Clang expects the GCC executable "gcc.exe" compiled for
  1860. ``i686-w64-mingw32`` (or ``x86_64-w64-mingw32``) to be present on PATH.
  1861. `Some tests might fail <https://bugs.llvm.org/show_bug.cgi?id=9072>`_ on
  1862. ``x86_64-w64-mingw32``.
  1863. .. _clang-cl:
  1864. clang-cl
  1865. ========
  1866. clang-cl is an alternative command-line interface to Clang, designed for
  1867. compatibility with the Visual C++ compiler, cl.exe.
  1868. To enable clang-cl to find system headers, libraries, and the linker when run
  1869. from the command-line, it should be executed inside a Visual Studio Native Tools
  1870. Command Prompt or a regular Command Prompt where the environment has been set
  1871. up using e.g. `vcvars32.bat <http://msdn.microsoft.com/en-us/library/f2ccy3wt.aspx>`_.
  1872. clang-cl can also be used from inside Visual Studio by using an LLVM Platform
  1873. Toolset.
  1874. Command-Line Options
  1875. --------------------
  1876. To be compatible with cl.exe, clang-cl supports most of the same command-line
  1877. options. Those options can start with either ``/`` or ``-``. It also supports
  1878. some of Clang's core options, such as the ``-W`` options.
  1879. Options that are known to clang-cl, but not currently supported, are ignored
  1880. with a warning. For example:
  1881. ::
  1882. clang-cl.exe: warning: argument unused during compilation: '/AI'
  1883. To suppress warnings about unused arguments, use the ``-Qunused-arguments`` option.
  1884. Options that are not known to clang-cl will be ignored by default. Use the
  1885. ``-Werror=unknown-argument`` option in order to treat them as errors. If these
  1886. options are spelled with a leading ``/``, they will be mistaken for a filename:
  1887. ::
  1888. clang-cl.exe: error: no such file or directory: '/foobar'
  1889. Please `file a bug <https://bugs.llvm.org/enter_bug.cgi?product=clang&component=Driver>`_
  1890. for any valid cl.exe flags that clang-cl does not understand.
  1891. Execute ``clang-cl /?`` to see a list of supported options:
  1892. ::
  1893. CL.EXE COMPATIBILITY OPTIONS:
  1894. /? Display available options
  1895. /arch:<value> Set architecture for code generation
  1896. /Brepro- Emit an object file which cannot be reproduced over time
  1897. /Brepro Emit an object file which can be reproduced over time
  1898. /C Don't discard comments when preprocessing
  1899. /c Compile only
  1900. /d1reportAllClassLayout Dump record layout information
  1901. /diagnostics:caret Enable caret and column diagnostics (on by default)
  1902. /diagnostics:classic Disable column and caret diagnostics
  1903. /diagnostics:column Disable caret diagnostics but keep column info
  1904. /D <macro[=value]> Define macro
  1905. /EH<value> Exception handling model
  1906. /EP Disable linemarker output and preprocess to stdout
  1907. /execution-charset:<value>
  1908. Runtime encoding, supports only UTF-8
  1909. /E Preprocess to stdout
  1910. /fallback Fall back to cl.exe if clang-cl fails to compile
  1911. /FA Output assembly code file during compilation
  1912. /Fa<file or directory> Output assembly code to this file during compilation (with /FA)
  1913. /Fe<file or directory> Set output executable file or directory (ends in / or \)
  1914. /FI <value> Include file before parsing
  1915. /Fi<file> Set preprocess output file name (with /P)
  1916. /Fo<file or directory> Set output object file, or directory (ends in / or \) (with /c)
  1917. /fp:except-
  1918. /fp:except
  1919. /fp:fast
  1920. /fp:precise
  1921. /fp:strict
  1922. /Fp<filename> Set pch filename (with /Yc and /Yu)
  1923. /GA Assume thread-local variables are defined in the executable
  1924. /Gd Set __cdecl as a default calling convention
  1925. /GF- Disable string pooling
  1926. /GR- Disable emission of RTTI data
  1927. /GR Enable emission of RTTI data
  1928. /Gr Set __fastcall as a default calling convention
  1929. /GS- Disable buffer security check
  1930. /GS Enable buffer security check
  1931. /Gs<value> Set stack probe size
  1932. /Gv Set __vectorcall as a default calling convention
  1933. /Gw- Don't put each data item in its own section
  1934. /Gw Put each data item in its own section
  1935. /GX- Enable exception handling
  1936. /GX Enable exception handling
  1937. /Gy- Don't put each function in its own section
  1938. /Gy Put each function in its own section
  1939. /Gz Set __stdcall as a default calling convention
  1940. /help Display available options
  1941. /imsvc <dir> Add directory to system include search path, as if part of %INCLUDE%
  1942. /I <dir> Add directory to include search path
  1943. /J Make char type unsigned
  1944. /LDd Create debug DLL
  1945. /LD Create DLL
  1946. /link <options> Forward options to the linker
  1947. /MDd Use DLL debug run-time
  1948. /MD Use DLL run-time
  1949. /MTd Use static debug run-time
  1950. /MT Use static run-time
  1951. /Od Disable optimization
  1952. /Oi- Disable use of builtin functions
  1953. /Oi Enable use of builtin functions
  1954. /Os Optimize for size
  1955. /Ot Optimize for speed
  1956. /O<value> Optimization level
  1957. /o <file or directory> Set output file or directory (ends in / or \)
  1958. /P Preprocess to file
  1959. /Qvec- Disable the loop vectorization passes
  1960. /Qvec Enable the loop vectorization passes
  1961. /showIncludes Print info about included files to stderr
  1962. /source-charset:<value> Source encoding, supports only UTF-8
  1963. /std:<value> Language standard to compile for
  1964. /TC Treat all source files as C
  1965. /Tc <filename> Specify a C source file
  1966. /TP Treat all source files as C++
  1967. /Tp <filename> Specify a C++ source file
  1968. /utf-8 Set source and runtime encoding to UTF-8 (default)
  1969. /U <macro> Undefine macro
  1970. /vd<value> Control vtordisp placement
  1971. /vmb Use a best-case representation method for member pointers
  1972. /vmg Use a most-general representation for member pointers
  1973. /vmm Set the default most-general representation to multiple inheritance
  1974. /vms Set the default most-general representation to single inheritance
  1975. /vmv Set the default most-general representation to virtual inheritance
  1976. /volatile:iso Volatile loads and stores have standard semantics
  1977. /volatile:ms Volatile loads and stores have acquire and release semantics
  1978. /W0 Disable all warnings
  1979. /W1 Enable -Wall
  1980. /W2 Enable -Wall
  1981. /W3 Enable -Wall
  1982. /W4 Enable -Wall and -Wextra
  1983. /Wall Enable -Wall and -Wextra
  1984. /WX- Do not treat warnings as errors
  1985. /WX Treat warnings as errors
  1986. /w Disable all warnings
  1987. /Y- Disable precompiled headers, overrides /Yc and /Yu
  1988. /Yc<filename> Generate a pch file for all code up to and including <filename>
  1989. /Yu<filename> Load a pch file and use it instead of all code up to and including <filename>
  1990. /Z7 Enable CodeView debug information in object files
  1991. /Zc:sizedDealloc- Disable C++14 sized global deallocation functions
  1992. /Zc:sizedDealloc Enable C++14 sized global deallocation functions
  1993. /Zc:strictStrings Treat string literals as const
  1994. /Zc:threadSafeInit- Disable thread-safe initialization of static variables
  1995. /Zc:threadSafeInit Enable thread-safe initialization of static variables
  1996. /Zc:trigraphs- Disable trigraphs (default)
  1997. /Zc:trigraphs Enable trigraphs
  1998. /Zc:twoPhase- Disable two-phase name lookup in templates
  1999. /Zc:twoPhase Enable two-phase name lookup in templates
  2000. /Zd Emit debug line number tables only
  2001. /Zi Alias for /Z7. Does not produce PDBs.
  2002. /Zl Don't mention any default libraries in the object file
  2003. /Zp Set the default maximum struct packing alignment to 1
  2004. /Zp<value> Specify the default maximum struct packing alignment
  2005. /Zs Syntax-check only
  2006. OPTIONS:
  2007. -### Print (but do not run) the commands to run for this compilation
  2008. --analyze Run the static analyzer
  2009. -fansi-escape-codes Use ANSI escape codes for diagnostics
  2010. -fcolor-diagnostics Use colors in diagnostics
  2011. -fdebug-macro Emit macro debug information
  2012. -fdelayed-template-parsing
  2013. Parse templated function definitions at the end of the translation unit
  2014. -fdiagnostics-absolute-paths
  2015. Print absolute paths in diagnostics
  2016. -fdiagnostics-parseable-fixits
  2017. Print fix-its in machine parseable form
  2018. -flto=<value> Set LTO mode to either 'full' or 'thin'
  2019. -flto Enable LTO in 'full' mode
  2020. -fms-compatibility-version=<value>
  2021. Dot-separated value representing the Microsoft compiler version
  2022. number to report in _MSC_VER (0 = don't define it (default))
  2023. -fms-compatibility Enable full Microsoft Visual C++ compatibility
  2024. -fms-extensions Accept some non-standard constructs supported by the Microsoft compiler
  2025. -fmsc-version=<value> Microsoft compiler version number to report in _MSC_VER
  2026. (0 = don't define it (default))
  2027. -fno-debug-macro Do not emit macro debug information
  2028. -fno-delayed-template-parsing
  2029. Disable delayed template parsing
  2030. -fno-sanitize-address-use-after-scope
  2031. Disable use-after-scope detection in AddressSanitizer
  2032. -fno-sanitize-blacklist Don't use blacklist file for sanitizers
  2033. -fno-sanitize-cfi-cross-dso
  2034. Disable control flow integrity (CFI) checks for cross-DSO calls.
  2035. -fno-sanitize-coverage=<value>
  2036. Disable specified features of coverage instrumentation for Sanitizers
  2037. -fno-sanitize-memory-track-origins
  2038. Disable origins tracking in MemorySanitizer
  2039. -fno-sanitize-recover=<value>
  2040. Disable recovery for specified sanitizers
  2041. -fno-sanitize-stats Disable sanitizer statistics gathering.
  2042. -fno-sanitize-thread-atomics
  2043. Disable atomic operations instrumentation in ThreadSanitizer
  2044. -fno-sanitize-thread-func-entry-exit
  2045. Disable function entry/exit instrumentation in ThreadSanitizer
  2046. -fno-sanitize-thread-memory-access
  2047. Disable memory access instrumentation in ThreadSanitizer
  2048. -fno-sanitize-trap=<value>
  2049. Disable trapping for specified sanitizers
  2050. -fno-standalone-debug Limit debug information produced to reduce size of debug binary
  2051. -fprofile-instr-generate=<file>
  2052. Generate instrumented code to collect execution counts into <file>
  2053. (overridden by LLVM_PROFILE_FILE env var)
  2054. -fprofile-instr-generate
  2055. Generate instrumented code to collect execution counts into default.profraw file
  2056. (overridden by '=' form of option or LLVM_PROFILE_FILE env var)
  2057. -fprofile-instr-use=<value>
  2058. Use instrumentation data for profile-guided optimization
  2059. -fsanitize-address-field-padding=<value>
  2060. Level of field padding for AddressSanitizer
  2061. -fsanitize-address-globals-dead-stripping
  2062. Enable linker dead stripping of globals in AddressSanitizer
  2063. -fsanitize-address-use-after-scope
  2064. Enable use-after-scope detection in AddressSanitizer
  2065. -fsanitize-blacklist=<value>
  2066. Path to blacklist file for sanitizers
  2067. -fsanitize-cfi-cross-dso
  2068. Enable control flow integrity (CFI) checks for cross-DSO calls.
  2069. -fsanitize-coverage=<value>
  2070. Specify the type of coverage instrumentation for Sanitizers
  2071. -fsanitize-memory-track-origins=<value>
  2072. Enable origins tracking in MemorySanitizer
  2073. -fsanitize-memory-track-origins
  2074. Enable origins tracking in MemorySanitizer
  2075. -fsanitize-memory-use-after-dtor
  2076. Enable use-after-destroy detection in MemorySanitizer
  2077. -fsanitize-recover=<value>
  2078. Enable recovery for specified sanitizers
  2079. -fsanitize-stats Enable sanitizer statistics gathering.
  2080. -fsanitize-thread-atomics
  2081. Enable atomic operations instrumentation in ThreadSanitizer (default)
  2082. -fsanitize-thread-func-entry-exit
  2083. Enable function entry/exit instrumentation in ThreadSanitizer (default)
  2084. -fsanitize-thread-memory-access
  2085. Enable memory access instrumentation in ThreadSanitizer (default)
  2086. -fsanitize-trap=<value> Enable trapping for specified sanitizers
  2087. -fsanitize-undefined-strip-path-components=<number>
  2088. Strip (or keep only, if negative) a given number of path components when emitting check metadata.
  2089. -fsanitize=<check> Turn on runtime checks for various forms of undefined or suspicious
  2090. behavior. See user manual for available checks
  2091. -fstandalone-debug Emit full debug info for all types used by the program
  2092. -gcodeview Generate CodeView debug information
  2093. -gline-tables-only Emit debug line number tables only
  2094. -miamcu Use Intel MCU ABI
  2095. -mllvm <value> Additional arguments to forward to LLVM's option processing
  2096. -nobuiltininc Disable builtin #include directories
  2097. -Qunused-arguments Don't emit warning for unused driver arguments
  2098. -R<remark> Enable the specified remark
  2099. --target=<value> Generate code for the given target
  2100. -v Show commands to run and use verbose output
  2101. -W<warning> Enable the specified warning
  2102. -Xclang <arg> Pass <arg> to the clang compiler
  2103. The /fallback Option
  2104. ^^^^^^^^^^^^^^^^^^^^
  2105. When clang-cl is run with the ``/fallback`` option, it will first try to
  2106. compile files itself. For any file that it fails to compile, it will fall back
  2107. and try to compile the file by invoking cl.exe.
  2108. This option is intended to be used as a temporary means to build projects where
  2109. clang-cl cannot successfully compile all the files. clang-cl may fail to compile
  2110. a file either because it cannot generate code for some C++ feature, or because
  2111. it cannot parse some Microsoft language extension.