UsersManual.rst 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906
  1. ============================
  2. Clang Compiler User's Manual
  3. ============================
  4. .. contents::
  5. :local:
  6. Introduction
  7. ============
  8. The Clang Compiler is an open-source compiler for the C family of
  9. programming languages, aiming to be the best in class implementation of
  10. these languages. Clang builds on the LLVM optimizer and code generator,
  11. allowing it to provide high-quality optimization and code generation
  12. support for many targets. For more general information, please see the
  13. `Clang Web Site <http://clang.llvm.org>`_ or the `LLVM Web
  14. Site <http://llvm.org>`_.
  15. This document describes important notes about using Clang as a compiler
  16. for an end-user, documenting the supported features, command line
  17. options, etc. If you are interested in using Clang to build a tool that
  18. processes code, please see :doc:`InternalsManual`. If you are interested in the
  19. `Clang Static Analyzer <http://clang-analyzer.llvm.org>`_, please see its web
  20. page.
  21. Clang is designed to support the C family of programming languages,
  22. which includes :ref:`C <c>`, :ref:`Objective-C <objc>`, :ref:`C++ <cxx>`, and
  23. :ref:`Objective-C++ <objcxx>` as well as many dialects of those. For
  24. language-specific information, please see the corresponding language
  25. specific section:
  26. - :ref:`C Language <c>`: K&R C, ANSI C89, ISO C90, ISO C94 (C89+AMD1), ISO
  27. C99 (+TC1, TC2, TC3).
  28. - :ref:`Objective-C Language <objc>`: ObjC 1, ObjC 2, ObjC 2.1, plus
  29. variants depending on base language.
  30. - :ref:`C++ Language <cxx>`
  31. - :ref:`Objective C++ Language <objcxx>`
  32. In addition to these base languages and their dialects, Clang supports a
  33. broad variety of language extensions, which are documented in the
  34. corresponding language section. These extensions are provided to be
  35. compatible with the GCC, Microsoft, and other popular compilers as well
  36. as to improve functionality through Clang-specific features. The Clang
  37. driver and language features are intentionally designed to be as
  38. compatible with the GNU GCC compiler as reasonably possible, easing
  39. migration from GCC to Clang. In most cases, code "just works".
  40. Clang also provides an alternative driver, :ref:`clang-cl`, that is designed
  41. to be compatible with the Visual C++ compiler, cl.exe.
  42. In addition to language specific features, Clang has a variety of
  43. features that depend on what CPU architecture or operating system is
  44. being compiled for. Please see the :ref:`Target-Specific Features and
  45. Limitations <target_features>` section for more details.
  46. The rest of the introduction introduces some basic :ref:`compiler
  47. terminology <terminology>` that is used throughout this manual and
  48. contains a basic :ref:`introduction to using Clang <basicusage>` as a
  49. command line compiler.
  50. .. _terminology:
  51. Terminology
  52. -----------
  53. Front end, parser, backend, preprocessor, undefined behavior,
  54. diagnostic, optimizer
  55. .. _basicusage:
  56. Basic Usage
  57. -----------
  58. Intro to how to use a C compiler for newbies.
  59. compile + link compile then link debug info enabling optimizations
  60. picking a language to use, defaults to C99 by default. Autosenses based
  61. on extension. using a makefile
  62. Command Line Options
  63. ====================
  64. This section is generally an index into other sections. It does not go
  65. into depth on the ones that are covered by other sections. However, the
  66. first part introduces the language selection and other high level
  67. options like :option:`-c`, :option:`-g`, etc.
  68. Options to Control Error and Warning Messages
  69. ---------------------------------------------
  70. .. option:: -Werror
  71. Turn warnings into errors.
  72. .. This is in plain monospaced font because it generates the same label as
  73. .. -Werror, and Sphinx complains.
  74. ``-Werror=foo``
  75. Turn warning "foo" into an error.
  76. .. option:: -Wno-error=foo
  77. Turn warning "foo" into an warning even if :option:`-Werror` is specified.
  78. .. option:: -Wfoo
  79. Enable warning "foo".
  80. .. option:: -Wno-foo
  81. Disable warning "foo".
  82. .. option:: -w
  83. Disable all diagnostics.
  84. .. option:: -Weverything
  85. :ref:`Enable all diagnostics. <diagnostics_enable_everything>`
  86. .. option:: -pedantic
  87. Warn on language extensions.
  88. .. option:: -pedantic-errors
  89. Error on language extensions.
  90. .. option:: -Wsystem-headers
  91. Enable warnings from system headers.
  92. .. option:: -ferror-limit=123
  93. Stop emitting diagnostics after 123 errors have been produced. The default is
  94. 20, and the error limit can be disabled with :option:`-ferror-limit=0`.
  95. .. option:: -ftemplate-backtrace-limit=123
  96. Only emit up to 123 template instantiation notes within the template
  97. instantiation backtrace for a single warning or error. The default is 10, and
  98. the limit can be disabled with :option:`-ftemplate-backtrace-limit=0`.
  99. .. _cl_diag_formatting:
  100. Formatting of Diagnostics
  101. ^^^^^^^^^^^^^^^^^^^^^^^^^
  102. Clang aims to produce beautiful diagnostics by default, particularly for
  103. new users that first come to Clang. However, different people have
  104. different preferences, and sometimes Clang is driven by another program
  105. that wants to parse simple and consistent output, not a person. For
  106. these cases, Clang provides a wide range of options to control the exact
  107. output format of the diagnostics that it generates.
  108. .. _opt_fshow-column:
  109. **-f[no-]show-column**
  110. Print column number in diagnostic.
  111. This option, which defaults to on, controls whether or not Clang
  112. prints the column number of a diagnostic. For example, when this is
  113. enabled, Clang will print something like:
  114. ::
  115. test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
  116. #endif bad
  117. ^
  118. //
  119. When this is disabled, Clang will print "test.c:28: warning..." with
  120. no column number.
  121. The printed column numbers count bytes from the beginning of the
  122. line; take care if your source contains multibyte characters.
  123. .. _opt_fshow-source-location:
  124. **-f[no-]show-source-location**
  125. Print source file/line/column information in diagnostic.
  126. This option, which defaults to on, controls whether or not Clang
  127. prints the filename, line number and column number of a diagnostic.
  128. For example, when this is enabled, Clang will print something like:
  129. ::
  130. test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
  131. #endif bad
  132. ^
  133. //
  134. When this is disabled, Clang will not print the "test.c:28:8: "
  135. part.
  136. .. _opt_fcaret-diagnostics:
  137. **-f[no-]caret-diagnostics**
  138. Print source line and ranges from source code in diagnostic.
  139. This option, which defaults to on, controls whether or not Clang
  140. prints the source line, source ranges, and caret when emitting a
  141. diagnostic. For example, when this is enabled, Clang will print
  142. something like:
  143. ::
  144. test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
  145. #endif bad
  146. ^
  147. //
  148. **-f[no-]color-diagnostics**
  149. This option, which defaults to on when a color-capable terminal is
  150. detected, controls whether or not Clang prints diagnostics in color.
  151. When this option is enabled, Clang will use colors to highlight
  152. specific parts of the diagnostic, e.g.,
  153. .. nasty hack to not lose our dignity
  154. .. raw:: html
  155. <pre>
  156. <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>
  157. #endif bad
  158. <span style="color:green">^</span>
  159. <span style="color:green">//</span>
  160. </pre>
  161. When this is disabled, Clang will just print:
  162. ::
  163. test.c:2:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
  164. #endif bad
  165. ^
  166. //
  167. **-fansi-escape-codes**
  168. Controls whether ANSI escape codes are used instead of the Windows Console
  169. API to output colored diagnostics. This option is only used on Windows and
  170. defaults to off.
  171. .. option:: -fdiagnostics-format=clang/msvc/vi
  172. Changes diagnostic output format to better match IDEs and command line tools.
  173. This option controls the output format of the filename, line number,
  174. and column printed in diagnostic messages. The options, and their
  175. affect on formatting a simple conversion diagnostic, follow:
  176. **clang** (default)
  177. ::
  178. t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int'
  179. **msvc**
  180. ::
  181. t.c(3,11) : warning: conversion specifies type 'char *' but the argument has type 'int'
  182. **vi**
  183. ::
  184. t.c +3:11: warning: conversion specifies type 'char *' but the argument has type 'int'
  185. .. _opt_fdiagnostics-show-option:
  186. **-f[no-]diagnostics-show-option**
  187. Enable ``[-Woption]`` information in diagnostic line.
  188. This option, which defaults to on, controls whether or not Clang
  189. prints the associated :ref:`warning group <cl_diag_warning_groups>`
  190. option name when outputting a warning diagnostic. For example, in
  191. this output:
  192. ::
  193. test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
  194. #endif bad
  195. ^
  196. //
  197. Passing **-fno-diagnostics-show-option** will prevent Clang from
  198. printing the [:ref:`-Wextra-tokens <opt_Wextra-tokens>`] information in
  199. the diagnostic. This information tells you the flag needed to enable
  200. or disable the diagnostic, either from the command line or through
  201. :ref:`#pragma GCC diagnostic <pragma_GCC_diagnostic>`.
  202. .. _opt_fdiagnostics-show-category:
  203. .. option:: -fdiagnostics-show-category=none/id/name
  204. Enable printing category information in diagnostic line.
  205. This option, which defaults to "none", controls whether or not Clang
  206. prints the category associated with a diagnostic when emitting it.
  207. Each diagnostic may or many not have an associated category, if it
  208. has one, it is listed in the diagnostic categorization field of the
  209. diagnostic line (in the []'s).
  210. For example, a format string warning will produce these three
  211. renditions based on the setting of this option:
  212. ::
  213. t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat]
  214. t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat,1]
  215. t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat,Format String]
  216. This category can be used by clients that want to group diagnostics
  217. by category, so it should be a high level category. We want dozens
  218. of these, not hundreds or thousands of them.
  219. .. _opt_fdiagnostics-fixit-info:
  220. **-f[no-]diagnostics-fixit-info**
  221. Enable "FixIt" information in the diagnostics output.
  222. This option, which defaults to on, controls whether or not Clang
  223. prints the information on how to fix a specific diagnostic
  224. underneath it when it knows. For example, in this output:
  225. ::
  226. test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
  227. #endif bad
  228. ^
  229. //
  230. Passing **-fno-diagnostics-fixit-info** will prevent Clang from
  231. printing the "//" line at the end of the message. This information
  232. is useful for users who may not understand what is wrong, but can be
  233. confusing for machine parsing.
  234. .. _opt_fdiagnostics-print-source-range-info:
  235. **-fdiagnostics-print-source-range-info**
  236. Print machine parsable information about source ranges.
  237. This option makes Clang print information about source ranges in a machine
  238. parsable format after the file/line/column number information. The
  239. information is a simple sequence of brace enclosed ranges, where each range
  240. lists the start and end line/column locations. For example, in this output:
  241. ::
  242. exprs.c:47:15:{47:8-47:14}{47:17-47:24}: error: invalid operands to binary expression ('int *' and '_Complex float')
  243. P = (P-42) + Gamma*4;
  244. ~~~~~~ ^ ~~~~~~~
  245. The {}'s are generated by -fdiagnostics-print-source-range-info.
  246. The printed column numbers count bytes from the beginning of the
  247. line; take care if your source contains multibyte characters.
  248. .. option:: -fdiagnostics-parseable-fixits
  249. Print Fix-Its in a machine parseable form.
  250. This option makes Clang print available Fix-Its in a machine
  251. parseable format at the end of diagnostics. The following example
  252. illustrates the format:
  253. ::
  254. fix-it:"t.cpp":{7:25-7:29}:"Gamma"
  255. The range printed is a half-open range, so in this example the
  256. characters at column 25 up to but not including column 29 on line 7
  257. in t.cpp should be replaced with the string "Gamma". Either the
  258. range or the replacement string may be empty (representing strict
  259. insertions and strict erasures, respectively). Both the file name
  260. and the insertion string escape backslash (as "\\\\"), tabs (as
  261. "\\t"), newlines (as "\\n"), double quotes(as "\\"") and
  262. non-printable characters (as octal "\\xxx").
  263. The printed column numbers count bytes from the beginning of the
  264. line; take care if your source contains multibyte characters.
  265. .. option:: -fno-elide-type
  266. Turns off elision in template type printing.
  267. The default for template type printing is to elide as many template
  268. arguments as possible, removing those which are the same in both
  269. template types, leaving only the differences. Adding this flag will
  270. print all the template arguments. If supported by the terminal,
  271. highlighting will still appear on differing arguments.
  272. Default:
  273. ::
  274. 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;
  275. -fno-elide-type:
  276. ::
  277. 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;
  278. .. option:: -fdiagnostics-show-template-tree
  279. Template type diffing prints a text tree.
  280. For diffing large templated types, this option will cause Clang to
  281. display the templates as an indented text tree, one argument per
  282. line, with differences marked inline. This is compatible with
  283. -fno-elide-type.
  284. Default:
  285. ::
  286. 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;
  287. With :option:`-fdiagnostics-show-template-tree`:
  288. ::
  289. t.cc:4:5: note: candidate function not viable: no known conversion for 1st argument;
  290. vector<
  291. map<
  292. [...],
  293. map<
  294. [float != double],
  295. [...]>>>
  296. .. _cl_diag_warning_groups:
  297. Individual Warning Groups
  298. ^^^^^^^^^^^^^^^^^^^^^^^^^
  299. TODO: Generate this from tblgen. Define one anchor per warning group.
  300. .. _opt_wextra-tokens:
  301. .. option:: -Wextra-tokens
  302. Warn about excess tokens at the end of a preprocessor directive.
  303. This option, which defaults to on, enables warnings about extra
  304. tokens at the end of preprocessor directives. For example:
  305. ::
  306. test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
  307. #endif bad
  308. ^
  309. These extra tokens are not strictly conforming, and are usually best
  310. handled by commenting them out.
  311. .. option:: -Wambiguous-member-template
  312. Warn about unqualified uses of a member template whose name resolves to
  313. another template at the location of the use.
  314. This option, which defaults to on, enables a warning in the
  315. following code:
  316. ::
  317. template<typename T> struct set{};
  318. template<typename T> struct trait { typedef const T& type; };
  319. struct Value {
  320. template<typename T> void set(typename trait<T>::type value) {}
  321. };
  322. void foo() {
  323. Value v;
  324. v.set<double>(3.2);
  325. }
  326. C++ [basic.lookup.classref] requires this to be an error, but,
  327. because it's hard to work around, Clang downgrades it to a warning
  328. as an extension.
  329. .. option:: -Wbind-to-temporary-copy
  330. Warn about an unusable copy constructor when binding a reference to a
  331. temporary.
  332. This option, which defaults to on, enables warnings about binding a
  333. reference to a temporary when the temporary doesn't have a usable
  334. copy constructor. For example:
  335. ::
  336. struct NonCopyable {
  337. NonCopyable();
  338. private:
  339. NonCopyable(const NonCopyable&);
  340. };
  341. void foo(const NonCopyable&);
  342. void bar() {
  343. foo(NonCopyable()); // Disallowed in C++98; allowed in C++11.
  344. }
  345. ::
  346. struct NonCopyable2 {
  347. NonCopyable2();
  348. NonCopyable2(NonCopyable2&);
  349. };
  350. void foo(const NonCopyable2&);
  351. void bar() {
  352. foo(NonCopyable2()); // Disallowed in C++98; allowed in C++11.
  353. }
  354. Note that if ``NonCopyable2::NonCopyable2()`` has a default argument
  355. whose instantiation produces a compile error, that error will still
  356. be a hard error in C++98 mode even if this warning is turned off.
  357. Options to Control Clang Crash Diagnostics
  358. ------------------------------------------
  359. As unbelievable as it may sound, Clang does crash from time to time.
  360. Generally, this only occurs to those living on the `bleeding
  361. edge <http://llvm.org/releases/download.html#svn>`_. Clang goes to great
  362. lengths to assist you in filing a bug report. Specifically, Clang
  363. generates preprocessed source file(s) and associated run script(s) upon
  364. a crash. These files should be attached to a bug report to ease
  365. reproducibility of the failure. Below are the command line options to
  366. control the crash diagnostics.
  367. .. option:: -fno-crash-diagnostics
  368. Disable auto-generation of preprocessed source files during a clang crash.
  369. The -fno-crash-diagnostics flag can be helpful for speeding the process
  370. of generating a delta reduced test case.
  371. Options to Emit Optimization Reports
  372. ------------------------------------
  373. Optimization reports trace, at a high-level, all the major decisions
  374. done by compiler transformations. For instance, when the inliner
  375. decides to inline function ``foo()`` into ``bar()``, or the loop unroller
  376. decides to unroll a loop N times, or the vectorizer decides to
  377. vectorize a loop body.
  378. Clang offers a family of flags which the optimizers can use to emit
  379. a diagnostic in three cases:
  380. 1. When the pass makes a transformation (:option:`-Rpass`).
  381. 2. When the pass fails to make a transformation (:option:`-Rpass-missed`).
  382. 3. When the pass determines whether or not to make a transformation
  383. (:option:`-Rpass-analysis`).
  384. NOTE: Although the discussion below focuses on :option:`-Rpass`, the exact
  385. same options apply to :option:`-Rpass-missed` and :option:`-Rpass-analysis`.
  386. Since there are dozens of passes inside the compiler, each of these flags
  387. take a regular expression that identifies the name of the pass which should
  388. emit the associated diagnostic. For example, to get a report from the inliner,
  389. compile the code with:
  390. .. code-block:: console
  391. $ clang -O2 -Rpass=inline code.cc -o code
  392. code.cc:4:25: remark: foo inlined into bar [-Rpass=inline]
  393. int bar(int j) { return foo(j, j - 2); }
  394. ^
  395. Note that remarks from the inliner are identified with `[-Rpass=inline]`.
  396. To request a report from every optimization pass, you should use
  397. :option:`-Rpass=.*` (in fact, you can use any valid POSIX regular
  398. expression). However, do not expect a report from every transformation
  399. made by the compiler. Optimization remarks do not really make sense
  400. outside of the major transformations (e.g., inlining, vectorization,
  401. loop optimizations) and not every optimization pass supports this
  402. feature.
  403. Current limitations
  404. ^^^^^^^^^^^^^^^^^^^
  405. 1. Optimization remarks that refer to function names will display the
  406. mangled name of the function. Since these remarks are emitted by the
  407. back end of the compiler, it does not know anything about the input
  408. language, nor its mangling rules.
  409. 2. Some source locations are not displayed correctly. The front end has
  410. a more detailed source location tracking than the locations included
  411. in the debug info (e.g., the front end can locate code inside macro
  412. expansions). However, the locations used by :option:`-Rpass` are
  413. translated from debug annotations. That translation can be lossy,
  414. which results in some remarks having no location information.
  415. Language and Target-Independent Features
  416. ========================================
  417. Controlling Errors and Warnings
  418. -------------------------------
  419. Clang provides a number of ways to control which code constructs cause
  420. it to emit errors and warning messages, and how they are displayed to
  421. the console.
  422. Controlling How Clang Displays Diagnostics
  423. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  424. When Clang emits a diagnostic, it includes rich information in the
  425. output, and gives you fine-grain control over which information is
  426. printed. Clang has the ability to print this information, and these are
  427. the options that control it:
  428. #. A file/line/column indicator that shows exactly where the diagnostic
  429. occurs in your code [:ref:`-fshow-column <opt_fshow-column>`,
  430. :ref:`-fshow-source-location <opt_fshow-source-location>`].
  431. #. A categorization of the diagnostic as a note, warning, error, or
  432. fatal error.
  433. #. A text string that describes what the problem is.
  434. #. An option that indicates how to control the diagnostic (for
  435. diagnostics that support it)
  436. [:ref:`-fdiagnostics-show-option <opt_fdiagnostics-show-option>`].
  437. #. A :ref:`high-level category <diagnostics_categories>` for the diagnostic
  438. for clients that want to group diagnostics by class (for diagnostics
  439. that support it)
  440. [:ref:`-fdiagnostics-show-category <opt_fdiagnostics-show-category>`].
  441. #. The line of source code that the issue occurs on, along with a caret
  442. and ranges that indicate the important locations
  443. [:ref:`-fcaret-diagnostics <opt_fcaret-diagnostics>`].
  444. #. "FixIt" information, which is a concise explanation of how to fix the
  445. problem (when Clang is certain it knows)
  446. [:ref:`-fdiagnostics-fixit-info <opt_fdiagnostics-fixit-info>`].
  447. #. A machine-parsable representation of the ranges involved (off by
  448. default)
  449. [:ref:`-fdiagnostics-print-source-range-info <opt_fdiagnostics-print-source-range-info>`].
  450. For more information please see :ref:`Formatting of
  451. Diagnostics <cl_diag_formatting>`.
  452. Diagnostic Mappings
  453. ^^^^^^^^^^^^^^^^^^^
  454. All diagnostics are mapped into one of these 5 classes:
  455. - Ignored
  456. - Note
  457. - Remark
  458. - Warning
  459. - Error
  460. - Fatal
  461. .. _diagnostics_categories:
  462. Diagnostic Categories
  463. ^^^^^^^^^^^^^^^^^^^^^
  464. Though not shown by default, diagnostics may each be associated with a
  465. high-level category. This category is intended to make it possible to
  466. triage builds that produce a large number of errors or warnings in a
  467. grouped way.
  468. Categories are not shown by default, but they can be turned on with the
  469. :ref:`-fdiagnostics-show-category <opt_fdiagnostics-show-category>` option.
  470. When set to "``name``", the category is printed textually in the
  471. diagnostic output. When it is set to "``id``", a category number is
  472. printed. The mapping of category names to category id's can be obtained
  473. by running '``clang --print-diagnostic-categories``'.
  474. Controlling Diagnostics via Command Line Flags
  475. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  476. TODO: -W flags, -pedantic, etc
  477. .. _pragma_gcc_diagnostic:
  478. Controlling Diagnostics via Pragmas
  479. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  480. Clang can also control what diagnostics are enabled through the use of
  481. pragmas in the source code. This is useful for turning off specific
  482. warnings in a section of source code. Clang supports GCC's pragma for
  483. compatibility with existing source code, as well as several extensions.
  484. The pragma may control any warning that can be used from the command
  485. line. Warnings may be set to ignored, warning, error, or fatal. The
  486. following example code will tell Clang or GCC to ignore the -Wall
  487. warnings:
  488. .. code-block:: c
  489. #pragma GCC diagnostic ignored "-Wall"
  490. In addition to all of the functionality provided by GCC's pragma, Clang
  491. also allows you to push and pop the current warning state. This is
  492. particularly useful when writing a header file that will be compiled by
  493. other people, because you don't know what warning flags they build with.
  494. In the below example :option:`-Wmultichar` is ignored for only a single line of
  495. code, after which the diagnostics return to whatever state had previously
  496. existed.
  497. .. code-block:: c
  498. #pragma clang diagnostic push
  499. #pragma clang diagnostic ignored "-Wmultichar"
  500. char b = 'df'; // no warning.
  501. #pragma clang diagnostic pop
  502. The push and pop pragmas will save and restore the full diagnostic state
  503. of the compiler, regardless of how it was set. That means that it is
  504. possible to use push and pop around GCC compatible diagnostics and Clang
  505. will push and pop them appropriately, while GCC will ignore the pushes
  506. and pops as unknown pragmas. It should be noted that while Clang
  507. supports the GCC pragma, Clang and GCC do not support the exact same set
  508. of warnings, so even when using GCC compatible #pragmas there is no
  509. guarantee that they will have identical behaviour on both compilers.
  510. In addition to controlling warnings and errors generated by the compiler, it is
  511. possible to generate custom warning and error messages through the following
  512. pragmas:
  513. .. code-block:: c
  514. // The following will produce warning messages
  515. #pragma message "some diagnostic message"
  516. #pragma GCC warning "TODO: replace deprecated feature"
  517. // The following will produce an error message
  518. #pragma GCC error "Not supported"
  519. These pragmas operate similarly to the ``#warning`` and ``#error`` preprocessor
  520. directives, except that they may also be embedded into preprocessor macros via
  521. the C99 ``_Pragma`` operator, for example:
  522. .. code-block:: c
  523. #define STR(X) #X
  524. #define DEFER(M,...) M(__VA_ARGS__)
  525. #define CUSTOM_ERROR(X) _Pragma(STR(GCC error(X " at line " DEFER(STR,__LINE__))))
  526. CUSTOM_ERROR("Feature not available");
  527. Controlling Diagnostics in System Headers
  528. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  529. Warnings are suppressed when they occur in system headers. By default,
  530. an included file is treated as a system header if it is found in an
  531. include path specified by ``-isystem``, but this can be overridden in
  532. several ways.
  533. The ``system_header`` pragma can be used to mark the current file as
  534. being a system header. No warnings will be produced from the location of
  535. the pragma onwards within the same file.
  536. .. code-block:: c
  537. char a = 'xy'; // warning
  538. #pragma clang system_header
  539. char b = 'ab'; // no warning
  540. The :option:`--system-header-prefix=` and :option:`--no-system-header-prefix=`
  541. command-line arguments can be used to override whether subsets of an include
  542. path are treated as system headers. When the name in a ``#include`` directive
  543. is found within a header search path and starts with a system prefix, the
  544. header is treated as a system header. The last prefix on the
  545. command-line which matches the specified header name takes precedence.
  546. For instance:
  547. .. code-block:: console
  548. $ clang -Ifoo -isystem bar --system-header-prefix=x/ \
  549. --no-system-header-prefix=x/y/
  550. Here, ``#include "x/a.h"`` is treated as including a system header, even
  551. if the header is found in ``foo``, and ``#include "x/y/b.h"`` is treated
  552. as not including a system header, even if the header is found in
  553. ``bar``.
  554. A ``#include`` directive which finds a file relative to the current
  555. directory is treated as including a system header if the including file
  556. is treated as a system header.
  557. .. _diagnostics_enable_everything:
  558. Enabling All Diagnostics
  559. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  560. In addition to the traditional ``-W`` flags, one can enable **all**
  561. diagnostics by passing :option:`-Weverything`. This works as expected
  562. with
  563. :option:`-Werror`, and also includes the warnings from :option:`-pedantic`.
  564. Note that when combined with :option:`-w` (which disables all warnings), that
  565. flag wins.
  566. Controlling Static Analyzer Diagnostics
  567. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  568. While not strictly part of the compiler, the diagnostics from Clang's
  569. `static analyzer <http://clang-analyzer.llvm.org>`_ can also be
  570. influenced by the user via changes to the source code. See the available
  571. `annotations <http://clang-analyzer.llvm.org/annotations.html>`_ and the
  572. analyzer's `FAQ
  573. page <http://clang-analyzer.llvm.org/faq.html#exclude_code>`_ for more
  574. information.
  575. .. _usersmanual-precompiled-headers:
  576. Precompiled Headers
  577. -------------------
  578. `Precompiled headers <http://en.wikipedia.org/wiki/Precompiled_header>`__
  579. are a general approach employed by many compilers to reduce compilation
  580. time. The underlying motivation of the approach is that it is common for
  581. the same (and often large) header files to be included by multiple
  582. source files. Consequently, compile times can often be greatly improved
  583. by caching some of the (redundant) work done by a compiler to process
  584. headers. Precompiled header files, which represent one of many ways to
  585. implement this optimization, are literally files that represent an
  586. on-disk cache that contains the vital information necessary to reduce
  587. some of the work needed to process a corresponding header file. While
  588. details of precompiled headers vary between compilers, precompiled
  589. headers have been shown to be highly effective at speeding up program
  590. compilation on systems with very large system headers (e.g., Mac OS X).
  591. Generating a PCH File
  592. ^^^^^^^^^^^^^^^^^^^^^
  593. To generate a PCH file using Clang, one invokes Clang with the
  594. :option:`-x <language>-header` option. This mirrors the interface in GCC
  595. for generating PCH files:
  596. .. code-block:: console
  597. $ gcc -x c-header test.h -o test.h.gch
  598. $ clang -x c-header test.h -o test.h.pch
  599. Using a PCH File
  600. ^^^^^^^^^^^^^^^^
  601. A PCH file can then be used as a prefix header when a :option:`-include`
  602. option is passed to ``clang``:
  603. .. code-block:: console
  604. $ clang -include test.h test.c -o test
  605. The ``clang`` driver will first check if a PCH file for ``test.h`` is
  606. available; if so, the contents of ``test.h`` (and the files it includes)
  607. will be processed from the PCH file. Otherwise, Clang falls back to
  608. directly processing the content of ``test.h``. This mirrors the behavior
  609. of GCC.
  610. .. note::
  611. Clang does *not* automatically use PCH files for headers that are directly
  612. included within a source file. For example:
  613. .. code-block:: console
  614. $ clang -x c-header test.h -o test.h.pch
  615. $ cat test.c
  616. #include "test.h"
  617. $ clang test.c -o test
  618. In this example, ``clang`` will not automatically use the PCH file for
  619. ``test.h`` since ``test.h`` was included directly in the source file and not
  620. specified on the command line using :option:`-include`.
  621. Relocatable PCH Files
  622. ^^^^^^^^^^^^^^^^^^^^^
  623. It is sometimes necessary to build a precompiled header from headers
  624. that are not yet in their final, installed locations. For example, one
  625. might build a precompiled header within the build tree that is then
  626. meant to be installed alongside the headers. Clang permits the creation
  627. of "relocatable" precompiled headers, which are built with a given path
  628. (into the build directory) and can later be used from an installed
  629. location.
  630. To build a relocatable precompiled header, place your headers into a
  631. subdirectory whose structure mimics the installed location. For example,
  632. if you want to build a precompiled header for the header ``mylib.h``
  633. that will be installed into ``/usr/include``, create a subdirectory
  634. ``build/usr/include`` and place the header ``mylib.h`` into that
  635. subdirectory. If ``mylib.h`` depends on other headers, then they can be
  636. stored within ``build/usr/include`` in a way that mimics the installed
  637. location.
  638. Building a relocatable precompiled header requires two additional
  639. arguments. First, pass the ``--relocatable-pch`` flag to indicate that
  640. the resulting PCH file should be relocatable. Second, pass
  641. :option:`-isysroot /path/to/build`, which makes all includes for your library
  642. relative to the build directory. For example:
  643. .. code-block:: console
  644. # clang -x c-header --relocatable-pch -isysroot /path/to/build /path/to/build/mylib.h mylib.h.pch
  645. When loading the relocatable PCH file, the various headers used in the
  646. PCH file are found from the system header root. For example, ``mylib.h``
  647. can be found in ``/usr/include/mylib.h``. If the headers are installed
  648. in some other system root, the :option:`-isysroot` option can be used provide
  649. a different system root from which the headers will be based. For
  650. example, :option:`-isysroot /Developer/SDKs/MacOSX10.4u.sdk` will look for
  651. ``mylib.h`` in ``/Developer/SDKs/MacOSX10.4u.sdk/usr/include/mylib.h``.
  652. Relocatable precompiled headers are intended to be used in a limited
  653. number of cases where the compilation environment is tightly controlled
  654. and the precompiled header cannot be generated after headers have been
  655. installed.
  656. Controlling Code Generation
  657. ---------------------------
  658. Clang provides a number of ways to control code generation. The options
  659. are listed below.
  660. **-f[no-]sanitize=check1,check2,...**
  661. Turn on runtime checks for various forms of undefined or suspicious
  662. behavior.
  663. This option controls whether Clang adds runtime checks for various
  664. forms of undefined or suspicious behavior, and is disabled by
  665. default. If a check fails, a diagnostic message is produced at
  666. runtime explaining the problem. The main checks are:
  667. - .. _opt_fsanitize_address:
  668. ``-fsanitize=address``:
  669. :doc:`AddressSanitizer`, a memory error
  670. detector.
  671. - ``-fsanitize=integer``: Enables checks for undefined or
  672. suspicious integer behavior.
  673. - .. _opt_fsanitize_thread:
  674. ``-fsanitize=thread``: :doc:`ThreadSanitizer`, a data race detector.
  675. - .. _opt_fsanitize_memory:
  676. ``-fsanitize=memory``: :doc:`MemorySanitizer`,
  677. an *experimental* detector of uninitialized reads. Not ready for
  678. widespread use.
  679. - .. _opt_fsanitize_undefined:
  680. ``-fsanitize=undefined``: Fast and compatible undefined behavior
  681. checker. Enables the undefined behavior checks that have small
  682. runtime cost and no impact on address space layout or ABI. This
  683. includes all of the checks listed below other than
  684. ``unsigned-integer-overflow``.
  685. - ``-fsanitize=undefined-trap``: This includes all sanitizers
  686. included by ``-fsanitize=undefined``, except those that require
  687. runtime support. This group of sanitizers is intended to be
  688. used in conjunction with the ``-fsanitize-undefined-trap-on-error``
  689. flag. This includes all of the checks listed below other than
  690. ``unsigned-integer-overflow`` and ``vptr``.
  691. - ``-fsanitize=dataflow``: :doc:`DataFlowSanitizer`, a general data
  692. flow analysis.
  693. The following more fine-grained checks are also available:
  694. - ``-fsanitize=alignment``: Use of a misaligned pointer or creation
  695. of a misaligned reference.
  696. - ``-fsanitize=bool``: Load of a ``bool`` value which is neither
  697. ``true`` nor ``false``.
  698. - ``-fsanitize=bounds``: Out of bounds array indexing, in cases
  699. where the array bound can be statically determined.
  700. - ``-fsanitize=enum``: Load of a value of an enumerated type which
  701. is not in the range of representable values for that enumerated
  702. type.
  703. - ``-fsanitize=float-cast-overflow``: Conversion to, from, or
  704. between floating-point types which would overflow the
  705. destination.
  706. - ``-fsanitize=float-divide-by-zero``: Floating point division by
  707. zero.
  708. - ``-fsanitize=function``: Indirect call of a function through a
  709. function pointer of the wrong type (Linux, C++ and x86/x86_64 only).
  710. - ``-fsanitize=integer-divide-by-zero``: Integer division by zero.
  711. - ``-fsanitize=null``: Use of a null pointer or creation of a null
  712. reference.
  713. - ``-fsanitize=object-size``: An attempt to use bytes which the
  714. optimizer can determine are not part of the object being
  715. accessed. The sizes of objects are determined using
  716. ``__builtin_object_size``, and consequently may be able to detect
  717. more problems at higher optimization levels.
  718. - ``-fsanitize=return``: In C++, reaching the end of a
  719. value-returning function without returning a value.
  720. - ``-fsanitize=shift``: Shift operators where the amount shifted is
  721. greater or equal to the promoted bit-width of the left hand side
  722. or less than zero, or where the left hand side is negative. For a
  723. signed left shift, also checks for signed overflow in C, and for
  724. unsigned overflow in C++.
  725. - ``-fsanitize=signed-integer-overflow``: Signed integer overflow,
  726. including all the checks added by ``-ftrapv``, and checking for
  727. overflow in signed division (``INT_MIN / -1``).
  728. - ``-fsanitize=unreachable``: If control flow reaches
  729. ``__builtin_unreachable``.
  730. - ``-fsanitize=unsigned-integer-overflow``: Unsigned integer
  731. overflows.
  732. - ``-fsanitize=vla-bound``: A variable-length array whose bound
  733. does not evaluate to a positive value.
  734. - ``-fsanitize=vptr``: Use of an object whose vptr indicates that
  735. it is of the wrong dynamic type, or that its lifetime has not
  736. begun or has ended. Incompatible with ``-fno-rtti``.
  737. You can turn off or modify checks for certain source files, functions
  738. or even variables by providing a special file:
  739. - ``-fsanitize-blacklist=/path/to/blacklist/file``: disable or modify
  740. sanitizer checks for objects listed in the file. See
  741. :doc:`SanitizerSpecialCaseList` for file format description.
  742. - ``-fno-sanitize-blacklist``: don't use blacklist file, if it was
  743. specified earlier in the command line.
  744. Extra features of MemorySanitizer (require explicit
  745. ``-fsanitize=memory``):
  746. - ``-fsanitize-memory-track-origins[=level]``: Enables origin tracking in
  747. MemorySanitizer. Adds a second section to MemorySanitizer
  748. reports pointing to the heap or stack allocation the
  749. uninitialized bits came from. Slows down execution by additional
  750. 1.5x-2x.
  751. Possible values for level are 0 (off), 1 (default), 2. Level 2 adds more
  752. sections to MemorySanitizer reports describing the order of memory stores
  753. the uninitialized value went through. Beware, this mode may use a lot of
  754. extra memory.
  755. Extra features of UndefinedBehaviorSanitizer:
  756. - ``-fno-sanitize-recover``: By default, after a sanitizer diagnoses
  757. an issue, it will attempt to continue executing the program if there
  758. is a reasonable behavior it can give to the faulting operation. This
  759. option causes the program to abort instead.
  760. - ``-fsanitize-undefined-trap-on-error``: Causes traps to be emitted
  761. rather than calls to runtime libraries when a problem is detected.
  762. This option is intended for use in cases where the sanitizer runtime
  763. cannot be used (for instance, when building libc or a kernel module).
  764. This is only compatible with the sanitizers in the ``undefined-trap``
  765. group.
  766. The ``-fsanitize=`` argument must also be provided when linking, in
  767. order to link to the appropriate runtime library. When using
  768. ``-fsanitize=vptr`` (or a group that includes it, such as
  769. ``-fsanitize=undefined``) with a C++ program, the link must be
  770. performed by ``clang++``, not ``clang``, in order to link against the
  771. C++-specific parts of the runtime library.
  772. It is not possible to combine more than one of the ``-fsanitize=address``,
  773. ``-fsanitize=thread``, and ``-fsanitize=memory`` checkers in the same
  774. program. The ``-fsanitize=undefined`` checks can be combined with other
  775. sanitizers.
  776. .. option:: -fno-assume-sane-operator-new
  777. Don't assume that the C++'s new operator is sane.
  778. This option tells the compiler to do not assume that C++'s global
  779. new operator will always return a pointer that does not alias any
  780. other pointer when the function returns.
  781. .. option:: -ftrap-function=[name]
  782. Instruct code generator to emit a function call to the specified
  783. function name for ``__builtin_trap()``.
  784. LLVM code generator translates ``__builtin_trap()`` to a trap
  785. instruction if it is supported by the target ISA. Otherwise, the
  786. builtin is translated into a call to ``abort``. If this option is
  787. set, then the code generator will always lower the builtin to a call
  788. to the specified function regardless of whether the target ISA has a
  789. trap instruction. This option is useful for environments (e.g.
  790. deeply embedded) where a trap cannot be properly handled, or when
  791. some custom behavior is desired.
  792. .. option:: -ftls-model=[model]
  793. Select which TLS model to use.
  794. Valid values are: ``global-dynamic``, ``local-dynamic``,
  795. ``initial-exec`` and ``local-exec``. The default value is
  796. ``global-dynamic``. The compiler may use a different model if the
  797. selected model is not supported by the target, or if a more
  798. efficient model can be used. The TLS model can be overridden per
  799. variable using the ``tls_model`` attribute.
  800. .. option:: -mhwdiv=[values]
  801. Select the ARM modes (arm or thumb) that support hardware division
  802. instructions.
  803. Valid values are: ``arm``, ``thumb`` and ``arm,thumb``.
  804. This option is used to indicate which mode (arm or thumb) supports
  805. hardware division instructions. This only applies to the ARM
  806. architecture.
  807. .. option:: -m[no-]crc
  808. Enable or disable CRC instructions.
  809. This option is used to indicate whether CRC instructions are to
  810. be generated. This only applies to the ARM architecture.
  811. CRC instructions are enabled by default on ARMv8.
  812. .. option:: -mgeneral-regs-only
  813. Generate code which only uses the general purpose registers.
  814. This option restricts the generated code to use general registers
  815. only. This only applies to the AArch64 architecture.
  816. Profile Guided Optimization
  817. ---------------------------
  818. Profile information enables better optimization. For example, knowing that a
  819. branch is taken very frequently helps the compiler make better decisions when
  820. ordering basic blocks. Knowing that a function ``foo`` is called more
  821. frequently than another function ``bar`` helps the inliner.
  822. Clang supports profile guided optimization with two different kinds of
  823. profiling. A sampling profiler can generate a profile with very low runtime
  824. overhead, or you can build an instrumented version of the code that collects
  825. more detailed profile information. Both kinds of profiles can provide execution
  826. counts for instructions in the code and information on branches taken and
  827. function invocation.
  828. Regardless of which kind of profiling you use, be careful to collect profiles
  829. by running your code with inputs that are representative of the typical
  830. behavior. Code that is not exercised in the profile will be optimized as if it
  831. is unimportant, and the compiler may make poor optimization choices for code
  832. that is disproportionately used while profiling.
  833. Using Sampling Profilers
  834. ^^^^^^^^^^^^^^^^^^^^^^^^
  835. Sampling profilers are used to collect runtime information, such as
  836. hardware counters, while your application executes. They are typically
  837. very efficient and do not incur a large runtime overhead. The
  838. sample data collected by the profiler can be used during compilation
  839. to determine what the most executed areas of the code are.
  840. Using the data from a sample profiler requires some changes in the way
  841. a program is built. Before the compiler can use profiling information,
  842. the code needs to execute under the profiler. The following is the
  843. usual build cycle when using sample profilers for optimization:
  844. 1. Build the code with source line table information. You can use all the
  845. usual build flags that you always build your application with. The only
  846. requirement is that you add ``-gline-tables-only`` or ``-g`` to the
  847. command line. This is important for the profiler to be able to map
  848. instructions back to source line locations.
  849. .. code-block:: console
  850. $ clang++ -O2 -gline-tables-only code.cc -o code
  851. 2. Run the executable under a sampling profiler. The specific profiler
  852. you use does not really matter, as long as its output can be converted
  853. into the format that the LLVM optimizer understands. Currently, there
  854. exists a conversion tool for the Linux Perf profiler
  855. (https://perf.wiki.kernel.org/), so these examples assume that you
  856. are using Linux Perf to profile your code.
  857. .. code-block:: console
  858. $ perf record -b ./code
  859. Note the use of the ``-b`` flag. This tells Perf to use the Last Branch
  860. Record (LBR) to record call chains. While this is not strictly required,
  861. it provides better call information, which improves the accuracy of
  862. the profile data.
  863. 3. Convert the collected profile data to LLVM's sample profile format.
  864. This is currently supported via the AutoFDO converter ``create_llvm_prof``.
  865. It is available at http://github.com/google/autofdo. Once built and
  866. installed, you can convert the ``perf.data`` file to LLVM using
  867. the command:
  868. .. code-block:: console
  869. $ create_llvm_prof --binary=./code --out=code.prof
  870. This will read ``perf.data`` and the binary file ``./code`` and emit
  871. the profile data in ``code.prof``. Note that if you ran ``perf``
  872. without the ``-b`` flag, you need to use ``--use_lbr=false`` when
  873. calling ``create_llvm_prof``.
  874. 4. Build the code again using the collected profile. This step feeds
  875. the profile back to the optimizers. This should result in a binary
  876. that executes faster than the original one. Note that you are not
  877. required to build the code with the exact same arguments that you
  878. used in the first step. The only requirement is that you build the code
  879. with ``-gline-tables-only`` and ``-fprofile-sample-use``.
  880. .. code-block:: console
  881. $ clang++ -O2 -gline-tables-only -fprofile-sample-use=code.prof code.cc -o code
  882. Sample Profile Format
  883. """""""""""""""""""""
  884. If you are not using Linux Perf to collect profiles, you will need to
  885. write a conversion tool from your profiler to LLVM's format. This section
  886. explains the file format expected by the backend.
  887. Sample profiles are written as ASCII text. The file is divided into sections,
  888. which correspond to each of the functions executed at runtime. Each
  889. section has the following format (taken from
  890. https://github.com/google/autofdo/blob/master/profile_writer.h):
  891. .. code-block:: console
  892. function1:total_samples:total_head_samples
  893. offset1[.discriminator]: number_of_samples [fn1:num fn2:num ... ]
  894. offset2[.discriminator]: number_of_samples [fn3:num fn4:num ... ]
  895. ...
  896. offsetN[.discriminator]: number_of_samples [fn5:num fn6:num ... ]
  897. The file may contain blank lines between sections and within a
  898. section. However, the spacing within a single line is fixed. Additional
  899. spaces will result in an error while reading the file.
  900. Function names must be mangled in order for the profile loader to
  901. match them in the current translation unit. The two numbers in the
  902. function header specify how many total samples were accumulated in the
  903. function (first number), and the total number of samples accumulated
  904. in the prologue of the function (second number). This head sample
  905. count provides an indicator of how frequently the function is invoked.
  906. Each sampled line may contain several items. Some are optional (marked
  907. below):
  908. a. Source line offset. This number represents the line number
  909. in the function where the sample was collected. The line number is
  910. always relative to the line where symbol of the function is
  911. defined. So, if the function has its header at line 280, the offset
  912. 13 is at line 293 in the file.
  913. Note that this offset should never be a negative number. This could
  914. happen in cases like macros. The debug machinery will register the
  915. line number at the point of macro expansion. So, if the macro was
  916. expanded in a line before the start of the function, the profile
  917. converter should emit a 0 as the offset (this means that the optimizers
  918. will not be able to associate a meaningful weight to the instructions
  919. in the macro).
  920. b. [OPTIONAL] Discriminator. This is used if the sampled program
  921. was compiled with DWARF discriminator support
  922. (http://wiki.dwarfstd.org/index.php?title=Path_Discriminators).
  923. DWARF discriminators are unsigned integer values that allow the
  924. compiler to distinguish between multiple execution paths on the
  925. same source line location.
  926. For example, consider the line of code ``if (cond) foo(); else bar();``.
  927. If the predicate ``cond`` is true 80% of the time, then the edge
  928. into function ``foo`` should be considered to be taken most of the
  929. time. But both calls to ``foo`` and ``bar`` are at the same source
  930. line, so a sample count at that line is not sufficient. The
  931. compiler needs to know which part of that line is taken more
  932. frequently.
  933. This is what discriminators provide. In this case, the calls to
  934. ``foo`` and ``bar`` will be at the same line, but will have
  935. different discriminator values. This allows the compiler to correctly
  936. set edge weights into ``foo`` and ``bar``.
  937. c. Number of samples. This is an integer quantity representing the
  938. number of samples collected by the profiler at this source
  939. location.
  940. d. [OPTIONAL] Potential call targets and samples. If present, this
  941. line contains a call instruction. This models both direct and
  942. number of samples. For example,
  943. .. code-block:: console
  944. 130: 7 foo:3 bar:2 baz:7
  945. The above means that at relative line offset 130 there is a call
  946. instruction that calls one of ``foo()``, ``bar()`` and ``baz()``,
  947. with ``baz()`` being the relatively more frequently called target.
  948. Profiling with Instrumentation
  949. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  950. Clang also supports profiling via instrumentation. This requires building a
  951. special instrumented version of the code and has some runtime
  952. overhead during the profiling, but it provides more detailed results than a
  953. sampling profiler. It also provides reproducible results, at least to the
  954. extent that the code behaves consistently across runs.
  955. Here are the steps for using profile guided optimization with
  956. instrumentation:
  957. 1. Build an instrumented version of the code by compiling and linking with the
  958. ``-fprofile-instr-generate`` option.
  959. .. code-block:: console
  960. $ clang++ -O2 -fprofile-instr-generate code.cc -o code
  961. 2. Run the instrumented executable with inputs that reflect the typical usage.
  962. By default, the profile data will be written to a ``default.profraw`` file
  963. in the current directory. You can override that default by setting the
  964. ``LLVM_PROFILE_FILE`` environment variable to specify an alternate file.
  965. Any instance of ``%p`` in that file name will be replaced by the process
  966. ID, so that you can easily distinguish the profile output from multiple
  967. runs.
  968. .. code-block:: console
  969. $ LLVM_PROFILE_FILE="code-%p.profraw" ./code
  970. 3. Combine profiles from multiple runs and convert the "raw" profile format to
  971. the input expected by clang. Use the ``merge`` command of the llvm-profdata
  972. tool to do this.
  973. .. code-block:: console
  974. $ llvm-profdata merge -output=code.profdata code-*.profraw
  975. Note that this step is necessary even when there is only one "raw" profile,
  976. since the merge operation also changes the file format.
  977. 4. Build the code again using the ``-fprofile-instr-use`` option to specify the
  978. collected profile data.
  979. .. code-block:: console
  980. $ clang++ -O2 -fprofile-instr-use=code.profdata code.cc -o code
  981. You can repeat step 4 as often as you like without regenerating the
  982. profile. As you make changes to your code, clang may no longer be able to
  983. use the profile data. It will warn you when this happens.
  984. Controlling Size of Debug Information
  985. -------------------------------------
  986. Debug info kind generated by Clang can be set by one of the flags listed
  987. below. If multiple flags are present, the last one is used.
  988. .. option:: -g0
  989. Don't generate any debug info (default).
  990. .. option:: -gline-tables-only
  991. Generate line number tables only.
  992. This kind of debug info allows to obtain stack traces with function names,
  993. file names and line numbers (by such tools as ``gdb`` or ``addr2line``). It
  994. doesn't contain any other data (e.g. description of local variables or
  995. function parameters).
  996. .. option:: -fstandalone-debug
  997. Clang supports a number of optimizations to reduce the size of debug
  998. information in the binary. They work based on the assumption that
  999. the debug type information can be spread out over multiple
  1000. compilation units. For instance, Clang will not emit type
  1001. definitions for types that are not needed by a module and could be
  1002. replaced with a forward declaration. Further, Clang will only emit
  1003. type info for a dynamic C++ class in the module that contains the
  1004. vtable for the class.
  1005. The **-fstandalone-debug** option turns off these optimizations.
  1006. This is useful when working with 3rd-party libraries that don't come
  1007. with debug information. Note that Clang will never emit type
  1008. information for types that are not referenced at all by the program.
  1009. .. option:: -fno-standalone-debug
  1010. On Darwin **-fstandalone-debug** is enabled by default. The
  1011. **-fno-standalone-debug** option can be used to get to turn on the
  1012. vtable-based optimization described above.
  1013. .. option:: -g
  1014. Generate complete debug info.
  1015. Comment Parsing Options
  1016. -----------------------
  1017. Clang parses Doxygen and non-Doxygen style documentation comments and attaches
  1018. them to the appropriate declaration nodes. By default, it only parses
  1019. Doxygen-style comments and ignores ordinary comments starting with ``//`` and
  1020. ``/*``.
  1021. .. option:: -Wdocumentation
  1022. Emit warnings about use of documentation comments. This warning group is off
  1023. by default.
  1024. This includes checking that ``\param`` commands name parameters that actually
  1025. present in the function signature, checking that ``\returns`` is used only on
  1026. functions that actually return a value etc.
  1027. .. option:: -Wno-documentation-unknown-command
  1028. Don't warn when encountering an unknown Doxygen command.
  1029. .. option:: -fparse-all-comments
  1030. Parse all comments as documentation comments (including ordinary comments
  1031. starting with ``//`` and ``/*``).
  1032. .. option:: -fcomment-block-commands=[commands]
  1033. Define custom documentation commands as block commands. This allows Clang to
  1034. construct the correct AST for these custom commands, and silences warnings
  1035. about unknown commands. Several commands must be separated by a comma
  1036. *without trailing space*; e.g. ``-fcomment-block-commands=foo,bar`` defines
  1037. custom commands ``\foo`` and ``\bar``.
  1038. It is also possible to use ``-fcomment-block-commands`` several times; e.g.
  1039. ``-fcomment-block-commands=foo -fcomment-block-commands=bar`` does the same
  1040. as above.
  1041. .. _c:
  1042. C Language Features
  1043. ===================
  1044. The support for standard C in clang is feature-complete except for the
  1045. C99 floating-point pragmas.
  1046. Extensions supported by clang
  1047. -----------------------------
  1048. See :doc:`LanguageExtensions`.
  1049. Differences between various standard modes
  1050. ------------------------------------------
  1051. clang supports the -std option, which changes what language mode clang
  1052. uses. The supported modes for C are c89, gnu89, c94, c99, gnu99 and
  1053. various aliases for those modes. If no -std option is specified, clang
  1054. defaults to gnu99 mode.
  1055. Differences between all ``c*`` and ``gnu*`` modes:
  1056. - ``c*`` modes define "``__STRICT_ANSI__``".
  1057. - Target-specific defines not prefixed by underscores, like "linux",
  1058. are defined in ``gnu*`` modes.
  1059. - Trigraphs default to being off in ``gnu*`` modes; they can be enabled by
  1060. the -trigraphs option.
  1061. - The parser recognizes "asm" and "typeof" as keywords in ``gnu*`` modes;
  1062. the variants "``__asm__``" and "``__typeof__``" are recognized in all
  1063. modes.
  1064. - The Apple "blocks" extension is recognized by default in ``gnu*`` modes
  1065. on some platforms; it can be enabled in any mode with the "-fblocks"
  1066. option.
  1067. - Arrays that are VLA's according to the standard, but which can be
  1068. constant folded by the frontend are treated as fixed size arrays.
  1069. This occurs for things like "int X[(1, 2)];", which is technically a
  1070. VLA. ``c*`` modes are strictly compliant and treat these as VLAs.
  1071. Differences between ``*89`` and ``*99`` modes:
  1072. - The ``*99`` modes default to implementing "inline" as specified in C99,
  1073. while the ``*89`` modes implement the GNU version. This can be
  1074. overridden for individual functions with the ``__gnu_inline__``
  1075. attribute.
  1076. - Digraphs are not recognized in c89 mode.
  1077. - The scope of names defined inside a "for", "if", "switch", "while",
  1078. or "do" statement is different. (example: "``if ((struct x {int
  1079. x;}*)0) {}``".)
  1080. - ``__STDC_VERSION__`` is not defined in ``*89`` modes.
  1081. - "inline" is not recognized as a keyword in c89 mode.
  1082. - "restrict" is not recognized as a keyword in ``*89`` modes.
  1083. - Commas are allowed in integer constant expressions in ``*99`` modes.
  1084. - Arrays which are not lvalues are not implicitly promoted to pointers
  1085. in ``*89`` modes.
  1086. - Some warnings are different.
  1087. c94 mode is identical to c89 mode except that digraphs are enabled in
  1088. c94 mode (FIXME: And ``__STDC_VERSION__`` should be defined!).
  1089. GCC extensions not implemented yet
  1090. ----------------------------------
  1091. clang tries to be compatible with gcc as much as possible, but some gcc
  1092. extensions are not implemented yet:
  1093. - clang does not support #pragma weak (`bug
  1094. 3679 <http://llvm.org/bugs/show_bug.cgi?id=3679>`_). Due to the uses
  1095. described in the bug, this is likely to be implemented at some point,
  1096. at least partially.
  1097. - clang does not support decimal floating point types (``_Decimal32`` and
  1098. friends) or fixed-point types (``_Fract`` and friends); nobody has
  1099. expressed interest in these features yet, so it's hard to say when
  1100. they will be implemented.
  1101. - clang does not support nested functions; this is a complex feature
  1102. which is infrequently used, so it is unlikely to be implemented
  1103. anytime soon. In C++11 it can be emulated by assigning lambda
  1104. functions to local variables, e.g:
  1105. .. code-block:: cpp
  1106. auto const local_function = [&](int parameter) {
  1107. // Do something
  1108. };
  1109. ...
  1110. local_function(1);
  1111. - clang does not support global register variables; this is unlikely to
  1112. be implemented soon because it requires additional LLVM backend
  1113. support.
  1114. - clang does not support static initialization of flexible array
  1115. members. This appears to be a rarely used extension, but could be
  1116. implemented pending user demand.
  1117. - clang does not support
  1118. ``__builtin_va_arg_pack``/``__builtin_va_arg_pack_len``. This is
  1119. used rarely, but in some potentially interesting places, like the
  1120. glibc headers, so it may be implemented pending user demand. Note
  1121. that because clang pretends to be like GCC 4.2, and this extension
  1122. was introduced in 4.3, the glibc headers will not try to use this
  1123. extension with clang at the moment.
  1124. - clang does not support the gcc extension for forward-declaring
  1125. function parameters; this has not shown up in any real-world code
  1126. yet, though, so it might never be implemented.
  1127. This is not a complete list; if you find an unsupported extension
  1128. missing from this list, please send an e-mail to cfe-dev. This list
  1129. currently excludes C++; see :ref:`C++ Language Features <cxx>`. Also, this
  1130. list does not include bugs in mostly-implemented features; please see
  1131. the `bug
  1132. tracker <http://llvm.org/bugs/buglist.cgi?quicksearch=product%3Aclang+component%3A-New%2BBugs%2CAST%2CBasic%2CDriver%2CHeaders%2CLLVM%2BCodeGen%2Cparser%2Cpreprocessor%2CSemantic%2BAnalyzer>`_
  1133. for known existing bugs (FIXME: Is there a section for bug-reporting
  1134. guidelines somewhere?).
  1135. Intentionally unsupported GCC extensions
  1136. ----------------------------------------
  1137. - clang does not support the gcc extension that allows variable-length
  1138. arrays in structures. This is for a few reasons: one, it is tricky to
  1139. implement, two, the extension is completely undocumented, and three,
  1140. the extension appears to be rarely used. Note that clang *does*
  1141. support flexible array members (arrays with a zero or unspecified
  1142. size at the end of a structure).
  1143. - clang does not have an equivalent to gcc's "fold"; this means that
  1144. clang doesn't accept some constructs gcc might accept in contexts
  1145. where a constant expression is required, like "x-x" where x is a
  1146. variable.
  1147. - clang does not support ``__builtin_apply`` and friends; this extension
  1148. is extremely obscure and difficult to implement reliably.
  1149. .. _c_ms:
  1150. Microsoft extensions
  1151. --------------------
  1152. clang has some experimental support for extensions from Microsoft Visual
  1153. C++; to enable it, use the ``-fms-extensions`` command-line option. This is
  1154. the default for Windows targets. Note that the support is incomplete.
  1155. Some constructs such as ``dllexport`` on classes are ignored with a warning,
  1156. and others such as `Microsoft IDL annotations
  1157. <http://msdn.microsoft.com/en-us/library/8tesw2eh.aspx>`_ are silently
  1158. ignored.
  1159. clang has a ``-fms-compatibility`` flag that makes clang accept enough
  1160. invalid C++ to be able to parse most Microsoft headers. For example, it
  1161. allows `unqualified lookup of dependent base class members
  1162. <http://clang.llvm.org/compatibility.html#dep_lookup_bases>`_, which is
  1163. a common compatibility issue with clang. This flag is enabled by default
  1164. for Windows targets.
  1165. ``-fdelayed-template-parsing`` lets clang delay parsing of function template
  1166. definitions until the end of a translation unit. This flag is enabled by
  1167. default for Windows targets.
  1168. - clang allows setting ``_MSC_VER`` with ``-fmsc-version=``. It defaults to
  1169. 1700 which is the same as Visual C/C++ 2012. Any number is supported
  1170. and can greatly affect what Windows SDK and c++stdlib headers clang
  1171. can compile.
  1172. - clang does not support the Microsoft extension where anonymous record
  1173. members can be declared using user defined typedefs.
  1174. - clang supports the Microsoft ``#pragma pack`` feature for controlling
  1175. record layout. GCC also contains support for this feature, however
  1176. where MSVC and GCC are incompatible clang follows the MSVC
  1177. definition.
  1178. - clang supports the Microsoft ``#pragma comment(lib, "foo.lib")`` feature for
  1179. automatically linking against the specified library. Currently this feature
  1180. only works with the Visual C++ linker.
  1181. - clang supports the Microsoft ``#pragma comment(linker, "/flag:foo")`` feature
  1182. for adding linker flags to COFF object files. The user is responsible for
  1183. ensuring that the linker understands the flags.
  1184. - clang defaults to C++11 for Windows targets.
  1185. .. _cxx:
  1186. C++ Language Features
  1187. =====================
  1188. clang fully implements all of standard C++98 except for exported
  1189. templates (which were removed in C++11), and all of standard C++11
  1190. and the current draft standard for C++1y.
  1191. Controlling implementation limits
  1192. ---------------------------------
  1193. .. option:: -fbracket-depth=N
  1194. Sets the limit for nested parentheses, brackets, and braces to N. The
  1195. default is 256.
  1196. .. option:: -fconstexpr-depth=N
  1197. Sets the limit for recursive constexpr function invocations to N. The
  1198. default is 512.
  1199. .. option:: -ftemplate-depth=N
  1200. Sets the limit for recursively nested template instantiations to N. The
  1201. default is 256.
  1202. .. option:: -foperator-arrow-depth=N
  1203. Sets the limit for iterative calls to 'operator->' functions to N. The
  1204. default is 256.
  1205. .. _objc:
  1206. Objective-C Language Features
  1207. =============================
  1208. .. _objcxx:
  1209. Objective-C++ Language Features
  1210. ===============================
  1211. .. _target_features:
  1212. Target-Specific Features and Limitations
  1213. ========================================
  1214. CPU Architectures Features and Limitations
  1215. ------------------------------------------
  1216. X86
  1217. ^^^
  1218. The support for X86 (both 32-bit and 64-bit) is considered stable on
  1219. Darwin (Mac OS X), Linux, FreeBSD, and Dragonfly BSD: it has been tested
  1220. to correctly compile many large C, C++, Objective-C, and Objective-C++
  1221. codebases.
  1222. On ``x86_64-mingw32``, passing i128(by value) is incompatible with the
  1223. Microsoft x64 calling convention. You might need to tweak
  1224. ``WinX86_64ABIInfo::classify()`` in lib/CodeGen/TargetInfo.cpp.
  1225. For the X86 target, clang supports the :option:`-m16` command line
  1226. argument which enables 16-bit code output. This is broadly similar to
  1227. using ``asm(".code16gcc")`` with the GNU toolchain. The generated code
  1228. and the ABI remains 32-bit but the assembler emits instructions
  1229. appropriate for a CPU running in 16-bit mode, with address-size and
  1230. operand-size prefixes to enable 32-bit addressing and operations.
  1231. ARM
  1232. ^^^
  1233. The support for ARM (specifically ARMv6 and ARMv7) is considered stable
  1234. on Darwin (iOS): it has been tested to correctly compile many large C,
  1235. C++, Objective-C, and Objective-C++ codebases. Clang only supports a
  1236. limited number of ARM architectures. It does not yet fully support
  1237. ARMv5, for example.
  1238. PowerPC
  1239. ^^^^^^^
  1240. The support for PowerPC (especially PowerPC64) is considered stable
  1241. on Linux and FreeBSD: it has been tested to correctly compile many
  1242. large C and C++ codebases. PowerPC (32bit) is still missing certain
  1243. features (e.g. PIC code on ELF platforms).
  1244. Other platforms
  1245. ^^^^^^^^^^^^^^^
  1246. clang currently contains some support for other architectures (e.g. Sparc);
  1247. however, significant pieces of code generation are still missing, and they
  1248. haven't undergone significant testing.
  1249. clang contains limited support for the MSP430 embedded processor, but
  1250. both the clang support and the LLVM backend support are highly
  1251. experimental.
  1252. Other platforms are completely unsupported at the moment. Adding the
  1253. minimal support needed for parsing and semantic analysis on a new
  1254. platform is quite easy; see ``lib/Basic/Targets.cpp`` in the clang source
  1255. tree. This level of support is also sufficient for conversion to LLVM IR
  1256. for simple programs. Proper support for conversion to LLVM IR requires
  1257. adding code to ``lib/CodeGen/CGCall.cpp`` at the moment; this is likely to
  1258. change soon, though. Generating assembly requires a suitable LLVM
  1259. backend.
  1260. Operating System Features and Limitations
  1261. -----------------------------------------
  1262. Darwin (Mac OS X)
  1263. ^^^^^^^^^^^^^^^^^
  1264. Thread Sanitizer is not supported.
  1265. Windows
  1266. ^^^^^^^
  1267. Clang has experimental support for targeting "Cygming" (Cygwin / MinGW)
  1268. platforms.
  1269. See also :ref:`Microsoft Extensions <c_ms>`.
  1270. Cygwin
  1271. """"""
  1272. Clang works on Cygwin-1.7.
  1273. MinGW32
  1274. """""""
  1275. Clang works on some mingw32 distributions. Clang assumes directories as
  1276. below;
  1277. - ``C:/mingw/include``
  1278. - ``C:/mingw/lib``
  1279. - ``C:/mingw/lib/gcc/mingw32/4.[3-5].0/include/c++``
  1280. On MSYS, a few tests might fail.
  1281. MinGW-w64
  1282. """""""""
  1283. For 32-bit (i686-w64-mingw32), and 64-bit (x86\_64-w64-mingw32), Clang
  1284. assumes as below;
  1285. - ``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)``
  1286. - ``some_directory/bin/gcc.exe``
  1287. - ``some_directory/bin/clang.exe``
  1288. - ``some_directory/bin/clang++.exe``
  1289. - ``some_directory/bin/../include/c++/GCC_version``
  1290. - ``some_directory/bin/../include/c++/GCC_version/x86_64-w64-mingw32``
  1291. - ``some_directory/bin/../include/c++/GCC_version/i686-w64-mingw32``
  1292. - ``some_directory/bin/../include/c++/GCC_version/backward``
  1293. - ``some_directory/bin/../x86_64-w64-mingw32/include``
  1294. - ``some_directory/bin/../i686-w64-mingw32/include``
  1295. - ``some_directory/bin/../include``
  1296. This directory layout is standard for any toolchain you will find on the
  1297. official `MinGW-w64 website <http://mingw-w64.sourceforge.net>`_.
  1298. Clang expects the GCC executable "gcc.exe" compiled for
  1299. ``i686-w64-mingw32`` (or ``x86_64-w64-mingw32``) to be present on PATH.
  1300. `Some tests might fail <http://llvm.org/bugs/show_bug.cgi?id=9072>`_ on
  1301. ``x86_64-w64-mingw32``.
  1302. .. _clang-cl:
  1303. clang-cl
  1304. ========
  1305. clang-cl is an alternative command-line interface to Clang driver, designed for
  1306. compatibility with the Visual C++ compiler, cl.exe.
  1307. To enable clang-cl to find system headers, libraries, and the linker when run
  1308. from the command-line, it should be executed inside a Visual Studio Native Tools
  1309. Command Prompt or a regular Command Prompt where the environment has been set
  1310. up using e.g. `vcvars32.bat <http://msdn.microsoft.com/en-us/library/f2ccy3wt.aspx>`_.
  1311. clang-cl can also be used from inside Visual Studio by using an LLVM Platform
  1312. Toolset.
  1313. Command-Line Options
  1314. --------------------
  1315. To be compatible with cl.exe, clang-cl supports most of the same command-line
  1316. options. Those options can start with either ``/`` or ``-``. It also supports
  1317. some of Clang's core options, such as the ``-W`` options.
  1318. Options that are known to clang-cl, but not currently supported, are ignored
  1319. with a warning. For example:
  1320. ::
  1321. clang-cl.exe: warning: argument unused during compilation: '/Zi'
  1322. To suppress warnings about unused arguments, use the ``-Qunused-arguments`` option.
  1323. Options that are not known to clang-cl will cause errors. If they are spelled with a
  1324. leading ``/``, they will be mistaken for a filename:
  1325. ::
  1326. clang-cl.exe: error: no such file or directory: '/foobar'
  1327. Please `file a bug <http://llvm.org/bugs/enter_bug.cgi?product=clang&component=Driver>`_
  1328. for any valid cl.exe flags that clang-cl does not understand.
  1329. Execute ``clang-cl /?`` to see a list of supported options:
  1330. ::
  1331. CL.EXE COMPATIBILITY OPTIONS:
  1332. /? Display available options
  1333. /arch:<value> Set architecture for code generation
  1334. /C Don't discard comments when preprocessing
  1335. /c Compile only
  1336. /D <macro[=value]> Define macro
  1337. /EH<value> Exception handling model
  1338. /EP Disable linemarker output and preprocess to stdout
  1339. /E Preprocess to stdout
  1340. /fallback Fall back to cl.exe if clang-cl fails to compile
  1341. /FA Output assembly code file during compilation
  1342. /Fa<file or directory> Output assembly code to this file during compilation
  1343. /Fe<file or directory> Set output executable file or directory (ends in / or \)
  1344. /FI <value> Include file before parsing
  1345. /Fi<file> Set preprocess output file name
  1346. /Fo<file or directory> Set output object file, or directory (ends in / or \)
  1347. /GF- Disable string pooling
  1348. /GR- Disable emission of RTTI data
  1349. /GR Enable emission of RTTI data
  1350. /Gw- Don't put each data item in its own section
  1351. /Gw Put each data item in its own section
  1352. /Gy- Don't put each function in its own section
  1353. /Gy Put each function in its own section
  1354. /help Display available options
  1355. /I <dir> Add directory to include search path
  1356. /J Make char type unsigned
  1357. /LDd Create debug DLL
  1358. /LD Create DLL
  1359. /link <options> Forward options to the linker
  1360. /MDd Use DLL debug run-time
  1361. /MD Use DLL run-time
  1362. /MTd Use static debug run-time
  1363. /MT Use static run-time
  1364. /Ob0 Disable inlining
  1365. /Od Disable optimization
  1366. /Oi- Disable use of builtin functions
  1367. /Oi Enable use of builtin functions
  1368. /Os Optimize for size
  1369. /Ot Optimize for speed
  1370. /Ox Maximum optimization
  1371. /Oy- Disable frame pointer omission
  1372. /Oy Enable frame pointer omission
  1373. /O<n> Optimization level
  1374. /P Preprocess to file
  1375. /showIncludes Print info about included files to stderr
  1376. /TC Treat all source files as C
  1377. /Tc <filename> Specify a C source file
  1378. /TP Treat all source files as C++
  1379. /Tp <filename> Specify a C++ source file
  1380. /U <macro> Undefine macro
  1381. /vd<value> Control vtordisp placement
  1382. /vmb Use a best-case representation method for member pointers
  1383. /vmg Use a most-general representation for member pointers
  1384. /vmm Set the default most-general representation to multiple inheritance
  1385. /vms Set the default most-general representation to single inheritance
  1386. /vmv Set the default most-general representation to virtual inheritance
  1387. /W0 Disable all warnings
  1388. /W1 Enable -Wall
  1389. /W2 Enable -Wall
  1390. /W3 Enable -Wall
  1391. /W4 Enable -Wall
  1392. /Wall Enable -Wall
  1393. /WX- Do not treat warnings as errors
  1394. /WX Treat warnings as errors
  1395. /w Disable all warnings
  1396. /Zi Enable debug information
  1397. /Zs Syntax-check only
  1398. OPTIONS:
  1399. -### Print (but do not run) the commands to run for this compilation
  1400. -fms-compatibility-version=<value>
  1401. Dot-separated value representing the Microsoft compiler version
  1402. number to report in _MSC_VER (0 = don't define it (default))
  1403. -fmsc-version=<value> Microsoft compiler version number to report in _MSC_VER (0 = don't
  1404. define it (default))
  1405. -fsanitize-blacklist=<value>
  1406. Path to blacklist file for sanitizers
  1407. -fsanitize=<check> Enable runtime instrumentation for bug detection: address (memory
  1408. errors) | thread (race detection) | undefined (miscellaneous
  1409. undefined behavior)
  1410. -mllvm <value> Additional arguments to forward to LLVM's option processing
  1411. -Qunused-arguments Don't emit warning for unused driver arguments
  1412. --target=<value> Generate code for the given target
  1413. -v Show commands to run and use verbose output
  1414. -W<warning> Enable the specified warning
  1415. -Xclang <arg> Pass <arg> to the clang compiler
  1416. The /fallback Option
  1417. ^^^^^^^^^^^^^^^^^^^^
  1418. When clang-cl is run with the ``/fallback`` option, it will first try to
  1419. compile files itself. For any file that it fails to compile, it will fall back
  1420. and try to compile the file by invoking cl.exe.
  1421. This option is intended to be used as a temporary means to build projects where
  1422. clang-cl cannot successfully compile all the files. clang-cl may fail to compile
  1423. a file either because it cannot generate code for some C++ feature, or because
  1424. it cannot parse some Microsoft language extension.