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 <https://clang.llvm.org>`_ or the `LLVM Web
19 Site <https://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 <https://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>`
44 - :ref:`OpenCL Kernel Language <opencl>`: OpenCL C 1.0, 1.1, 1.2, 2.0, 3.0,
45 and C++ for OpenCL 1.0 and 2021.
47 In addition to these base languages and their dialects, Clang supports a
48 broad variety of language extensions, which are documented in the
49 corresponding language section. These extensions are provided to be
50 compatible with the GCC, Microsoft, and other popular compilers as well
51 as to improve functionality through Clang-specific features. The Clang
52 driver and language features are intentionally designed to be as
53 compatible with the GNU GCC compiler as reasonably possible, easing
54 migration from GCC to Clang. In most cases, code "just works".
55 Clang also provides an alternative driver, :ref:`clang-cl`, that is designed
56 to be compatible with the Visual C++ compiler, cl.exe.
58 In addition to language specific features, Clang has a variety of
59 features that depend on what CPU architecture or operating system is
60 being compiled for. Please see the :ref:`Target-Specific Features and
61 Limitations <target_features>` section for more details.
63 The rest of the introduction introduces some basic :ref:`compiler
64 terminology <terminology>` that is used throughout this manual and
65 contains a basic :ref:`introduction to using Clang <basicusage>` as a
66 command line compiler.
73 Front end, parser, backend, preprocessor, undefined behavior,
81 Intro to how to use a C compiler for newbies.
83 compile + link compile then link debug info enabling optimizations
84 picking a language to use, defaults to C17 by default. Autosenses based
85 on extension. using a makefile
90 This section is generally an index into other sections. It does not go
91 into depth on the ones that are covered by other sections. However, the
92 first part introduces the language selection and other high level
93 options like :option:`-c`, :option:`-g`, etc.
95 Options to Control Error and Warning Messages
96 ---------------------------------------------
100 Turn warnings into errors.
102 .. This is in plain monospaced font because it generates the same label as
103 .. -Werror, and Sphinx complains.
107 Turn warning "foo" into an error.
109 .. option:: -Wno-error=foo
111 Turn warning "foo" into a warning even if :option:`-Werror` is specified.
115 Enable warning "foo".
116 See the :doc:`diagnostics reference <DiagnosticsReference>` for a complete
117 list of the warning flags that can be specified in this way.
121 Disable warning "foo".
125 Disable all diagnostics.
127 .. option:: -Weverything
129 :ref:`Enable all diagnostics. <diagnostics_enable_everything>`
131 .. option:: -pedantic
133 Warn on language extensions.
135 .. option:: -pedantic-errors
137 Error on language extensions.
139 .. option:: -Wsystem-headers
141 Enable warnings from system headers.
143 .. option:: -ferror-limit=123
145 Stop emitting diagnostics after 123 errors have been produced. The default is
146 20, and the error limit can be disabled with `-ferror-limit=0`.
148 .. option:: -ftemplate-backtrace-limit=123
150 Only emit up to 123 template instantiation notes within the template
151 instantiation backtrace for a single warning or error. The default is 10, and
152 the limit can be disabled with `-ftemplate-backtrace-limit=0`.
154 .. _cl_diag_formatting:
156 Formatting of Diagnostics
157 ^^^^^^^^^^^^^^^^^^^^^^^^^
159 Clang aims to produce beautiful diagnostics by default, particularly for
160 new users that first come to Clang. However, different people have
161 different preferences, and sometimes Clang is driven not by a human,
162 but by a program that wants consistent and easily parsable output. For
163 these cases, Clang provides a wide range of options to control the exact
164 output format of the diagnostics that it generates.
166 .. _opt_fshow-column:
168 **-f[no-]show-column**
169 Print column number in diagnostic.
171 This option, which defaults to on, controls whether or not Clang
172 prints the column number of a diagnostic. For example, when this is
173 enabled, Clang will print something like:
177 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
182 When this is disabled, Clang will print "test.c:28: warning..." with
185 The printed column numbers count bytes from the beginning of the
186 line; take care if your source contains multibyte characters.
188 .. _opt_fshow-source-location:
190 **-f[no-]show-source-location**
191 Print source file/line/column information in diagnostic.
193 This option, which defaults to on, controls whether or not Clang
194 prints the filename, line number and column number of a diagnostic.
195 For example, when this is enabled, Clang will print something like:
199 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
204 When this is disabled, Clang will not print the "test.c:28:8: "
207 .. _opt_fcaret-diagnostics:
209 **-f[no-]caret-diagnostics**
210 Print source line and ranges from source code in diagnostic.
211 This option, which defaults to on, controls whether or not Clang
212 prints the source line, source ranges, and caret when emitting a
213 diagnostic. For example, when this is enabled, Clang will print
218 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
223 **-f[no-]color-diagnostics**
224 This option, which defaults to on when a color-capable terminal is
225 detected, controls whether or not Clang prints diagnostics in color.
227 When this option is enabled, Clang will use colors to highlight
228 specific parts of the diagnostic, e.g.,
230 .. nasty hack to not lose our dignity
235 <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>
237 <span style="color:green">^</span>
238 <span style="color:green">//</span>
241 When this is disabled, Clang will just print:
245 test.c:2:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
250 **-fansi-escape-codes**
251 Controls whether ANSI escape codes are used instead of the Windows Console
252 API to output colored diagnostics. This option is only used on Windows and
255 .. option:: -fdiagnostics-format=clang/msvc/vi
257 Changes diagnostic output format to better match IDEs and command line tools.
259 This option controls the output format of the filename, line number,
260 and column printed in diagnostic messages. The options, and their
261 affect on formatting a simple conversion diagnostic, follow:
266 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int'
271 t.c(3,11) : warning: conversion specifies type 'char *' but the argument has type 'int'
276 t.c +3:11: warning: conversion specifies type 'char *' but the argument has type 'int'
278 .. _opt_fdiagnostics-show-option:
280 **-f[no-]diagnostics-show-option**
281 Enable ``[-Woption]`` information in diagnostic line.
283 This option, which defaults to on, controls whether or not Clang
284 prints the associated :ref:`warning group <cl_diag_warning_groups>`
285 option name when outputting a warning diagnostic. For example, in
290 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
295 Passing **-fno-diagnostics-show-option** will prevent Clang from
296 printing the [:ref:`-Wextra-tokens <opt_Wextra-tokens>`] information in
297 the diagnostic. This information tells you the flag needed to enable
298 or disable the diagnostic, either from the command line or through
299 :ref:`#pragma GCC diagnostic <pragma_GCC_diagnostic>`.
301 .. _opt_fdiagnostics-show-category:
303 .. option:: -fdiagnostics-show-category=none/id/name
305 Enable printing category information in diagnostic line.
307 This option, which defaults to "none", controls whether or not Clang
308 prints the category associated with a diagnostic when emitting it.
309 Each diagnostic may or many not have an associated category, if it
310 has one, it is listed in the diagnostic categorization field of the
311 diagnostic line (in the []'s).
313 For example, a format string warning will produce these three
314 renditions based on the setting of this option:
318 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat]
319 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat,1]
320 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat,Format String]
322 This category can be used by clients that want to group diagnostics
323 by category, so it should be a high level category. We want dozens
324 of these, not hundreds or thousands of them.
326 .. _opt_fsave-optimization-record:
328 .. option:: -f[no-]save-optimization-record[=<format>]
330 Enable optimization remarks during compilation and write them to a separate
333 This option, which defaults to off, controls whether Clang writes
334 optimization reports to a separate file. By recording diagnostics in a file,
335 users can parse or sort the remarks in a convenient way.
337 By default, the serialization format is YAML.
339 The supported serialization formats are:
341 - .. _opt_fsave_optimization_record_yaml:
343 ``-fsave-optimization-record=yaml``: A structured YAML format.
345 - .. _opt_fsave_optimization_record_bitstream:
347 ``-fsave-optimization-record=bitstream``: A binary format based on LLVM
350 The output file is controlled by :ref:`-foptimization-record-file <opt_foptimization-record-file>`.
352 In the absence of an explicit output file, the file is chosen using the
355 ``<base>.opt.<format>``
357 where ``<base>`` is based on the output file of the compilation (whether
358 it's explicitly specified through `-o` or not) when used with `-c` or `-S`.
361 * ``clang -fsave-optimization-record -c in.c -o out.o`` will generate
364 * ``clang -fsave-optimization-record -c in.c `` will generate
367 When targeting (Thin)LTO, the base is derived from the output filename, and
368 the extension is not dropped.
370 When targeting ThinLTO, the following scheme is used:
372 ``<base>.opt.<format>.thin.<num>.<format>``
374 Darwin-only: when used for generating a linked binary from a source file
375 (through an intermediate object file), the driver will invoke `cc1` to
376 generate a temporary object file. The temporary remark file will be emitted
377 next to the object file, which will then be picked up by `dsymutil` and
378 emitted in the .dSYM bundle. This is available for all formats except YAML.
382 ``clang -fsave-optimization-record=bitstream in.c -o out`` will generate
384 * ``/var/folders/43/9y164hh52tv_2nrdxrj31nyw0000gn/T/a-9be59b.o``
386 * ``/var/folders/43/9y164hh52tv_2nrdxrj31nyw0000gn/T/a-9be59b.opt.bitstream``
390 * ``out.dSYM/Contents/Resources/Remarks/out``
392 Darwin-only: compiling for multiple architectures will use the following
395 ``<base>-<arch>.opt.<format>``
397 Note that this is incompatible with passing the
398 :ref:`-foptimization-record-file <opt_foptimization-record-file>` option.
400 .. _opt_foptimization-record-file:
402 **-foptimization-record-file**
403 Control the file to which optimization reports are written. This implies
404 :ref:`-fsave-optimization-record <opt_fsave-optimization-record>`.
406 On Darwin platforms, this is incompatible with passing multiple
407 ``-arch <arch>`` options.
409 .. _opt_foptimization-record-passes:
411 **-foptimization-record-passes**
412 Only include passes which match a specified regular expression.
414 When optimization reports are being output (see
415 :ref:`-fsave-optimization-record <opt_fsave-optimization-record>`), this
416 option controls the passes that will be included in the final report.
418 If this option is not used, all the passes are included in the optimization
421 .. _opt_fdiagnostics-show-hotness:
423 **-f[no-]diagnostics-show-hotness**
424 Enable profile hotness information in diagnostic line.
426 This option controls whether Clang prints the profile hotness associated
427 with diagnostics in the presence of profile-guided optimization information.
428 This is currently supported with optimization remarks (see
429 :ref:`Options to Emit Optimization Reports <rpass>`). The hotness information
430 allows users to focus on the hot optimization remarks that are likely to be
431 more relevant for run-time performance.
433 For example, in this output, the block containing the callsite of `foo` was
434 executed 3000 times according to the profile data:
438 s.c:7:10: remark: foo inlined into bar (hotness: 3000) [-Rpass-analysis=inline]
439 sum += foo(x, x - 2);
442 This option is implied when
443 :ref:`-fsave-optimization-record <opt_fsave-optimization-record>` is used.
444 Otherwise, it defaults to off.
446 .. _opt_fdiagnostics-hotness-threshold:
448 **-fdiagnostics-hotness-threshold**
449 Prevent optimization remarks from being output if they do not have at least
452 This option, which defaults to zero, controls the minimum hotness an
453 optimization remark would need in order to be output by Clang. This is
454 currently supported with optimization remarks (see :ref:`Options to Emit
455 Optimization Reports <rpass>`) when profile hotness information in
456 diagnostics is enabled (see
457 :ref:`-fdiagnostics-show-hotness <opt_fdiagnostics-show-hotness>`).
459 .. _opt_fdiagnostics-fixit-info:
461 **-f[no-]diagnostics-fixit-info**
462 Enable "FixIt" information in the diagnostics output.
464 This option, which defaults to on, controls whether or not Clang
465 prints the information on how to fix a specific diagnostic
466 underneath it when it knows. For example, in this output:
470 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
475 Passing **-fno-diagnostics-fixit-info** will prevent Clang from
476 printing the "//" line at the end of the message. This information
477 is useful for users who may not understand what is wrong, but can be
478 confusing for machine parsing.
480 .. _opt_fdiagnostics-print-source-range-info:
482 **-fdiagnostics-print-source-range-info**
483 Print machine parsable information about source ranges.
484 This option makes Clang print information about source ranges in a machine
485 parsable format after the file/line/column number information. The
486 information is a simple sequence of brace enclosed ranges, where each range
487 lists the start and end line/column locations. For example, in this output:
491 exprs.c:47:15:{47:8-47:14}{47:17-47:24}: error: invalid operands to binary expression ('int *' and '_Complex float')
492 P = (P-42) + Gamma*4;
495 The {}'s are generated by -fdiagnostics-print-source-range-info.
497 The printed column numbers count bytes from the beginning of the
498 line; take care if your source contains multibyte characters.
500 .. option:: -fdiagnostics-parseable-fixits
502 Print Fix-Its in a machine parseable form.
504 This option makes Clang print available Fix-Its in a machine
505 parseable format at the end of diagnostics. The following example
506 illustrates the format:
510 fix-it:"t.cpp":{7:25-7:29}:"Gamma"
512 The range printed is a half-open range, so in this example the
513 characters at column 25 up to but not including column 29 on line 7
514 in t.cpp should be replaced with the string "Gamma". Either the
515 range or the replacement string may be empty (representing strict
516 insertions and strict erasures, respectively). Both the file name
517 and the insertion string escape backslash (as "\\\\"), tabs (as
518 "\\t"), newlines (as "\\n"), double quotes(as "\\"") and
519 non-printable characters (as octal "\\xxx").
521 The printed column numbers count bytes from the beginning of the
522 line; take care if your source contains multibyte characters.
524 .. option:: -fno-elide-type
526 Turns off elision in template type printing.
528 The default for template type printing is to elide as many template
529 arguments as possible, removing those which are the same in both
530 template types, leaving only the differences. Adding this flag will
531 print all the template arguments. If supported by the terminal,
532 highlighting will still appear on differing arguments.
538 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;
544 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;
546 .. option:: -fdiagnostics-show-template-tree
548 Template type diffing prints a text tree.
550 For diffing large templated types, this option will cause Clang to
551 display the templates as an indented text tree, one argument per
552 line, with differences marked inline. This is compatible with
559 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;
561 With :option:`-fdiagnostics-show-template-tree`:
565 t.cc:4:5: note: candidate function not viable: no known conversion for 1st argument;
573 .. _cl_diag_warning_groups:
575 Individual Warning Groups
576 ^^^^^^^^^^^^^^^^^^^^^^^^^
578 TODO: Generate this from tblgen. Define one anchor per warning group.
580 .. _opt_wextra-tokens:
582 .. option:: -Wextra-tokens
584 Warn about excess tokens at the end of a preprocessor directive.
586 This option, which defaults to on, enables warnings about extra
587 tokens at the end of preprocessor directives. For example:
591 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
595 These extra tokens are not strictly conforming, and are usually best
596 handled by commenting them out.
598 .. option:: -Wambiguous-member-template
600 Warn about unqualified uses of a member template whose name resolves to
601 another template at the location of the use.
603 This option, which defaults to on, enables a warning in the
608 template<typename T> struct set{};
609 template<typename T> struct trait { typedef const T& type; };
611 template<typename T> void set(typename trait<T>::type value) {}
618 C++ [basic.lookup.classref] requires this to be an error, but,
619 because it's hard to work around, Clang downgrades it to a warning
622 .. option:: -Wbind-to-temporary-copy
624 Warn about an unusable copy constructor when binding a reference to a
627 This option enables warnings about binding a
628 reference to a temporary when the temporary doesn't have a usable
629 copy constructor. For example:
636 NonCopyable(const NonCopyable&);
638 void foo(const NonCopyable&);
640 foo(NonCopyable()); // Disallowed in C++98; allowed in C++11.
645 struct NonCopyable2 {
647 NonCopyable2(NonCopyable2&);
649 void foo(const NonCopyable2&);
651 foo(NonCopyable2()); // Disallowed in C++98; allowed in C++11.
654 Note that if ``NonCopyable2::NonCopyable2()`` has a default argument
655 whose instantiation produces a compile error, that error will still
656 be a hard error in C++98 mode even if this warning is turned off.
658 Options to Control Clang Crash Diagnostics
659 ------------------------------------------
661 As unbelievable as it may sound, Clang does crash from time to time.
662 Generally, this only occurs to those living on the `bleeding
663 edge <https://llvm.org/releases/download.html#svn>`_. Clang goes to great
664 lengths to assist you in filing a bug report. Specifically, Clang
665 generates preprocessed source file(s) and associated run script(s) upon
666 a crash. These files should be attached to a bug report to ease
667 reproducibility of the failure. Below are the command line options to
668 control the crash diagnostics.
670 .. option:: -fcrash-diagnostics=<val>
674 * ``off`` (Disable auto-generation of preprocessed source files during a clang crash.)
675 * ``compiler`` (Generate diagnostics for compiler crashes (default))
676 * ``all`` (Generate diagnostics for all tools which support it)
678 .. option:: -fno-crash-diagnostics
680 Disable auto-generation of preprocessed source files during a clang crash.
682 The -fno-crash-diagnostics flag can be helpful for speeding the process
683 of generating a delta reduced test case.
685 .. option:: -fcrash-diagnostics-dir=<dir>
687 Specify where to write the crash diagnostics files; defaults to the
688 usual location for temporary files.
690 Clang is also capable of generating preprocessed source file(s) and associated
691 run script(s) even without a crash. This is specially useful when trying to
692 generate a reproducer for warnings or errors while using modules.
694 .. option:: -gen-reproducer
696 Generates preprocessed source files, a reproducer script and if relevant, a
697 cache containing: built module pcm's and all headers needed to rebuild the
702 Options to Emit Optimization Reports
703 ------------------------------------
705 Optimization reports trace, at a high-level, all the major decisions
706 done by compiler transformations. For instance, when the inliner
707 decides to inline function ``foo()`` into ``bar()``, or the loop unroller
708 decides to unroll a loop N times, or the vectorizer decides to
709 vectorize a loop body.
711 Clang offers a family of flags which the optimizers can use to emit
712 a diagnostic in three cases:
714 1. When the pass makes a transformation (`-Rpass`).
716 2. When the pass fails to make a transformation (`-Rpass-missed`).
718 3. When the pass determines whether or not to make a transformation
721 NOTE: Although the discussion below focuses on `-Rpass`, the exact
722 same options apply to `-Rpass-missed` and `-Rpass-analysis`.
724 Since there are dozens of passes inside the compiler, each of these flags
725 take a regular expression that identifies the name of the pass which should
726 emit the associated diagnostic. For example, to get a report from the inliner,
727 compile the code with:
729 .. code-block:: console
731 $ clang -O2 -Rpass=inline code.cc -o code
732 code.cc:4:25: remark: foo inlined into bar [-Rpass=inline]
733 int bar(int j) { return foo(j, j - 2); }
736 Note that remarks from the inliner are identified with `[-Rpass=inline]`.
737 To request a report from every optimization pass, you should use
738 `-Rpass=.*` (in fact, you can use any valid POSIX regular
739 expression). However, do not expect a report from every transformation
740 made by the compiler. Optimization remarks do not really make sense
741 outside of the major transformations (e.g., inlining, vectorization,
742 loop optimizations) and not every optimization pass supports this
745 Note that when using profile-guided optimization information, profile hotness
746 information can be included in the remarks (see
747 :ref:`-fdiagnostics-show-hotness <opt_fdiagnostics-show-hotness>`).
752 1. Optimization remarks that refer to function names will display the
753 mangled name of the function. Since these remarks are emitted by the
754 back end of the compiler, it does not know anything about the input
755 language, nor its mangling rules.
757 2. Some source locations are not displayed correctly. The front end has
758 a more detailed source location tracking than the locations included
759 in the debug info (e.g., the front end can locate code inside macro
760 expansions). However, the locations used by `-Rpass` are
761 translated from debug annotations. That translation can be lossy,
762 which results in some remarks having no location information.
764 Options to Emit Resource Consumption Reports
765 --------------------------------------------
767 These are options that report execution time and consumed memory of different
770 .. option:: -fproc-stat-report=
772 This option requests driver to print used memory and execution time of each
773 compilation step. The ``clang`` driver during execution calls different tools,
774 like compiler, assembler, linker etc. With this option the driver reports
775 total execution time, the execution time spent in user mode and peak memory
776 usage of each the called tool. Value of the option specifies where the report
777 is sent to. If it specifies a regular file, the data are saved to this file in
780 .. code-block:: console
782 $ clang -fproc-stat-report=abc foo.c
784 clang-11,"/tmp/foo-123456.o",92000,84000,87536
785 ld,"a.out",900,8000,53568
787 The data on each row represent:
789 * file name of the tool executable,
790 * output file name in quotes,
791 * total execution time in microseconds,
792 * execution time in user mode in microseconds,
793 * peak memory usage in Kb.
795 It is possible to specify this option without any value. In this case statistics
796 are printed on standard output in human readable format:
798 .. code-block:: console
800 $ clang -fproc-stat-report foo.c
801 clang-11: output=/tmp/foo-855a8e.o, total=68.000 ms, user=60.000 ms, mem=86920 Kb
802 ld: output=a.out, total=8.000 ms, user=4.000 ms, mem=52320 Kb
804 The report file specified in the option is locked for write, so this option
805 can be used to collect statistics in parallel builds. The report file is not
806 cleared, new data is appended to it, thus making posible to accumulate build
809 You can also use environment variables to control the process statistics reporting.
810 Setting ``CC_PRINT_PROC_STAT`` to ``1`` enables the feature, the report goes to
811 stdout in human readable format.
812 Setting ``CC_PRINT_PROC_STAT_FILE`` to a fully qualified file path makes it report
813 process statistics to the given file in the CSV format. Specifying a relative
814 path will likely lead to multiple files with the same name created in different
815 directories, since the path is relative to a changing working directory.
817 These environment variables are handy when you need to request the statistics
818 report without changing your build scripts or alter the existing set of compiler
819 options. Note that ``-fproc-stat-report`` take precedence over ``CC_PRINT_PROC_STAT``
820 and ``CC_PRINT_PROC_STAT_FILE``.
822 .. code-block:: console
824 $ export CC_PRINT_PROC_STAT=1
825 $ export CC_PRINT_PROC_STAT_FILE=~/project-build-proc-stat.csv
830 Clang options that don't fit neatly into other categories.
832 .. option:: -fgnuc-version=
834 This flag controls the value of ``__GNUC__`` and related macros. This flag
835 does not enable or disable any GCC extensions implemented in Clang. Setting
836 the version to zero causes Clang to leave ``__GNUC__`` and other
837 GNU-namespaced macros, such as ``__GXX_WEAK__``, undefined.
841 When emitting a dependency file, use formatting conventions appropriate
842 for NMake or Jom. Ignored unless another option causes Clang to emit a
845 When Clang emits a dependency file (e.g., you supplied the -M option)
846 most filenames can be written to the file without any special formatting.
847 Different Make tools will treat different sets of characters as "special"
848 and use different conventions for telling the Make tool that the character
849 is actually part of the filename. Normally Clang uses backslash to "escape"
850 a special character, which is the convention used by GNU Make. The -MV
851 option tells Clang to put double-quotes around the entire filename, which
852 is the convention used by NMake and Jom.
854 .. option:: -femit-dwarf-unwind=<value>
856 When to emit DWARF unwind (EH frame) info. This is a Mach-O-specific option.
860 * ``no-compact-unwind`` - Only emit DWARF unwind when compact unwind encodings
861 aren't available. This is the default for arm64.
862 * ``always`` - Always emit DWARF unwind regardless.
863 * ``default`` - Use the platform-specific default (``always`` for all
864 non-arm64-platforms).
866 ``no-compact-unwind`` is a performance optimization -- Clang will emit smaller
867 object files that are more quickly processed by the linker. This may cause
868 binary compatibility issues on older x86_64 targets, however, so use it with
871 .. _configuration-files:
876 Configuration files group command-line options and allow all of them to be
877 specified just by referencing the configuration file. They may be used, for
878 example, to collect options required to tune compilation for particular
879 target, such as -L, -I, -l, --sysroot, codegen options, etc.
881 The command line option `--config` can be used to specify configuration
882 file in a Clang invocation. For example:
886 clang --config /home/user/cfgs/testing.txt
887 clang --config debug.cfg
889 If the provided argument contains a directory separator, it is considered as
890 a file path, and options are read from that file. Otherwise the argument is
891 treated as a file name and is searched for sequentially in the directories:
895 - the directory where Clang executable resides.
897 Both user and system directories for configuration files are specified during
898 clang build using CMake parameters, CLANG_CONFIG_FILE_USER_DIR and
899 CLANG_CONFIG_FILE_SYSTEM_DIR respectively. The first file found is used. It is
900 an error if the required file cannot be found.
902 Another way to specify a configuration file is to encode it in executable name.
903 For example, if the Clang executable is named `armv7l-clang` (it may be a
904 symbolic link to `clang`), then Clang will search for file `armv7l.cfg` in the
905 directory where Clang resides.
907 If a driver mode is specified in invocation, Clang tries to find a file specific
908 for the specified mode. For example, if the executable file is named
909 `x86_64-clang-cl`, Clang first looks for `x86_64-cl.cfg` and if it is not found,
910 looks for `x86_64.cfg`.
912 If the command line contains options that effectively change target architecture
913 (these are -m32, -EL, and some others) and the configuration file starts with an
914 architecture name, Clang tries to load the configuration file for the effective
915 architecture. For example, invocation:
919 x86_64-clang -m32 abc.c
921 causes Clang search for a file `i368.cfg` first, and if no such file is found,
922 Clang looks for the file `x86_64.cfg`.
924 The configuration file consists of command-line options specified on one or
925 more lines. Lines composed of whitespace characters only are ignored as well as
926 lines in which the first non-blank character is `#`. Long options may be split
927 between several lines by a trailing backslash. Here is example of a
932 # Several options on line
933 -c --target=x86_64-unknown-linux-gnu
935 # Long option split between lines
936 -I/usr/lib/gcc/x86_64-linux-gnu/5.4.0/../../../../\
939 # other config files may be included
942 Files included by `@file` directives in configuration files are resolved
943 relative to the including file. For example, if a configuration file
944 `~/.llvm/target.cfg` contains the directive `@os/linux.opts`, the file
945 `linux.opts` is searched for in the directory `~/.llvm/os`.
947 To generate paths relative to the configuration file, the `<CFGDIR>` token may
948 be used. This will expand to the absolute path of the directory containing the
951 In cases where a configuration file is deployed alongside SDK contents, the
952 SDK directory can remain fully portable by using `<CFGDIR>` prefixed paths.
953 In this way, the user may only need to specify a root configuration file with
954 `--config` to establish every aspect of the SDK with the compiler:
959 -isystem <CFGDIR>/include
961 -T <CFGDIR>/ldscripts/link.ld
963 Language and Target-Independent Features
964 ========================================
966 Controlling Errors and Warnings
967 -------------------------------
969 Clang provides a number of ways to control which code constructs cause
970 it to emit errors and warning messages, and how they are displayed to
973 Controlling How Clang Displays Diagnostics
974 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
976 When Clang emits a diagnostic, it includes rich information in the
977 output, and gives you fine-grain control over which information is
978 printed. Clang has the ability to print this information, and these are
979 the options that control it:
981 #. A file/line/column indicator that shows exactly where the diagnostic
982 occurs in your code [:ref:`-fshow-column <opt_fshow-column>`,
983 :ref:`-fshow-source-location <opt_fshow-source-location>`].
984 #. A categorization of the diagnostic as a note, warning, error, or
986 #. A text string that describes what the problem is.
987 #. An option that indicates how to control the diagnostic (for
988 diagnostics that support it)
989 [:ref:`-fdiagnostics-show-option <opt_fdiagnostics-show-option>`].
990 #. A :ref:`high-level category <diagnostics_categories>` for the diagnostic
991 for clients that want to group diagnostics by class (for diagnostics
993 [:ref:`-fdiagnostics-show-category <opt_fdiagnostics-show-category>`].
994 #. The line of source code that the issue occurs on, along with a caret
995 and ranges that indicate the important locations
996 [:ref:`-fcaret-diagnostics <opt_fcaret-diagnostics>`].
997 #. "FixIt" information, which is a concise explanation of how to fix the
998 problem (when Clang is certain it knows)
999 [:ref:`-fdiagnostics-fixit-info <opt_fdiagnostics-fixit-info>`].
1000 #. A machine-parsable representation of the ranges involved (off by
1002 [:ref:`-fdiagnostics-print-source-range-info <opt_fdiagnostics-print-source-range-info>`].
1004 For more information please see :ref:`Formatting of
1005 Diagnostics <cl_diag_formatting>`.
1010 All diagnostics are mapped into one of these 6 classes:
1019 .. _diagnostics_categories:
1021 Diagnostic Categories
1022 ^^^^^^^^^^^^^^^^^^^^^
1024 Though not shown by default, diagnostics may each be associated with a
1025 high-level category. This category is intended to make it possible to
1026 triage builds that produce a large number of errors or warnings in a
1029 Categories are not shown by default, but they can be turned on with the
1030 :ref:`-fdiagnostics-show-category <opt_fdiagnostics-show-category>` option.
1031 When set to "``name``", the category is printed textually in the
1032 diagnostic output. When it is set to "``id``", a category number is
1033 printed. The mapping of category names to category id's can be obtained
1034 by running '``clang --print-diagnostic-categories``'.
1036 Controlling Diagnostics via Command Line Flags
1037 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1039 TODO: -W flags, -pedantic, etc
1041 .. _pragma_gcc_diagnostic:
1043 Controlling Diagnostics via Pragmas
1044 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1046 Clang can also control what diagnostics are enabled through the use of
1047 pragmas in the source code. This is useful for turning off specific
1048 warnings in a section of source code. Clang supports GCC's pragma for
1049 compatibility with existing source code, as well as several extensions.
1051 The pragma may control any warning that can be used from the command
1052 line. Warnings may be set to ignored, warning, error, or fatal. The
1053 following example code will tell Clang or GCC to ignore the -Wall
1058 #pragma GCC diagnostic ignored "-Wall"
1060 In addition to all of the functionality provided by GCC's pragma, Clang
1061 also allows you to push and pop the current warning state. This is
1062 particularly useful when writing a header file that will be compiled by
1063 other people, because you don't know what warning flags they build with.
1065 In the below example :option:`-Wextra-tokens` is ignored for only a single line
1066 of code, after which the diagnostics return to whatever state had previously
1072 #endif foo // warning: extra tokens at end of #endif directive
1074 #pragma clang diagnostic push
1075 #pragma clang diagnostic ignored "-Wextra-tokens"
1078 #endif foo // no warning
1080 #pragma clang diagnostic pop
1082 The push and pop pragmas will save and restore the full diagnostic state
1083 of the compiler, regardless of how it was set. That means that it is
1084 possible to use push and pop around GCC compatible diagnostics and Clang
1085 will push and pop them appropriately, while GCC will ignore the pushes
1086 and pops as unknown pragmas. It should be noted that while Clang
1087 supports the GCC pragma, Clang and GCC do not support the exact same set
1088 of warnings, so even when using GCC compatible #pragmas there is no
1089 guarantee that they will have identical behaviour on both compilers.
1091 In addition to controlling warnings and errors generated by the compiler, it is
1092 possible to generate custom warning and error messages through the following
1097 // The following will produce warning messages
1098 #pragma message "some diagnostic message"
1099 #pragma GCC warning "TODO: replace deprecated feature"
1101 // The following will produce an error message
1102 #pragma GCC error "Not supported"
1104 These pragmas operate similarly to the ``#warning`` and ``#error`` preprocessor
1105 directives, except that they may also be embedded into preprocessor macros via
1106 the C99 ``_Pragma`` operator, for example:
1111 #define DEFER(M,...) M(__VA_ARGS__)
1112 #define CUSTOM_ERROR(X) _Pragma(STR(GCC error(X " at line " DEFER(STR,__LINE__))))
1114 CUSTOM_ERROR("Feature not available");
1116 Controlling Diagnostics in System Headers
1117 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1119 Warnings are suppressed when they occur in system headers. By default,
1120 an included file is treated as a system header if it is found in an
1121 include path specified by ``-isystem``, but this can be overridden in
1124 The ``system_header`` pragma can be used to mark the current file as
1125 being a system header. No warnings will be produced from the location of
1126 the pragma onwards within the same file.
1131 #endif foo // warning: extra tokens at end of #endif directive
1133 #pragma clang system_header
1136 #endif foo // no warning
1138 The `--system-header-prefix=` and `--no-system-header-prefix=`
1139 command-line arguments can be used to override whether subsets of an include
1140 path are treated as system headers. When the name in a ``#include`` directive
1141 is found within a header search path and starts with a system prefix, the
1142 header is treated as a system header. The last prefix on the
1143 command-line which matches the specified header name takes precedence.
1146 .. code-block:: console
1148 $ clang -Ifoo -isystem bar --system-header-prefix=x/ \
1149 --no-system-header-prefix=x/y/
1151 Here, ``#include "x/a.h"`` is treated as including a system header, even
1152 if the header is found in ``foo``, and ``#include "x/y/b.h"`` is treated
1153 as not including a system header, even if the header is found in
1156 A ``#include`` directive which finds a file relative to the current
1157 directory is treated as including a system header if the including file
1158 is treated as a system header.
1160 Controlling Deprecation Diagnostics in Clang-Provided C Runtime Headers
1161 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1163 Clang is responsible for providing some of the C runtime headers that cannot be
1164 provided by a platform CRT, such as implementation limits or when compiling in
1165 freestanding mode. Define the ``_CLANG_DISABLE_CRT_DEPRECATION_WARNINGS`` macro
1166 prior to including such a C runtime header to disable the deprecation warnings.
1167 Note that the C Standard Library headers are allowed to transitively include
1168 other standard library headers (see 7.1.2p5), and so the most appropriate use
1169 of this macro is to set it within the build system using ``-D`` or before any
1170 include directives in the translation unit.
1174 #define _CLANG_DISABLE_CRT_DEPRECATION_WARNINGS
1175 #include <stdint.h> // Clang CRT deprecation warnings are disabled.
1176 #include <stdatomic.h> // Clang CRT deprecation warnings are disabled.
1178 .. _diagnostics_enable_everything:
1180 Enabling All Diagnostics
1181 ^^^^^^^^^^^^^^^^^^^^^^^^
1183 In addition to the traditional ``-W`` flags, one can enable **all** diagnostics
1184 by passing :option:`-Weverything`. This works as expected with
1185 :option:`-Werror`, and also includes the warnings from :option:`-pedantic`. Some
1186 diagnostics contradict each other, therefore, users of :option:`-Weverything`
1187 often disable many diagnostics such as `-Wno-c++98-compat` and `-Wno-c++-compat`
1188 because they contradict recent C++ standards.
1190 Since :option:`-Weverything` enables every diagnostic, we generally don't
1191 recommend using it. `-Wall` `-Wextra` are a better choice for most projects.
1192 Using :option:`-Weverything` means that updating your compiler is more difficult
1193 because you're exposed to experimental diagnostics which might be of lower
1194 quality than the default ones. If you do use :option:`-Weverything` then we
1195 advise that you address all new compiler diagnostics as they get added to Clang,
1196 either by fixing everything they find or explicitly disabling that diagnostic
1197 with its corresponding `Wno-` option.
1199 Note that when combined with :option:`-w` (which disables all warnings),
1200 disabling all warnings wins.
1202 Controlling Static Analyzer Diagnostics
1203 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1205 While not strictly part of the compiler, the diagnostics from Clang's
1206 `static analyzer <https://clang-analyzer.llvm.org>`_ can also be
1207 influenced by the user via changes to the source code. See the available
1208 `annotations <https://clang-analyzer.llvm.org/annotations.html>`_ and the
1210 page <https://clang-analyzer.llvm.org/faq.html#exclude_code>`_ for more
1213 .. _usersmanual-precompiled-headers:
1218 `Precompiled headers <https://en.wikipedia.org/wiki/Precompiled_header>`_
1219 are a general approach employed by many compilers to reduce compilation
1220 time. The underlying motivation of the approach is that it is common for
1221 the same (and often large) header files to be included by multiple
1222 source files. Consequently, compile times can often be greatly improved
1223 by caching some of the (redundant) work done by a compiler to process
1224 headers. Precompiled header files, which represent one of many ways to
1225 implement this optimization, are literally files that represent an
1226 on-disk cache that contains the vital information necessary to reduce
1227 some of the work needed to process a corresponding header file. While
1228 details of precompiled headers vary between compilers, precompiled
1229 headers have been shown to be highly effective at speeding up program
1230 compilation on systems with very large system headers (e.g., macOS).
1232 Generating a PCH File
1233 ^^^^^^^^^^^^^^^^^^^^^
1235 To generate a PCH file using Clang, one invokes Clang with the
1236 `-x <language>-header` option. This mirrors the interface in GCC
1237 for generating PCH files:
1239 .. code-block:: console
1241 $ gcc -x c-header test.h -o test.h.gch
1242 $ clang -x c-header test.h -o test.h.pch
1247 A PCH file can then be used as a prefix header when a ``-include-pch``
1248 option is passed to ``clang``:
1250 .. code-block:: console
1252 $ clang -include-pch test.h.pch test.c -o test
1254 The ``clang`` driver will check if the PCH file ``test.h.pch`` is
1255 available; if so, the contents of ``test.h`` (and the files it includes)
1256 will be processed from the PCH file. Otherwise, Clang will report an error.
1260 Clang does *not* automatically use PCH files for headers that are directly
1261 included within a source file or indirectly via :option:`-include`.
1264 .. code-block:: console
1266 $ clang -x c-header test.h -o test.h.pch
1269 $ clang test.c -o test
1271 In this example, ``clang`` will not automatically use the PCH file for
1272 ``test.h`` since ``test.h`` was included directly in the source file and not
1273 specified on the command line using ``-include-pch``.
1275 Relocatable PCH Files
1276 ^^^^^^^^^^^^^^^^^^^^^
1278 It is sometimes necessary to build a precompiled header from headers
1279 that are not yet in their final, installed locations. For example, one
1280 might build a precompiled header within the build tree that is then
1281 meant to be installed alongside the headers. Clang permits the creation
1282 of "relocatable" precompiled headers, which are built with a given path
1283 (into the build directory) and can later be used from an installed
1286 To build a relocatable precompiled header, place your headers into a
1287 subdirectory whose structure mimics the installed location. For example,
1288 if you want to build a precompiled header for the header ``mylib.h``
1289 that will be installed into ``/usr/include``, create a subdirectory
1290 ``build/usr/include`` and place the header ``mylib.h`` into that
1291 subdirectory. If ``mylib.h`` depends on other headers, then they can be
1292 stored within ``build/usr/include`` in a way that mimics the installed
1295 Building a relocatable precompiled header requires two additional
1296 arguments. First, pass the ``--relocatable-pch`` flag to indicate that
1297 the resulting PCH file should be relocatable. Second, pass
1298 ``-isysroot /path/to/build``, which makes all includes for your library
1299 relative to the build directory. For example:
1301 .. code-block:: console
1303 # clang -x c-header --relocatable-pch -isysroot /path/to/build /path/to/build/mylib.h mylib.h.pch
1305 When loading the relocatable PCH file, the various headers used in the
1306 PCH file are found from the system header root. For example, ``mylib.h``
1307 can be found in ``/usr/include/mylib.h``. If the headers are installed
1308 in some other system root, the ``-isysroot`` option can be used provide
1309 a different system root from which the headers will be based. For
1310 example, ``-isysroot /Developer/SDKs/MacOSX10.4u.sdk`` will look for
1311 ``mylib.h`` in ``/Developer/SDKs/MacOSX10.4u.sdk/usr/include/mylib.h``.
1313 Relocatable precompiled headers are intended to be used in a limited
1314 number of cases where the compilation environment is tightly controlled
1315 and the precompiled header cannot be generated after headers have been
1318 .. _controlling-fp-behavior:
1320 Controlling Floating Point Behavior
1321 -----------------------------------
1323 Clang provides a number of ways to control floating point behavior, including
1324 with command line options and source pragmas. This section
1325 describes the various floating point semantic modes and the corresponding options.
1327 .. csv-table:: Floating Point Semantic Modes
1328 :header: "Mode", "Values"
1331 "ffp-exception-behavior", "{ignore, strict, may_trap}",
1332 "fenv_access", "{off, on}", "(none)"
1333 "frounding-math", "{dynamic, tonearest, downward, upward, towardzero}"
1334 "ffp-contract", "{on, off, fast, fast-honor-pragmas}"
1335 "fdenormal-fp-math", "{IEEE, PreserveSign, PositiveZero}"
1336 "fdenormal-fp-math-fp32", "{IEEE, PreserveSign, PositiveZero}"
1337 "fmath-errno", "{on, off}"
1338 "fhonor-nans", "{on, off}"
1339 "fhonor-infinities", "{on, off}"
1340 "fsigned-zeros", "{on, off}"
1341 "freciprocal-math", "{on, off}"
1342 "allow_approximate_fns", "{on, off}"
1343 "fassociative-math", "{on, off}"
1345 This table describes the option settings that correspond to the three
1346 floating point semantic models: precise (the default), strict, and fast.
1349 .. csv-table:: Floating Point Models
1350 :header: "Mode", "Precise", "Strict", "Fast"
1351 :widths: 25, 15, 15, 15
1353 "except_behavior", "ignore", "strict", "ignore"
1354 "fenv_access", "off", "on", "off"
1355 "rounding_mode", "tonearest", "dynamic", "tonearest"
1356 "contract", "on", "off", "fast"
1357 "denormal_fp_math", "IEEE", "IEEE", "PreserveSign"
1358 "denormal_fp32_math", "IEEE","IEEE", "PreserveSign"
1359 "support_math_errno", "on", "on", "off"
1360 "no_honor_nans", "off", "off", "on"
1361 "no_honor_infinities", "off", "off", "on"
1362 "no_signed_zeros", "off", "off", "on"
1363 "allow_reciprocal", "off", "off", "on"
1364 "allow_approximate_fns", "off", "off", "on"
1365 "allow_reassociation", "off", "off", "on"
1367 .. option:: -ffast-math
1369 Enable fast-math mode. This option lets the
1370 compiler make aggressive, potentially-lossy assumptions about
1371 floating-point math. These include:
1373 * Floating-point math obeys regular algebraic rules for real numbers (e.g.
1374 ``+`` and ``*`` are associative, ``x/y == x * (1/y)``, and
1375 ``(a + b) * c == a * c + b * c``),
1376 * Operands to floating-point operations are not equal to ``NaN`` and
1378 * ``+0`` and ``-0`` are interchangeable.
1380 ``-ffast-math`` also defines the ``__FAST_MATH__`` preprocessor
1381 macro. Some math libraries recognize this macro and change their behavior.
1382 With the exception of ``-ffp-contract=fast``, using any of the options
1383 below to disable any of the individual optimizations in ``-ffast-math``
1384 will cause ``__FAST_MATH__`` to no longer be set.
1386 This option implies:
1388 * ``-fno-honor-infinities``
1390 * ``-fno-honor-nans``
1392 * ``-fno-math-errno``
1394 * ``-ffinite-math-only``
1396 * ``-fassociative-math``
1398 * ``-freciprocal-math``
1400 * ``-fno-signed-zeros``
1402 * ``-fno-trapping-math``
1404 * ``-ffp-contract=fast``
1406 .. option:: -fdenormal-fp-math=<value>
1408 Select which denormal numbers the code is permitted to require.
1412 * ``ieee`` - IEEE 754 denormal numbers
1413 * ``preserve-sign`` - the sign of a flushed-to-zero number is preserved in the sign of 0
1414 * ``positive-zero`` - denormals are flushed to positive zero
1416 Defaults to ``ieee``.
1418 .. _opt_fstrict-float-cast-overflow:
1420 **-f[no-]strict-float-cast-overflow**
1422 When a floating-point value is not representable in a destination integer
1423 type, the code has undefined behavior according to the language standard.
1424 By default, Clang will not guarantee any particular result in that case.
1425 With the 'no-strict' option, Clang will saturate towards the smallest and
1426 largest representable integer values instead. NaNs will be converted to zero.
1428 .. _opt_fmath-errno:
1430 **-f[no-]math-errno**
1432 Require math functions to indicate errors by setting errno.
1433 The default varies by ToolChain. ``-fno-math-errno`` allows optimizations
1434 that might cause standard C math functions to not set ``errno``.
1435 For example, on some systems, the math function ``sqrt`` is specified
1436 as setting ``errno`` to ``EDOM`` when the input is negative. On these
1437 systems, the compiler cannot normally optimize a call to ``sqrt`` to use
1438 inline code (e.g. the x86 ``sqrtsd`` instruction) without additional
1439 checking to ensure that ``errno`` is set appropriately.
1440 ``-fno-math-errno`` permits these transformations.
1442 On some targets, math library functions never set ``errno``, and so
1443 ``-fno-math-errno`` is the default. This includes most BSD-derived
1444 systems, including Darwin.
1446 .. _opt_ftrapping-math:
1448 **-f[no-]trapping-math**
1450 Control floating point exception behavior. ``-fno-trapping-math`` allows optimizations that assume that floating point operations cannot generate traps such as divide-by-zero, overflow and underflow.
1452 - The option ``-ftrapping-math`` behaves identically to ``-ffp-exception-behavior=strict``.
1453 - The option ``-fno-trapping-math`` behaves identically to ``-ffp-exception-behavior=ignore``. This is the default.
1455 .. option:: -ffp-contract=<value>
1457 Specify when the compiler is permitted to form fused floating-point
1458 operations, such as fused multiply-add (FMA). Fused operations are
1459 permitted to produce more precise results than performing the same
1460 operations separately.
1462 The C standard permits intermediate floating-point results within an
1463 expression to be computed with more precision than their type would
1464 normally allow. This permits operation fusing, and Clang takes advantage
1465 of this by default. This behavior can be controlled with the ``FP_CONTRACT``
1466 and ``clang fp contract`` pragmas. Please refer to the pragma documentation
1467 for a description of how the pragmas interact with this option.
1471 * ``fast`` (fuse across statements disregarding pragmas, default for CUDA)
1472 * ``on`` (fuse in the same statement unless dictated by pragmas, default for languages other than CUDA/HIP)
1473 * ``off`` (never fuse)
1474 * ``fast-honor-pragmas`` (fuse across statements unless dictated by pragmas, default for HIP)
1476 .. _opt_fhonor-infinities:
1478 **-f[no-]honor-infinities**
1480 If both ``-fno-honor-infinities`` and ``-fno-honor-nans`` are used,
1481 has the same effect as specifying ``-ffinite-math-only``.
1483 .. _opt_fhonor-nans:
1485 **-f[no-]honor-nans**
1487 If both ``-fno-honor-infinities`` and ``-fno-honor-nans`` are used,
1488 has the same effect as specifying ``-ffinite-math-only``.
1490 .. _opt_fapprox-func:
1492 **-f[no-]approx-func**
1494 Allow certain math function calls (such as ``log``, ``sqrt``, ``pow``, etc)
1495 to be replaced with an approximately equivalent set of instructions
1496 or alternative math function calls. For example, a ``pow(x, 0.25)``
1497 may be replaced with ``sqrt(sqrt(x))``, despite being an inexact result
1498 in cases where ``x`` is ``-0.0`` or ``-inf``.
1499 Defaults to ``-fno-approx-func``.
1501 .. _opt_fsigned-zeros:
1503 **-f[no-]signed-zeros**
1505 Allow optimizations that ignore the sign of floating point zeros.
1506 Defaults to ``-fno-signed-zeros``.
1508 .. _opt_fassociative-math:
1510 **-f[no-]associative-math**
1512 Allow floating point operations to be reassociated.
1513 Defaults to ``-fno-associative-math``.
1515 .. _opt_freciprocal-math:
1517 **-f[no-]reciprocal-math**
1519 Allow division operations to be transformed into multiplication by a
1520 reciprocal. This can be significantly faster than an ordinary division
1521 but can also have significantly less precision. Defaults to
1522 ``-fno-reciprocal-math``.
1524 .. _opt_funsafe-math-optimizations:
1526 **-f[no-]unsafe-math-optimizations**
1528 Allow unsafe floating-point optimizations. Also implies:
1530 * ``-fassociative-math``
1531 * ``-freciprocal-math``
1532 * ``-fno-signed-zeroes``
1533 * ``-fno-trapping-math``.
1535 Defaults to ``-fno-unsafe-math-optimizations``.
1537 .. _opt_ffinite-math-only:
1539 **-f[no-]finite-math-only**
1541 Allow floating-point optimizations that assume arguments and results are
1542 not NaNs or +-Inf. This defines the ``__FINITE_MATH_ONLY__`` preprocessor macro.
1545 * ``-fno-honor-infinities``
1546 * ``-fno-honor-nans``
1548 Defaults to ``-fno-finite-math-only``.
1550 .. _opt_frounding-math:
1552 **-f[no-]rounding-math**
1554 Force floating-point operations to honor the dynamically-set rounding mode by default.
1556 The result of a floating-point operation often cannot be exactly represented in the result type and therefore must be rounded. IEEE 754 describes different rounding modes that control how to perform this rounding, not all of which are supported by all implementations. C provides interfaces (``fesetround`` and ``fesetenv``) for dynamically controlling the rounding mode, and while it also recommends certain conventions for changing the rounding mode, these conventions are not typically enforced in the ABI. Since the rounding mode changes the numerical result of operations, the compiler must understand something about it in order to optimize floating point operations.
1558 Note that floating-point operations performed as part of constant initialization are formally performed prior to the start of the program and are therefore not subject to the current rounding mode. This includes the initialization of global variables and local ``static`` variables. Floating-point operations in these contexts will be rounded using ``FE_TONEAREST``.
1560 - The option ``-fno-rounding-math`` allows the compiler to assume that the rounding mode is set to ``FE_TONEAREST``. This is the default.
1561 - The option ``-frounding-math`` forces the compiler to honor the dynamically-set rounding mode. This prevents optimizations which might affect results if the rounding mode changes or is different from the default; for example, it prevents floating-point operations from being reordered across most calls and prevents constant-folding when the result is not exactly representable.
1563 .. option:: -ffp-model=<value>
1565 Specify floating point behavior. ``-ffp-model`` is an umbrella
1566 option that encompasses functionality provided by other, single
1567 purpose, floating point options. Valid values are: ``precise``, ``strict``,
1571 * ``precise`` Disables optimizations that are not value-safe on floating-point data, although FP contraction (FMA) is enabled (``-ffp-contract=on``). This is the default behavior.
1572 * ``strict`` Enables ``-frounding-math`` and ``-ffp-exception-behavior=strict``, and disables contractions (FMA). All of the ``-ffast-math`` enablements are disabled. Enables ``STDC FENV_ACCESS``: by default ``FENV_ACCESS`` is disabled. This option setting behaves as though ``#pragma STDC FENV_ACESS ON`` appeared at the top of the source file.
1573 * ``fast`` Behaves identically to specifying both ``-ffast-math`` and ``ffp-contract=fast``
1575 Note: If your command line specifies multiple instances
1576 of the ``-ffp-model`` option, or if your command line option specifies
1577 ``-ffp-model`` and later on the command line selects a floating point
1578 option that has the effect of negating part of the ``ffp-model`` that
1579 has been selected, then the compiler will issue a diagnostic warning
1580 that the override has occurred.
1582 .. option:: -ffp-exception-behavior=<value>
1584 Specify the floating-point exception behavior.
1586 Valid values are: ``ignore``, ``maytrap``, and ``strict``.
1587 The default value is ``ignore``. Details:
1589 * ``ignore`` The compiler assumes that the exception status flags will not be read and that floating point exceptions will be masked.
1590 * ``maytrap`` The compiler avoids transformations that may raise exceptions that would not have been raised by the original code. Constant folding performed by the compiler is exempt from this option.
1591 * ``strict`` The compiler ensures that all transformations strictly preserve the floating point exception semantics of the original code.
1593 .. option:: -ffp-eval-method=<value>
1595 Specify the floating-point evaluation method for intermediate results within
1596 a single expression of the code.
1598 Valid values are: ``source``, ``double``, and ``extended``.
1599 For 64-bit targets, the default value is ``source``. For 32-bit x86 targets
1600 however, in the case of NETBSD 6.99.26 and under, the default value is
1601 ``double``; in the case of NETBSD greater than 6.99.26, with NoSSE, the
1602 default value is ``extended``, with SSE the default value is ``source``.
1605 * ``source`` The compiler uses the floating-point type declared in the source program as the evaluation method.
1606 * ``double`` The compiler uses ``double`` as the floating-point evaluation method for all float expressions of type that is narrower than ``double``.
1607 * ``extended`` The compiler uses ``long double`` as the floating-point evaluation method for all float expressions of type that is narrower than ``long double``.
1609 .. option:: -f[no-]protect-parens:
1611 This option pertains to floating-point types, complex types with
1612 floating-point components, and vectors of these types. Some arithmetic
1613 expression transformations that are mathematically correct and permissible
1614 according to the C and C++ language standards may be incorrect when dealing
1615 with floating-point types, such as reassociation and distribution. Further,
1616 the optimizer may ignore parentheses when computing arithmetic expressions
1617 in circumstances where the parenthesized and unparenthesized expression
1618 express the same mathematical value. For example (a+b)+c is the same
1619 mathematical value as a+(b+c), but the optimizer is free to evaluate the
1620 additions in any order regardless of the parentheses. When enabled, this
1621 option forces the optimizer to honor the order of operations with respect
1622 to parentheses in all circumstances.
1624 Note that floating-point contraction (option `-ffp-contract=`) is disabled
1625 when `-fprotect-parens` is enabled. Also note that in safe floating-point
1626 modes, such as `-ffp-model=precise` or `-ffp-model=strict`, this option
1627 has no effect because the optimizer is prohibited from making unsafe
1630 .. _FLT_EVAL_METHOD:
1632 A note about ``__FLT_EVAL_METHOD__``
1633 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1634 The ``__FLT_EVAL_METHOD__`` is not defined as a traditional macro, and so it
1635 will not appear when dumping preprocessor macros. Instead, the value
1636 ``__FLT_EVAL_METHOD__`` expands to is determined at the point of expansion
1637 either from the value set by the ``-ffp-eval-method`` command line option or
1638 from the target. This is because the ``__FLT_EVAL_METHOD__`` macro
1639 cannot expand to the correct evaluation method in the presence of a ``#pragma``
1640 which alters the evaluation method. An error is issued if
1641 ``__FLT_EVAL_METHOD__`` is expanded inside a scope modified by
1642 ``#pragma clang fp eval_method``.
1644 .. _fp-constant-eval:
1646 A note about Floating Point Constant Evaluation
1647 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1649 In C, the only place floating point operations are guaranteed to be evaluated
1650 during translation is in the initializers of variables of static storage
1651 duration, which are all notionally initialized before the program begins
1652 executing (and thus before a non-default floating point environment can be
1653 entered). But C++ has many more contexts where floating point constant
1654 evaluation occurs. Specifically: for static/thread-local variables,
1655 first try evaluating the initializer in a constant context, including in the
1656 constant floating point environment (just like in C), and then, if that fails,
1657 fall back to emitting runtime code to perform the initialization (which might
1658 in general be in a different floating point environment).
1660 Consider this example when compiled with ``-frounding-math``
1662 .. code-block:: console
1664 constexpr float func_01(float x, float y) {
1667 float V1 = func_01(1.0F, 0x0.000001p0F);
1669 The C++ rule is that initializers for static storage duration variables are
1670 first evaluated during translation (therefore, in the default rounding mode),
1671 and only evaluated at runtime (and therefore in the runtime rounding mode) if
1672 the compile-time evaluation fails. This is in line with the C rules;
1673 C11 F.8.5 says: *All computation for automatic initialization is done (as if)
1674 at execution time; thus, it is affected by any operative modes and raises
1675 floating-point exceptions as required by IEC 60559 (provided the state for the
1676 FENV_ACCESS pragma is ‘‘on’’). All computation for initialization of objects
1677 that have static or thread storage duration is done (as if) at translation
1678 time.* C++ generalizes this by adding another phase of initialization
1679 (at runtime) if the translation-time initialization fails, but the
1680 translation-time evaluation of the initializer of succeeds, it will be
1681 treated as a constant initializer.
1684 .. _controlling-code-generation:
1686 Controlling Code Generation
1687 ---------------------------
1689 Clang provides a number of ways to control code generation. The options
1692 **-f[no-]sanitize=check1,check2,...**
1693 Turn on runtime checks for various forms of undefined or suspicious
1696 This option controls whether Clang adds runtime checks for various
1697 forms of undefined or suspicious behavior, and is disabled by
1698 default. If a check fails, a diagnostic message is produced at
1699 runtime explaining the problem. The main checks are:
1701 - .. _opt_fsanitize_address:
1703 ``-fsanitize=address``:
1704 :doc:`AddressSanitizer`, a memory error
1706 - .. _opt_fsanitize_thread:
1708 ``-fsanitize=thread``: :doc:`ThreadSanitizer`, a data race detector.
1709 - .. _opt_fsanitize_memory:
1711 ``-fsanitize=memory``: :doc:`MemorySanitizer`,
1712 a detector of uninitialized reads. Requires instrumentation of all
1714 - .. _opt_fsanitize_undefined:
1716 ``-fsanitize=undefined``: :doc:`UndefinedBehaviorSanitizer`,
1717 a fast and compatible undefined behavior checker.
1719 - ``-fsanitize=dataflow``: :doc:`DataFlowSanitizer`, a general data
1721 - ``-fsanitize=cfi``: :doc:`control flow integrity <ControlFlowIntegrity>`
1722 checks. Requires ``-flto``.
1723 - ``-fsanitize=safe-stack``: :doc:`safe stack <SafeStack>`
1724 protection against stack-based memory corruption errors.
1726 There are more fine-grained checks available: see
1727 the :ref:`list <ubsan-checks>` of specific kinds of
1728 undefined behavior that can be detected and the :ref:`list <cfi-schemes>`
1729 of control flow integrity schemes.
1731 The ``-fsanitize=`` argument must also be provided when linking, in
1732 order to link to the appropriate runtime library.
1734 It is not possible to combine more than one of the ``-fsanitize=address``,
1735 ``-fsanitize=thread``, and ``-fsanitize=memory`` checkers in the same
1738 **-f[no-]sanitize-recover=check1,check2,...**
1740 **-f[no-]sanitize-recover[=all]**
1742 Controls which checks enabled by ``-fsanitize=`` flag are non-fatal.
1743 If the check is fatal, program will halt after the first error
1744 of this kind is detected and error report is printed.
1746 By default, non-fatal checks are those enabled by
1747 :doc:`UndefinedBehaviorSanitizer`,
1748 except for ``-fsanitize=return`` and ``-fsanitize=unreachable``. Some
1749 sanitizers may not support recovery (or not support it by default
1750 e.g. :doc:`AddressSanitizer`), and always crash the program after the issue
1753 Note that the ``-fsanitize-trap`` flag has precedence over this flag.
1754 This means that if a check has been configured to trap elsewhere on the
1755 command line, or if the check traps by default, this flag will not have
1756 any effect unless that sanitizer's trapping behavior is disabled with
1757 ``-fno-sanitize-trap``.
1759 For example, if a command line contains the flags ``-fsanitize=undefined
1760 -fsanitize-trap=undefined``, the flag ``-fsanitize-recover=alignment``
1761 will have no effect on its own; it will need to be accompanied by
1762 ``-fno-sanitize-trap=alignment``.
1764 **-f[no-]sanitize-trap=check1,check2,...**
1766 **-f[no-]sanitize-trap[=all]**
1768 Controls which checks enabled by the ``-fsanitize=`` flag trap. This
1769 option is intended for use in cases where the sanitizer runtime cannot
1770 be used (for instance, when building libc or a kernel module), or where
1771 the binary size increase caused by the sanitizer runtime is a concern.
1773 This flag is only compatible with :doc:`control flow integrity
1774 <ControlFlowIntegrity>` schemes and :doc:`UndefinedBehaviorSanitizer`
1775 checks other than ``vptr``.
1777 This flag is enabled by default for sanitizers in the ``cfi`` group.
1779 .. option:: -fsanitize-ignorelist=/path/to/ignorelist/file
1781 Disable or modify sanitizer checks for objects (source files, functions,
1782 variables, types) listed in the file. See
1783 :doc:`SanitizerSpecialCaseList` for file format description.
1785 .. option:: -fno-sanitize-ignorelist
1787 Don't use ignorelist file, if it was specified earlier in the command line.
1789 **-f[no-]sanitize-coverage=[type,features,...]**
1791 Enable simple code coverage in addition to certain sanitizers.
1792 See :doc:`SanitizerCoverage` for more details.
1794 **-f[no-]sanitize-address-outline-instrumentation**
1796 Controls how address sanitizer code is generated. If enabled will always use
1797 a function call instead of inlining the code. Turning this option on could
1798 reduce the binary size, but might result in a worse run-time performance.
1800 See :doc: `AddressSanitizer` for more details.
1802 **-f[no-]sanitize-stats**
1804 Enable simple statistics gathering for the enabled sanitizers.
1805 See :doc:`SanitizerStats` for more details.
1807 .. option:: -fsanitize-undefined-trap-on-error
1809 Deprecated alias for ``-fsanitize-trap=undefined``.
1811 .. option:: -fsanitize-cfi-cross-dso
1813 Enable cross-DSO control flow integrity checks. This flag modifies
1814 the behavior of sanitizers in the ``cfi`` group to allow checking
1815 of cross-DSO virtual and indirect calls.
1817 .. option:: -fsanitize-cfi-icall-generalize-pointers
1819 Generalize pointers in return and argument types in function type signatures
1820 checked by Control Flow Integrity indirect call checking. See
1821 :doc:`ControlFlowIntegrity` for more details.
1823 .. option:: -fstrict-vtable-pointers
1825 Enable optimizations based on the strict rules for overwriting polymorphic
1826 C++ objects, i.e. the vptr is invariant during an object's lifetime.
1827 This enables better devirtualization. Turned off by default, because it is
1830 .. option:: -fwhole-program-vtables
1832 Enable whole-program vtable optimizations, such as single-implementation
1833 devirtualization and virtual constant propagation, for classes with
1834 :doc:`hidden LTO visibility <LTOVisibility>`. Requires ``-flto``.
1836 .. option:: -fforce-emit-vtables
1838 In order to improve devirtualization, forces emitting of vtables even in
1839 modules where it isn't necessary. It causes more inline virtual functions
1842 .. option:: -fno-assume-sane-operator-new
1844 Don't assume that the C++'s new operator is sane.
1846 This option tells the compiler to do not assume that C++'s global
1847 new operator will always return a pointer that does not alias any
1848 other pointer when the function returns.
1850 .. option:: -ftrap-function=[name]
1852 Instruct code generator to emit a function call to the specified
1853 function name for ``__builtin_trap()``.
1855 LLVM code generator translates ``__builtin_trap()`` to a trap
1856 instruction if it is supported by the target ISA. Otherwise, the
1857 builtin is translated into a call to ``abort``. If this option is
1858 set, then the code generator will always lower the builtin to a call
1859 to the specified function regardless of whether the target ISA has a
1860 trap instruction. This option is useful for environments (e.g.
1861 deeply embedded) where a trap cannot be properly handled, or when
1862 some custom behavior is desired.
1864 .. option:: -ftls-model=[model]
1866 Select which TLS model to use.
1868 Valid values are: ``global-dynamic``, ``local-dynamic``,
1869 ``initial-exec`` and ``local-exec``. The default value is
1870 ``global-dynamic``. The compiler may use a different model if the
1871 selected model is not supported by the target, or if a more
1872 efficient model can be used. The TLS model can be overridden per
1873 variable using the ``tls_model`` attribute.
1875 .. option:: -femulated-tls
1877 Select emulated TLS model, which overrides all -ftls-model choices.
1879 In emulated TLS mode, all access to TLS variables are converted to
1880 calls to __emutls_get_address in the runtime library.
1882 .. option:: -mhwdiv=[values]
1884 Select the ARM modes (arm or thumb) that support hardware division
1887 Valid values are: ``arm``, ``thumb`` and ``arm,thumb``.
1888 This option is used to indicate which mode (arm or thumb) supports
1889 hardware division instructions. This only applies to the ARM
1892 .. option:: -m[no-]crc
1894 Enable or disable CRC instructions.
1896 This option is used to indicate whether CRC instructions are to
1897 be generated. This only applies to the ARM architecture.
1899 CRC instructions are enabled by default on ARMv8.
1901 .. option:: -mgeneral-regs-only
1903 Generate code which only uses the general purpose registers.
1905 This option restricts the generated code to use general registers
1906 only. This only applies to the AArch64 architecture.
1908 .. option:: -mcompact-branches=[values]
1910 Control the usage of compact branches for MIPSR6.
1912 Valid values are: ``never``, ``optimal`` and ``always``.
1913 The default value is ``optimal`` which generates compact branches
1914 when a delay slot cannot be filled. ``never`` disables the usage of
1915 compact branches and ``always`` generates compact branches whenever
1918 **-f[no-]max-type-align=[number]**
1919 Instruct the code generator to not enforce a higher alignment than the given
1920 number (of bytes) when accessing memory via an opaque pointer or reference.
1921 This cap is ignored when directly accessing a variable or when the pointee
1922 type has an explicit “aligned” attribute.
1924 The value should usually be determined by the properties of the system allocator.
1925 Some builtin types, especially vector types, have very high natural alignments;
1926 when working with values of those types, Clang usually wants to use instructions
1927 that take advantage of that alignment. However, many system allocators do
1928 not promise to return memory that is more than 8-byte or 16-byte-aligned. Use
1929 this option to limit the alignment that the compiler can assume for an arbitrary
1930 pointer, which may point onto the heap.
1932 This option does not affect the ABI alignment of types; the layout of structs and
1933 unions and the value returned by the alignof operator remain the same.
1935 This option can be overridden on a case-by-case basis by putting an explicit
1936 “aligned” alignment on a struct, union, or typedef. For example:
1938 .. code-block:: console
1940 #include <immintrin.h>
1941 // Make an aligned typedef of the AVX-512 16-int vector type.
1942 typedef __v16si __aligned_v16si __attribute__((aligned(64)));
1944 void initialize_vector(__aligned_v16si *v) {
1945 // The compiler may assume that ‘v’ is 64-byte aligned, regardless of the
1946 // value of -fmax-type-align.
1949 .. option:: -faddrsig, -fno-addrsig
1951 Controls whether Clang emits an address-significance table into the object
1952 file. Address-significance tables allow linkers to implement `safe ICF
1953 <https://research.google.com/pubs/archive/36912.pdf>`_ without the false
1954 positives that can result from other implementation techniques such as
1955 relocation scanning. Address-significance tables are enabled by default
1956 on ELF targets when using the integrated assembler. This flag currently
1957 only has an effect on ELF targets.
1959 **-f[no]-unique-internal-linkage-names**
1961 Controls whether Clang emits a unique (best-effort) symbol name for internal
1962 linkage symbols. When this option is set, compiler hashes the main source
1963 file path from the command line and appends it to all internal symbols. If a
1964 program contains multiple objects compiled with the same command-line source
1965 file path, the symbols are not guaranteed to be unique. This option is
1966 particularly useful in attributing profile information to the correct
1967 function when multiple functions with the same private linkage name exist
1970 It should be noted that this option cannot guarantee uniqueness and the
1971 following is an example where it is not unique when two modules contain
1972 symbols with the same private linkage name:
1974 .. code-block:: console
1976 $ cd $P/foo && clang -c -funique-internal-linkage-names name_conflict.c
1977 $ cd $P/bar && clang -c -funique-internal-linkage-names name_conflict.c
1978 $ cd $P && clang foo/name_conflict.o && bar/name_conflict.o
1980 **-fbasic-block-sections=[labels, all, list=<arg>, none]**
1982 Controls how Clang emits text sections for basic blocks. With values ``all``
1983 and ``list=<arg>``, each basic block or a subset of basic blocks can be placed
1984 in its own unique section. With the "labels" value, normal text sections are
1985 emitted, but a ``.bb_addr_map`` section is emitted which includes address
1986 offsets for each basic block in the program, relative to the parent function
1989 With the ``list=<arg>`` option, a file containing the subset of basic blocks
1990 that need to placed in unique sections can be specified. The format of the
1991 file is as follows. For example, ``list=spec.txt`` where ``spec.txt`` is the
2000 will place the machine basic block with ``id 2`` in function ``foo`` in a
2001 unique section. It will also place all basic blocks of functions ``bar``
2004 Further, section clusters can also be specified using the ``list=<arg>``
2005 option. For example, ``list=spec.txt`` where ``spec.txt`` contains:
2013 will create two unique sections for function ``foo`` with the first
2014 containing the odd numbered basic blocks and the second containing the
2015 even numbered basic blocks.
2017 Basic block sections allow the linker to reorder basic blocks and enables
2018 link-time optimizations like whole program inter-procedural basic block
2021 Profile Guided Optimization
2022 ---------------------------
2024 Profile information enables better optimization. For example, knowing that a
2025 branch is taken very frequently helps the compiler make better decisions when
2026 ordering basic blocks. Knowing that a function ``foo`` is called more
2027 frequently than another function ``bar`` helps the inliner. Optimization
2028 levels ``-O2`` and above are recommended for use of profile guided optimization.
2030 Clang supports profile guided optimization with two different kinds of
2031 profiling. A sampling profiler can generate a profile with very low runtime
2032 overhead, or you can build an instrumented version of the code that collects
2033 more detailed profile information. Both kinds of profiles can provide execution
2034 counts for instructions in the code and information on branches taken and
2035 function invocation.
2037 Regardless of which kind of profiling you use, be careful to collect profiles
2038 by running your code with inputs that are representative of the typical
2039 behavior. Code that is not exercised in the profile will be optimized as if it
2040 is unimportant, and the compiler may make poor optimization choices for code
2041 that is disproportionately used while profiling.
2043 Differences Between Sampling and Instrumentation
2044 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2046 Although both techniques are used for similar purposes, there are important
2047 differences between the two:
2049 1. Profile data generated with one cannot be used by the other, and there is no
2050 conversion tool that can convert one to the other. So, a profile generated
2051 via ``-fprofile-instr-generate`` must be used with ``-fprofile-instr-use``.
2052 Similarly, sampling profiles generated by external profilers must be
2053 converted and used with ``-fprofile-sample-use``.
2055 2. Instrumentation profile data can be used for code coverage analysis and
2058 3. Sampling profiles can only be used for optimization. They cannot be used for
2059 code coverage analysis. Although it would be technically possible to use
2060 sampling profiles for code coverage, sample-based profiles are too
2061 coarse-grained for code coverage purposes; it would yield poor results.
2063 4. Sampling profiles must be generated by an external tool. The profile
2064 generated by that tool must then be converted into a format that can be read
2065 by LLVM. The section on sampling profilers describes one of the supported
2066 sampling profile formats.
2069 Using Sampling Profilers
2070 ^^^^^^^^^^^^^^^^^^^^^^^^
2072 Sampling profilers are used to collect runtime information, such as
2073 hardware counters, while your application executes. They are typically
2074 very efficient and do not incur a large runtime overhead. The
2075 sample data collected by the profiler can be used during compilation
2076 to determine what the most executed areas of the code are.
2078 Using the data from a sample profiler requires some changes in the way
2079 a program is built. Before the compiler can use profiling information,
2080 the code needs to execute under the profiler. The following is the
2081 usual build cycle when using sample profilers for optimization:
2083 1. Build the code with source line table information. You can use all the
2084 usual build flags that you always build your application with. The only
2085 requirement is that you add ``-gline-tables-only`` or ``-g`` to the
2086 command line. This is important for the profiler to be able to map
2087 instructions back to source line locations.
2089 .. code-block:: console
2091 $ clang++ -O2 -gline-tables-only code.cc -o code
2093 2. Run the executable under a sampling profiler. The specific profiler
2094 you use does not really matter, as long as its output can be converted
2095 into the format that the LLVM optimizer understands. Currently, there
2096 exists a conversion tool for the Linux Perf profiler
2097 (https://perf.wiki.kernel.org/), so these examples assume that you
2098 are using Linux Perf to profile your code.
2100 .. code-block:: console
2102 $ perf record -b ./code
2104 Note the use of the ``-b`` flag. This tells Perf to use the Last Branch
2105 Record (LBR) to record call chains. While this is not strictly required,
2106 it provides better call information, which improves the accuracy of
2109 3. Convert the collected profile data to LLVM's sample profile format.
2110 This is currently supported via the AutoFDO converter ``create_llvm_prof``.
2111 It is available at https://github.com/google/autofdo. Once built and
2112 installed, you can convert the ``perf.data`` file to LLVM using
2115 .. code-block:: console
2117 $ create_llvm_prof --binary=./code --out=code.prof
2119 This will read ``perf.data`` and the binary file ``./code`` and emit
2120 the profile data in ``code.prof``. Note that if you ran ``perf``
2121 without the ``-b`` flag, you need to use ``--use_lbr=false`` when
2122 calling ``create_llvm_prof``.
2124 4. Build the code again using the collected profile. This step feeds
2125 the profile back to the optimizers. This should result in a binary
2126 that executes faster than the original one. Note that you are not
2127 required to build the code with the exact same arguments that you
2128 used in the first step. The only requirement is that you build the code
2129 with ``-gline-tables-only`` and ``-fprofile-sample-use``.
2131 .. code-block:: console
2133 $ clang++ -O2 -gline-tables-only -fprofile-sample-use=code.prof code.cc -o code
2136 Sample Profile Formats
2137 """"""""""""""""""""""
2139 Since external profilers generate profile data in a variety of custom formats,
2140 the data generated by the profiler must be converted into a format that can be
2141 read by the backend. LLVM supports three different sample profile formats:
2143 1. ASCII text. This is the easiest one to generate. The file is divided into
2144 sections, which correspond to each of the functions with profile
2145 information. The format is described below. It can also be generated from
2146 the binary or gcov formats using the ``llvm-profdata`` tool.
2148 2. Binary encoding. This uses a more efficient encoding that yields smaller
2149 profile files. This is the format generated by the ``create_llvm_prof`` tool
2150 in https://github.com/google/autofdo.
2152 3. GCC encoding. This is based on the gcov format, which is accepted by GCC. It
2153 is only interesting in environments where GCC and Clang co-exist. This
2154 encoding is only generated by the ``create_gcov`` tool in
2155 https://github.com/google/autofdo. It can be read by LLVM and
2156 ``llvm-profdata``, but it cannot be generated by either.
2158 If you are using Linux Perf to generate sampling profiles, you can use the
2159 conversion tool ``create_llvm_prof`` described in the previous section.
2160 Otherwise, you will need to write a conversion tool that converts your
2161 profiler's native format into one of these three.
2164 Sample Profile Text Format
2165 """"""""""""""""""""""""""
2167 This section describes the ASCII text format for sampling profiles. It is,
2168 arguably, the easiest one to generate. If you are interested in generating any
2169 of the other two, consult the ``ProfileData`` library in LLVM's source tree
2170 (specifically, ``include/llvm/ProfileData/SampleProfReader.h``).
2172 .. code-block:: console
2174 function1:total_samples:total_head_samples
2175 offset1[.discriminator]: number_of_samples [fn1:num fn2:num ... ]
2176 offset2[.discriminator]: number_of_samples [fn3:num fn4:num ... ]
2178 offsetN[.discriminator]: number_of_samples [fn5:num fn6:num ... ]
2179 offsetA[.discriminator]: fnA:num_of_total_samples
2180 offsetA1[.discriminator]: number_of_samples [fn7:num fn8:num ... ]
2181 offsetA1[.discriminator]: number_of_samples [fn9:num fn10:num ... ]
2182 offsetB[.discriminator]: fnB:num_of_total_samples
2183 offsetB1[.discriminator]: number_of_samples [fn11:num fn12:num ... ]
2185 This is a nested tree in which the indentation represents the nesting level
2186 of the inline stack. There are no blank lines in the file. And the spacing
2187 within a single line is fixed. Additional spaces will result in an error
2188 while reading the file.
2190 Any line starting with the '#' character is completely ignored.
2192 Inlined calls are represented with indentation. The Inline stack is a
2193 stack of source locations in which the top of the stack represents the
2194 leaf function, and the bottom of the stack represents the actual
2195 symbol to which the instruction belongs.
2197 Function names must be mangled in order for the profile loader to
2198 match them in the current translation unit. The two numbers in the
2199 function header specify how many total samples were accumulated in the
2200 function (first number), and the total number of samples accumulated
2201 in the prologue of the function (second number). This head sample
2202 count provides an indicator of how frequently the function is invoked.
2204 There are two types of lines in the function body.
2206 - Sampled line represents the profile information of a source location.
2207 ``offsetN[.discriminator]: number_of_samples [fn5:num fn6:num ... ]``
2209 - Callsite line represents the profile information of an inlined callsite.
2210 ``offsetA[.discriminator]: fnA:num_of_total_samples``
2212 Each sampled line may contain several items. Some are optional (marked
2215 a. Source line offset. This number represents the line number
2216 in the function where the sample was collected. The line number is
2217 always relative to the line where symbol of the function is
2218 defined. So, if the function has its header at line 280, the offset
2219 13 is at line 293 in the file.
2221 Note that this offset should never be a negative number. This could
2222 happen in cases like macros. The debug machinery will register the
2223 line number at the point of macro expansion. So, if the macro was
2224 expanded in a line before the start of the function, the profile
2225 converter should emit a 0 as the offset (this means that the optimizers
2226 will not be able to associate a meaningful weight to the instructions
2229 b. [OPTIONAL] Discriminator. This is used if the sampled program
2230 was compiled with DWARF discriminator support
2231 (http://wiki.dwarfstd.org/index.php?title=Path_Discriminators).
2232 DWARF discriminators are unsigned integer values that allow the
2233 compiler to distinguish between multiple execution paths on the
2234 same source line location.
2236 For example, consider the line of code ``if (cond) foo(); else bar();``.
2237 If the predicate ``cond`` is true 80% of the time, then the edge
2238 into function ``foo`` should be considered to be taken most of the
2239 time. But both calls to ``foo`` and ``bar`` are at the same source
2240 line, so a sample count at that line is not sufficient. The
2241 compiler needs to know which part of that line is taken more
2244 This is what discriminators provide. In this case, the calls to
2245 ``foo`` and ``bar`` will be at the same line, but will have
2246 different discriminator values. This allows the compiler to correctly
2247 set edge weights into ``foo`` and ``bar``.
2249 c. Number of samples. This is an integer quantity representing the
2250 number of samples collected by the profiler at this source
2253 d. [OPTIONAL] Potential call targets and samples. If present, this
2254 line contains a call instruction. This models both direct and
2255 number of samples. For example,
2257 .. code-block:: console
2259 130: 7 foo:3 bar:2 baz:7
2261 The above means that at relative line offset 130 there is a call
2262 instruction that calls one of ``foo()``, ``bar()`` and ``baz()``,
2263 with ``baz()`` being the relatively more frequently called target.
2265 As an example, consider a program with the call chain ``main -> foo -> bar``.
2266 When built with optimizations enabled, the compiler may inline the
2267 calls to ``bar`` and ``foo`` inside ``main``. The generated profile
2268 could then be something like this:
2270 .. code-block:: console
2278 This profile indicates that there were a total of 35,504 samples
2279 collected in main. All of those were at line 1 (the call to ``foo``).
2280 Of those, 31,977 were spent inside the body of ``bar``. The last line
2281 of the profile (``2: 0``) corresponds to line 2 inside ``main``. No
2282 samples were collected there.
2284 Profiling with Instrumentation
2285 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2287 Clang also supports profiling via instrumentation. This requires building a
2288 special instrumented version of the code and has some runtime
2289 overhead during the profiling, but it provides more detailed results than a
2290 sampling profiler. It also provides reproducible results, at least to the
2291 extent that the code behaves consistently across runs.
2293 Here are the steps for using profile guided optimization with
2296 1. Build an instrumented version of the code by compiling and linking with the
2297 ``-fprofile-instr-generate`` option.
2299 .. code-block:: console
2301 $ clang++ -O2 -fprofile-instr-generate code.cc -o code
2303 2. Run the instrumented executable with inputs that reflect the typical usage.
2304 By default, the profile data will be written to a ``default.profraw`` file
2305 in the current directory. You can override that default by using option
2306 ``-fprofile-instr-generate=`` or by setting the ``LLVM_PROFILE_FILE``
2307 environment variable to specify an alternate file. If non-default file name
2308 is specified by both the environment variable and the command line option,
2309 the environment variable takes precedence. The file name pattern specified
2310 can include different modifiers: ``%p``, ``%h``, and ``%m``.
2312 Any instance of ``%p`` in that file name will be replaced by the process
2313 ID, so that you can easily distinguish the profile output from multiple
2316 .. code-block:: console
2318 $ LLVM_PROFILE_FILE="code-%p.profraw" ./code
2320 The modifier ``%h`` can be used in scenarios where the same instrumented
2321 binary is run in multiple different host machines dumping profile data
2322 to a shared network based storage. The ``%h`` specifier will be substituted
2323 with the hostname so that profiles collected from different hosts do not
2326 While the use of ``%p`` specifier can reduce the likelihood for the profiles
2327 dumped from different processes to clobber each other, such clobbering can still
2328 happen because of the ``pid`` re-use by the OS. Another side-effect of using
2329 ``%p`` is that the storage requirement for raw profile data files is greatly
2330 increased. To avoid issues like this, the ``%m`` specifier can used in the profile
2331 name. When this specifier is used, the profiler runtime will substitute ``%m``
2332 with a unique integer identifier associated with the instrumented binary. Additionally,
2333 multiple raw profiles dumped from different processes that share a file system (can be
2334 on different hosts) will be automatically merged by the profiler runtime during the
2335 dumping. If the program links in multiple instrumented shared libraries, each library
2336 will dump the profile data into its own profile data file (with its unique integer
2337 id embedded in the profile name). Note that the merging enabled by ``%m`` is for raw
2338 profile data generated by profiler runtime. The resulting merged "raw" profile data
2339 file still needs to be converted to a different format expected by the compiler (
2342 .. code-block:: console
2344 $ LLVM_PROFILE_FILE="code-%m.profraw" ./code
2347 3. Combine profiles from multiple runs and convert the "raw" profile format to
2348 the input expected by clang. Use the ``merge`` command of the
2349 ``llvm-profdata`` tool to do this.
2351 .. code-block:: console
2353 $ llvm-profdata merge -output=code.profdata code-*.profraw
2355 Note that this step is necessary even when there is only one "raw" profile,
2356 since the merge operation also changes the file format.
2358 4. Build the code again using the ``-fprofile-instr-use`` option to specify the
2359 collected profile data.
2361 .. code-block:: console
2363 $ clang++ -O2 -fprofile-instr-use=code.profdata code.cc -o code
2365 You can repeat step 4 as often as you like without regenerating the
2366 profile. As you make changes to your code, clang may no longer be able to
2367 use the profile data. It will warn you when this happens.
2369 Profile generation using an alternative instrumentation method can be
2370 controlled by the GCC-compatible flags ``-fprofile-generate`` and
2371 ``-fprofile-use``. Although these flags are semantically equivalent to
2372 their GCC counterparts, they *do not* handle GCC-compatible profiles.
2373 They are only meant to implement GCC's semantics with respect to
2374 profile creation and use. Flag ``-fcs-profile-generate`` also instruments
2375 programs using the same instrumentation method as ``-fprofile-generate``.
2377 .. option:: -fprofile-generate[=<dirname>]
2379 The ``-fprofile-generate`` and ``-fprofile-generate=`` flags will use
2380 an alternative instrumentation method for profile generation. When
2381 given a directory name, it generates the profile file
2382 ``default_%m.profraw`` in the directory named ``dirname`` if specified.
2383 If ``dirname`` does not exist, it will be created at runtime. ``%m`` specifier
2384 will be substituted with a unique id documented in step 2 above. In other words,
2385 with ``-fprofile-generate[=<dirname>]`` option, the "raw" profile data automatic
2386 merging is turned on by default, so there will no longer any risk of profile
2387 clobbering from different running processes. For example,
2389 .. code-block:: console
2391 $ clang++ -O2 -fprofile-generate=yyy/zzz code.cc -o code
2393 When ``code`` is executed, the profile will be written to the file
2394 ``yyy/zzz/default_xxxx.profraw``.
2396 To generate the profile data file with the compiler readable format, the
2397 ``llvm-profdata`` tool can be used with the profile directory as the input:
2399 .. code-block:: console
2401 $ llvm-profdata merge -output=code.profdata yyy/zzz/
2403 If the user wants to turn off the auto-merging feature, or simply override the
2404 the profile dumping path specified at command line, the environment variable
2405 ``LLVM_PROFILE_FILE`` can still be used to override
2406 the directory and filename for the profile file at runtime.
2408 .. option:: -fcs-profile-generate[=<dirname>]
2410 The ``-fcs-profile-generate`` and ``-fcs-profile-generate=`` flags will use
2411 the same instrumentation method, and generate the same profile as in the
2412 ``-fprofile-generate`` and ``-fprofile-generate=`` flags. The difference is
2413 that the instrumentation is performed after inlining so that the resulted
2414 profile has a better context sensitive information. They cannot be used
2415 together with ``-fprofile-generate`` and ``-fprofile-generate=`` flags.
2416 They are typically used in conjunction with ``-fprofile-use`` flag.
2417 The profile generated by ``-fcs-profile-generate`` and ``-fprofile-generate``
2418 can be merged by llvm-profdata. A use example:
2420 .. code-block:: console
2422 $ clang++ -O2 -fprofile-generate=yyy/zzz code.cc -o code
2424 $ llvm-profdata merge -output=code.profdata yyy/zzz/
2426 The first few steps are the same as that in ``-fprofile-generate``
2427 compilation. Then perform a second round of instrumentation.
2429 .. code-block:: console
2431 $ clang++ -O2 -fprofile-use=code.profdata -fcs-profile-generate=sss/ttt \
2434 $ llvm-profdata merge -output=cs_code.profdata sss/ttt code.profdata
2436 The resulted ``cs_code.prodata`` combines ``code.profdata`` and the profile
2437 generated from binary ``cs_code``. Profile ``cs_code.profata`` can be used by
2438 ``-fprofile-use`` compilation.
2440 .. code-block:: console
2442 $ clang++ -O2 -fprofile-use=cs_code.profdata
2444 The above command will read both profiles to the compiler at the identical
2445 point of instrumentations.
2447 .. option:: -fprofile-use[=<pathname>]
2449 Without any other arguments, ``-fprofile-use`` behaves identically to
2450 ``-fprofile-instr-use``. Otherwise, if ``pathname`` is the full path to a
2451 profile file, it reads from that file. If ``pathname`` is a directory name,
2452 it reads from ``pathname/default.profdata``.
2454 .. option:: -fprofile-update[=<method>]
2456 Unless ``-fsanitize=thread`` is specified, the default is ``single``, which
2457 uses non-atomic increments. The counters can be inaccurate under thread
2458 contention. ``atomic`` uses atomic increments which is accurate but has
2459 overhead. ``prefer-atomic`` will be transformed to ``atomic`` when supported
2460 by the target, or ``single`` otherwise.
2462 This option currently works with ``-fprofile-arcs`` and ``-fprofile-instr-generate``,
2463 but not with ``-fprofile-generate``.
2465 Disabling Instrumentation
2466 ^^^^^^^^^^^^^^^^^^^^^^^^^
2468 In certain situations, it may be useful to disable profile generation or use
2469 for specific files in a build, without affecting the main compilation flags
2470 used for the other files in the project.
2472 In these cases, you can use the flag ``-fno-profile-instr-generate`` (or
2473 ``-fno-profile-generate``) to disable profile generation, and
2474 ``-fno-profile-instr-use`` (or ``-fno-profile-use``) to disable profile use.
2476 Note that these flags should appear after the corresponding profile
2477 flags to have an effect.
2481 When none of the translation units inside a binary is instrumented, in the
2482 case of Fuchsia the profile runtime will not be linked into the binary and
2483 no profile will be produced, while on other platforms the profile runtime
2484 will be linked and profile will be produced but there will not be any
2487 Instrumenting only selected files or functions
2488 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2490 Sometimes it's useful to only instrument certain files or functions. For
2491 example in automated testing infrastructure, it may be desirable to only
2492 instrument files or functions that were modified by a patch to reduce the
2493 overhead of instrumenting a full system.
2495 This can be done using the ``-fprofile-list`` option.
2497 .. option:: -fprofile-list=<pathname>
2499 This option can be used to apply profile instrumentation only to selected
2500 files or functions. ``pathname`` should point to a file in the
2501 :doc:`SanitizerSpecialCaseList` format which selects which files and
2502 functions to instrument.
2504 .. code-block:: console
2506 $ clang++ -O2 -fprofile-instr-generate -fprofile-list=fun.list code.cc -o code
2508 The option can be specified multiple times to pass multiple files.
2510 .. code-block:: console
2512 $ clang++ -O2 -fprofile-instr-generate -fcoverage-mapping -fprofile-list=fun.list -fprofile-list=code.list code.cc -o code
2514 Supported sections are ``[clang]``, ``[llvm]``, and ``[csllvm]`` representing
2515 clang PGO, IRPGO, and CSIRPGO, respectively. Supported prefixes are ``function``
2516 and ``source``. Supported categories are ``allow``, ``skip``, and ``forbid``.
2517 ``skip`` adds the ``skipprofile`` attribute while ``forbid`` adds the
2518 ``noprofile`` attribute to the appropriate function. Use
2519 ``default:<allow|skip|forbid>`` to specify the default category.
2521 .. code-block:: console
2524 # The following cases are for clang instrumentation.
2527 # We might not want to profile functions that are inlined in many places.
2528 function:inlinedLots=skip
2530 # We want to forbid profiling where it might be dangerous.
2531 source:lib/unsafe/*.cc=forbid
2533 # Otherwise we allow profiling.
2538 An older format is also supported, but it is only able to add the
2539 ``noprofile`` attribute.
2540 To filter individual functions or entire source files use ``fun:<name>`` or
2541 ``src:<file>`` respectively. To exclude a function or a source file, use
2542 ``!fun:<name>`` or ``!src:<file>`` respectively. The format also supports
2543 wildcard expansion. The compiler generated functions are assumed to be located
2544 in the main source file. It is also possible to restrict the filter to a
2545 particular instrumentation type by using a named section.
2547 .. code-block:: none
2549 # all functions whose name starts with foo will be instrumented.
2552 # except for foo1 which will be excluded from instrumentation.
2555 # every function in path/to/foo.cc will be instrumented.
2558 # bar will be instrumented only when using backend instrumentation.
2559 # Recognized section names are clang, llvm and csllvm.
2563 When the file contains only excludes, all files and functions except for the
2564 excluded ones will be instrumented. Otherwise, only the files and functions
2565 specified will be instrumented.
2567 Instrument function groups
2568 ^^^^^^^^^^^^^^^^^^^^^^^^^^
2570 Sometimes it is desirable to minimize the size overhead of instrumented
2571 binaries. One way to do this is to partition functions into groups and only
2572 instrument functions in a specified group. This can be done using the
2573 `-fprofile-function-groups` and `-fprofile-selected-function-group` options.
2575 .. option:: -fprofile-function-groups=<N>, -fprofile-selected-function-group=<i>
2577 The following uses 3 groups
2579 .. code-block:: console
2581 $ clang++ -Oz -fprofile-generate=group_0/ -fprofile-function-groups=3 -fprofile-selected-function-group=0 code.cc -o code.0
2582 $ clang++ -Oz -fprofile-generate=group_1/ -fprofile-function-groups=3 -fprofile-selected-function-group=1 code.cc -o code.1
2583 $ clang++ -Oz -fprofile-generate=group_2/ -fprofile-function-groups=3 -fprofile-selected-function-group=2 code.cc -o code.2
2585 After collecting raw profiles from the three binaries, they can be merged into
2586 a single profile like normal.
2588 .. code-block:: console
2590 $ llvm-profdata merge -output=code.profdata group_*/*.profraw
2596 When the program is compiled after a change that affects many symbol names,
2597 pre-existing profile data may no longer match the program. For example:
2599 * switching from libstdc++ to libc++ will result in the mangled names of all
2600 functions taking standard library types to change
2601 * renaming a widely-used type in C++ will result in the mangled names of all
2602 functions that have parameters involving that type to change
2603 * moving from a 32-bit compilation to a 64-bit compilation may change the
2604 underlying type of ``size_t`` and similar types, resulting in changes to
2607 Clang allows use of a profile remapping file to specify that such differences
2608 in mangled names should be ignored when matching the profile data against the
2611 .. option:: -fprofile-remapping-file=<file>
2613 Specifies a file containing profile remapping information, that will be
2614 used to match mangled names in the profile data to mangled names in the
2617 The profile remapping file is a text file containing lines of the form
2619 .. code-block:: text
2621 fragmentkind fragment1 fragment2
2623 where ``fragmentkind`` is one of ``name``, ``type``, or ``encoding``,
2624 indicating whether the following mangled name fragments are
2625 <`name <https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangle.name>`_>s,
2626 <`type <https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangle.type>`_>s, or
2627 <`encoding <https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangle.encoding>`_>s,
2629 Blank lines and lines starting with ``#`` are ignored.
2631 For convenience, built-in <substitution>s such as ``St`` and ``Ss``
2632 are accepted as <name>s (even though they technically are not <name>s).
2634 For example, to specify that ``absl::string_view`` and ``std::string_view``
2635 should be treated as equivalent when matching profile data, the following
2636 remapping file could be used:
2638 .. code-block:: text
2640 # absl::string_view is considered equivalent to std::string_view
2641 type N4absl11string_viewE St17basic_string_viewIcSt11char_traitsIcEE
2643 # std:: might be std::__1:: in libc++ or std::__cxx11:: in libstdc++
2645 name 3std St7__cxx11
2647 Matching profile data using a profile remapping file is supported on a
2648 best-effort basis. For example, information regarding indirect call targets is
2649 currently not remapped. For best results, you are encouraged to generate new
2650 profile data matching the updated program, or to remap the profile data
2651 using the ``llvm-cxxmap`` and ``llvm-profdata merge`` tools.
2655 Profile data remapping is currently only supported for C++ mangled names
2656 following the Itanium C++ ABI mangling scheme. This covers all C++ targets
2657 supported by Clang other than Windows.
2659 GCOV-based Profiling
2660 --------------------
2662 GCOV is a test coverage program, it helps to know how often a line of code
2663 is executed. When instrumenting the code with ``--coverage`` option, some
2664 counters are added for each edge linking basic blocks.
2666 At compile time, gcno files are generated containing information about
2667 blocks and edges between them. At runtime the counters are incremented and at
2668 exit the counters are dumped in gcda files.
2670 The tool ``llvm-cov gcov`` will parse gcno, gcda and source files to generate
2671 a report ``.c.gcov``.
2673 .. option:: -fprofile-filter-files=[regexes]
2675 Define a list of regexes separated by a semi-colon.
2676 If a file name matches any of the regexes then the file is instrumented.
2678 .. code-block:: console
2680 $ clang --coverage -fprofile-filter-files=".*\.c$" foo.c
2682 For example, this will only instrument files finishing with ``.c``, skipping ``.h`` files.
2684 .. option:: -fprofile-exclude-files=[regexes]
2686 Define a list of regexes separated by a semi-colon.
2687 If a file name doesn't match all the regexes then the file is instrumented.
2689 .. code-block:: console
2691 $ clang --coverage -fprofile-exclude-files="^/usr/include/.*$" foo.c
2693 For example, this will instrument all the files except the ones in ``/usr/include``.
2695 If both options are used then a file is instrumented if its name matches any
2696 of the regexes from ``-fprofile-filter-list`` and doesn't match all the regexes
2697 from ``-fprofile-exclude-list``.
2699 .. code-block:: console
2701 $ clang --coverage -fprofile-exclude-files="^/usr/include/.*$" \
2702 -fprofile-filter-files="^/usr/.*$"
2704 In that case ``/usr/foo/oof.h`` is instrumented since it matches the filter regex and
2705 doesn't match the exclude regex, but ``/usr/include/foo.h`` doesn't since it matches
2708 Controlling Debug Information
2709 -----------------------------
2711 Controlling Size of Debug Information
2712 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2714 Debug info kind generated by Clang can be set by one of the flags listed
2715 below. If multiple flags are present, the last one is used.
2719 Don't generate any debug info (default).
2721 .. option:: -gline-tables-only
2723 Generate line number tables only.
2725 This kind of debug info allows to obtain stack traces with function names,
2726 file names and line numbers (by such tools as ``gdb`` or ``addr2line``). It
2727 doesn't contain any other data (e.g. description of local variables or
2728 function parameters).
2730 .. option:: -fstandalone-debug
2732 Clang supports a number of optimizations to reduce the size of debug
2733 information in the binary. They work based on the assumption that
2734 the debug type information can be spread out over multiple
2735 compilation units. For instance, Clang will not emit type
2736 definitions for types that are not needed by a module and could be
2737 replaced with a forward declaration. Further, Clang will only emit
2738 type info for a dynamic C++ class in the module that contains the
2739 vtable for the class.
2741 The **-fstandalone-debug** option turns off these optimizations.
2742 This is useful when working with 3rd-party libraries that don't come
2743 with debug information. Note that Clang will never emit type
2744 information for types that are not referenced at all by the program.
2746 .. option:: -fno-standalone-debug
2748 On Darwin **-fstandalone-debug** is enabled by default. The
2749 **-fno-standalone-debug** option can be used to get to turn on the
2750 vtable-based optimization described above.
2752 .. option:: -fuse-ctor-homing
2754 This optimization is similar to the optimizations that are enabled as part
2755 of -fno-standalone-debug. Here, Clang only emits type info for a
2756 non-trivial, non-aggregate C++ class in the modules that contain a
2757 definition of one of its constructors. This relies on the additional
2758 assumption that all classes that are not trivially constructible have a
2759 non-trivial constructor that is used somewhere. The negation,
2760 -fno-use-ctor-homing, ensures that constructor homing is not used.
2762 This flag is not enabled by default, and needs to be used with -cc1 or
2767 Generate complete debug info.
2769 .. option:: -feliminate-unused-debug-types
2771 By default, Clang does not emit type information for types that are defined
2772 but not used in a program. To retain the debug info for these unused types,
2773 the negation **-fno-eliminate-unused-debug-types** can be used.
2775 Controlling Macro Debug Info Generation
2776 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2778 Debug info for C preprocessor macros increases the size of debug information in
2779 the binary. Macro debug info generated by Clang can be controlled by the flags
2782 .. option:: -fdebug-macro
2784 Generate debug info for preprocessor macros. This flag is discarded when
2787 .. option:: -fno-debug-macro
2789 Do not generate debug info for preprocessor macros (default).
2791 Controlling Debugger "Tuning"
2792 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2794 While Clang generally emits standard DWARF debug info (http://dwarfstd.org),
2795 different debuggers may know how to take advantage of different specific DWARF
2796 features. You can "tune" the debug info for one of several different debuggers.
2798 .. option:: -ggdb, -glldb, -gsce, -gdbx
2800 Tune the debug info for the ``gdb``, ``lldb``, Sony PlayStation\ |reg|
2801 debugger, or ``dbx``, respectively. Each of these options implies **-g**.
2802 (Therefore, if you want both **-gline-tables-only** and debugger tuning, the
2803 tuning option must come first.)
2805 Controlling LLVM IR Output
2806 --------------------------
2808 Controlling Value Names in LLVM IR
2809 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2811 Emitting value names in LLVM IR increases the size and verbosity of the IR.
2812 By default, value names are only emitted in assertion-enabled builds of Clang.
2813 However, when reading IR it can be useful to re-enable the emission of value
2814 names to improve readability.
2816 .. option:: -fdiscard-value-names
2818 Discard value names when generating LLVM IR.
2820 .. option:: -fno-discard-value-names
2822 Do not discard value names when generating LLVM IR. This option can be used
2823 to re-enable names for release builds of Clang.
2826 Comment Parsing Options
2827 -----------------------
2829 Clang parses Doxygen and non-Doxygen style documentation comments and attaches
2830 them to the appropriate declaration nodes. By default, it only parses
2831 Doxygen-style comments and ignores ordinary comments starting with ``//`` and
2834 .. option:: -Wdocumentation
2836 Emit warnings about use of documentation comments. This warning group is off
2839 This includes checking that ``\param`` commands name parameters that actually
2840 present in the function signature, checking that ``\returns`` is used only on
2841 functions that actually return a value etc.
2843 .. option:: -Wno-documentation-unknown-command
2845 Don't warn when encountering an unknown Doxygen command.
2847 .. option:: -fparse-all-comments
2849 Parse all comments as documentation comments (including ordinary comments
2850 starting with ``//`` and ``/*``).
2852 .. option:: -fcomment-block-commands=[commands]
2854 Define custom documentation commands as block commands. This allows Clang to
2855 construct the correct AST for these custom commands, and silences warnings
2856 about unknown commands. Several commands must be separated by a comma
2857 *without trailing space*; e.g. ``-fcomment-block-commands=foo,bar`` defines
2858 custom commands ``\foo`` and ``\bar``.
2860 It is also possible to use ``-fcomment-block-commands`` several times; e.g.
2861 ``-fcomment-block-commands=foo -fcomment-block-commands=bar`` does the same
2869 The support for standard C in clang is feature-complete except for the
2870 C99 floating-point pragmas.
2872 Extensions supported by clang
2873 -----------------------------
2875 See :doc:`LanguageExtensions`.
2877 Differences between various standard modes
2878 ------------------------------------------
2880 clang supports the -std option, which changes what language mode clang uses.
2881 The supported modes for C are c89, gnu89, c94, c99, gnu99, c11, gnu11, c17,
2882 gnu17, c2x, gnu2x, and various aliases for those modes. If no -std option is
2883 specified, clang defaults to gnu17 mode. Many C99 and C11 features are
2884 supported in earlier modes as a conforming extension, with a warning. Use
2885 ``-pedantic-errors`` to request an error if a feature from a later standard
2886 revision is used in an earlier mode.
2888 Differences between all ``c*`` and ``gnu*`` modes:
2890 - ``c*`` modes define "``__STRICT_ANSI__``".
2891 - Target-specific defines not prefixed by underscores, like ``linux``,
2892 are defined in ``gnu*`` modes.
2893 - Trigraphs default to being off in ``gnu*`` modes; they can be enabled
2894 by the ``-trigraphs`` option.
2895 - The parser recognizes ``asm`` and ``typeof`` as keywords in ``gnu*`` modes;
2896 the variants ``__asm__`` and ``__typeof__`` are recognized in all modes.
2897 - The parser recognizes ``inline`` as a keyword in ``gnu*`` mode, in
2898 addition to recognizing it in the ``*99`` and later modes for which it is
2899 part of the ISO C standard. The variant ``__inline__`` is recognized in all
2901 - The Apple "blocks" extension is recognized by default in ``gnu*`` modes
2902 on some platforms; it can be enabled in any mode with the ``-fblocks``
2905 Differences between ``*89`` and ``*94`` modes:
2907 - Digraphs are not recognized in c89 mode.
2909 Differences between ``*94`` and ``*99`` modes:
2911 - The ``*99`` modes default to implementing ``inline`` / ``__inline__``
2912 as specified in C99, while the ``*89`` modes implement the GNU version.
2913 This can be overridden for individual functions with the ``__gnu_inline__``
2915 - The scope of names defined inside a ``for``, ``if``, ``switch``, ``while``,
2916 or ``do`` statement is different. (example: ``if ((struct x {int x;}*)0) {}``.)
2917 - ``__STDC_VERSION__`` is not defined in ``*89`` modes.
2918 - ``inline`` is not recognized as a keyword in ``c89`` mode.
2919 - ``restrict`` is not recognized as a keyword in ``*89`` modes.
2920 - Commas are allowed in integer constant expressions in ``*99`` modes.
2921 - Arrays which are not lvalues are not implicitly promoted to pointers
2923 - Some warnings are different.
2925 Differences between ``*99`` and ``*11`` modes:
2927 - Warnings for use of C11 features are disabled.
2928 - ``__STDC_VERSION__`` is defined to ``201112L`` rather than ``199901L``.
2930 Differences between ``*11`` and ``*17`` modes:
2932 - ``__STDC_VERSION__`` is defined to ``201710L`` rather than ``201112L``.
2934 GCC extensions not implemented yet
2935 ----------------------------------
2937 clang tries to be compatible with gcc as much as possible, but some gcc
2938 extensions are not implemented yet:
2940 - clang does not support decimal floating point types (``_Decimal32`` and
2942 - clang does not support nested functions; this is a complex feature
2943 which is infrequently used, so it is unlikely to be implemented
2944 anytime soon. In C++11 it can be emulated by assigning lambda
2945 functions to local variables, e.g:
2949 auto const local_function = [&](int parameter) {
2955 - clang only supports global register variables when the register specified
2956 is non-allocatable (e.g. the stack pointer). Support for general global
2957 register variables is unlikely to be implemented soon because it requires
2958 additional LLVM backend support.
2959 - clang does not support static initialization of flexible array
2960 members. This appears to be a rarely used extension, but could be
2961 implemented pending user demand.
2962 - clang does not support
2963 ``__builtin_va_arg_pack``/``__builtin_va_arg_pack_len``. This is
2964 used rarely, but in some potentially interesting places, like the
2965 glibc headers, so it may be implemented pending user demand. Note
2966 that because clang pretends to be like GCC 4.2, and this extension
2967 was introduced in 4.3, the glibc headers will not try to use this
2968 extension with clang at the moment.
2969 - clang does not support the gcc extension for forward-declaring
2970 function parameters; this has not shown up in any real-world code
2971 yet, though, so it might never be implemented.
2973 This is not a complete list; if you find an unsupported extension
2974 missing from this list, please send an e-mail to cfe-dev. This list
2975 currently excludes C++; see :ref:`C++ Language Features <cxx>`. Also, this
2976 list does not include bugs in mostly-implemented features; please see
2978 tracker <https://bugs.llvm.org/buglist.cgi?quicksearch=product%3Aclang+component%3A-New%2BBugs%2CAST%2CBasic%2CDriver%2CHeaders%2CLLVM%2BCodeGen%2Cparser%2Cpreprocessor%2CSemantic%2BAnalyzer>`_
2979 for known existing bugs (FIXME: Is there a section for bug-reporting
2980 guidelines somewhere?).
2982 Intentionally unsupported GCC extensions
2983 ----------------------------------------
2985 - clang does not support the gcc extension that allows variable-length
2986 arrays in structures. This is for a few reasons: one, it is tricky to
2987 implement, two, the extension is completely undocumented, and three,
2988 the extension appears to be rarely used. Note that clang *does*
2989 support flexible array members (arrays with a zero or unspecified
2990 size at the end of a structure).
2991 - GCC accepts many expression forms that are not valid integer constant
2992 expressions in bit-field widths, enumerator constants, case labels,
2993 and in array bounds at global scope. Clang also accepts additional
2994 expression forms in these contexts, but constructs that GCC accepts due to
2995 simplifications GCC performs while parsing, such as ``x - x`` (where ``x`` is a
2996 variable) will likely never be accepted by Clang.
2997 - clang does not support ``__builtin_apply`` and friends; this extension
2998 is extremely obscure and difficult to implement reliably.
3002 Microsoft extensions
3003 --------------------
3005 clang has support for many extensions from Microsoft Visual C++. To enable these
3006 extensions, use the ``-fms-extensions`` command-line option. This is the default
3007 for Windows targets. Clang does not implement every pragma or declspec provided
3008 by MSVC, but the popular ones, such as ``__declspec(dllexport)`` and ``#pragma
3009 comment(lib)`` are well supported.
3011 clang has a ``-fms-compatibility`` flag that makes clang accept enough
3012 invalid C++ to be able to parse most Microsoft headers. For example, it
3013 allows `unqualified lookup of dependent base class members
3014 <https://clang.llvm.org/compatibility.html#dep_lookup_bases>`_, which is
3015 a common compatibility issue with clang. This flag is enabled by default
3016 for Windows targets.
3018 ``-fdelayed-template-parsing`` lets clang delay parsing of function template
3019 definitions until the end of a translation unit. This flag is enabled by
3020 default for Windows targets.
3022 For compatibility with existing code that compiles with MSVC, clang defines the
3023 ``_MSC_VER`` and ``_MSC_FULL_VER`` macros. These default to the values of 1800
3024 and 180000000 respectively, making clang look like an early release of Visual
3025 C++ 2013. The ``-fms-compatibility-version=`` flag overrides these values. It
3026 accepts a dotted version tuple, such as 19.00.23506. Changing the MSVC
3027 compatibility version makes clang behave more like that version of MSVC. For
3028 example, ``-fms-compatibility-version=19`` will enable C++14 features and define
3029 ``char16_t`` and ``char32_t`` as builtin types.
3033 C++ Language Features
3034 =====================
3036 clang fully implements all of standard C++98 except for exported
3037 templates (which were removed in C++11), all of standard C++11,
3038 C++14, and C++17, and most of C++20.
3040 See the `C++ support in Clang <https://clang.llvm.org/cxx_status.html>`_ page
3041 for detailed information on C++ feature support across Clang versions.
3043 Controlling implementation limits
3044 ---------------------------------
3046 .. option:: -fbracket-depth=N
3048 Sets the limit for nested parentheses, brackets, and braces to N. The
3051 .. option:: -fconstexpr-depth=N
3053 Sets the limit for recursive constexpr function invocations to N. The
3056 .. option:: -fconstexpr-steps=N
3058 Sets the limit for the number of full-expressions evaluated in a single
3059 constant expression evaluation. The default is 1048576.
3061 .. option:: -ftemplate-depth=N
3063 Sets the limit for recursively nested template instantiations to N. The
3066 .. option:: -foperator-arrow-depth=N
3068 Sets the limit for iterative calls to 'operator->' functions to N. The
3073 Objective-C Language Features
3074 =============================
3078 Objective-C++ Language Features
3079 ===============================
3086 Clang supports all OpenMP 4.5 directives and clauses. See :doc:`OpenMPSupport`
3087 for additional details.
3089 Use `-fopenmp` to enable OpenMP. Support for OpenMP can be disabled with
3092 Use `-fopenmp-simd` to enable OpenMP simd features only, without linking
3093 the runtime library; for combined constructs
3094 (e.g. ``#pragma omp parallel for simd``) the non-simd directives and clauses
3095 will be ignored. This can be disabled with `-fno-openmp-simd`.
3097 Controlling implementation limits
3098 ---------------------------------
3100 .. option:: -fopenmp-use-tls
3102 Controls code generation for OpenMP threadprivate variables. In presence of
3103 this option all threadprivate variables are generated the same way as thread
3104 local variables, using TLS support. If `-fno-openmp-use-tls`
3105 is provided or target does not support TLS, code generation for threadprivate
3106 variables relies on OpenMP runtime library.
3113 Clang can be used to compile OpenCL kernels for execution on a device
3114 (e.g. GPU). It is possible to compile the kernel into a binary (e.g. for AMDGPU)
3115 that can be uploaded to run directly on a device (e.g. using
3116 `clCreateProgramWithBinary
3117 <https://www.khronos.org/registry/OpenCL/specs/opencl-1.1.pdf#111>`_) or
3118 into generic bitcode files loadable into other toolchains.
3120 Compiling to a binary using the default target from the installation can be done
3123 .. code-block:: console
3125 $ echo "kernel void k(){}" > test.cl
3128 Compiling for a specific target can be done by specifying the triple corresponding
3129 to the target, for example:
3131 .. code-block:: console
3133 $ clang -target nvptx64-unknown-unknown test.cl
3134 $ clang -target amdgcn-amd-amdhsa -mcpu=gfx900 test.cl
3136 Compiling to bitcode can be done as follows:
3138 .. code-block:: console
3140 $ clang -c -emit-llvm test.cl
3142 This will produce a file `test.bc` that can be used in vendor toolchains
3143 to perform machine code generation.
3145 Note that if compiled to bitcode for generic targets such as SPIR/SPIR-V,
3146 portable IR is produced that can be used with various vendor
3147 tools as well as open source tools such as `SPIRV-LLVM Translator
3148 <https://github.com/KhronosGroup/SPIRV-LLVM-Translator>`_
3149 to produce SPIR-V binary. More details are provided in `the offline
3150 compilation from OpenCL kernel sources into SPIR-V using open source
3152 <https://github.com/KhronosGroup/OpenCL-Guide/blob/main/chapters/os_tooling.md>`_.
3153 From clang 14 onwards SPIR-V can be generated directly as detailed in
3154 :ref:`the SPIR-V support section <spir-v>`.
3156 Clang currently supports OpenCL C language standards up to v2.0. Clang mainly
3157 supports full profile. There is only very limited support of the embedded
3159 From clang 9 a C++ mode is available for OpenCL (see
3160 :ref:`C++ for OpenCL <cxx_for_opencl>`).
3162 OpenCL v3.0 support is complete but it remains in experimental state, see more
3163 details about the experimental features and limitations in :doc:`OpenCLSupport`
3166 OpenCL Specific Options
3167 -----------------------
3169 Most of the OpenCL build options from `the specification v2.0 section 5.8.4
3170 <https://www.khronos.org/registry/cl/specs/opencl-2.0.pdf#200>`_ are available.
3174 .. code-block:: console
3176 $ clang -cl-std=CL2.0 -cl-single-precision-constant test.cl
3179 Many flags used for the compilation for C sources can also be passed while
3180 compiling for OpenCL, examples: ``-c``, ``-O<1-4|s>``, ``-o``, ``-emit-llvm``, etc.
3182 Some extra options are available to support special OpenCL features.
3184 .. _opencl_cl_no_stdinc:
3186 .. option:: -cl-no-stdinc
3188 Allows to disable all extra types and functions that are not native to the compiler.
3189 This might reduce the compilation speed marginally but many declarations from the
3190 OpenCL standard will not be accessible. For example, the following will fail to
3193 .. code-block:: console
3195 $ echo "bool is_wg_uniform(int i){return get_enqueued_local_size(i)==get_local_size(i);}" > test.cl
3196 $ clang -cl-std=CL2.0 -cl-no-stdinc test.cl
3197 error: use of undeclared identifier 'get_enqueued_local_size'
3198 error: use of undeclared identifier 'get_local_size'
3200 More information about the standard types and functions is provided in :ref:`the
3201 section on the OpenCL Header <opencl_header>`.
3207 Enables/Disables support of OpenCL extensions and optional features. All OpenCL
3208 targets set a list of extensions that they support. Clang allows to amend this using
3209 the ``-cl-ext`` flag with a comma-separated list of extensions prefixed with
3210 ``'+'`` or ``'-'``. The syntax: ``-cl-ext=<(['-'|'+']<extension>[,])+>``, where
3211 extensions can be either one of `the OpenCL published extensions
3212 <https://www.khronos.org/registry/OpenCL>`_
3213 or any vendor extension. Alternatively, ``'all'`` can be used to enable
3214 or disable all known extensions.
3216 Example disabling double support for the 64-bit SPIR-V target:
3218 .. code-block:: console
3220 $ clang -c -target spirv64 -cl-ext=-cl_khr_fp64 test.cl
3222 Enabling all extensions except double support in R600 AMD GPU can be done using:
3224 .. code-block:: console
3226 $ clang -target r600 -cl-ext=-all,+cl_khr_fp16 test.cl
3228 Note that some generic targets e.g. SPIR/SPIR-V enable all extensions/features in
3234 OpenCL targets are derived from the regular Clang target classes. The OpenCL
3235 specific parts of the target representation provide address space mapping as
3236 well as a set of supported extensions.
3241 There is a set of concrete HW architectures that OpenCL can be compiled for.
3245 .. code-block:: console
3247 $ clang -target amdgcn-amd-amdhsa -mcpu=gfx900 test.cl
3249 - For Nvidia architectures:
3251 .. code-block:: console
3253 $ clang -target nvptx64-unknown-unknown test.cl
3259 - A SPIR-V binary can be produced for 32 or 64 bit targets.
3261 .. code-block:: console
3263 $ clang -target spirv32 -c test.cl
3264 $ clang -target spirv64 -c test.cl
3266 More details can be found in :ref:`the SPIR-V support section <spir-v>`.
3268 - SPIR is available as a generic target to allow portable bitcode to be produced
3269 that can be used across GPU toolchains. The implementation follows `the SPIR
3270 specification <https://www.khronos.org/spir>`_. There are two flavors
3271 available for 32 and 64 bits.
3273 .. code-block:: console
3275 $ clang -target spir test.cl -emit-llvm -c
3276 $ clang -target spir64 test.cl -emit-llvm -c
3278 Clang will generate SPIR v1.2 compatible IR for OpenCL versions up to 2.0 and
3279 SPIR v2.0 for OpenCL v2.0 or C++ for OpenCL.
3281 - x86 is used by some implementations that are x86 compatible and currently
3282 remains for backwards compatibility (with older implementations prior to
3283 SPIR target support). For "non-SPMD" targets which cannot spawn multiple
3284 work-items on the fly using hardware, which covers practically all non-GPU
3285 devices such as CPUs and DSPs, additional processing is needed for the kernels
3286 to support multiple work-item execution. For this, a 3rd party toolchain,
3287 such as for example `POCL <http://portablecl.org/>`_, can be used.
3289 This target does not support multiple memory segments and, therefore, the fake
3290 address space map can be added using the :ref:`-ffake-address-space-map
3291 <opencl_fake_address_space_map>` flag.
3293 All known OpenCL extensions and features are set to supported in the generic targets,
3294 however :option:`-cl-ext` flag can be used to toggle individual extensions and
3302 By default Clang will include standard headers and therefore most of OpenCL
3303 builtin functions and types are available during compilation. The
3304 default declarations of non-native compiler types and functions can be disabled
3305 by using flag :ref:`-cl-no-stdinc <opencl_cl_no_stdinc>`.
3307 The following example demonstrates that OpenCL kernel sources with various
3308 standard builtin functions can be compiled without the need for an explicit
3309 includes or compiler flags.
3311 .. code-block:: console
3313 $ echo "bool is_wg_uniform(int i){return get_enqueued_local_size(i)==get_local_size(i);}" > test.cl
3314 $ clang -cl-std=CL2.0 test.cl
3316 More information about the default headers is provided in :doc:`OpenCLSupport`.
3321 Most of the ``cl_khr_*`` extensions to OpenCL C from `the official OpenCL
3322 registry <https://www.khronos.org/registry/OpenCL/>`_ are available and
3323 configured per target depending on the support available in the specific
3326 It is possible to alter the default extensions setting per target using
3327 ``-cl-ext`` flag. (See :ref:`flags description <opencl_cl_ext>` for more details).
3329 Vendor extensions can be added flexibly by declaring the list of types and
3330 functions associated with each extensions enclosed within the following
3331 compiler pragma directives:
3335 #pragma OPENCL EXTENSION the_new_extension_name : begin
3336 // declare types and functions associated with the extension here
3337 #pragma OPENCL EXTENSION the_new_extension_name : end
3339 For example, parsing the following code adds ``my_t`` type and ``my_func``
3340 function to the custom ``my_ext`` extension.
3344 #pragma OPENCL EXTENSION my_ext : begin
3349 #pragma OPENCL EXTENSION my_ext : end
3351 There is no conflict resolution for identifier clashes among extensions.
3352 It is therefore recommended that the identifiers are prefixed with a
3353 double underscore to avoid clashing with user space identifiers. Vendor
3354 extension should use reserved identifier prefix e.g. amd, arm, intel.
3356 Clang also supports language extensions documented in `The OpenCL C Language
3357 Extensions Documentation
3358 <https://github.com/KhronosGroup/Khronosdotorg/blob/main/api/opencl/assets/OpenCL_LangExt.pdf>`_.
3360 OpenCL-Specific Attributes
3361 --------------------------
3363 OpenCL support in Clang contains a set of attribute taken directly from the
3364 specification as well as additional attributes.
3366 See also :doc:`AttributeReference`.
3371 Clang supports this attribute to comply to OpenCL v2.0 conformance, but it
3372 does not have any effect on the IR. For more details reffer to the specification
3374 <https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#49>`_
3380 The implementation of this feature mirrors the unroll hint for C.
3381 More details on the syntax can be found in the specification
3383 <https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#61>`_
3388 To make sure no invalid optimizations occur for single program multiple data
3389 (SPMD) / single instruction multiple thread (SIMT) Clang provides attributes that
3390 can be used for special functions that have cross work item semantics.
3391 An example is the subgroup operations such as `intel_sub_group_shuffle
3392 <https://www.khronos.org/registry/cl/extensions/intel/cl_intel_subgroups.txt>`_
3396 // Define custom my_sub_group_shuffle(data, c)
3397 // that makes use of intel_sub_group_shuffle
3399 if (r0) r1 = computeA();
3400 // Shuffle data from r1 into r3
3401 // of threads id r2.
3402 r3 = my_sub_group_shuffle(r1, r2);
3403 if (r0) r3 = computeB();
3405 with non-SPMD semantics this is optimized to the following equivalent code:
3411 // Incorrect functionality! The data in r1
3412 // have not been computed by all threads yet.
3413 r3 = my_sub_group_shuffle(r1, r2);
3416 r3 = my_sub_group_shuffle(r1, r2);
3420 Declaring the function ``my_sub_group_shuffle`` with the convergent attribute
3425 my_sub_group_shuffle() __attribute__((convergent));
3427 Using ``convergent`` guarantees correct execution by keeping CFG equivalence
3428 wrt operations marked as ``convergent``. CFG ``G´`` is equivalent to ``G`` wrt
3429 node ``Ni`` : ``iff ∀ Nj (i≠j)`` domination and post-domination relations with
3430 respect to ``Ni`` remain the same in both ``G`` and ``G´``.
3435 ``noduplicate`` is more restrictive with respect to optimizations than
3436 ``convergent`` because a convergent function only preserves CFG equivalence.
3437 This allows some optimizations to happen as long as the control flow remains
3442 for (int i=0; i<4; i++)
3443 my_sub_group_shuffle()
3449 my_sub_group_shuffle();
3450 my_sub_group_shuffle();
3451 my_sub_group_shuffle();
3452 my_sub_group_shuffle();
3454 while using ``noduplicate`` would disallow this. Also ``noduplicate`` doesn't
3455 have the same safe semantics of CFG as ``convergent`` and can cause changes in
3456 CFG that modify semantics of the original program.
3458 ``noduplicate`` is kept for backwards compatibility only and it considered to be
3459 deprecated for future uses.
3466 Starting from clang 9 kernel code can contain C++17 features: classes, templates,
3467 function overloading, type deduction, etc. Please note that this is not an
3468 implementation of `OpenCL C++
3469 <https://www.khronos.org/registry/OpenCL/specs/2.2/pdf/OpenCL_Cxx.pdf>`_ and
3470 there is no plan to support it in clang in any new releases in the near future.
3472 Clang currently supports C++ for OpenCL 1.0 and 2021.
3473 For detailed information about this language refer to the C++ for OpenCL
3474 Programming Language Documentation available
3475 in `the latest build
3476 <https://www.khronos.org/opencl/assets/CXX_for_OpenCL.html>`_
3477 or in `the official release
3478 <https://github.com/KhronosGroup/OpenCL-Docs/releases/tag/cxxforopencl-docrev2021.12>`_.
3480 To enable the C++ for OpenCL mode, pass one of following command line options when
3481 compiling ``.clcpp`` file:
3483 - C++ for OpenCL 1.0: ``-cl-std=clc++``, ``-cl-std=CLC++``, ``-cl-std=clc++1.0``,
3484 ``-cl-std=CLC++1.0``, ``-std=clc++``, ``-std=CLC++``, ``-std=clc++1.0`` or
3487 - C++ for OpenCL 2021: ``-cl-std=clc++2021``, ``-cl-std=CLC++2021``,
3488 ``-std=clc++2021``, ``-std=CLC++2021``.
3493 template<class T> T add( T x, T y )
3498 __kernel void test( __global float* a, __global float* b)
3500 auto index = get_global_id(0);
3501 a[index] = add(b[index], b[index+1]);
3505 .. code-block:: console
3507 clang -cl-std=clc++1.0 test.clcpp
3508 clang -cl-std=clc++ -c -target spirv64 test.cl
3511 By default, files with ``.clcpp`` extension are compiled with the C++ for
3514 .. code-block:: console
3518 For backward compatibility files with ``.cl`` extensions can also be compiled
3519 in C++ for OpenCL mode but the desirable language mode must be activated with
3522 .. code-block:: console
3524 clang -cl-std=clc++ test.cl
3526 Support of C++ for OpenCL 2021 is currently in experimental phase, refer to
3527 :doc:`OpenCLSupport` for more details.
3529 C++ for OpenCL kernel sources can also be compiled online in drivers supporting
3530 `cl_ext_cxx_for_opencl
3531 <https://www.khronos.org/registry/OpenCL/extensions/ext/cl_ext_cxx_for_opencl.html>`_
3534 Constructing and destroying global objects
3535 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3537 Global objects with non-trivial constructors require the constructors to be run
3538 before the first kernel using the global objects is executed. Similarly global
3539 objects with non-trivial destructors require destructor invocation just after
3540 the last kernel using the program objects is executed.
3541 In OpenCL versions earlier than v2.2 there is no support for invoking global
3542 constructors. However, an easy workaround is to manually enqueue the
3543 constructor initialization kernel that has the following name scheme
3544 ``_GLOBAL__sub_I_<compiled file name>``.
3545 This kernel is only present if there are global objects with non-trivial
3546 constructors present in the compiled binary. One way to check this is by
3547 passing ``CL_PROGRAM_KERNEL_NAMES`` to ``clGetProgramInfo`` (OpenCL v2.0
3548 s5.8.7) and then checking whether any kernel name matches the naming scheme of
3549 global constructor initialization kernel above.
3551 Note that if multiple files are compiled and linked into libraries, multiple
3552 kernels that initialize global objects for multiple modules would have to be
3555 Applications are currently required to run initialization of global objects
3556 manually before running any kernels in which the objects are used.
3558 .. code-block:: console
3560 clang -cl-std=clc++ test.cl
3562 If there are any global objects to be initialized, the final binary will
3563 contain the ``_GLOBAL__sub_I_test.cl`` kernel to be enqueued.
3565 Note that the manual workaround only applies to objects declared at the
3566 program scope. There is no manual workaround for the construction of static
3567 objects with non-trivial constructors inside functions.
3569 Global destructors can not be invoked manually in the OpenCL v2.0 drivers.
3570 However, all memory used for program scope objects should be released on
3571 ``clReleaseProgram``.
3575 Limited experimental support of C++ standard libraries for OpenCL is
3576 described in :doc:`OpenCLSupport` page.
3578 .. _target_features:
3580 Target-Specific Features and Limitations
3581 ========================================
3583 CPU Architectures Features and Limitations
3584 ------------------------------------------
3589 The support for X86 (both 32-bit and 64-bit) is considered stable on
3590 Darwin (macOS), Linux, FreeBSD, and Dragonfly BSD: it has been tested
3591 to correctly compile many large C, C++, Objective-C, and Objective-C++
3594 On ``x86_64-mingw32``, passing i128(by value) is incompatible with the
3595 Microsoft x64 calling convention. You might need to tweak
3596 ``WinX86_64ABIInfo::classify()`` in lib/CodeGen/TargetInfo.cpp.
3598 For the X86 target, clang supports the `-m16` command line
3599 argument which enables 16-bit code output. This is broadly similar to
3600 using ``asm(".code16gcc")`` with the GNU toolchain. The generated code
3601 and the ABI remains 32-bit but the assembler emits instructions
3602 appropriate for a CPU running in 16-bit mode, with address-size and
3603 operand-size prefixes to enable 32-bit addressing and operations.
3605 Several micro-architecture levels as specified by the x86-64 psABI are defined.
3606 They are cumulative in the sense that features from previous levels are
3607 implicitly included in later levels.
3609 - ``-march=x86-64``: CMOV, CMPXCHG8B, FPU, FXSR, MMX, FXSR, SCE, SSE, SSE2
3610 - ``-march=x86-64-v2``: (close to Nehalem) CMPXCHG16B, LAHF-SAHF, POPCNT, SSE3, SSE4.1, SSE4.2, SSSE3
3611 - ``-march=x86-64-v3``: (close to Haswell) AVX, AVX2, BMI1, BMI2, F16C, FMA, LZCNT, MOVBE, XSAVE
3612 - ``-march=x86-64-v4``: AVX512F, AVX512BW, AVX512CD, AVX512DQ, AVX512VL
3617 The support for ARM (specifically ARMv6 and ARMv7) is considered stable
3618 on Darwin (iOS): it has been tested to correctly compile many large C,
3619 C++, Objective-C, and Objective-C++ codebases. Clang only supports a
3620 limited number of ARM architectures. It does not yet fully support
3626 The support for PowerPC (especially PowerPC64) is considered stable
3627 on Linux and FreeBSD: it has been tested to correctly compile many
3628 large C and C++ codebases. PowerPC (32bit) is still missing certain
3629 features (e.g. PIC code on ELF platforms).
3634 clang currently contains some support for other architectures (e.g. Sparc);
3635 however, significant pieces of code generation are still missing, and they
3636 haven't undergone significant testing.
3638 clang contains limited support for the MSP430 embedded processor, but
3639 both the clang support and the LLVM backend support are highly
3642 Other platforms are completely unsupported at the moment. Adding the
3643 minimal support needed for parsing and semantic analysis on a new
3644 platform is quite easy; see ``lib/Basic/Targets.cpp`` in the clang source
3645 tree. This level of support is also sufficient for conversion to LLVM IR
3646 for simple programs. Proper support for conversion to LLVM IR requires
3647 adding code to ``lib/CodeGen/CGCall.cpp`` at the moment; this is likely to
3648 change soon, though. Generating assembly requires a suitable LLVM
3651 Operating System Features and Limitations
3652 -----------------------------------------
3657 Clang has experimental support for targeting "Cygming" (Cygwin / MinGW)
3660 See also :ref:`Microsoft Extensions <c_ms>`.
3665 Clang works on Cygwin-1.7.
3670 Clang works on some mingw32 distributions. Clang assumes directories as
3673 - ``C:/mingw/include``
3675 - ``C:/mingw/lib/gcc/mingw32/4.[3-5].0/include/c++``
3677 On MSYS, a few tests might fail.
3682 For 32-bit (i686-w64-mingw32), and 64-bit (x86\_64-w64-mingw32), Clang
3685 - ``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)``
3686 - ``some_directory/bin/gcc.exe``
3687 - ``some_directory/bin/clang.exe``
3688 - ``some_directory/bin/clang++.exe``
3689 - ``some_directory/bin/../include/c++/GCC_version``
3690 - ``some_directory/bin/../include/c++/GCC_version/x86_64-w64-mingw32``
3691 - ``some_directory/bin/../include/c++/GCC_version/i686-w64-mingw32``
3692 - ``some_directory/bin/../include/c++/GCC_version/backward``
3693 - ``some_directory/bin/../x86_64-w64-mingw32/include``
3694 - ``some_directory/bin/../i686-w64-mingw32/include``
3695 - ``some_directory/bin/../include``
3697 This directory layout is standard for any toolchain you will find on the
3698 official `MinGW-w64 website <http://mingw-w64.sourceforge.net>`_.
3700 Clang expects the GCC executable "gcc.exe" compiled for
3701 ``i686-w64-mingw32`` (or ``x86_64-w64-mingw32``) to be present on PATH.
3703 `Some tests might fail <https://bugs.llvm.org/show_bug.cgi?id=9072>`_ on
3704 ``x86_64-w64-mingw32``.
3709 The ``-mdefault-visibility-export-mapping=`` option can be used to control
3710 mapping of default visibility to an explicit shared object export
3711 (i.e. XCOFF exported visibility). Three values are provided for the option:
3713 * ``-mdefault-visibility-export-mapping=none``: no additional export
3714 information is created for entities with default visibility.
3715 * ``-mdefault-visibility-export-mapping=explicit``: mark entities for export
3716 if they have explict (e.g. via an attribute) default visibility from the
3717 source, including RTTI.
3718 * ``-mdefault-visibility-export-mapping=all``: set XCOFF exported visibility
3719 for all entities with default visibility from any source. This gives a
3720 export behavior similar to ELF platforms where all entities with default
3721 visibility are exported.
3728 Clang supports generation of SPIR-V conformant to `the OpenCL Environment
3730 <https://www.khronos.org/registry/OpenCL/specs/3.0-unified/html/OpenCL_Env.html>`_.
3732 To generate SPIR-V binaries, Clang uses the external ``llvm-spirv`` tool from the
3733 `SPIRV-LLVM-Translator repo
3734 <https://github.com/KhronosGroup/SPIRV-LLVM-Translator>`_.
3736 Prior to the generation of SPIR-V binary with Clang, ``llvm-spirv``
3737 should be built or installed. Please refer to `the following instructions
3738 <https://github.com/KhronosGroup/SPIRV-LLVM-Translator#build-instructions>`_
3739 for more details. Clang will expect the ``llvm-spirv`` executable to
3740 be present in the ``PATH`` environment variable. Clang uses ``llvm-spirv``
3741 with `the widely adopted assembly syntax package
3742 <https://github.com/KhronosGroup/SPIRV-LLVM-Translator/#build-with-spirv-tools>`_.
3745 <https://github.com/KhronosGroup/SPIRV-LLVM-Translator/releases>`_ of
3746 ``llvm-spirv`` is aligned with Clang major releases. The same applies to the
3747 main development branch. It is therefore important to ensure the ``llvm-spirv``
3748 version is in alignment with the Clang version. For troubleshooting purposes
3749 ``llvm-spirv`` can be `tested in isolation
3750 <https://github.com/KhronosGroup/SPIRV-LLVM-Translator#test-instructions>`_.
3752 Example usage for OpenCL kernel compilation:
3754 .. code-block:: console
3756 $ clang -target spirv32 -c test.cl
3757 $ clang -target spirv64 -c test.cl
3759 Both invocations of Clang will result in the generation of a SPIR-V binary file
3760 `test.o` for 32 bit and 64 bit respectively. This file can be imported
3761 by an OpenCL driver that support SPIR-V consumption or it can be compiled
3762 further by offline SPIR-V consumer tools.
3764 Converting to SPIR-V produced with the optimization levels other than `-O0` is
3765 currently available as an experimental feature and it is not guaranteed to work
3768 Clang also supports integrated generation of SPIR-V without use of ``llvm-spirv``
3769 tool as an experimental feature when ``-fintegrated-objemitter`` flag is passed in
3772 .. code-block:: console
3774 $ clang -target spirv32 -fintegrated-objemitter -c test.cl
3776 Note that only very basic functionality is supported at this point and therefore
3777 it is not suitable for arbitrary use cases. This feature is only enabled when clang
3778 build is configured with ``-DLLVM_EXPERIMENTAL_TARGETS_TO_BUILD=SPIRV`` option.
3780 Linking is done using ``spirv-link`` from `the SPIRV-Tools project
3781 <https://github.com/KhronosGroup/SPIRV-Tools#linker>`_. Similar to other external
3782 linkers, Clang will expect ``spirv-link`` to be installed separately and to be
3783 present in the ``PATH`` environment variable. Please refer to `the build and
3784 installation instructions
3785 <https://github.com/KhronosGroup/SPIRV-Tools#build>`_.
3787 .. code-block:: console
3789 $ clang -target spirv64 test1.cl test2.cl
3791 More information about the SPIR-V target settings and supported versions of SPIR-V
3792 format can be found in `the SPIR-V target guide
3793 <https://llvm.org/docs/SPIRVUsage.html>`__.
3800 clang-cl is an alternative command-line interface to Clang, designed for
3801 compatibility with the Visual C++ compiler, cl.exe.
3803 To enable clang-cl to find system headers, libraries, and the linker when run
3804 from the command-line, it should be executed inside a Visual Studio Native Tools
3805 Command Prompt or a regular Command Prompt where the environment has been set
3806 up using e.g. `vcvarsall.bat <https://msdn.microsoft.com/en-us/library/f2ccy3wt.aspx>`_.
3808 clang-cl can also be used from inside Visual Studio by selecting the LLVM
3809 Platform Toolset. The toolset is not part of the installer, but may be installed
3811 `Visual Studio Marketplace <https://marketplace.visualstudio.com/items?itemName=LLVMExtensions.llvm-toolchain>`_.
3812 To use the toolset, select a project in Solution Explorer, open its Property
3813 Page (Alt+F7), and in the "General" section of "Configuration Properties"
3814 change "Platform Toolset" to LLVM. Doing so enables an additional Property
3815 Page for selecting the clang-cl executable to use for builds.
3817 To use the toolset with MSBuild directly, invoke it with e.g.
3818 ``/p:PlatformToolset=LLVM``. This allows trying out the clang-cl toolchain
3819 without modifying your project files.
3821 It's also possible to point MSBuild at clang-cl without changing toolset by
3822 passing ``/p:CLToolPath=c:\llvm\bin /p:CLToolExe=clang-cl.exe``.
3824 When using CMake and the Visual Studio generators, the toolset can be set with the ``-T`` flag:
3828 cmake -G"Visual Studio 16 2019" -T LLVM ..
3830 When using CMake with the Ninja generator, set the ``CMAKE_C_COMPILER`` and
3831 ``CMAKE_CXX_COMPILER`` variables to clang-cl:
3835 cmake -GNinja -DCMAKE_C_COMPILER="c:/Program Files (x86)/LLVM/bin/clang-cl.exe"
3836 -DCMAKE_CXX_COMPILER="c:/Program Files (x86)/LLVM/bin/clang-cl.exe" ..
3839 Command-Line Options
3840 --------------------
3842 To be compatible with cl.exe, clang-cl supports most of the same command-line
3843 options. Those options can start with either ``/`` or ``-``. It also supports
3844 some of Clang's core options, such as the ``-W`` options.
3846 Options that are known to clang-cl, but not currently supported, are ignored
3847 with a warning. For example:
3851 clang-cl.exe: warning: argument unused during compilation: '/AI'
3853 To suppress warnings about unused arguments, use the ``-Qunused-arguments`` option.
3855 Options that are not known to clang-cl will be ignored by default. Use the
3856 ``-Werror=unknown-argument`` option in order to treat them as errors. If these
3857 options are spelled with a leading ``/``, they will be mistaken for a filename:
3861 clang-cl.exe: error: no such file or directory: '/foobar'
3863 Please `file a bug <https://bugs.llvm.org/enter_bug.cgi?product=clang&component=Driver>`_
3864 for any valid cl.exe flags that clang-cl does not understand.
3866 Execute ``clang-cl /?`` to see a list of supported options:
3870 CL.EXE COMPATIBILITY OPTIONS:
3871 /? Display available options
3872 /arch:<value> Set architecture for code generation
3873 /Brepro- Emit an object file which cannot be reproduced over time
3874 /Brepro Emit an object file which can be reproduced over time
3875 /clang:<arg> Pass <arg> to the clang driver
3876 /C Don't discard comments when preprocessing
3878 /d1PP Retain macro definitions in /E mode
3879 /d1reportAllClassLayout Dump record layout information
3880 /diagnostics:caret Enable caret and column diagnostics (on by default)
3881 /diagnostics:classic Disable column and caret diagnostics
3882 /diagnostics:column Disable caret diagnostics but keep column info
3883 /D <macro[=value]> Define macro
3884 /EH<value> Exception handling model
3885 /EP Disable linemarker output and preprocess to stdout
3886 /execution-charset:<value>
3887 Runtime encoding, supports only UTF-8
3888 /E Preprocess to stdout
3889 /FA Output assembly code file during compilation
3890 /Fa<file or directory> Output assembly code to this file during compilation (with /FA)
3891 /Fe<file or directory> Set output executable file or directory (ends in / or \)
3892 /FI <value> Include file before parsing
3893 /Fi<file> Set preprocess output file name (with /P)
3894 /Fo<file or directory> Set output object file, or directory (ends in / or \) (with /c)
3900 /Fp<filename> Set pch filename (with /Yc and /Yu)
3901 /GA Assume thread-local variables are defined in the executable
3902 /Gd Set __cdecl as a default calling convention
3903 /GF- Disable string pooling
3904 /GF Enable string pooling (default)
3905 /GR- Disable emission of RTTI data
3906 /Gregcall Set __regcall as a default calling convention
3907 /GR Enable emission of RTTI data
3908 /Gr Set __fastcall as a default calling convention
3909 /GS- Disable buffer security check
3910 /GS Enable buffer security check (default)
3911 /Gs Use stack probes (default)
3912 /Gs<value> Set stack probe size (default 4096)
3913 /guard:<value> Enable Control Flow Guard with /guard:cf,
3914 or only the table with /guard:cf,nochecks.
3915 Enable EH Continuation Guard with /guard:ehcont
3916 /Gv Set __vectorcall as a default calling convention
3917 /Gw- Don't put each data item in its own section
3918 /Gw Put each data item in its own section
3919 /GX- Disable exception handling
3920 /GX Enable exception handling
3921 /Gy- Don't put each function in its own section (default)
3922 /Gy Put each function in its own section
3923 /Gz Set __stdcall as a default calling convention
3924 /help Display available options
3925 /imsvc <dir> Add directory to system include search path, as if part of %INCLUDE%
3926 /I <dir> Add directory to include search path
3927 /J Make char type unsigned
3928 /LDd Create debug DLL
3930 /link <options> Forward options to the linker
3931 /MDd Use DLL debug run-time
3932 /MD Use DLL run-time
3933 /MTd Use static debug run-time
3934 /MT Use static run-time
3935 /O0 Disable optimization
3936 /O1 Optimize for size (same as /Og /Os /Oy /Ob2 /GF /Gy)
3937 /O2 Optimize for speed (same as /Og /Oi /Ot /Oy /Ob2 /GF /Gy)
3938 /Ob0 Disable function inlining
3939 /Ob1 Only inline functions which are (explicitly or implicitly) marked inline
3940 /Ob2 Inline functions as deemed beneficial by the compiler
3941 /Od Disable optimization
3943 /Oi- Disable use of builtin functions
3944 /Oi Enable use of builtin functions
3945 /Os Optimize for size
3946 /Ot Optimize for speed
3947 /Ox Deprecated (same as /Og /Oi /Ot /Oy /Ob2); use /O2 instead
3948 /Oy- Disable frame pointer omission (x86 only, default)
3949 /Oy Enable frame pointer omission (x86 only)
3950 /O<flags> Set multiple /O flags at once; e.g. '/O2y-' for '/O2 /Oy-'
3951 /o <file or directory> Set output file or directory (ends in / or \)
3952 /P Preprocess to file
3953 /Qvec- Disable the loop vectorization passes
3954 /Qvec Enable the loop vectorization passes
3955 /showFilenames- Don't print the name of each compiled file (default)
3956 /showFilenames Print the name of each compiled file
3957 /showIncludes Print info about included files to stderr
3958 /source-charset:<value> Source encoding, supports only UTF-8
3959 /std:<value> Language standard to compile for
3960 /TC Treat all source files as C
3961 /Tc <filename> Specify a C source file
3962 /TP Treat all source files as C++
3963 /Tp <filename> Specify a C++ source file
3964 /utf-8 Set source and runtime encoding to UTF-8 (default)
3965 /U <macro> Undefine macro
3966 /vd<value> Control vtordisp placement
3967 /vmb Use a best-case representation method for member pointers
3968 /vmg Use a most-general representation for member pointers
3969 /vmm Set the default most-general representation to multiple inheritance
3970 /vms Set the default most-general representation to single inheritance
3971 /vmv Set the default most-general representation to virtual inheritance
3972 /volatile:iso Volatile loads and stores have standard semantics
3973 /volatile:ms Volatile loads and stores have acquire and release semantics
3974 /W0 Disable all warnings
3978 /W4 Enable -Wall and -Wextra
3979 /Wall Enable -Weverything
3980 /WX- Do not treat warnings as errors
3981 /WX Treat warnings as errors
3982 /w Disable all warnings
3983 /X Don't add %INCLUDE% to the include search path
3984 /Y- Disable precompiled headers, overrides /Yc and /Yu
3985 /Yc<filename> Generate a pch file for all code up to and including <filename>
3986 /Yu<filename> Load a pch file and use it instead of all code up to and including <filename>
3987 /Z7 Enable CodeView debug information in object files
3988 /Zc:char8_t Enable C++2a char8_t type
3989 /Zc:char8_t- Disable C++2a char8_t type
3990 /Zc:dllexportInlines- Don't dllexport/dllimport inline member functions of dllexport/import classes
3991 /Zc:dllexportInlines dllexport/dllimport inline member functions of dllexport/import classes (default)
3992 /Zc:sizedDealloc- Disable C++14 sized global deallocation functions
3993 /Zc:sizedDealloc Enable C++14 sized global deallocation functions
3994 /Zc:strictStrings Treat string literals as const
3995 /Zc:threadSafeInit- Disable thread-safe initialization of static variables
3996 /Zc:threadSafeInit Enable thread-safe initialization of static variables
3997 /Zc:trigraphs- Disable trigraphs (default)
3998 /Zc:trigraphs Enable trigraphs
3999 /Zc:twoPhase- Disable two-phase name lookup in templates
4000 /Zc:twoPhase Enable two-phase name lookup in templates
4001 /Zi Alias for /Z7. Does not produce PDBs.
4002 /Zl Don't mention any default libraries in the object file
4003 /Zp Set the default maximum struct packing alignment to 1
4004 /Zp<value> Specify the default maximum struct packing alignment
4005 /Zs Run the preprocessor, parser and semantic analysis stages
4008 -### Print (but do not run) the commands to run for this compilation
4009 --analyze Run the static analyzer
4010 -faddrsig Emit an address-significance table
4011 -fansi-escape-codes Use ANSI escape codes for diagnostics
4012 -fblocks Enable the 'blocks' language feature
4013 -fcf-protection=<value> Instrument control-flow architecture protection. Options: return, branch, full, none.
4014 -fcf-protection Enable cf-protection in 'full' mode
4015 -fcolor-diagnostics Use colors in diagnostics
4016 -fcomplete-member-pointers
4017 Require member pointer base types to be complete if they would be significant under the Microsoft ABI
4018 -fcoverage-mapping Generate coverage mapping to enable code coverage analysis
4019 -fcrash-diagnostics-dir=<dir>
4020 Put crash-report files in <dir>
4021 -fdebug-macro Emit macro debug information
4022 -fdelayed-template-parsing
4023 Parse templated function definitions at the end of the translation unit
4024 -fdiagnostics-absolute-paths
4025 Print absolute paths in diagnostics
4026 -fdiagnostics-parseable-fixits
4027 Print fix-its in machine parseable form
4028 -flto=<value> Set LTO mode to either 'full' or 'thin'
4029 -flto Enable LTO in 'full' mode
4030 -fmerge-all-constants Allow merging of constants
4031 -fms-compatibility-version=<value>
4032 Dot-separated value representing the Microsoft compiler version
4033 number to report in _MSC_VER (0 = don't define it (default))
4034 -fms-compatibility Enable full Microsoft Visual C++ compatibility
4035 -fms-extensions Accept some non-standard constructs supported by the Microsoft compiler
4036 -fmsc-version=<value> Microsoft compiler version number to report in _MSC_VER
4037 (0 = don't define it (default))
4038 -fno-addrsig Don't emit an address-significance table
4039 -fno-builtin-<value> Disable implicit builtin knowledge of a specific function
4040 -fno-builtin Disable implicit builtin knowledge of functions
4041 -fno-complete-member-pointers
4042 Do not require member pointer base types to be complete if they would be significant under the Microsoft ABI
4043 -fno-coverage-mapping Disable code coverage analysis
4044 -fno-crash-diagnostics Disable auto-generation of preprocessed source files and a script for reproduction during a clang crash
4045 -fno-debug-macro Do not emit macro debug information
4046 -fno-delayed-template-parsing
4047 Disable delayed template parsing
4048 -fno-sanitize-address-poison-custom-array-cookie
4049 Disable poisoning array cookies when using custom operator new[] in AddressSanitizer
4050 -fno-sanitize-address-use-after-scope
4051 Disable use-after-scope detection in AddressSanitizer
4052 -fno-sanitize-address-use-odr-indicator
4053 Disable ODR indicator globals
4054 -fno-sanitize-ignorelist Don't use ignorelist file for sanitizers
4055 -fno-sanitize-cfi-cross-dso
4056 Disable control flow integrity (CFI) checks for cross-DSO calls.
4057 -fno-sanitize-coverage=<value>
4058 Disable specified features of coverage instrumentation for Sanitizers
4059 -fno-sanitize-memory-track-origins
4060 Disable origins tracking in MemorySanitizer
4061 -fno-sanitize-memory-use-after-dtor
4062 Disable use-after-destroy detection in MemorySanitizer
4063 -fno-sanitize-recover=<value>
4064 Disable recovery for specified sanitizers
4065 -fno-sanitize-stats Disable sanitizer statistics gathering.
4066 -fno-sanitize-thread-atomics
4067 Disable atomic operations instrumentation in ThreadSanitizer
4068 -fno-sanitize-thread-func-entry-exit
4069 Disable function entry/exit instrumentation in ThreadSanitizer
4070 -fno-sanitize-thread-memory-access
4071 Disable memory access instrumentation in ThreadSanitizer
4072 -fno-sanitize-trap=<value>
4073 Disable trapping for specified sanitizers
4074 -fno-standalone-debug Limit debug information produced to reduce size of debug binary
4075 -fobjc-runtime=<value> Specify the target Objective-C runtime kind and version
4076 -fprofile-exclude-files=<value>
4077 Instrument only functions from files where names don't match all the regexes separated by a semi-colon
4078 -fprofile-filter-files=<value>
4079 Instrument only functions from files where names match any regex separated by a semi-colon
4080 -fprofile-instr-generate=<file>
4081 Generate instrumented code to collect execution counts into <file>
4082 (overridden by LLVM_PROFILE_FILE env var)
4083 -fprofile-instr-generate
4084 Generate instrumented code to collect execution counts into default.profraw file
4085 (overridden by '=' form of option or LLVM_PROFILE_FILE env var)
4086 -fprofile-instr-use=<value>
4087 Use instrumentation data for profile-guided optimization
4088 -fprofile-remapping-file=<file>
4089 Use the remappings described in <file> to match the profile data against names in the program
4090 -fprofile-list=<file>
4091 Filename defining the list of functions/files to instrument
4092 -fsanitize-address-field-padding=<value>
4093 Level of field padding for AddressSanitizer
4094 -fsanitize-address-globals-dead-stripping
4095 Enable linker dead stripping of globals in AddressSanitizer
4096 -fsanitize-address-poison-custom-array-cookie
4097 Enable poisoning array cookies when using custom operator new[] in AddressSanitizer
4098 -fsanitize-address-use-after-return=<mode>
4099 Select the mode of detecting stack use-after-return in AddressSanitizer: never | runtime (default) | always
4100 -fsanitize-address-use-after-scope
4101 Enable use-after-scope detection in AddressSanitizer
4102 -fsanitize-address-use-odr-indicator
4103 Enable ODR indicator globals to avoid false ODR violation reports in partially sanitized programs at the cost of an increase in binary size
4104 -fsanitize-ignorelist=<value>
4105 Path to ignorelist file for sanitizers
4106 -fsanitize-cfi-cross-dso
4107 Enable control flow integrity (CFI) checks for cross-DSO calls.
4108 -fsanitize-cfi-icall-generalize-pointers
4109 Generalize pointers in CFI indirect call type signature checks
4110 -fsanitize-coverage=<value>
4111 Specify the type of coverage instrumentation for Sanitizers
4112 -fsanitize-hwaddress-abi=<value>
4113 Select the HWAddressSanitizer ABI to target (interceptor or platform, default interceptor)
4114 -fsanitize-memory-track-origins=<value>
4115 Enable origins tracking in MemorySanitizer
4116 -fsanitize-memory-track-origins
4117 Enable origins tracking in MemorySanitizer
4118 -fsanitize-memory-use-after-dtor
4119 Enable use-after-destroy detection in MemorySanitizer
4120 -fsanitize-recover=<value>
4121 Enable recovery for specified sanitizers
4122 -fsanitize-stats Enable sanitizer statistics gathering.
4123 -fsanitize-thread-atomics
4124 Enable atomic operations instrumentation in ThreadSanitizer (default)
4125 -fsanitize-thread-func-entry-exit
4126 Enable function entry/exit instrumentation in ThreadSanitizer (default)
4127 -fsanitize-thread-memory-access
4128 Enable memory access instrumentation in ThreadSanitizer (default)
4129 -fsanitize-trap=<value> Enable trapping for specified sanitizers
4130 -fsanitize-undefined-strip-path-components=<number>
4131 Strip (or keep only, if negative) a given number of path components when emitting check metadata.
4132 -fsanitize=<check> Turn on runtime checks for various forms of undefined or suspicious
4133 behavior. See user manual for available checks
4134 -fsplit-lto-unit Enables splitting of the LTO unit.
4135 -fstandalone-debug Emit full debug info for all types used by the program
4136 -fsyntax-only Run the preprocessor, parser and semantic analysis stages
4137 -fwhole-program-vtables Enables whole-program vtable optimization. Requires -flto
4138 -gcodeview-ghash Emit type record hashes in a .debug$H section
4139 -gcodeview Generate CodeView debug information
4140 -gline-directives-only Emit debug line info directives only
4141 -gline-tables-only Emit debug line number tables only
4142 -miamcu Use Intel MCU ABI
4143 -mllvm <value> Additional arguments to forward to LLVM's option processing
4144 -nobuiltininc Disable builtin #include directories
4145 -Qunused-arguments Don't emit warning for unused driver arguments
4146 -R<remark> Enable the specified remark
4147 --target=<value> Generate code for the given target
4148 --version Print version information
4149 -v Show commands to run and use verbose output
4150 -W<warning> Enable the specified warning
4151 -Xclang <arg> Pass <arg> to the clang compiler
4156 When clang-cl is run with a set of ``/clang:<arg>`` options, it will gather all
4157 of the ``<arg>`` arguments and process them as if they were passed to the clang
4158 driver. This mechanism allows you to pass flags that are not exposed in the
4159 clang-cl options or flags that have a different meaning when passed to the clang
4160 driver. Regardless of where they appear in the command line, the ``/clang:``
4161 arguments are treated as if they were passed at the end of the clang-cl command
4164 The /Zc:dllexportInlines- Option
4165 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4167 This causes the class-level `dllexport` and `dllimport` attributes to not apply
4168 to inline member functions, as they otherwise would. For example, in the code
4169 below `S::foo()` would normally be defined and exported by the DLL, but when
4170 using the ``/Zc:dllexportInlines-`` flag it is not:
4174 struct __declspec(dllexport) S {
4178 This has the benefit that the compiler doesn't need to emit a definition of
4179 `S::foo()` in every translation unit where the declaration is included, as it
4180 would otherwise do to ensure there's a definition in the DLL even if it's not
4181 used there. If the declaration occurs in a header file that's widely used, this
4182 can save significant compilation time and output size. It also reduces the
4183 number of functions exported by the DLL similarly to what
4184 ``-fvisibility-inlines-hidden`` does for shared objects on ELF and Mach-O.
4185 Since the function declaration comes with an inline definition, users of the
4186 library can use that definition directly instead of importing it from the DLL.
4188 Note that the Microsoft Visual C++ compiler does not support this option, and
4189 if code in a DLL is compiled with ``/Zc:dllexportInlines-``, the code using the
4190 DLL must be compiled in the same way so that it doesn't attempt to dllimport
4191 the inline member functions. The reverse scenario should generally work though:
4192 a DLL compiled without this flag (such as a system library compiled with Visual
4193 C++) can be referenced from code compiled using the flag, meaning that the
4194 referencing code will use the inline definitions instead of importing them from
4197 Also note that like when using ``-fvisibility-inlines-hidden``, the address of
4198 `S::foo()` will be different inside and outside the DLL, breaking the C/C++
4199 standard requirement that functions have a unique address.
4201 The flag does not apply to explicit class template instantiation definitions or
4202 declarations, as those are typically used to explicitly provide a single
4203 definition in a DLL, (dllexported instantiation definition) or to signal that
4204 the definition is available elsewhere (dllimport instantiation declaration). It
4205 also doesn't apply to inline members with static local variables, to ensure
4206 that the same instance of the variable is used inside and outside the DLL.
4208 Using this flag can cause problems when inline functions that would otherwise
4209 be dllexported refer to internal symbols of a DLL. For example:
4215 struct __declspec(dllimport) S {
4216 void foo() { internal(); }
4219 Normally, references to `S::foo()` would use the definition in the DLL from
4220 which it was exported, and which presumably also has the definition of
4221 `internal()`. However, when using ``/Zc:dllexportInlines-``, the inline
4222 definition of `S::foo()` is used directly, resulting in a link error since
4223 `internal()` is not available. Even worse, if there is an inline definition of
4224 `internal()` containing a static local variable, we will now refer to a
4225 different instance of that variable than in the DLL:
4229 inline int internal() { static int x; return x++; }
4231 struct __declspec(dllimport) S {
4232 int foo() { return internal(); }
4235 This could lead to very subtle bugs. Using ``-fvisibility-inlines-hidden`` can
4236 lead to the same issue. To avoid it in this case, make `S::foo()` or
4237 `internal()` non-inline, or mark them `dllimport/dllexport` explicitly.
4239 Finding Clang runtime libraries
4240 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4242 clang-cl supports several features that require runtime library support:
4244 - Address Sanitizer (ASan): ``-fsanitize=address``
4245 - Undefined Behavior Sanitizer (UBSan): ``-fsanitize=undefined``
4246 - Code coverage: ``-fprofile-instr-generate -fcoverage-mapping``
4247 - Profile Guided Optimization (PGO): ``-fprofile-instr-generate``
4248 - Certain math operations (int128 division) require the builtins library
4250 In order to use these features, the user must link the right runtime libraries
4251 into their program. These libraries are distributed alongside Clang in the
4252 library resource directory. Clang searches for the resource directory by
4253 searching relative to the Clang executable. For example, if LLVM is installed
4254 in ``C:\Program Files\LLVM``, then the profile runtime library will be located
4256 ``C:\Program Files\LLVM\lib\clang\11.0.0\lib\windows\clang_rt.profile-x86_64.lib``.
4258 For UBSan, PGO, and coverage, Clang will emit object files that auto-link the
4259 appropriate runtime library, but the user generally needs to help the linker
4260 (whether it is ``lld-link.exe`` or MSVC ``link.exe``) find the library resource
4261 directory. Using the example installation above, this would mean passing
4262 ``/LIBPATH:C:\Program Files\LLVM\lib\clang\11.0.0\lib\windows`` to the linker.
4263 If the user links the program with the ``clang`` or ``clang-cl`` drivers, the
4264 driver will pass this flag for them.
4266 If the linker cannot find the appropriate library, it will emit an error like
4269 $ clang-cl -c -fsanitize=undefined t.cpp
4271 $ lld-link t.obj -dll
4272 lld-link: error: could not open 'clang_rt.ubsan_standalone-x86_64.lib': no such file or directory
4273 lld-link: error: could not open 'clang_rt.ubsan_standalone_cxx-x86_64.lib': no such file or directory
4275 $ link t.obj -dll -nologo
4276 LINK : fatal error LNK1104: cannot open file 'clang_rt.ubsan_standalone-x86_64.lib'
4278 To fix the error, add the appropriate ``/libpath:`` flag to the link line.
4280 For ASan, as of this writing, the user is also responsible for linking against
4281 the correct ASan libraries.
4283 If the user is using the dynamic CRT (``/MD``), then they should add
4284 ``clang_rt.asan_dynamic-x86_64.lib`` to the link line as a regular input. For
4285 other architectures, replace x86_64 with the appropriate name here and below.
4287 If the user is using the static CRT (``/MT``), then different runtimes are used
4288 to produce DLLs and EXEs. To link a DLL, pass
4289 ``clang_rt.asan_dll_thunk-x86_64.lib``. To link an EXE, pass
4290 ``-wholearchive:clang_rt.asan-x86_64.lib``.