blob: 4470dab947fd7eec4a476522062ae8379ccb663b [file] [log] [blame]
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001============================
2Clang Compiler User's Manual
3============================
4
Paul Robinson8ce9b442016-08-15 18:45:52 +00005.. include:: <isonum.txt>
6
Sean Silvabf9b4cd2012-12-13 01:10:46 +00007.. contents::
8 :local:
9
10Introduction
11============
12
13The Clang Compiler is an open-source compiler for the C family of
14programming languages, aiming to be the best in class implementation of
15these languages. Clang builds on the LLVM optimizer and code generator,
16allowing it to provide high-quality optimization and code generation
17support for many targets. For more general information, please see the
18`Clang Web Site <http://clang.llvm.org>`_ or the `LLVM Web
19Site <http://llvm.org>`_.
20
21This document describes important notes about using Clang as a compiler
22for an end-user, documenting the supported features, command line
23options, etc. If you are interested in using Clang to build a tool that
Dmitri Gribenkod9d26072012-12-15 20:41:17 +000024processes code, please see :doc:`InternalsManual`. If you are interested in the
25`Clang Static Analyzer <http://clang-analyzer.llvm.org>`_, please see its web
Sean Silvabf9b4cd2012-12-13 01:10:46 +000026page.
27
Richard Smith58e14742016-10-27 20:55:56 +000028Clang is one component in a complete toolchain for C family languages.
29A separate document describes the other pieces necessary to
30:doc:`assemble a complete toolchain <Toolchain>`.
31
Sean Silvabf9b4cd2012-12-13 01:10:46 +000032Clang is designed to support the C family of programming languages,
33which includes :ref:`C <c>`, :ref:`Objective-C <objc>`, :ref:`C++ <cxx>`, and
34:ref:`Objective-C++ <objcxx>` as well as many dialects of those. For
35language-specific information, please see the corresponding language
36specific section:
37
38- :ref:`C Language <c>`: K&R C, ANSI C89, ISO C90, ISO C94 (C89+AMD1), ISO
39 C99 (+TC1, TC2, TC3).
40- :ref:`Objective-C Language <objc>`: ObjC 1, ObjC 2, ObjC 2.1, plus
41 variants depending on base language.
42- :ref:`C++ Language <cxx>`
43- :ref:`Objective C++ Language <objcxx>`
Anastasia Stulova18e165f2017-01-12 17:52:22 +000044- :ref:`OpenCL C Language <opencl>`: v1.0, v1.1, v1.2, v2.0.
Sean Silvabf9b4cd2012-12-13 01:10:46 +000045
46In addition to these base languages and their dialects, Clang supports a
47broad variety of language extensions, which are documented in the
48corresponding language section. These extensions are provided to be
49compatible with the GCC, Microsoft, and other popular compilers as well
50as to improve functionality through Clang-specific features. The Clang
51driver and language features are intentionally designed to be as
52compatible with the GNU GCC compiler as reasonably possible, easing
53migration from GCC to Clang. In most cases, code "just works".
Hans Wennborg2a6e6bc2013-10-10 01:15:16 +000054Clang also provides an alternative driver, :ref:`clang-cl`, that is designed
55to be compatible with the Visual C++ compiler, cl.exe.
Sean Silvabf9b4cd2012-12-13 01:10:46 +000056
57In addition to language specific features, Clang has a variety of
58features that depend on what CPU architecture or operating system is
59being compiled for. Please see the :ref:`Target-Specific Features and
60Limitations <target_features>` section for more details.
61
62The rest of the introduction introduces some basic :ref:`compiler
63terminology <terminology>` that is used throughout this manual and
64contains a basic :ref:`introduction to using Clang <basicusage>` as a
65command line compiler.
66
67.. _terminology:
68
69Terminology
70-----------
71
72Front end, parser, backend, preprocessor, undefined behavior,
73diagnostic, optimizer
74
75.. _basicusage:
76
77Basic Usage
78-----------
79
80Intro to how to use a C compiler for newbies.
81
82compile + link compile then link debug info enabling optimizations
Richard Smithab506ad2014-10-20 23:26:58 +000083picking a language to use, defaults to C11 by default. Autosenses based
Sean Silvabf9b4cd2012-12-13 01:10:46 +000084on extension. using a makefile
85
86Command Line Options
87====================
88
89This section is generally an index into other sections. It does not go
90into depth on the ones that are covered by other sections. However, the
91first part introduces the language selection and other high level
Dmitri Gribenko1436ff22012-12-19 22:06:59 +000092options like :option:`-c`, :option:`-g`, etc.
Sean Silvabf9b4cd2012-12-13 01:10:46 +000093
94Options to Control Error and Warning Messages
95---------------------------------------------
96
Dmitri Gribenko1436ff22012-12-19 22:06:59 +000097.. option:: -Werror
Sean Silvabf9b4cd2012-12-13 01:10:46 +000098
Dmitri Gribenko1436ff22012-12-19 22:06:59 +000099 Turn warnings into errors.
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000100
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000101.. This is in plain monospaced font because it generates the same label as
102.. -Werror, and Sphinx complains.
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000103
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000104``-Werror=foo``
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000105
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000106 Turn warning "foo" into an error.
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000107
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000108.. option:: -Wno-error=foo
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000109
Reka Kovacsf616a892017-09-23 12:13:32 +0000110 Turn warning "foo" into a warning even if :option:`-Werror` is specified.
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000111
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000112.. option:: -Wfoo
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000113
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000114 Enable warning "foo".
Richard Smithb6a3b4b2016-09-12 05:58:29 +0000115 See the :doc:`diagnostics reference <DiagnosticsReference>` for a complete
116 list of the warning flags that can be specified in this way.
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000117
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000118.. option:: -Wno-foo
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000119
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000120 Disable warning "foo".
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000121
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000122.. option:: -w
123
Tobias Grosser74160242014-02-28 09:11:08 +0000124 Disable all diagnostics.
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000125
126.. option:: -Weverything
127
Tobias Grosser74160242014-02-28 09:11:08 +0000128 :ref:`Enable all diagnostics. <diagnostics_enable_everything>`
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000129
130.. option:: -pedantic
131
132 Warn on language extensions.
133
134.. option:: -pedantic-errors
135
136 Error on language extensions.
137
138.. option:: -Wsystem-headers
139
140 Enable warnings from system headers.
141
142.. option:: -ferror-limit=123
143
144 Stop emitting diagnostics after 123 errors have been produced. The default is
Aaron Ballman4f6b3ec2016-07-14 17:15:06 +0000145 20, and the error limit can be disabled with `-ferror-limit=0`.
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000146
147.. option:: -ftemplate-backtrace-limit=123
148
149 Only emit up to 123 template instantiation notes within the template
150 instantiation backtrace for a single warning or error. The default is 10, and
Aaron Ballman4f6b3ec2016-07-14 17:15:06 +0000151 the limit can be disabled with `-ftemplate-backtrace-limit=0`.
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000152
153.. _cl_diag_formatting:
154
155Formatting of Diagnostics
156^^^^^^^^^^^^^^^^^^^^^^^^^
157
158Clang aims to produce beautiful diagnostics by default, particularly for
159new users that first come to Clang. However, different people have
Douglas Katzman1e7bf362015-08-03 20:41:31 +0000160different preferences, and sometimes Clang is driven not by a human,
161but by a program that wants consistent and easily parsable output. For
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000162these cases, Clang provides a wide range of options to control the exact
163output format of the diagnostics that it generates.
164
165.. _opt_fshow-column:
166
167**-f[no-]show-column**
168 Print column number in diagnostic.
169
170 This option, which defaults to on, controls whether or not Clang
171 prints the column number of a diagnostic. For example, when this is
172 enabled, Clang will print something like:
173
174 ::
175
176 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
177 #endif bad
178 ^
179 //
180
181 When this is disabled, Clang will print "test.c:28: warning..." with
182 no column number.
183
184 The printed column numbers count bytes from the beginning of the
185 line; take care if your source contains multibyte characters.
186
187.. _opt_fshow-source-location:
188
189**-f[no-]show-source-location**
190 Print source file/line/column information in diagnostic.
191
192 This option, which defaults to on, controls whether or not Clang
193 prints the filename, line number and column number of a diagnostic.
194 For example, when this is enabled, Clang will print something like:
195
196 ::
197
198 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
199 #endif bad
200 ^
201 //
202
203 When this is disabled, Clang will not print the "test.c:28:8: "
204 part.
205
206.. _opt_fcaret-diagnostics:
207
208**-f[no-]caret-diagnostics**
209 Print source line and ranges from source code in diagnostic.
210 This option, which defaults to on, controls whether or not Clang
211 prints the source line, source ranges, and caret when emitting a
212 diagnostic. For example, when this is enabled, Clang will print
213 something like:
214
215 ::
216
217 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
218 #endif bad
219 ^
220 //
221
222**-f[no-]color-diagnostics**
223 This option, which defaults to on when a color-capable terminal is
224 detected, controls whether or not Clang prints diagnostics in color.
225
226 When this option is enabled, Clang will use colors to highlight
227 specific parts of the diagnostic, e.g.,
228
229 .. nasty hack to not lose our dignity
230
231 .. raw:: html
232
233 <pre>
234 <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>
235 #endif bad
236 <span style="color:green">^</span>
237 <span style="color:green">//</span>
238 </pre>
239
240 When this is disabled, Clang will just print:
241
242 ::
243
244 test.c:2:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
245 #endif bad
246 ^
247 //
248
Nico Rieck7857d462013-09-11 00:38:02 +0000249**-fansi-escape-codes**
250 Controls whether ANSI escape codes are used instead of the Windows Console
251 API to output colored diagnostics. This option is only used on Windows and
252 defaults to off.
253
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000254.. option:: -fdiagnostics-format=clang/msvc/vi
255
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000256 Changes diagnostic output format to better match IDEs and command line tools.
257
258 This option controls the output format of the filename, line number,
259 and column printed in diagnostic messages. The options, and their
260 affect on formatting a simple conversion diagnostic, follow:
261
262 **clang** (default)
263 ::
264
265 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int'
266
267 **msvc**
268 ::
269
270 t.c(3,11) : warning: conversion specifies type 'char *' but the argument has type 'int'
271
272 **vi**
273 ::
274
275 t.c +3:11: warning: conversion specifies type 'char *' but the argument has type 'int'
276
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000277.. _opt_fdiagnostics-show-option:
278
279**-f[no-]diagnostics-show-option**
280 Enable ``[-Woption]`` information in diagnostic line.
281
282 This option, which defaults to on, controls whether or not Clang
283 prints the associated :ref:`warning group <cl_diag_warning_groups>`
284 option name when outputting a warning diagnostic. For example, in
285 this output:
286
287 ::
288
289 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
290 #endif bad
291 ^
292 //
293
294 Passing **-fno-diagnostics-show-option** will prevent Clang from
295 printing the [:ref:`-Wextra-tokens <opt_Wextra-tokens>`] information in
296 the diagnostic. This information tells you the flag needed to enable
297 or disable the diagnostic, either from the command line or through
298 :ref:`#pragma GCC diagnostic <pragma_GCC_diagnostic>`.
299
300.. _opt_fdiagnostics-show-category:
301
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000302.. option:: -fdiagnostics-show-category=none/id/name
303
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000304 Enable printing category information in diagnostic line.
305
306 This option, which defaults to "none", controls whether or not Clang
307 prints the category associated with a diagnostic when emitting it.
308 Each diagnostic may or many not have an associated category, if it
309 has one, it is listed in the diagnostic categorization field of the
310 diagnostic line (in the []'s).
311
312 For example, a format string warning will produce these three
313 renditions based on the setting of this option:
314
315 ::
316
317 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat]
318 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat,1]
319 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat,Format String]
320
321 This category can be used by clients that want to group diagnostics
322 by category, so it should be a high level category. We want dozens
323 of these, not hundreds or thousands of them.
324
Brian Gesiak562eab92017-07-01 05:45:26 +0000325.. _opt_fsave-optimization-record:
326
327**-fsave-optimization-record**
328 Write optimization remarks to a YAML file.
329
330 This option, which defaults to off, controls whether Clang writes
331 optimization reports to a YAML file. By recording diagnostics in a file,
332 using a structured YAML format, users can parse or sort the remarks in a
333 convenient way.
334
Brian Gesiakbb83ce462017-07-05 19:55:51 +0000335.. _opt_foptimization-record-file:
336
337**-foptimization-record-file**
338 Control the file to which optimization reports are written.
339
340 When optimization reports are being output (see
341 :ref:`-fsave-optimization-record <opt_fsave-optimization-record>`), this
342 option controls the file to which those reports are written.
343
344 If this option is not used, optimization records are output to a file named
345 after the primary file being compiled. If that's "foo.c", for example,
346 optimization records are output to "foo.opt.yaml".
347
Adam Nemet1eea3e52016-09-13 04:32:40 +0000348.. _opt_fdiagnostics-show-hotness:
349
350**-f[no-]diagnostics-show-hotness**
351 Enable profile hotness information in diagnostic line.
352
Brian Gesiak562eab92017-07-01 05:45:26 +0000353 This option controls whether Clang prints the profile hotness associated
354 with diagnostics in the presence of profile-guided optimization information.
355 This is currently supported with optimization remarks (see
356 :ref:`Options to Emit Optimization Reports <rpass>`). The hotness information
357 allows users to focus on the hot optimization remarks that are likely to be
358 more relevant for run-time performance.
Adam Nemet1eea3e52016-09-13 04:32:40 +0000359
360 For example, in this output, the block containing the callsite of `foo` was
361 executed 3000 times according to the profile data:
362
363 ::
364
365 s.c:7:10: remark: foo inlined into bar (hotness: 3000) [-Rpass-analysis=inline]
366 sum += foo(x, x - 2);
367 ^
368
Brian Gesiak562eab92017-07-01 05:45:26 +0000369 This option is implied when
370 :ref:`-fsave-optimization-record <opt_fsave-optimization-record>` is used.
371 Otherwise, it defaults to off.
372
373.. _opt_fdiagnostics-hotness-threshold:
374
375**-fdiagnostics-hotness-threshold**
376 Prevent optimization remarks from being output if they do not have at least
377 this hotness value.
378
379 This option, which defaults to zero, controls the minimum hotness an
380 optimization remark would need in order to be output by Clang. This is
381 currently supported with optimization remarks (see :ref:`Options to Emit
382 Optimization Reports <rpass>`) when profile hotness information in
383 diagnostics is enabled (see
384 :ref:`-fdiagnostics-show-hotness <opt_fdiagnostics-show-hotness>`).
385
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000386.. _opt_fdiagnostics-fixit-info:
387
388**-f[no-]diagnostics-fixit-info**
389 Enable "FixIt" information in the diagnostics output.
390
391 This option, which defaults to on, controls whether or not Clang
392 prints the information on how to fix a specific diagnostic
393 underneath it when it knows. For example, in this output:
394
395 ::
396
397 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
398 #endif bad
399 ^
400 //
401
402 Passing **-fno-diagnostics-fixit-info** will prevent Clang from
403 printing the "//" line at the end of the message. This information
404 is useful for users who may not understand what is wrong, but can be
405 confusing for machine parsing.
406
407.. _opt_fdiagnostics-print-source-range-info:
408
Nico Weber69dce49c72013-01-09 05:06:41 +0000409**-fdiagnostics-print-source-range-info**
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000410 Print machine parsable information about source ranges.
Nico Weber69dce49c72013-01-09 05:06:41 +0000411 This option makes Clang print information about source ranges in a machine
412 parsable format after the file/line/column number information. The
413 information is a simple sequence of brace enclosed ranges, where each range
414 lists the start and end line/column locations. For example, in this output:
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000415
416 ::
417
418 exprs.c:47:15:{47:8-47:14}{47:17-47:24}: error: invalid operands to binary expression ('int *' and '_Complex float')
419 P = (P-42) + Gamma*4;
420 ~~~~~~ ^ ~~~~~~~
421
422 The {}'s are generated by -fdiagnostics-print-source-range-info.
423
424 The printed column numbers count bytes from the beginning of the
425 line; take care if your source contains multibyte characters.
426
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000427.. option:: -fdiagnostics-parseable-fixits
428
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000429 Print Fix-Its in a machine parseable form.
430
431 This option makes Clang print available Fix-Its in a machine
432 parseable format at the end of diagnostics. The following example
433 illustrates the format:
434
435 ::
436
437 fix-it:"t.cpp":{7:25-7:29}:"Gamma"
438
439 The range printed is a half-open range, so in this example the
440 characters at column 25 up to but not including column 29 on line 7
441 in t.cpp should be replaced with the string "Gamma". Either the
442 range or the replacement string may be empty (representing strict
443 insertions and strict erasures, respectively). Both the file name
444 and the insertion string escape backslash (as "\\\\"), tabs (as
445 "\\t"), newlines (as "\\n"), double quotes(as "\\"") and
446 non-printable characters (as octal "\\xxx").
447
448 The printed column numbers count bytes from the beginning of the
449 line; take care if your source contains multibyte characters.
450
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000451.. option:: -fno-elide-type
452
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000453 Turns off elision in template type printing.
454
455 The default for template type printing is to elide as many template
456 arguments as possible, removing those which are the same in both
457 template types, leaving only the differences. Adding this flag will
458 print all the template arguments. If supported by the terminal,
459 highlighting will still appear on differing arguments.
460
461 Default:
462
463 ::
464
465 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;
466
467 -fno-elide-type:
468
469 ::
470
471 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;
472
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000473.. option:: -fdiagnostics-show-template-tree
474
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000475 Template type diffing prints a text tree.
476
477 For diffing large templated types, this option will cause Clang to
478 display the templates as an indented text tree, one argument per
479 line, with differences marked inline. This is compatible with
480 -fno-elide-type.
481
482 Default:
483
484 ::
485
486 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;
487
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000488 With :option:`-fdiagnostics-show-template-tree`:
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000489
490 ::
491
492 t.cc:4:5: note: candidate function not viable: no known conversion for 1st argument;
493 vector<
494 map<
495 [...],
496 map<
Richard Trieu98ca59e2013-08-09 22:52:48 +0000497 [float != double],
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000498 [...]>>>
499
500.. _cl_diag_warning_groups:
501
502Individual Warning Groups
503^^^^^^^^^^^^^^^^^^^^^^^^^
504
505TODO: Generate this from tblgen. Define one anchor per warning group.
506
507.. _opt_wextra-tokens:
508
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000509.. option:: -Wextra-tokens
510
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000511 Warn about excess tokens at the end of a preprocessor directive.
512
513 This option, which defaults to on, enables warnings about extra
514 tokens at the end of preprocessor directives. For example:
515
516 ::
517
518 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
519 #endif bad
520 ^
521
522 These extra tokens are not strictly conforming, and are usually best
523 handled by commenting them out.
524
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000525.. option:: -Wambiguous-member-template
526
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000527 Warn about unqualified uses of a member template whose name resolves to
528 another template at the location of the use.
529
530 This option, which defaults to on, enables a warning in the
531 following code:
532
533 ::
534
535 template<typename T> struct set{};
536 template<typename T> struct trait { typedef const T& type; };
537 struct Value {
538 template<typename T> void set(typename trait<T>::type value) {}
539 };
540 void foo() {
541 Value v;
542 v.set<double>(3.2);
543 }
544
545 C++ [basic.lookup.classref] requires this to be an error, but,
546 because it's hard to work around, Clang downgrades it to a warning
547 as an extension.
548
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000549.. option:: -Wbind-to-temporary-copy
550
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000551 Warn about an unusable copy constructor when binding a reference to a
552 temporary.
553
Nico Weberacb35c02014-09-18 02:09:53 +0000554 This option enables warnings about binding a
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000555 reference to a temporary when the temporary doesn't have a usable
556 copy constructor. For example:
557
558 ::
559
560 struct NonCopyable {
561 NonCopyable();
562 private:
563 NonCopyable(const NonCopyable&);
564 };
565 void foo(const NonCopyable&);
566 void bar() {
567 foo(NonCopyable()); // Disallowed in C++98; allowed in C++11.
568 }
569
570 ::
571
572 struct NonCopyable2 {
573 NonCopyable2();
574 NonCopyable2(NonCopyable2&);
575 };
576 void foo(const NonCopyable2&);
577 void bar() {
578 foo(NonCopyable2()); // Disallowed in C++98; allowed in C++11.
579 }
580
581 Note that if ``NonCopyable2::NonCopyable2()`` has a default argument
582 whose instantiation produces a compile error, that error will still
583 be a hard error in C++98 mode even if this warning is turned off.
584
585Options to Control Clang Crash Diagnostics
586------------------------------------------
587
588As unbelievable as it may sound, Clang does crash from time to time.
589Generally, this only occurs to those living on the `bleeding
590edge <http://llvm.org/releases/download.html#svn>`_. Clang goes to great
591lengths to assist you in filing a bug report. Specifically, Clang
592generates preprocessed source file(s) and associated run script(s) upon
593a crash. These files should be attached to a bug report to ease
594reproducibility of the failure. Below are the command line options to
595control the crash diagnostics.
596
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000597.. option:: -fno-crash-diagnostics
598
599 Disable auto-generation of preprocessed source files during a clang crash.
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000600
601The -fno-crash-diagnostics flag can be helpful for speeding the process
602of generating a delta reduced test case.
603
Bruno Cardoso Lopes52dfe712017-04-12 21:46:20 +0000604Clang is also capable of generating preprocessed source file(s) and associated
605run script(s) even without a crash. This is specially useful when trying to
606generate a reproducer for warnings or errors while using modules.
607
608.. option:: -gen-reproducer
609
610 Generates preprocessed source files, a reproducer script and if relevant, a
611 cache containing: built module pcm's and all headers needed to rebuilt the
612 same modules.
613
Adam Nemet1eea3e52016-09-13 04:32:40 +0000614.. _rpass:
615
Diego Novillo263ce212014-05-29 20:13:27 +0000616Options to Emit Optimization Reports
617------------------------------------
618
619Optimization reports trace, at a high-level, all the major decisions
620done by compiler transformations. For instance, when the inliner
621decides to inline function ``foo()`` into ``bar()``, or the loop unroller
622decides to unroll a loop N times, or the vectorizer decides to
623vectorize a loop body.
624
625Clang offers a family of flags which the optimizers can use to emit
626a diagnostic in three cases:
627
Aaron Ballman05efec82016-07-15 12:55:47 +00006281. When the pass makes a transformation (`-Rpass`).
Diego Novillo263ce212014-05-29 20:13:27 +0000629
Aaron Ballman05efec82016-07-15 12:55:47 +00006302. When the pass fails to make a transformation (`-Rpass-missed`).
Diego Novillo263ce212014-05-29 20:13:27 +0000631
6323. When the pass determines whether or not to make a transformation
Aaron Ballman05efec82016-07-15 12:55:47 +0000633 (`-Rpass-analysis`).
Diego Novillo263ce212014-05-29 20:13:27 +0000634
Aaron Ballman05efec82016-07-15 12:55:47 +0000635NOTE: Although the discussion below focuses on `-Rpass`, the exact
636same options apply to `-Rpass-missed` and `-Rpass-analysis`.
Diego Novillo263ce212014-05-29 20:13:27 +0000637
638Since there are dozens of passes inside the compiler, each of these flags
639take a regular expression that identifies the name of the pass which should
640emit the associated diagnostic. For example, to get a report from the inliner,
641compile the code with:
642
643.. code-block:: console
644
645 $ clang -O2 -Rpass=inline code.cc -o code
646 code.cc:4:25: remark: foo inlined into bar [-Rpass=inline]
647 int bar(int j) { return foo(j, j - 2); }
648 ^
649
650Note that remarks from the inliner are identified with `[-Rpass=inline]`.
651To request a report from every optimization pass, you should use
Aaron Ballman05efec82016-07-15 12:55:47 +0000652`-Rpass=.*` (in fact, you can use any valid POSIX regular
Diego Novillo263ce212014-05-29 20:13:27 +0000653expression). However, do not expect a report from every transformation
654made by the compiler. Optimization remarks do not really make sense
655outside of the major transformations (e.g., inlining, vectorization,
656loop optimizations) and not every optimization pass supports this
657feature.
658
Adam Nemet1eea3e52016-09-13 04:32:40 +0000659Note that when using profile-guided optimization information, profile hotness
660information can be included in the remarks (see
661:ref:`-fdiagnostics-show-hotness <opt_fdiagnostics-show-hotness>`).
662
Diego Novillo263ce212014-05-29 20:13:27 +0000663Current limitations
664^^^^^^^^^^^^^^^^^^^
665
Diego Novillo94b276d2014-07-10 23:29:28 +00006661. Optimization remarks that refer to function names will display the
Diego Novillo263ce212014-05-29 20:13:27 +0000667 mangled name of the function. Since these remarks are emitted by the
668 back end of the compiler, it does not know anything about the input
669 language, nor its mangling rules.
670
Diego Novillo94b276d2014-07-10 23:29:28 +00006712. Some source locations are not displayed correctly. The front end has
Diego Novillo263ce212014-05-29 20:13:27 +0000672 a more detailed source location tracking than the locations included
673 in the debug info (e.g., the front end can locate code inside macro
Aaron Ballman05efec82016-07-15 12:55:47 +0000674 expansions). However, the locations used by `-Rpass` are
Diego Novillo263ce212014-05-29 20:13:27 +0000675 translated from debug annotations. That translation can be lossy,
676 which results in some remarks having no location information.
677
Paul Robinsond7214a72015-04-27 18:14:32 +0000678Other Options
679-------------
Reka Kovacsf616a892017-09-23 12:13:32 +0000680Clang options that don't fit neatly into other categories.
Paul Robinsond7214a72015-04-27 18:14:32 +0000681
682.. option:: -MV
683
684 When emitting a dependency file, use formatting conventions appropriate
685 for NMake or Jom. Ignored unless another option causes Clang to emit a
686 dependency file.
687
688When Clang emits a dependency file (e.g., you supplied the -M option)
689most filenames can be written to the file without any special formatting.
690Different Make tools will treat different sets of characters as "special"
691and use different conventions for telling the Make tool that the character
692is actually part of the filename. Normally Clang uses backslash to "escape"
693a special character, which is the convention used by GNU Make. The -MV
694option tells Clang to put double-quotes around the entire filename, which
695is the convention used by NMake and Jom.
696
Serge Pavlov208ac652018-01-01 13:27:01 +0000697Configuration files
698-------------------
699
700Configuration files group command-line options and allow all of them to be
701specified just by referencing the configuration file. They may be used, for
702example, to collect options required to tune compilation for particular
703target, such as -L, -I, -l, --sysroot, codegen options, etc.
704
705The command line option `--config` can be used to specify configuration
706file in a Clang invocation. For example:
707
708::
709
710 clang --config /home/user/cfgs/testing.txt
711 clang --config debug.cfg
712
713If the provided argument contains a directory separator, it is considered as
714a file path, and options are read from that file. Otherwise the argument is
715treated as a file name and is searched for sequentially in the directories:
716
717 - user directory,
718 - system directory,
719 - the directory where Clang executable resides.
720
721Both user and system directories for configuration files are specified during
722clang build using CMake parameters, CLANG_CONFIG_FILE_USER_DIR and
723CLANG_CONFIG_FILE_SYSTEM_DIR respectively. The first file found is used. It is
724an error if the required file cannot be found.
725
726Another way to specify a configuration file is to encode it in executable name.
727For example, if the Clang executable is named `armv7l-clang` (it may be a
728symbolic link to `clang`), then Clang will search for file `armv7l.cfg` in the
729directory where Clang resides.
730
731If a driver mode is specified in invocation, Clang tries to find a file specific
732for the specified mode. For example, if the executable file is named
733`x86_64-clang-cl`, Clang first looks for `x86_64-cl.cfg` and if it is not found,
Serge Pavlov93581c52018-01-01 15:53:16 +0000734looks for `x86_64.cfg`.
Serge Pavlov208ac652018-01-01 13:27:01 +0000735
736If the command line contains options that effectively change target architecture
737(these are -m32, -EL, and some others) and the configuration file starts with an
738architecture name, Clang tries to load the configuration file for the effective
739architecture. For example, invocation:
740
741::
742
743 x86_64-clang -m32 abc.c
744
745causes Clang search for a file `i368.cfg` first, and if no such file is found,
746Clang looks for the file `x86_64.cfg`.
747
748The configuration file consists of command-line options specified on one or
749more lines. Lines composed of whitespace characters only are ignored as well as
750lines in which the first non-blank character is `#`. Long options may be split
751between several lines by a trailing backslash. Here is example of a
752configuration file:
753
754::
755
756 # Several options on line
757 -c --target=x86_64-unknown-linux-gnu
758
759 # Long option split between lines
760 -I/usr/lib/gcc/x86_64-linux-gnu/5.4.0/../../../../\
761 include/c++/5.4.0
762
763 # other config files may be included
764 @linux.options
765
766Files included by `@file` directives in configuration files are resolved
767relative to the including file. For example, if a configuration file
768`~/.llvm/target.cfg` contains the directive `@os/linux.opts`, the file
769`linux.opts` is searched for in the directory `~/.llvm/os`.
Diego Novillo263ce212014-05-29 20:13:27 +0000770
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000771Language and Target-Independent Features
772========================================
773
774Controlling Errors and Warnings
775-------------------------------
776
777Clang provides a number of ways to control which code constructs cause
778it to emit errors and warning messages, and how they are displayed to
779the console.
780
781Controlling How Clang Displays Diagnostics
782^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
783
784When Clang emits a diagnostic, it includes rich information in the
785output, and gives you fine-grain control over which information is
786printed. Clang has the ability to print this information, and these are
787the options that control it:
788
789#. A file/line/column indicator that shows exactly where the diagnostic
790 occurs in your code [:ref:`-fshow-column <opt_fshow-column>`,
791 :ref:`-fshow-source-location <opt_fshow-source-location>`].
792#. A categorization of the diagnostic as a note, warning, error, or
793 fatal error.
794#. A text string that describes what the problem is.
795#. An option that indicates how to control the diagnostic (for
796 diagnostics that support it)
797 [:ref:`-fdiagnostics-show-option <opt_fdiagnostics-show-option>`].
798#. A :ref:`high-level category <diagnostics_categories>` for the diagnostic
799 for clients that want to group diagnostics by class (for diagnostics
800 that support it)
801 [:ref:`-fdiagnostics-show-category <opt_fdiagnostics-show-category>`].
802#. The line of source code that the issue occurs on, along with a caret
803 and ranges that indicate the important locations
804 [:ref:`-fcaret-diagnostics <opt_fcaret-diagnostics>`].
805#. "FixIt" information, which is a concise explanation of how to fix the
806 problem (when Clang is certain it knows)
807 [:ref:`-fdiagnostics-fixit-info <opt_fdiagnostics-fixit-info>`].
808#. A machine-parsable representation of the ranges involved (off by
809 default)
810 [:ref:`-fdiagnostics-print-source-range-info <opt_fdiagnostics-print-source-range-info>`].
811
812For more information please see :ref:`Formatting of
813Diagnostics <cl_diag_formatting>`.
814
815Diagnostic Mappings
816^^^^^^^^^^^^^^^^^^^
817
Alex Denisov793e0672015-02-11 07:56:16 +0000818All diagnostics are mapped into one of these 6 classes:
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000819
820- Ignored
821- Note
Tobias Grosser74160242014-02-28 09:11:08 +0000822- Remark
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000823- Warning
824- Error
825- Fatal
826
827.. _diagnostics_categories:
828
829Diagnostic Categories
830^^^^^^^^^^^^^^^^^^^^^
831
832Though not shown by default, diagnostics may each be associated with a
833high-level category. This category is intended to make it possible to
834triage builds that produce a large number of errors or warnings in a
835grouped way.
836
837Categories are not shown by default, but they can be turned on with the
838:ref:`-fdiagnostics-show-category <opt_fdiagnostics-show-category>` option.
839When set to "``name``", the category is printed textually in the
840diagnostic output. When it is set to "``id``", a category number is
841printed. The mapping of category names to category id's can be obtained
842by running '``clang --print-diagnostic-categories``'.
843
844Controlling Diagnostics via Command Line Flags
845^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
846
847TODO: -W flags, -pedantic, etc
848
849.. _pragma_gcc_diagnostic:
850
851Controlling Diagnostics via Pragmas
852^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
853
854Clang can also control what diagnostics are enabled through the use of
855pragmas in the source code. This is useful for turning off specific
856warnings in a section of source code. Clang supports GCC's pragma for
857compatibility with existing source code, as well as several extensions.
858
859The pragma may control any warning that can be used from the command
860line. Warnings may be set to ignored, warning, error, or fatal. The
861following example code will tell Clang or GCC to ignore the -Wall
862warnings:
863
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000864.. code-block:: c
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000865
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000866 #pragma GCC diagnostic ignored "-Wall"
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000867
868In addition to all of the functionality provided by GCC's pragma, Clang
869also allows you to push and pop the current warning state. This is
870particularly useful when writing a header file that will be compiled by
871other people, because you don't know what warning flags they build with.
872
George Burgess IVbc8cc5ac2016-06-21 02:19:43 +0000873In the below example :option:`-Wextra-tokens` is ignored for only a single line
874of code, after which the diagnostics return to whatever state had previously
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000875existed.
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000876
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000877.. code-block:: c
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000878
George Burgess IVbc8cc5ac2016-06-21 02:19:43 +0000879 #if foo
880 #endif foo // warning: extra tokens at end of #endif directive
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000881
Asiri Rathnayakeb0bbb7d2017-02-02 10:35:18 +0000882 #pragma clang diagnostic push
George Burgess IVbc8cc5ac2016-06-21 02:19:43 +0000883 #pragma clang diagnostic ignored "-Wextra-tokens"
884
885 #if foo
886 #endif foo // no warning
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000887
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000888 #pragma clang diagnostic pop
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000889
890The push and pop pragmas will save and restore the full diagnostic state
891of the compiler, regardless of how it was set. That means that it is
892possible to use push and pop around GCC compatible diagnostics and Clang
893will push and pop them appropriately, while GCC will ignore the pushes
894and pops as unknown pragmas. It should be noted that while Clang
895supports the GCC pragma, Clang and GCC do not support the exact same set
896of warnings, so even when using GCC compatible #pragmas there is no
897guarantee that they will have identical behaviour on both compilers.
898
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000899In addition to controlling warnings and errors generated by the compiler, it is
900possible to generate custom warning and error messages through the following
901pragmas:
902
903.. code-block:: c
904
905 // The following will produce warning messages
906 #pragma message "some diagnostic message"
907 #pragma GCC warning "TODO: replace deprecated feature"
908
909 // The following will produce an error message
910 #pragma GCC error "Not supported"
911
912These pragmas operate similarly to the ``#warning`` and ``#error`` preprocessor
913directives, except that they may also be embedded into preprocessor macros via
914the C99 ``_Pragma`` operator, for example:
915
916.. code-block:: c
917
918 #define STR(X) #X
919 #define DEFER(M,...) M(__VA_ARGS__)
920 #define CUSTOM_ERROR(X) _Pragma(STR(GCC error(X " at line " DEFER(STR,__LINE__))))
921
922 CUSTOM_ERROR("Feature not available");
923
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000924Controlling Diagnostics in System Headers
925^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
926
927Warnings are suppressed when they occur in system headers. By default,
928an included file is treated as a system header if it is found in an
929include path specified by ``-isystem``, but this can be overridden in
930several ways.
931
932The ``system_header`` pragma can be used to mark the current file as
933being a system header. No warnings will be produced from the location of
934the pragma onwards within the same file.
935
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000936.. code-block:: c
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000937
George Burgess IVbc8cc5ac2016-06-21 02:19:43 +0000938 #if foo
939 #endif foo // warning: extra tokens at end of #endif directive
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000940
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000941 #pragma clang system_header
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000942
George Burgess IVbc8cc5ac2016-06-21 02:19:43 +0000943 #if foo
944 #endif foo // no warning
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000945
Aaron Ballman51fb0312016-07-15 13:13:45 +0000946The `--system-header-prefix=` and `--no-system-header-prefix=`
Alexander Kornienko18fa48c2014-03-26 01:39:59 +0000947command-line arguments can be used to override whether subsets of an include
948path are treated as system headers. When the name in a ``#include`` directive
949is found within a header search path and starts with a system prefix, the
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000950header is treated as a system header. The last prefix on the
951command-line which matches the specified header name takes precedence.
952For instance:
953
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000954.. code-block:: console
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000955
Alexander Kornienko18fa48c2014-03-26 01:39:59 +0000956 $ clang -Ifoo -isystem bar --system-header-prefix=x/ \
957 --no-system-header-prefix=x/y/
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000958
959Here, ``#include "x/a.h"`` is treated as including a system header, even
960if the header is found in ``foo``, and ``#include "x/y/b.h"`` is treated
961as not including a system header, even if the header is found in
962``bar``.
963
964A ``#include`` directive which finds a file relative to the current
965directory is treated as including a system header if the including file
966is treated as a system header.
967
968.. _diagnostics_enable_everything:
969
Tobias Grosser74160242014-02-28 09:11:08 +0000970Enabling All Diagnostics
971^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000972
973In addition to the traditional ``-W`` flags, one can enable **all**
Tobias Grosser74160242014-02-28 09:11:08 +0000974diagnostics by passing :option:`-Weverything`. This works as expected
975with
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000976:option:`-Werror`, and also includes the warnings from :option:`-pedantic`.
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000977
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000978Note that when combined with :option:`-w` (which disables all warnings), that
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000979flag wins.
980
981Controlling Static Analyzer Diagnostics
982^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
983
984While not strictly part of the compiler, the diagnostics from Clang's
985`static analyzer <http://clang-analyzer.llvm.org>`_ can also be
986influenced by the user via changes to the source code. See the available
987`annotations <http://clang-analyzer.llvm.org/annotations.html>`_ and the
988analyzer's `FAQ
989page <http://clang-analyzer.llvm.org/faq.html#exclude_code>`_ for more
990information.
991
Dmitri Gribenko7ac0cc32012-12-15 21:10:51 +0000992.. _usersmanual-precompiled-headers:
993
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000994Precompiled Headers
995-------------------
996
997`Precompiled headers <http://en.wikipedia.org/wiki/Precompiled_header>`__
998are a general approach employed by many compilers to reduce compilation
999time. The underlying motivation of the approach is that it is common for
1000the same (and often large) header files to be included by multiple
1001source files. Consequently, compile times can often be greatly improved
1002by caching some of the (redundant) work done by a compiler to process
1003headers. Precompiled header files, which represent one of many ways to
1004implement this optimization, are literally files that represent an
1005on-disk cache that contains the vital information necessary to reduce
1006some of the work needed to process a corresponding header file. While
1007details of precompiled headers vary between compilers, precompiled
1008headers have been shown to be highly effective at speeding up program
Nico Weberab88f0b2014-03-07 18:09:57 +00001009compilation on systems with very large system headers (e.g., Mac OS X).
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001010
1011Generating a PCH File
1012^^^^^^^^^^^^^^^^^^^^^
1013
1014To generate a PCH file using Clang, one invokes Clang with the
Aaron Ballman51fb0312016-07-15 13:13:45 +00001015`-x <language>-header` option. This mirrors the interface in GCC
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001016for generating PCH files:
1017
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001018.. code-block:: console
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001019
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001020 $ gcc -x c-header test.h -o test.h.gch
1021 $ clang -x c-header test.h -o test.h.pch
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001022
1023Using a PCH File
1024^^^^^^^^^^^^^^^^
1025
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001026A PCH file can then be used as a prefix header when a :option:`-include`
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001027option is passed to ``clang``:
1028
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001029.. code-block:: console
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001030
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001031 $ clang -include test.h test.c -o test
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001032
1033The ``clang`` driver will first check if a PCH file for ``test.h`` is
1034available; if so, the contents of ``test.h`` (and the files it includes)
1035will be processed from the PCH file. Otherwise, Clang falls back to
1036directly processing the content of ``test.h``. This mirrors the behavior
1037of GCC.
1038
1039.. note::
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001040
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001041 Clang does *not* automatically use PCH files for headers that are directly
1042 included within a source file. For example:
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001043
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001044 .. code-block:: console
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001045
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001046 $ clang -x c-header test.h -o test.h.pch
1047 $ cat test.c
1048 #include "test.h"
1049 $ clang test.c -o test
1050
1051 In this example, ``clang`` will not automatically use the PCH file for
1052 ``test.h`` since ``test.h`` was included directly in the source file and not
1053 specified on the command line using :option:`-include`.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001054
1055Relocatable PCH Files
1056^^^^^^^^^^^^^^^^^^^^^
1057
1058It is sometimes necessary to build a precompiled header from headers
1059that are not yet in their final, installed locations. For example, one
1060might build a precompiled header within the build tree that is then
1061meant to be installed alongside the headers. Clang permits the creation
1062of "relocatable" precompiled headers, which are built with a given path
1063(into the build directory) and can later be used from an installed
1064location.
1065
1066To build a relocatable precompiled header, place your headers into a
1067subdirectory whose structure mimics the installed location. For example,
1068if you want to build a precompiled header for the header ``mylib.h``
1069that will be installed into ``/usr/include``, create a subdirectory
1070``build/usr/include`` and place the header ``mylib.h`` into that
1071subdirectory. If ``mylib.h`` depends on other headers, then they can be
1072stored within ``build/usr/include`` in a way that mimics the installed
1073location.
1074
1075Building a relocatable precompiled header requires two additional
1076arguments. First, pass the ``--relocatable-pch`` flag to indicate that
1077the resulting PCH file should be relocatable. Second, pass
Brian Gesiak49956142018-01-13 18:34:07 +00001078``-isysroot /path/to/build``, which makes all includes for your library
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001079relative to the build directory. For example:
1080
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001081.. code-block:: console
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001082
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001083 # clang -x c-header --relocatable-pch -isysroot /path/to/build /path/to/build/mylib.h mylib.h.pch
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001084
1085When loading the relocatable PCH file, the various headers used in the
1086PCH file are found from the system header root. For example, ``mylib.h``
1087can be found in ``/usr/include/mylib.h``. If the headers are installed
Brian Gesiak49956142018-01-13 18:34:07 +00001088in some other system root, the ``-isysroot`` option can be used provide
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001089a different system root from which the headers will be based. For
Brian Gesiak49956142018-01-13 18:34:07 +00001090example, ``-isysroot /Developer/SDKs/MacOSX10.4u.sdk`` will look for
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001091``mylib.h`` in ``/Developer/SDKs/MacOSX10.4u.sdk/usr/include/mylib.h``.
1092
1093Relocatable precompiled headers are intended to be used in a limited
1094number of cases where the compilation environment is tightly controlled
1095and the precompiled header cannot be generated after headers have been
Argyrios Kyrtzidisf0ad09f2013-02-14 00:12:44 +00001096installed.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001097
Peter Collingbourne915df992015-05-15 18:33:32 +00001098.. _controlling-code-generation:
1099
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001100Controlling Code Generation
1101---------------------------
1102
1103Clang provides a number of ways to control code generation. The options
1104are listed below.
1105
Sean Silva4c280bd2013-06-21 23:50:58 +00001106**-f[no-]sanitize=check1,check2,...**
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001107 Turn on runtime checks for various forms of undefined or suspicious
1108 behavior.
1109
1110 This option controls whether Clang adds runtime checks for various
1111 forms of undefined or suspicious behavior, and is disabled by
1112 default. If a check fails, a diagnostic message is produced at
1113 runtime explaining the problem. The main checks are:
1114
Richard Smithbb741f42012-12-13 07:29:23 +00001115 - .. _opt_fsanitize_address:
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001116
Richard Smithbb741f42012-12-13 07:29:23 +00001117 ``-fsanitize=address``:
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001118 :doc:`AddressSanitizer`, a memory error
1119 detector.
Richard Smithbb741f42012-12-13 07:29:23 +00001120 - .. _opt_fsanitize_thread:
1121
Dmitry Vyukov42de1082012-12-21 08:21:25 +00001122 ``-fsanitize=thread``: :doc:`ThreadSanitizer`, a data race detector.
Evgeniy Stepanov17d55902012-12-21 10:50:00 +00001123 - .. _opt_fsanitize_memory:
1124
1125 ``-fsanitize=memory``: :doc:`MemorySanitizer`,
Alexey Samsonov1f7051e2015-12-04 22:50:44 +00001126 a detector of uninitialized reads. Requires instrumentation of all
1127 program code.
Richard Smithbb741f42012-12-13 07:29:23 +00001128 - .. _opt_fsanitize_undefined:
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001129
Alexey Samsonov778fc722015-12-04 17:30:29 +00001130 ``-fsanitize=undefined``: :doc:`UndefinedBehaviorSanitizer`,
1131 a fast and compatible undefined behavior checker.
Peter Collingbourne9881b782015-06-18 23:59:22 +00001132
Peter Collingbournec3772752013-08-07 22:47:34 +00001133 - ``-fsanitize=dataflow``: :doc:`DataFlowSanitizer`, a general data
1134 flow analysis.
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001135 - ``-fsanitize=cfi``: :doc:`control flow integrity <ControlFlowIntegrity>`
Alexey Samsonov907880e2015-06-19 19:57:46 +00001136 checks. Requires ``-flto``.
Peter Collingbournec4122c12015-06-15 21:08:13 +00001137 - ``-fsanitize=safe-stack``: :doc:`safe stack <SafeStack>`
1138 protection against stack-based memory corruption errors.
Chad Rosierae229d52013-01-29 23:31:22 +00001139
Alexey Samsonov778fc722015-12-04 17:30:29 +00001140 There are more fine-grained checks available: see
1141 the :ref:`list <ubsan-checks>` of specific kinds of
Alexey Samsonov9eda6402015-12-04 21:30:58 +00001142 undefined behavior that can be detected and the :ref:`list <cfi-schemes>`
1143 of control flow integrity schemes.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001144
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001145 The ``-fsanitize=`` argument must also be provided when linking, in
Alexey Samsonovb6761c22015-12-04 23:13:14 +00001146 order to link to the appropriate runtime library.
Richard Smith83c728b2013-07-19 19:06:48 +00001147
1148 It is not possible to combine more than one of the ``-fsanitize=address``,
1149 ``-fsanitize=thread``, and ``-fsanitize=memory`` checkers in the same
Alexey Samsonov88460172015-12-04 17:35:47 +00001150 program.
Richard Smith83c728b2013-07-19 19:06:48 +00001151
Alexey Samsonov88459522015-01-12 22:39:12 +00001152**-f[no-]sanitize-recover=check1,check2,...**
Kostya Serebryany40b82152016-05-04 20:24:54 +00001153
Kostya Serebryanyceb1add2016-05-04 20:21:47 +00001154**-f[no-]sanitize-recover=all**
Alexey Samsonov88459522015-01-12 22:39:12 +00001155
1156 Controls which checks enabled by ``-fsanitize=`` flag are non-fatal.
1157 If the check is fatal, program will halt after the first error
1158 of this kind is detected and error report is printed.
1159
Alexey Samsonov778fc722015-12-04 17:30:29 +00001160 By default, non-fatal checks are those enabled by
1161 :doc:`UndefinedBehaviorSanitizer`,
Alexey Samsonov88459522015-01-12 22:39:12 +00001162 except for ``-fsanitize=return`` and ``-fsanitize=unreachable``. Some
Yury Gribov5bfeca12015-11-11 10:45:48 +00001163 sanitizers may not support recovery (or not support it by default
1164 e.g. :doc:`AddressSanitizer`), and always crash the program after the issue
1165 is detected.
Alexey Samsonov88459522015-01-12 22:39:12 +00001166
Peter Collingbourne9881b782015-06-18 23:59:22 +00001167 Note that the ``-fsanitize-trap`` flag has precedence over this flag.
1168 This means that if a check has been configured to trap elsewhere on the
1169 command line, or if the check traps by default, this flag will not have
1170 any effect unless that sanitizer's trapping behavior is disabled with
1171 ``-fno-sanitize-trap``.
1172
1173 For example, if a command line contains the flags ``-fsanitize=undefined
1174 -fsanitize-trap=undefined``, the flag ``-fsanitize-recover=alignment``
1175 will have no effect on its own; it will need to be accompanied by
1176 ``-fno-sanitize-trap=alignment``.
1177
1178**-f[no-]sanitize-trap=check1,check2,...**
1179
1180 Controls which checks enabled by the ``-fsanitize=`` flag trap. This
1181 option is intended for use in cases where the sanitizer runtime cannot
1182 be used (for instance, when building libc or a kernel module), or where
1183 the binary size increase caused by the sanitizer runtime is a concern.
1184
Alexey Samsonovb6761c22015-12-04 23:13:14 +00001185 This flag is only compatible with :doc:`control flow integrity
1186 <ControlFlowIntegrity>` schemes and :doc:`UndefinedBehaviorSanitizer`
1187 checks other than ``vptr``. If this flag
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001188 is supplied together with ``-fsanitize=undefined``, the ``vptr`` sanitizer
1189 will be implicitly disabled.
1190
1191 This flag is enabled by default for sanitizers in the ``cfi`` group.
Peter Collingbourne9881b782015-06-18 23:59:22 +00001192
Alexey Samsonovb6761c22015-12-04 23:13:14 +00001193.. option:: -fsanitize-blacklist=/path/to/blacklist/file
1194
1195 Disable or modify sanitizer checks for objects (source files, functions,
1196 variables, types) listed in the file. See
1197 :doc:`SanitizerSpecialCaseList` for file format description.
1198
1199.. option:: -fno-sanitize-blacklist
1200
1201 Don't use blacklist file, if it was specified earlier in the command line.
1202
Alexey Samsonov8fffba12015-05-07 23:04:19 +00001203**-f[no-]sanitize-coverage=[type,features,...]**
1204
1205 Enable simple code coverage in addition to certain sanitizers.
1206 See :doc:`SanitizerCoverage` for more details.
1207
Peter Collingbournedc134532016-01-16 00:31:22 +00001208**-f[no-]sanitize-stats**
1209
1210 Enable simple statistics gathering for the enabled sanitizers.
1211 See :doc:`SanitizerStats` for more details.
1212
Peter Collingbourne9881b782015-06-18 23:59:22 +00001213.. option:: -fsanitize-undefined-trap-on-error
1214
1215 Deprecated alias for ``-fsanitize-trap=undefined``.
1216
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001217.. option:: -fsanitize-cfi-cross-dso
1218
1219 Enable cross-DSO control flow integrity checks. This flag modifies
1220 the behavior of sanitizers in the ``cfi`` group to allow checking
1221 of cross-DSO virtual and indirect calls.
1222
Vlad Tsyrklevich634c6012017-10-31 22:39:44 +00001223.. option:: -fsanitize-cfi-icall-generalize-pointers
1224
1225 Generalize pointers in return and argument types in function type signatures
1226 checked by Control Flow Integrity indirect call checking. See
1227 :doc:`ControlFlowIntegrity` for more details.
Piotr Padlewskieb9dd5a2017-01-16 13:20:08 +00001228
1229.. option:: -fstrict-vtable-pointers
Hans Wennborgf6d61d42017-01-17 21:31:57 +00001230
Piotr Padlewskieb9dd5a2017-01-16 13:20:08 +00001231 Enable optimizations based on the strict rules for overwriting polymorphic
1232 C++ objects, i.e. the vptr is invariant during an object's lifetime.
1233 This enables better devirtualization. Turned off by default, because it is
1234 still experimental.
1235
Justin Lebar84da8b22016-05-20 21:33:01 +00001236.. option:: -ffast-math
1237
1238 Enable fast-math mode. This defines the ``__FAST_MATH__`` preprocessor
1239 macro, and lets the compiler make aggressive, potentially-lossy assumptions
1240 about floating-point math. These include:
1241
1242 * Floating-point math obeys regular algebraic rules for real numbers (e.g.
1243 ``+`` and ``*`` are associative, ``x/y == x * (1/y)``, and
1244 ``(a + b) * c == a * c + b * c``),
1245 * operands to floating-point operations are not equal to ``NaN`` and
1246 ``Inf``, and
1247 * ``+0`` and ``-0`` are interchangeable.
1248
Sjoerd Meijer0a8d4212016-08-30 08:09:45 +00001249.. option:: -fdenormal-fp-math=[values]
1250
1251 Select which denormal numbers the code is permitted to require.
1252
1253 Valid values are: ``ieee``, ``preserve-sign``, and ``positive-zero``,
1254 which correspond to IEEE 754 denormal numbers, the sign of a
1255 flushed-to-zero number is preserved in the sign of 0, denormals are
1256 flushed to positive zero, respectively.
1257
Sanjay Patelc81450e2018-04-30 18:19:03 +00001258.. option:: -f[no-]strict-float-cast-overflow
Sanjay Pateld1754762018-04-27 14:22:48 +00001259
Sanjay Patelc81450e2018-04-30 18:19:03 +00001260 When a floating-point value is not representable in a destination integer
1261 type, the code has undefined behavior according to the language standard.
1262 By default, Clang will not guarantee any particular result in that case.
1263 With the 'no-strict' option, Clang attempts to match the overflowing behavior
1264 of the target's native float-to-int conversion instructions.
Sanjay Pateld1754762018-04-27 14:22:48 +00001265
Peter Collingbournefb532b92016-02-24 20:46:36 +00001266.. option:: -fwhole-program-vtables
1267
1268 Enable whole-program vtable optimizations, such as single-implementation
Peter Collingbourne3afb2662016-04-28 17:09:37 +00001269 devirtualization and virtual constant propagation, for classes with
1270 :doc:`hidden LTO visibility <LTOVisibility>`. Requires ``-flto``.
Peter Collingbournefb532b92016-02-24 20:46:36 +00001271
Piotr Padlewskie368de32018-06-13 13:55:42 +00001272.. option:: -fforce-emit-vtables
1273
1274 In order to improve devirtualization, forces emitting of vtables even in
1275 modules where it isn't necessary. It causes more inline virtual functions
1276 to be emitted.
1277
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001278.. option:: -fno-assume-sane-operator-new
1279
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001280 Don't assume that the C++'s new operator is sane.
1281
1282 This option tells the compiler to do not assume that C++'s global
1283 new operator will always return a pointer that does not alias any
1284 other pointer when the function returns.
1285
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001286.. option:: -ftrap-function=[name]
1287
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001288 Instruct code generator to emit a function call to the specified
1289 function name for ``__builtin_trap()``.
1290
1291 LLVM code generator translates ``__builtin_trap()`` to a trap
1292 instruction if it is supported by the target ISA. Otherwise, the
1293 builtin is translated into a call to ``abort``. If this option is
1294 set, then the code generator will always lower the builtin to a call
1295 to the specified function regardless of whether the target ISA has a
1296 trap instruction. This option is useful for environments (e.g.
1297 deeply embedded) where a trap cannot be properly handled, or when
1298 some custom behavior is desired.
1299
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001300.. option:: -ftls-model=[model]
1301
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001302 Select which TLS model to use.
1303
1304 Valid values are: ``global-dynamic``, ``local-dynamic``,
1305 ``initial-exec`` and ``local-exec``. The default value is
1306 ``global-dynamic``. The compiler may use a different model if the
1307 selected model is not supported by the target, or if a more
1308 efficient model can be used. The TLS model can be overridden per
1309 variable using the ``tls_model`` attribute.
1310
Chih-Hung Hsieh2c656c92015-07-28 16:27:56 +00001311.. option:: -femulated-tls
1312
1313 Select emulated TLS model, which overrides all -ftls-model choices.
1314
1315 In emulated TLS mode, all access to TLS variables are converted to
1316 calls to __emutls_get_address in the runtime library.
1317
Silviu Barangaf9671dd2013-10-21 10:54:53 +00001318.. option:: -mhwdiv=[values]
1319
1320 Select the ARM modes (arm or thumb) that support hardware division
1321 instructions.
1322
1323 Valid values are: ``arm``, ``thumb`` and ``arm,thumb``.
1324 This option is used to indicate which mode (arm or thumb) supports
1325 hardware division instructions. This only applies to the ARM
1326 architecture.
1327
Bernard Ogden18b57012013-10-29 09:47:51 +00001328.. option:: -m[no-]crc
1329
1330 Enable or disable CRC instructions.
1331
1332 This option is used to indicate whether CRC instructions are to
1333 be generated. This only applies to the ARM architecture.
1334
1335 CRC instructions are enabled by default on ARMv8.
1336
Amara Emerson05d816d2014-01-24 15:15:27 +00001337.. option:: -mgeneral-regs-only
Amara Emerson04e2ecf2014-01-23 15:48:30 +00001338
1339 Generate code which only uses the general purpose registers.
1340
1341 This option restricts the generated code to use general registers
1342 only. This only applies to the AArch64 architecture.
1343
Simon Dardisd0e83ba2016-05-27 15:13:31 +00001344.. option:: -mcompact-branches=[values]
1345
1346 Control the usage of compact branches for MIPSR6.
1347
1348 Valid values are: ``never``, ``optimal`` and ``always``.
1349 The default value is ``optimal`` which generates compact branches
1350 when a delay slot cannot be filled. ``never`` disables the usage of
1351 compact branches and ``always`` generates compact branches whenever
1352 possible.
1353
Yunzhong Gaoeecc9e972015-12-10 01:37:18 +00001354**-f[no-]max-type-align=[number]**
Fariborz Jahanianbcd82af2014-08-05 18:37:48 +00001355 Instruct the code generator to not enforce a higher alignment than the given
1356 number (of bytes) when accessing memory via an opaque pointer or reference.
1357 This cap is ignored when directly accessing a variable or when the pointee
1358 type has an explicit “aligned” attribute.
1359
1360 The value should usually be determined by the properties of the system allocator.
1361 Some builtin types, especially vector types, have very high natural alignments;
1362 when working with values of those types, Clang usually wants to use instructions
1363 that take advantage of that alignment. However, many system allocators do
1364 not promise to return memory that is more than 8-byte or 16-byte-aligned. Use
1365 this option to limit the alignment that the compiler can assume for an arbitrary
1366 pointer, which may point onto the heap.
1367
1368 This option does not affect the ABI alignment of types; the layout of structs and
1369 unions and the value returned by the alignof operator remain the same.
1370
1371 This option can be overridden on a case-by-case basis by putting an explicit
1372 “aligned” alignment on a struct, union, or typedef. For example:
1373
1374 .. code-block:: console
1375
1376 #include <immintrin.h>
1377 // Make an aligned typedef of the AVX-512 16-int vector type.
1378 typedef __v16si __aligned_v16si __attribute__((aligned(64)));
1379
1380 void initialize_vector(__aligned_v16si *v) {
1381 // The compiler may assume that ‘v’ is 64-byte aligned, regardless of the
Yunzhong Gaoeecc9e972015-12-10 01:37:18 +00001382 // value of -fmax-type-align.
Fariborz Jahanianbcd82af2014-08-05 18:37:48 +00001383 }
1384
Silviu Barangaf9671dd2013-10-21 10:54:53 +00001385
Bob Wilson3f2ed172014-06-17 00:45:30 +00001386Profile Guided Optimization
1387---------------------------
1388
1389Profile information enables better optimization. For example, knowing that a
1390branch is taken very frequently helps the compiler make better decisions when
1391ordering basic blocks. Knowing that a function ``foo`` is called more
Eric Christopherc61c9b62018-01-31 19:52:58 +00001392frequently than another function ``bar`` helps the inliner. Optimization
1393levels ``-O2`` and above are recommended for use of profile guided optimization.
Bob Wilson3f2ed172014-06-17 00:45:30 +00001394
1395Clang supports profile guided optimization with two different kinds of
1396profiling. A sampling profiler can generate a profile with very low runtime
1397overhead, or you can build an instrumented version of the code that collects
1398more detailed profile information. Both kinds of profiles can provide execution
1399counts for instructions in the code and information on branches taken and
1400function invocation.
1401
1402Regardless of which kind of profiling you use, be careful to collect profiles
1403by running your code with inputs that are representative of the typical
1404behavior. Code that is not exercised in the profile will be optimized as if it
1405is unimportant, and the compiler may make poor optimization choices for code
1406that is disproportionately used while profiling.
1407
Diego Novillo46ab35d2015-05-28 21:30:04 +00001408Differences Between Sampling and Instrumentation
1409^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1410
1411Although both techniques are used for similar purposes, there are important
1412differences between the two:
1413
14141. Profile data generated with one cannot be used by the other, and there is no
1415 conversion tool that can convert one to the other. So, a profile generated
1416 via ``-fprofile-instr-generate`` must be used with ``-fprofile-instr-use``.
1417 Similarly, sampling profiles generated by external profilers must be
1418 converted and used with ``-fprofile-sample-use``.
1419
14202. Instrumentation profile data can be used for code coverage analysis and
1421 optimization.
1422
14233. Sampling profiles can only be used for optimization. They cannot be used for
1424 code coverage analysis. Although it would be technically possible to use
1425 sampling profiles for code coverage, sample-based profiles are too
1426 coarse-grained for code coverage purposes; it would yield poor results.
1427
14284. Sampling profiles must be generated by an external tool. The profile
1429 generated by that tool must then be converted into a format that can be read
1430 by LLVM. The section on sampling profilers describes one of the supported
1431 sampling profile formats.
1432
1433
Bob Wilson3f2ed172014-06-17 00:45:30 +00001434Using Sampling Profilers
1435^^^^^^^^^^^^^^^^^^^^^^^^
Diego Novilloa5256bf2014-04-23 15:21:07 +00001436
1437Sampling profilers are used to collect runtime information, such as
1438hardware counters, while your application executes. They are typically
Diego Novillo8ebff322014-04-23 15:21:20 +00001439very efficient and do not incur a large runtime overhead. The
Diego Novilloa5256bf2014-04-23 15:21:07 +00001440sample data collected by the profiler can be used during compilation
Diego Novillo8ebff322014-04-23 15:21:20 +00001441to determine what the most executed areas of the code are.
Diego Novilloa5256bf2014-04-23 15:21:07 +00001442
Diego Novilloa5256bf2014-04-23 15:21:07 +00001443Using the data from a sample profiler requires some changes in the way
1444a program is built. Before the compiler can use profiling information,
1445the code needs to execute under the profiler. The following is the
1446usual build cycle when using sample profilers for optimization:
1447
14481. Build the code with source line table information. You can use all the
1449 usual build flags that you always build your application with. The only
Diego Novillo8ebff322014-04-23 15:21:20 +00001450 requirement is that you add ``-gline-tables-only`` or ``-g`` to the
Diego Novilloa5256bf2014-04-23 15:21:07 +00001451 command line. This is important for the profiler to be able to map
1452 instructions back to source line locations.
1453
1454 .. code-block:: console
1455
1456 $ clang++ -O2 -gline-tables-only code.cc -o code
1457
14582. Run the executable under a sampling profiler. The specific profiler
1459 you use does not really matter, as long as its output can be converted
1460 into the format that the LLVM optimizer understands. Currently, there
1461 exists a conversion tool for the Linux Perf profiler
1462 (https://perf.wiki.kernel.org/), so these examples assume that you
1463 are using Linux Perf to profile your code.
1464
1465 .. code-block:: console
1466
1467 $ perf record -b ./code
1468
1469 Note the use of the ``-b`` flag. This tells Perf to use the Last Branch
1470 Record (LBR) to record call chains. While this is not strictly required,
1471 it provides better call information, which improves the accuracy of
1472 the profile data.
1473
14743. Convert the collected profile data to LLVM's sample profile format.
1475 This is currently supported via the AutoFDO converter ``create_llvm_prof``.
1476 It is available at http://github.com/google/autofdo. Once built and
1477 installed, you can convert the ``perf.data`` file to LLVM using
1478 the command:
1479
1480 .. code-block:: console
1481
1482 $ create_llvm_prof --binary=./code --out=code.prof
1483
Diego Novillo9e430842014-04-23 15:21:23 +00001484 This will read ``perf.data`` and the binary file ``./code`` and emit
Diego Novilloa5256bf2014-04-23 15:21:07 +00001485 the profile data in ``code.prof``. Note that if you ran ``perf``
1486 without the ``-b`` flag, you need to use ``--use_lbr=false`` when
1487 calling ``create_llvm_prof``.
1488
14894. Build the code again using the collected profile. This step feeds
1490 the profile back to the optimizers. This should result in a binary
Diego Novillo8ebff322014-04-23 15:21:20 +00001491 that executes faster than the original one. Note that you are not
1492 required to build the code with the exact same arguments that you
1493 used in the first step. The only requirement is that you build the code
1494 with ``-gline-tables-only`` and ``-fprofile-sample-use``.
Diego Novilloa5256bf2014-04-23 15:21:07 +00001495
1496 .. code-block:: console
1497
1498 $ clang++ -O2 -gline-tables-only -fprofile-sample-use=code.prof code.cc -o code
1499
1500
Diego Novillo46ab35d2015-05-28 21:30:04 +00001501Sample Profile Formats
1502""""""""""""""""""""""
Diego Novilloa5256bf2014-04-23 15:21:07 +00001503
Diego Novillo46ab35d2015-05-28 21:30:04 +00001504Since external profilers generate profile data in a variety of custom formats,
1505the data generated by the profiler must be converted into a format that can be
1506read by the backend. LLVM supports three different sample profile formats:
Diego Novilloa5256bf2014-04-23 15:21:07 +00001507
Diego Novillo46ab35d2015-05-28 21:30:04 +000015081. ASCII text. This is the easiest one to generate. The file is divided into
1509 sections, which correspond to each of the functions with profile
Diego Novillo33452762015-10-14 18:37:39 +00001510 information. The format is described below. It can also be generated from
1511 the binary or gcov formats using the ``llvm-profdata`` tool.
Diego Novilloe0d289e2015-05-22 16:05:07 +00001512
Diego Novillo46ab35d2015-05-28 21:30:04 +000015132. Binary encoding. This uses a more efficient encoding that yields smaller
Diego Novillo33452762015-10-14 18:37:39 +00001514 profile files. This is the format generated by the ``create_llvm_prof`` tool
1515 in http://github.com/google/autofdo.
Diego Novillo46ab35d2015-05-28 21:30:04 +00001516
15173. GCC encoding. This is based on the gcov format, which is accepted by GCC. It
Diego Novillo33452762015-10-14 18:37:39 +00001518 is only interesting in environments where GCC and Clang co-exist. This
1519 encoding is only generated by the ``create_gcov`` tool in
1520 http://github.com/google/autofdo. It can be read by LLVM and
1521 ``llvm-profdata``, but it cannot be generated by either.
Diego Novillo46ab35d2015-05-28 21:30:04 +00001522
1523If you are using Linux Perf to generate sampling profiles, you can use the
1524conversion tool ``create_llvm_prof`` described in the previous section.
1525Otherwise, you will need to write a conversion tool that converts your
1526profiler's native format into one of these three.
1527
1528
1529Sample Profile Text Format
1530""""""""""""""""""""""""""
1531
1532This section describes the ASCII text format for sampling profiles. It is,
1533arguably, the easiest one to generate. If you are interested in generating any
Sylvestre Ledru6fd88392017-08-27 17:34:06 +00001534of the other two, consult the ``ProfileData`` library in LLVM's source tree
Diego Novillo843dc6f2015-10-19 15:53:17 +00001535(specifically, ``include/llvm/ProfileData/SampleProfReader.h``).
Diego Novilloa5256bf2014-04-23 15:21:07 +00001536
1537.. code-block:: console
1538
1539 function1:total_samples:total_head_samples
Diego Novillo33452762015-10-14 18:37:39 +00001540 offset1[.discriminator]: number_of_samples [fn1:num fn2:num ... ]
1541 offset2[.discriminator]: number_of_samples [fn3:num fn4:num ... ]
1542 ...
1543 offsetN[.discriminator]: number_of_samples [fn5:num fn6:num ... ]
1544 offsetA[.discriminator]: fnA:num_of_total_samples
1545 offsetA1[.discriminator]: number_of_samples [fn7:num fn8:num ... ]
1546 offsetA1[.discriminator]: number_of_samples [fn9:num fn10:num ... ]
1547 offsetB[.discriminator]: fnB:num_of_total_samples
1548 offsetB1[.discriminator]: number_of_samples [fn11:num fn12:num ... ]
Diego Novilloa5256bf2014-04-23 15:21:07 +00001549
Sylvestre Ledru6fd88392017-08-27 17:34:06 +00001550This is a nested tree in which the indentation represents the nesting level
Diego Novillo33452762015-10-14 18:37:39 +00001551of the inline stack. There are no blank lines in the file. And the spacing
1552within a single line is fixed. Additional spaces will result in an error
1553while reading the file.
1554
1555Any line starting with the '#' character is completely ignored.
1556
1557Inlined calls are represented with indentation. The Inline stack is a
1558stack of source locations in which the top of the stack represents the
1559leaf function, and the bottom of the stack represents the actual
1560symbol to which the instruction belongs.
Diego Novillo8ebff322014-04-23 15:21:20 +00001561
Diego Novilloa5256bf2014-04-23 15:21:07 +00001562Function names must be mangled in order for the profile loader to
1563match them in the current translation unit. The two numbers in the
1564function header specify how many total samples were accumulated in the
1565function (first number), and the total number of samples accumulated
Diego Novillo8ebff322014-04-23 15:21:20 +00001566in the prologue of the function (second number). This head sample
1567count provides an indicator of how frequently the function is invoked.
Diego Novilloa5256bf2014-04-23 15:21:07 +00001568
Diego Novillo33452762015-10-14 18:37:39 +00001569There are two types of lines in the function body.
1570
1571- Sampled line represents the profile information of a source location.
1572 ``offsetN[.discriminator]: number_of_samples [fn5:num fn6:num ... ]``
1573
1574- Callsite line represents the profile information of an inlined callsite.
1575 ``offsetA[.discriminator]: fnA:num_of_total_samples``
1576
Diego Novilloa5256bf2014-04-23 15:21:07 +00001577Each sampled line may contain several items. Some are optional (marked
1578below):
1579
1580a. Source line offset. This number represents the line number
1581 in the function where the sample was collected. The line number is
1582 always relative to the line where symbol of the function is
1583 defined. So, if the function has its header at line 280, the offset
1584 13 is at line 293 in the file.
1585
Diego Novillo897c59c2014-04-23 15:21:21 +00001586 Note that this offset should never be a negative number. This could
1587 happen in cases like macros. The debug machinery will register the
1588 line number at the point of macro expansion. So, if the macro was
1589 expanded in a line before the start of the function, the profile
1590 converter should emit a 0 as the offset (this means that the optimizers
1591 will not be able to associate a meaningful weight to the instructions
1592 in the macro).
1593
Diego Novilloa5256bf2014-04-23 15:21:07 +00001594b. [OPTIONAL] Discriminator. This is used if the sampled program
1595 was compiled with DWARF discriminator support
Diego Novillo8ebff322014-04-23 15:21:20 +00001596 (http://wiki.dwarfstd.org/index.php?title=Path_Discriminators).
Diego Novillo897c59c2014-04-23 15:21:21 +00001597 DWARF discriminators are unsigned integer values that allow the
1598 compiler to distinguish between multiple execution paths on the
1599 same source line location.
Diego Novilloa5256bf2014-04-23 15:21:07 +00001600
Diego Novillo8ebff322014-04-23 15:21:20 +00001601 For example, consider the line of code ``if (cond) foo(); else bar();``.
1602 If the predicate ``cond`` is true 80% of the time, then the edge
1603 into function ``foo`` should be considered to be taken most of the
1604 time. But both calls to ``foo`` and ``bar`` are at the same source
1605 line, so a sample count at that line is not sufficient. The
1606 compiler needs to know which part of that line is taken more
1607 frequently.
1608
1609 This is what discriminators provide. In this case, the calls to
1610 ``foo`` and ``bar`` will be at the same line, but will have
1611 different discriminator values. This allows the compiler to correctly
1612 set edge weights into ``foo`` and ``bar``.
1613
1614c. Number of samples. This is an integer quantity representing the
1615 number of samples collected by the profiler at this source
1616 location.
Diego Novilloa5256bf2014-04-23 15:21:07 +00001617
1618d. [OPTIONAL] Potential call targets and samples. If present, this
1619 line contains a call instruction. This models both direct and
Diego Novilloa5256bf2014-04-23 15:21:07 +00001620 number of samples. For example,
1621
1622 .. code-block:: console
1623
1624 130: 7 foo:3 bar:2 baz:7
1625
1626 The above means that at relative line offset 130 there is a call
Diego Novillo8ebff322014-04-23 15:21:20 +00001627 instruction that calls one of ``foo()``, ``bar()`` and ``baz()``,
1628 with ``baz()`` being the relatively more frequently called target.
Diego Novilloa5256bf2014-04-23 15:21:07 +00001629
Diego Novillo33452762015-10-14 18:37:39 +00001630As an example, consider a program with the call chain ``main -> foo -> bar``.
1631When built with optimizations enabled, the compiler may inline the
1632calls to ``bar`` and ``foo`` inside ``main``. The generated profile
1633could then be something like this:
1634
1635.. code-block:: console
1636
1637 main:35504:0
1638 1: _Z3foov:35504
1639 2: _Z32bari:31977
1640 1.1: 31977
1641 2: 0
1642
1643This profile indicates that there were a total of 35,504 samples
1644collected in main. All of those were at line 1 (the call to ``foo``).
1645Of those, 31,977 were spent inside the body of ``bar``. The last line
1646of the profile (``2: 0``) corresponds to line 2 inside ``main``. No
1647samples were collected there.
Diego Novilloa5256bf2014-04-23 15:21:07 +00001648
Bob Wilson3f2ed172014-06-17 00:45:30 +00001649Profiling with Instrumentation
1650^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1651
1652Clang also supports profiling via instrumentation. This requires building a
1653special instrumented version of the code and has some runtime
1654overhead during the profiling, but it provides more detailed results than a
1655sampling profiler. It also provides reproducible results, at least to the
1656extent that the code behaves consistently across runs.
1657
1658Here are the steps for using profile guided optimization with
1659instrumentation:
1660
16611. Build an instrumented version of the code by compiling and linking with the
1662 ``-fprofile-instr-generate`` option.
1663
1664 .. code-block:: console
1665
1666 $ clang++ -O2 -fprofile-instr-generate code.cc -o code
1667
16682. Run the instrumented executable with inputs that reflect the typical usage.
1669 By default, the profile data will be written to a ``default.profraw`` file
Xinliang David Li7cd5e382016-07-20 23:32:50 +00001670 in the current directory. You can override that default by using option
1671 ``-fprofile-instr-generate=`` or by setting the ``LLVM_PROFILE_FILE``
1672 environment variable to specify an alternate file. If non-default file name
1673 is specified by both the environment variable and the command line option,
1674 the environment variable takes precedence. The file name pattern specified
1675 can include different modifiers: ``%p``, ``%h``, and ``%m``.
1676
Bob Wilson3f2ed172014-06-17 00:45:30 +00001677 Any instance of ``%p`` in that file name will be replaced by the process
1678 ID, so that you can easily distinguish the profile output from multiple
1679 runs.
1680
1681 .. code-block:: console
1682
1683 $ LLVM_PROFILE_FILE="code-%p.profraw" ./code
1684
Xinliang David Li7cd5e382016-07-20 23:32:50 +00001685 The modifier ``%h`` can be used in scenarios where the same instrumented
1686 binary is run in multiple different host machines dumping profile data
1687 to a shared network based storage. The ``%h`` specifier will be substituted
1688 with the hostname so that profiles collected from different hosts do not
1689 clobber each other.
1690
1691 While the use of ``%p`` specifier can reduce the likelihood for the profiles
1692 dumped from different processes to clobber each other, such clobbering can still
1693 happen because of the ``pid`` re-use by the OS. Another side-effect of using
1694 ``%p`` is that the storage requirement for raw profile data files is greatly
1695 increased. To avoid issues like this, the ``%m`` specifier can used in the profile
1696 name. When this specifier is used, the profiler runtime will substitute ``%m``
1697 with a unique integer identifier associated with the instrumented binary. Additionally,
1698 multiple raw profiles dumped from different processes that share a file system (can be
1699 on different hosts) will be automatically merged by the profiler runtime during the
1700 dumping. If the program links in multiple instrumented shared libraries, each library
1701 will dump the profile data into its own profile data file (with its unique integer
1702 id embedded in the profile name). Note that the merging enabled by ``%m`` is for raw
1703 profile data generated by profiler runtime. The resulting merged "raw" profile data
1704 file still needs to be converted to a different format expected by the compiler (
1705 see step 3 below).
1706
1707 .. code-block:: console
1708
1709 $ LLVM_PROFILE_FILE="code-%m.profraw" ./code
1710
1711
Bob Wilson3f2ed172014-06-17 00:45:30 +000017123. Combine profiles from multiple runs and convert the "raw" profile format to
Diego Novillo46ab35d2015-05-28 21:30:04 +00001713 the input expected by clang. Use the ``merge`` command of the
1714 ``llvm-profdata`` tool to do this.
Bob Wilson3f2ed172014-06-17 00:45:30 +00001715
1716 .. code-block:: console
1717
1718 $ llvm-profdata merge -output=code.profdata code-*.profraw
1719
1720 Note that this step is necessary even when there is only one "raw" profile,
1721 since the merge operation also changes the file format.
1722
17234. Build the code again using the ``-fprofile-instr-use`` option to specify the
1724 collected profile data.
1725
1726 .. code-block:: console
1727
1728 $ clang++ -O2 -fprofile-instr-use=code.profdata code.cc -o code
1729
1730 You can repeat step 4 as often as you like without regenerating the
1731 profile. As you make changes to your code, clang may no longer be able to
1732 use the profile data. It will warn you when this happens.
1733
Sean Silvaa834ff22016-07-16 02:54:58 +00001734Profile generation using an alternative instrumentation method can be
1735controlled by the GCC-compatible flags ``-fprofile-generate`` and
1736``-fprofile-use``. Although these flags are semantically equivalent to
1737their GCC counterparts, they *do not* handle GCC-compatible profiles.
1738They are only meant to implement GCC's semantics with respect to
1739profile creation and use.
Diego Novillo578caf52015-07-09 17:23:53 +00001740
1741.. option:: -fprofile-generate[=<dirname>]
1742
Sean Silvaa834ff22016-07-16 02:54:58 +00001743 The ``-fprofile-generate`` and ``-fprofile-generate=`` flags will use
Joel Galenson267ea722018-05-07 16:23:46 +00001744 an alternative instrumentation method for profile generation. When
Sean Silvaa834ff22016-07-16 02:54:58 +00001745 given a directory name, it generates the profile file
Xinliang David Lib7b335a2016-07-22 22:25:01 +00001746 ``default_%m.profraw`` in the directory named ``dirname`` if specified.
1747 If ``dirname`` does not exist, it will be created at runtime. ``%m`` specifier
Joel Galenson267ea722018-05-07 16:23:46 +00001748 will be substituted with a unique id documented in step 2 above. In other words,
Xinliang David Lib7b335a2016-07-22 22:25:01 +00001749 with ``-fprofile-generate[=<dirname>]`` option, the "raw" profile data automatic
1750 merging is turned on by default, so there will no longer any risk of profile
1751 clobbering from different running processes. For example,
Diego Novillo578caf52015-07-09 17:23:53 +00001752
1753 .. code-block:: console
1754
1755 $ clang++ -O2 -fprofile-generate=yyy/zzz code.cc -o code
1756
1757 When ``code`` is executed, the profile will be written to the file
Xinliang David Lib7b335a2016-07-22 22:25:01 +00001758 ``yyy/zzz/default_xxxx.profraw``.
Diego Novillo578caf52015-07-09 17:23:53 +00001759
Xinliang David Lib7b335a2016-07-22 22:25:01 +00001760 To generate the profile data file with the compiler readable format, the
1761 ``llvm-profdata`` tool can be used with the profile directory as the input:
Diego Novillo578caf52015-07-09 17:23:53 +00001762
Xinliang David Lib7b335a2016-07-22 22:25:01 +00001763 .. code-block:: console
Diego Novillo578caf52015-07-09 17:23:53 +00001764
Xinliang David Lib7b335a2016-07-22 22:25:01 +00001765 $ llvm-profdata merge -output=code.profdata yyy/zzz/
1766
1767 If the user wants to turn off the auto-merging feature, or simply override the
1768 the profile dumping path specified at command line, the environment variable
1769 ``LLVM_PROFILE_FILE`` can still be used to override
1770 the directory and filename for the profile file at runtime.
Diego Novillo578caf52015-07-09 17:23:53 +00001771
1772.. option:: -fprofile-use[=<pathname>]
1773
1774 Without any other arguments, ``-fprofile-use`` behaves identically to
1775 ``-fprofile-instr-use``. Otherwise, if ``pathname`` is the full path to a
1776 profile file, it reads from that file. If ``pathname`` is a directory name,
1777 it reads from ``pathname/default.profdata``.
1778
Diego Novillo758f3f52015-08-05 21:49:51 +00001779Disabling Instrumentation
1780^^^^^^^^^^^^^^^^^^^^^^^^^
1781
1782In certain situations, it may be useful to disable profile generation or use
1783for specific files in a build, without affecting the main compilation flags
1784used for the other files in the project.
1785
1786In these cases, you can use the flag ``-fno-profile-instr-generate`` (or
1787``-fno-profile-generate``) to disable profile generation, and
1788``-fno-profile-instr-use`` (or ``-fno-profile-use``) to disable profile use.
1789
1790Note that these flags should appear after the corresponding profile
1791flags to have an effect.
Bob Wilson3f2ed172014-06-17 00:45:30 +00001792
Paul Robinson0334a042015-12-19 19:41:48 +00001793Controlling Debug Information
1794-----------------------------
1795
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001796Controlling Size of Debug Information
Paul Robinson0334a042015-12-19 19:41:48 +00001797^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001798
1799Debug info kind generated by Clang can be set by one of the flags listed
1800below. If multiple flags are present, the last one is used.
1801
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001802.. option:: -g0
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001803
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001804 Don't generate any debug info (default).
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001805
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001806.. option:: -gline-tables-only
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001807
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001808 Generate line number tables only.
1809
1810 This kind of debug info allows to obtain stack traces with function names,
1811 file names and line numbers (by such tools as ``gdb`` or ``addr2line``). It
1812 doesn't contain any other data (e.g. description of local variables or
1813 function parameters).
1814
Adrian Prantl4ad03dc2014-06-13 23:35:54 +00001815.. option:: -fstandalone-debug
Adrian Prantl36b80672014-06-13 21:12:31 +00001816
1817 Clang supports a number of optimizations to reduce the size of debug
1818 information in the binary. They work based on the assumption that
1819 the debug type information can be spread out over multiple
1820 compilation units. For instance, Clang will not emit type
1821 definitions for types that are not needed by a module and could be
1822 replaced with a forward declaration. Further, Clang will only emit
1823 type info for a dynamic C++ class in the module that contains the
1824 vtable for the class.
1825
Adrian Prantl4ad03dc2014-06-13 23:35:54 +00001826 The **-fstandalone-debug** option turns off these optimizations.
Adrian Prantl36b80672014-06-13 21:12:31 +00001827 This is useful when working with 3rd-party libraries that don't come
1828 with debug information. Note that Clang will never emit type
1829 information for types that are not referenced at all by the program.
1830
Adrian Prantl4ad03dc2014-06-13 23:35:54 +00001831.. option:: -fno-standalone-debug
1832
1833 On Darwin **-fstandalone-debug** is enabled by default. The
1834 **-fno-standalone-debug** option can be used to get to turn on the
1835 vtable-based optimization described above.
1836
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001837.. option:: -g
1838
1839 Generate complete debug info.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001840
Amjad Aboud546bc112017-02-09 22:07:24 +00001841Controlling Macro Debug Info Generation
1842^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1843
1844Debug info for C preprocessor macros increases the size of debug information in
1845the binary. Macro debug info generated by Clang can be controlled by the flags
1846listed below.
1847
1848.. option:: -fdebug-macro
1849
1850 Generate debug info for preprocessor macros. This flag is discarded when
1851 **-g0** is enabled.
1852
1853.. option:: -fno-debug-macro
1854
1855 Do not generate debug info for preprocessor macros (default).
1856
Paul Robinson0334a042015-12-19 19:41:48 +00001857Controlling Debugger "Tuning"
1858^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1859
1860While Clang generally emits standard DWARF debug info (http://dwarfstd.org),
1861different debuggers may know how to take advantage of different specific DWARF
1862features. You can "tune" the debug info for one of several different debuggers.
1863
1864.. option:: -ggdb, -glldb, -gsce
1865
Paul Robinson8ce9b442016-08-15 18:45:52 +00001866 Tune the debug info for the ``gdb``, ``lldb``, or Sony PlayStation\ |reg|
Paul Robinson0334a042015-12-19 19:41:48 +00001867 debugger, respectively. Each of these options implies **-g**. (Therefore, if
1868 you want both **-gline-tables-only** and debugger tuning, the tuning option
1869 must come first.)
1870
1871
Eric Fiselier123c7492018-02-07 18:36:51 +00001872Controlling LLVM IR Output
1873--------------------------
1874
1875Controlling Value Names in LLVM IR
1876^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1877
1878Emitting value names in LLVM IR increases the size and verbosity of the IR.
1879By default, value names are only emitted in assertion-enabled builds of Clang.
1880However, when reading IR it can be useful to re-enable the emission of value
1881names to improve readability.
1882
1883.. option:: -fdiscard-value-names
1884
1885 Discard value names when generating LLVM IR.
1886
1887.. option:: -fno-discard-value-names
1888
1889 Do not discard value names when generating LLVM IR. This option can be used
1890 to re-enable names for release builds of Clang.
1891
1892
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00001893Comment Parsing Options
Dmitri Gribenko28bfb482014-03-06 16:32:09 +00001894-----------------------
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00001895
1896Clang parses Doxygen and non-Doxygen style documentation comments and attaches
1897them to the appropriate declaration nodes. By default, it only parses
1898Doxygen-style comments and ignores ordinary comments starting with ``//`` and
1899``/*``.
1900
Dmitri Gribenko28bfb482014-03-06 16:32:09 +00001901.. option:: -Wdocumentation
1902
1903 Emit warnings about use of documentation comments. This warning group is off
1904 by default.
1905
1906 This includes checking that ``\param`` commands name parameters that actually
1907 present in the function signature, checking that ``\returns`` is used only on
1908 functions that actually return a value etc.
1909
1910.. option:: -Wno-documentation-unknown-command
1911
1912 Don't warn when encountering an unknown Doxygen command.
1913
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00001914.. option:: -fparse-all-comments
1915
1916 Parse all comments as documentation comments (including ordinary comments
1917 starting with ``//`` and ``/*``).
1918
Dmitri Gribenko28bfb482014-03-06 16:32:09 +00001919.. option:: -fcomment-block-commands=[commands]
1920
1921 Define custom documentation commands as block commands. This allows Clang to
1922 construct the correct AST for these custom commands, and silences warnings
1923 about unknown commands. Several commands must be separated by a comma
1924 *without trailing space*; e.g. ``-fcomment-block-commands=foo,bar`` defines
1925 custom commands ``\foo`` and ``\bar``.
1926
1927 It is also possible to use ``-fcomment-block-commands`` several times; e.g.
1928 ``-fcomment-block-commands=foo -fcomment-block-commands=bar`` does the same
1929 as above.
1930
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001931.. _c:
1932
1933C Language Features
1934===================
1935
1936The support for standard C in clang is feature-complete except for the
1937C99 floating-point pragmas.
1938
1939Extensions supported by clang
1940-----------------------------
1941
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001942See :doc:`LanguageExtensions`.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001943
1944Differences between various standard modes
1945------------------------------------------
1946
1947clang supports the -std option, which changes what language mode clang
Aaron Ballman567d9a32018-03-12 13:09:13 +00001948uses. The supported modes for C are c89, gnu89, c99, gnu99, c11, gnu11,
1949c17, gnu17, and various aliases for those modes. If no -std option is
Richard Smithab506ad2014-10-20 23:26:58 +00001950specified, clang defaults to gnu11 mode. Many C99 and C11 features are
1951supported in earlier modes as a conforming extension, with a warning. Use
1952``-pedantic-errors`` to request an error if a feature from a later standard
1953revision is used in an earlier mode.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001954
1955Differences between all ``c*`` and ``gnu*`` modes:
1956
1957- ``c*`` modes define "``__STRICT_ANSI__``".
1958- Target-specific defines not prefixed by underscores, like "linux",
1959 are defined in ``gnu*`` modes.
1960- Trigraphs default to being off in ``gnu*`` modes; they can be enabled by
1961 the -trigraphs option.
1962- The parser recognizes "asm" and "typeof" as keywords in ``gnu*`` modes;
1963 the variants "``__asm__``" and "``__typeof__``" are recognized in all
1964 modes.
1965- The Apple "blocks" extension is recognized by default in ``gnu*`` modes
1966 on some platforms; it can be enabled in any mode with the "-fblocks"
1967 option.
1968- Arrays that are VLA's according to the standard, but which can be
1969 constant folded by the frontend are treated as fixed size arrays.
1970 This occurs for things like "int X[(1, 2)];", which is technically a
1971 VLA. ``c*`` modes are strictly compliant and treat these as VLAs.
1972
1973Differences between ``*89`` and ``*99`` modes:
1974
1975- The ``*99`` modes default to implementing "inline" as specified in C99,
1976 while the ``*89`` modes implement the GNU version. This can be
1977 overridden for individual functions with the ``__gnu_inline__``
1978 attribute.
1979- Digraphs are not recognized in c89 mode.
1980- The scope of names defined inside a "for", "if", "switch", "while",
1981 or "do" statement is different. (example: "``if ((struct x {int
1982 x;}*)0) {}``".)
1983- ``__STDC_VERSION__`` is not defined in ``*89`` modes.
1984- "inline" is not recognized as a keyword in c89 mode.
1985- "restrict" is not recognized as a keyword in ``*89`` modes.
1986- Commas are allowed in integer constant expressions in ``*99`` modes.
1987- Arrays which are not lvalues are not implicitly promoted to pointers
1988 in ``*89`` modes.
1989- Some warnings are different.
1990
Richard Smithab506ad2014-10-20 23:26:58 +00001991Differences between ``*99`` and ``*11`` modes:
1992
1993- Warnings for use of C11 features are disabled.
1994- ``__STDC_VERSION__`` is defined to ``201112L`` rather than ``199901L``.
1995
Aaron Ballman567d9a32018-03-12 13:09:13 +00001996Differences between ``*11`` and ``*17`` modes:
1997
1998- ``__STDC_VERSION__`` is defined to ``201710L`` rather than ``201112L``.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001999
2000GCC extensions not implemented yet
2001----------------------------------
2002
2003clang tries to be compatible with gcc as much as possible, but some gcc
2004extensions are not implemented yet:
2005
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002006- clang does not support decimal floating point types (``_Decimal32`` and
2007 friends) or fixed-point types (``_Fract`` and friends); nobody has
2008 expressed interest in these features yet, so it's hard to say when
2009 they will be implemented.
2010- clang does not support nested functions; this is a complex feature
2011 which is infrequently used, so it is unlikely to be implemented
2012 anytime soon. In C++11 it can be emulated by assigning lambda
2013 functions to local variables, e.g:
2014
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00002015 .. code-block:: cpp
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002016
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00002017 auto const local_function = [&](int parameter) {
2018 // Do something
2019 };
2020 ...
2021 local_function(1);
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002022
Michael Kuperstein94b25ec2016-12-12 19:11:39 +00002023- clang only supports global register variables when the register specified
2024 is non-allocatable (e.g. the stack pointer). Support for general global
2025 register variables is unlikely to be implemented soon because it requires
2026 additional LLVM backend support.
Andrey Bokhanko5dfd5b62016-02-11 13:27:02 +00002027- clang does not support static initialization of flexible array
2028 members. This appears to be a rarely used extension, but could be
2029 implemented pending user demand.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002030- clang does not support
2031 ``__builtin_va_arg_pack``/``__builtin_va_arg_pack_len``. This is
2032 used rarely, but in some potentially interesting places, like the
2033 glibc headers, so it may be implemented pending user demand. Note
2034 that because clang pretends to be like GCC 4.2, and this extension
2035 was introduced in 4.3, the glibc headers will not try to use this
2036 extension with clang at the moment.
2037- clang does not support the gcc extension for forward-declaring
2038 function parameters; this has not shown up in any real-world code
2039 yet, though, so it might never be implemented.
2040
2041This is not a complete list; if you find an unsupported extension
2042missing from this list, please send an e-mail to cfe-dev. This list
2043currently excludes C++; see :ref:`C++ Language Features <cxx>`. Also, this
2044list does not include bugs in mostly-implemented features; please see
2045the `bug
Ismail Donmezcb17fbb2017-02-17 08:26:54 +00002046tracker <https://bugs.llvm.org/buglist.cgi?quicksearch=product%3Aclang+component%3A-New%2BBugs%2CAST%2CBasic%2CDriver%2CHeaders%2CLLVM%2BCodeGen%2Cparser%2Cpreprocessor%2CSemantic%2BAnalyzer>`_
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002047for known existing bugs (FIXME: Is there a section for bug-reporting
2048guidelines somewhere?).
2049
2050Intentionally unsupported GCC extensions
2051----------------------------------------
2052
2053- clang does not support the gcc extension that allows variable-length
2054 arrays in structures. This is for a few reasons: one, it is tricky to
2055 implement, two, the extension is completely undocumented, and three,
2056 the extension appears to be rarely used. Note that clang *does*
2057 support flexible array members (arrays with a zero or unspecified
2058 size at the end of a structure).
2059- clang does not have an equivalent to gcc's "fold"; this means that
2060 clang doesn't accept some constructs gcc might accept in contexts
2061 where a constant expression is required, like "x-x" where x is a
2062 variable.
2063- clang does not support ``__builtin_apply`` and friends; this extension
2064 is extremely obscure and difficult to implement reliably.
2065
2066.. _c_ms:
2067
2068Microsoft extensions
2069--------------------
2070
Reid Kleckner2a5d34b2016-03-28 20:42:41 +00002071clang has support for many extensions from Microsoft Visual C++. To enable these
2072extensions, use the ``-fms-extensions`` command-line option. This is the default
2073for Windows targets. Clang does not implement every pragma or declspec provided
2074by MSVC, but the popular ones, such as ``__declspec(dllexport)`` and ``#pragma
2075comment(lib)`` are well supported.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002076
Richard Smith48d1b652013-12-12 02:42:17 +00002077clang has a ``-fms-compatibility`` flag that makes clang accept enough
Reid Kleckner993e72a2013-09-20 17:04:25 +00002078invalid C++ to be able to parse most Microsoft headers. For example, it
2079allows `unqualified lookup of dependent base class members
Reid Klecknereb248d72013-09-20 17:54:39 +00002080<http://clang.llvm.org/compatibility.html#dep_lookup_bases>`_, which is
2081a common compatibility issue with clang. This flag is enabled by default
Reid Kleckner993e72a2013-09-20 17:04:25 +00002082for Windows targets.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002083
Richard Smith48d1b652013-12-12 02:42:17 +00002084``-fdelayed-template-parsing`` lets clang delay parsing of function template
2085definitions until the end of a translation unit. This flag is enabled by
2086default for Windows targets.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002087
Reid Kleckner2a5d34b2016-03-28 20:42:41 +00002088For compatibility with existing code that compiles with MSVC, clang defines the
2089``_MSC_VER`` and ``_MSC_FULL_VER`` macros. These default to the values of 1800
2090and 180000000 respectively, making clang look like an early release of Visual
2091C++ 2013. The ``-fms-compatibility-version=`` flag overrides these values. It
2092accepts a dotted version tuple, such as 19.00.23506. Changing the MSVC
2093compatibility version makes clang behave more like that version of MSVC. For
2094example, ``-fms-compatibility-version=19`` will enable C++14 features and define
2095``char16_t`` and ``char32_t`` as builtin types.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002096
2097.. _cxx:
2098
2099C++ Language Features
2100=====================
2101
2102clang fully implements all of standard C++98 except for exported
Richard Smith48d1b652013-12-12 02:42:17 +00002103templates (which were removed in C++11), and all of standard C++11
2104and the current draft standard for C++1y.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002105
2106Controlling implementation limits
2107---------------------------------
2108
Richard Smithb3a14522013-02-22 01:59:51 +00002109.. option:: -fbracket-depth=N
2110
2111 Sets the limit for nested parentheses, brackets, and braces to N. The
2112 default is 256.
2113
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00002114.. option:: -fconstexpr-depth=N
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002115
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00002116 Sets the limit for recursive constexpr function invocations to N. The
2117 default is 512.
2118
Richard Smith869038e2018-07-11 00:34:54 +00002119.. option:: -fconstexpr-steps=N
2120
2121 Sets the limit for the number of full-expressions evaluated in a single
2122 constant expression evaluation. The default is 1048576.
2123
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00002124.. option:: -ftemplate-depth=N
2125
2126 Sets the limit for recursively nested template instantiations to N. The
Richard Smith869038e2018-07-11 00:34:54 +00002127 default is 1024.
Richard Smith79c927b2013-11-06 19:31:51 +00002128
2129.. option:: -foperator-arrow-depth=N
2130
2131 Sets the limit for iterative calls to 'operator->' functions to N. The
2132 default is 256.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002133
2134.. _objc:
2135
2136Objective-C Language Features
2137=============================
2138
2139.. _objcxx:
2140
2141Objective-C++ Language Features
2142===============================
2143
Alexey Bataevae8c17e2015-08-24 05:31:10 +00002144.. _openmp:
2145
2146OpenMP Features
2147===============
2148
2149Clang supports all OpenMP 3.1 directives and clauses. In addition, some
2150features of OpenMP 4.0 are supported. For example, ``#pragma omp simd``,
2151``#pragma omp for simd``, ``#pragma omp parallel for simd`` directives, extended
2152set of atomic constructs, ``proc_bind`` clause for all parallel-based
2153directives, ``depend`` clause for ``#pragma omp task`` directive (except for
2154array sections), ``#pragma omp cancel`` and ``#pragma omp cancellation point``
2155directives, and ``#pragma omp taskgroup`` directive.
2156
Aaron Ballman51fb0312016-07-15 13:13:45 +00002157Use `-fopenmp` to enable OpenMP. Support for OpenMP can be disabled with
2158`-fno-openmp`.
Alexey Bataevae8c17e2015-08-24 05:31:10 +00002159
Alexey Bataevfa4814d2017-12-29 18:27:00 +00002160Use `-fopenmp-simd` to enable OpenMP simd features only, without linking
2161the runtime library; for combined constructs
2162(e.g. ``#pragma omp parallel for simd``) the non-simd directives and clauses
2163will be ignored. This can be disabled with `-fno-openmp-simd`.
2164
Alexey Bataevae8c17e2015-08-24 05:31:10 +00002165Controlling implementation limits
2166---------------------------------
2167
2168.. option:: -fopenmp-use-tls
2169
2170 Controls code generation for OpenMP threadprivate variables. In presence of
2171 this option all threadprivate variables are generated the same way as thread
Aaron Ballman51fb0312016-07-15 13:13:45 +00002172 local variables, using TLS support. If `-fno-openmp-use-tls`
Alexey Bataevae8c17e2015-08-24 05:31:10 +00002173 is provided or target does not support TLS, code generation for threadprivate
2174 variables relies on OpenMP runtime library.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002175
Anastasia Stulova18e165f2017-01-12 17:52:22 +00002176.. _opencl:
2177
2178OpenCL Features
2179===============
2180
2181Clang can be used to compile OpenCL kernels for execution on a device
2182(e.g. GPU). It is possible to compile the kernel into a binary (e.g. for AMD or
2183Nvidia targets) that can be uploaded to run directly on a device (e.g. using
2184`clCreateProgramWithBinary
2185<https://www.khronos.org/registry/OpenCL/specs/opencl-1.1.pdf#111>`_) or
2186into generic bitcode files loadable into other toolchains.
2187
2188Compiling to a binary using the default target from the installation can be done
2189as follows:
2190
2191 .. code-block:: console
2192
2193 $ echo "kernel void k(){}" > test.cl
2194 $ clang test.cl
2195
2196Compiling for a specific target can be done by specifying the triple corresponding
2197to the target, for example:
2198
2199 .. code-block:: console
2200
2201 $ clang -target nvptx64-unknown-unknown test.cl
Tony Tye1a3f3a22018-03-23 18:43:15 +00002202 $ clang -target amdgcn-amd-amdhsa -mcpu=gfx900 test.cl
Anastasia Stulova18e165f2017-01-12 17:52:22 +00002203
2204Compiling to bitcode can be done as follows:
2205
2206 .. code-block:: console
2207
2208 $ clang -c -emit-llvm test.cl
2209
2210This will produce a generic test.bc file that can be used in vendor toolchains
2211to perform machine code generation.
2212
2213Clang currently supports OpenCL C language standards up to v2.0.
2214
2215OpenCL Specific Options
2216-----------------------
2217
2218Most of the OpenCL build options from `the specification v2.0 section 5.8.4
2219<https://www.khronos.org/registry/cl/specs/opencl-2.0.pdf#200>`_ are available.
2220
2221Examples:
2222
2223 .. code-block:: console
2224
2225 $ clang -cl-std=CL2.0 -cl-single-precision-constant test.cl
2226
2227Some extra options are available to support special OpenCL features.
2228
2229.. option:: -finclude-default-header
2230
2231Loads standard includes during compilations. By default OpenCL headers are not
2232loaded and therefore standard library includes are not available. To load them
2233automatically a flag has been added to the frontend (see also :ref:`the section
2234on the OpenCL Header <opencl_header>`):
2235
2236 .. code-block:: console
2237
2238 $ clang -Xclang -finclude-default-header test.cl
2239
2240Alternatively ``-include`` or ``-I`` followed by the path to the header location
2241can be given manually.
2242
2243 .. code-block:: console
2244
2245 $ clang -I<path to clang>/lib/Headers/opencl-c.h test.cl
2246
2247In this case the kernel code should contain ``#include <opencl-c.h>`` just as a
2248regular C include.
2249
Anastasia Stulovab376bee2017-02-16 12:49:29 +00002250.. _opencl_cl_ext:
2251
Anastasia Stulova18e165f2017-01-12 17:52:22 +00002252.. option:: -cl-ext
2253
2254Disables support of OpenCL extensions. All OpenCL targets provide a list
2255of extensions that they support. Clang allows to amend this using the ``-cl-ext``
2256flag with a comma-separated list of extensions prefixed with ``'+'`` or ``'-'``.
2257The syntax: ``-cl-ext=<(['-'|'+']<extension>[,])+>``, where extensions
2258can be either one of `the OpenCL specification extensions
2259<https://www.khronos.org/registry/cl/sdk/2.0/docs/man/xhtml/EXTENSION.html>`_
2260or any known vendor extension. Alternatively, ``'all'`` can be used to enable
2261or disable all known extensions.
2262Example disabling double support for the 64-bit SPIR target:
2263
2264 .. code-block:: console
2265
2266 $ clang -cc1 -triple spir64-unknown-unknown -cl-ext=-cl_khr_fp64 test.cl
2267
2268Enabling all extensions except double support in R600 AMD GPU can be done using:
2269
2270 .. code-block:: console
2271
2272 $ clang -cc1 -triple r600-unknown-unknown -cl-ext=-all,+cl_khr_fp16 test.cl
2273
2274.. _opencl_fake_address_space_map:
2275
2276.. option:: -ffake-address-space-map
2277
2278Overrides the target address space map with a fake map.
2279This allows adding explicit address space IDs to the bitcode for non-segmented
2280memory architectures that don't have separate IDs for each of the OpenCL
2281logical address spaces by default. Passing ``-ffake-address-space-map`` will
2282add/override address spaces of the target compiled for with the following values:
2283``1-global``, ``2-constant``, ``3-local``, ``4-generic``. The private address
2284space is represented by the absence of an address space attribute in the IR (see
2285also :ref:`the section on the address space attribute <opencl_addrsp>`).
2286
2287 .. code-block:: console
2288
2289 $ clang -ffake-address-space-map test.cl
2290
2291Some other flags used for the compilation for C can also be passed while
2292compiling for OpenCL, examples: ``-c``, ``-O<1-4|s>``, ``-o``, ``-emit-llvm``, etc.
2293
2294OpenCL Targets
2295--------------
2296
2297OpenCL targets are derived from the regular Clang target classes. The OpenCL
2298specific parts of the target representation provide address space mapping as
2299well as a set of supported extensions.
2300
2301Specific Targets
2302^^^^^^^^^^^^^^^^
2303
2304There is a set of concrete HW architectures that OpenCL can be compiled for.
2305
2306- For AMD target:
2307
2308 .. code-block:: console
2309
Tony Tye1a3f3a22018-03-23 18:43:15 +00002310 $ clang -target amdgcn-amd-amdhsa -mcpu=gfx900 test.cl
Anastasia Stulova18e165f2017-01-12 17:52:22 +00002311
2312- For Nvidia architectures:
2313
2314 .. code-block:: console
2315
2316 $ clang -target nvptx64-unknown-unknown test.cl
2317
2318
2319Generic Targets
2320^^^^^^^^^^^^^^^
2321
2322- SPIR is available as a generic target to allow portable bitcode to be produced
2323 that can be used across GPU toolchains. The implementation follows `the SPIR
2324 specification <https://www.khronos.org/spir>`_. There are two flavors
2325 available for 32 and 64 bits.
2326
2327 .. code-block:: console
2328
2329 $ clang -target spir-unknown-unknown test.cl
2330 $ clang -target spir64-unknown-unknown test.cl
2331
2332 All known OpenCL extensions are supported in the SPIR targets. Clang will
2333 generate SPIR v1.2 compatible IR for OpenCL versions up to 2.0 and SPIR v2.0
2334 for OpenCL v2.0.
2335
2336- x86 is used by some implementations that are x86 compatible and currently
2337 remains for backwards compatibility (with older implementations prior to
2338 SPIR target support). For "non-SPMD" targets which cannot spawn multiple
2339 work-items on the fly using hardware, which covers practically all non-GPU
2340 devices such as CPUs and DSPs, additional processing is needed for the kernels
2341 to support multiple work-item execution. For this, a 3rd party toolchain,
2342 such as for example `POCL <http://portablecl.org/>`_, can be used.
2343
2344 This target does not support multiple memory segments and, therefore, the fake
2345 address space map can be added using the :ref:`-ffake-address-space-map
2346 <opencl_fake_address_space_map>` flag.
2347
2348.. _opencl_header:
2349
2350OpenCL Header
2351-------------
2352
2353By default Clang will not include standard headers and therefore OpenCL builtin
2354functions and some types (i.e. vectors) are unknown. The default CL header is,
2355however, provided in the Clang installation and can be enabled by passing the
2356``-finclude-default-header`` flag to the Clang frontend.
2357
2358 .. code-block:: console
2359
2360 $ echo "bool is_wg_uniform(int i){return get_enqueued_local_size(i)==get_local_size(i);}" > test.cl
2361 $ clang -Xclang -finclude-default-header -cl-std=CL2.0 test.cl
2362
2363Because the header is very large and long to parse, PCH (:doc:`PCHInternals`)
2364and modules (:doc:`Modules`) are used internally to improve the compilation
2365speed.
2366
2367To enable modules for OpenCL:
2368
2369 .. code-block:: console
2370
2371 $ 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
2372
Anastasia Stulovab376bee2017-02-16 12:49:29 +00002373OpenCL Extensions
2374-----------------
2375
2376All of the ``cl_khr_*`` extensions from `the official OpenCL specification
2377<https://www.khronos.org/registry/OpenCL/sdk/2.0/docs/man/xhtml/EXTENSION.html>`_
2378up to and including version 2.0 are available and set per target depending on the
2379support available in the specific architecture.
2380
2381It is possible to alter the default extensions setting per target using
2382``-cl-ext`` flag. (See :ref:`flags description <opencl_cl_ext>` for more details).
2383
2384Vendor extensions can be added flexibly by declaring the list of types and
2385functions associated with each extensions enclosed within the following
2386compiler pragma directives:
2387
2388 .. code-block:: c
2389
2390 #pragma OPENCL EXTENSION the_new_extension_name : begin
2391 // declare types and functions associated with the extension here
2392 #pragma OPENCL EXTENSION the_new_extension_name : end
2393
2394For example, parsing the following code adds ``my_t`` type and ``my_func``
2395function to the custom ``my_ext`` extension.
2396
2397 .. code-block:: c
2398
2399 #pragma OPENCL EXTENSION my_ext : begin
2400 typedef struct{
2401 int a;
2402 }my_t;
2403 void my_func(my_t);
2404 #pragma OPENCL EXTENSION my_ext : end
2405
2406Declaring the same types in different vendor extensions is disallowed.
2407
Anastasia Stulova18e165f2017-01-12 17:52:22 +00002408OpenCL Metadata
2409---------------
2410
2411Clang uses metadata to provide additional OpenCL semantics in IR needed for
2412backends and OpenCL runtime.
2413
2414Each kernel will have function metadata attached to it, specifying the arguments.
2415Kernel argument metadata is used to provide source level information for querying
2416at runtime, for example using the `clGetKernelArgInfo
2417<https://www.khronos.org/registry/OpenCL/specs/opencl-1.2.pdf#167>`_
2418call.
2419
2420Note that ``-cl-kernel-arg-info`` enables more information about the original CL
2421code to be added e.g. kernel parameter names will appear in the OpenCL metadata
2422along with other information.
2423
2424The IDs used to encode the OpenCL's logical address spaces in the argument info
2425metadata follows the SPIR address space mapping as defined in the SPIR
2426specification `section 2.2
2427<https://www.khronos.org/registry/spir/specs/spir_spec-2.0.pdf#18>`_
2428
2429OpenCL-Specific Attributes
2430--------------------------
2431
2432OpenCL support in Clang contains a set of attribute taken directly from the
2433specification as well as additional attributes.
2434
2435See also :doc:`AttributeReference`.
2436
2437nosvm
2438^^^^^
2439
2440Clang supports this attribute to comply to OpenCL v2.0 conformance, but it
2441does not have any effect on the IR. For more details reffer to the specification
2442`section 6.7.2
2443<https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#49>`_
2444
2445
Anastasia Stulovab376bee2017-02-16 12:49:29 +00002446opencl_unroll_hint
Anastasia Stulova18e165f2017-01-12 17:52:22 +00002447^^^^^^^^^^^^^^^^^^
2448
2449The implementation of this feature mirrors the unroll hint for C.
2450More details on the syntax can be found in the specification
2451`section 6.11.5
2452<https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#61>`_
2453
2454convergent
2455^^^^^^^^^^
2456
2457To make sure no invalid optimizations occur for single program multiple data
2458(SPMD) / single instruction multiple thread (SIMT) Clang provides attributes that
2459can be used for special functions that have cross work item semantics.
2460An example is the subgroup operations such as `intel_sub_group_shuffle
2461<https://www.khronos.org/registry/cl/extensions/intel/cl_intel_subgroups.txt>`_
2462
2463 .. code-block:: c
2464
2465 // Define custom my_sub_group_shuffle(data, c)
2466 // that makes use of intel_sub_group_shuffle
Aaron Ballman37ff16f2017-01-16 13:42:21 +00002467 r1 = ...
Anastasia Stulova18e165f2017-01-12 17:52:22 +00002468 if (r0) r1 = computeA();
2469 // Shuffle data from r1 into r3
2470 // of threads id r2.
2471 r3 = my_sub_group_shuffle(r1, r2);
2472 if (r0) r3 = computeB();
2473
2474with non-SPMD semantics this is optimized to the following equivalent code:
2475
2476 .. code-block:: c
2477
Aaron Ballman37ff16f2017-01-16 13:42:21 +00002478 r1 = ...
Anastasia Stulova18e165f2017-01-12 17:52:22 +00002479 if (!r0)
2480 // Incorrect functionality! The data in r1
2481 // have not been computed by all threads yet.
2482 r3 = my_sub_group_shuffle(r1, r2);
2483 else {
2484 r1 = computeA();
2485 r3 = my_sub_group_shuffle(r1, r2);
2486 r3 = computeB();
2487 }
2488
2489Declaring the function ``my_sub_group_shuffle`` with the convergent attribute
2490would prevent this:
2491
2492 .. code-block:: c
2493
2494 my_sub_group_shuffle() __attribute__((convergent));
2495
2496Using ``convergent`` guarantees correct execution by keeping CFG equivalence
2497wrt operations marked as ``convergent``. CFG ``G´`` is equivalent to ``G`` wrt
2498node ``Ni`` : ``iff ∀ Nj (i≠j)`` domination and post-domination relations with
2499respect to ``Ni`` remain the same in both ``G`` and ``G´``.
2500
2501noduplicate
2502^^^^^^^^^^^
2503
2504``noduplicate`` is more restrictive with respect to optimizations than
2505``convergent`` because a convergent function only preserves CFG equivalence.
2506This allows some optimizations to happen as long as the control flow remains
2507unmodified.
2508
2509 .. code-block:: c
2510
2511 for (int i=0; i<4; i++)
2512 my_sub_group_shuffle()
2513
2514can be modified to:
2515
2516 .. code-block:: c
2517
2518 my_sub_group_shuffle();
2519 my_sub_group_shuffle();
2520 my_sub_group_shuffle();
2521 my_sub_group_shuffle();
2522
2523while using ``noduplicate`` would disallow this. Also ``noduplicate`` doesn't
2524have the same safe semantics of CFG as ``convergent`` and can cause changes in
2525CFG that modify semantics of the original program.
2526
2527``noduplicate`` is kept for backwards compatibility only and it considered to be
2528deprecated for future uses.
2529
2530.. _opencl_addrsp:
2531
2532address_space
2533^^^^^^^^^^^^^
2534
2535Clang has arbitrary address space support using the ``address_space(N)``
2536attribute, where ``N`` is an integer number in the range ``0`` to ``16777215``
2537(``0xffffffu``).
2538
2539An OpenCL implementation provides a list of standard address spaces using
2540keywords: ``private``, ``local``, ``global``, and ``generic``. In the AST and
2541in the IR local, global, or generic will be represented by the address space
2542attribute with the corresponding unique number. Note that private does not have
2543any corresponding attribute added and, therefore, is represented by the absence
2544of an address space number. The specific IDs for an address space do not have to
2545match between the AST and the IR. Typically in the AST address space numbers
2546represent logical segments while in the IR they represent physical segments.
2547Therefore, machines with flat memory segments can map all AST address space
2548numbers to the same physical segment ID or skip address space attribute
2549completely while generating the IR. However, if the address space information
2550is needed by the IR passes e.g. to improve alias analysis, it is recommended
2551to keep it and only lower to reflect physical memory segments in the late
2552machine passes.
2553
2554OpenCL builtins
2555---------------
2556
2557There are some standard OpenCL functions that are implemented as Clang builtins:
2558
2559- All pipe functions from `section 6.13.16.2/6.13.16.3
2560 <https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#160>`_ of
2561 the OpenCL v2.0 kernel language specification. `
2562
2563- Address space qualifier conversion functions ``to_global``/``to_local``/``to_private``
2564 from `section 6.13.9
2565 <https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#101>`_.
2566
2567- All the ``enqueue_kernel`` functions from `section 6.13.17.1
2568 <https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#164>`_ and
2569 enqueue query functions from `section 6.13.17.5
2570 <https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#171>`_.
2571
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002572.. _target_features:
2573
2574Target-Specific Features and Limitations
2575========================================
2576
2577CPU Architectures Features and Limitations
2578------------------------------------------
2579
2580X86
2581^^^
2582
2583The support for X86 (both 32-bit and 64-bit) is considered stable on
Nico Weberab88f0b2014-03-07 18:09:57 +00002584Darwin (Mac OS X), Linux, FreeBSD, and Dragonfly BSD: it has been tested
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002585to correctly compile many large C, C++, Objective-C, and Objective-C++
2586codebases.
2587
Richard Smith48d1b652013-12-12 02:42:17 +00002588On ``x86_64-mingw32``, passing i128(by value) is incompatible with the
David Woodhouseddf89852014-01-23 14:32:46 +00002589Microsoft x64 calling convention. You might need to tweak
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002590``WinX86_64ABIInfo::classify()`` in lib/CodeGen/TargetInfo.cpp.
2591
Aaron Ballman51fb0312016-07-15 13:13:45 +00002592For the X86 target, clang supports the `-m16` command line
David Woodhouseddf89852014-01-23 14:32:46 +00002593argument which enables 16-bit code output. This is broadly similar to
2594using ``asm(".code16gcc")`` with the GNU toolchain. The generated code
2595and the ABI remains 32-bit but the assembler emits instructions
2596appropriate for a CPU running in 16-bit mode, with address-size and
2597operand-size prefixes to enable 32-bit addressing and operations.
2598
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002599ARM
2600^^^
2601
2602The support for ARM (specifically ARMv6 and ARMv7) is considered stable
2603on Darwin (iOS): it has been tested to correctly compile many large C,
2604C++, Objective-C, and Objective-C++ codebases. Clang only supports a
2605limited number of ARM architectures. It does not yet fully support
2606ARMv5, for example.
2607
Roman Divacky786d32e2013-09-11 17:12:49 +00002608PowerPC
2609^^^^^^^
2610
2611The support for PowerPC (especially PowerPC64) is considered stable
2612on Linux and FreeBSD: it has been tested to correctly compile many
2613large C and C++ codebases. PowerPC (32bit) is still missing certain
2614features (e.g. PIC code on ELF platforms).
2615
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002616Other platforms
2617^^^^^^^^^^^^^^^
2618
Roman Divacky786d32e2013-09-11 17:12:49 +00002619clang currently contains some support for other architectures (e.g. Sparc);
2620however, significant pieces of code generation are still missing, and they
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002621haven't undergone significant testing.
2622
2623clang contains limited support for the MSP430 embedded processor, but
2624both the clang support and the LLVM backend support are highly
2625experimental.
2626
2627Other platforms are completely unsupported at the moment. Adding the
2628minimal support needed for parsing and semantic analysis on a new
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00002629platform is quite easy; see ``lib/Basic/Targets.cpp`` in the clang source
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002630tree. This level of support is also sufficient for conversion to LLVM IR
2631for simple programs. Proper support for conversion to LLVM IR requires
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00002632adding code to ``lib/CodeGen/CGCall.cpp`` at the moment; this is likely to
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002633change soon, though. Generating assembly requires a suitable LLVM
2634backend.
2635
2636Operating System Features and Limitations
2637-----------------------------------------
2638
Nico Weberab88f0b2014-03-07 18:09:57 +00002639Darwin (Mac OS X)
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002640^^^^^^^^^^^^^^^^^
2641
Nico Weberc7cb9402014-03-07 18:11:40 +00002642Thread Sanitizer is not supported.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002643
2644Windows
2645^^^^^^^
2646
Richard Smith48d1b652013-12-12 02:42:17 +00002647Clang has experimental support for targeting "Cygming" (Cygwin / MinGW)
2648platforms.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002649
Reid Kleckner725b7b32013-09-05 21:29:35 +00002650See also :ref:`Microsoft Extensions <c_ms>`.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002651
2652Cygwin
2653""""""
2654
2655Clang works on Cygwin-1.7.
2656
2657MinGW32
2658"""""""
2659
2660Clang works on some mingw32 distributions. Clang assumes directories as
2661below;
2662
2663- ``C:/mingw/include``
2664- ``C:/mingw/lib``
2665- ``C:/mingw/lib/gcc/mingw32/4.[3-5].0/include/c++``
2666
2667On MSYS, a few tests might fail.
2668
2669MinGW-w64
2670"""""""""
2671
2672For 32-bit (i686-w64-mingw32), and 64-bit (x86\_64-w64-mingw32), Clang
2673assumes as below;
2674
2675- ``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)``
2676- ``some_directory/bin/gcc.exe``
2677- ``some_directory/bin/clang.exe``
2678- ``some_directory/bin/clang++.exe``
2679- ``some_directory/bin/../include/c++/GCC_version``
2680- ``some_directory/bin/../include/c++/GCC_version/x86_64-w64-mingw32``
2681- ``some_directory/bin/../include/c++/GCC_version/i686-w64-mingw32``
2682- ``some_directory/bin/../include/c++/GCC_version/backward``
2683- ``some_directory/bin/../x86_64-w64-mingw32/include``
2684- ``some_directory/bin/../i686-w64-mingw32/include``
2685- ``some_directory/bin/../include``
2686
2687This directory layout is standard for any toolchain you will find on the
2688official `MinGW-w64 website <http://mingw-w64.sourceforge.net>`_.
2689
2690Clang expects the GCC executable "gcc.exe" compiled for
2691``i686-w64-mingw32`` (or ``x86_64-w64-mingw32``) to be present on PATH.
2692
Ismail Donmezcb17fbb2017-02-17 08:26:54 +00002693`Some tests might fail <https://bugs.llvm.org/show_bug.cgi?id=9072>`_ on
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002694``x86_64-w64-mingw32``.
Hans Wennborg2a6e6bc2013-10-10 01:15:16 +00002695
2696.. _clang-cl:
2697
2698clang-cl
2699========
2700
Hans Wennborg715dd7f2017-01-12 18:15:06 +00002701clang-cl is an alternative command-line interface to Clang, designed for
Hans Wennborg2a6e6bc2013-10-10 01:15:16 +00002702compatibility with the Visual C++ compiler, cl.exe.
2703
2704To enable clang-cl to find system headers, libraries, and the linker when run
2705from the command-line, it should be executed inside a Visual Studio Native Tools
2706Command Prompt or a regular Command Prompt where the environment has been set
Hans Wennborg69d6d7a2018-03-01 14:00:19 +00002707up using e.g. `vcvarsall.bat <http://msdn.microsoft.com/en-us/library/f2ccy3wt.aspx>`_.
Hans Wennborg2a6e6bc2013-10-10 01:15:16 +00002708
Hans Wennborg69d6d7a2018-03-01 14:00:19 +00002709clang-cl can also be used from inside Visual Studio by selecting the LLVM
2710Platform Toolset. The toolset is installed by the LLVM installer, which can be
2711downloaded from the `LLVM release <http://releases.llvm.org/download.html>`_ or
2712`snapshot build <http://llvm.org/builds/>`_ web pages. To use the toolset,
2713select a project in Solution Explorer, open its Property Page (Alt+F7), and in
2714the "General" section of "Configuration Properties" change "Platform Toolset"
2715to e.g. LLVM-vs2014.
2716
2717To use the toolset with MSBuild directly, invoke it with e.g.
2718``/p:PlatformToolset=LLVM-vs2014``. This allows trying out the clang-cl
2719toolchain without modifying your project files.
2720
Hans Wennborg1bab7012018-03-01 14:48:19 +00002721It's also possible to point MSBuild at clang-cl without changing toolset by
2722passing ``/p:CLToolPath=c:\llvm\bin /p:CLToolExe=clang-cl.exe``.
2723
2724When using CMake and the Visual Studio generators, the toolset can be set with the ``-T`` flag:
2725
2726 ::
2727
2728 cmake -G"Visual Studio 15 2017" -T LLVM-vs2014 ..
2729
2730When using CMake with the Ninja generator, set the ``CMAKE_C_COMPILER`` and
2731``CMAKE_CXX_COMPILER`` variables to clang-cl:
2732
2733 ::
2734
2735 cmake -GNinja -DCMAKE_C_COMPILER="c:/Program Files (x86)/LLVM/bin/clang-cl.exe"
2736 -DCMAKE_CXX_COMPILER="c:/Program Files (x86)/LLVM/bin/clang-cl.exe" ..
2737
Hans Wennborg2a6e6bc2013-10-10 01:15:16 +00002738
2739Command-Line Options
2740--------------------
2741
2742To be compatible with cl.exe, clang-cl supports most of the same command-line
2743options. Those options can start with either ``/`` or ``-``. It also supports
2744some of Clang's core options, such as the ``-W`` options.
2745
2746Options that are known to clang-cl, but not currently supported, are ignored
2747with a warning. For example:
2748
2749 ::
2750
Hans Wennborg0d080622015-08-12 19:35:01 +00002751 clang-cl.exe: warning: argument unused during compilation: '/AI'
Hans Wennborg2a6e6bc2013-10-10 01:15:16 +00002752
2753To suppress warnings about unused arguments, use the ``-Qunused-arguments`` option.
2754
Ehsan Akhgarid8518332016-01-25 21:14:52 +00002755Options that are not known to clang-cl will be ignored by default. Use the
2756``-Werror=unknown-argument`` option in order to treat them as errors. If these
2757options are spelled with a leading ``/``, they will be mistaken for a filename:
Hans Wennborg2a6e6bc2013-10-10 01:15:16 +00002758
2759 ::
2760
2761 clang-cl.exe: error: no such file or directory: '/foobar'
2762
Ismail Donmezcb17fbb2017-02-17 08:26:54 +00002763Please `file a bug <https://bugs.llvm.org/enter_bug.cgi?product=clang&component=Driver>`_
Hans Wennborg2a6e6bc2013-10-10 01:15:16 +00002764for any valid cl.exe flags that clang-cl does not understand.
2765
2766Execute ``clang-cl /?`` to see a list of supported options:
2767
2768 ::
2769
Hans Wennborg35487d82014-08-04 21:07:58 +00002770 CL.EXE COMPATIBILITY OPTIONS:
Hans Wennborg715dd7f2017-01-12 18:15:06 +00002771 /? Display available options
2772 /arch:<value> Set architecture for code generation
2773 /Brepro- Emit an object file which cannot be reproduced over time
2774 /Brepro Emit an object file which can be reproduced over time
2775 /C Don't discard comments when preprocessing
2776 /c Compile only
Hans Wennborg7f36a952017-07-19 09:52:24 +00002777 /d1reportAllClassLayout Dump record layout information
2778 /diagnostics:caret Enable caret and column diagnostics (on by default)
2779 /diagnostics:classic Disable column and caret diagnostics
2780 /diagnostics:column Disable caret diagnostics but keep column info
Hans Wennborg715dd7f2017-01-12 18:15:06 +00002781 /D <macro[=value]> Define macro
2782 /EH<value> Exception handling model
2783 /EP Disable linemarker output and preprocess to stdout
2784 /execution-charset:<value>
2785 Runtime encoding, supports only UTF-8
2786 /E Preprocess to stdout
2787 /fallback Fall back to cl.exe if clang-cl fails to compile
2788 /FA Output assembly code file during compilation
2789 /Fa<file or directory> Output assembly code to this file during compilation (with /FA)
2790 /Fe<file or directory> Set output executable file or directory (ends in / or \)
2791 /FI <value> Include file before parsing
2792 /Fi<file> Set preprocess output file name (with /P)
2793 /Fo<file or directory> Set output object file, or directory (ends in / or \) (with /c)
Hans Wennborg0d080622015-08-12 19:35:01 +00002794 /fp:except-
2795 /fp:except
2796 /fp:fast
2797 /fp:precise
2798 /fp:strict
Hans Wennborg715dd7f2017-01-12 18:15:06 +00002799 /Fp<filename> Set pch filename (with /Yc and /Yu)
2800 /GA Assume thread-local variables are defined in the executable
2801 /Gd Set __cdecl as a default calling convention
2802 /GF- Disable string pooling
2803 /GR- Disable emission of RTTI data
Hans Wennborgcb766532018-01-03 13:20:25 +00002804 /Gregcall Set __regcall as a default calling convention
Hans Wennborg715dd7f2017-01-12 18:15:06 +00002805 /GR Enable emission of RTTI data
2806 /Gr Set __fastcall as a default calling convention
2807 /GS- Disable buffer security check
2808 /GS Enable buffer security check
2809 /Gs<value> Set stack probe size
2810 /Gv Set __vectorcall as a default calling convention
2811 /Gw- Don't put each data item in its own section
2812 /Gw Put each data item in its own section
Hans Wennborg729eb0b2018-04-03 09:28:21 +00002813 /GX- Disable exception handling
Hans Wennborg715dd7f2017-01-12 18:15:06 +00002814 /GX Enable exception handling
2815 /Gy- Don't put each function in its own section
2816 /Gy Put each function in its own section
2817 /Gz Set __stdcall as a default calling convention
2818 /help Display available options
2819 /imsvc <dir> Add directory to system include search path, as if part of %INCLUDE%
2820 /I <dir> Add directory to include search path
2821 /J Make char type unsigned
2822 /LDd Create debug DLL
2823 /LD Create DLL
2824 /link <options> Forward options to the linker
2825 /MDd Use DLL debug run-time
2826 /MD Use DLL run-time
2827 /MTd Use static debug run-time
2828 /MT Use static run-time
2829 /Od Disable optimization
2830 /Oi- Disable use of builtin functions
2831 /Oi Enable use of builtin functions
2832 /Os Optimize for size
2833 /Ot Optimize for speed
2834 /O<value> Optimization level
2835 /o <file or directory> Set output file or directory (ends in / or \)
2836 /P Preprocess to file
2837 /Qvec- Disable the loop vectorization passes
2838 /Qvec Enable the loop vectorization passes
2839 /showIncludes Print info about included files to stderr
2840 /source-charset:<value> Source encoding, supports only UTF-8
2841 /std:<value> Language standard to compile for
2842 /TC Treat all source files as C
2843 /Tc <filename> Specify a C source file
2844 /TP Treat all source files as C++
2845 /Tp <filename> Specify a C++ source file
Hans Wennborg9d1ed002017-01-12 19:26:54 +00002846 /utf-8 Set source and runtime encoding to UTF-8 (default)
Hans Wennborg715dd7f2017-01-12 18:15:06 +00002847 /U <macro> Undefine macro
2848 /vd<value> Control vtordisp placement
2849 /vmb Use a best-case representation method for member pointers
2850 /vmg Use a most-general representation for member pointers
2851 /vmm Set the default most-general representation to multiple inheritance
2852 /vms Set the default most-general representation to single inheritance
2853 /vmv Set the default most-general representation to virtual inheritance
2854 /volatile:iso Volatile loads and stores have standard semantics
2855 /volatile:ms Volatile loads and stores have acquire and release semantics
2856 /W0 Disable all warnings
2857 /W1 Enable -Wall
2858 /W2 Enable -Wall
2859 /W3 Enable -Wall
2860 /W4 Enable -Wall and -Wextra
Hans Wennborgcb766532018-01-03 13:20:25 +00002861 /Wall Enable -Weverything
Hans Wennborg715dd7f2017-01-12 18:15:06 +00002862 /WX- Do not treat warnings as errors
2863 /WX Treat warnings as errors
2864 /w Disable all warnings
2865 /Y- Disable precompiled headers, overrides /Yc and /Yu
2866 /Yc<filename> Generate a pch file for all code up to and including <filename>
2867 /Yu<filename> Load a pch file and use it instead of all code up to and including <filename>
2868 /Z7 Enable CodeView debug information in object files
2869 /Zc:sizedDealloc- Disable C++14 sized global deallocation functions
2870 /Zc:sizedDealloc Enable C++14 sized global deallocation functions
2871 /Zc:strictStrings Treat string literals as const
2872 /Zc:threadSafeInit- Disable thread-safe initialization of static variables
2873 /Zc:threadSafeInit Enable thread-safe initialization of static variables
2874 /Zc:trigraphs- Disable trigraphs (default)
2875 /Zc:trigraphs Enable trigraphs
Hans Wennborg7f36a952017-07-19 09:52:24 +00002876 /Zc:twoPhase- Disable two-phase name lookup in templates
2877 /Zc:twoPhase Enable two-phase name lookup in templates
Hans Wennborg715dd7f2017-01-12 18:15:06 +00002878 /Zd Emit debug line number tables only
2879 /Zi Alias for /Z7. Does not produce PDBs.
2880 /Zl Don't mention any default libraries in the object file
2881 /Zp Set the default maximum struct packing alignment to 1
2882 /Zp<value> Specify the default maximum struct packing alignment
2883 /Zs Syntax-check only
Hans Wennborg35487d82014-08-04 21:07:58 +00002884
2885 OPTIONS:
Hans Wennborg0d080622015-08-12 19:35:01 +00002886 -### Print (but do not run) the commands to run for this compilation
2887 --analyze Run the static analyzer
2888 -fansi-escape-codes Use ANSI escape codes for diagnostics
2889 -fcolor-diagnostics Use colors in diagnostics
Hans Wennborg7f36a952017-07-19 09:52:24 +00002890 -fdebug-macro Emit macro debug information
Hans Wennborg715dd7f2017-01-12 18:15:06 +00002891 -fdelayed-template-parsing
2892 Parse templated function definitions at the end of the translation unit
2893 -fdiagnostics-absolute-paths
2894 Print absolute paths in diagnostics
Hans Wennborg0d080622015-08-12 19:35:01 +00002895 -fdiagnostics-parseable-fixits
2896 Print fix-its in machine parseable form
Hans Wennborg7f36a952017-07-19 09:52:24 +00002897 -flto=<value> Set LTO mode to either 'full' or 'thin'
Hans Wennborg715dd7f2017-01-12 18:15:06 +00002898 -flto Enable LTO in 'full' mode
Hans Wennborg35487d82014-08-04 21:07:58 +00002899 -fms-compatibility-version=<value>
Hans Wennborg0d080622015-08-12 19:35:01 +00002900 Dot-separated value representing the Microsoft compiler version
2901 number to report in _MSC_VER (0 = don't define it (default))
Hans Wennborge8178e82016-02-12 01:01:37 +00002902 -fms-compatibility Enable full Microsoft Visual C++ compatibility
2903 -fms-extensions Accept some non-standard constructs supported by the Microsoft compiler
2904 -fmsc-version=<value> Microsoft compiler version number to report in _MSC_VER
2905 (0 = don't define it (default))
Hans Wennborg7f36a952017-07-19 09:52:24 +00002906 -fno-debug-macro Do not emit macro debug information
Hans Wennborg9d1ed002017-01-12 19:26:54 +00002907 -fno-delayed-template-parsing
2908 Disable delayed template parsing
Hans Wennborg7f36a952017-07-19 09:52:24 +00002909 -fno-sanitize-address-use-after-scope
2910 Disable use-after-scope detection in AddressSanitizer
2911 -fno-sanitize-blacklist Don't use blacklist file for sanitizers
2912 -fno-sanitize-cfi-cross-dso
2913 Disable control flow integrity (CFI) checks for cross-DSO calls.
Hans Wennborg0d080622015-08-12 19:35:01 +00002914 -fno-sanitize-coverage=<value>
2915 Disable specified features of coverage instrumentation for Sanitizers
Hans Wennborg7f36a952017-07-19 09:52:24 +00002916 -fno-sanitize-memory-track-origins
2917 Disable origins tracking in MemorySanitizer
Hans Wennborgcb766532018-01-03 13:20:25 +00002918 -fno-sanitize-memory-use-after-dtor
2919 Disable use-after-destroy detection in MemorySanitizer
Hans Wennborg0d080622015-08-12 19:35:01 +00002920 -fno-sanitize-recover=<value>
2921 Disable recovery for specified sanitizers
Hans Wennborg7f36a952017-07-19 09:52:24 +00002922 -fno-sanitize-stats Disable sanitizer statistics gathering.
2923 -fno-sanitize-thread-atomics
2924 Disable atomic operations instrumentation in ThreadSanitizer
2925 -fno-sanitize-thread-func-entry-exit
2926 Disable function entry/exit instrumentation in ThreadSanitizer
2927 -fno-sanitize-thread-memory-access
2928 Disable memory access instrumentation in ThreadSanitizer
Hans Wennborg0d080622015-08-12 19:35:01 +00002929 -fno-sanitize-trap=<value>
2930 Disable trapping for specified sanitizers
Hans Wennborg715dd7f2017-01-12 18:15:06 +00002931 -fno-standalone-debug Limit debug information produced to reduce size of debug binary
2932 -fprofile-instr-generate=<file>
2933 Generate instrumented code to collect execution counts into <file>
2934 (overridden by LLVM_PROFILE_FILE env var)
2935 -fprofile-instr-generate
2936 Generate instrumented code to collect execution counts into default.profraw file
Sylvestre Ledrue86ee6b2017-01-14 11:41:45 +00002937 (overridden by '=' form of option or LLVM_PROFILE_FILE env var)
Hans Wennborg715dd7f2017-01-12 18:15:06 +00002938 -fprofile-instr-use=<value>
2939 Use instrumentation data for profile-guided optimization
Hans Wennborg7f36a952017-07-19 09:52:24 +00002940 -fsanitize-address-field-padding=<value>
2941 Level of field padding for AddressSanitizer
2942 -fsanitize-address-globals-dead-stripping
2943 Enable linker dead stripping of globals in AddressSanitizer
2944 -fsanitize-address-use-after-scope
2945 Enable use-after-scope detection in AddressSanitizer
Hans Wennborg35487d82014-08-04 21:07:58 +00002946 -fsanitize-blacklist=<value>
Hans Wennborg0d080622015-08-12 19:35:01 +00002947 Path to blacklist file for sanitizers
Hans Wennborg7f36a952017-07-19 09:52:24 +00002948 -fsanitize-cfi-cross-dso
2949 Enable control flow integrity (CFI) checks for cross-DSO calls.
Hans Wennborgcb766532018-01-03 13:20:25 +00002950 -fsanitize-cfi-icall-generalize-pointers
2951 Generalize pointers in CFI indirect call type signature checks
Hans Wennborg0d080622015-08-12 19:35:01 +00002952 -fsanitize-coverage=<value>
2953 Specify the type of coverage instrumentation for Sanitizers
Hans Wennborg7f36a952017-07-19 09:52:24 +00002954 -fsanitize-memory-track-origins=<value>
2955 Enable origins tracking in MemorySanitizer
2956 -fsanitize-memory-track-origins
2957 Enable origins tracking in MemorySanitizer
2958 -fsanitize-memory-use-after-dtor
2959 Enable use-after-destroy detection in MemorySanitizer
Hans Wennborg0d080622015-08-12 19:35:01 +00002960 -fsanitize-recover=<value>
2961 Enable recovery for specified sanitizers
Hans Wennborg7f36a952017-07-19 09:52:24 +00002962 -fsanitize-stats Enable sanitizer statistics gathering.
2963 -fsanitize-thread-atomics
2964 Enable atomic operations instrumentation in ThreadSanitizer (default)
2965 -fsanitize-thread-func-entry-exit
2966 Enable function entry/exit instrumentation in ThreadSanitizer (default)
2967 -fsanitize-thread-memory-access
2968 Enable memory access instrumentation in ThreadSanitizer (default)
Hans Wennborg0d080622015-08-12 19:35:01 +00002969 -fsanitize-trap=<value> Enable trapping for specified sanitizers
Hans Wennborg7f36a952017-07-19 09:52:24 +00002970 -fsanitize-undefined-strip-path-components=<number>
2971 Strip (or keep only, if negative) a given number of path components when emitting check metadata.
Hans Wennborg0d080622015-08-12 19:35:01 +00002972 -fsanitize=<check> Turn on runtime checks for various forms of undefined or suspicious
2973 behavior. See user manual for available checks
Hans Wennborg715dd7f2017-01-12 18:15:06 +00002974 -fstandalone-debug Emit full debug info for all types used by the program
Hans Wennborgcb766532018-01-03 13:20:25 +00002975 -fwhole-program-vtables Enables whole-program vtable optimization. Requires -flto
Hans Wennborg0d080622015-08-12 19:35:01 +00002976 -gcodeview Generate CodeView debug information
Hans Wennborg6e70f4e2016-07-27 16:56:03 +00002977 -gline-tables-only Emit debug line number tables only
2978 -miamcu Use Intel MCU ABI
Hans Wennborg0d080622015-08-12 19:35:01 +00002979 -mllvm <value> Additional arguments to forward to LLVM's option processing
Hans Wennborg7f36a952017-07-19 09:52:24 +00002980 -nobuiltininc Disable builtin #include directories
Hans Wennborg0d080622015-08-12 19:35:01 +00002981 -Qunused-arguments Don't emit warning for unused driver arguments
2982 -R<remark> Enable the specified remark
2983 --target=<value> Generate code for the given target
Hans Wennborgcb766532018-01-03 13:20:25 +00002984 --version Print version information
Hans Wennborg0d080622015-08-12 19:35:01 +00002985 -v Show commands to run and use verbose output
2986 -W<warning> Enable the specified warning
2987 -Xclang <arg> Pass <arg> to the clang compiler
Hans Wennborg2a6e6bc2013-10-10 01:15:16 +00002988
2989The /fallback Option
2990^^^^^^^^^^^^^^^^^^^^
2991
2992When clang-cl is run with the ``/fallback`` option, it will first try to
2993compile files itself. For any file that it fails to compile, it will fall back
2994and try to compile the file by invoking cl.exe.
2995
2996This option is intended to be used as a temporary means to build projects where
2997clang-cl cannot successfully compile all the files. clang-cl may fail to compile
2998a file either because it cannot generate code for some C++ feature, or because
2999it cannot parse some Microsoft language extension.