blob: df6344af91021edc84a4d8f3a9d833cc5c71733a [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
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000110 Turn warning "foo" into an 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
Adam Nemet1eea3e52016-09-13 04:32:40 +0000335.. _opt_fdiagnostics-show-hotness:
336
337**-f[no-]diagnostics-show-hotness**
338 Enable profile hotness information in diagnostic line.
339
Brian Gesiak562eab92017-07-01 05:45:26 +0000340 This option controls whether Clang prints the profile hotness associated
341 with diagnostics in the presence of profile-guided optimization information.
342 This is currently supported with optimization remarks (see
343 :ref:`Options to Emit Optimization Reports <rpass>`). The hotness information
344 allows users to focus on the hot optimization remarks that are likely to be
345 more relevant for run-time performance.
Adam Nemet1eea3e52016-09-13 04:32:40 +0000346
347 For example, in this output, the block containing the callsite of `foo` was
348 executed 3000 times according to the profile data:
349
350 ::
351
352 s.c:7:10: remark: foo inlined into bar (hotness: 3000) [-Rpass-analysis=inline]
353 sum += foo(x, x - 2);
354 ^
355
Brian Gesiak562eab92017-07-01 05:45:26 +0000356 This option is implied when
357 :ref:`-fsave-optimization-record <opt_fsave-optimization-record>` is used.
358 Otherwise, it defaults to off.
359
360.. _opt_fdiagnostics-hotness-threshold:
361
362**-fdiagnostics-hotness-threshold**
363 Prevent optimization remarks from being output if they do not have at least
364 this hotness value.
365
366 This option, which defaults to zero, controls the minimum hotness an
367 optimization remark would need in order to be output by Clang. This is
368 currently supported with optimization remarks (see :ref:`Options to Emit
369 Optimization Reports <rpass>`) when profile hotness information in
370 diagnostics is enabled (see
371 :ref:`-fdiagnostics-show-hotness <opt_fdiagnostics-show-hotness>`).
372
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000373.. _opt_fdiagnostics-fixit-info:
374
375**-f[no-]diagnostics-fixit-info**
376 Enable "FixIt" information in the diagnostics output.
377
378 This option, which defaults to on, controls whether or not Clang
379 prints the information on how to fix a specific diagnostic
380 underneath it when it knows. For example, in this output:
381
382 ::
383
384 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
385 #endif bad
386 ^
387 //
388
389 Passing **-fno-diagnostics-fixit-info** will prevent Clang from
390 printing the "//" line at the end of the message. This information
391 is useful for users who may not understand what is wrong, but can be
392 confusing for machine parsing.
393
394.. _opt_fdiagnostics-print-source-range-info:
395
Nico Weber69dce49c72013-01-09 05:06:41 +0000396**-fdiagnostics-print-source-range-info**
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000397 Print machine parsable information about source ranges.
Nico Weber69dce49c72013-01-09 05:06:41 +0000398 This option makes Clang print information about source ranges in a machine
399 parsable format after the file/line/column number information. The
400 information is a simple sequence of brace enclosed ranges, where each range
401 lists the start and end line/column locations. For example, in this output:
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000402
403 ::
404
405 exprs.c:47:15:{47:8-47:14}{47:17-47:24}: error: invalid operands to binary expression ('int *' and '_Complex float')
406 P = (P-42) + Gamma*4;
407 ~~~~~~ ^ ~~~~~~~
408
409 The {}'s are generated by -fdiagnostics-print-source-range-info.
410
411 The printed column numbers count bytes from the beginning of the
412 line; take care if your source contains multibyte characters.
413
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000414.. option:: -fdiagnostics-parseable-fixits
415
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000416 Print Fix-Its in a machine parseable form.
417
418 This option makes Clang print available Fix-Its in a machine
419 parseable format at the end of diagnostics. The following example
420 illustrates the format:
421
422 ::
423
424 fix-it:"t.cpp":{7:25-7:29}:"Gamma"
425
426 The range printed is a half-open range, so in this example the
427 characters at column 25 up to but not including column 29 on line 7
428 in t.cpp should be replaced with the string "Gamma". Either the
429 range or the replacement string may be empty (representing strict
430 insertions and strict erasures, respectively). Both the file name
431 and the insertion string escape backslash (as "\\\\"), tabs (as
432 "\\t"), newlines (as "\\n"), double quotes(as "\\"") and
433 non-printable characters (as octal "\\xxx").
434
435 The printed column numbers count bytes from the beginning of the
436 line; take care if your source contains multibyte characters.
437
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000438.. option:: -fno-elide-type
439
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000440 Turns off elision in template type printing.
441
442 The default for template type printing is to elide as many template
443 arguments as possible, removing those which are the same in both
444 template types, leaving only the differences. Adding this flag will
445 print all the template arguments. If supported by the terminal,
446 highlighting will still appear on differing arguments.
447
448 Default:
449
450 ::
451
452 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;
453
454 -fno-elide-type:
455
456 ::
457
458 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;
459
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000460.. option:: -fdiagnostics-show-template-tree
461
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000462 Template type diffing prints a text tree.
463
464 For diffing large templated types, this option will cause Clang to
465 display the templates as an indented text tree, one argument per
466 line, with differences marked inline. This is compatible with
467 -fno-elide-type.
468
469 Default:
470
471 ::
472
473 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;
474
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000475 With :option:`-fdiagnostics-show-template-tree`:
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000476
477 ::
478
479 t.cc:4:5: note: candidate function not viable: no known conversion for 1st argument;
480 vector<
481 map<
482 [...],
483 map<
Richard Trieu98ca59e2013-08-09 22:52:48 +0000484 [float != double],
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000485 [...]>>>
486
487.. _cl_diag_warning_groups:
488
489Individual Warning Groups
490^^^^^^^^^^^^^^^^^^^^^^^^^
491
492TODO: Generate this from tblgen. Define one anchor per warning group.
493
494.. _opt_wextra-tokens:
495
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000496.. option:: -Wextra-tokens
497
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000498 Warn about excess tokens at the end of a preprocessor directive.
499
500 This option, which defaults to on, enables warnings about extra
501 tokens at the end of preprocessor directives. For example:
502
503 ::
504
505 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
506 #endif bad
507 ^
508
509 These extra tokens are not strictly conforming, and are usually best
510 handled by commenting them out.
511
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000512.. option:: -Wambiguous-member-template
513
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000514 Warn about unqualified uses of a member template whose name resolves to
515 another template at the location of the use.
516
517 This option, which defaults to on, enables a warning in the
518 following code:
519
520 ::
521
522 template<typename T> struct set{};
523 template<typename T> struct trait { typedef const T& type; };
524 struct Value {
525 template<typename T> void set(typename trait<T>::type value) {}
526 };
527 void foo() {
528 Value v;
529 v.set<double>(3.2);
530 }
531
532 C++ [basic.lookup.classref] requires this to be an error, but,
533 because it's hard to work around, Clang downgrades it to a warning
534 as an extension.
535
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000536.. option:: -Wbind-to-temporary-copy
537
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000538 Warn about an unusable copy constructor when binding a reference to a
539 temporary.
540
Nico Weberacb35c02014-09-18 02:09:53 +0000541 This option enables warnings about binding a
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000542 reference to a temporary when the temporary doesn't have a usable
543 copy constructor. For example:
544
545 ::
546
547 struct NonCopyable {
548 NonCopyable();
549 private:
550 NonCopyable(const NonCopyable&);
551 };
552 void foo(const NonCopyable&);
553 void bar() {
554 foo(NonCopyable()); // Disallowed in C++98; allowed in C++11.
555 }
556
557 ::
558
559 struct NonCopyable2 {
560 NonCopyable2();
561 NonCopyable2(NonCopyable2&);
562 };
563 void foo(const NonCopyable2&);
564 void bar() {
565 foo(NonCopyable2()); // Disallowed in C++98; allowed in C++11.
566 }
567
568 Note that if ``NonCopyable2::NonCopyable2()`` has a default argument
569 whose instantiation produces a compile error, that error will still
570 be a hard error in C++98 mode even if this warning is turned off.
571
572Options to Control Clang Crash Diagnostics
573------------------------------------------
574
575As unbelievable as it may sound, Clang does crash from time to time.
576Generally, this only occurs to those living on the `bleeding
577edge <http://llvm.org/releases/download.html#svn>`_. Clang goes to great
578lengths to assist you in filing a bug report. Specifically, Clang
579generates preprocessed source file(s) and associated run script(s) upon
580a crash. These files should be attached to a bug report to ease
581reproducibility of the failure. Below are the command line options to
582control the crash diagnostics.
583
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000584.. option:: -fno-crash-diagnostics
585
586 Disable auto-generation of preprocessed source files during a clang crash.
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000587
588The -fno-crash-diagnostics flag can be helpful for speeding the process
589of generating a delta reduced test case.
590
Bruno Cardoso Lopes52dfe712017-04-12 21:46:20 +0000591Clang is also capable of generating preprocessed source file(s) and associated
592run script(s) even without a crash. This is specially useful when trying to
593generate a reproducer for warnings or errors while using modules.
594
595.. option:: -gen-reproducer
596
597 Generates preprocessed source files, a reproducer script and if relevant, a
598 cache containing: built module pcm's and all headers needed to rebuilt the
599 same modules.
600
Adam Nemet1eea3e52016-09-13 04:32:40 +0000601.. _rpass:
602
Diego Novillo263ce212014-05-29 20:13:27 +0000603Options to Emit Optimization Reports
604------------------------------------
605
606Optimization reports trace, at a high-level, all the major decisions
607done by compiler transformations. For instance, when the inliner
608decides to inline function ``foo()`` into ``bar()``, or the loop unroller
609decides to unroll a loop N times, or the vectorizer decides to
610vectorize a loop body.
611
612Clang offers a family of flags which the optimizers can use to emit
613a diagnostic in three cases:
614
Aaron Ballman05efec82016-07-15 12:55:47 +00006151. When the pass makes a transformation (`-Rpass`).
Diego Novillo263ce212014-05-29 20:13:27 +0000616
Aaron Ballman05efec82016-07-15 12:55:47 +00006172. When the pass fails to make a transformation (`-Rpass-missed`).
Diego Novillo263ce212014-05-29 20:13:27 +0000618
6193. When the pass determines whether or not to make a transformation
Aaron Ballman05efec82016-07-15 12:55:47 +0000620 (`-Rpass-analysis`).
Diego Novillo263ce212014-05-29 20:13:27 +0000621
Aaron Ballman05efec82016-07-15 12:55:47 +0000622NOTE: Although the discussion below focuses on `-Rpass`, the exact
623same options apply to `-Rpass-missed` and `-Rpass-analysis`.
Diego Novillo263ce212014-05-29 20:13:27 +0000624
625Since there are dozens of passes inside the compiler, each of these flags
626take a regular expression that identifies the name of the pass which should
627emit the associated diagnostic. For example, to get a report from the inliner,
628compile the code with:
629
630.. code-block:: console
631
632 $ clang -O2 -Rpass=inline code.cc -o code
633 code.cc:4:25: remark: foo inlined into bar [-Rpass=inline]
634 int bar(int j) { return foo(j, j - 2); }
635 ^
636
637Note that remarks from the inliner are identified with `[-Rpass=inline]`.
638To request a report from every optimization pass, you should use
Aaron Ballman05efec82016-07-15 12:55:47 +0000639`-Rpass=.*` (in fact, you can use any valid POSIX regular
Diego Novillo263ce212014-05-29 20:13:27 +0000640expression). However, do not expect a report from every transformation
641made by the compiler. Optimization remarks do not really make sense
642outside of the major transformations (e.g., inlining, vectorization,
643loop optimizations) and not every optimization pass supports this
644feature.
645
Adam Nemet1eea3e52016-09-13 04:32:40 +0000646Note that when using profile-guided optimization information, profile hotness
647information can be included in the remarks (see
648:ref:`-fdiagnostics-show-hotness <opt_fdiagnostics-show-hotness>`).
649
Diego Novillo263ce212014-05-29 20:13:27 +0000650Current limitations
651^^^^^^^^^^^^^^^^^^^
652
Diego Novillo94b276d2014-07-10 23:29:28 +00006531. Optimization remarks that refer to function names will display the
Diego Novillo263ce212014-05-29 20:13:27 +0000654 mangled name of the function. Since these remarks are emitted by the
655 back end of the compiler, it does not know anything about the input
656 language, nor its mangling rules.
657
Diego Novillo94b276d2014-07-10 23:29:28 +00006582. Some source locations are not displayed correctly. The front end has
Diego Novillo263ce212014-05-29 20:13:27 +0000659 a more detailed source location tracking than the locations included
660 in the debug info (e.g., the front end can locate code inside macro
Aaron Ballman05efec82016-07-15 12:55:47 +0000661 expansions). However, the locations used by `-Rpass` are
Diego Novillo263ce212014-05-29 20:13:27 +0000662 translated from debug annotations. That translation can be lossy,
663 which results in some remarks having no location information.
664
Paul Robinsond7214a72015-04-27 18:14:32 +0000665Other Options
666-------------
667Clang options that that don't fit neatly into other categories.
668
669.. option:: -MV
670
671 When emitting a dependency file, use formatting conventions appropriate
672 for NMake or Jom. Ignored unless another option causes Clang to emit a
673 dependency file.
674
675When Clang emits a dependency file (e.g., you supplied the -M option)
676most filenames can be written to the file without any special formatting.
677Different Make tools will treat different sets of characters as "special"
678and use different conventions for telling the Make tool that the character
679is actually part of the filename. Normally Clang uses backslash to "escape"
680a special character, which is the convention used by GNU Make. The -MV
681option tells Clang to put double-quotes around the entire filename, which
682is the convention used by NMake and Jom.
683
Diego Novillo263ce212014-05-29 20:13:27 +0000684
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000685Language and Target-Independent Features
686========================================
687
688Controlling Errors and Warnings
689-------------------------------
690
691Clang provides a number of ways to control which code constructs cause
692it to emit errors and warning messages, and how they are displayed to
693the console.
694
695Controlling How Clang Displays Diagnostics
696^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
697
698When Clang emits a diagnostic, it includes rich information in the
699output, and gives you fine-grain control over which information is
700printed. Clang has the ability to print this information, and these are
701the options that control it:
702
703#. A file/line/column indicator that shows exactly where the diagnostic
704 occurs in your code [:ref:`-fshow-column <opt_fshow-column>`,
705 :ref:`-fshow-source-location <opt_fshow-source-location>`].
706#. A categorization of the diagnostic as a note, warning, error, or
707 fatal error.
708#. A text string that describes what the problem is.
709#. An option that indicates how to control the diagnostic (for
710 diagnostics that support it)
711 [:ref:`-fdiagnostics-show-option <opt_fdiagnostics-show-option>`].
712#. A :ref:`high-level category <diagnostics_categories>` for the diagnostic
713 for clients that want to group diagnostics by class (for diagnostics
714 that support it)
715 [:ref:`-fdiagnostics-show-category <opt_fdiagnostics-show-category>`].
716#. The line of source code that the issue occurs on, along with a caret
717 and ranges that indicate the important locations
718 [:ref:`-fcaret-diagnostics <opt_fcaret-diagnostics>`].
719#. "FixIt" information, which is a concise explanation of how to fix the
720 problem (when Clang is certain it knows)
721 [:ref:`-fdiagnostics-fixit-info <opt_fdiagnostics-fixit-info>`].
722#. A machine-parsable representation of the ranges involved (off by
723 default)
724 [:ref:`-fdiagnostics-print-source-range-info <opt_fdiagnostics-print-source-range-info>`].
725
726For more information please see :ref:`Formatting of
727Diagnostics <cl_diag_formatting>`.
728
729Diagnostic Mappings
730^^^^^^^^^^^^^^^^^^^
731
Alex Denisov793e0672015-02-11 07:56:16 +0000732All diagnostics are mapped into one of these 6 classes:
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000733
734- Ignored
735- Note
Tobias Grosser74160242014-02-28 09:11:08 +0000736- Remark
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000737- Warning
738- Error
739- Fatal
740
741.. _diagnostics_categories:
742
743Diagnostic Categories
744^^^^^^^^^^^^^^^^^^^^^
745
746Though not shown by default, diagnostics may each be associated with a
747high-level category. This category is intended to make it possible to
748triage builds that produce a large number of errors or warnings in a
749grouped way.
750
751Categories are not shown by default, but they can be turned on with the
752:ref:`-fdiagnostics-show-category <opt_fdiagnostics-show-category>` option.
753When set to "``name``", the category is printed textually in the
754diagnostic output. When it is set to "``id``", a category number is
755printed. The mapping of category names to category id's can be obtained
756by running '``clang --print-diagnostic-categories``'.
757
758Controlling Diagnostics via Command Line Flags
759^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
760
761TODO: -W flags, -pedantic, etc
762
763.. _pragma_gcc_diagnostic:
764
765Controlling Diagnostics via Pragmas
766^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
767
768Clang can also control what diagnostics are enabled through the use of
769pragmas in the source code. This is useful for turning off specific
770warnings in a section of source code. Clang supports GCC's pragma for
771compatibility with existing source code, as well as several extensions.
772
773The pragma may control any warning that can be used from the command
774line. Warnings may be set to ignored, warning, error, or fatal. The
775following example code will tell Clang or GCC to ignore the -Wall
776warnings:
777
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000778.. code-block:: c
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000779
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000780 #pragma GCC diagnostic ignored "-Wall"
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000781
782In addition to all of the functionality provided by GCC's pragma, Clang
783also allows you to push and pop the current warning state. This is
784particularly useful when writing a header file that will be compiled by
785other people, because you don't know what warning flags they build with.
786
George Burgess IVbc8cc5ac2016-06-21 02:19:43 +0000787In the below example :option:`-Wextra-tokens` is ignored for only a single line
788of code, after which the diagnostics return to whatever state had previously
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000789existed.
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000790
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000791.. code-block:: c
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000792
George Burgess IVbc8cc5ac2016-06-21 02:19:43 +0000793 #if foo
794 #endif foo // warning: extra tokens at end of #endif directive
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000795
Asiri Rathnayakeb0bbb7d2017-02-02 10:35:18 +0000796 #pragma clang diagnostic push
George Burgess IVbc8cc5ac2016-06-21 02:19:43 +0000797 #pragma clang diagnostic ignored "-Wextra-tokens"
798
799 #if foo
800 #endif foo // no warning
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000801
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000802 #pragma clang diagnostic pop
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000803
804The push and pop pragmas will save and restore the full diagnostic state
805of the compiler, regardless of how it was set. That means that it is
806possible to use push and pop around GCC compatible diagnostics and Clang
807will push and pop them appropriately, while GCC will ignore the pushes
808and pops as unknown pragmas. It should be noted that while Clang
809supports the GCC pragma, Clang and GCC do not support the exact same set
810of warnings, so even when using GCC compatible #pragmas there is no
811guarantee that they will have identical behaviour on both compilers.
812
Andy Gibbs9c2ccd62013-04-17 16:16:16 +0000813In addition to controlling warnings and errors generated by the compiler, it is
814possible to generate custom warning and error messages through the following
815pragmas:
816
817.. code-block:: c
818
819 // The following will produce warning messages
820 #pragma message "some diagnostic message"
821 #pragma GCC warning "TODO: replace deprecated feature"
822
823 // The following will produce an error message
824 #pragma GCC error "Not supported"
825
826These pragmas operate similarly to the ``#warning`` and ``#error`` preprocessor
827directives, except that they may also be embedded into preprocessor macros via
828the C99 ``_Pragma`` operator, for example:
829
830.. code-block:: c
831
832 #define STR(X) #X
833 #define DEFER(M,...) M(__VA_ARGS__)
834 #define CUSTOM_ERROR(X) _Pragma(STR(GCC error(X " at line " DEFER(STR,__LINE__))))
835
836 CUSTOM_ERROR("Feature not available");
837
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000838Controlling Diagnostics in System Headers
839^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
840
841Warnings are suppressed when they occur in system headers. By default,
842an included file is treated as a system header if it is found in an
843include path specified by ``-isystem``, but this can be overridden in
844several ways.
845
846The ``system_header`` pragma can be used to mark the current file as
847being a system header. No warnings will be produced from the location of
848the pragma onwards within the same file.
849
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000850.. code-block:: c
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000851
George Burgess IVbc8cc5ac2016-06-21 02:19:43 +0000852 #if foo
853 #endif foo // warning: extra tokens at end of #endif directive
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000854
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000855 #pragma clang system_header
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000856
George Burgess IVbc8cc5ac2016-06-21 02:19:43 +0000857 #if foo
858 #endif foo // no warning
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000859
Aaron Ballman51fb0312016-07-15 13:13:45 +0000860The `--system-header-prefix=` and `--no-system-header-prefix=`
Alexander Kornienko18fa48c2014-03-26 01:39:59 +0000861command-line arguments can be used to override whether subsets of an include
862path are treated as system headers. When the name in a ``#include`` directive
863is found within a header search path and starts with a system prefix, the
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000864header is treated as a system header. The last prefix on the
865command-line which matches the specified header name takes precedence.
866For instance:
867
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000868.. code-block:: console
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000869
Alexander Kornienko18fa48c2014-03-26 01:39:59 +0000870 $ clang -Ifoo -isystem bar --system-header-prefix=x/ \
871 --no-system-header-prefix=x/y/
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000872
873Here, ``#include "x/a.h"`` is treated as including a system header, even
874if the header is found in ``foo``, and ``#include "x/y/b.h"`` is treated
875as not including a system header, even if the header is found in
876``bar``.
877
878A ``#include`` directive which finds a file relative to the current
879directory is treated as including a system header if the including file
880is treated as a system header.
881
882.. _diagnostics_enable_everything:
883
Tobias Grosser74160242014-02-28 09:11:08 +0000884Enabling All Diagnostics
885^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000886
887In addition to the traditional ``-W`` flags, one can enable **all**
Tobias Grosser74160242014-02-28 09:11:08 +0000888diagnostics by passing :option:`-Weverything`. This works as expected
889with
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000890:option:`-Werror`, and also includes the warnings from :option:`-pedantic`.
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000891
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000892Note that when combined with :option:`-w` (which disables all warnings), that
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000893flag wins.
894
895Controlling Static Analyzer Diagnostics
896^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
897
898While not strictly part of the compiler, the diagnostics from Clang's
899`static analyzer <http://clang-analyzer.llvm.org>`_ can also be
900influenced by the user via changes to the source code. See the available
901`annotations <http://clang-analyzer.llvm.org/annotations.html>`_ and the
902analyzer's `FAQ
903page <http://clang-analyzer.llvm.org/faq.html#exclude_code>`_ for more
904information.
905
Dmitri Gribenko7ac0cc32012-12-15 21:10:51 +0000906.. _usersmanual-precompiled-headers:
907
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000908Precompiled Headers
909-------------------
910
911`Precompiled headers <http://en.wikipedia.org/wiki/Precompiled_header>`__
912are a general approach employed by many compilers to reduce compilation
913time. The underlying motivation of the approach is that it is common for
914the same (and often large) header files to be included by multiple
915source files. Consequently, compile times can often be greatly improved
916by caching some of the (redundant) work done by a compiler to process
917headers. Precompiled header files, which represent one of many ways to
918implement this optimization, are literally files that represent an
919on-disk cache that contains the vital information necessary to reduce
920some of the work needed to process a corresponding header file. While
921details of precompiled headers vary between compilers, precompiled
922headers have been shown to be highly effective at speeding up program
Nico Weberab88f0b2014-03-07 18:09:57 +0000923compilation on systems with very large system headers (e.g., Mac OS X).
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000924
925Generating a PCH File
926^^^^^^^^^^^^^^^^^^^^^
927
928To generate a PCH file using Clang, one invokes Clang with the
Aaron Ballman51fb0312016-07-15 13:13:45 +0000929`-x <language>-header` option. This mirrors the interface in GCC
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000930for generating PCH files:
931
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000932.. code-block:: console
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000933
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000934 $ gcc -x c-header test.h -o test.h.gch
935 $ clang -x c-header test.h -o test.h.pch
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000936
937Using a PCH File
938^^^^^^^^^^^^^^^^
939
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000940A PCH file can then be used as a prefix header when a :option:`-include`
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000941option is passed to ``clang``:
942
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000943.. code-block:: console
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000944
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000945 $ clang -include test.h test.c -o test
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000946
947The ``clang`` driver will first check if a PCH file for ``test.h`` is
948available; if so, the contents of ``test.h`` (and the files it includes)
949will be processed from the PCH file. Otherwise, Clang falls back to
950directly processing the content of ``test.h``. This mirrors the behavior
951of GCC.
952
953.. note::
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000954
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000955 Clang does *not* automatically use PCH files for headers that are directly
956 included within a source file. For example:
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000957
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000958 .. code-block:: console
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000959
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000960 $ clang -x c-header test.h -o test.h.pch
961 $ cat test.c
962 #include "test.h"
963 $ clang test.c -o test
964
965 In this example, ``clang`` will not automatically use the PCH file for
966 ``test.h`` since ``test.h`` was included directly in the source file and not
967 specified on the command line using :option:`-include`.
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000968
969Relocatable PCH Files
970^^^^^^^^^^^^^^^^^^^^^
971
972It is sometimes necessary to build a precompiled header from headers
973that are not yet in their final, installed locations. For example, one
974might build a precompiled header within the build tree that is then
975meant to be installed alongside the headers. Clang permits the creation
976of "relocatable" precompiled headers, which are built with a given path
977(into the build directory) and can later be used from an installed
978location.
979
980To build a relocatable precompiled header, place your headers into a
981subdirectory whose structure mimics the installed location. For example,
982if you want to build a precompiled header for the header ``mylib.h``
983that will be installed into ``/usr/include``, create a subdirectory
984``build/usr/include`` and place the header ``mylib.h`` into that
985subdirectory. If ``mylib.h`` depends on other headers, then they can be
986stored within ``build/usr/include`` in a way that mimics the installed
987location.
988
989Building a relocatable precompiled header requires two additional
990arguments. First, pass the ``--relocatable-pch`` flag to indicate that
991the resulting PCH file should be relocatable. Second, pass
Aaron Ballman51fb0312016-07-15 13:13:45 +0000992`-isysroot /path/to/build`, which makes all includes for your library
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000993relative to the build directory. For example:
994
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000995.. code-block:: console
Sean Silvabf9b4cd2012-12-13 01:10:46 +0000996
Dmitri Gribenko1436ff22012-12-19 22:06:59 +0000997 # 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 +0000998
999When loading the relocatable PCH file, the various headers used in the
1000PCH file are found from the system header root. For example, ``mylib.h``
1001can be found in ``/usr/include/mylib.h``. If the headers are installed
Aaron Ballman51fb0312016-07-15 13:13:45 +00001002in some other system root, the `-isysroot` option can be used provide
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001003a different system root from which the headers will be based. For
Aaron Ballman51fb0312016-07-15 13:13:45 +00001004example, `-isysroot /Developer/SDKs/MacOSX10.4u.sdk` will look for
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001005``mylib.h`` in ``/Developer/SDKs/MacOSX10.4u.sdk/usr/include/mylib.h``.
1006
1007Relocatable precompiled headers are intended to be used in a limited
1008number of cases where the compilation environment is tightly controlled
1009and the precompiled header cannot be generated after headers have been
Argyrios Kyrtzidisf0ad09f2013-02-14 00:12:44 +00001010installed.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001011
Peter Collingbourne915df992015-05-15 18:33:32 +00001012.. _controlling-code-generation:
1013
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001014Controlling Code Generation
1015---------------------------
1016
1017Clang provides a number of ways to control code generation. The options
1018are listed below.
1019
Sean Silva4c280bd2013-06-21 23:50:58 +00001020**-f[no-]sanitize=check1,check2,...**
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001021 Turn on runtime checks for various forms of undefined or suspicious
1022 behavior.
1023
1024 This option controls whether Clang adds runtime checks for various
1025 forms of undefined or suspicious behavior, and is disabled by
1026 default. If a check fails, a diagnostic message is produced at
1027 runtime explaining the problem. The main checks are:
1028
Richard Smithbb741f42012-12-13 07:29:23 +00001029 - .. _opt_fsanitize_address:
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001030
Richard Smithbb741f42012-12-13 07:29:23 +00001031 ``-fsanitize=address``:
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001032 :doc:`AddressSanitizer`, a memory error
1033 detector.
Richard Smithbb741f42012-12-13 07:29:23 +00001034 - .. _opt_fsanitize_thread:
1035
Dmitry Vyukov42de1082012-12-21 08:21:25 +00001036 ``-fsanitize=thread``: :doc:`ThreadSanitizer`, a data race detector.
Evgeniy Stepanov17d55902012-12-21 10:50:00 +00001037 - .. _opt_fsanitize_memory:
1038
1039 ``-fsanitize=memory``: :doc:`MemorySanitizer`,
Alexey Samsonov1f7051e2015-12-04 22:50:44 +00001040 a detector of uninitialized reads. Requires instrumentation of all
1041 program code.
Richard Smithbb741f42012-12-13 07:29:23 +00001042 - .. _opt_fsanitize_undefined:
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001043
Alexey Samsonov778fc722015-12-04 17:30:29 +00001044 ``-fsanitize=undefined``: :doc:`UndefinedBehaviorSanitizer`,
1045 a fast and compatible undefined behavior checker.
Peter Collingbourne9881b782015-06-18 23:59:22 +00001046
Peter Collingbournec3772752013-08-07 22:47:34 +00001047 - ``-fsanitize=dataflow``: :doc:`DataFlowSanitizer`, a general data
1048 flow analysis.
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001049 - ``-fsanitize=cfi``: :doc:`control flow integrity <ControlFlowIntegrity>`
Alexey Samsonov907880e2015-06-19 19:57:46 +00001050 checks. Requires ``-flto``.
Peter Collingbournec4122c12015-06-15 21:08:13 +00001051 - ``-fsanitize=safe-stack``: :doc:`safe stack <SafeStack>`
1052 protection against stack-based memory corruption errors.
Chad Rosierae229d52013-01-29 23:31:22 +00001053
Alexey Samsonov778fc722015-12-04 17:30:29 +00001054 There are more fine-grained checks available: see
1055 the :ref:`list <ubsan-checks>` of specific kinds of
Alexey Samsonov9eda6402015-12-04 21:30:58 +00001056 undefined behavior that can be detected and the :ref:`list <cfi-schemes>`
1057 of control flow integrity schemes.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001058
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001059 The ``-fsanitize=`` argument must also be provided when linking, in
Alexey Samsonovb6761c22015-12-04 23:13:14 +00001060 order to link to the appropriate runtime library.
Richard Smith83c728b2013-07-19 19:06:48 +00001061
1062 It is not possible to combine more than one of the ``-fsanitize=address``,
1063 ``-fsanitize=thread``, and ``-fsanitize=memory`` checkers in the same
Alexey Samsonov88460172015-12-04 17:35:47 +00001064 program.
Richard Smith83c728b2013-07-19 19:06:48 +00001065
Alexey Samsonov88459522015-01-12 22:39:12 +00001066**-f[no-]sanitize-recover=check1,check2,...**
Kostya Serebryany40b82152016-05-04 20:24:54 +00001067
Kostya Serebryanyceb1add2016-05-04 20:21:47 +00001068**-f[no-]sanitize-recover=all**
Alexey Samsonov88459522015-01-12 22:39:12 +00001069
1070 Controls which checks enabled by ``-fsanitize=`` flag are non-fatal.
1071 If the check is fatal, program will halt after the first error
1072 of this kind is detected and error report is printed.
1073
Alexey Samsonov778fc722015-12-04 17:30:29 +00001074 By default, non-fatal checks are those enabled by
1075 :doc:`UndefinedBehaviorSanitizer`,
Alexey Samsonov88459522015-01-12 22:39:12 +00001076 except for ``-fsanitize=return`` and ``-fsanitize=unreachable``. Some
Yury Gribov5bfeca12015-11-11 10:45:48 +00001077 sanitizers may not support recovery (or not support it by default
1078 e.g. :doc:`AddressSanitizer`), and always crash the program after the issue
1079 is detected.
Alexey Samsonov88459522015-01-12 22:39:12 +00001080
Peter Collingbourne9881b782015-06-18 23:59:22 +00001081 Note that the ``-fsanitize-trap`` flag has precedence over this flag.
1082 This means that if a check has been configured to trap elsewhere on the
1083 command line, or if the check traps by default, this flag will not have
1084 any effect unless that sanitizer's trapping behavior is disabled with
1085 ``-fno-sanitize-trap``.
1086
1087 For example, if a command line contains the flags ``-fsanitize=undefined
1088 -fsanitize-trap=undefined``, the flag ``-fsanitize-recover=alignment``
1089 will have no effect on its own; it will need to be accompanied by
1090 ``-fno-sanitize-trap=alignment``.
1091
1092**-f[no-]sanitize-trap=check1,check2,...**
1093
1094 Controls which checks enabled by the ``-fsanitize=`` flag trap. This
1095 option is intended for use in cases where the sanitizer runtime cannot
1096 be used (for instance, when building libc or a kernel module), or where
1097 the binary size increase caused by the sanitizer runtime is a concern.
1098
Alexey Samsonovb6761c22015-12-04 23:13:14 +00001099 This flag is only compatible with :doc:`control flow integrity
1100 <ControlFlowIntegrity>` schemes and :doc:`UndefinedBehaviorSanitizer`
1101 checks other than ``vptr``. If this flag
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001102 is supplied together with ``-fsanitize=undefined``, the ``vptr`` sanitizer
1103 will be implicitly disabled.
1104
1105 This flag is enabled by default for sanitizers in the ``cfi`` group.
Peter Collingbourne9881b782015-06-18 23:59:22 +00001106
Alexey Samsonovb6761c22015-12-04 23:13:14 +00001107.. option:: -fsanitize-blacklist=/path/to/blacklist/file
1108
1109 Disable or modify sanitizer checks for objects (source files, functions,
1110 variables, types) listed in the file. See
1111 :doc:`SanitizerSpecialCaseList` for file format description.
1112
1113.. option:: -fno-sanitize-blacklist
1114
1115 Don't use blacklist file, if it was specified earlier in the command line.
1116
Alexey Samsonov8fffba12015-05-07 23:04:19 +00001117**-f[no-]sanitize-coverage=[type,features,...]**
1118
1119 Enable simple code coverage in addition to certain sanitizers.
1120 See :doc:`SanitizerCoverage` for more details.
1121
Peter Collingbournedc134532016-01-16 00:31:22 +00001122**-f[no-]sanitize-stats**
1123
1124 Enable simple statistics gathering for the enabled sanitizers.
1125 See :doc:`SanitizerStats` for more details.
1126
Peter Collingbourne9881b782015-06-18 23:59:22 +00001127.. option:: -fsanitize-undefined-trap-on-error
1128
1129 Deprecated alias for ``-fsanitize-trap=undefined``.
1130
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001131.. option:: -fsanitize-cfi-cross-dso
1132
1133 Enable cross-DSO control flow integrity checks. This flag modifies
1134 the behavior of sanitizers in the ``cfi`` group to allow checking
1135 of cross-DSO virtual and indirect calls.
1136
Piotr Padlewskieb9dd5a2017-01-16 13:20:08 +00001137
1138.. option:: -fstrict-vtable-pointers
Hans Wennborgf6d61d42017-01-17 21:31:57 +00001139
Piotr Padlewskieb9dd5a2017-01-16 13:20:08 +00001140 Enable optimizations based on the strict rules for overwriting polymorphic
1141 C++ objects, i.e. the vptr is invariant during an object's lifetime.
1142 This enables better devirtualization. Turned off by default, because it is
1143 still experimental.
1144
Justin Lebar84da8b22016-05-20 21:33:01 +00001145.. option:: -ffast-math
1146
1147 Enable fast-math mode. This defines the ``__FAST_MATH__`` preprocessor
1148 macro, and lets the compiler make aggressive, potentially-lossy assumptions
1149 about floating-point math. These include:
1150
1151 * Floating-point math obeys regular algebraic rules for real numbers (e.g.
1152 ``+`` and ``*`` are associative, ``x/y == x * (1/y)``, and
1153 ``(a + b) * c == a * c + b * c``),
1154 * operands to floating-point operations are not equal to ``NaN`` and
1155 ``Inf``, and
1156 * ``+0`` and ``-0`` are interchangeable.
1157
Sjoerd Meijer0a8d4212016-08-30 08:09:45 +00001158.. option:: -fdenormal-fp-math=[values]
1159
1160 Select which denormal numbers the code is permitted to require.
1161
1162 Valid values are: ``ieee``, ``preserve-sign``, and ``positive-zero``,
1163 which correspond to IEEE 754 denormal numbers, the sign of a
1164 flushed-to-zero number is preserved in the sign of 0, denormals are
1165 flushed to positive zero, respectively.
1166
Peter Collingbournefb532b92016-02-24 20:46:36 +00001167.. option:: -fwhole-program-vtables
1168
1169 Enable whole-program vtable optimizations, such as single-implementation
Peter Collingbourne3afb2662016-04-28 17:09:37 +00001170 devirtualization and virtual constant propagation, for classes with
1171 :doc:`hidden LTO visibility <LTOVisibility>`. Requires ``-flto``.
Peter Collingbournefb532b92016-02-24 20:46:36 +00001172
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001173.. option:: -fno-assume-sane-operator-new
1174
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001175 Don't assume that the C++'s new operator is sane.
1176
1177 This option tells the compiler to do not assume that C++'s global
1178 new operator will always return a pointer that does not alias any
1179 other pointer when the function returns.
1180
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001181.. option:: -ftrap-function=[name]
1182
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001183 Instruct code generator to emit a function call to the specified
1184 function name for ``__builtin_trap()``.
1185
1186 LLVM code generator translates ``__builtin_trap()`` to a trap
1187 instruction if it is supported by the target ISA. Otherwise, the
1188 builtin is translated into a call to ``abort``. If this option is
1189 set, then the code generator will always lower the builtin to a call
1190 to the specified function regardless of whether the target ISA has a
1191 trap instruction. This option is useful for environments (e.g.
1192 deeply embedded) where a trap cannot be properly handled, or when
1193 some custom behavior is desired.
1194
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001195.. option:: -ftls-model=[model]
1196
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001197 Select which TLS model to use.
1198
1199 Valid values are: ``global-dynamic``, ``local-dynamic``,
1200 ``initial-exec`` and ``local-exec``. The default value is
1201 ``global-dynamic``. The compiler may use a different model if the
1202 selected model is not supported by the target, or if a more
1203 efficient model can be used. The TLS model can be overridden per
1204 variable using the ``tls_model`` attribute.
1205
Chih-Hung Hsieh2c656c92015-07-28 16:27:56 +00001206.. option:: -femulated-tls
1207
1208 Select emulated TLS model, which overrides all -ftls-model choices.
1209
1210 In emulated TLS mode, all access to TLS variables are converted to
1211 calls to __emutls_get_address in the runtime library.
1212
Silviu Barangaf9671dd2013-10-21 10:54:53 +00001213.. option:: -mhwdiv=[values]
1214
1215 Select the ARM modes (arm or thumb) that support hardware division
1216 instructions.
1217
1218 Valid values are: ``arm``, ``thumb`` and ``arm,thumb``.
1219 This option is used to indicate which mode (arm or thumb) supports
1220 hardware division instructions. This only applies to the ARM
1221 architecture.
1222
Bernard Ogden18b57012013-10-29 09:47:51 +00001223.. option:: -m[no-]crc
1224
1225 Enable or disable CRC instructions.
1226
1227 This option is used to indicate whether CRC instructions are to
1228 be generated. This only applies to the ARM architecture.
1229
1230 CRC instructions are enabled by default on ARMv8.
1231
Amara Emerson05d816d2014-01-24 15:15:27 +00001232.. option:: -mgeneral-regs-only
Amara Emerson04e2ecf2014-01-23 15:48:30 +00001233
1234 Generate code which only uses the general purpose registers.
1235
1236 This option restricts the generated code to use general registers
1237 only. This only applies to the AArch64 architecture.
1238
Simon Dardisd0e83ba2016-05-27 15:13:31 +00001239.. option:: -mcompact-branches=[values]
1240
1241 Control the usage of compact branches for MIPSR6.
1242
1243 Valid values are: ``never``, ``optimal`` and ``always``.
1244 The default value is ``optimal`` which generates compact branches
1245 when a delay slot cannot be filled. ``never`` disables the usage of
1246 compact branches and ``always`` generates compact branches whenever
1247 possible.
1248
Yunzhong Gaoeecc9e972015-12-10 01:37:18 +00001249**-f[no-]max-type-align=[number]**
Fariborz Jahanianbcd82af2014-08-05 18:37:48 +00001250 Instruct the code generator to not enforce a higher alignment than the given
1251 number (of bytes) when accessing memory via an opaque pointer or reference.
1252 This cap is ignored when directly accessing a variable or when the pointee
1253 type has an explicit “aligned” attribute.
1254
1255 The value should usually be determined by the properties of the system allocator.
1256 Some builtin types, especially vector types, have very high natural alignments;
1257 when working with values of those types, Clang usually wants to use instructions
1258 that take advantage of that alignment. However, many system allocators do
1259 not promise to return memory that is more than 8-byte or 16-byte-aligned. Use
1260 this option to limit the alignment that the compiler can assume for an arbitrary
1261 pointer, which may point onto the heap.
1262
1263 This option does not affect the ABI alignment of types; the layout of structs and
1264 unions and the value returned by the alignof operator remain the same.
1265
1266 This option can be overridden on a case-by-case basis by putting an explicit
1267 “aligned” alignment on a struct, union, or typedef. For example:
1268
1269 .. code-block:: console
1270
1271 #include <immintrin.h>
1272 // Make an aligned typedef of the AVX-512 16-int vector type.
1273 typedef __v16si __aligned_v16si __attribute__((aligned(64)));
1274
1275 void initialize_vector(__aligned_v16si *v) {
1276 // The compiler may assume that ‘v’ is 64-byte aligned, regardless of the
Yunzhong Gaoeecc9e972015-12-10 01:37:18 +00001277 // value of -fmax-type-align.
Fariborz Jahanianbcd82af2014-08-05 18:37:48 +00001278 }
1279
Silviu Barangaf9671dd2013-10-21 10:54:53 +00001280
Bob Wilson3f2ed172014-06-17 00:45:30 +00001281Profile Guided Optimization
1282---------------------------
1283
1284Profile information enables better optimization. For example, knowing that a
1285branch is taken very frequently helps the compiler make better decisions when
1286ordering basic blocks. Knowing that a function ``foo`` is called more
1287frequently than another function ``bar`` helps the inliner.
1288
1289Clang supports profile guided optimization with two different kinds of
1290profiling. A sampling profiler can generate a profile with very low runtime
1291overhead, or you can build an instrumented version of the code that collects
1292more detailed profile information. Both kinds of profiles can provide execution
1293counts for instructions in the code and information on branches taken and
1294function invocation.
1295
1296Regardless of which kind of profiling you use, be careful to collect profiles
1297by running your code with inputs that are representative of the typical
1298behavior. Code that is not exercised in the profile will be optimized as if it
1299is unimportant, and the compiler may make poor optimization choices for code
1300that is disproportionately used while profiling.
1301
Diego Novillo46ab35d2015-05-28 21:30:04 +00001302Differences Between Sampling and Instrumentation
1303^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1304
1305Although both techniques are used for similar purposes, there are important
1306differences between the two:
1307
13081. Profile data generated with one cannot be used by the other, and there is no
1309 conversion tool that can convert one to the other. So, a profile generated
1310 via ``-fprofile-instr-generate`` must be used with ``-fprofile-instr-use``.
1311 Similarly, sampling profiles generated by external profilers must be
1312 converted and used with ``-fprofile-sample-use``.
1313
13142. Instrumentation profile data can be used for code coverage analysis and
1315 optimization.
1316
13173. Sampling profiles can only be used for optimization. They cannot be used for
1318 code coverage analysis. Although it would be technically possible to use
1319 sampling profiles for code coverage, sample-based profiles are too
1320 coarse-grained for code coverage purposes; it would yield poor results.
1321
13224. Sampling profiles must be generated by an external tool. The profile
1323 generated by that tool must then be converted into a format that can be read
1324 by LLVM. The section on sampling profilers describes one of the supported
1325 sampling profile formats.
1326
1327
Bob Wilson3f2ed172014-06-17 00:45:30 +00001328Using Sampling Profilers
1329^^^^^^^^^^^^^^^^^^^^^^^^
Diego Novilloa5256bf2014-04-23 15:21:07 +00001330
1331Sampling profilers are used to collect runtime information, such as
1332hardware counters, while your application executes. They are typically
Diego Novillo8ebff322014-04-23 15:21:20 +00001333very efficient and do not incur a large runtime overhead. The
Diego Novilloa5256bf2014-04-23 15:21:07 +00001334sample data collected by the profiler can be used during compilation
Diego Novillo8ebff322014-04-23 15:21:20 +00001335to determine what the most executed areas of the code are.
Diego Novilloa5256bf2014-04-23 15:21:07 +00001336
Diego Novilloa5256bf2014-04-23 15:21:07 +00001337Using the data from a sample profiler requires some changes in the way
1338a program is built. Before the compiler can use profiling information,
1339the code needs to execute under the profiler. The following is the
1340usual build cycle when using sample profilers for optimization:
1341
13421. Build the code with source line table information. You can use all the
1343 usual build flags that you always build your application with. The only
Diego Novillo8ebff322014-04-23 15:21:20 +00001344 requirement is that you add ``-gline-tables-only`` or ``-g`` to the
Diego Novilloa5256bf2014-04-23 15:21:07 +00001345 command line. This is important for the profiler to be able to map
1346 instructions back to source line locations.
1347
1348 .. code-block:: console
1349
1350 $ clang++ -O2 -gline-tables-only code.cc -o code
1351
13522. Run the executable under a sampling profiler. The specific profiler
1353 you use does not really matter, as long as its output can be converted
1354 into the format that the LLVM optimizer understands. Currently, there
1355 exists a conversion tool for the Linux Perf profiler
1356 (https://perf.wiki.kernel.org/), so these examples assume that you
1357 are using Linux Perf to profile your code.
1358
1359 .. code-block:: console
1360
1361 $ perf record -b ./code
1362
1363 Note the use of the ``-b`` flag. This tells Perf to use the Last Branch
1364 Record (LBR) to record call chains. While this is not strictly required,
1365 it provides better call information, which improves the accuracy of
1366 the profile data.
1367
13683. Convert the collected profile data to LLVM's sample profile format.
1369 This is currently supported via the AutoFDO converter ``create_llvm_prof``.
1370 It is available at http://github.com/google/autofdo. Once built and
1371 installed, you can convert the ``perf.data`` file to LLVM using
1372 the command:
1373
1374 .. code-block:: console
1375
1376 $ create_llvm_prof --binary=./code --out=code.prof
1377
Diego Novillo9e430842014-04-23 15:21:23 +00001378 This will read ``perf.data`` and the binary file ``./code`` and emit
Diego Novilloa5256bf2014-04-23 15:21:07 +00001379 the profile data in ``code.prof``. Note that if you ran ``perf``
1380 without the ``-b`` flag, you need to use ``--use_lbr=false`` when
1381 calling ``create_llvm_prof``.
1382
13834. Build the code again using the collected profile. This step feeds
1384 the profile back to the optimizers. This should result in a binary
Diego Novillo8ebff322014-04-23 15:21:20 +00001385 that executes faster than the original one. Note that you are not
1386 required to build the code with the exact same arguments that you
1387 used in the first step. The only requirement is that you build the code
1388 with ``-gline-tables-only`` and ``-fprofile-sample-use``.
Diego Novilloa5256bf2014-04-23 15:21:07 +00001389
1390 .. code-block:: console
1391
1392 $ clang++ -O2 -gline-tables-only -fprofile-sample-use=code.prof code.cc -o code
1393
1394
Diego Novillo46ab35d2015-05-28 21:30:04 +00001395Sample Profile Formats
1396""""""""""""""""""""""
Diego Novilloa5256bf2014-04-23 15:21:07 +00001397
Diego Novillo46ab35d2015-05-28 21:30:04 +00001398Since external profilers generate profile data in a variety of custom formats,
1399the data generated by the profiler must be converted into a format that can be
1400read by the backend. LLVM supports three different sample profile formats:
Diego Novilloa5256bf2014-04-23 15:21:07 +00001401
Diego Novillo46ab35d2015-05-28 21:30:04 +000014021. ASCII text. This is the easiest one to generate. The file is divided into
1403 sections, which correspond to each of the functions with profile
Diego Novillo33452762015-10-14 18:37:39 +00001404 information. The format is described below. It can also be generated from
1405 the binary or gcov formats using the ``llvm-profdata`` tool.
Diego Novilloe0d289e2015-05-22 16:05:07 +00001406
Diego Novillo46ab35d2015-05-28 21:30:04 +000014072. Binary encoding. This uses a more efficient encoding that yields smaller
Diego Novillo33452762015-10-14 18:37:39 +00001408 profile files. This is the format generated by the ``create_llvm_prof`` tool
1409 in http://github.com/google/autofdo.
Diego Novillo46ab35d2015-05-28 21:30:04 +00001410
14113. GCC encoding. This is based on the gcov format, which is accepted by GCC. It
Diego Novillo33452762015-10-14 18:37:39 +00001412 is only interesting in environments where GCC and Clang co-exist. This
1413 encoding is only generated by the ``create_gcov`` tool in
1414 http://github.com/google/autofdo. It can be read by LLVM and
1415 ``llvm-profdata``, but it cannot be generated by either.
Diego Novillo46ab35d2015-05-28 21:30:04 +00001416
1417If you are using Linux Perf to generate sampling profiles, you can use the
1418conversion tool ``create_llvm_prof`` described in the previous section.
1419Otherwise, you will need to write a conversion tool that converts your
1420profiler's native format into one of these three.
1421
1422
1423Sample Profile Text Format
1424""""""""""""""""""""""""""
1425
1426This section describes the ASCII text format for sampling profiles. It is,
1427arguably, the easiest one to generate. If you are interested in generating any
1428of the other two, consult the ``ProfileData`` library in in LLVM's source tree
Diego Novillo843dc6f2015-10-19 15:53:17 +00001429(specifically, ``include/llvm/ProfileData/SampleProfReader.h``).
Diego Novilloa5256bf2014-04-23 15:21:07 +00001430
1431.. code-block:: console
1432
1433 function1:total_samples:total_head_samples
Diego Novillo33452762015-10-14 18:37:39 +00001434 offset1[.discriminator]: number_of_samples [fn1:num fn2:num ... ]
1435 offset2[.discriminator]: number_of_samples [fn3:num fn4:num ... ]
1436 ...
1437 offsetN[.discriminator]: number_of_samples [fn5:num fn6:num ... ]
1438 offsetA[.discriminator]: fnA:num_of_total_samples
1439 offsetA1[.discriminator]: number_of_samples [fn7:num fn8:num ... ]
1440 offsetA1[.discriminator]: number_of_samples [fn9:num fn10:num ... ]
1441 offsetB[.discriminator]: fnB:num_of_total_samples
1442 offsetB1[.discriminator]: number_of_samples [fn11:num fn12:num ... ]
Diego Novilloa5256bf2014-04-23 15:21:07 +00001443
Diego Novillo33452762015-10-14 18:37:39 +00001444This is a nested tree in which the identation represents the nesting level
1445of the inline stack. There are no blank lines in the file. And the spacing
1446within a single line is fixed. Additional spaces will result in an error
1447while reading the file.
1448
1449Any line starting with the '#' character is completely ignored.
1450
1451Inlined calls are represented with indentation. The Inline stack is a
1452stack of source locations in which the top of the stack represents the
1453leaf function, and the bottom of the stack represents the actual
1454symbol to which the instruction belongs.
Diego Novillo8ebff322014-04-23 15:21:20 +00001455
Diego Novilloa5256bf2014-04-23 15:21:07 +00001456Function names must be mangled in order for the profile loader to
1457match them in the current translation unit. The two numbers in the
1458function header specify how many total samples were accumulated in the
1459function (first number), and the total number of samples accumulated
Diego Novillo8ebff322014-04-23 15:21:20 +00001460in the prologue of the function (second number). This head sample
1461count provides an indicator of how frequently the function is invoked.
Diego Novilloa5256bf2014-04-23 15:21:07 +00001462
Diego Novillo33452762015-10-14 18:37:39 +00001463There are two types of lines in the function body.
1464
1465- Sampled line represents the profile information of a source location.
1466 ``offsetN[.discriminator]: number_of_samples [fn5:num fn6:num ... ]``
1467
1468- Callsite line represents the profile information of an inlined callsite.
1469 ``offsetA[.discriminator]: fnA:num_of_total_samples``
1470
Diego Novilloa5256bf2014-04-23 15:21:07 +00001471Each sampled line may contain several items. Some are optional (marked
1472below):
1473
1474a. Source line offset. This number represents the line number
1475 in the function where the sample was collected. The line number is
1476 always relative to the line where symbol of the function is
1477 defined. So, if the function has its header at line 280, the offset
1478 13 is at line 293 in the file.
1479
Diego Novillo897c59c2014-04-23 15:21:21 +00001480 Note that this offset should never be a negative number. This could
1481 happen in cases like macros. The debug machinery will register the
1482 line number at the point of macro expansion. So, if the macro was
1483 expanded in a line before the start of the function, the profile
1484 converter should emit a 0 as the offset (this means that the optimizers
1485 will not be able to associate a meaningful weight to the instructions
1486 in the macro).
1487
Diego Novilloa5256bf2014-04-23 15:21:07 +00001488b. [OPTIONAL] Discriminator. This is used if the sampled program
1489 was compiled with DWARF discriminator support
Diego Novillo8ebff322014-04-23 15:21:20 +00001490 (http://wiki.dwarfstd.org/index.php?title=Path_Discriminators).
Diego Novillo897c59c2014-04-23 15:21:21 +00001491 DWARF discriminators are unsigned integer values that allow the
1492 compiler to distinguish between multiple execution paths on the
1493 same source line location.
Diego Novilloa5256bf2014-04-23 15:21:07 +00001494
Diego Novillo8ebff322014-04-23 15:21:20 +00001495 For example, consider the line of code ``if (cond) foo(); else bar();``.
1496 If the predicate ``cond`` is true 80% of the time, then the edge
1497 into function ``foo`` should be considered to be taken most of the
1498 time. But both calls to ``foo`` and ``bar`` are at the same source
1499 line, so a sample count at that line is not sufficient. The
1500 compiler needs to know which part of that line is taken more
1501 frequently.
1502
1503 This is what discriminators provide. In this case, the calls to
1504 ``foo`` and ``bar`` will be at the same line, but will have
1505 different discriminator values. This allows the compiler to correctly
1506 set edge weights into ``foo`` and ``bar``.
1507
1508c. Number of samples. This is an integer quantity representing the
1509 number of samples collected by the profiler at this source
1510 location.
Diego Novilloa5256bf2014-04-23 15:21:07 +00001511
1512d. [OPTIONAL] Potential call targets and samples. If present, this
1513 line contains a call instruction. This models both direct and
Diego Novilloa5256bf2014-04-23 15:21:07 +00001514 number of samples. For example,
1515
1516 .. code-block:: console
1517
1518 130: 7 foo:3 bar:2 baz:7
1519
1520 The above means that at relative line offset 130 there is a call
Diego Novillo8ebff322014-04-23 15:21:20 +00001521 instruction that calls one of ``foo()``, ``bar()`` and ``baz()``,
1522 with ``baz()`` being the relatively more frequently called target.
Diego Novilloa5256bf2014-04-23 15:21:07 +00001523
Diego Novillo33452762015-10-14 18:37:39 +00001524As an example, consider a program with the call chain ``main -> foo -> bar``.
1525When built with optimizations enabled, the compiler may inline the
1526calls to ``bar`` and ``foo`` inside ``main``. The generated profile
1527could then be something like this:
1528
1529.. code-block:: console
1530
1531 main:35504:0
1532 1: _Z3foov:35504
1533 2: _Z32bari:31977
1534 1.1: 31977
1535 2: 0
1536
1537This profile indicates that there were a total of 35,504 samples
1538collected in main. All of those were at line 1 (the call to ``foo``).
1539Of those, 31,977 were spent inside the body of ``bar``. The last line
1540of the profile (``2: 0``) corresponds to line 2 inside ``main``. No
1541samples were collected there.
Diego Novilloa5256bf2014-04-23 15:21:07 +00001542
Bob Wilson3f2ed172014-06-17 00:45:30 +00001543Profiling with Instrumentation
1544^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1545
1546Clang also supports profiling via instrumentation. This requires building a
1547special instrumented version of the code and has some runtime
1548overhead during the profiling, but it provides more detailed results than a
1549sampling profiler. It also provides reproducible results, at least to the
1550extent that the code behaves consistently across runs.
1551
1552Here are the steps for using profile guided optimization with
1553instrumentation:
1554
15551. Build an instrumented version of the code by compiling and linking with the
1556 ``-fprofile-instr-generate`` option.
1557
1558 .. code-block:: console
1559
1560 $ clang++ -O2 -fprofile-instr-generate code.cc -o code
1561
15622. Run the instrumented executable with inputs that reflect the typical usage.
1563 By default, the profile data will be written to a ``default.profraw`` file
Xinliang David Li7cd5e382016-07-20 23:32:50 +00001564 in the current directory. You can override that default by using option
1565 ``-fprofile-instr-generate=`` or by setting the ``LLVM_PROFILE_FILE``
1566 environment variable to specify an alternate file. If non-default file name
1567 is specified by both the environment variable and the command line option,
1568 the environment variable takes precedence. The file name pattern specified
1569 can include different modifiers: ``%p``, ``%h``, and ``%m``.
1570
Bob Wilson3f2ed172014-06-17 00:45:30 +00001571 Any instance of ``%p`` in that file name will be replaced by the process
1572 ID, so that you can easily distinguish the profile output from multiple
1573 runs.
1574
1575 .. code-block:: console
1576
1577 $ LLVM_PROFILE_FILE="code-%p.profraw" ./code
1578
Xinliang David Li7cd5e382016-07-20 23:32:50 +00001579 The modifier ``%h`` can be used in scenarios where the same instrumented
1580 binary is run in multiple different host machines dumping profile data
1581 to a shared network based storage. The ``%h`` specifier will be substituted
1582 with the hostname so that profiles collected from different hosts do not
1583 clobber each other.
1584
1585 While the use of ``%p`` specifier can reduce the likelihood for the profiles
1586 dumped from different processes to clobber each other, such clobbering can still
1587 happen because of the ``pid`` re-use by the OS. Another side-effect of using
1588 ``%p`` is that the storage requirement for raw profile data files is greatly
1589 increased. To avoid issues like this, the ``%m`` specifier can used in the profile
1590 name. When this specifier is used, the profiler runtime will substitute ``%m``
1591 with a unique integer identifier associated with the instrumented binary. Additionally,
1592 multiple raw profiles dumped from different processes that share a file system (can be
1593 on different hosts) will be automatically merged by the profiler runtime during the
1594 dumping. If the program links in multiple instrumented shared libraries, each library
1595 will dump the profile data into its own profile data file (with its unique integer
1596 id embedded in the profile name). Note that the merging enabled by ``%m`` is for raw
1597 profile data generated by profiler runtime. The resulting merged "raw" profile data
1598 file still needs to be converted to a different format expected by the compiler (
1599 see step 3 below).
1600
1601 .. code-block:: console
1602
1603 $ LLVM_PROFILE_FILE="code-%m.profraw" ./code
1604
1605
Bob Wilson3f2ed172014-06-17 00:45:30 +000016063. Combine profiles from multiple runs and convert the "raw" profile format to
Diego Novillo46ab35d2015-05-28 21:30:04 +00001607 the input expected by clang. Use the ``merge`` command of the
1608 ``llvm-profdata`` tool to do this.
Bob Wilson3f2ed172014-06-17 00:45:30 +00001609
1610 .. code-block:: console
1611
1612 $ llvm-profdata merge -output=code.profdata code-*.profraw
1613
1614 Note that this step is necessary even when there is only one "raw" profile,
1615 since the merge operation also changes the file format.
1616
16174. Build the code again using the ``-fprofile-instr-use`` option to specify the
1618 collected profile data.
1619
1620 .. code-block:: console
1621
1622 $ clang++ -O2 -fprofile-instr-use=code.profdata code.cc -o code
1623
1624 You can repeat step 4 as often as you like without regenerating the
1625 profile. As you make changes to your code, clang may no longer be able to
1626 use the profile data. It will warn you when this happens.
1627
Sean Silvaa834ff22016-07-16 02:54:58 +00001628Profile generation using an alternative instrumentation method can be
1629controlled by the GCC-compatible flags ``-fprofile-generate`` and
1630``-fprofile-use``. Although these flags are semantically equivalent to
1631their GCC counterparts, they *do not* handle GCC-compatible profiles.
1632They are only meant to implement GCC's semantics with respect to
1633profile creation and use.
Diego Novillo578caf52015-07-09 17:23:53 +00001634
1635.. option:: -fprofile-generate[=<dirname>]
1636
Sean Silvaa834ff22016-07-16 02:54:58 +00001637 The ``-fprofile-generate`` and ``-fprofile-generate=`` flags will use
1638 an alterantive instrumentation method for profile generation. When
1639 given a directory name, it generates the profile file
Xinliang David Lib7b335a2016-07-22 22:25:01 +00001640 ``default_%m.profraw`` in the directory named ``dirname`` if specified.
1641 If ``dirname`` does not exist, it will be created at runtime. ``%m`` specifier
1642 will be substibuted with a unique id documented in step 2 above. In other words,
1643 with ``-fprofile-generate[=<dirname>]`` option, the "raw" profile data automatic
1644 merging is turned on by default, so there will no longer any risk of profile
1645 clobbering from different running processes. For example,
Diego Novillo578caf52015-07-09 17:23:53 +00001646
1647 .. code-block:: console
1648
1649 $ clang++ -O2 -fprofile-generate=yyy/zzz code.cc -o code
1650
1651 When ``code`` is executed, the profile will be written to the file
Xinliang David Lib7b335a2016-07-22 22:25:01 +00001652 ``yyy/zzz/default_xxxx.profraw``.
Diego Novillo578caf52015-07-09 17:23:53 +00001653
Xinliang David Lib7b335a2016-07-22 22:25:01 +00001654 To generate the profile data file with the compiler readable format, the
1655 ``llvm-profdata`` tool can be used with the profile directory as the input:
Diego Novillo578caf52015-07-09 17:23:53 +00001656
Xinliang David Lib7b335a2016-07-22 22:25:01 +00001657 .. code-block:: console
Diego Novillo578caf52015-07-09 17:23:53 +00001658
Xinliang David Lib7b335a2016-07-22 22:25:01 +00001659 $ llvm-profdata merge -output=code.profdata yyy/zzz/
1660
1661 If the user wants to turn off the auto-merging feature, or simply override the
1662 the profile dumping path specified at command line, the environment variable
1663 ``LLVM_PROFILE_FILE`` can still be used to override
1664 the directory and filename for the profile file at runtime.
Diego Novillo578caf52015-07-09 17:23:53 +00001665
1666.. option:: -fprofile-use[=<pathname>]
1667
1668 Without any other arguments, ``-fprofile-use`` behaves identically to
1669 ``-fprofile-instr-use``. Otherwise, if ``pathname`` is the full path to a
1670 profile file, it reads from that file. If ``pathname`` is a directory name,
1671 it reads from ``pathname/default.profdata``.
1672
Diego Novillo758f3f52015-08-05 21:49:51 +00001673Disabling Instrumentation
1674^^^^^^^^^^^^^^^^^^^^^^^^^
1675
1676In certain situations, it may be useful to disable profile generation or use
1677for specific files in a build, without affecting the main compilation flags
1678used for the other files in the project.
1679
1680In these cases, you can use the flag ``-fno-profile-instr-generate`` (or
1681``-fno-profile-generate``) to disable profile generation, and
1682``-fno-profile-instr-use`` (or ``-fno-profile-use``) to disable profile use.
1683
1684Note that these flags should appear after the corresponding profile
1685flags to have an effect.
Bob Wilson3f2ed172014-06-17 00:45:30 +00001686
Paul Robinson0334a042015-12-19 19:41:48 +00001687Controlling Debug Information
1688-----------------------------
1689
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001690Controlling Size of Debug Information
Paul Robinson0334a042015-12-19 19:41:48 +00001691^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001692
1693Debug info kind generated by Clang can be set by one of the flags listed
1694below. If multiple flags are present, the last one is used.
1695
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001696.. option:: -g0
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001697
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001698 Don't generate any debug info (default).
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001699
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001700.. option:: -gline-tables-only
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001701
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001702 Generate line number tables only.
1703
1704 This kind of debug info allows to obtain stack traces with function names,
1705 file names and line numbers (by such tools as ``gdb`` or ``addr2line``). It
1706 doesn't contain any other data (e.g. description of local variables or
1707 function parameters).
1708
Adrian Prantl4ad03dc2014-06-13 23:35:54 +00001709.. option:: -fstandalone-debug
Adrian Prantl36b80672014-06-13 21:12:31 +00001710
1711 Clang supports a number of optimizations to reduce the size of debug
1712 information in the binary. They work based on the assumption that
1713 the debug type information can be spread out over multiple
1714 compilation units. For instance, Clang will not emit type
1715 definitions for types that are not needed by a module and could be
1716 replaced with a forward declaration. Further, Clang will only emit
1717 type info for a dynamic C++ class in the module that contains the
1718 vtable for the class.
1719
Adrian Prantl4ad03dc2014-06-13 23:35:54 +00001720 The **-fstandalone-debug** option turns off these optimizations.
Adrian Prantl36b80672014-06-13 21:12:31 +00001721 This is useful when working with 3rd-party libraries that don't come
1722 with debug information. Note that Clang will never emit type
1723 information for types that are not referenced at all by the program.
1724
Adrian Prantl4ad03dc2014-06-13 23:35:54 +00001725.. option:: -fno-standalone-debug
1726
1727 On Darwin **-fstandalone-debug** is enabled by default. The
1728 **-fno-standalone-debug** option can be used to get to turn on the
1729 vtable-based optimization described above.
1730
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001731.. option:: -g
1732
1733 Generate complete debug info.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001734
Amjad Aboud546bc112017-02-09 22:07:24 +00001735Controlling Macro Debug Info Generation
1736^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1737
1738Debug info for C preprocessor macros increases the size of debug information in
1739the binary. Macro debug info generated by Clang can be controlled by the flags
1740listed below.
1741
1742.. option:: -fdebug-macro
1743
1744 Generate debug info for preprocessor macros. This flag is discarded when
1745 **-g0** is enabled.
1746
1747.. option:: -fno-debug-macro
1748
1749 Do not generate debug info for preprocessor macros (default).
1750
Paul Robinson0334a042015-12-19 19:41:48 +00001751Controlling Debugger "Tuning"
1752^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1753
1754While Clang generally emits standard DWARF debug info (http://dwarfstd.org),
1755different debuggers may know how to take advantage of different specific DWARF
1756features. You can "tune" the debug info for one of several different debuggers.
1757
1758.. option:: -ggdb, -glldb, -gsce
1759
Paul Robinson8ce9b442016-08-15 18:45:52 +00001760 Tune the debug info for the ``gdb``, ``lldb``, or Sony PlayStation\ |reg|
Paul Robinson0334a042015-12-19 19:41:48 +00001761 debugger, respectively. Each of these options implies **-g**. (Therefore, if
1762 you want both **-gline-tables-only** and debugger tuning, the tuning option
1763 must come first.)
1764
1765
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00001766Comment Parsing Options
Dmitri Gribenko28bfb482014-03-06 16:32:09 +00001767-----------------------
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00001768
1769Clang parses Doxygen and non-Doxygen style documentation comments and attaches
1770them to the appropriate declaration nodes. By default, it only parses
1771Doxygen-style comments and ignores ordinary comments starting with ``//`` and
1772``/*``.
1773
Dmitri Gribenko28bfb482014-03-06 16:32:09 +00001774.. option:: -Wdocumentation
1775
1776 Emit warnings about use of documentation comments. This warning group is off
1777 by default.
1778
1779 This includes checking that ``\param`` commands name parameters that actually
1780 present in the function signature, checking that ``\returns`` is used only on
1781 functions that actually return a value etc.
1782
1783.. option:: -Wno-documentation-unknown-command
1784
1785 Don't warn when encountering an unknown Doxygen command.
1786
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00001787.. option:: -fparse-all-comments
1788
1789 Parse all comments as documentation comments (including ordinary comments
1790 starting with ``//`` and ``/*``).
1791
Dmitri Gribenko28bfb482014-03-06 16:32:09 +00001792.. option:: -fcomment-block-commands=[commands]
1793
1794 Define custom documentation commands as block commands. This allows Clang to
1795 construct the correct AST for these custom commands, and silences warnings
1796 about unknown commands. Several commands must be separated by a comma
1797 *without trailing space*; e.g. ``-fcomment-block-commands=foo,bar`` defines
1798 custom commands ``\foo`` and ``\bar``.
1799
1800 It is also possible to use ``-fcomment-block-commands`` several times; e.g.
1801 ``-fcomment-block-commands=foo -fcomment-block-commands=bar`` does the same
1802 as above.
1803
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001804.. _c:
1805
1806C Language Features
1807===================
1808
1809The support for standard C in clang is feature-complete except for the
1810C99 floating-point pragmas.
1811
1812Extensions supported by clang
1813-----------------------------
1814
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001815See :doc:`LanguageExtensions`.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001816
1817Differences between various standard modes
1818------------------------------------------
1819
1820clang supports the -std option, which changes what language mode clang
Richard Smithab506ad2014-10-20 23:26:58 +00001821uses. The supported modes for C are c89, gnu89, c94, c99, gnu99, c11,
1822gnu11, and various aliases for those modes. If no -std option is
1823specified, clang defaults to gnu11 mode. Many C99 and C11 features are
1824supported in earlier modes as a conforming extension, with a warning. Use
1825``-pedantic-errors`` to request an error if a feature from a later standard
1826revision is used in an earlier mode.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001827
1828Differences between all ``c*`` and ``gnu*`` modes:
1829
1830- ``c*`` modes define "``__STRICT_ANSI__``".
1831- Target-specific defines not prefixed by underscores, like "linux",
1832 are defined in ``gnu*`` modes.
1833- Trigraphs default to being off in ``gnu*`` modes; they can be enabled by
1834 the -trigraphs option.
1835- The parser recognizes "asm" and "typeof" as keywords in ``gnu*`` modes;
1836 the variants "``__asm__``" and "``__typeof__``" are recognized in all
1837 modes.
1838- The Apple "blocks" extension is recognized by default in ``gnu*`` modes
1839 on some platforms; it can be enabled in any mode with the "-fblocks"
1840 option.
1841- Arrays that are VLA's according to the standard, but which can be
1842 constant folded by the frontend are treated as fixed size arrays.
1843 This occurs for things like "int X[(1, 2)];", which is technically a
1844 VLA. ``c*`` modes are strictly compliant and treat these as VLAs.
1845
1846Differences between ``*89`` and ``*99`` modes:
1847
1848- The ``*99`` modes default to implementing "inline" as specified in C99,
1849 while the ``*89`` modes implement the GNU version. This can be
1850 overridden for individual functions with the ``__gnu_inline__``
1851 attribute.
1852- Digraphs are not recognized in c89 mode.
1853- The scope of names defined inside a "for", "if", "switch", "while",
1854 or "do" statement is different. (example: "``if ((struct x {int
1855 x;}*)0) {}``".)
1856- ``__STDC_VERSION__`` is not defined in ``*89`` modes.
1857- "inline" is not recognized as a keyword in c89 mode.
1858- "restrict" is not recognized as a keyword in ``*89`` modes.
1859- Commas are allowed in integer constant expressions in ``*99`` modes.
1860- Arrays which are not lvalues are not implicitly promoted to pointers
1861 in ``*89`` modes.
1862- Some warnings are different.
1863
Richard Smithab506ad2014-10-20 23:26:58 +00001864Differences between ``*99`` and ``*11`` modes:
1865
1866- Warnings for use of C11 features are disabled.
1867- ``__STDC_VERSION__`` is defined to ``201112L`` rather than ``199901L``.
1868
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001869c94 mode is identical to c89 mode except that digraphs are enabled in
1870c94 mode (FIXME: And ``__STDC_VERSION__`` should be defined!).
1871
1872GCC extensions not implemented yet
1873----------------------------------
1874
1875clang tries to be compatible with gcc as much as possible, but some gcc
1876extensions are not implemented yet:
1877
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001878- clang does not support decimal floating point types (``_Decimal32`` and
1879 friends) or fixed-point types (``_Fract`` and friends); nobody has
1880 expressed interest in these features yet, so it's hard to say when
1881 they will be implemented.
1882- clang does not support nested functions; this is a complex feature
1883 which is infrequently used, so it is unlikely to be implemented
1884 anytime soon. In C++11 it can be emulated by assigning lambda
1885 functions to local variables, e.g:
1886
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001887 .. code-block:: cpp
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001888
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001889 auto const local_function = [&](int parameter) {
1890 // Do something
1891 };
1892 ...
1893 local_function(1);
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001894
Michael Kuperstein94b25ec2016-12-12 19:11:39 +00001895- clang only supports global register variables when the register specified
1896 is non-allocatable (e.g. the stack pointer). Support for general global
1897 register variables is unlikely to be implemented soon because it requires
1898 additional LLVM backend support.
Andrey Bokhanko5dfd5b62016-02-11 13:27:02 +00001899- clang does not support static initialization of flexible array
1900 members. This appears to be a rarely used extension, but could be
1901 implemented pending user demand.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001902- clang does not support
1903 ``__builtin_va_arg_pack``/``__builtin_va_arg_pack_len``. This is
1904 used rarely, but in some potentially interesting places, like the
1905 glibc headers, so it may be implemented pending user demand. Note
1906 that because clang pretends to be like GCC 4.2, and this extension
1907 was introduced in 4.3, the glibc headers will not try to use this
1908 extension with clang at the moment.
1909- clang does not support the gcc extension for forward-declaring
1910 function parameters; this has not shown up in any real-world code
1911 yet, though, so it might never be implemented.
1912
1913This is not a complete list; if you find an unsupported extension
1914missing from this list, please send an e-mail to cfe-dev. This list
1915currently excludes C++; see :ref:`C++ Language Features <cxx>`. Also, this
1916list does not include bugs in mostly-implemented features; please see
1917the `bug
Ismail Donmezcb17fbb2017-02-17 08:26:54 +00001918tracker <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 +00001919for known existing bugs (FIXME: Is there a section for bug-reporting
1920guidelines somewhere?).
1921
1922Intentionally unsupported GCC extensions
1923----------------------------------------
1924
1925- clang does not support the gcc extension that allows variable-length
1926 arrays in structures. This is for a few reasons: one, it is tricky to
1927 implement, two, the extension is completely undocumented, and three,
1928 the extension appears to be rarely used. Note that clang *does*
1929 support flexible array members (arrays with a zero or unspecified
1930 size at the end of a structure).
1931- clang does not have an equivalent to gcc's "fold"; this means that
1932 clang doesn't accept some constructs gcc might accept in contexts
1933 where a constant expression is required, like "x-x" where x is a
1934 variable.
1935- clang does not support ``__builtin_apply`` and friends; this extension
1936 is extremely obscure and difficult to implement reliably.
1937
1938.. _c_ms:
1939
1940Microsoft extensions
1941--------------------
1942
Reid Kleckner2a5d34b2016-03-28 20:42:41 +00001943clang has support for many extensions from Microsoft Visual C++. To enable these
1944extensions, use the ``-fms-extensions`` command-line option. This is the default
1945for Windows targets. Clang does not implement every pragma or declspec provided
1946by MSVC, but the popular ones, such as ``__declspec(dllexport)`` and ``#pragma
1947comment(lib)`` are well supported.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001948
Richard Smith48d1b652013-12-12 02:42:17 +00001949clang has a ``-fms-compatibility`` flag that makes clang accept enough
Reid Kleckner993e72a2013-09-20 17:04:25 +00001950invalid C++ to be able to parse most Microsoft headers. For example, it
1951allows `unqualified lookup of dependent base class members
Reid Klecknereb248d72013-09-20 17:54:39 +00001952<http://clang.llvm.org/compatibility.html#dep_lookup_bases>`_, which is
1953a common compatibility issue with clang. This flag is enabled by default
Reid Kleckner993e72a2013-09-20 17:04:25 +00001954for Windows targets.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001955
Richard Smith48d1b652013-12-12 02:42:17 +00001956``-fdelayed-template-parsing`` lets clang delay parsing of function template
1957definitions until the end of a translation unit. This flag is enabled by
1958default for Windows targets.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001959
Reid Kleckner2a5d34b2016-03-28 20:42:41 +00001960For compatibility with existing code that compiles with MSVC, clang defines the
1961``_MSC_VER`` and ``_MSC_FULL_VER`` macros. These default to the values of 1800
1962and 180000000 respectively, making clang look like an early release of Visual
1963C++ 2013. The ``-fms-compatibility-version=`` flag overrides these values. It
1964accepts a dotted version tuple, such as 19.00.23506. Changing the MSVC
1965compatibility version makes clang behave more like that version of MSVC. For
1966example, ``-fms-compatibility-version=19`` will enable C++14 features and define
1967``char16_t`` and ``char32_t`` as builtin types.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001968
1969.. _cxx:
1970
1971C++ Language Features
1972=====================
1973
1974clang fully implements all of standard C++98 except for exported
Richard Smith48d1b652013-12-12 02:42:17 +00001975templates (which were removed in C++11), and all of standard C++11
1976and the current draft standard for C++1y.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001977
1978Controlling implementation limits
1979---------------------------------
1980
Richard Smithb3a14522013-02-22 01:59:51 +00001981.. option:: -fbracket-depth=N
1982
1983 Sets the limit for nested parentheses, brackets, and braces to N. The
1984 default is 256.
1985
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001986.. option:: -fconstexpr-depth=N
Sean Silvabf9b4cd2012-12-13 01:10:46 +00001987
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00001988 Sets the limit for recursive constexpr function invocations to N. The
1989 default is 512.
1990
1991.. option:: -ftemplate-depth=N
1992
1993 Sets the limit for recursively nested template instantiations to N. The
Richard Smith79c927b2013-11-06 19:31:51 +00001994 default is 256.
1995
1996.. option:: -foperator-arrow-depth=N
1997
1998 Sets the limit for iterative calls to 'operator->' functions to N. The
1999 default is 256.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002000
2001.. _objc:
2002
2003Objective-C Language Features
2004=============================
2005
2006.. _objcxx:
2007
2008Objective-C++ Language Features
2009===============================
2010
Alexey Bataevae8c17e2015-08-24 05:31:10 +00002011.. _openmp:
2012
2013OpenMP Features
2014===============
2015
2016Clang supports all OpenMP 3.1 directives and clauses. In addition, some
2017features of OpenMP 4.0 are supported. For example, ``#pragma omp simd``,
2018``#pragma omp for simd``, ``#pragma omp parallel for simd`` directives, extended
2019set of atomic constructs, ``proc_bind`` clause for all parallel-based
2020directives, ``depend`` clause for ``#pragma omp task`` directive (except for
2021array sections), ``#pragma omp cancel`` and ``#pragma omp cancellation point``
2022directives, and ``#pragma omp taskgroup`` directive.
2023
Aaron Ballman51fb0312016-07-15 13:13:45 +00002024Use `-fopenmp` to enable OpenMP. Support for OpenMP can be disabled with
2025`-fno-openmp`.
Alexey Bataevae8c17e2015-08-24 05:31:10 +00002026
2027Controlling implementation limits
2028---------------------------------
2029
2030.. option:: -fopenmp-use-tls
2031
2032 Controls code generation for OpenMP threadprivate variables. In presence of
2033 this option all threadprivate variables are generated the same way as thread
Aaron Ballman51fb0312016-07-15 13:13:45 +00002034 local variables, using TLS support. If `-fno-openmp-use-tls`
Alexey Bataevae8c17e2015-08-24 05:31:10 +00002035 is provided or target does not support TLS, code generation for threadprivate
2036 variables relies on OpenMP runtime library.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002037
Anastasia Stulova18e165f2017-01-12 17:52:22 +00002038.. _opencl:
2039
2040OpenCL Features
2041===============
2042
2043Clang can be used to compile OpenCL kernels for execution on a device
2044(e.g. GPU). It is possible to compile the kernel into a binary (e.g. for AMD or
2045Nvidia targets) that can be uploaded to run directly on a device (e.g. using
2046`clCreateProgramWithBinary
2047<https://www.khronos.org/registry/OpenCL/specs/opencl-1.1.pdf#111>`_) or
2048into generic bitcode files loadable into other toolchains.
2049
2050Compiling to a binary using the default target from the installation can be done
2051as follows:
2052
2053 .. code-block:: console
2054
2055 $ echo "kernel void k(){}" > test.cl
2056 $ clang test.cl
2057
2058Compiling for a specific target can be done by specifying the triple corresponding
2059to the target, for example:
2060
2061 .. code-block:: console
2062
2063 $ clang -target nvptx64-unknown-unknown test.cl
2064 $ clang -target amdgcn-amd-amdhsa-opencl test.cl
2065
2066Compiling to bitcode can be done as follows:
2067
2068 .. code-block:: console
2069
2070 $ clang -c -emit-llvm test.cl
2071
2072This will produce a generic test.bc file that can be used in vendor toolchains
2073to perform machine code generation.
2074
2075Clang currently supports OpenCL C language standards up to v2.0.
2076
2077OpenCL Specific Options
2078-----------------------
2079
2080Most of the OpenCL build options from `the specification v2.0 section 5.8.4
2081<https://www.khronos.org/registry/cl/specs/opencl-2.0.pdf#200>`_ are available.
2082
2083Examples:
2084
2085 .. code-block:: console
2086
2087 $ clang -cl-std=CL2.0 -cl-single-precision-constant test.cl
2088
2089Some extra options are available to support special OpenCL features.
2090
2091.. option:: -finclude-default-header
2092
2093Loads standard includes during compilations. By default OpenCL headers are not
2094loaded and therefore standard library includes are not available. To load them
2095automatically a flag has been added to the frontend (see also :ref:`the section
2096on the OpenCL Header <opencl_header>`):
2097
2098 .. code-block:: console
2099
2100 $ clang -Xclang -finclude-default-header test.cl
2101
2102Alternatively ``-include`` or ``-I`` followed by the path to the header location
2103can be given manually.
2104
2105 .. code-block:: console
2106
2107 $ clang -I<path to clang>/lib/Headers/opencl-c.h test.cl
2108
2109In this case the kernel code should contain ``#include <opencl-c.h>`` just as a
2110regular C include.
2111
Anastasia Stulovab376bee2017-02-16 12:49:29 +00002112.. _opencl_cl_ext:
2113
Anastasia Stulova18e165f2017-01-12 17:52:22 +00002114.. option:: -cl-ext
2115
2116Disables support of OpenCL extensions. All OpenCL targets provide a list
2117of extensions that they support. Clang allows to amend this using the ``-cl-ext``
2118flag with a comma-separated list of extensions prefixed with ``'+'`` or ``'-'``.
2119The syntax: ``-cl-ext=<(['-'|'+']<extension>[,])+>``, where extensions
2120can be either one of `the OpenCL specification extensions
2121<https://www.khronos.org/registry/cl/sdk/2.0/docs/man/xhtml/EXTENSION.html>`_
2122or any known vendor extension. Alternatively, ``'all'`` can be used to enable
2123or disable all known extensions.
2124Example disabling double support for the 64-bit SPIR target:
2125
2126 .. code-block:: console
2127
2128 $ clang -cc1 -triple spir64-unknown-unknown -cl-ext=-cl_khr_fp64 test.cl
2129
2130Enabling all extensions except double support in R600 AMD GPU can be done using:
2131
2132 .. code-block:: console
2133
2134 $ clang -cc1 -triple r600-unknown-unknown -cl-ext=-all,+cl_khr_fp16 test.cl
2135
2136.. _opencl_fake_address_space_map:
2137
2138.. option:: -ffake-address-space-map
2139
2140Overrides the target address space map with a fake map.
2141This allows adding explicit address space IDs to the bitcode for non-segmented
2142memory architectures that don't have separate IDs for each of the OpenCL
2143logical address spaces by default. Passing ``-ffake-address-space-map`` will
2144add/override address spaces of the target compiled for with the following values:
2145``1-global``, ``2-constant``, ``3-local``, ``4-generic``. The private address
2146space is represented by the absence of an address space attribute in the IR (see
2147also :ref:`the section on the address space attribute <opencl_addrsp>`).
2148
2149 .. code-block:: console
2150
2151 $ clang -ffake-address-space-map test.cl
2152
2153Some other flags used for the compilation for C can also be passed while
2154compiling for OpenCL, examples: ``-c``, ``-O<1-4|s>``, ``-o``, ``-emit-llvm``, etc.
2155
2156OpenCL Targets
2157--------------
2158
2159OpenCL targets are derived from the regular Clang target classes. The OpenCL
2160specific parts of the target representation provide address space mapping as
2161well as a set of supported extensions.
2162
2163Specific Targets
2164^^^^^^^^^^^^^^^^
2165
2166There is a set of concrete HW architectures that OpenCL can be compiled for.
2167
2168- For AMD target:
2169
2170 .. code-block:: console
2171
2172 $ clang -target amdgcn-amd-amdhsa-opencl test.cl
2173
2174- For Nvidia architectures:
2175
2176 .. code-block:: console
2177
2178 $ clang -target nvptx64-unknown-unknown test.cl
2179
2180
2181Generic Targets
2182^^^^^^^^^^^^^^^
2183
2184- SPIR is available as a generic target to allow portable bitcode to be produced
2185 that can be used across GPU toolchains. The implementation follows `the SPIR
2186 specification <https://www.khronos.org/spir>`_. There are two flavors
2187 available for 32 and 64 bits.
2188
2189 .. code-block:: console
2190
2191 $ clang -target spir-unknown-unknown test.cl
2192 $ clang -target spir64-unknown-unknown test.cl
2193
2194 All known OpenCL extensions are supported in the SPIR targets. Clang will
2195 generate SPIR v1.2 compatible IR for OpenCL versions up to 2.0 and SPIR v2.0
2196 for OpenCL v2.0.
2197
2198- x86 is used by some implementations that are x86 compatible and currently
2199 remains for backwards compatibility (with older implementations prior to
2200 SPIR target support). For "non-SPMD" targets which cannot spawn multiple
2201 work-items on the fly using hardware, which covers practically all non-GPU
2202 devices such as CPUs and DSPs, additional processing is needed for the kernels
2203 to support multiple work-item execution. For this, a 3rd party toolchain,
2204 such as for example `POCL <http://portablecl.org/>`_, can be used.
2205
2206 This target does not support multiple memory segments and, therefore, the fake
2207 address space map can be added using the :ref:`-ffake-address-space-map
2208 <opencl_fake_address_space_map>` flag.
2209
2210.. _opencl_header:
2211
2212OpenCL Header
2213-------------
2214
2215By default Clang will not include standard headers and therefore OpenCL builtin
2216functions and some types (i.e. vectors) are unknown. The default CL header is,
2217however, provided in the Clang installation and can be enabled by passing the
2218``-finclude-default-header`` flag to the Clang frontend.
2219
2220 .. code-block:: console
2221
2222 $ echo "bool is_wg_uniform(int i){return get_enqueued_local_size(i)==get_local_size(i);}" > test.cl
2223 $ clang -Xclang -finclude-default-header -cl-std=CL2.0 test.cl
2224
2225Because the header is very large and long to parse, PCH (:doc:`PCHInternals`)
2226and modules (:doc:`Modules`) are used internally to improve the compilation
2227speed.
2228
2229To enable modules for OpenCL:
2230
2231 .. code-block:: console
2232
2233 $ 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
2234
Anastasia Stulovab376bee2017-02-16 12:49:29 +00002235OpenCL Extensions
2236-----------------
2237
2238All of the ``cl_khr_*`` extensions from `the official OpenCL specification
2239<https://www.khronos.org/registry/OpenCL/sdk/2.0/docs/man/xhtml/EXTENSION.html>`_
2240up to and including version 2.0 are available and set per target depending on the
2241support available in the specific architecture.
2242
2243It is possible to alter the default extensions setting per target using
2244``-cl-ext`` flag. (See :ref:`flags description <opencl_cl_ext>` for more details).
2245
2246Vendor extensions can be added flexibly by declaring the list of types and
2247functions associated with each extensions enclosed within the following
2248compiler pragma directives:
2249
2250 .. code-block:: c
2251
2252 #pragma OPENCL EXTENSION the_new_extension_name : begin
2253 // declare types and functions associated with the extension here
2254 #pragma OPENCL EXTENSION the_new_extension_name : end
2255
2256For example, parsing the following code adds ``my_t`` type and ``my_func``
2257function to the custom ``my_ext`` extension.
2258
2259 .. code-block:: c
2260
2261 #pragma OPENCL EXTENSION my_ext : begin
2262 typedef struct{
2263 int a;
2264 }my_t;
2265 void my_func(my_t);
2266 #pragma OPENCL EXTENSION my_ext : end
2267
2268Declaring the same types in different vendor extensions is disallowed.
2269
Anastasia Stulova18e165f2017-01-12 17:52:22 +00002270OpenCL Metadata
2271---------------
2272
2273Clang uses metadata to provide additional OpenCL semantics in IR needed for
2274backends and OpenCL runtime.
2275
2276Each kernel will have function metadata attached to it, specifying the arguments.
2277Kernel argument metadata is used to provide source level information for querying
2278at runtime, for example using the `clGetKernelArgInfo
2279<https://www.khronos.org/registry/OpenCL/specs/opencl-1.2.pdf#167>`_
2280call.
2281
2282Note that ``-cl-kernel-arg-info`` enables more information about the original CL
2283code to be added e.g. kernel parameter names will appear in the OpenCL metadata
2284along with other information.
2285
2286The IDs used to encode the OpenCL's logical address spaces in the argument info
2287metadata follows the SPIR address space mapping as defined in the SPIR
2288specification `section 2.2
2289<https://www.khronos.org/registry/spir/specs/spir_spec-2.0.pdf#18>`_
2290
2291OpenCL-Specific Attributes
2292--------------------------
2293
2294OpenCL support in Clang contains a set of attribute taken directly from the
2295specification as well as additional attributes.
2296
2297See also :doc:`AttributeReference`.
2298
2299nosvm
2300^^^^^
2301
2302Clang supports this attribute to comply to OpenCL v2.0 conformance, but it
2303does not have any effect on the IR. For more details reffer to the specification
2304`section 6.7.2
2305<https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#49>`_
2306
2307
Anastasia Stulovab376bee2017-02-16 12:49:29 +00002308opencl_unroll_hint
Anastasia Stulova18e165f2017-01-12 17:52:22 +00002309^^^^^^^^^^^^^^^^^^
2310
2311The implementation of this feature mirrors the unroll hint for C.
2312More details on the syntax can be found in the specification
2313`section 6.11.5
2314<https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#61>`_
2315
2316convergent
2317^^^^^^^^^^
2318
2319To make sure no invalid optimizations occur for single program multiple data
2320(SPMD) / single instruction multiple thread (SIMT) Clang provides attributes that
2321can be used for special functions that have cross work item semantics.
2322An example is the subgroup operations such as `intel_sub_group_shuffle
2323<https://www.khronos.org/registry/cl/extensions/intel/cl_intel_subgroups.txt>`_
2324
2325 .. code-block:: c
2326
2327 // Define custom my_sub_group_shuffle(data, c)
2328 // that makes use of intel_sub_group_shuffle
Aaron Ballman37ff16f2017-01-16 13:42:21 +00002329 r1 = ...
Anastasia Stulova18e165f2017-01-12 17:52:22 +00002330 if (r0) r1 = computeA();
2331 // Shuffle data from r1 into r3
2332 // of threads id r2.
2333 r3 = my_sub_group_shuffle(r1, r2);
2334 if (r0) r3 = computeB();
2335
2336with non-SPMD semantics this is optimized to the following equivalent code:
2337
2338 .. code-block:: c
2339
Aaron Ballman37ff16f2017-01-16 13:42:21 +00002340 r1 = ...
Anastasia Stulova18e165f2017-01-12 17:52:22 +00002341 if (!r0)
2342 // Incorrect functionality! The data in r1
2343 // have not been computed by all threads yet.
2344 r3 = my_sub_group_shuffle(r1, r2);
2345 else {
2346 r1 = computeA();
2347 r3 = my_sub_group_shuffle(r1, r2);
2348 r3 = computeB();
2349 }
2350
2351Declaring the function ``my_sub_group_shuffle`` with the convergent attribute
2352would prevent this:
2353
2354 .. code-block:: c
2355
2356 my_sub_group_shuffle() __attribute__((convergent));
2357
2358Using ``convergent`` guarantees correct execution by keeping CFG equivalence
2359wrt operations marked as ``convergent``. CFG ``G´`` is equivalent to ``G`` wrt
2360node ``Ni`` : ``iff ∀ Nj (i≠j)`` domination and post-domination relations with
2361respect to ``Ni`` remain the same in both ``G`` and ``G´``.
2362
2363noduplicate
2364^^^^^^^^^^^
2365
2366``noduplicate`` is more restrictive with respect to optimizations than
2367``convergent`` because a convergent function only preserves CFG equivalence.
2368This allows some optimizations to happen as long as the control flow remains
2369unmodified.
2370
2371 .. code-block:: c
2372
2373 for (int i=0; i<4; i++)
2374 my_sub_group_shuffle()
2375
2376can be modified to:
2377
2378 .. code-block:: c
2379
2380 my_sub_group_shuffle();
2381 my_sub_group_shuffle();
2382 my_sub_group_shuffle();
2383 my_sub_group_shuffle();
2384
2385while using ``noduplicate`` would disallow this. Also ``noduplicate`` doesn't
2386have the same safe semantics of CFG as ``convergent`` and can cause changes in
2387CFG that modify semantics of the original program.
2388
2389``noduplicate`` is kept for backwards compatibility only and it considered to be
2390deprecated for future uses.
2391
2392.. _opencl_addrsp:
2393
2394address_space
2395^^^^^^^^^^^^^
2396
2397Clang has arbitrary address space support using the ``address_space(N)``
2398attribute, where ``N`` is an integer number in the range ``0`` to ``16777215``
2399(``0xffffffu``).
2400
2401An OpenCL implementation provides a list of standard address spaces using
2402keywords: ``private``, ``local``, ``global``, and ``generic``. In the AST and
2403in the IR local, global, or generic will be represented by the address space
2404attribute with the corresponding unique number. Note that private does not have
2405any corresponding attribute added and, therefore, is represented by the absence
2406of an address space number. The specific IDs for an address space do not have to
2407match between the AST and the IR. Typically in the AST address space numbers
2408represent logical segments while in the IR they represent physical segments.
2409Therefore, machines with flat memory segments can map all AST address space
2410numbers to the same physical segment ID or skip address space attribute
2411completely while generating the IR. However, if the address space information
2412is needed by the IR passes e.g. to improve alias analysis, it is recommended
2413to keep it and only lower to reflect physical memory segments in the late
2414machine passes.
2415
2416OpenCL builtins
2417---------------
2418
2419There are some standard OpenCL functions that are implemented as Clang builtins:
2420
2421- All pipe functions from `section 6.13.16.2/6.13.16.3
2422 <https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#160>`_ of
2423 the OpenCL v2.0 kernel language specification. `
2424
2425- Address space qualifier conversion functions ``to_global``/``to_local``/``to_private``
2426 from `section 6.13.9
2427 <https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#101>`_.
2428
2429- All the ``enqueue_kernel`` functions from `section 6.13.17.1
2430 <https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#164>`_ and
2431 enqueue query functions from `section 6.13.17.5
2432 <https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#171>`_.
2433
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002434.. _target_features:
2435
2436Target-Specific Features and Limitations
2437========================================
2438
2439CPU Architectures Features and Limitations
2440------------------------------------------
2441
2442X86
2443^^^
2444
2445The support for X86 (both 32-bit and 64-bit) is considered stable on
Nico Weberab88f0b2014-03-07 18:09:57 +00002446Darwin (Mac OS X), Linux, FreeBSD, and Dragonfly BSD: it has been tested
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002447to correctly compile many large C, C++, Objective-C, and Objective-C++
2448codebases.
2449
Richard Smith48d1b652013-12-12 02:42:17 +00002450On ``x86_64-mingw32``, passing i128(by value) is incompatible with the
David Woodhouseddf89852014-01-23 14:32:46 +00002451Microsoft x64 calling convention. You might need to tweak
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002452``WinX86_64ABIInfo::classify()`` in lib/CodeGen/TargetInfo.cpp.
2453
Aaron Ballman51fb0312016-07-15 13:13:45 +00002454For the X86 target, clang supports the `-m16` command line
David Woodhouseddf89852014-01-23 14:32:46 +00002455argument which enables 16-bit code output. This is broadly similar to
2456using ``asm(".code16gcc")`` with the GNU toolchain. The generated code
2457and the ABI remains 32-bit but the assembler emits instructions
2458appropriate for a CPU running in 16-bit mode, with address-size and
2459operand-size prefixes to enable 32-bit addressing and operations.
2460
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002461ARM
2462^^^
2463
2464The support for ARM (specifically ARMv6 and ARMv7) is considered stable
2465on Darwin (iOS): it has been tested to correctly compile many large C,
2466C++, Objective-C, and Objective-C++ codebases. Clang only supports a
2467limited number of ARM architectures. It does not yet fully support
2468ARMv5, for example.
2469
Roman Divacky786d32e2013-09-11 17:12:49 +00002470PowerPC
2471^^^^^^^
2472
2473The support for PowerPC (especially PowerPC64) is considered stable
2474on Linux and FreeBSD: it has been tested to correctly compile many
2475large C and C++ codebases. PowerPC (32bit) is still missing certain
2476features (e.g. PIC code on ELF platforms).
2477
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002478Other platforms
2479^^^^^^^^^^^^^^^
2480
Roman Divacky786d32e2013-09-11 17:12:49 +00002481clang currently contains some support for other architectures (e.g. Sparc);
2482however, significant pieces of code generation are still missing, and they
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002483haven't undergone significant testing.
2484
2485clang contains limited support for the MSP430 embedded processor, but
2486both the clang support and the LLVM backend support are highly
2487experimental.
2488
2489Other platforms are completely unsupported at the moment. Adding the
2490minimal support needed for parsing and semantic analysis on a new
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00002491platform is quite easy; see ``lib/Basic/Targets.cpp`` in the clang source
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002492tree. This level of support is also sufficient for conversion to LLVM IR
2493for simple programs. Proper support for conversion to LLVM IR requires
Dmitri Gribenko1436ff22012-12-19 22:06:59 +00002494adding code to ``lib/CodeGen/CGCall.cpp`` at the moment; this is likely to
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002495change soon, though. Generating assembly requires a suitable LLVM
2496backend.
2497
2498Operating System Features and Limitations
2499-----------------------------------------
2500
Nico Weberab88f0b2014-03-07 18:09:57 +00002501Darwin (Mac OS X)
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002502^^^^^^^^^^^^^^^^^
2503
Nico Weberc7cb9402014-03-07 18:11:40 +00002504Thread Sanitizer is not supported.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002505
2506Windows
2507^^^^^^^
2508
Richard Smith48d1b652013-12-12 02:42:17 +00002509Clang has experimental support for targeting "Cygming" (Cygwin / MinGW)
2510platforms.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002511
Reid Kleckner725b7b32013-09-05 21:29:35 +00002512See also :ref:`Microsoft Extensions <c_ms>`.
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002513
2514Cygwin
2515""""""
2516
2517Clang works on Cygwin-1.7.
2518
2519MinGW32
2520"""""""
2521
2522Clang works on some mingw32 distributions. Clang assumes directories as
2523below;
2524
2525- ``C:/mingw/include``
2526- ``C:/mingw/lib``
2527- ``C:/mingw/lib/gcc/mingw32/4.[3-5].0/include/c++``
2528
2529On MSYS, a few tests might fail.
2530
2531MinGW-w64
2532"""""""""
2533
2534For 32-bit (i686-w64-mingw32), and 64-bit (x86\_64-w64-mingw32), Clang
2535assumes as below;
2536
2537- ``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)``
2538- ``some_directory/bin/gcc.exe``
2539- ``some_directory/bin/clang.exe``
2540- ``some_directory/bin/clang++.exe``
2541- ``some_directory/bin/../include/c++/GCC_version``
2542- ``some_directory/bin/../include/c++/GCC_version/x86_64-w64-mingw32``
2543- ``some_directory/bin/../include/c++/GCC_version/i686-w64-mingw32``
2544- ``some_directory/bin/../include/c++/GCC_version/backward``
2545- ``some_directory/bin/../x86_64-w64-mingw32/include``
2546- ``some_directory/bin/../i686-w64-mingw32/include``
2547- ``some_directory/bin/../include``
2548
2549This directory layout is standard for any toolchain you will find on the
2550official `MinGW-w64 website <http://mingw-w64.sourceforge.net>`_.
2551
2552Clang expects the GCC executable "gcc.exe" compiled for
2553``i686-w64-mingw32`` (or ``x86_64-w64-mingw32``) to be present on PATH.
2554
Ismail Donmezcb17fbb2017-02-17 08:26:54 +00002555`Some tests might fail <https://bugs.llvm.org/show_bug.cgi?id=9072>`_ on
Sean Silvabf9b4cd2012-12-13 01:10:46 +00002556``x86_64-w64-mingw32``.
Hans Wennborg2a6e6bc2013-10-10 01:15:16 +00002557
2558.. _clang-cl:
2559
2560clang-cl
2561========
2562
Hans Wennborg715dd7f2017-01-12 18:15:06 +00002563clang-cl is an alternative command-line interface to Clang, designed for
Hans Wennborg2a6e6bc2013-10-10 01:15:16 +00002564compatibility with the Visual C++ compiler, cl.exe.
2565
2566To enable clang-cl to find system headers, libraries, and the linker when run
2567from the command-line, it should be executed inside a Visual Studio Native Tools
2568Command Prompt or a regular Command Prompt where the environment has been set
2569up using e.g. `vcvars32.bat <http://msdn.microsoft.com/en-us/library/f2ccy3wt.aspx>`_.
2570
Hans Wennborg715dd7f2017-01-12 18:15:06 +00002571clang-cl can also be used from inside Visual Studio by using an LLVM Platform
Hans Wennborg2a6e6bc2013-10-10 01:15:16 +00002572Toolset.
2573
2574Command-Line Options
2575--------------------
2576
2577To be compatible with cl.exe, clang-cl supports most of the same command-line
2578options. Those options can start with either ``/`` or ``-``. It also supports
2579some of Clang's core options, such as the ``-W`` options.
2580
2581Options that are known to clang-cl, but not currently supported, are ignored
2582with a warning. For example:
2583
2584 ::
2585
Hans Wennborg0d080622015-08-12 19:35:01 +00002586 clang-cl.exe: warning: argument unused during compilation: '/AI'
Hans Wennborg2a6e6bc2013-10-10 01:15:16 +00002587
2588To suppress warnings about unused arguments, use the ``-Qunused-arguments`` option.
2589
Ehsan Akhgarid8518332016-01-25 21:14:52 +00002590Options that are not known to clang-cl will be ignored by default. Use the
2591``-Werror=unknown-argument`` option in order to treat them as errors. If these
2592options are spelled with a leading ``/``, they will be mistaken for a filename:
Hans Wennborg2a6e6bc2013-10-10 01:15:16 +00002593
2594 ::
2595
2596 clang-cl.exe: error: no such file or directory: '/foobar'
2597
Ismail Donmezcb17fbb2017-02-17 08:26:54 +00002598Please `file a bug <https://bugs.llvm.org/enter_bug.cgi?product=clang&component=Driver>`_
Hans Wennborg2a6e6bc2013-10-10 01:15:16 +00002599for any valid cl.exe flags that clang-cl does not understand.
2600
2601Execute ``clang-cl /?`` to see a list of supported options:
2602
2603 ::
2604
Hans Wennborg35487d82014-08-04 21:07:58 +00002605 CL.EXE COMPATIBILITY OPTIONS:
Hans Wennborg715dd7f2017-01-12 18:15:06 +00002606 /? Display available options
2607 /arch:<value> Set architecture for code generation
2608 /Brepro- Emit an object file which cannot be reproduced over time
2609 /Brepro Emit an object file which can be reproduced over time
2610 /C Don't discard comments when preprocessing
2611 /c Compile only
2612 /D <macro[=value]> Define macro
2613 /EH<value> Exception handling model
2614 /EP Disable linemarker output and preprocess to stdout
2615 /execution-charset:<value>
2616 Runtime encoding, supports only UTF-8
2617 /E Preprocess to stdout
2618 /fallback Fall back to cl.exe if clang-cl fails to compile
2619 /FA Output assembly code file during compilation
2620 /Fa<file or directory> Output assembly code to this file during compilation (with /FA)
2621 /Fe<file or directory> Set output executable file or directory (ends in / or \)
2622 /FI <value> Include file before parsing
2623 /Fi<file> Set preprocess output file name (with /P)
2624 /Fo<file or directory> Set output object file, or directory (ends in / or \) (with /c)
Hans Wennborg0d080622015-08-12 19:35:01 +00002625 /fp:except-
2626 /fp:except
2627 /fp:fast
2628 /fp:precise
2629 /fp:strict
Hans Wennborg715dd7f2017-01-12 18:15:06 +00002630 /Fp<filename> Set pch filename (with /Yc and /Yu)
2631 /GA Assume thread-local variables are defined in the executable
2632 /Gd Set __cdecl as a default calling convention
2633 /GF- Disable string pooling
2634 /GR- Disable emission of RTTI data
2635 /GR Enable emission of RTTI data
2636 /Gr Set __fastcall as a default calling convention
2637 /GS- Disable buffer security check
2638 /GS Enable buffer security check
2639 /Gs<value> Set stack probe size
2640 /Gv Set __vectorcall as a default calling convention
2641 /Gw- Don't put each data item in its own section
2642 /Gw Put each data item in its own section
2643 /GX- Enable exception handling
2644 /GX Enable exception handling
2645 /Gy- Don't put each function in its own section
2646 /Gy Put each function in its own section
2647 /Gz Set __stdcall as a default calling convention
2648 /help Display available options
2649 /imsvc <dir> Add directory to system include search path, as if part of %INCLUDE%
2650 /I <dir> Add directory to include search path
2651 /J Make char type unsigned
2652 /LDd Create debug DLL
2653 /LD Create DLL
2654 /link <options> Forward options to the linker
2655 /MDd Use DLL debug run-time
2656 /MD Use DLL run-time
2657 /MTd Use static debug run-time
2658 /MT Use static run-time
2659 /Od Disable optimization
2660 /Oi- Disable use of builtin functions
2661 /Oi Enable use of builtin functions
2662 /Os Optimize for size
2663 /Ot Optimize for speed
2664 /O<value> Optimization level
2665 /o <file or directory> Set output file or directory (ends in / or \)
2666 /P Preprocess to file
2667 /Qvec- Disable the loop vectorization passes
2668 /Qvec Enable the loop vectorization passes
2669 /showIncludes Print info about included files to stderr
2670 /source-charset:<value> Source encoding, supports only UTF-8
2671 /std:<value> Language standard to compile for
2672 /TC Treat all source files as C
2673 /Tc <filename> Specify a C source file
2674 /TP Treat all source files as C++
2675 /Tp <filename> Specify a C++ source file
Hans Wennborg9d1ed002017-01-12 19:26:54 +00002676 /utf-8 Set source and runtime encoding to UTF-8 (default)
Hans Wennborg715dd7f2017-01-12 18:15:06 +00002677 /U <macro> Undefine macro
2678 /vd<value> Control vtordisp placement
2679 /vmb Use a best-case representation method for member pointers
2680 /vmg Use a most-general representation for member pointers
2681 /vmm Set the default most-general representation to multiple inheritance
2682 /vms Set the default most-general representation to single inheritance
2683 /vmv Set the default most-general representation to virtual inheritance
2684 /volatile:iso Volatile loads and stores have standard semantics
2685 /volatile:ms Volatile loads and stores have acquire and release semantics
2686 /W0 Disable all warnings
2687 /W1 Enable -Wall
2688 /W2 Enable -Wall
2689 /W3 Enable -Wall
2690 /W4 Enable -Wall and -Wextra
2691 /Wall Enable -Wall and -Wextra
2692 /WX- Do not treat warnings as errors
2693 /WX Treat warnings as errors
2694 /w Disable all warnings
2695 /Y- Disable precompiled headers, overrides /Yc and /Yu
2696 /Yc<filename> Generate a pch file for all code up to and including <filename>
2697 /Yu<filename> Load a pch file and use it instead of all code up to and including <filename>
2698 /Z7 Enable CodeView debug information in object files
2699 /Zc:sizedDealloc- Disable C++14 sized global deallocation functions
2700 /Zc:sizedDealloc Enable C++14 sized global deallocation functions
2701 /Zc:strictStrings Treat string literals as const
2702 /Zc:threadSafeInit- Disable thread-safe initialization of static variables
2703 /Zc:threadSafeInit Enable thread-safe initialization of static variables
2704 /Zc:trigraphs- Disable trigraphs (default)
2705 /Zc:trigraphs Enable trigraphs
2706 /Zd Emit debug line number tables only
2707 /Zi Alias for /Z7. Does not produce PDBs.
2708 /Zl Don't mention any default libraries in the object file
2709 /Zp Set the default maximum struct packing alignment to 1
2710 /Zp<value> Specify the default maximum struct packing alignment
2711 /Zs Syntax-check only
Hans Wennborg35487d82014-08-04 21:07:58 +00002712
2713 OPTIONS:
Hans Wennborg0d080622015-08-12 19:35:01 +00002714 -### Print (but do not run) the commands to run for this compilation
2715 --analyze Run the static analyzer
2716 -fansi-escape-codes Use ANSI escape codes for diagnostics
2717 -fcolor-diagnostics Use colors in diagnostics
Hans Wennborg715dd7f2017-01-12 18:15:06 +00002718 -fdelayed-template-parsing
2719 Parse templated function definitions at the end of the translation unit
2720 -fdiagnostics-absolute-paths
2721 Print absolute paths in diagnostics
Hans Wennborg0d080622015-08-12 19:35:01 +00002722 -fdiagnostics-parseable-fixits
2723 Print fix-its in machine parseable form
Hans Wennborg715dd7f2017-01-12 18:15:06 +00002724 -flto Enable LTO in 'full' mode
Hans Wennborg35487d82014-08-04 21:07:58 +00002725 -fms-compatibility-version=<value>
Hans Wennborg0d080622015-08-12 19:35:01 +00002726 Dot-separated value representing the Microsoft compiler version
2727 number to report in _MSC_VER (0 = don't define it (default))
Hans Wennborge8178e82016-02-12 01:01:37 +00002728 -fms-compatibility Enable full Microsoft Visual C++ compatibility
2729 -fms-extensions Accept some non-standard constructs supported by the Microsoft compiler
2730 -fmsc-version=<value> Microsoft compiler version number to report in _MSC_VER
2731 (0 = don't define it (default))
Hans Wennborg9d1ed002017-01-12 19:26:54 +00002732 -fno-delayed-template-parsing
2733 Disable delayed template parsing
Hans Wennborg0d080622015-08-12 19:35:01 +00002734 -fno-sanitize-coverage=<value>
2735 Disable specified features of coverage instrumentation for Sanitizers
2736 -fno-sanitize-recover=<value>
2737 Disable recovery for specified sanitizers
2738 -fno-sanitize-trap=<value>
2739 Disable trapping for specified sanitizers
Hans Wennborg715dd7f2017-01-12 18:15:06 +00002740 -fno-standalone-debug Limit debug information produced to reduce size of debug binary
2741 -fprofile-instr-generate=<file>
2742 Generate instrumented code to collect execution counts into <file>
2743 (overridden by LLVM_PROFILE_FILE env var)
2744 -fprofile-instr-generate
2745 Generate instrumented code to collect execution counts into default.profraw file
Sylvestre Ledrue86ee6b2017-01-14 11:41:45 +00002746 (overridden by '=' form of option or LLVM_PROFILE_FILE env var)
Hans Wennborg715dd7f2017-01-12 18:15:06 +00002747 -fprofile-instr-use=<value>
2748 Use instrumentation data for profile-guided optimization
Hans Wennborg35487d82014-08-04 21:07:58 +00002749 -fsanitize-blacklist=<value>
Hans Wennborg0d080622015-08-12 19:35:01 +00002750 Path to blacklist file for sanitizers
2751 -fsanitize-coverage=<value>
2752 Specify the type of coverage instrumentation for Sanitizers
2753 -fsanitize-recover=<value>
2754 Enable recovery for specified sanitizers
2755 -fsanitize-trap=<value> Enable trapping for specified sanitizers
2756 -fsanitize=<check> Turn on runtime checks for various forms of undefined or suspicious
2757 behavior. See user manual for available checks
Hans Wennborg715dd7f2017-01-12 18:15:06 +00002758 -fstandalone-debug Emit full debug info for all types used by the program
Hans Wennborg0d080622015-08-12 19:35:01 +00002759 -gcodeview Generate CodeView debug information
Hans Wennborg6e70f4e2016-07-27 16:56:03 +00002760 -gline-tables-only Emit debug line number tables only
2761 -miamcu Use Intel MCU ABI
Hans Wennborg0d080622015-08-12 19:35:01 +00002762 -mllvm <value> Additional arguments to forward to LLVM's option processing
2763 -Qunused-arguments Don't emit warning for unused driver arguments
2764 -R<remark> Enable the specified remark
2765 --target=<value> Generate code for the given target
2766 -v Show commands to run and use verbose output
2767 -W<warning> Enable the specified warning
2768 -Xclang <arg> Pass <arg> to the clang compiler
Hans Wennborg2a6e6bc2013-10-10 01:15:16 +00002769
2770The /fallback Option
2771^^^^^^^^^^^^^^^^^^^^
2772
2773When clang-cl is run with the ``/fallback`` option, it will first try to
2774compile files itself. For any file that it fails to compile, it will fall back
2775and try to compile the file by invoking cl.exe.
2776
2777This option is intended to be used as a temporary means to build projects where
2778clang-cl cannot successfully compile all the files. clang-cl may fail to compile
2779a file either because it cannot generate code for some C++ feature, or because
2780it cannot parse some Microsoft language extension.