1 ============================
2 Clang Compiler User's Manual
3 ============================
5 .. include:: <isonum.txt>
13 The Clang Compiler is an open-source compiler for the C family of
14 programming languages, aiming to be the best in class implementation of
15 these languages. Clang builds on the LLVM optimizer and code generator,
16 allowing it to provide high-quality optimization and code generation
17 support for many targets. For more general information, please see the
18 `Clang Web Site <http://clang.llvm.org>`_ or the `LLVM Web
19 Site <http://llvm.org>`_.
21 This document describes important notes about using Clang as a compiler
22 for an end-user, documenting the supported features, command line
23 options, etc. If you are interested in using Clang to build a tool that
24 processes code, please see :doc:`InternalsManual`. If you are interested in the
25 `Clang Static Analyzer <http://clang-analyzer.llvm.org>`_, please see its web
28 Clang is one component in a complete toolchain for C family languages.
29 A separate document describes the other pieces necessary to
30 :doc:`assemble a complete toolchain <Toolchain>`.
32 Clang is designed to support the C family of programming languages,
33 which 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
35 language-specific information, please see the corresponding language
38 - :ref:`C Language <c>`: K&R C, ANSI C89, ISO C90, ISO C94 (C89+AMD1), ISO
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>`
45 In addition to these base languages and their dialects, Clang supports a
46 broad variety of language extensions, which are documented in the
47 corresponding language section. These extensions are provided to be
48 compatible with the GCC, Microsoft, and other popular compilers as well
49 as to improve functionality through Clang-specific features. The Clang
50 driver and language features are intentionally designed to be as
51 compatible with the GNU GCC compiler as reasonably possible, easing
52 migration from GCC to Clang. In most cases, code "just works".
53 Clang also provides an alternative driver, :ref:`clang-cl`, that is designed
54 to be compatible with the Visual C++ compiler, cl.exe.
56 In addition to language specific features, Clang has a variety of
57 features that depend on what CPU architecture or operating system is
58 being compiled for. Please see the :ref:`Target-Specific Features and
59 Limitations <target_features>` section for more details.
61 The rest of the introduction introduces some basic :ref:`compiler
62 terminology <terminology>` that is used throughout this manual and
63 contains a basic :ref:`introduction to using Clang <basicusage>` as a
64 command line compiler.
71 Front end, parser, backend, preprocessor, undefined behavior,
79 Intro to how to use a C compiler for newbies.
81 compile + link compile then link debug info enabling optimizations
82 picking a language to use, defaults to C11 by default. Autosenses based
83 on extension. using a makefile
88 This section is generally an index into other sections. It does not go
89 into depth on the ones that are covered by other sections. However, the
90 first part introduces the language selection and other high level
91 options like :option:`-c`, :option:`-g`, etc.
93 Options to Control Error and Warning Messages
94 ---------------------------------------------
98 Turn warnings into errors.
100 .. This is in plain monospaced font because it generates the same label as
101 .. -Werror, and Sphinx complains.
105 Turn warning "foo" into an error.
107 .. option:: -Wno-error=foo
109 Turn warning "foo" into an warning even if :option:`-Werror` is specified.
113 Enable warning "foo".
114 See the :doc:`diagnostics reference <DiagnosticsReference>` for a complete
115 list of the warning flags that can be specified in this way.
119 Disable warning "foo".
123 Disable all diagnostics.
125 .. option:: -Weverything
127 :ref:`Enable all diagnostics. <diagnostics_enable_everything>`
129 .. option:: -pedantic
131 Warn on language extensions.
133 .. option:: -pedantic-errors
135 Error on language extensions.
137 .. option:: -Wsystem-headers
139 Enable warnings from system headers.
141 .. option:: -ferror-limit=123
143 Stop emitting diagnostics after 123 errors have been produced. The default is
144 20, and the error limit can be disabled with `-ferror-limit=0`.
146 .. option:: -ftemplate-backtrace-limit=123
148 Only emit up to 123 template instantiation notes within the template
149 instantiation backtrace for a single warning or error. The default is 10, and
150 the limit can be disabled with `-ftemplate-backtrace-limit=0`.
152 .. _cl_diag_formatting:
154 Formatting of Diagnostics
155 ^^^^^^^^^^^^^^^^^^^^^^^^^
157 Clang aims to produce beautiful diagnostics by default, particularly for
158 new users that first come to Clang. However, different people have
159 different preferences, and sometimes Clang is driven not by a human,
160 but by a program that wants consistent and easily parsable output. For
161 these cases, Clang provides a wide range of options to control the exact
162 output format of the diagnostics that it generates.
164 .. _opt_fshow-column:
166 **-f[no-]show-column**
167 Print column number in diagnostic.
169 This option, which defaults to on, controls whether or not Clang
170 prints the column number of a diagnostic. For example, when this is
171 enabled, Clang will print something like:
175 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
180 When this is disabled, Clang will print "test.c:28: warning..." with
183 The printed column numbers count bytes from the beginning of the
184 line; take care if your source contains multibyte characters.
186 .. _opt_fshow-source-location:
188 **-f[no-]show-source-location**
189 Print source file/line/column information in diagnostic.
191 This option, which defaults to on, controls whether or not Clang
192 prints the filename, line number and column number of a diagnostic.
193 For example, when this is enabled, Clang will print something like:
197 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
202 When this is disabled, Clang will not print the "test.c:28:8: "
205 .. _opt_fcaret-diagnostics:
207 **-f[no-]caret-diagnostics**
208 Print source line and ranges from source code in diagnostic.
209 This option, which defaults to on, controls whether or not Clang
210 prints the source line, source ranges, and caret when emitting a
211 diagnostic. For example, when this is enabled, Clang will print
216 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
221 **-f[no-]color-diagnostics**
222 This option, which defaults to on when a color-capable terminal is
223 detected, controls whether or not Clang prints diagnostics in color.
225 When this option is enabled, Clang will use colors to highlight
226 specific parts of the diagnostic, e.g.,
228 .. nasty hack to not lose our dignity
233 <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 <span style="color:green">^</span>
236 <span style="color:green">//</span>
239 When this is disabled, Clang will just print:
243 test.c:2:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
248 **-fansi-escape-codes**
249 Controls whether ANSI escape codes are used instead of the Windows Console
250 API to output colored diagnostics. This option is only used on Windows and
253 .. option:: -fdiagnostics-format=clang/msvc/vi
255 Changes diagnostic output format to better match IDEs and command line tools.
257 This option controls the output format of the filename, line number,
258 and column printed in diagnostic messages. The options, and their
259 affect on formatting a simple conversion diagnostic, follow:
264 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int'
269 t.c(3,11) : warning: conversion specifies type 'char *' but the argument has type 'int'
274 t.c +3:11: warning: conversion specifies type 'char *' but the argument has type 'int'
276 .. _opt_fdiagnostics-show-option:
278 **-f[no-]diagnostics-show-option**
279 Enable ``[-Woption]`` information in diagnostic line.
281 This option, which defaults to on, controls whether or not Clang
282 prints the associated :ref:`warning group <cl_diag_warning_groups>`
283 option name when outputting a warning diagnostic. For example, in
288 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
293 Passing **-fno-diagnostics-show-option** will prevent Clang from
294 printing the [:ref:`-Wextra-tokens <opt_Wextra-tokens>`] information in
295 the diagnostic. This information tells you the flag needed to enable
296 or disable the diagnostic, either from the command line or through
297 :ref:`#pragma GCC diagnostic <pragma_GCC_diagnostic>`.
299 .. _opt_fdiagnostics-show-category:
301 .. option:: -fdiagnostics-show-category=none/id/name
303 Enable printing category information in diagnostic line.
305 This option, which defaults to "none", controls whether or not Clang
306 prints the category associated with a diagnostic when emitting it.
307 Each diagnostic may or many not have an associated category, if it
308 has one, it is listed in the diagnostic categorization field of the
309 diagnostic line (in the []'s).
311 For example, a format string warning will produce these three
312 renditions based on the setting of this option:
316 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat]
317 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat,1]
318 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat,Format String]
320 This category can be used by clients that want to group diagnostics
321 by category, so it should be a high level category. We want dozens
322 of these, not hundreds or thousands of them.
324 .. _opt_fdiagnostics-show-hotness:
326 **-f[no-]diagnostics-show-hotness**
327 Enable profile hotness information in diagnostic line.
329 This option, which defaults to off, controls whether Clang prints the
330 profile hotness associated with a diagnostics in the presence of
331 profile-guided optimization information. This is currently supported with
332 optimization remarks (see :ref:`Options to Emit Optimization Reports
333 <rpass>`). The hotness information allows users to focus on the hot
334 optimization remarks that are likely to be more relevant for run-time
337 For example, in this output, the block containing the callsite of `foo` was
338 executed 3000 times according to the profile data:
342 s.c:7:10: remark: foo inlined into bar (hotness: 3000) [-Rpass-analysis=inline]
343 sum += foo(x, x - 2);
346 .. _opt_fdiagnostics-fixit-info:
348 **-f[no-]diagnostics-fixit-info**
349 Enable "FixIt" information in the diagnostics output.
351 This option, which defaults to on, controls whether or not Clang
352 prints the information on how to fix a specific diagnostic
353 underneath it when it knows. For example, in this output:
357 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
362 Passing **-fno-diagnostics-fixit-info** will prevent Clang from
363 printing the "//" line at the end of the message. This information
364 is useful for users who may not understand what is wrong, but can be
365 confusing for machine parsing.
367 .. _opt_fdiagnostics-print-source-range-info:
369 **-fdiagnostics-print-source-range-info**
370 Print machine parsable information about source ranges.
371 This option makes Clang print information about source ranges in a machine
372 parsable format after the file/line/column number information. The
373 information is a simple sequence of brace enclosed ranges, where each range
374 lists the start and end line/column locations. For example, in this output:
378 exprs.c:47:15:{47:8-47:14}{47:17-47:24}: error: invalid operands to binary expression ('int *' and '_Complex float')
379 P = (P-42) + Gamma*4;
382 The {}'s are generated by -fdiagnostics-print-source-range-info.
384 The printed column numbers count bytes from the beginning of the
385 line; take care if your source contains multibyte characters.
387 .. option:: -fdiagnostics-parseable-fixits
389 Print Fix-Its in a machine parseable form.
391 This option makes Clang print available Fix-Its in a machine
392 parseable format at the end of diagnostics. The following example
393 illustrates the format:
397 fix-it:"t.cpp":{7:25-7:29}:"Gamma"
399 The range printed is a half-open range, so in this example the
400 characters at column 25 up to but not including column 29 on line 7
401 in t.cpp should be replaced with the string "Gamma". Either the
402 range or the replacement string may be empty (representing strict
403 insertions and strict erasures, respectively). Both the file name
404 and the insertion string escape backslash (as "\\\\"), tabs (as
405 "\\t"), newlines (as "\\n"), double quotes(as "\\"") and
406 non-printable characters (as octal "\\xxx").
408 The printed column numbers count bytes from the beginning of the
409 line; take care if your source contains multibyte characters.
411 .. option:: -fno-elide-type
413 Turns off elision in template type printing.
415 The default for template type printing is to elide as many template
416 arguments as possible, removing those which are the same in both
417 template types, leaving only the differences. Adding this flag will
418 print all the template arguments. If supported by the terminal,
419 highlighting will still appear on differing arguments.
425 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;
431 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;
433 .. option:: -fdiagnostics-show-template-tree
435 Template type diffing prints a text tree.
437 For diffing large templated types, this option will cause Clang to
438 display the templates as an indented text tree, one argument per
439 line, with differences marked inline. This is compatible with
446 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;
448 With :option:`-fdiagnostics-show-template-tree`:
452 t.cc:4:5: note: candidate function not viable: no known conversion for 1st argument;
460 .. _cl_diag_warning_groups:
462 Individual Warning Groups
463 ^^^^^^^^^^^^^^^^^^^^^^^^^
465 TODO: Generate this from tblgen. Define one anchor per warning group.
467 .. _opt_wextra-tokens:
469 .. option:: -Wextra-tokens
471 Warn about excess tokens at the end of a preprocessor directive.
473 This option, which defaults to on, enables warnings about extra
474 tokens at the end of preprocessor directives. For example:
478 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
482 These extra tokens are not strictly conforming, and are usually best
483 handled by commenting them out.
485 .. option:: -Wambiguous-member-template
487 Warn about unqualified uses of a member template whose name resolves to
488 another template at the location of the use.
490 This option, which defaults to on, enables a warning in the
495 template<typename T> struct set{};
496 template<typename T> struct trait { typedef const T& type; };
498 template<typename T> void set(typename trait<T>::type value) {}
505 C++ [basic.lookup.classref] requires this to be an error, but,
506 because it's hard to work around, Clang downgrades it to a warning
509 .. option:: -Wbind-to-temporary-copy
511 Warn about an unusable copy constructor when binding a reference to a
514 This option enables warnings about binding a
515 reference to a temporary when the temporary doesn't have a usable
516 copy constructor. For example:
523 NonCopyable(const NonCopyable&);
525 void foo(const NonCopyable&);
527 foo(NonCopyable()); // Disallowed in C++98; allowed in C++11.
532 struct NonCopyable2 {
534 NonCopyable2(NonCopyable2&);
536 void foo(const NonCopyable2&);
538 foo(NonCopyable2()); // Disallowed in C++98; allowed in C++11.
541 Note that if ``NonCopyable2::NonCopyable2()`` has a default argument
542 whose instantiation produces a compile error, that error will still
543 be a hard error in C++98 mode even if this warning is turned off.
545 Options to Control Clang Crash Diagnostics
546 ------------------------------------------
548 As unbelievable as it may sound, Clang does crash from time to time.
549 Generally, this only occurs to those living on the `bleeding
550 edge <http://llvm.org/releases/download.html#svn>`_. Clang goes to great
551 lengths to assist you in filing a bug report. Specifically, Clang
552 generates preprocessed source file(s) and associated run script(s) upon
553 a crash. These files should be attached to a bug report to ease
554 reproducibility of the failure. Below are the command line options to
555 control the crash diagnostics.
557 .. option:: -fno-crash-diagnostics
559 Disable auto-generation of preprocessed source files during a clang crash.
561 The -fno-crash-diagnostics flag can be helpful for speeding the process
562 of generating a delta reduced test case.
566 Options to Emit Optimization Reports
567 ------------------------------------
569 Optimization reports trace, at a high-level, all the major decisions
570 done by compiler transformations. For instance, when the inliner
571 decides to inline function ``foo()`` into ``bar()``, or the loop unroller
572 decides to unroll a loop N times, or the vectorizer decides to
573 vectorize a loop body.
575 Clang offers a family of flags which the optimizers can use to emit
576 a diagnostic in three cases:
578 1. When the pass makes a transformation (`-Rpass`).
580 2. When the pass fails to make a transformation (`-Rpass-missed`).
582 3. When the pass determines whether or not to make a transformation
585 NOTE: Although the discussion below focuses on `-Rpass`, the exact
586 same options apply to `-Rpass-missed` and `-Rpass-analysis`.
588 Since there are dozens of passes inside the compiler, each of these flags
589 take a regular expression that identifies the name of the pass which should
590 emit the associated diagnostic. For example, to get a report from the inliner,
591 compile the code with:
593 .. code-block:: console
595 $ clang -O2 -Rpass=inline code.cc -o code
596 code.cc:4:25: remark: foo inlined into bar [-Rpass=inline]
597 int bar(int j) { return foo(j, j - 2); }
600 Note that remarks from the inliner are identified with `[-Rpass=inline]`.
601 To request a report from every optimization pass, you should use
602 `-Rpass=.*` (in fact, you can use any valid POSIX regular
603 expression). However, do not expect a report from every transformation
604 made by the compiler. Optimization remarks do not really make sense
605 outside of the major transformations (e.g., inlining, vectorization,
606 loop optimizations) and not every optimization pass supports this
609 Note that when using profile-guided optimization information, profile hotness
610 information can be included in the remarks (see
611 :ref:`-fdiagnostics-show-hotness <opt_fdiagnostics-show-hotness>`).
616 1. Optimization remarks that refer to function names will display the
617 mangled name of the function. Since these remarks are emitted by the
618 back end of the compiler, it does not know anything about the input
619 language, nor its mangling rules.
621 2. Some source locations are not displayed correctly. The front end has
622 a more detailed source location tracking than the locations included
623 in the debug info (e.g., the front end can locate code inside macro
624 expansions). However, the locations used by `-Rpass` are
625 translated from debug annotations. That translation can be lossy,
626 which results in some remarks having no location information.
630 Clang options that that don't fit neatly into other categories.
634 When emitting a dependency file, use formatting conventions appropriate
635 for NMake or Jom. Ignored unless another option causes Clang to emit a
638 When Clang emits a dependency file (e.g., you supplied the -M option)
639 most filenames can be written to the file without any special formatting.
640 Different Make tools will treat different sets of characters as "special"
641 and use different conventions for telling the Make tool that the character
642 is actually part of the filename. Normally Clang uses backslash to "escape"
643 a special character, which is the convention used by GNU Make. The -MV
644 option tells Clang to put double-quotes around the entire filename, which
645 is the convention used by NMake and Jom.
648 Language and Target-Independent Features
649 ========================================
651 Controlling Errors and Warnings
652 -------------------------------
654 Clang provides a number of ways to control which code constructs cause
655 it to emit errors and warning messages, and how they are displayed to
658 Controlling How Clang Displays Diagnostics
659 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
661 When Clang emits a diagnostic, it includes rich information in the
662 output, and gives you fine-grain control over which information is
663 printed. Clang has the ability to print this information, and these are
664 the options that control it:
666 #. A file/line/column indicator that shows exactly where the diagnostic
667 occurs in your code [:ref:`-fshow-column <opt_fshow-column>`,
668 :ref:`-fshow-source-location <opt_fshow-source-location>`].
669 #. A categorization of the diagnostic as a note, warning, error, or
671 #. A text string that describes what the problem is.
672 #. An option that indicates how to control the diagnostic (for
673 diagnostics that support it)
674 [:ref:`-fdiagnostics-show-option <opt_fdiagnostics-show-option>`].
675 #. A :ref:`high-level category <diagnostics_categories>` for the diagnostic
676 for clients that want to group diagnostics by class (for diagnostics
678 [:ref:`-fdiagnostics-show-category <opt_fdiagnostics-show-category>`].
679 #. The line of source code that the issue occurs on, along with a caret
680 and ranges that indicate the important locations
681 [:ref:`-fcaret-diagnostics <opt_fcaret-diagnostics>`].
682 #. "FixIt" information, which is a concise explanation of how to fix the
683 problem (when Clang is certain it knows)
684 [:ref:`-fdiagnostics-fixit-info <opt_fdiagnostics-fixit-info>`].
685 #. A machine-parsable representation of the ranges involved (off by
687 [:ref:`-fdiagnostics-print-source-range-info <opt_fdiagnostics-print-source-range-info>`].
689 For more information please see :ref:`Formatting of
690 Diagnostics <cl_diag_formatting>`.
695 All diagnostics are mapped into one of these 6 classes:
704 .. _diagnostics_categories:
706 Diagnostic Categories
707 ^^^^^^^^^^^^^^^^^^^^^
709 Though not shown by default, diagnostics may each be associated with a
710 high-level category. This category is intended to make it possible to
711 triage builds that produce a large number of errors or warnings in a
714 Categories are not shown by default, but they can be turned on with the
715 :ref:`-fdiagnostics-show-category <opt_fdiagnostics-show-category>` option.
716 When set to "``name``", the category is printed textually in the
717 diagnostic output. When it is set to "``id``", a category number is
718 printed. The mapping of category names to category id's can be obtained
719 by running '``clang --print-diagnostic-categories``'.
721 Controlling Diagnostics via Command Line Flags
722 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
724 TODO: -W flags, -pedantic, etc
726 .. _pragma_gcc_diagnostic:
728 Controlling Diagnostics via Pragmas
729 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
731 Clang can also control what diagnostics are enabled through the use of
732 pragmas in the source code. This is useful for turning off specific
733 warnings in a section of source code. Clang supports GCC's pragma for
734 compatibility with existing source code, as well as several extensions.
736 The pragma may control any warning that can be used from the command
737 line. Warnings may be set to ignored, warning, error, or fatal. The
738 following example code will tell Clang or GCC to ignore the -Wall
743 #pragma GCC diagnostic ignored "-Wall"
745 In addition to all of the functionality provided by GCC's pragma, Clang
746 also allows you to push and pop the current warning state. This is
747 particularly useful when writing a header file that will be compiled by
748 other people, because you don't know what warning flags they build with.
750 In the below example :option:`-Wextra-tokens` is ignored for only a single line
751 of code, after which the diagnostics return to whatever state had previously
757 #endif foo // warning: extra tokens at end of #endif directive
759 #pragma clang diagnostic ignored "-Wextra-tokens"
762 #endif foo // no warning
764 #pragma clang diagnostic pop
766 The push and pop pragmas will save and restore the full diagnostic state
767 of the compiler, regardless of how it was set. That means that it is
768 possible to use push and pop around GCC compatible diagnostics and Clang
769 will push and pop them appropriately, while GCC will ignore the pushes
770 and pops as unknown pragmas. It should be noted that while Clang
771 supports the GCC pragma, Clang and GCC do not support the exact same set
772 of warnings, so even when using GCC compatible #pragmas there is no
773 guarantee that they will have identical behaviour on both compilers.
775 In addition to controlling warnings and errors generated by the compiler, it is
776 possible to generate custom warning and error messages through the following
781 // The following will produce warning messages
782 #pragma message "some diagnostic message"
783 #pragma GCC warning "TODO: replace deprecated feature"
785 // The following will produce an error message
786 #pragma GCC error "Not supported"
788 These pragmas operate similarly to the ``#warning`` and ``#error`` preprocessor
789 directives, except that they may also be embedded into preprocessor macros via
790 the C99 ``_Pragma`` operator, for example:
795 #define DEFER(M,...) M(__VA_ARGS__)
796 #define CUSTOM_ERROR(X) _Pragma(STR(GCC error(X " at line " DEFER(STR,__LINE__))))
798 CUSTOM_ERROR("Feature not available");
800 Controlling Diagnostics in System Headers
801 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
803 Warnings are suppressed when they occur in system headers. By default,
804 an included file is treated as a system header if it is found in an
805 include path specified by ``-isystem``, but this can be overridden in
808 The ``system_header`` pragma can be used to mark the current file as
809 being a system header. No warnings will be produced from the location of
810 the pragma onwards within the same file.
815 #endif foo // warning: extra tokens at end of #endif directive
817 #pragma clang system_header
820 #endif foo // no warning
822 The `--system-header-prefix=` and `--no-system-header-prefix=`
823 command-line arguments can be used to override whether subsets of an include
824 path are treated as system headers. When the name in a ``#include`` directive
825 is found within a header search path and starts with a system prefix, the
826 header is treated as a system header. The last prefix on the
827 command-line which matches the specified header name takes precedence.
830 .. code-block:: console
832 $ clang -Ifoo -isystem bar --system-header-prefix=x/ \
833 --no-system-header-prefix=x/y/
835 Here, ``#include "x/a.h"`` is treated as including a system header, even
836 if the header is found in ``foo``, and ``#include "x/y/b.h"`` is treated
837 as not including a system header, even if the header is found in
840 A ``#include`` directive which finds a file relative to the current
841 directory is treated as including a system header if the including file
842 is treated as a system header.
844 .. _diagnostics_enable_everything:
846 Enabling All Diagnostics
847 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
849 In addition to the traditional ``-W`` flags, one can enable **all**
850 diagnostics by passing :option:`-Weverything`. This works as expected
852 :option:`-Werror`, and also includes the warnings from :option:`-pedantic`.
854 Note that when combined with :option:`-w` (which disables all warnings), that
857 Controlling Static Analyzer Diagnostics
858 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
860 While not strictly part of the compiler, the diagnostics from Clang's
861 `static analyzer <http://clang-analyzer.llvm.org>`_ can also be
862 influenced by the user via changes to the source code. See the available
863 `annotations <http://clang-analyzer.llvm.org/annotations.html>`_ and the
865 page <http://clang-analyzer.llvm.org/faq.html#exclude_code>`_ for more
868 .. _usersmanual-precompiled-headers:
873 `Precompiled headers <http://en.wikipedia.org/wiki/Precompiled_header>`__
874 are a general approach employed by many compilers to reduce compilation
875 time. The underlying motivation of the approach is that it is common for
876 the same (and often large) header files to be included by multiple
877 source files. Consequently, compile times can often be greatly improved
878 by caching some of the (redundant) work done by a compiler to process
879 headers. Precompiled header files, which represent one of many ways to
880 implement this optimization, are literally files that represent an
881 on-disk cache that contains the vital information necessary to reduce
882 some of the work needed to process a corresponding header file. While
883 details of precompiled headers vary between compilers, precompiled
884 headers have been shown to be highly effective at speeding up program
885 compilation on systems with very large system headers (e.g., Mac OS X).
887 Generating a PCH File
888 ^^^^^^^^^^^^^^^^^^^^^
890 To generate a PCH file using Clang, one invokes Clang with the
891 `-x <language>-header` option. This mirrors the interface in GCC
892 for generating PCH files:
894 .. code-block:: console
896 $ gcc -x c-header test.h -o test.h.gch
897 $ clang -x c-header test.h -o test.h.pch
902 A PCH file can then be used as a prefix header when a :option:`-include`
903 option is passed to ``clang``:
905 .. code-block:: console
907 $ clang -include test.h test.c -o test
909 The ``clang`` driver will first check if a PCH file for ``test.h`` is
910 available; if so, the contents of ``test.h`` (and the files it includes)
911 will be processed from the PCH file. Otherwise, Clang falls back to
912 directly processing the content of ``test.h``. This mirrors the behavior
917 Clang does *not* automatically use PCH files for headers that are directly
918 included within a source file. For example:
920 .. code-block:: console
922 $ clang -x c-header test.h -o test.h.pch
925 $ clang test.c -o test
927 In this example, ``clang`` will not automatically use the PCH file for
928 ``test.h`` since ``test.h`` was included directly in the source file and not
929 specified on the command line using :option:`-include`.
931 Relocatable PCH Files
932 ^^^^^^^^^^^^^^^^^^^^^
934 It is sometimes necessary to build a precompiled header from headers
935 that are not yet in their final, installed locations. For example, one
936 might build a precompiled header within the build tree that is then
937 meant to be installed alongside the headers. Clang permits the creation
938 of "relocatable" precompiled headers, which are built with a given path
939 (into the build directory) and can later be used from an installed
942 To build a relocatable precompiled header, place your headers into a
943 subdirectory whose structure mimics the installed location. For example,
944 if you want to build a precompiled header for the header ``mylib.h``
945 that will be installed into ``/usr/include``, create a subdirectory
946 ``build/usr/include`` and place the header ``mylib.h`` into that
947 subdirectory. If ``mylib.h`` depends on other headers, then they can be
948 stored within ``build/usr/include`` in a way that mimics the installed
951 Building a relocatable precompiled header requires two additional
952 arguments. First, pass the ``--relocatable-pch`` flag to indicate that
953 the resulting PCH file should be relocatable. Second, pass
954 `-isysroot /path/to/build`, which makes all includes for your library
955 relative to the build directory. For example:
957 .. code-block:: console
959 # clang -x c-header --relocatable-pch -isysroot /path/to/build /path/to/build/mylib.h mylib.h.pch
961 When loading the relocatable PCH file, the various headers used in the
962 PCH file are found from the system header root. For example, ``mylib.h``
963 can be found in ``/usr/include/mylib.h``. If the headers are installed
964 in some other system root, the `-isysroot` option can be used provide
965 a different system root from which the headers will be based. For
966 example, `-isysroot /Developer/SDKs/MacOSX10.4u.sdk` will look for
967 ``mylib.h`` in ``/Developer/SDKs/MacOSX10.4u.sdk/usr/include/mylib.h``.
969 Relocatable precompiled headers are intended to be used in a limited
970 number of cases where the compilation environment is tightly controlled
971 and the precompiled header cannot be generated after headers have been
974 .. _controlling-code-generation:
976 Controlling Code Generation
977 ---------------------------
979 Clang provides a number of ways to control code generation. The options
982 **-f[no-]sanitize=check1,check2,...**
983 Turn on runtime checks for various forms of undefined or suspicious
986 This option controls whether Clang adds runtime checks for various
987 forms of undefined or suspicious behavior, and is disabled by
988 default. If a check fails, a diagnostic message is produced at
989 runtime explaining the problem. The main checks are:
991 - .. _opt_fsanitize_address:
993 ``-fsanitize=address``:
994 :doc:`AddressSanitizer`, a memory error
996 - .. _opt_fsanitize_thread:
998 ``-fsanitize=thread``: :doc:`ThreadSanitizer`, a data race detector.
999 - .. _opt_fsanitize_memory:
1001 ``-fsanitize=memory``: :doc:`MemorySanitizer`,
1002 a detector of uninitialized reads. Requires instrumentation of all
1004 - .. _opt_fsanitize_undefined:
1006 ``-fsanitize=undefined``: :doc:`UndefinedBehaviorSanitizer`,
1007 a fast and compatible undefined behavior checker.
1009 - ``-fsanitize=dataflow``: :doc:`DataFlowSanitizer`, a general data
1011 - ``-fsanitize=cfi``: :doc:`control flow integrity <ControlFlowIntegrity>`
1012 checks. Requires ``-flto``.
1013 - ``-fsanitize=safe-stack``: :doc:`safe stack <SafeStack>`
1014 protection against stack-based memory corruption errors.
1016 There are more fine-grained checks available: see
1017 the :ref:`list <ubsan-checks>` of specific kinds of
1018 undefined behavior that can be detected and the :ref:`list <cfi-schemes>`
1019 of control flow integrity schemes.
1021 The ``-fsanitize=`` argument must also be provided when linking, in
1022 order to link to the appropriate runtime library.
1024 It is not possible to combine more than one of the ``-fsanitize=address``,
1025 ``-fsanitize=thread``, and ``-fsanitize=memory`` checkers in the same
1028 **-f[no-]sanitize-recover=check1,check2,...**
1030 **-f[no-]sanitize-recover=all**
1032 Controls which checks enabled by ``-fsanitize=`` flag are non-fatal.
1033 If the check is fatal, program will halt after the first error
1034 of this kind is detected and error report is printed.
1036 By default, non-fatal checks are those enabled by
1037 :doc:`UndefinedBehaviorSanitizer`,
1038 except for ``-fsanitize=return`` and ``-fsanitize=unreachable``. Some
1039 sanitizers may not support recovery (or not support it by default
1040 e.g. :doc:`AddressSanitizer`), and always crash the program after the issue
1043 Note that the ``-fsanitize-trap`` flag has precedence over this flag.
1044 This means that if a check has been configured to trap elsewhere on the
1045 command line, or if the check traps by default, this flag will not have
1046 any effect unless that sanitizer's trapping behavior is disabled with
1047 ``-fno-sanitize-trap``.
1049 For example, if a command line contains the flags ``-fsanitize=undefined
1050 -fsanitize-trap=undefined``, the flag ``-fsanitize-recover=alignment``
1051 will have no effect on its own; it will need to be accompanied by
1052 ``-fno-sanitize-trap=alignment``.
1054 **-f[no-]sanitize-trap=check1,check2,...**
1056 Controls which checks enabled by the ``-fsanitize=`` flag trap. This
1057 option is intended for use in cases where the sanitizer runtime cannot
1058 be used (for instance, when building libc or a kernel module), or where
1059 the binary size increase caused by the sanitizer runtime is a concern.
1061 This flag is only compatible with :doc:`control flow integrity
1062 <ControlFlowIntegrity>` schemes and :doc:`UndefinedBehaviorSanitizer`
1063 checks other than ``vptr``. If this flag
1064 is supplied together with ``-fsanitize=undefined``, the ``vptr`` sanitizer
1065 will be implicitly disabled.
1067 This flag is enabled by default for sanitizers in the ``cfi`` group.
1069 .. option:: -fsanitize-blacklist=/path/to/blacklist/file
1071 Disable or modify sanitizer checks for objects (source files, functions,
1072 variables, types) listed in the file. See
1073 :doc:`SanitizerSpecialCaseList` for file format description.
1075 .. option:: -fno-sanitize-blacklist
1077 Don't use blacklist file, if it was specified earlier in the command line.
1079 **-f[no-]sanitize-coverage=[type,features,...]**
1081 Enable simple code coverage in addition to certain sanitizers.
1082 See :doc:`SanitizerCoverage` for more details.
1084 **-f[no-]sanitize-stats**
1086 Enable simple statistics gathering for the enabled sanitizers.
1087 See :doc:`SanitizerStats` for more details.
1089 .. option:: -fsanitize-undefined-trap-on-error
1091 Deprecated alias for ``-fsanitize-trap=undefined``.
1093 .. option:: -fsanitize-cfi-cross-dso
1095 Enable cross-DSO control flow integrity checks. This flag modifies
1096 the behavior of sanitizers in the ``cfi`` group to allow checking
1097 of cross-DSO virtual and indirect calls.
1099 .. option:: -ffast-math
1101 Enable fast-math mode. This defines the ``__FAST_MATH__`` preprocessor
1102 macro, and lets the compiler make aggressive, potentially-lossy assumptions
1103 about floating-point math. These include:
1105 * Floating-point math obeys regular algebraic rules for real numbers (e.g.
1106 ``+`` and ``*`` are associative, ``x/y == x * (1/y)``, and
1107 ``(a + b) * c == a * c + b * c``),
1108 * operands to floating-point operations are not equal to ``NaN`` and
1110 * ``+0`` and ``-0`` are interchangeable.
1112 .. option:: -fdenormal-fp-math=[values]
1114 Select which denormal numbers the code is permitted to require.
1116 Valid values are: ``ieee``, ``preserve-sign``, and ``positive-zero``,
1117 which correspond to IEEE 754 denormal numbers, the sign of a
1118 flushed-to-zero number is preserved in the sign of 0, denormals are
1119 flushed to positive zero, respectively.
1121 .. option:: -fwhole-program-vtables
1123 Enable whole-program vtable optimizations, such as single-implementation
1124 devirtualization and virtual constant propagation, for classes with
1125 :doc:`hidden LTO visibility <LTOVisibility>`. Requires ``-flto``.
1127 .. option:: -fno-assume-sane-operator-new
1129 Don't assume that the C++'s new operator is sane.
1131 This option tells the compiler to do not assume that C++'s global
1132 new operator will always return a pointer that does not alias any
1133 other pointer when the function returns.
1135 .. option:: -ftrap-function=[name]
1137 Instruct code generator to emit a function call to the specified
1138 function name for ``__builtin_trap()``.
1140 LLVM code generator translates ``__builtin_trap()`` to a trap
1141 instruction if it is supported by the target ISA. Otherwise, the
1142 builtin is translated into a call to ``abort``. If this option is
1143 set, then the code generator will always lower the builtin to a call
1144 to the specified function regardless of whether the target ISA has a
1145 trap instruction. This option is useful for environments (e.g.
1146 deeply embedded) where a trap cannot be properly handled, or when
1147 some custom behavior is desired.
1149 .. option:: -ftls-model=[model]
1151 Select which TLS model to use.
1153 Valid values are: ``global-dynamic``, ``local-dynamic``,
1154 ``initial-exec`` and ``local-exec``. The default value is
1155 ``global-dynamic``. The compiler may use a different model if the
1156 selected model is not supported by the target, or if a more
1157 efficient model can be used. The TLS model can be overridden per
1158 variable using the ``tls_model`` attribute.
1160 .. option:: -femulated-tls
1162 Select emulated TLS model, which overrides all -ftls-model choices.
1164 In emulated TLS mode, all access to TLS variables are converted to
1165 calls to __emutls_get_address in the runtime library.
1167 .. option:: -mhwdiv=[values]
1169 Select the ARM modes (arm or thumb) that support hardware division
1172 Valid values are: ``arm``, ``thumb`` and ``arm,thumb``.
1173 This option is used to indicate which mode (arm or thumb) supports
1174 hardware division instructions. This only applies to the ARM
1177 .. option:: -m[no-]crc
1179 Enable or disable CRC instructions.
1181 This option is used to indicate whether CRC instructions are to
1182 be generated. This only applies to the ARM architecture.
1184 CRC instructions are enabled by default on ARMv8.
1186 .. option:: -mgeneral-regs-only
1188 Generate code which only uses the general purpose registers.
1190 This option restricts the generated code to use general registers
1191 only. This only applies to the AArch64 architecture.
1193 .. option:: -mcompact-branches=[values]
1195 Control the usage of compact branches for MIPSR6.
1197 Valid values are: ``never``, ``optimal`` and ``always``.
1198 The default value is ``optimal`` which generates compact branches
1199 when a delay slot cannot be filled. ``never`` disables the usage of
1200 compact branches and ``always`` generates compact branches whenever
1203 **-f[no-]max-type-align=[number]**
1204 Instruct the code generator to not enforce a higher alignment than the given
1205 number (of bytes) when accessing memory via an opaque pointer or reference.
1206 This cap is ignored when directly accessing a variable or when the pointee
1207 type has an explicit “aligned” attribute.
1209 The value should usually be determined by the properties of the system allocator.
1210 Some builtin types, especially vector types, have very high natural alignments;
1211 when working with values of those types, Clang usually wants to use instructions
1212 that take advantage of that alignment. However, many system allocators do
1213 not promise to return memory that is more than 8-byte or 16-byte-aligned. Use
1214 this option to limit the alignment that the compiler can assume for an arbitrary
1215 pointer, which may point onto the heap.
1217 This option does not affect the ABI alignment of types; the layout of structs and
1218 unions and the value returned by the alignof operator remain the same.
1220 This option can be overridden on a case-by-case basis by putting an explicit
1221 “aligned” alignment on a struct, union, or typedef. For example:
1223 .. code-block:: console
1225 #include <immintrin.h>
1226 // Make an aligned typedef of the AVX-512 16-int vector type.
1227 typedef __v16si __aligned_v16si __attribute__((aligned(64)));
1229 void initialize_vector(__aligned_v16si *v) {
1230 // The compiler may assume that ‘v’ is 64-byte aligned, regardless of the
1231 // value of -fmax-type-align.
1235 Profile Guided Optimization
1236 ---------------------------
1238 Profile information enables better optimization. For example, knowing that a
1239 branch is taken very frequently helps the compiler make better decisions when
1240 ordering basic blocks. Knowing that a function ``foo`` is called more
1241 frequently than another function ``bar`` helps the inliner.
1243 Clang supports profile guided optimization with two different kinds of
1244 profiling. A sampling profiler can generate a profile with very low runtime
1245 overhead, or you can build an instrumented version of the code that collects
1246 more detailed profile information. Both kinds of profiles can provide execution
1247 counts for instructions in the code and information on branches taken and
1248 function invocation.
1250 Regardless of which kind of profiling you use, be careful to collect profiles
1251 by running your code with inputs that are representative of the typical
1252 behavior. Code that is not exercised in the profile will be optimized as if it
1253 is unimportant, and the compiler may make poor optimization choices for code
1254 that is disproportionately used while profiling.
1256 Differences Between Sampling and Instrumentation
1257 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1259 Although both techniques are used for similar purposes, there are important
1260 differences between the two:
1262 1. Profile data generated with one cannot be used by the other, and there is no
1263 conversion tool that can convert one to the other. So, a profile generated
1264 via ``-fprofile-instr-generate`` must be used with ``-fprofile-instr-use``.
1265 Similarly, sampling profiles generated by external profilers must be
1266 converted and used with ``-fprofile-sample-use``.
1268 2. Instrumentation profile data can be used for code coverage analysis and
1271 3. Sampling profiles can only be used for optimization. They cannot be used for
1272 code coverage analysis. Although it would be technically possible to use
1273 sampling profiles for code coverage, sample-based profiles are too
1274 coarse-grained for code coverage purposes; it would yield poor results.
1276 4. Sampling profiles must be generated by an external tool. The profile
1277 generated by that tool must then be converted into a format that can be read
1278 by LLVM. The section on sampling profilers describes one of the supported
1279 sampling profile formats.
1282 Using Sampling Profilers
1283 ^^^^^^^^^^^^^^^^^^^^^^^^
1285 Sampling profilers are used to collect runtime information, such as
1286 hardware counters, while your application executes. They are typically
1287 very efficient and do not incur a large runtime overhead. The
1288 sample data collected by the profiler can be used during compilation
1289 to determine what the most executed areas of the code are.
1291 Using the data from a sample profiler requires some changes in the way
1292 a program is built. Before the compiler can use profiling information,
1293 the code needs to execute under the profiler. The following is the
1294 usual build cycle when using sample profilers for optimization:
1296 1. Build the code with source line table information. You can use all the
1297 usual build flags that you always build your application with. The only
1298 requirement is that you add ``-gline-tables-only`` or ``-g`` to the
1299 command line. This is important for the profiler to be able to map
1300 instructions back to source line locations.
1302 .. code-block:: console
1304 $ clang++ -O2 -gline-tables-only code.cc -o code
1306 2. Run the executable under a sampling profiler. The specific profiler
1307 you use does not really matter, as long as its output can be converted
1308 into the format that the LLVM optimizer understands. Currently, there
1309 exists a conversion tool for the Linux Perf profiler
1310 (https://perf.wiki.kernel.org/), so these examples assume that you
1311 are using Linux Perf to profile your code.
1313 .. code-block:: console
1315 $ perf record -b ./code
1317 Note the use of the ``-b`` flag. This tells Perf to use the Last Branch
1318 Record (LBR) to record call chains. While this is not strictly required,
1319 it provides better call information, which improves the accuracy of
1322 3. Convert the collected profile data to LLVM's sample profile format.
1323 This is currently supported via the AutoFDO converter ``create_llvm_prof``.
1324 It is available at http://github.com/google/autofdo. Once built and
1325 installed, you can convert the ``perf.data`` file to LLVM using
1328 .. code-block:: console
1330 $ create_llvm_prof --binary=./code --out=code.prof
1332 This will read ``perf.data`` and the binary file ``./code`` and emit
1333 the profile data in ``code.prof``. Note that if you ran ``perf``
1334 without the ``-b`` flag, you need to use ``--use_lbr=false`` when
1335 calling ``create_llvm_prof``.
1337 4. Build the code again using the collected profile. This step feeds
1338 the profile back to the optimizers. This should result in a binary
1339 that executes faster than the original one. Note that you are not
1340 required to build the code with the exact same arguments that you
1341 used in the first step. The only requirement is that you build the code
1342 with ``-gline-tables-only`` and ``-fprofile-sample-use``.
1344 .. code-block:: console
1346 $ clang++ -O2 -gline-tables-only -fprofile-sample-use=code.prof code.cc -o code
1349 Sample Profile Formats
1350 """"""""""""""""""""""
1352 Since external profilers generate profile data in a variety of custom formats,
1353 the data generated by the profiler must be converted into a format that can be
1354 read by the backend. LLVM supports three different sample profile formats:
1356 1. ASCII text. This is the easiest one to generate. The file is divided into
1357 sections, which correspond to each of the functions with profile
1358 information. The format is described below. It can also be generated from
1359 the binary or gcov formats using the ``llvm-profdata`` tool.
1361 2. Binary encoding. This uses a more efficient encoding that yields smaller
1362 profile files. This is the format generated by the ``create_llvm_prof`` tool
1363 in http://github.com/google/autofdo.
1365 3. GCC encoding. This is based on the gcov format, which is accepted by GCC. It
1366 is only interesting in environments where GCC and Clang co-exist. This
1367 encoding is only generated by the ``create_gcov`` tool in
1368 http://github.com/google/autofdo. It can be read by LLVM and
1369 ``llvm-profdata``, but it cannot be generated by either.
1371 If you are using Linux Perf to generate sampling profiles, you can use the
1372 conversion tool ``create_llvm_prof`` described in the previous section.
1373 Otherwise, you will need to write a conversion tool that converts your
1374 profiler's native format into one of these three.
1377 Sample Profile Text Format
1378 """"""""""""""""""""""""""
1380 This section describes the ASCII text format for sampling profiles. It is,
1381 arguably, the easiest one to generate. If you are interested in generating any
1382 of the other two, consult the ``ProfileData`` library in in LLVM's source tree
1383 (specifically, ``include/llvm/ProfileData/SampleProfReader.h``).
1385 .. code-block:: console
1387 function1:total_samples:total_head_samples
1388 offset1[.discriminator]: number_of_samples [fn1:num fn2:num ... ]
1389 offset2[.discriminator]: number_of_samples [fn3:num fn4:num ... ]
1391 offsetN[.discriminator]: number_of_samples [fn5:num fn6:num ... ]
1392 offsetA[.discriminator]: fnA:num_of_total_samples
1393 offsetA1[.discriminator]: number_of_samples [fn7:num fn8:num ... ]
1394 offsetA1[.discriminator]: number_of_samples [fn9:num fn10:num ... ]
1395 offsetB[.discriminator]: fnB:num_of_total_samples
1396 offsetB1[.discriminator]: number_of_samples [fn11:num fn12:num ... ]
1398 This is a nested tree in which the identation represents the nesting level
1399 of the inline stack. There are no blank lines in the file. And the spacing
1400 within a single line is fixed. Additional spaces will result in an error
1401 while reading the file.
1403 Any line starting with the '#' character is completely ignored.
1405 Inlined calls are represented with indentation. The Inline stack is a
1406 stack of source locations in which the top of the stack represents the
1407 leaf function, and the bottom of the stack represents the actual
1408 symbol to which the instruction belongs.
1410 Function names must be mangled in order for the profile loader to
1411 match them in the current translation unit. The two numbers in the
1412 function header specify how many total samples were accumulated in the
1413 function (first number), and the total number of samples accumulated
1414 in the prologue of the function (second number). This head sample
1415 count provides an indicator of how frequently the function is invoked.
1417 There are two types of lines in the function body.
1419 - Sampled line represents the profile information of a source location.
1420 ``offsetN[.discriminator]: number_of_samples [fn5:num fn6:num ... ]``
1422 - Callsite line represents the profile information of an inlined callsite.
1423 ``offsetA[.discriminator]: fnA:num_of_total_samples``
1425 Each sampled line may contain several items. Some are optional (marked
1428 a. Source line offset. This number represents the line number
1429 in the function where the sample was collected. The line number is
1430 always relative to the line where symbol of the function is
1431 defined. So, if the function has its header at line 280, the offset
1432 13 is at line 293 in the file.
1434 Note that this offset should never be a negative number. This could
1435 happen in cases like macros. The debug machinery will register the
1436 line number at the point of macro expansion. So, if the macro was
1437 expanded in a line before the start of the function, the profile
1438 converter should emit a 0 as the offset (this means that the optimizers
1439 will not be able to associate a meaningful weight to the instructions
1442 b. [OPTIONAL] Discriminator. This is used if the sampled program
1443 was compiled with DWARF discriminator support
1444 (http://wiki.dwarfstd.org/index.php?title=Path_Discriminators).
1445 DWARF discriminators are unsigned integer values that allow the
1446 compiler to distinguish between multiple execution paths on the
1447 same source line location.
1449 For example, consider the line of code ``if (cond) foo(); else bar();``.
1450 If the predicate ``cond`` is true 80% of the time, then the edge
1451 into function ``foo`` should be considered to be taken most of the
1452 time. But both calls to ``foo`` and ``bar`` are at the same source
1453 line, so a sample count at that line is not sufficient. The
1454 compiler needs to know which part of that line is taken more
1457 This is what discriminators provide. In this case, the calls to
1458 ``foo`` and ``bar`` will be at the same line, but will have
1459 different discriminator values. This allows the compiler to correctly
1460 set edge weights into ``foo`` and ``bar``.
1462 c. Number of samples. This is an integer quantity representing the
1463 number of samples collected by the profiler at this source
1466 d. [OPTIONAL] Potential call targets and samples. If present, this
1467 line contains a call instruction. This models both direct and
1468 number of samples. For example,
1470 .. code-block:: console
1472 130: 7 foo:3 bar:2 baz:7
1474 The above means that at relative line offset 130 there is a call
1475 instruction that calls one of ``foo()``, ``bar()`` and ``baz()``,
1476 with ``baz()`` being the relatively more frequently called target.
1478 As an example, consider a program with the call chain ``main -> foo -> bar``.
1479 When built with optimizations enabled, the compiler may inline the
1480 calls to ``bar`` and ``foo`` inside ``main``. The generated profile
1481 could then be something like this:
1483 .. code-block:: console
1491 This profile indicates that there were a total of 35,504 samples
1492 collected in main. All of those were at line 1 (the call to ``foo``).
1493 Of those, 31,977 were spent inside the body of ``bar``. The last line
1494 of the profile (``2: 0``) corresponds to line 2 inside ``main``. No
1495 samples were collected there.
1497 Profiling with Instrumentation
1498 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1500 Clang also supports profiling via instrumentation. This requires building a
1501 special instrumented version of the code and has some runtime
1502 overhead during the profiling, but it provides more detailed results than a
1503 sampling profiler. It also provides reproducible results, at least to the
1504 extent that the code behaves consistently across runs.
1506 Here are the steps for using profile guided optimization with
1509 1. Build an instrumented version of the code by compiling and linking with the
1510 ``-fprofile-instr-generate`` option.
1512 .. code-block:: console
1514 $ clang++ -O2 -fprofile-instr-generate code.cc -o code
1516 2. Run the instrumented executable with inputs that reflect the typical usage.
1517 By default, the profile data will be written to a ``default.profraw`` file
1518 in the current directory. You can override that default by using option
1519 ``-fprofile-instr-generate=`` or by setting the ``LLVM_PROFILE_FILE``
1520 environment variable to specify an alternate file. If non-default file name
1521 is specified by both the environment variable and the command line option,
1522 the environment variable takes precedence. The file name pattern specified
1523 can include different modifiers: ``%p``, ``%h``, and ``%m``.
1525 Any instance of ``%p`` in that file name will be replaced by the process
1526 ID, so that you can easily distinguish the profile output from multiple
1529 .. code-block:: console
1531 $ LLVM_PROFILE_FILE="code-%p.profraw" ./code
1533 The modifier ``%h`` can be used in scenarios where the same instrumented
1534 binary is run in multiple different host machines dumping profile data
1535 to a shared network based storage. The ``%h`` specifier will be substituted
1536 with the hostname so that profiles collected from different hosts do not
1539 While the use of ``%p`` specifier can reduce the likelihood for the profiles
1540 dumped from different processes to clobber each other, such clobbering can still
1541 happen because of the ``pid`` re-use by the OS. Another side-effect of using
1542 ``%p`` is that the storage requirement for raw profile data files is greatly
1543 increased. To avoid issues like this, the ``%m`` specifier can used in the profile
1544 name. When this specifier is used, the profiler runtime will substitute ``%m``
1545 with a unique integer identifier associated with the instrumented binary. Additionally,
1546 multiple raw profiles dumped from different processes that share a file system (can be
1547 on different hosts) will be automatically merged by the profiler runtime during the
1548 dumping. If the program links in multiple instrumented shared libraries, each library
1549 will dump the profile data into its own profile data file (with its unique integer
1550 id embedded in the profile name). Note that the merging enabled by ``%m`` is for raw
1551 profile data generated by profiler runtime. The resulting merged "raw" profile data
1552 file still needs to be converted to a different format expected by the compiler (
1555 .. code-block:: console
1557 $ LLVM_PROFILE_FILE="code-%m.profraw" ./code
1560 3. Combine profiles from multiple runs and convert the "raw" profile format to
1561 the input expected by clang. Use the ``merge`` command of the
1562 ``llvm-profdata`` tool to do this.
1564 .. code-block:: console
1566 $ llvm-profdata merge -output=code.profdata code-*.profraw
1568 Note that this step is necessary even when there is only one "raw" profile,
1569 since the merge operation also changes the file format.
1571 4. Build the code again using the ``-fprofile-instr-use`` option to specify the
1572 collected profile data.
1574 .. code-block:: console
1576 $ clang++ -O2 -fprofile-instr-use=code.profdata code.cc -o code
1578 You can repeat step 4 as often as you like without regenerating the
1579 profile. As you make changes to your code, clang may no longer be able to
1580 use the profile data. It will warn you when this happens.
1582 Profile generation using an alternative instrumentation method can be
1583 controlled by the GCC-compatible flags ``-fprofile-generate`` and
1584 ``-fprofile-use``. Although these flags are semantically equivalent to
1585 their GCC counterparts, they *do not* handle GCC-compatible profiles.
1586 They are only meant to implement GCC's semantics with respect to
1587 profile creation and use.
1589 .. option:: -fprofile-generate[=<dirname>]
1591 The ``-fprofile-generate`` and ``-fprofile-generate=`` flags will use
1592 an alterantive instrumentation method for profile generation. When
1593 given a directory name, it generates the profile file
1594 ``default_%m.profraw`` in the directory named ``dirname`` if specified.
1595 If ``dirname`` does not exist, it will be created at runtime. ``%m`` specifier
1596 will be substibuted with a unique id documented in step 2 above. In other words,
1597 with ``-fprofile-generate[=<dirname>]`` option, the "raw" profile data automatic
1598 merging is turned on by default, so there will no longer any risk of profile
1599 clobbering from different running processes. For example,
1601 .. code-block:: console
1603 $ clang++ -O2 -fprofile-generate=yyy/zzz code.cc -o code
1605 When ``code`` is executed, the profile will be written to the file
1606 ``yyy/zzz/default_xxxx.profraw``.
1608 To generate the profile data file with the compiler readable format, the
1609 ``llvm-profdata`` tool can be used with the profile directory as the input:
1611 .. code-block:: console
1613 $ llvm-profdata merge -output=code.profdata yyy/zzz/
1615 If the user wants to turn off the auto-merging feature, or simply override the
1616 the profile dumping path specified at command line, the environment variable
1617 ``LLVM_PROFILE_FILE`` can still be used to override
1618 the directory and filename for the profile file at runtime.
1620 .. option:: -fprofile-use[=<pathname>]
1622 Without any other arguments, ``-fprofile-use`` behaves identically to
1623 ``-fprofile-instr-use``. Otherwise, if ``pathname`` is the full path to a
1624 profile file, it reads from that file. If ``pathname`` is a directory name,
1625 it reads from ``pathname/default.profdata``.
1627 Disabling Instrumentation
1628 ^^^^^^^^^^^^^^^^^^^^^^^^^
1630 In certain situations, it may be useful to disable profile generation or use
1631 for specific files in a build, without affecting the main compilation flags
1632 used for the other files in the project.
1634 In these cases, you can use the flag ``-fno-profile-instr-generate`` (or
1635 ``-fno-profile-generate``) to disable profile generation, and
1636 ``-fno-profile-instr-use`` (or ``-fno-profile-use``) to disable profile use.
1638 Note that these flags should appear after the corresponding profile
1639 flags to have an effect.
1641 Controlling Debug Information
1642 -----------------------------
1644 Controlling Size of Debug Information
1645 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1647 Debug info kind generated by Clang can be set by one of the flags listed
1648 below. If multiple flags are present, the last one is used.
1652 Don't generate any debug info (default).
1654 .. option:: -gline-tables-only
1656 Generate line number tables only.
1658 This kind of debug info allows to obtain stack traces with function names,
1659 file names and line numbers (by such tools as ``gdb`` or ``addr2line``). It
1660 doesn't contain any other data (e.g. description of local variables or
1661 function parameters).
1663 .. option:: -fstandalone-debug
1665 Clang supports a number of optimizations to reduce the size of debug
1666 information in the binary. They work based on the assumption that
1667 the debug type information can be spread out over multiple
1668 compilation units. For instance, Clang will not emit type
1669 definitions for types that are not needed by a module and could be
1670 replaced with a forward declaration. Further, Clang will only emit
1671 type info for a dynamic C++ class in the module that contains the
1672 vtable for the class.
1674 The **-fstandalone-debug** option turns off these optimizations.
1675 This is useful when working with 3rd-party libraries that don't come
1676 with debug information. Note that Clang will never emit type
1677 information for types that are not referenced at all by the program.
1679 .. option:: -fno-standalone-debug
1681 On Darwin **-fstandalone-debug** is enabled by default. The
1682 **-fno-standalone-debug** option can be used to get to turn on the
1683 vtable-based optimization described above.
1687 Generate complete debug info.
1689 Controlling Debugger "Tuning"
1690 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1692 While Clang generally emits standard DWARF debug info (http://dwarfstd.org),
1693 different debuggers may know how to take advantage of different specific DWARF
1694 features. You can "tune" the debug info for one of several different debuggers.
1696 .. option:: -ggdb, -glldb, -gsce
1698 Tune the debug info for the ``gdb``, ``lldb``, or Sony PlayStation\ |reg|
1699 debugger, respectively. Each of these options implies **-g**. (Therefore, if
1700 you want both **-gline-tables-only** and debugger tuning, the tuning option
1704 Comment Parsing Options
1705 -----------------------
1707 Clang parses Doxygen and non-Doxygen style documentation comments and attaches
1708 them to the appropriate declaration nodes. By default, it only parses
1709 Doxygen-style comments and ignores ordinary comments starting with ``//`` and
1712 .. option:: -Wdocumentation
1714 Emit warnings about use of documentation comments. This warning group is off
1717 This includes checking that ``\param`` commands name parameters that actually
1718 present in the function signature, checking that ``\returns`` is used only on
1719 functions that actually return a value etc.
1721 .. option:: -Wno-documentation-unknown-command
1723 Don't warn when encountering an unknown Doxygen command.
1725 .. option:: -fparse-all-comments
1727 Parse all comments as documentation comments (including ordinary comments
1728 starting with ``//`` and ``/*``).
1730 .. option:: -fcomment-block-commands=[commands]
1732 Define custom documentation commands as block commands. This allows Clang to
1733 construct the correct AST for these custom commands, and silences warnings
1734 about unknown commands. Several commands must be separated by a comma
1735 *without trailing space*; e.g. ``-fcomment-block-commands=foo,bar`` defines
1736 custom commands ``\foo`` and ``\bar``.
1738 It is also possible to use ``-fcomment-block-commands`` several times; e.g.
1739 ``-fcomment-block-commands=foo -fcomment-block-commands=bar`` does the same
1747 The support for standard C in clang is feature-complete except for the
1748 C99 floating-point pragmas.
1750 Extensions supported by clang
1751 -----------------------------
1753 See :doc:`LanguageExtensions`.
1755 Differences between various standard modes
1756 ------------------------------------------
1758 clang supports the -std option, which changes what language mode clang
1759 uses. The supported modes for C are c89, gnu89, c94, c99, gnu99, c11,
1760 gnu11, and various aliases for those modes. If no -std option is
1761 specified, clang defaults to gnu11 mode. Many C99 and C11 features are
1762 supported in earlier modes as a conforming extension, with a warning. Use
1763 ``-pedantic-errors`` to request an error if a feature from a later standard
1764 revision is used in an earlier mode.
1766 Differences between all ``c*`` and ``gnu*`` modes:
1768 - ``c*`` modes define "``__STRICT_ANSI__``".
1769 - Target-specific defines not prefixed by underscores, like "linux",
1770 are defined in ``gnu*`` modes.
1771 - Trigraphs default to being off in ``gnu*`` modes; they can be enabled by
1772 the -trigraphs option.
1773 - The parser recognizes "asm" and "typeof" as keywords in ``gnu*`` modes;
1774 the variants "``__asm__``" and "``__typeof__``" are recognized in all
1776 - The Apple "blocks" extension is recognized by default in ``gnu*`` modes
1777 on some platforms; it can be enabled in any mode with the "-fblocks"
1779 - Arrays that are VLA's according to the standard, but which can be
1780 constant folded by the frontend are treated as fixed size arrays.
1781 This occurs for things like "int X[(1, 2)];", which is technically a
1782 VLA. ``c*`` modes are strictly compliant and treat these as VLAs.
1784 Differences between ``*89`` and ``*99`` modes:
1786 - The ``*99`` modes default to implementing "inline" as specified in C99,
1787 while the ``*89`` modes implement the GNU version. This can be
1788 overridden for individual functions with the ``__gnu_inline__``
1790 - Digraphs are not recognized in c89 mode.
1791 - The scope of names defined inside a "for", "if", "switch", "while",
1792 or "do" statement is different. (example: "``if ((struct x {int
1794 - ``__STDC_VERSION__`` is not defined in ``*89`` modes.
1795 - "inline" is not recognized as a keyword in c89 mode.
1796 - "restrict" is not recognized as a keyword in ``*89`` modes.
1797 - Commas are allowed in integer constant expressions in ``*99`` modes.
1798 - Arrays which are not lvalues are not implicitly promoted to pointers
1800 - Some warnings are different.
1802 Differences between ``*99`` and ``*11`` modes:
1804 - Warnings for use of C11 features are disabled.
1805 - ``__STDC_VERSION__`` is defined to ``201112L`` rather than ``199901L``.
1807 c94 mode is identical to c89 mode except that digraphs are enabled in
1808 c94 mode (FIXME: And ``__STDC_VERSION__`` should be defined!).
1810 GCC extensions not implemented yet
1811 ----------------------------------
1813 clang tries to be compatible with gcc as much as possible, but some gcc
1814 extensions are not implemented yet:
1816 - clang does not support decimal floating point types (``_Decimal32`` and
1817 friends) or fixed-point types (``_Fract`` and friends); nobody has
1818 expressed interest in these features yet, so it's hard to say when
1819 they will be implemented.
1820 - clang does not support nested functions; this is a complex feature
1821 which is infrequently used, so it is unlikely to be implemented
1822 anytime soon. In C++11 it can be emulated by assigning lambda
1823 functions to local variables, e.g:
1827 auto const local_function = [&](int parameter) {
1833 - clang only supports global register variables when the register specified
1834 is non-allocatable (e.g. the stack pointer). Support for general global
1835 register variables is unlikely to be implemented soon because it requires
1836 additional LLVM backend support.
1837 - clang does not support static initialization of flexible array
1838 members. This appears to be a rarely used extension, but could be
1839 implemented pending user demand.
1840 - clang does not support
1841 ``__builtin_va_arg_pack``/``__builtin_va_arg_pack_len``. This is
1842 used rarely, but in some potentially interesting places, like the
1843 glibc headers, so it may be implemented pending user demand. Note
1844 that because clang pretends to be like GCC 4.2, and this extension
1845 was introduced in 4.3, the glibc headers will not try to use this
1846 extension with clang at the moment.
1847 - clang does not support the gcc extension for forward-declaring
1848 function parameters; this has not shown up in any real-world code
1849 yet, though, so it might never be implemented.
1851 This is not a complete list; if you find an unsupported extension
1852 missing from this list, please send an e-mail to cfe-dev. This list
1853 currently excludes C++; see :ref:`C++ Language Features <cxx>`. Also, this
1854 list does not include bugs in mostly-implemented features; please see
1856 tracker <http://llvm.org/bugs/buglist.cgi?quicksearch=product%3Aclang+component%3A-New%2BBugs%2CAST%2CBasic%2CDriver%2CHeaders%2CLLVM%2BCodeGen%2Cparser%2Cpreprocessor%2CSemantic%2BAnalyzer>`_
1857 for known existing bugs (FIXME: Is there a section for bug-reporting
1858 guidelines somewhere?).
1860 Intentionally unsupported GCC extensions
1861 ----------------------------------------
1863 - clang does not support the gcc extension that allows variable-length
1864 arrays in structures. This is for a few reasons: one, it is tricky to
1865 implement, two, the extension is completely undocumented, and three,
1866 the extension appears to be rarely used. Note that clang *does*
1867 support flexible array members (arrays with a zero or unspecified
1868 size at the end of a structure).
1869 - clang does not have an equivalent to gcc's "fold"; this means that
1870 clang doesn't accept some constructs gcc might accept in contexts
1871 where a constant expression is required, like "x-x" where x is a
1873 - clang does not support ``__builtin_apply`` and friends; this extension
1874 is extremely obscure and difficult to implement reliably.
1878 Microsoft extensions
1879 --------------------
1881 clang has support for many extensions from Microsoft Visual C++. To enable these
1882 extensions, use the ``-fms-extensions`` command-line option. This is the default
1883 for Windows targets. Clang does not implement every pragma or declspec provided
1884 by MSVC, but the popular ones, such as ``__declspec(dllexport)`` and ``#pragma
1885 comment(lib)`` are well supported.
1887 clang has a ``-fms-compatibility`` flag that makes clang accept enough
1888 invalid C++ to be able to parse most Microsoft headers. For example, it
1889 allows `unqualified lookup of dependent base class members
1890 <http://clang.llvm.org/compatibility.html#dep_lookup_bases>`_, which is
1891 a common compatibility issue with clang. This flag is enabled by default
1892 for Windows targets.
1894 ``-fdelayed-template-parsing`` lets clang delay parsing of function template
1895 definitions until the end of a translation unit. This flag is enabled by
1896 default for Windows targets.
1898 For compatibility with existing code that compiles with MSVC, clang defines the
1899 ``_MSC_VER`` and ``_MSC_FULL_VER`` macros. These default to the values of 1800
1900 and 180000000 respectively, making clang look like an early release of Visual
1901 C++ 2013. The ``-fms-compatibility-version=`` flag overrides these values. It
1902 accepts a dotted version tuple, such as 19.00.23506. Changing the MSVC
1903 compatibility version makes clang behave more like that version of MSVC. For
1904 example, ``-fms-compatibility-version=19`` will enable C++14 features and define
1905 ``char16_t`` and ``char32_t`` as builtin types.
1909 C++ Language Features
1910 =====================
1912 clang fully implements all of standard C++98 except for exported
1913 templates (which were removed in C++11), and all of standard C++11
1914 and the current draft standard for C++1y.
1916 Controlling implementation limits
1917 ---------------------------------
1919 .. option:: -fbracket-depth=N
1921 Sets the limit for nested parentheses, brackets, and braces to N. The
1924 .. option:: -fconstexpr-depth=N
1926 Sets the limit for recursive constexpr function invocations to N. The
1929 .. option:: -ftemplate-depth=N
1931 Sets the limit for recursively nested template instantiations to N. The
1934 .. option:: -foperator-arrow-depth=N
1936 Sets the limit for iterative calls to 'operator->' functions to N. The
1941 Objective-C Language Features
1942 =============================
1946 Objective-C++ Language Features
1947 ===============================
1954 Clang supports all OpenMP 3.1 directives and clauses. In addition, some
1955 features of OpenMP 4.0 are supported. For example, ``#pragma omp simd``,
1956 ``#pragma omp for simd``, ``#pragma omp parallel for simd`` directives, extended
1957 set of atomic constructs, ``proc_bind`` clause for all parallel-based
1958 directives, ``depend`` clause for ``#pragma omp task`` directive (except for
1959 array sections), ``#pragma omp cancel`` and ``#pragma omp cancellation point``
1960 directives, and ``#pragma omp taskgroup`` directive.
1962 Use `-fopenmp` to enable OpenMP. Support for OpenMP can be disabled with
1965 Controlling implementation limits
1966 ---------------------------------
1968 .. option:: -fopenmp-use-tls
1970 Controls code generation for OpenMP threadprivate variables. In presence of
1971 this option all threadprivate variables are generated the same way as thread
1972 local variables, using TLS support. If `-fno-openmp-use-tls`
1973 is provided or target does not support TLS, code generation for threadprivate
1974 variables relies on OpenMP runtime library.
1976 .. _target_features:
1978 Target-Specific Features and Limitations
1979 ========================================
1981 CPU Architectures Features and Limitations
1982 ------------------------------------------
1987 The support for X86 (both 32-bit and 64-bit) is considered stable on
1988 Darwin (Mac OS X), Linux, FreeBSD, and Dragonfly BSD: it has been tested
1989 to correctly compile many large C, C++, Objective-C, and Objective-C++
1992 On ``x86_64-mingw32``, passing i128(by value) is incompatible with the
1993 Microsoft x64 calling convention. You might need to tweak
1994 ``WinX86_64ABIInfo::classify()`` in lib/CodeGen/TargetInfo.cpp.
1996 For the X86 target, clang supports the `-m16` command line
1997 argument which enables 16-bit code output. This is broadly similar to
1998 using ``asm(".code16gcc")`` with the GNU toolchain. The generated code
1999 and the ABI remains 32-bit but the assembler emits instructions
2000 appropriate for a CPU running in 16-bit mode, with address-size and
2001 operand-size prefixes to enable 32-bit addressing and operations.
2006 The support for ARM (specifically ARMv6 and ARMv7) is considered stable
2007 on Darwin (iOS): it has been tested to correctly compile many large C,
2008 C++, Objective-C, and Objective-C++ codebases. Clang only supports a
2009 limited number of ARM architectures. It does not yet fully support
2015 The support for PowerPC (especially PowerPC64) is considered stable
2016 on Linux and FreeBSD: it has been tested to correctly compile many
2017 large C and C++ codebases. PowerPC (32bit) is still missing certain
2018 features (e.g. PIC code on ELF platforms).
2023 clang currently contains some support for other architectures (e.g. Sparc);
2024 however, significant pieces of code generation are still missing, and they
2025 haven't undergone significant testing.
2027 clang contains limited support for the MSP430 embedded processor, but
2028 both the clang support and the LLVM backend support are highly
2031 Other platforms are completely unsupported at the moment. Adding the
2032 minimal support needed for parsing and semantic analysis on a new
2033 platform is quite easy; see ``lib/Basic/Targets.cpp`` in the clang source
2034 tree. This level of support is also sufficient for conversion to LLVM IR
2035 for simple programs. Proper support for conversion to LLVM IR requires
2036 adding code to ``lib/CodeGen/CGCall.cpp`` at the moment; this is likely to
2037 change soon, though. Generating assembly requires a suitable LLVM
2040 Operating System Features and Limitations
2041 -----------------------------------------
2046 Thread Sanitizer is not supported.
2051 Clang has experimental support for targeting "Cygming" (Cygwin / MinGW)
2054 See also :ref:`Microsoft Extensions <c_ms>`.
2059 Clang works on Cygwin-1.7.
2064 Clang works on some mingw32 distributions. Clang assumes directories as
2067 - ``C:/mingw/include``
2069 - ``C:/mingw/lib/gcc/mingw32/4.[3-5].0/include/c++``
2071 On MSYS, a few tests might fail.
2076 For 32-bit (i686-w64-mingw32), and 64-bit (x86\_64-w64-mingw32), Clang
2079 - ``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)``
2080 - ``some_directory/bin/gcc.exe``
2081 - ``some_directory/bin/clang.exe``
2082 - ``some_directory/bin/clang++.exe``
2083 - ``some_directory/bin/../include/c++/GCC_version``
2084 - ``some_directory/bin/../include/c++/GCC_version/x86_64-w64-mingw32``
2085 - ``some_directory/bin/../include/c++/GCC_version/i686-w64-mingw32``
2086 - ``some_directory/bin/../include/c++/GCC_version/backward``
2087 - ``some_directory/bin/../x86_64-w64-mingw32/include``
2088 - ``some_directory/bin/../i686-w64-mingw32/include``
2089 - ``some_directory/bin/../include``
2091 This directory layout is standard for any toolchain you will find on the
2092 official `MinGW-w64 website <http://mingw-w64.sourceforge.net>`_.
2094 Clang expects the GCC executable "gcc.exe" compiled for
2095 ``i686-w64-mingw32`` (or ``x86_64-w64-mingw32``) to be present on PATH.
2097 `Some tests might fail <http://llvm.org/bugs/show_bug.cgi?id=9072>`_ on
2098 ``x86_64-w64-mingw32``.
2105 clang-cl is an alternative command-line interface to Clang driver, designed for
2106 compatibility with the Visual C++ compiler, cl.exe.
2108 To enable clang-cl to find system headers, libraries, and the linker when run
2109 from the command-line, it should be executed inside a Visual Studio Native Tools
2110 Command Prompt or a regular Command Prompt where the environment has been set
2111 up using e.g. `vcvars32.bat <http://msdn.microsoft.com/en-us/library/f2ccy3wt.aspx>`_.
2113 clang-cl can also be used from inside Visual Studio by using an LLVM Platform
2116 Command-Line Options
2117 --------------------
2119 To be compatible with cl.exe, clang-cl supports most of the same command-line
2120 options. Those options can start with either ``/`` or ``-``. It also supports
2121 some of Clang's core options, such as the ``-W`` options.
2123 Options that are known to clang-cl, but not currently supported, are ignored
2124 with a warning. For example:
2128 clang-cl.exe: warning: argument unused during compilation: '/AI'
2130 To suppress warnings about unused arguments, use the ``-Qunused-arguments`` option.
2132 Options that are not known to clang-cl will be ignored by default. Use the
2133 ``-Werror=unknown-argument`` option in order to treat them as errors. If these
2134 options are spelled with a leading ``/``, they will be mistaken for a filename:
2138 clang-cl.exe: error: no such file or directory: '/foobar'
2140 Please `file a bug <http://llvm.org/bugs/enter_bug.cgi?product=clang&component=Driver>`_
2141 for any valid cl.exe flags that clang-cl does not understand.
2143 Execute ``clang-cl /?`` to see a list of supported options:
2147 CL.EXE COMPATIBILITY OPTIONS:
2148 /? Display available options
2149 /arch:<value> Set architecture for code generation
2150 /Brepro- Emit an object file which cannot be reproduced over time
2151 /Brepro Emit an object file which can be reproduced over time
2152 /C Don't discard comments when preprocessing
2154 /D <macro[=value]> Define macro
2155 /EH<value> Exception handling model
2156 /EP Disable linemarker output and preprocess to stdout
2157 /E Preprocess to stdout
2158 /fallback Fall back to cl.exe if clang-cl fails to compile
2159 /FA Output assembly code file during compilation
2160 /Fa<file or directory> Output assembly code to this file during compilation (with /FA)
2161 /Fe<file or directory> Set output executable file or directory (ends in / or \)
2162 /FI <value> Include file before parsing
2163 /Fi<file> Set preprocess output file name (with /P)
2164 /Fo<file or directory> Set output object file, or directory (ends in / or \) (with /c)
2170 /Fp<filename> Set pch filename (with /Yc and /Yu)
2171 /GA Assume thread-local variables are defined in the executable
2172 /Gd Set __cdecl as a default calling convention
2173 /GF- Disable string pooling
2174 /GR- Disable emission of RTTI data
2175 /GR Enable emission of RTTI data
2176 /Gr Set __fastcall as a default calling convention
2177 /GS- Disable buffer security check
2178 /GS Enable buffer security check
2179 /Gs<value> Set stack probe size
2180 /Gv Set __vectorcall as a default calling convention
2181 /Gw- Don't put each data item in its own section
2182 /Gw Put each data item in its own section
2183 /GX- Enable exception handling
2184 /GX Enable exception handling
2185 /Gy- Don't put each function in its own section
2186 /Gy Put each function in its own section
2187 /Gz Set __stdcall as a default calling convention
2188 /help Display available options
2189 /imsvc <dir> Add directory to system include search path, as if part of %INCLUDE%
2190 /I <dir> Add directory to include search path
2191 /J Make char type unsigned
2192 /LDd Create debug DLL
2194 /link <options> Forward options to the linker
2195 /MDd Use DLL debug run-time
2196 /MD Use DLL run-time
2197 /MTd Use static debug run-time
2198 /MT Use static run-time
2199 /Od Disable optimization
2200 /Oi- Disable use of builtin functions
2201 /Oi Enable use of builtin functions
2202 /Os Optimize for size
2203 /Ot Optimize for speed
2204 /O<value> Optimization level
2205 /o <file or directory> Set output file or directory (ends in / or \)
2206 /P Preprocess to file
2207 /Qvec- Disable the loop vectorization passes
2208 /Qvec Enable the loop vectorization passes
2209 /showIncludes Print info about included files to stderr
2210 /std:<value> Language standard to compile for
2211 /TC Treat all source files as C
2212 /Tc <filename> Specify a C source file
2213 /TP Treat all source files as C++
2214 /Tp <filename> Specify a C++ source file
2215 /U <macro> Undefine macro
2216 /vd<value> Control vtordisp placement
2217 /vmb Use a best-case representation method for member pointers
2218 /vmg Use a most-general representation for member pointers
2219 /vmm Set the default most-general representation to multiple inheritance
2220 /vms Set the default most-general representation to single inheritance
2221 /vmv Set the default most-general representation to virtual inheritance
2222 /volatile:iso Volatile loads and stores have standard semantics
2223 /volatile:ms Volatile loads and stores have acquire and release semantics
2224 /W0 Disable all warnings
2228 /W4 Enable -Wall and -Wextra
2229 /Wall Enable -Wall and -Wextra
2230 /WX- Do not treat warnings as errors
2231 /WX Treat warnings as errors
2232 /w Disable all warnings
2233 /Y- Disable precompiled headers, overrides /Yc and /Yu
2234 /Yc<filename> Generate a pch file for all code up to and including <filename>
2235 /Yu<filename> Load a pch file and use it instead of all code up to and including <filename>
2236 /Z7 Enable CodeView debug information in object files
2237 /Zc:sizedDealloc- Disable C++14 sized global deallocation functions
2238 /Zc:sizedDealloc Enable C++14 sized global deallocation functions
2239 /Zc:strictStrings Treat string literals as const
2240 /Zc:threadSafeInit- Disable thread-safe initialization of static variables
2241 /Zc:threadSafeInit Enable thread-safe initialization of static variables
2242 /Zc:trigraphs- Disable trigraphs (default)
2243 /Zc:trigraphs Enable trigraphs
2244 /Zd Emit debug line number tables only
2245 /Zi Alias for /Z7. Does not produce PDBs.
2246 /Zl Don't mention any default libraries in the object file
2247 /Zp Set the default maximum struct packing alignment to 1
2248 /Zp<value> Specify the default maximum struct packing alignment
2249 /Zs Syntax-check only
2252 -### Print (but do not run) the commands to run for this compilation
2253 --analyze Run the static analyzer
2254 -fansi-escape-codes Use ANSI escape codes for diagnostics
2255 -fcolor-diagnostics Use colors in diagnostics
2256 -fdiagnostics-parseable-fixits
2257 Print fix-its in machine parseable form
2258 -fms-compatibility-version=<value>
2259 Dot-separated value representing the Microsoft compiler version
2260 number to report in _MSC_VER (0 = don't define it (default))
2261 -fms-compatibility Enable full Microsoft Visual C++ compatibility
2262 -fms-extensions Accept some non-standard constructs supported by the Microsoft compiler
2263 -fmsc-version=<value> Microsoft compiler version number to report in _MSC_VER
2264 (0 = don't define it (default))
2265 -fno-sanitize-coverage=<value>
2266 Disable specified features of coverage instrumentation for Sanitizers
2267 -fno-sanitize-recover=<value>
2268 Disable recovery for specified sanitizers
2269 -fno-sanitize-trap=<value>
2270 Disable trapping for specified sanitizers
2271 -fsanitize-blacklist=<value>
2272 Path to blacklist file for sanitizers
2273 -fsanitize-coverage=<value>
2274 Specify the type of coverage instrumentation for Sanitizers
2275 -fsanitize-recover=<value>
2276 Enable recovery for specified sanitizers
2277 -fsanitize-trap=<value> Enable trapping for specified sanitizers
2278 -fsanitize=<check> Turn on runtime checks for various forms of undefined or suspicious
2279 behavior. See user manual for available checks
2280 -gcodeview Generate CodeView debug information
2281 -gline-tables-only Emit debug line number tables only
2282 -miamcu Use Intel MCU ABI
2283 -mllvm <value> Additional arguments to forward to LLVM's option processing
2284 -Qunused-arguments Don't emit warning for unused driver arguments
2285 -R<remark> Enable the specified remark
2286 --target=<value> Generate code for the given target
2287 -v Show commands to run and use verbose output
2288 -W<warning> Enable the specified warning
2289 -Xclang <arg> Pass <arg> to the clang compiler
2291 The /fallback Option
2292 ^^^^^^^^^^^^^^^^^^^^
2294 When clang-cl is run with the ``/fallback`` option, it will first try to
2295 compile files itself. For any file that it fails to compile, it will fall back
2296 and try to compile the file by invoking cl.exe.
2298 This option is intended to be used as a temporary means to build projects where
2299 clang-cl cannot successfully compile all the files. clang-cl may fail to compile
2300 a file either because it cannot generate code for some C++ feature, or because
2301 it cannot parse some Microsoft language extension.