5507 lines · plain
1============================2Clang Compiler User's Manual3============================4 5.. include:: <isonum.txt>6 7.. contents::8 :local:9 10Introduction11============12 13The Clang Compiler is an open-source compiler for the C family of14programming languages, aiming to be the best-in-class implementation of15these languages. Clang builds on the LLVM optimizer and code generator,16allowing it to provide high-quality optimization and code generation17support for many targets. For more general information, please see the18`Clang Web Site <https://clang.llvm.org>`_ or the `LLVM Web19Site <https://llvm.org>`_.20 21This document describes important notes about using Clang as a compiler22for an end-user, documenting the supported features, command line23options, etc. If you are interested in using Clang to build a tool that24processes code, please see :doc:`InternalsManual`. If you are interested in the25`Clang Static Analyzer <https://clang-analyzer.llvm.org>`_, please see its web26page.27 28Clang is one component in a complete toolchain for C family languages.29A separate document describes the other pieces necessary to30:doc:`assemble a complete toolchain <Toolchain>`.31 32Clang is designed to support the C family of programming languages,33which includes :ref:`C <c>`, :ref:`Objective-C <objc>`, :ref:`C++ <cxx>`, and34:ref:`Objective-C++ <objcxx>` as well as many dialects of those. For35language-specific information, please see the corresponding language36specific section:37 38- :ref:`C Language <c>`: K&R C, ANSI C89, ISO C90, C94 (C89+AMD1), C99 (+TC1,39 TC2, TC3), C11, C17, C23, and C2y.40- :ref:`Objective-C Language <objc>`: ObjC 1, ObjC 2, ObjC 2.1, plus41 variants depending on base language.42- :ref:`C++ Language <cxx>`: C++98, C++03, C++11, C++14, C++17, C++20, C++23,43 and C++26.44- :ref:`Objective C++ Language <objcxx>`45- :ref:`OpenCL Kernel Language <opencl>`: OpenCL C 1.0, 1.1, 1.2, 2.0, 3.0,46 and C++ for OpenCL 1.0 and 2021.47 48In addition to these base languages and their dialects, Clang supports a49broad variety of language extensions, which are documented in the50corresponding language section. These extensions are provided to be51compatible with the GCC, Microsoft, and other popular compilers as well52as to improve functionality through Clang-specific features. The Clang53driver and language features are intentionally designed to be as54compatible with the GNU GCC compiler as reasonably possible, easing55migration from GCC to Clang. In most cases, code "just works".56Clang also provides an alternative driver, :ref:`clang-cl`, that is designed57to be compatible with the Visual C++ compiler, cl.exe.58 59In addition to language-specific features, Clang has a variety of60features that depend on what CPU architecture or operating system is61being compiled for. Please see the :ref:`Target-Specific Features and62Limitations <target_features>` section for more details.63 64.. _terminology:65 66Terminology67-----------68* Lexer -- the part of the compiler responsible for converting source code into69 abstract representations called tokens.70* Preprocessor -- the part of the compiler responsible for in-place textual71 replacement of source constructs. When the lexer is required to produce a72 token, it will run the preprocessor while determining which token to produce.73 In other words, when the lexer encounters something like `#include` or a macro74 name, the preprocessor will be used to perform the inclusion or expand the75 macro name into its replacement list, and return the resulting non-preprocessor76 token.77* Parser -- the part of the compiler responsible for determining syntactic78 correctness of the source code. The parser will request tokens from the lexer79 and after performing semantic analysis of the production, generates an80 abstract representation of the source called an AST.81* Sema -- the part of the compiler responsible for determining semantic82 correctness of the source code. It is closely related to the parser and is83 where many diagnostics are produced.84* Diagnostic -- a message to the user about properties of the source code. For85 example, errors or warnings and their associated notes.86* Undefined behavior -- behavior for which the standard imposes no requirements87 on how the code behaves. Generally speaking, undefined behavior is a bug in88 the user's code. However, it can also be a place for the compiler to define89 the behavior, called an extension.90* Optimizer -- the part of the compiler responsible for transforming code to91 have better performance characteristics without changing the semantics of how92 the code behaves. Note, the optimizer assumes the code has no undefined93 behavior, so if the code does contain undefined behavior, it will often behave94 differently depending on which optimization level is enabled.95* Frontend -- the Lexer, Preprocessor, Parser, Sema, and LLVM IR code generation96 parts of the compiler.97* Middle-end -- a term used for the of the subset of the backend that does98 (typically not target specific) optimizations prior to assembly code99 generation.100* Backend -- the parts of the compiler which run after LLVM IR code generation,101 such as the optimizer and generation of assembly code.102 103See the :doc:`InternalsManual` for more details about the internal construction104of the compiler.105 106Support107-------108Clang releases happen roughly `every six months <https://llvm.org/docs/HowToReleaseLLVM.html#annual-release-schedule>`_.109Only the current public release is officially supported. Bug-fix releases for110the current release will be produced on an as-needed basis, but bug fixes are111not backported to releases older than the current one.112 113 114Command Line Options115====================116 117This section is generally an index into other sections. It does not go118into depth on the ones that are covered by other sections. However, the119first part introduces the language selection and other high level120options like :option:`-c`, :option:`-g`, etc.121 122Options to Control Error and Warning Messages123---------------------------------------------124 125.. option:: -Werror126 127 Turn warnings into errors.128 129.. This is in plain monospaced font because it generates the same label as130.. -Werror, and Sphinx complains.131 132``-Werror=foo``133 134 Turn warning "foo" into an error.135 136.. option:: -Wno-error=foo137 138 Turn warning "foo" into a warning even if :option:`-Werror` is specified.139 140.. option:: -Wfoo141 142 Enable warning "foo".143 See the :doc:`diagnostics reference <DiagnosticsReference>` for a complete144 list of the warning flags that can be specified in this way.145 146.. option:: -Wno-foo147 148 Disable warning "foo".149 150.. option:: -w151 152 Disable all diagnostics.153 154.. option:: -Weverything155 156 :ref:`Enable all diagnostics. <diagnostics_enable_everything>`157 158.. option:: -pedantic159 160 Warn on language extensions.161 162.. option:: -pedantic-errors163 164 Error on language extensions.165 166.. option:: -Wsystem-headers167 168 Enable warnings from system headers.169 170.. option:: -ferror-limit=123171 172 Stop emitting diagnostics after 123 errors have been produced. The default is173 20, and the error limit can be disabled with `-ferror-limit=0`.174 175.. option:: -ftemplate-backtrace-limit=123176 177 Only emit up to 123 template instantiation notes within the template178 instantiation backtrace for a single warning or error. The default is 10, and179 the limit can be disabled with `-ftemplate-backtrace-limit=0`.180 181.. option:: --warning-suppression-mappings=foo.txt182 183 :ref:`Suppress certain diagnostics for certain files. <warning_suppression_mappings>`184 185.. _cl_diag_formatting:186 187Formatting of Diagnostics188^^^^^^^^^^^^^^^^^^^^^^^^^189 190Clang aims to produce beautiful diagnostics by default, particularly for191new users that first come to Clang. However, different people have192different preferences, and sometimes Clang is driven not by a human,193but by a program that wants consistent and easily parsable output. For194these cases, Clang provides a wide range of options to control the exact195output format of the diagnostics that it generates.196 197.. _opt_fshow-column:198 199.. option:: -f[no-]show-column200 201 Print column number in diagnostic.202 203 This option, which defaults to on, controls whether or not Clang204 prints the column number of a diagnostic. For example, when this is205 enabled, Clang will print something like:206 207 ::208 209 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]210 #endif bad211 ^212 //213 214 When this is disabled, Clang will print "test.c:28: warning..." with215 no column number.216 217 The printed column numbers count bytes from the beginning of the218 line; take care if your source contains multibyte characters.219 220.. _opt_fshow-source-location:221 222.. option:: -f[no-]show-source-location223 224 Print source file/line/column information in diagnostic.225 226 This option, which defaults to on, controls whether or not Clang227 prints the filename, line number and column number of a diagnostic.228 For example, when this is enabled, Clang will print something like:229 230 ::231 232 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]233 #endif bad234 ^235 //236 237 When this is disabled, Clang will not print the "test.c:28:8: "238 part.239 240.. _opt_fcaret-diagnostics:241 242.. option:: -f[no-]caret-diagnostics243 244 Print source line and ranges from source code in diagnostic.245 This option, which defaults to on, controls whether or not Clang246 prints the source line, source ranges, and caret when emitting a247 diagnostic. For example, when this is enabled, Clang will print248 something like:249 250 ::251 252 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]253 #endif bad254 ^255 //256 257.. option:: -f[no-]color-diagnostics258 259 This option, which defaults to on when a color-capable terminal is260 detected, controls whether or not Clang prints diagnostics in color.261 262 When this option is enabled, Clang will use colors to highlight263 specific parts of the diagnostic, e.g.,264 265 .. nasty hack to not lose our dignity266 267 .. raw:: html268 269 <pre>270 <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>271 #endif bad272 <span style="color:green">^</span>273 <span style="color:green">//</span>274 </pre>275 276 When this is disabled, Clang will just print:277 278 ::279 280 test.c:2:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]281 #endif bad282 ^283 //284 285 If the ``NO_COLOR`` environment variable is defined and not empty286 (regardless of value), color diagnostics are disabled. If ``NO_COLOR`` is287 defined and ``-fcolor-diagnostics`` is passed on the command line, Clang288 will honor the command line argument.289 290.. option:: -fansi-escape-codes291 292 Controls whether ANSI escape codes are used instead of the Windows Console293 API to output colored diagnostics. This option is only used on Windows and294 defaults to off.295 296.. option:: -fdiagnostics-format=clang/msvc/vi297 298 Changes diagnostic output format to better match IDEs and command line tools.299 300 This option controls the output format of the filename, line number,301 and column printed in diagnostic messages. The options, and their302 effect on formatting a simple conversion diagnostic, follow:303 304 **clang** (default)305 ::306 307 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int'308 309 **msvc**310 ::311 312 t.c(3,11) : warning: conversion specifies type 'char *' but the argument has type 'int'313 314 **vi**315 ::316 317 t.c +3:11: warning: conversion specifies type 'char *' but the argument has type 'int'318 319.. _opt_fdiagnostics-show-option:320 321.. option:: -f[no-]diagnostics-show-option322 323 Enable ``[-Woption]`` information in diagnostic line.324 325 This option, which defaults to on, controls whether or not Clang326 prints the associated :ref:`warning group <cl_diag_warning_groups>`327 option name when outputting a warning diagnostic. For example, in328 this output:329 330 ::331 332 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]333 #endif bad334 ^335 //336 337 Passing **-fno-diagnostics-show-option** will prevent Clang from338 printing the [:option:`-Wextra-tokens`] information in339 the diagnostic. This information tells you the flag needed to enable340 or disable the diagnostic, either from the command line or through341 :ref:`#pragma GCC diagnostic <pragma_GCC_diagnostic>`.342 343.. option:: -fdiagnostics-show-category=none/id/name344 345 Enable printing category information in diagnostic line.346 347 This option, which defaults to "none", controls whether or not Clang348 prints the category associated with a diagnostic when emitting it.349 Each diagnostic may or may not have an associated category, if it350 has one, it is listed in the diagnostic categorization field of the351 diagnostic line (in the []'s).352 353 For example, a format string warning will produce these three354 renditions based on the setting of this option:355 356 ::357 358 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat]359 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat,1]360 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat,Format String]361 362 This category can be used by clients that want to group diagnostics363 by category, so it should be a high-level category. We want dozens364 of these, not hundreds or thousands of them.365 366.. _opt_fsave-optimization-record:367 368.. option:: -f[no-]save-optimization-record[=<format>]369 370 Enable optimization remarks during compilation and write them to a separate371 file.372 373 This option, which defaults to off, controls whether Clang writes374 optimization reports to a separate file. By recording diagnostics in a file,375 users can parse or sort the remarks in a convenient way.376 377 By default, the serialization format is YAML.378 379 The supported serialization formats are:380 381 - .. _opt_fsave_optimization_record_yaml:382 383 ``-fsave-optimization-record=yaml``: A structured YAML format.384 385 - .. _opt_fsave_optimization_record_bitstream:386 387 ``-fsave-optimization-record=bitstream``: A binary format based on LLVM388 Bitstream.389 390 The output file is controlled by :option:`-foptimization-record-file`.391 392 In the absence of an explicit output file, the file is chosen using the393 following scheme:394 395 ``<base>.opt.<format>``396 397 where ``<base>`` is based on the output file of the compilation (whether398 it's explicitly specified through `-o` or not) when used with `-c` or `-S`.399 For example:400 401 * ``clang -fsave-optimization-record -c in.c -o out.o`` will generate402 ``out.opt.yaml``403 404 * ``clang -fsave-optimization-record -c in.c`` will generate405 ``in.opt.yaml``406 407 When targeting (Thin)LTO, the base is derived from the output filename, and408 the extension is not dropped.409 410 When targeting ThinLTO, the following scheme is used:411 412 ``<base>.opt.<format>.thin.<num>.<format>``413 414 Darwin-only: when used for generating a linked binary from a source file415 (through an intermediate object file), the driver will invoke `cc1` to416 generate a temporary object file. The temporary remark file will be emitted417 next to the object file, which will then be picked up by `dsymutil` and418 emitted in the .dSYM bundle. This is available for all formats except YAML.419 420 For example:421 422 ``clang -fsave-optimization-record=bitstream in.c -o out`` will generate423 424 * ``/var/folders/43/9y164hh52tv_2nrdxrj31nyw0000gn/T/a-9be59b.o``425 426 * ``/var/folders/43/9y164hh52tv_2nrdxrj31nyw0000gn/T/a-9be59b.opt.bitstream``427 428 * ``out``429 430 * ``out.dSYM/Contents/Resources/Remarks/out``431 432 Darwin-only: compiling for multiple architectures will use the following433 scheme:434 435 ``<base>-<arch>.opt.<format>``436 437 Note that this is incompatible with passing the438 :option:`-foptimization-record-file` option.439 440.. option:: -foptimization-record-file441 442 Control the file to which optimization reports are written. This implies443 :ref:`-fsave-optimization-record <opt_fsave-optimization-record>`.444 445 On Darwin platforms, this is incompatible with passing multiple446 ``-arch <arch>`` options.447 448.. option:: -foptimization-record-passes449 450 Only include passes which match a specified regular expression.451 452 When optimization reports are being output (see453 :ref:`-fsave-optimization-record <opt_fsave-optimization-record>`), this454 option controls the passes that will be included in the final report.455 456 If this option is not used, all the passes are included in the optimization457 record.458 459.. _opt_fdiagnostics-show-hotness:460 461.. option:: -f[no-]diagnostics-show-hotness462 463 Enable profile hotness information in diagnostic line.464 465 This option controls whether Clang prints the profile hotness associated466 with diagnostics in the presence of profile-guided optimization information.467 This is currently supported with optimization remarks (see468 :ref:`Options to Emit Optimization Reports <rpass>`). The hotness information469 allows users to focus on the hot optimization remarks that are likely to be470 more relevant for run-time performance.471 472 For example, in this output, the block containing the callsite of `foo` was473 executed 3000 times according to the profile data:474 475 ::476 477 s.c:7:10: remark: foo inlined into bar (hotness: 3000) [-Rpass-analysis=inline]478 sum += foo(x, x - 2);479 ^480 481 This option is implied when482 :ref:`-fsave-optimization-record <opt_fsave-optimization-record>` is used.483 Otherwise, it defaults to off.484 485.. option:: -fdiagnostics-hotness-threshold486 487 Prevent optimization remarks from being output if they do not have at least488 this hotness value.489 490 This option, which defaults to zero, controls the minimum hotness an491 optimization remark would need in order to be output by Clang. This is492 currently supported with optimization remarks (see :ref:`Options to Emit493 Optimization Reports <rpass>`) when profile hotness information in494 diagnostics is enabled (see495 :ref:`-fdiagnostics-show-hotness <opt_fdiagnostics-show-hotness>`).496 497.. _opt_fdiagnostics-fixit-info:498 499.. option:: -f[no-]diagnostics-fixit-info500 501 Enable "FixIt" information in the diagnostics output.502 503 This option, which defaults to on, controls whether or not Clang504 prints the information on how to fix a specific diagnostic505 underneath it when it knows. For example, in this output:506 507 ::508 509 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]510 #endif bad511 ^512 //513 514 Passing **-fno-diagnostics-fixit-info** will prevent Clang from515 printing the "//" line at the end of the message. This information516 is useful for users who may not understand what is wrong, but can be517 confusing for machine parsing.518 519.. _opt_fdiagnostics-print-source-range-info:520 521.. option:: -fdiagnostics-print-source-range-info522 523 Print machine parsable information about source ranges.524 This option makes Clang print information about source ranges in a machine525 parsable format after the file/line/column number information. The526 information is a simple sequence of brace enclosed ranges, where each range527 lists the start and end line/column locations. For example, in this output:528 529 ::530 531 exprs.c:47:15:{47:8-47:14}{47:17-47:24}: error: invalid operands to binary expression ('int *' and '_Complex float')532 P = (P-42) + Gamma*4;533 ~~~~~~ ^ ~~~~~~~534 535 The {}'s are generated by -fdiagnostics-print-source-range-info.536 537 The printed column numbers count bytes from the beginning of the538 line; take care if your source contains multibyte characters.539 540.. option:: -fdiagnostics-parseable-fixits541 542 Print Fix-Its in a machine parseable form.543 544 This option makes Clang print available Fix-Its in a machine545 parseable format at the end of diagnostics. The following example546 illustrates the format:547 548 ::549 550 fix-it:"t.cpp":{7:25-7:29}:"Gamma"551 552 The range printed is a half-open range, so in this example the553 characters at column 25 up to but not including column 29 on line 7554 in t.cpp should be replaced with the string "Gamma". Either the555 range or the replacement string may be empty (representing strict556 insertions and strict erasures, respectively). Both the file name557 and the insertion string escape backslash (as "\\\\"), tabs (as558 "\\t"), newlines (as "\\n"), double quotes(as "\\"") and559 non-printable characters (as octal "\\xxx").560 561 The printed column numbers count bytes from the beginning of the562 line; take care if your source contains multibyte characters.563 564.. option:: -fno-elide-type565 566 Turns off elision in template type printing.567 568 The default for template type printing is to elide as many template569 arguments as possible, removing those which are the same in both570 template types, leaving only the differences. Adding this flag will571 print all the template arguments. If supported by the terminal,572 highlighting will still appear on differing arguments.573 574 Default:575 576 ::577 578 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;579 580 -fno-elide-type:581 582 ::583 584 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;585 586.. option:: -fdiagnostics-show-template-tree587 588 Template type diffing prints a text tree.589 590 For diffing large templated types, this option will cause Clang to591 display the templates as an indented text tree, one argument per592 line, with differences marked inline. This is compatible with593 -fno-elide-type.594 595 Default:596 597 ::598 599 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;600 601 With :option:`-fdiagnostics-show-template-tree`:602 603 ::604 605 t.cc:4:5: note: candidate function not viable: no known conversion for 1st argument;606 vector<607 map<608 [...],609 map<610 [float != double],611 [...]>>>612 613 614.. option:: -fcaret-diagnostics-max-lines:615 616 Controls how many lines of code clang prints for diagnostics. By default,617 clang prints a maximum of 16 lines of code.618 619 620.. option:: -fdiagnostics-show-line-numbers:621 622 Controls whether clang will print a margin containing the line number on623 the left of each line of code it prints for diagnostics.624 625 Default:626 627 ::628 629 test.cpp:5:1: error: 'main' must return 'int'630 5 | void main() {}631 | ^~~~632 | int633 634 635 With -fno-diagnostics-show-line-numbers:636 637 ::638 639 test.cpp:5:1: error: 'main' must return 'int'640 void main() {}641 ^~~~642 int643 644 645 646.. _cl_diag_warning_groups:647 648Individual Warning Groups649^^^^^^^^^^^^^^^^^^^^^^^^^650 651TODO: Generate this from tblgen. Define one anchor per warning group.652 653.. option:: -Wextra-tokens654 655 Warn about excess tokens at the end of a preprocessor directive.656 657 This option, which defaults to on, enables warnings about extra658 tokens at the end of preprocessor directives. For example:659 660 ::661 662 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]663 #endif bad664 ^665 666 These extra tokens are not strictly conforming, and are usually best667 handled by commenting them out.668 669.. option:: -Wambiguous-member-template670 671 Warn about unqualified uses of a member template whose name resolves to672 another template at the location of the use.673 674 This option, which defaults to on, enables a warning in the675 following code:676 677 ::678 679 template<typename T> struct set{};680 template<typename T> struct trait { typedef const T& type; };681 struct Value {682 template<typename T> void set(typename trait<T>::type value) {}683 };684 void foo() {685 Value v;686 v.set<double>(3.2);687 }688 689 C++ [basic.lookup.classref] requires this to be an error, but,690 because it's hard to work around, Clang downgrades it to a warning691 as an extension.692 693.. option:: -Wbind-to-temporary-copy694 695 Warn about an unusable copy constructor when binding a reference to a696 temporary.697 698 This option enables warnings about binding a699 reference to a temporary when the temporary doesn't have a usable700 copy constructor. For example:701 702 ::703 704 struct NonCopyable {705 NonCopyable();706 private:707 NonCopyable(const NonCopyable&);708 };709 void foo(const NonCopyable&);710 void bar() {711 foo(NonCopyable()); // Disallowed in C++98; allowed in C++11.712 }713 714 ::715 716 struct NonCopyable2 {717 NonCopyable2();718 NonCopyable2(NonCopyable2&);719 };720 void foo(const NonCopyable2&);721 void bar() {722 foo(NonCopyable2()); // Disallowed in C++98; allowed in C++11.723 }724 725 Note that if ``NonCopyable2::NonCopyable2()`` has a default argument726 whose instantiation produces a compile error, that error will still727 be a hard error in C++98 mode even if this warning is turned off.728 729Options to Control Clang Crash Diagnostics730------------------------------------------731 732As unbelievable as it may sound, Clang does crash from time to time.733Generally, this only occurs to those living on the `bleeding734edge <https://llvm.org/releases/download.html#svn>`_. Clang goes to great735lengths to assist you in filing a bug report. Specifically, Clang736generates preprocessed source file(s) and associated run script(s) upon737a crash. These files should be attached to a bug report to ease738reproducibility of the failure. Below are the command line options to739control the crash diagnostics.740 741.. option:: -fcrash-diagnostics=<val>742 743 Valid values are:744 745 * ``off`` (Disable auto-generation of preprocessed source files during a clang crash.)746 * ``compiler`` (Generate diagnostics for compiler crashes (default))747 * ``all`` (Generate diagnostics for all tools which support it)748 749.. option:: -fno-crash-diagnostics750 751 Disable auto-generation of preprocessed source files during a clang crash.752 753 The ``-fno-crash-diagnostics`` flag can be helpful for speeding the process754 of generating a delta reduced test case.755 756.. option:: -fcrash-diagnostics-dir=<dir>757 758 Specify where to write the crash diagnostics files; defaults to the759 usual location for temporary files.760 761.. envvar:: CLANG_CRASH_DIAGNOSTICS_DIR=<dir>762 763 Like ``-fcrash-diagnostics-dir=<dir>``, specifies where to write the764 crash diagnostics files, but with lower precedence than the option.765 766Clang is also capable of generating preprocessed source file(s) and associated767run script(s) even without a crash. This is especially useful when trying to768generate a reproducer for warnings or errors while using modules.769 770.. option:: -gen-reproducer771 772 Generates preprocessed source files, a reproducer script and if relevant, a773 cache containing: built module pcm's and all headers needed to rebuild the774 same modules.775 776.. _rpass:777 778Options to Emit Optimization Reports779------------------------------------780 781Optimization reports trace, at a high-level, all the major decisions782made by compiler transformations. For instance, when the inliner783decides to inline function ``foo()`` into ``bar()``, or the loop unroller784decides to unroll a loop N times, or the vectorizer decides to785vectorize a loop body.786 787Clang offers a family of flags which the optimizers can use to emit788a diagnostic in three cases:789 7901. When the pass makes a transformation (`-Rpass`).791 7922. When the pass fails to make a transformation (`-Rpass-missed`).793 7943. When the pass determines whether or not to make a transformation795 (`-Rpass-analysis`).796 797NOTE: Although the discussion below focuses on `-Rpass`, the exact798same options apply to `-Rpass-missed` and `-Rpass-analysis`.799 800Since there are dozens of passes inside the compiler, each of these flags801take a regular expression that identifies the name of the pass which should802emit the associated diagnostic. For example, to get a report from the inliner,803compile the code with:804 805.. code-block:: console806 807 $ clang -O2 -Rpass=inline code.cc -o code808 code.cc:4:25: remark: foo inlined into bar [-Rpass=inline]809 int bar(int j) { return foo(j, j - 2); }810 ^811 812Note that remarks from the inliner are identified with `[-Rpass=inline]`.813To request a report from every optimization pass, you should use814`-Rpass=.*` (in fact, you can use any valid POSIX regular815expression). However, do not expect a report from every transformation816made by the compiler. Optimization remarks do not really make sense817outside of the major transformations (e.g., inlining, vectorization,818loop optimizations) and not every optimization pass supports this819feature.820 821Note that when using profile-guided optimization information, profile hotness822information can be included in the remarks (see823:ref:`-fdiagnostics-show-hotness <opt_fdiagnostics-show-hotness>`).824 825Current limitations826^^^^^^^^^^^^^^^^^^^827 8281. Optimization remarks that refer to function names will display the829 mangled name of the function. Since these remarks are emitted by the830 back end of the compiler, it does not know anything about the input831 language, nor its mangling rules.832 8332. Some source locations are not displayed correctly. The front end has834 a more detailed source location tracking than the locations included835 in the debug info (e.g., the front end can locate code inside macro836 expansions). However, the locations used by `-Rpass` are837 translated from debug annotations. That translation can be lossy,838 which results in some remarks having no location information.839 840Options to Emit Resource Consumption Reports841--------------------------------------------842 843These are options that report execution time and consumed memory of different844compilations steps.845 846.. option:: -fproc-stat-report=847 848 This option requests the driver to print used memory and execution time of each849 compilation step. The ``clang`` driver during execution calls different tools,850 like compiler, assembler, linker etc. With this option the driver reports851 total execution time, the execution time spent in user mode and peak memory852 usage of each called tool. Value of the option specifies where the report853 is sent to. If it specifies a regular file, the data are saved to this file in854 CSV format:855 856 .. code-block:: console857 858 $ clang -fproc-stat-report=abc foo.c859 $ cat abc860 clang-11,"/tmp/foo-123456.o",92000,84000,87536861 ld,"a.out",900,8000,53568862 863 The data on each row represent:864 865 * file name of the tool executable,866 * output file name in quotes,867 * total execution time in microseconds,868 * execution time in user mode in microseconds,869 * peak memory usage in Kb.870 871 It is possible to specify this option without any value. In this case statistics872 are printed on standard output in human-readable format:873 874 .. code-block:: console875 876 $ clang -fproc-stat-report foo.c877 clang-11: output=/tmp/foo-855a8e.o, total=68.000 ms, user=60.000 ms, mem=86920 Kb878 ld: output=a.out, total=8.000 ms, user=4.000 ms, mem=52320 Kb879 880 The report file specified in the option is locked for write, so this option881 can be used to collect statistics in parallel builds. The report file is not882 cleared, new data is appended to it, thus making possible to accumulate build883 statistics.884 885 You can also use environment variables to control the process statistics reporting.886 Setting ``CC_PRINT_PROC_STAT`` to ``1`` enables the feature, the report goes to887 stdout in human-readable format.888 Setting ``CC_PRINT_PROC_STAT_FILE`` to a fully qualified file path makes it report889 process statistics to the given file in the CSV format. Specifying a relative890 path will likely lead to multiple files with the same name created in different891 directories, since the path is relative to a changing working directory.892 893 These environment variables are handy when you need to request the statistics894 report without changing your build scripts or alter the existing set of compiler895 options. Note that ``-fproc-stat-report`` take precedence over ``CC_PRINT_PROC_STAT``896 and ``CC_PRINT_PROC_STAT_FILE``.897 898 .. code-block:: console899 900 $ export CC_PRINT_PROC_STAT=1901 $ export CC_PRINT_PROC_STAT_FILE=~/project-build-proc-stat.csv902 $ make903 904Other Options905-------------906Clang options that don't fit neatly into other categories.907 908.. option:: -fgnuc-version=909 910 This flag controls the value of ``__GNUC__`` and related macros. This flag911 does not enable or disable any GCC extensions implemented in Clang. Setting912 the version to zero causes Clang to leave ``__GNUC__`` and other913 GNU-namespaced macros, such as ``__GXX_WEAK__``, undefined.914 915.. option:: -MV916 917 When emitting a dependency file, use formatting conventions appropriate918 for NMake or Jom. Ignored unless another option causes Clang to emit a919 dependency file.920 921 When Clang emits a dependency file (e.g., you supplied the -M option)922 most filenames can be written to the file without any special formatting.923 Different Make tools will treat different sets of characters as "special"924 and use different conventions for telling the Make tool that the character925 is actually part of the filename. Normally, Clang uses backslash to "escape"926 a special character, which is the convention used by GNU Make. The -MV927 option tells Clang to put double-quotes around the entire filename, which928 is the convention used by NMake and Jom.929 930.. option:: -femit-dwarf-unwind=<value>931 932 When to emit DWARF unwind (EH frame) info. This is a Mach-O-specific option.933 934 Valid values are:935 936 * ``no-compact-unwind`` - Only emit DWARF unwind when compact unwind encodings937 aren't available. This is the default for arm64.938 * ``always`` - Always emit DWARF unwind regardless.939 * ``default`` - Use the platform-specific default (``always`` for all940 non-arm64-platforms).941 942 ``no-compact-unwind`` is a performance optimization -- Clang will emit smaller943 object files that are more quickly processed by the linker. This may cause944 binary compatibility issues on older x86_64 targets, however, so use it with945 caution.946 947.. option:: -fdisable-block-signature-string948 949 Instruct clang not to emit the signature string for blocks. Disabling the950 string can potentially break existing code that relies on it. Users should951 carefully consider this possibility when using the flag.952 953.. _configuration-files:954 955Configuration files956-------------------957 958Configuration files group command-line options and allow all of them to be959specified just by referencing the configuration file. They may be used, for960example, to collect options required to tune compilation for a particular961target, such as ``-L``, ``-I``, ``-l``, ``--sysroot``, codegen options, etc.962 963Configuration files can be either specified on the command line or loaded964from default locations. If both variants are present, the default configuration965files are loaded first.966 967The command line option ``--config=`` can be used to specify explicit968configuration files in a Clang invocation. If the option is used multiple times,969all specified files are loaded, in order. For example:970 971::972 973 clang --config=/home/user/cfgs/testing.txt974 clang --config=debug.cfg --config=runtimes.cfg975 976If the provided argument contains a directory separator, it is considered as977a file path, and options are read from that file. Otherwise the argument is978treated as a file name and is searched for sequentially in the directories:979 980 - user directory,981 - system directory,982 - the directory where Clang executable resides.983 984Both user and system directories for configuration files can be specified985either during build or during runtime. At build time, use986``CLANG_CONFIG_FILE_USER_DIR`` and ``CLANG_CONFIG_FILE_SYSTEM_DIR``. At run987time use the ``--config-user-dir=`` and ``--config-system-dir=`` command line988options. Specifying config directories at runtime overrides the config989directories set at build time. The first file found is used. It is an error if990the required file cannot be found.991 992The default configuration files are searched for in the same directories993following the rules described in the next paragraphs. Loading default994configuration files can be disabled entirely via passing995the ``--no-default-config`` flag.996 997First, the algorithm searches for a configuration file named998``<triple>-<driver>.cfg`` where `triple` is the triple for the target being999built, and `driver` is the name of the currently used driver. The algorithm1000first attempts to use the canonical name for the driver used, then falls back1001to the one found in the executable name.1002 1003The following canonical driver names are used:1004 1005- ``clang`` for the ``gcc`` driver (used to compile C programs)1006- ``clang++`` for the ``gxx`` driver (used to compile C++ programs)1007- ``clang-cpp`` for the ``cpp`` driver (pure preprocessor)1008- ``clang-cl`` for the ``cl`` driver1009- ``flang`` for the ``flang`` driver1010- ``clang-dxc`` for the ``dxc`` driver1011 1012For example, when calling ``x86_64-pc-linux-gnu-clang-g++``,1013the driver will first attempt to use the configuration file named::1014 1015 x86_64-pc-linux-gnu-clang++.cfg1016 1017If this file is not found, it will attempt to use the name found1018in the executable instead::1019 1020 x86_64-pc-linux-gnu-clang-g++.cfg1021 1022Note that options such as ``--driver-mode=``, ``--target=``, ``-m32`` affect1023the search algorithm. For example, the aforementioned executable called with1024``-m32`` argument will instead search for::1025 1026 i386-pc-linux-gnu-clang++.cfg1027 1028If none of the aforementioned files are found, the driver will instead search1029for separate driver and target configuration files and attempt to load both.1030The former is named ``<driver>.cfg`` while the latter is named1031``<triple>.cfg``. Similarly to the previous variants, the canonical driver name1032will be preferred, and the compiler will fall back to the actual name.1033 1034For example, ``x86_64-pc-linux-gnu-clang-g++`` will attempt to load two1035configuration files named respectively::1036 1037 clang++.cfg1038 x86_64-pc-linux-gnu.cfg1039 1040with fallback to trying::1041 1042 clang-g++.cfg1043 x86_64-pc-linux-gnu.cfg1044 1045It is not an error if either of these files is not found.1046 1047The configuration file consists of command-line options specified on one or1048more lines. Lines composed of whitespace characters only are ignored as well as1049lines in which the first non-blank character is ``#``. Long options may be split1050between several lines by a trailing backslash. Here is an example of a1051configuration file:1052 1053::1054 1055 # Several options on line1056 -c --target=x86_64-unknown-linux-gnu1057 1058 # Long option split between lines1059 -I/usr/lib/gcc/x86_64-linux-gnu/5.4.0/../../../../\1060 include/c++/5.4.01061 1062 # other config files may be included1063 @linux.options1064 1065Files included by ``@file`` directives in configuration files are resolved1066relative to the including file. For example, if a configuration file1067``~/.llvm/target.cfg`` contains the directive ``@os/linux.opts``, the file1068``linux.opts`` is searched for in the directory ``~/.llvm/os``. Another way to1069include a file content is using the command line option ``--config=``. It works1070similarly but the included file is searched for using the rules for configuration1071files.1072 1073To generate paths relative to the configuration file, the ``<CFGDIR>`` token may1074be used. This will expand to the absolute path of the directory containing the1075configuration file.1076 1077In cases where a configuration file is deployed alongside SDK contents, the1078SDK directory can remain fully portable by using ``<CFGDIR>`` prefixed paths.1079In this way, the user may only need to specify a root configuration file with1080``--config=`` to establish every aspect of the SDK with the compiler:1081 1082::1083 1084 --target=foo1085 -isystem <CFGDIR>/include1086 -L <CFGDIR>/lib1087 -T <CFGDIR>/ldscripts/link.ld1088 1089Usually, config file options are placed before command-line options, regardless1090of the actual operation to be performed. The exception is being made for the1091options prefixed with the ``$`` character. These will be used only when the linker1092is being invoked, and added after all of the command-line specified linker1093inputs. Here is an example of ``$``-prefixed options:1094 1095::1096 1097 $-Wl,-Bstatic $-lm1098 $-Wl,-Bshared1099 1100Language and Target-Independent Features1101========================================1102 1103Freestanding Builds1104-------------------1105Passing the ``-ffreestanding`` flag causes Clang to build for a freestanding1106(rather than a hosted) environment. The flag has the following effects:1107 1108* the ``__STDC_HOSTED__`` predefined macro will expand to ``0``,1109* builtin functions are disabled by default (``-fno-builtins``),1110* unwind tables are disabled by default 1111 (``fno-asynchronous-unwind-tables -fno-unwind-tables``), and1112* does not treat the global ``main`` function as a special function.1113 1114An implementation of the following runtime library functions must always be1115provided with the usual semantics, as Clang will generate calls to them:1116 1117* ``memcpy``,1118* ``memmove``, and1119* ``memset``.1120 1121Clang does not, by itself, provide a full "conforming freestanding1122implementation". If you wish to have a conforming freestanding implementation,1123you must provide a freestanding C library. While Clang provides some of the1124required header files, it does not provide all of them, nor any library1125implementations.1126 1127Conversely, when ``-ffreestanding`` is specified, Clang does not require you to1128provide a conforming freestanding implementation library. Clang will not make1129any assumptions as to the availability or semantics of standard-library1130functions other than those mentioned above.1131 1132Controlling Errors and Warnings1133-------------------------------1134 1135Clang provides a number of ways to control which code constructs cause1136it to emit errors and warning messages, and how they are displayed to1137the console.1138 1139Controlling How Clang Displays Diagnostics1140^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^1141 1142When Clang emits a diagnostic, it includes rich information in the1143output, and gives you fine-grain control over which information is1144printed. Clang has the ability to print this information, and these are1145the options that control it:1146 1147#. A file/line/column indicator that shows exactly where the diagnostic1148 occurs in your code [:ref:`-fshow-column <opt_fshow-column>`,1149 :ref:`-fshow-source-location <opt_fshow-source-location>`].1150#. A categorization of the diagnostic as a note, warning, error, or1151 fatal error.1152#. A text string that describes what the problem is.1153#. An option that indicates how to control the diagnostic (for1154 diagnostics that support it)1155 [:ref:`-fdiagnostics-show-option <opt_fdiagnostics-show-option>`].1156#. A :ref:`high-level category <diagnostics_categories>` for the diagnostic1157 for clients that want to group diagnostics by class (for diagnostics1158 that support it)1159 [:option:`-fdiagnostics-show-category`].1160#. The line of source code that the issue occurs on, along with a caret1161 and ranges that indicate the important locations1162 [:ref:`-fcaret-diagnostics <opt_fcaret-diagnostics>`].1163#. "FixIt" information, which is a concise explanation of how to fix the1164 problem (when Clang is certain it knows)1165 [:ref:`-fdiagnostics-fixit-info <opt_fdiagnostics-fixit-info>`].1166#. A machine-parsable representation of the ranges involved (off by1167 default)1168 [:ref:`-fdiagnostics-print-source-range-info <opt_fdiagnostics-print-source-range-info>`].1169 1170For more information please see :ref:`Formatting of1171Diagnostics <cl_diag_formatting>`.1172 1173Diagnostic Mappings1174^^^^^^^^^^^^^^^^^^^1175 1176All diagnostics are mapped into one of these 6 classes:1177 1178- Ignored1179- Note1180- Remark1181- Warning1182- Error1183- Fatal1184 1185.. _diagnostics_categories:1186 1187Diagnostic Categories1188^^^^^^^^^^^^^^^^^^^^^1189 1190Though not shown by default, diagnostics may each be associated with a1191high-level category. This category is intended to make it possible to1192triage builds that produce a large number of errors or warnings in a1193grouped way.1194 1195Categories are not shown by default, but they can be turned on with the1196:option:`-fdiagnostics-show-category` option.1197When set to "``name``", the category is printed textually in the1198diagnostic output. When it is set to "``id``", a category number is1199printed. The mapping of category names to category id's can be obtained1200by running '``clang --print-diagnostic-categories``'.1201 1202Controlling Diagnostics via Command Line Flags1203^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^1204 1205TODO: -W flags, -pedantic, etc1206 1207.. _pragma_gcc_diagnostic:1208 1209Controlling Diagnostics via Pragmas1210^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^1211 1212Clang can also control what diagnostics are enabled through the use of1213pragmas in the source code. This is useful for turning off specific1214warnings in a section of source code. Clang supports GCC's pragma for1215compatibility with existing source code, so ``#pragma GCC diagnostic``1216and ``#pragma clang diagnostic`` are synonyms for Clang. GCC will ignore1217``#pragma clang diagnostic``, though.1218 1219The pragma may control any warning that can be used from the command1220line. Warnings may be set to ignored, warning, error, or fatal. The1221following example code will tell Clang or GCC to ignore the ``-Wall``1222warnings:1223 1224.. code-block:: c1225 1226 #pragma GCC diagnostic ignored "-Wall"1227 1228Clang also allows you to push and pop the current warning state. This is1229particularly useful when writing a header file that will be compiled by1230other people, because you don't know what warning flags they build with.1231 1232In the example below, :option:`-Wextra-tokens` is ignored for only a single line1233of code, after which the diagnostics return to whatever state had previously1234existed.1235 1236.. code-block:: c1237 1238 #if foo1239 #endif foo // warning: extra tokens at end of #endif directive1240 1241 #pragma GCC diagnostic push1242 #pragma GCC diagnostic ignored "-Wextra-tokens"1243 1244 #if foo1245 #endif foo // no warning1246 1247 #pragma GCC diagnostic pop1248 1249The push and pop pragmas will save and restore the full diagnostic state1250of the compiler, regardless of how it was set. It should be noted that while Clang1251supports the GCC pragma, Clang and GCC do not support the exact same set1252of warnings, so even when using GCC-compatible #pragmas there is no1253guarantee that they will have identical behaviour on both compilers.1254 1255Clang also doesn't yet support GCC behavior for ``#pragma diagnostic pop``1256that doesn't have a corresponding ``#pragma diagnostic push``. In this case,1257GCC pretends that there is a ``#pragma diagnostic push`` at the very beginning1258of the source file, so "unpaired" ``#pragma diagnostic pop`` matches that1259implicit push. This makes a difference for ``#pragma GCC diagnostic ignored``1260which are not guarded by push and pop. Refer to1261`GCC documentation <https://gcc.gnu.org/onlinedocs/gcc/Diagnostic-Pragmas.html>`_1262for details.1263 1264Like GCC, Clang accepts ``ignored``, ``warning``, ``error``, and ``fatal``1265severity levels. They can be used to change severity of a particular diagnostic1266for a region of source file. A notable difference from GCC is that diagnostic1267not enabled via command line arguments can't be enabled this way yet.1268 1269Some diagnostics associated with a ``-W`` flag have the error severity by1270default. They can be ignored or downgraded to warnings:1271 1272.. code-block:: cpp1273 1274 // C only1275 #pragma GCC diagnostic warning "-Wimplicit-function-declaration"1276 int main(void) { puts(""); }1277 1278In addition to controlling warnings and errors generated by the compiler, it is1279possible to generate custom warning and error messages through the following1280pragmas:1281 1282.. code-block:: c1283 1284 // The following will produce warning messages1285 #pragma message "some diagnostic message"1286 #pragma GCC warning "TODO: replace deprecated feature"1287 1288 // The following will produce an error message1289 #pragma GCC error "Not supported"1290 1291These pragmas operate similarly to the ``#warning`` and ``#error`` preprocessor1292directives, except that they may also be embedded into preprocessor macros via1293the C99 ``_Pragma`` operator, for example:1294 1295.. code-block:: c1296 1297 #define STR(X) #X1298 #define DEFER(M,...) M(__VA_ARGS__)1299 #define CUSTOM_ERROR(X) _Pragma(STR(GCC error(X " at line " DEFER(STR,__LINE__))))1300 1301 CUSTOM_ERROR("Feature not available");1302 1303Controlling Diagnostics in System Headers1304^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^1305 1306Warnings are suppressed when they occur in system headers. By default,1307an included file is treated as a system header if it is found in an1308include path specified by ``-isystem``, but this can be overridden in1309several ways.1310 1311The ``system_header`` pragma can be used to mark the current file as1312being a system header. No warnings will be produced from the location of1313the pragma onwards within the same file.1314 1315.. code-block:: c1316 1317 #if foo1318 #endif foo // warning: extra tokens at end of #endif directive1319 1320 #pragma clang system_header1321 1322 #if foo1323 #endif foo // no warning1324 1325The `--system-header-prefix=` and `--no-system-header-prefix=`1326command-line arguments can be used to override whether subsets of an include1327path are treated as system headers. When the name in a ``#include`` directive1328is found within a header search path and starts with a system prefix, the1329header is treated as a system header. The last prefix on the1330command-line which matches the specified header name takes precedence.1331For instance:1332 1333.. code-block:: console1334 1335 $ clang -Ifoo -isystem bar --system-header-prefix=x/ \1336 --no-system-header-prefix=x/y/1337 1338Here, ``#include "x/a.h"`` is treated as including a system header, even1339if the header is found in ``foo``, and ``#include "x/y/b.h"`` is treated1340as not including a system header, even if the header is found in1341``bar``.1342 1343A ``#include`` directive which finds a file relative to the current1344directory is treated as including a system header if the including file1345is treated as a system header.1346 1347Controlling Deprecation Diagnostics in Clang-Provided C Runtime Headers1348^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^1349 1350Clang is responsible for providing some of the C runtime headers that cannot be1351provided by a platform CRT, such as implementation limits or when compiling in1352freestanding mode. Define the ``_CLANG_DISABLE_CRT_DEPRECATION_WARNINGS`` macro1353prior to including such a C runtime header to disable the deprecation warnings.1354Note that the C Standard Library headers are allowed to transitively include1355other standard library headers (see 7.1.2p5), and so the most appropriate use1356of this macro is to set it within the build system using ``-D`` or before any1357include directives in the translation unit.1358 1359.. code-block:: c1360 1361 #define _CLANG_DISABLE_CRT_DEPRECATION_WARNINGS1362 #include <stdint.h> // Clang CRT deprecation warnings are disabled.1363 #include <stdatomic.h> // Clang CRT deprecation warnings are disabled.1364 1365.. _diagnostics_enable_everything:1366 1367Enabling All Diagnostics1368^^^^^^^^^^^^^^^^^^^^^^^^1369 1370In addition to the traditional ``-W`` flags, one can enable **all** diagnostics1371by passing :option:`-Weverything`. This works as expected with1372:option:`-Werror`, and also includes the warnings from :option:`-pedantic`. Some1373diagnostics contradict each other, therefore, users of :option:`-Weverything`1374often disable many diagnostics such as `-Wno-c++98-compat` and `-Wno-c++-compat`1375because they contradict recent C++ standards.1376 1377Since :option:`-Weverything` enables every diagnostic, we generally don't1378recommend using it. `-Wall` `-Wextra` are a better choice for most projects.1379Using :option:`-Weverything` means that updating your compiler is more difficult1380because you're exposed to experimental diagnostics which might be of lower1381quality than the default ones. If you do use :option:`-Weverything` then we1382advise that you address all new compiler diagnostics as they get added to Clang,1383either by fixing everything they find or explicitly disabling that diagnostic1384with its corresponding `Wno-` option.1385 1386Note that when combined with :option:`-w` (which disables all warnings),1387disabling all warnings wins.1388 1389.. _warning_suppression_mappings:1390 1391Controlling Diagnostics via Suppression Mappings1392^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^1393 1394Warning suppression mappings enable users to suppress Clang's diagnostics at a1395per-file granularity. This allows enforcing diagnostics in specific parts of the1396project even if there are violations in some headers.1397 1398.. code-block:: console1399 1400 $ cat mappings.txt1401 [unused]1402 src:foo/*1403 1404 $ clang --warning-suppression-mappings=mapping.txt -Wunused foo/bar.cc1405 # This compilation won't emit any unused findings for sources under foo/1406 # directory. But it'll still complain for all the other sources, e.g:1407 $ cat foo/bar.cc1408 #include "dir/include.h" // Clang flags unused declarations here.1409 #include "foo/include.h" // but unused warnings under this source are omitted.1410 #include "next_to_bar_cc.h" // as are unused warnings from this header file.1411 // Further, unused warnings in the remainder of bar.cc are also omitted.1412 1413 1414See :doc:`WarningSuppressionMappings` for details about the file format and1415functionality.1416 1417Controlling Static Analyzer Diagnostics1418^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^1419 1420While not strictly part of the compiler, the diagnostics from Clang's1421`static analyzer <https://clang-analyzer.llvm.org>`_ can also be1422influenced by the user via changes to the source code. See the available1423`annotations <analyzer/user-docs/Annotations.html>`_ and the analyzer's1424`FAQ page <analyzer/user-docs/FAQ.html#exclude-code>`_ for more information.1425 1426.. _usersmanual-precompiled-headers:1427 1428Precompiled Headers1429-------------------1430 1431`Precompiled headers <https://en.wikipedia.org/wiki/Precompiled_header>`_1432are a general approach employed by many compilers to reduce compilation1433time. The underlying motivation of the approach is that it is common for1434the same (and often large) header files to be included by multiple1435source files. Consequently, compile times can often be greatly improved1436by caching some of the (redundant) work done by a compiler to process1437headers. Precompiled header files, which represent one of many ways to1438implement this optimization, are literally files that represent an1439on-disk cache that contains the vital information necessary to reduce1440some of the work needed to process a corresponding header file. While1441details of precompiled headers vary between compilers, precompiled1442headers have been shown to be highly effective at speeding up program1443compilation on systems with very large system headers (e.g., macOS).1444 1445Generating a PCH File1446^^^^^^^^^^^^^^^^^^^^^1447 1448To generate a PCH file using Clang, one invokes Clang with the1449`-x <language>-header` option. This mirrors the interface in GCC1450for generating PCH files:1451 1452.. code-block:: console1453 1454 $ gcc -x c-header test.h -o test.h.gch1455 $ clang -x c-header test.h -o test.h.pch1456 1457Using a PCH File1458^^^^^^^^^^^^^^^^1459 1460A PCH file can then be used as a prefix header when a ``-include-pch``1461option is passed to ``clang``:1462 1463.. code-block:: console1464 1465 $ clang -include-pch test.h.pch test.c -o test1466 1467The ``clang`` driver will check if the PCH file ``test.h.pch`` is1468available; if so, the contents of ``test.h`` (and the files it includes)1469will be processed from the PCH file. Otherwise, Clang will report an error.1470 1471.. note::1472 1473 Clang does *not* automatically use PCH files for headers that are directly1474 included within a source file or indirectly via :option:`-include`.1475 For example:1476 1477 .. code-block:: console1478 1479 $ clang -x c-header test.h -o test.h.pch1480 $ cat test.c1481 #include "test.h"1482 $ clang test.c -o test1483 1484 In this example, ``clang`` will not automatically use the PCH file for1485 ``test.h`` since ``test.h`` was included directly in the source file and not1486 specified on the command line using ``-include-pch``.1487 1488Ignoring a PCH File1489^^^^^^^^^^^^^^^^^^^1490 1491To ignore PCH options, a `-ignore-pch` option is passed to ``clang``:1492 1493.. code-block:: console1494 1495 $ clang -x c-header test.h -Xclang -ignore-pch -o test.h.pch1496 $ clang -include-pch test.h.pch -Xclang -ignore-pch test.c -o test1497 1498This option disables precompiled headers, overrides -emit-pch and -include-pch.1499test.h.pch is not generated and not used as a prefix header.1500 1501Relocatable PCH Files1502^^^^^^^^^^^^^^^^^^^^^1503 1504It is sometimes necessary to build a precompiled header from headers1505that are not yet in their final, installed locations. For example, one1506might build a precompiled header within the build tree that is then1507meant to be installed alongside the headers. Clang permits the creation1508of "relocatable" precompiled headers, which are built with a given path1509(into the build directory) and can later be used from an installed1510location.1511 1512To build a relocatable precompiled header, place your headers into a1513subdirectory whose structure mimics the installed location. For example,1514if you want to build a precompiled header for the header ``mylib.h``1515that will be installed into ``/usr/include``, create a subdirectory1516``build/usr/include`` and place the header ``mylib.h`` into that1517subdirectory. If ``mylib.h`` depends on other headers, then they can be1518stored within ``build/usr/include`` in a way that mimics the installed1519location.1520 1521Building a relocatable precompiled header requires two additional1522arguments. First, pass the ``--relocatable-pch`` flag to indicate that1523the resulting PCH file should be relocatable. Second, pass1524``-isysroot /path/to/build``, which makes all includes for your library1525relative to the build directory. For example:1526 1527.. code-block:: console1528 1529 # clang -x c-header --relocatable-pch -isysroot /path/to/build /path/to/build/mylib.h mylib.h.pch1530 1531When loading the relocatable PCH file, the various headers used in the1532PCH file are found from the system header root. For example, ``mylib.h``1533can be found in ``/usr/include/mylib.h``. If the headers are installed1534in some other system root, the ``-isysroot`` option can be used provide1535a different system root from which the headers will be based. For1536example, ``-isysroot /Developer/SDKs/MacOSX10.4u.sdk`` will look for1537``mylib.h`` in ``/Developer/SDKs/MacOSX10.4u.sdk/usr/include/mylib.h``.1538 1539Relocatable precompiled headers are intended to be used in a limited1540number of cases where the compilation environment is tightly controlled1541and the precompiled header cannot be generated after headers have been1542installed.1543 1544.. _controlling-fp-behavior:1545 1546Controlling Floating Point Behavior1547-----------------------------------1548 1549Clang provides a number of ways to control floating point behavior, including1550with command line options and source pragmas. This section1551describes the various floating point semantic modes and the corresponding options.1552 1553.. csv-table:: Floating Point Semantic Modes1554 :header: "Mode", "Values"1555 :widths: 15, 30, 301556 1557 "ffp-exception-behavior", "{ignore, strict, maytrap}",1558 "fenv_access", "{off, on}", "(none)"1559 "frounding-math", "{dynamic, tonearest, downward, upward, towardzero}"1560 "ffp-contract", "{on, off, fast, fast-honor-pragmas}"1561 "fdenormal-fp-math", "{IEEE, PreserveSign, PositiveZero}"1562 "fdenormal-fp-math-fp32", "{IEEE, PreserveSign, PositiveZero}"1563 "fmath-errno", "{on, off}"1564 "fhonor-nans", "{on, off}"1565 "fhonor-infinities", "{on, off}"1566 "fsigned-zeros", "{on, off}"1567 "freciprocal-math", "{on, off}"1568 "fallow-approximate-fns", "{on, off}"1569 "fassociative-math", "{on, off}"1570 "fcomplex-arithmetic", "{basic, improved, full, promoted}"1571 1572This table describes the option settings that correspond to the three1573floating point semantic models: precise (the default), strict, and fast.1574 1575 1576.. csv-table:: Floating Point Models1577 :header: "Mode", "Precise", "Strict", "Fast", "Aggressive"1578 :widths: 25, 25, 25, 25, 251579 1580 "except_behavior", "ignore", "strict", "ignore", "ignore"1581 "fenv_access", "off", "on", "off", "off"1582 "rounding_mode", "tonearest", "dynamic", "tonearest", "tonearest"1583 "contract", "on", "off", "fast", "fast"1584 "support_math_errno", "on", "on", "off", "off"1585 "no_honor_nans", "off", "off", "off", "on"1586 "no_honor_infinities", "off", "off", "off", "on"1587 "no_signed_zeros", "off", "off", "on", "on"1588 "allow_reciprocal", "off", "off", "on", "on"1589 "allow_approximate_fns", "off", "off", "on", "on"1590 "allow_reassociation", "off", "off", "on", "on"1591 "complex_arithmetic", "full", "full", "promoted", "basic"1592 1593The ``-ffp-model`` option does not modify the ``fdenormal-fp-math``1594setting, but it does have an impact on whether ``crtfastmath.o`` is1595linked. Because linking ``crtfastmath.o`` has a global effect on the1596program, and because the global denormal handling can be changed in1597other ways, the state of ``fdenormal-fp-math`` handling cannot1598be assumed in any function based on fp-model. See :ref:`crtfastmath.o`1599for more details.1600 1601.. option:: -ffast-math1602 1603 Enable fast-math mode. This option lets the1604 compiler make aggressive, potentially-lossy assumptions about1605 floating-point math. These include:1606 1607 * Floating-point math obeys regular algebraic rules for real numbers (e.g.1608 ``+`` and ``*`` are associative, ``x/y == x * (1/y)``, and1609 ``(a + b) * c == a * c + b * c``),1610 * No ``NaN`` or infinite values will be operands or results of1611 floating-point operations,1612 * ``+0`` and ``-0`` may be treated as interchangeable.1613 1614 ``-ffast-math`` also defines the ``__FAST_MATH__`` preprocessor1615 macro. Some math libraries recognize this macro and change their behavior.1616 With the exception of ``-ffp-contract=fast``, using any of the options1617 below to disable any of the individual optimizations in ``-ffast-math``1618 will cause ``__FAST_MATH__`` to no longer be set.1619 ``-ffast-math`` enables ``-fcx-limited-range``.1620 1621 This option implies:1622 1623 * ``-fno-honor-infinities``1624 1625 * ``-fno-honor-nans``1626 1627 * ``-fapprox-func``1628 1629 * ``-fno-math-errno``1630 1631 * ``-ffinite-math-only``1632 1633 * ``-fassociative-math``1634 1635 * ``-freciprocal-math``1636 1637 * ``-fno-signed-zeros``1638 1639 * ``-fno-trapping-math``1640 1641 * ``-fno-rounding-math``1642 1643 * ``-ffp-contract=fast``1644 1645 Note: ``-ffast-math`` causes ``crtfastmath.o`` to be linked with code unless1646 ``-shared`` or ``-mno-daz-ftz`` is present. See1647 :ref:`crtfastmath.o` for more details.1648 1649.. option:: -fno-fast-math1650 1651 Disable fast-math mode. This option disables unsafe floating-point1652 optimizations by preventing the compiler from making any transformations that1653 could affect the results.1654 1655 This option implies:1656 1657 * ``-fhonor-infinities``1658 1659 * ``-fhonor-nans``1660 1661 * ``-fno-approx-func``1662 1663 * ``-fno-finite-math-only``1664 1665 * ``-fno-associative-math``1666 1667 * ``-fno-reciprocal-math``1668 1669 * ``-fsigned-zeros``1670 1671 * ``-ffp-contract=on``1672 1673 Also, this option resets following options to their target-dependent defaults.1674 1675 * ``-f[no-]math-errno``1676 1677 There is ambiguity about how ``-ffp-contract``, ``-ffast-math``,1678 and ``-fno-fast-math`` behave when combined. To keep the value of1679 ``-ffp-contract`` consistent, we define this set of rules:1680 1681 * ``-ffast-math`` sets ``ffp-contract`` to ``fast``.1682 1683 * ``-fno-fast-math`` sets ``-ffp-contract`` to ``on`` (``fast`` for CUDA and1684 HIP).1685 1686 * If ``-ffast-math`` and ``-ffp-contract`` are both seen, but1687 ``-ffast-math`` is not followed by ``-fno-fast-math``, ``ffp-contract``1688 will be given the value of whichever option was last seen.1689 1690 * If ``-fno-fast-math`` is seen and ``-ffp-contract`` has been seen at least1691 once, the ``ffp-contract`` will get the value of the last seen value of1692 ``-ffp-contract``.1693 1694 * If ``-fno-fast-math`` is seen and ``-ffp-contract`` has not been seen, the1695 ``-ffp-contract`` setting is determined by the default value of1696 ``-ffp-contract``.1697 1698 Note: ``-fno-fast-math`` causes ``crtfastmath.o`` to not be linked with code1699 unless ``-mdaz-ftz`` is present.1700 1701.. option:: -fdenormal-fp-math=<value>1702 1703 Select which denormal numbers the code is permitted to require.1704 1705 Valid values are:1706 1707 * ``ieee`` - IEEE 754 denormal numbers1708 * ``preserve-sign`` - the sign of a flushed-to-zero number is preserved in the sign of 01709 * ``positive-zero`` - denormals are flushed to positive zero1710 1711 The default value depends on the target. For most targets, it defaults to1712 ``ieee``.1713 1714.. option:: -f[no-]strict-float-cast-overflow1715 1716 When a floating-point value is not representable in a destination integer1717 type, the code has undefined behavior according to the language standard.1718 By default, Clang will not guarantee any particular result in that case.1719 With the 'no-strict' option, Clang will saturate towards the smallest and1720 largest representable integer values instead. NaNs will be converted to zero.1721 Defaults to ``-fstrict-float-cast-overflow``.1722 1723.. option:: -f[no-]math-errno1724 1725 Require math functions to indicate errors by setting errno.1726 The default varies by ToolChain. ``-fno-math-errno`` allows optimizations1727 that might cause standard C math functions to not set ``errno``.1728 For example, on some systems, the math function ``sqrt`` is specified1729 as setting ``errno`` to ``EDOM`` when the input is negative. On these1730 systems, the compiler cannot normally optimize a call to ``sqrt`` to use1731 inline code (e.g. the x86 ``sqrtsd`` instruction) without additional1732 checking to ensure that ``errno`` is set appropriately.1733 ``-fno-math-errno`` permits these transformations.1734 1735 On some targets, math library functions never set ``errno``, and so1736 ``-fno-math-errno`` is the default. This includes most BSD-derived1737 systems, including Darwin.1738 1739.. option:: -f[no-]trapping-math1740 1741 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.1742 1743 - The option ``-ftrapping-math`` behaves identically to ``-ffp-exception-behavior=strict``.1744 - The option ``-fno-trapping-math`` behaves identically to ``-ffp-exception-behavior=ignore``. This is the default.1745 1746.. option:: -ffp-contract=<value>1747 1748 Specify when the compiler is permitted to form fused floating-point1749 operations, such as fused multiply-add (FMA). Fused operations are1750 permitted to produce more precise results than performing the same1751 operations separately.1752 1753 The C and C++ standards permit intermediate floating-point results within an1754 expression to be computed with more precision than their type would1755 normally allow. This permits operation fusing, and Clang takes advantage1756 of this by default (``on``). Fusion across statements is not compliant with1757 the C and C++ standards but can be enabled using ``-ffp-contract=fast``.1758 1759 Fusion can be controlled with the ``FP_CONTRACT`` and ``clang fp contract``1760 pragmas. Please note that pragmas will be ignored with1761 ``-ffp-contract=fast``, and refer to the pragma documentation for a1762 description of how the pragmas interact with the different ``-ffp-contract``1763 option values.1764 1765 Valid values are:1766 1767 * ``fast``: enable fusion across statements disregarding pragmas, breaking1768 compliance with the C and C++ standards (default for CUDA).1769 * ``on``: enable C and C++ standard compliant fusion in the same statement1770 unless dictated by pragmas (default for languages other than CUDA/HIP)1771 * ``off``: disable fusion1772 * ``fast-honor-pragmas``: fuse across statements unless dictated by pragmas1773 (default for HIP)1774 1775.. option:: -f[no-]honor-infinities1776 1777 Allow floating-point optimizations that assume arguments and results are1778 not +-Inf.1779 Defaults to ``-fhonor-infinities``.1780 1781 If both ``-fno-honor-infinities`` and ``-fno-honor-nans`` are used,1782 has the same effect as specifying ``-ffinite-math-only``.1783 1784.. option:: -f[no-]honor-nans1785 1786 Allow floating-point optimizations that assume arguments and results are1787 not NaNs.1788 Defaults to ``-fhonor-nans``.1789 1790 If both ``-fno-honor-infinities`` and ``-fno-honor-nans`` are used,1791 has the same effect as specifying ``-ffinite-math-only``.1792 1793.. option:: -f[no-]approx-func1794 1795 Allow certain math function calls (such as ``log``, ``sqrt``, ``pow``, etc)1796 to be replaced with an approximately equivalent set of instructions1797 or alternative math function calls. For example, a ``pow(x, 0.25)``1798 may be replaced with ``sqrt(sqrt(x))``, despite being an inexact result1799 in cases where ``x`` is ``-0.0`` or ``-inf``.1800 Defaults to ``-fno-approx-func``.1801 1802.. option:: -f[no-]signed-zeros1803 1804 Allow optimizations that ignore the sign of floating point zeros.1805 Defaults to ``-fsigned-zeros``.1806 1807.. option:: -f[no-]associative-math1808 1809 Allow floating point operations to be reassociated.1810 Defaults to ``-fno-associative-math``.1811 1812.. option:: -f[no-]reciprocal-math1813 1814 Allow division operations to be transformed into multiplication by a1815 reciprocal. This can be significantly faster than an ordinary division1816 but can also have significantly less precision. Defaults to1817 ``-fno-reciprocal-math``.1818 1819.. option:: -f[no-]unsafe-math-optimizations1820 1821 Allow unsafe floating-point optimizations.1822 ``-funsafe-math-optimizations`` also implies:1823 1824 * ``-fapprox-func``1825 * ``-fassociative-math``1826 * ``-freciprocal-math``1827 * ``-fno-signed-zeros``1828 * ``-fno-trapping-math``1829 * ``-ffp-contract=fast``1830 1831 ``-fno-unsafe-math-optimizations`` implies:1832 1833 * ``-fno-approx-func``1834 * ``-fno-associative-math``1835 * ``-fno-reciprocal-math``1836 * ``-fsigned-zeros``1837 * ``-ffp-contract=on``1838 1839 There is ambiguity about how ``-ffp-contract``,1840 ``-funsafe-math-optimizations``, and ``-fno-unsafe-math-optimizations``1841 behave when combined. Explanation in :option:`-fno-fast-math` also applies1842 to these options.1843 1844 Defaults to ``-fno-unsafe-math-optimizations``.1845 1846.. option:: -f[no-]finite-math-only1847 1848 Allow floating-point optimizations that assume arguments and results are1849 not NaNs or +-Inf. ``-ffinite-math-only`` defines the1850 ``__FINITE_MATH_ONLY__`` preprocessor macro.1851 ``-ffinite-math-only`` implies:1852 1853 * ``-fno-honor-infinities``1854 * ``-fno-honor-nans``1855 1856 ``-ffno-inite-math-only`` implies:1857 1858 * ``-fhonor-infinities``1859 * ``-fhonor-nans``1860 1861 Defaults to ``-fno-finite-math-only``.1862 1863.. option:: -f[no-]rounding-math1864 1865 Force floating-point operations to honor the dynamically-set rounding mode by default.1866 1867 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.1868 1869 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``.1870 1871 - The option ``-fno-rounding-math`` allows the compiler to assume that the rounding mode is set to ``FE_TONEAREST``. This is the default.1872 - 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.1873 1874.. option:: -ffp-model=<value>1875 1876 Specify floating point behavior. ``-ffp-model`` is an umbrella1877 option that encompasses functionality provided by other, single1878 purpose, floating point options. Valid values are: ``precise``, ``strict``,1879 ``fast``, and ``aggressive``.1880 Details:1881 1882 * ``precise`` Disables optimizations that are not value-safe on1883 floating-point data, although FP contraction (FMA) is enabled1884 (``-ffp-contract=on``). This is the default behavior. This value resets1885 ``-fmath-errno`` to its target-dependent default.1886 * ``strict`` Enables ``-frounding-math`` and1887 ``-ffp-exception-behavior=strict``, and disables contractions (FMA). All1888 of the ``-ffast-math`` enablements are disabled. Enables1889 ``STDC FENV_ACCESS``: by default ``FENV_ACCESS`` is disabled. This option1890 setting behaves as though ``#pragma STDC FENV_ACCESS ON`` appeared at the1891 top of the source file.1892 * ``fast`` Behaves identically to specifying ``-funsafe-math-optimizations``,1893 ``-fno-math-errno`` and ``-fcomplex-arithmetic=promoted``1894 ``ffp-contract=fast``1895 * ``aggressive`` Behaves identically to specifying both ``-ffast-math`` and1896 ``ffp-contract=fast``1897 1898 Note: If your command line specifies multiple instances1899 of the ``-ffp-model`` option, or if your command line option specifies1900 ``-ffp-model`` and later on the command line selects a floating point1901 option that has the effect of negating part of the ``ffp-model`` that1902 has been selected, then the compiler will issue a diagnostic warning1903 that the override has occurred.1904 1905.. option:: -ffp-exception-behavior=<value>1906 1907 Specify the floating-point exception behavior.1908 1909 Valid values are: ``ignore``, ``maytrap``, and ``strict``.1910 The default value is ``ignore``. Details:1911 1912 * ``ignore`` The compiler assumes that the exception status flags will not be read and that floating point exceptions will be masked.1913 * ``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.1914 * ``strict`` The compiler ensures that all transformations strictly preserve the floating point exception semantics of the original code.1915 1916.. option:: -ffp-eval-method=<value>1917 1918 Specify the floating-point evaluation method for intermediate results within1919 a single expression of the code.1920 1921 Valid values are: ``source``, ``double``, and ``extended``.1922 For 64-bit targets, the default value is ``source``. For 32-bit x86 targets,1923 however, in the case of NETBSD 6.99.26 and under, the default value is1924 ``double``; in the case of NETBSD greater than 6.99.26, with NoSSE, the1925 default value is ``extended``, with SSE the default value is ``source``.1926 Details:1927 1928 * ``source`` The compiler uses the floating-point type declared in the source program as the evaluation method.1929 * ``double`` The compiler uses ``double`` as the floating-point evaluation method for all float expressions of type that is narrower than ``double``.1930 * ``extended`` The compiler uses ``long double`` as the floating-point evaluation method for all float expressions of type that is narrower than ``long double``.1931 1932.. option:: -f[no-]protect-parens1933 1934 This option pertains to floating-point types, complex types with1935 floating-point components, and vectors of these types. Some arithmetic1936 expression transformations that are mathematically correct and permissible1937 according to the C and C++ language standards may be incorrect when dealing1938 with floating-point types, such as reassociation and distribution. Further,1939 the optimizer may ignore parentheses when computing arithmetic expressions1940 in circumstances where the parenthesized and unparenthesized expression1941 express the same mathematical value. For example (a+b)+c is the same1942 mathematical value as a+(b+c), but the optimizer is free to evaluate the1943 additions in any order regardless of the parentheses. When enabled, this1944 option forces the optimizer to honor the order of operations with respect1945 to parentheses in all circumstances.1946 Defaults to ``-fno-protect-parens``.1947 1948 Note that floating-point contraction (option `-ffp-contract=`) is disabled1949 when `-fprotect-parens` is enabled. Also note that in safe floating-point1950 modes, such as `-ffp-model=precise` or `-ffp-model=strict`, this option1951 has no effect because the optimizer is prohibited from making unsafe1952 transformations.1953 1954.. option:: -fexcess-precision:1955 1956 The C and C++ standards allow floating-point expressions to be computed as if1957 intermediate results had more precision (and/or a wider range) than the type1958 of the expression strictly allows. This is called excess precision1959 arithmetic.1960 Excess precision arithmetic can improve the accuracy of results (although not1961 always), and it can make computation significantly faster if the target lacks1962 direct hardware support for arithmetic in a particular type. However, it can1963 also undermine strict floating-point reproducibility.1964 1965 Under the standards, assignments and explicit casts force the operand to be1966 converted to its formal type, discarding any excess precision. Because data1967 can only flow between statements via an assignment, this means that the use1968 of excess precision arithmetic is a reliable local property of a single1969 statement, and results do not change based on optimization. However, when1970 excess precision arithmetic is in use, Clang does not guarantee strict1971 reproducibility, and future compiler releases may recognize more1972 opportunities to use excess precision arithmetic, e.g. with floating-point1973 builtins.1974 1975 Clang does not use excess precision arithmetic for most types or on most1976 targets. For example, even on pre-SSE X86 targets where ``float`` and1977 ``double`` computations must be performed in the 80-bit X87 format, Clang1978 rounds all intermediate results correctly for their type. Clang currently1979 uses excess precision arithmetic by default only for the following types and1980 targets:1981 1982 * ``_Float16`` on X86 targets without ``AVX512-FP16``.1983 1984 The ``-fexcess-precision=<value>`` option can be used to control the use of1985 excess precision arithmetic. Valid values are:1986 1987 * ``standard`` - The default. Allow the use of excess precision arithmetic1988 under the constraints of the C and C++ standards. Has no effect except on1989 the types and targets listed above.1990 * ``fast`` - Accepted for GCC compatibility, but currently treated as an1991 alias for ``standard``.1992 * ``16`` - Forces ``_Float16`` operations to be emitted without using excess1993 precision arithmetic.1994 1995.. option:: -fcomplex-arithmetic=<value>:1996 1997 This option specifies the implementation for complex multiplication and division.1998 1999 Valid values are: ``basic``, ``improved``, ``full`` and ``promoted``.2000 2001 * ``basic`` Implementation of complex division and multiplication using2002 algebraic formulas at source precision. No special handling to avoid2003 overflow. NaN and infinite values are not handled.2004 * ``improved`` Implementation of complex division using the Smith algorithm2005 at source precision. Smith's algorithm for complex division.2006 See SMITH, R. L. Algorithm 116: Complex division. Commun. ACM 5, 8 (1962).2007 This value offers improved handling for overflow in intermediate2008 calculations, but overflow may occur. NaN and infinite values are not2009 handled in some cases.2010 * ``full`` Implementation of complex division and multiplication using a2011 call to runtime library functions (generally the case, but the BE might2012 sometimes replace the library call if it knows enough about the potential2013 range of the inputs). Overflow and non-finite values are handled by the2014 library implementation. For the case of multiplication, overflow will occur in2015 accordance with normal floating-point rules. This is the default value.2016 * ``promoted`` Implementation of complex division using algebraic formulas at2017 higher precision. Overflow is handled. Non-finite values are handled in some2018 cases. If the target does not have native support for a higher-precision2019 data type, the implementation for the complex operation using the Smith2020 algorithm will be used. Overflow may still occur in some cases. NaN and2021 infinite values are not handled.2022 2023.. option:: -fcx-limited-range:2024 2025 This option is aliased to ``-fcomplex-arithmetic=basic``. It enables the2026 naive mathematical formulas for complex division and multiplication with no2027 NaN checking of results. The default is ``-fno-cx-limited-range`` aliased to2028 ``-fcomplex-arithmetic=full``. This option is enabled by the ``-ffast-math``2029 option.2030 2031.. option:: -fcx-fortran-rules:2032 2033 This option is aliased to ``-fcomplex-arithmetic=improved``. It enables the2034 naive mathematical formulas for complex multiplication and enables application2035 of Smith's algorithm for complex division. See SMITH, R. L. Algorithm 116:2036 Complex division. Commun. ACM 5, 8 (1962).2037 The default is ``-fno-cx-fortran-rules`` aliased to2038 ``-fcomplex-arithmetic=full``.2039 2040.. _floating-point-environment:2041 2042Accessing the floating point environment2043^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^2044Many targets allow floating point operations to be configured to control things2045such as how inexact results should be rounded and how exceptional conditions2046should be handled. This configuration is called the floating point environment.2047C and C++ restrict access to the floating point environment by default, and the2048compiler is allowed to assume that all operations are performed in the default2049environment. When code is compiled in this default mode, operations that depend2050on the environment (such as floating-point arithmetic and `FLT_ROUNDS`) may have2051undefined behavior if the dynamic environment is not the default environment; for2052example, `FLT_ROUNDS` may or may not simply return its default value for the target2053instead of reading the dynamic environment, and floating-point operations may be2054optimized as if the dynamic environment were the default. Similarly, it is undefined2055behavior to change the floating point environment in this default mode, for example2056by calling the `fesetround` function.2057C provides two pragmas to allow code to dynamically modify the floating point environment:2058 2059- ``#pragma STDC FENV_ACCESS ON`` allows dynamic changes to the entire floating2060 point environment.2061 2062- ``#pragma STDC FENV_ROUND FE_DYNAMIC`` allows dynamic changes to just the floating2063 point rounding mode. This may be more optimizable than ``FENV_ACCESS ON`` because2064 the compiler can still ignore the possibility of floating-point exceptions by default.2065 2066Both of these can be used either at the start of a block scope, in which case2067they cover all code in that scope (unless they're turned off in a child scope),2068or at the top level in a file, in which case they cover all subsequent function2069bodies until they're turned off. Note that it is undefined behavior to enter2070code that is *not* covered by one of these pragmas from code that *is* covered2071by one of these pragmas unless the floating point environment has been restored2072to its default state. See the C standard for more information about these pragmas.2073 2074The command line option ``-frounding-math`` behaves as if the translation unit2075began with ``#pragma STDC FENV_ROUND FE_DYNAMIC``. The command line option2076``-ffp-model=strict`` behaves as if the translation unit began with ``#pragma STDC FENV_ACCESS ON``.2077 2078Code that just wants to use a specific rounding mode for specific floating point2079operations can avoid most of the hazards of the dynamic floating point environment2080by using ``#pragma STDC FENV_ROUND`` with a value other than ``FE_DYNAMIC``.2081 2082.. _crtfastmath.o:2083 2084A note about ``crtfastmath.o``2085^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^2086``-ffast-math`` and ``-funsafe-math-optimizations`` without the ``-shared``2087option cause ``crtfastmath.o`` to be2088automatically linked, which adds a static constructor that sets the FTZ/DAZ2089bits in MXCSR, affecting not only the current compilation unit but all static2090and shared libraries included in the program. This decision can be overridden2091by using either the flag ``-mdaz-ftz`` or ``-mno-daz-ftz`` to respectively2092link or not link ``crtfastmath.o``.2093 2094.. _FLT_EVAL_METHOD:2095 2096A note about ``__FLT_EVAL_METHOD__``2097^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^2098The ``__FLT_EVAL_METHOD__`` is not defined as a traditional macro, and so it2099will not appear when dumping preprocessor macros. Instead, the value2100``__FLT_EVAL_METHOD__`` expands to is determined at the point of expansion2101either from the value set by the ``-ffp-eval-method`` command line option or2102from the target. This is because the ``__FLT_EVAL_METHOD__`` macro2103cannot expand to the correct evaluation method in the presence of a ``#pragma``2104which alters the evaluation method. An error is issued if2105``__FLT_EVAL_METHOD__`` is expanded inside a scope modified by2106``#pragma clang fp eval_method``.2107 2108.. _fp-constant-eval:2109 2110A note about Floating Point Constant Evaluation2111^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^2112 2113In C, the only place floating point operations are guaranteed to be evaluated2114during translation is in the initializers of variables of static storage2115duration, which are all notionally initialized before the program begins2116executing (and thus before a non-default floating point environment can be2117entered). But C++ has many more contexts where floating point constant2118evaluation occurs. Specifically: for static/thread-local variables,2119first try evaluating the initializer in a constant context, including in the2120constant floating point environment (just like in C), and then, if that fails,2121fall back to emitting runtime code to perform the initialization (which might2122in general be in a different floating point environment).2123 2124Consider this example when compiled with ``-frounding-math``2125 2126 .. code-block:: console2127 2128 constexpr float func_01(float x, float y) {2129 return x + y;2130 }2131 float V1 = func_01(1.0F, 0x0.000001p0F);2132 2133The C++ rule is that initializers for static storage duration variables are2134first evaluated during translation (therefore, in the default rounding mode),2135and only evaluated at runtime (and therefore in the runtime rounding mode) if2136the compile-time evaluation fails. This is in line with the C rules;2137C11 F.8.5 says: *All computation for automatic initialization is done (as if)2138at execution time; thus, it is affected by any operative modes and raises2139floating-point exceptions as required by IEC 60559 (provided the state for the2140FENV_ACCESS pragma is ‘‘on’’). All computation for initialization of objects2141that have static or thread storage duration is done (as if) at translation2142time.* C++ generalizes this by adding another phase of initialization2143(at runtime) if the translation-time initialization fails, but the2144translation-time evaluation of the initializer of succeeds, it will be2145treated as a constant initializer.2146 2147 2148.. _controlling-code-generation:2149 2150Controlling Code Generation2151---------------------------2152 2153Clang provides a number of ways to control code generation. The options2154are listed below.2155 2156.. option:: -f[no-]sanitize=check1,check2,...2157 2158 Turn on runtime checks or mitigations for various forms of undefined or2159 suspicious behavior. These are disabled by default.2160 2161 The following options enable runtime checks for various forms of undefined2162 or suspicious behavior:2163 2164 - .. _opt_fsanitize_address:2165 2166 ``-fsanitize=address``:2167 :doc:`AddressSanitizer`, a memory error2168 detector.2169 - .. _opt_fsanitize_thread:2170 2171 ``-fsanitize=thread``: :doc:`ThreadSanitizer`, a data race detector.2172 - .. _opt_fsanitize_memory:2173 2174 ``-fsanitize=memory``: :doc:`MemorySanitizer`,2175 a detector of uninitialized reads. Requires instrumentation of all2176 program code.2177 - .. _opt_fsanitize_undefined:2178 2179 ``-fsanitize=undefined``: :doc:`UndefinedBehaviorSanitizer`,2180 a fast and compatible undefined behavior checker.2181 - .. _opt_fsanitize_type:2182 2183 ``-fsanitize=type``: :doc:`TypeSanitizer`, a detector for strict2184 aliasing violations.2185 - ``-fsanitize=dataflow``: :doc:`DataFlowSanitizer`, a general data2186 flow analysis.2187 - ``-fsanitize=cfi``: :doc:`control flow integrity <ControlFlowIntegrity>`2188 checks. Requires ``-flto``.2189 - ``-fsanitize=kcfi``: kernel indirect call forward-edge control flow2190 integrity.2191 - ``-fsanitize=safe-stack``: :doc:`safe stack <SafeStack>`2192 protection against stack-based memory corruption errors.2193 - ``-fsanitize=realtime``: :doc:`RealtimeSanitizer`,2194 a real-time safety checker.2195 2196 The following options enable runtime mitigations for various forms of2197 undefined or suspicious behavior:2198 2199 - ``-fsanitize=alloc-token``: Enables :doc:`allocation tokens <AllocToken>`2200 for allocator-level heap organization strategies, such as for security2201 hardening. It passes type-derived token IDs to a compatible memory2202 allocator. Requires linking against a token-aware allocator.2203 2204 There are more fine-grained checks available: see2205 the :ref:`list <ubsan-checks>` of specific kinds of2206 undefined behavior that can be detected and the :ref:`list <cfi-schemes>`2207 of control flow integrity schemes.2208 2209 The ``-fsanitize=`` argument must also be provided when linking, in2210 order to link to the appropriate runtime library.2211 2212 It is not possible to combine more than one of the ``-fsanitize=address``,2213 ``-fsanitize=thread``, and ``-fsanitize=memory`` checkers in the same2214 program.2215 2216.. option:: -f[no-]sanitize-recover=check1,check2,...2217 2218.. option:: -f[no-]sanitize-recover[=all]2219 2220 Controls which checks enabled by ``-fsanitize=`` flag are non-fatal.2221 If the check is fatal, program will halt after the first error2222 of this kind is detected and error report is printed.2223 2224 By default, non-fatal checks are those enabled by2225 :doc:`UndefinedBehaviorSanitizer`,2226 except for ``-fsanitize=return`` and ``-fsanitize=unreachable``. Some2227 sanitizers may not support recovery (or not support it by default2228 e.g. :doc:`AddressSanitizer`), and always crash the program after the issue2229 is detected.2230 2231 Note that the ``-fsanitize-trap`` flag has precedence over this flag.2232 This means that if a check has been configured to trap elsewhere on the2233 command line, or if the check traps by default, this flag will not have2234 any effect unless that sanitizer's trapping behavior is disabled with2235 ``-fno-sanitize-trap``.2236 2237 For example, if a command line contains the flags ``-fsanitize=undefined2238 -fsanitize-trap=undefined``, the flag ``-fsanitize-recover=alignment``2239 will have no effect on its own; it will need to be accompanied by2240 ``-fno-sanitize-trap=alignment``.2241 2242.. option:: -f[no-]sanitize-trap=check1,check2,...2243 2244.. option:: -f[no-]sanitize-trap[=all]2245 2246 Controls which checks enabled by the ``-fsanitize=`` flag trap. This2247 option is intended for use in cases where the sanitizer runtime cannot2248 be used (for instance, when building libc or a kernel module), or where2249 the binary size increase caused by the sanitizer runtime is a concern.2250 2251 This flag is only compatible with :doc:`control flow integrity2252 <ControlFlowIntegrity>` schemes and :doc:`UndefinedBehaviorSanitizer`2253 checks other than ``vptr``.2254 2255 This flag is enabled by default for sanitizers in the ``cfi`` group.2256 2257.. option:: -fsanitize-ignorelist=/path/to/ignorelist/file2258 2259 Disable or modify sanitizer checks for objects (source files, functions,2260 variables, types) listed in the file. See2261 :doc:`SanitizerSpecialCaseList` for file format description.2262 2263.. option:: -fno-sanitize-ignorelist2264 2265 Don't use ignorelist file, if it was specified earlier in the command line.2266 2267.. option:: -f[no-]sanitize-coverage=[type,features,...]2268 2269 Enable simple code coverage in addition to certain sanitizers.2270 See :doc:`SanitizerCoverage` for more details.2271 2272.. option:: -f[no-]sanitize-address-outline-instrumentation2273 2274 Controls how address sanitizer code is generated. If enabled will always use2275 a function call instead of inlining the code. Turning this option on could2276 reduce the binary size, but might result in a worse run-time performance.2277 2278 See :doc: `AddressSanitizer` for more details.2279 2280.. option:: -f[no-]sanitize-type-outline-instrumentation2281 2282 Controls how type sanitizer code is generated. If enabled will always use2283 a function call instead of inlining the code. Turning this option off may2284 result in better run-time performance, but will increase binary size and2285 compilation overhead.2286 2287 See :doc: `TypeSanitizer` for more details.2288 2289.. option:: -f[no-]sanitize-stats2290 2291 Enable simple statistics gathering for the enabled sanitizers.2292 See :doc:`SanitizerStats` for more details.2293 2294.. option:: -fsanitize-undefined-trap-on-error2295 2296 Deprecated alias for ``-fsanitize-trap=undefined``.2297 2298.. option:: -fsanitize-cfi-cross-dso2299 2300 Enable cross-DSO control flow integrity checks. This flag modifies2301 the behavior of sanitizers in the ``cfi`` group to allow checking2302 of cross-DSO virtual and indirect calls.2303 2304.. option:: -fsanitize-cfi-icall-generalize-pointers2305 2306 Generalize pointers in return and argument types in function type signatures2307 checked by Control Flow Integrity indirect call checking. See2308 :doc:`ControlFlowIntegrity` for more details.2309 2310.. option:: -fsanitize-cfi-icall-experimental-normalize-integers2311 2312 Normalize integers in return and argument types in function type signatures2313 checked by Control Flow Integrity indirect call checking. See2314 :doc:`ControlFlowIntegrity` for more details.2315 2316 This option is currently experimental.2317 2318.. option:: -fsanitize-kcfi-arity2319 2320 Extends kernel indirect call forward-edge control flow integrity with2321 additional function arity information (for supported targets). See2322 :doc:`ControlFlowIntegrity` for more details.2323 2324.. option:: -fstrict-vtable-pointers2325 2326 Enable optimizations based on the strict rules for overwriting polymorphic2327 C++ objects, i.e. the vptr is invariant during an object's lifetime.2328 This enables better devirtualization. Turned off by default, because it is2329 still experimental.2330 2331.. option:: -fwhole-program-vtables2332 2333 Enable whole-program vtable optimizations, such as single-implementation2334 devirtualization and virtual constant propagation, for classes with2335 :doc:`hidden LTO visibility <LTOVisibility>`. Requires ``-flto``.2336 2337.. option:: -f[no-]split-lto-unit2338 2339 Controls splitting the :doc:`LTO unit <LTOVisibility>` into regular LTO and2340 :doc:`ThinLTO` portions, when compiling with -flto=thin. Defaults to false2341 unless ``-fsanitize=cfi`` or ``-fwhole-program-vtables`` are specified, in2342 which case it defaults to true. Splitting is required with ``fsanitize=cfi``,2343 and it is an error to disable via ``-fno-split-lto-unit``. Splitting is2344 optional with ``-fwhole-program-vtables``, however, it enables more2345 aggressive whole program vtable optimizations (specifically virtual constant2346 propagation).2347 2348 When enabled, vtable definitions and select virtual functions are placed2349 in the split regular LTO module, enabling more aggressive whole program2350 vtable optimizations required for CFI and virtual constant propagation.2351 However, this can increase the LTO link time and memory requirements over2352 pure ThinLTO, as all split regular LTO modules are merged and LTO linked2353 with regular LTO.2354 2355.. option:: -f[no-]unique-source-file-names2356 2357 When enabled, allows the compiler to assume that each object file2358 passed to the linker has a unique identifier. The identifier for2359 an object file is either the source file path or the value of the2360 argument `-funique-source-file-identifier` if specified. This is2361 useful for reducing link times when doing ThinLTO in combination with2362 whole-program devirtualization or CFI.2363 2364 The full source path or identifier passed to the compiler must be2365 unique. This means that, for example, the following is a usage error:2366 2367 .. code-block:: console2368 2369 $ cd foo2370 $ clang -funique-source-file-names -c foo.c2371 $ cd ../bar2372 $ clang -funique-source-file-names -c foo.c2373 $ cd ..2374 $ clang foo/foo.o bar/foo.o2375 2376 but this is not:2377 2378 .. code-block:: console2379 2380 $ clang -funique-source-file-names -c foo/foo.c2381 $ clang -funique-source-file-names -c bar/foo.c2382 $ clang foo/foo.o bar/foo.o2383 2384 A misuse of this flag may result in a duplicate symbol error at2385 link time.2386 2387.. option:: -funique-source-file-identifier=IDENTIFIER2388 2389 Used with `-funique-source-file-names` to specify a source file2390 identifier.2391 2392.. option:: -fforce-emit-vtables2393 2394 In order to improve devirtualization, forces emitting of vtables even in2395 modules where it isn't necessary. It causes more inline virtual functions2396 to be emitted.2397 2398.. option:: -fno-assume-sane-operator-new2399 2400 Don't assume that the C++'s new operator is sane.2401 2402 This option tells the compiler to do not assume that C++'s global2403 new operator will always return a pointer that does not alias any2404 other pointer when the function returns.2405 2406.. option:: -fassume-nothrow-exception-dtor2407 2408 Assume that an exception object' destructor will not throw, and generate2409 less code for catch handlers. A throw expression of a type with a2410 potentially-throwing destructor will lead to an error.2411 2412 By default, Clang assumes that the exception object may have a throwing2413 destructor. For the Itanium C++ ABI, Clang generates a landing pad to2414 destroy local variables and call ``_Unwind_Resume`` for the code2415 ``catch (...) { ... }``. This option tells Clang that an exception object's2416 destructor will not throw and code simplification is possible.2417 2418.. option:: -ftrap-function=[name]2419 2420 Instruct code generator to emit a function call to the specified2421 function name for ``__builtin_trap()``.2422 2423 LLVM code generator translates ``__builtin_trap()`` to a trap2424 instruction if it is supported by the target ISA. Otherwise, the2425 builtin is translated into a call to ``abort``. If this option is2426 set, then the code generator will always lower the builtin to a call2427 to the specified function regardless of whether the target ISA has a2428 trap instruction. This option is useful for environments (e.g.2429 deeply embedded) where a trap cannot be properly handled, or when2430 some custom behavior is desired.2431 2432.. option:: -ftls-model=[model]2433 2434 Select which TLS model to use.2435 2436 Valid values are: ``global-dynamic``, ``local-dynamic``,2437 ``initial-exec`` and ``local-exec``. The default value is2438 ``global-dynamic``. The compiler may use a different model if the2439 selected model is not supported by the target, or if a more2440 efficient model can be used. The TLS model can be overridden per2441 variable using the ``tls_model`` attribute.2442 2443.. option:: -femulated-tls2444 2445 Select emulated TLS model, which overrides all -ftls-model choices.2446 2447 In emulated TLS mode, all access to TLS variables are converted to2448 calls to __emutls_get_address in the runtime library.2449 2450.. option:: -mhwdiv=[values]2451 2452 Select the ARM modes (arm or thumb) that support hardware division2453 instructions.2454 2455 Valid values are: ``arm``, ``thumb`` and ``arm,thumb``.2456 This option is used to indicate which mode (arm or thumb) supports2457 hardware division instructions. This only applies to the ARM2458 architecture.2459 2460.. option:: -m[no-]crc2461 2462 Enable or disable CRC instructions.2463 2464 This option is used to indicate whether CRC instructions are to2465 be generated. This only applies to the ARM architecture.2466 2467 CRC instructions are enabled by default on ARMv8.2468 2469.. option:: -mgeneral-regs-only2470 2471 Generate code which only uses the general purpose registers.2472 2473 This option restricts the generated code to use general registers2474 only. This only applies to the AArch64 architecture.2475 2476.. option:: -mcompact-branches=[values]2477 2478 Control the usage of compact branches for MIPSR6.2479 2480 Valid values are: ``never``, ``optimal`` and ``always``.2481 The default value is ``optimal`` which generates compact branches2482 when a delay slot cannot be filled. ``never`` disables the usage of2483 compact branches and ``always`` generates compact branches whenever2484 possible.2485 2486.. option:: -f[no-]max-type-align=[number]2487 2488 Instruct the code generator to not enforce a higher alignment than the given2489 number (of bytes) when accessing memory via an opaque pointer or reference.2490 This cap is ignored when directly accessing a variable or when the pointee2491 type has an explicit “aligned” attribute.2492 2493 The value should usually be determined by the properties of the system allocator.2494 Some builtin types, especially vector types, have very high natural alignments;2495 when working with values of those types, Clang usually wants to use instructions2496 that take advantage of that alignment. However, many system allocators do2497 not promise to return memory that is more than 8-byte or 16-byte-aligned. Use2498 this option to limit the alignment that the compiler can assume for an arbitrary2499 pointer, which may point onto the heap.2500 2501 This option does not affect the ABI alignment of types; the layout of structs and2502 unions and the value returned by the alignof operator remain the same.2503 2504 This option can be overridden on a case-by-case basis by putting an explicit2505 “aligned” alignment on a struct, union, or typedef. For example:2506 2507 .. code-block:: console2508 2509 #include <immintrin.h>2510 // Make an aligned typedef of the AVX-512 16-int vector type.2511 typedef __v16si __aligned_v16si __attribute__((aligned(64)));2512 2513 void initialize_vector(__aligned_v16si *v) {2514 // The compiler may assume that ‘v’ is 64-byte aligned, regardless of the2515 // value of -fmax-type-align.2516 }2517 2518.. option:: -faddrsig, -fno-addrsig2519 2520 Controls whether Clang emits an address-significance table into the object2521 file. Address-significance tables allow linkers to implement `safe ICF2522 <https://research.google.com/pubs/archive/36912.pdf>`_ without the false2523 positives that can result from other implementation techniques such as2524 relocation scanning. Address-significance tables are enabled by default2525 on ELF targets when using the integrated assembler. This flag currently2526 only has an effect on ELF targets.2527 2528.. _funique_internal_linkage_names:2529 2530.. option:: -f[no-]unique-internal-linkage-names2531 2532 Controls whether Clang emits a unique (best-effort) symbol name for internal2533 linkage symbols. When this option is set, compiler hashes the main source2534 file path from the command line and appends it to all internal symbols. If a2535 program contains multiple objects compiled with the same command-line source2536 file path, the symbols are not guaranteed to be unique. This option is2537 particularly useful in attributing profile information to the correct2538 function when multiple functions with the same private linkage name exist2539 in the binary.2540 2541 It should be noted that this option cannot guarantee uniqueness and the2542 following is an example where it is not unique when two modules contain2543 symbols with the same private linkage name:2544 2545 .. code-block:: console2546 2547 $ cd $P/foo && clang -c -funique-internal-linkage-names name_conflict.c2548 $ cd $P/bar && clang -c -funique-internal-linkage-names name_conflict.c2549 $ cd $P && clang foo/name_conflict.o && bar/name_conflict.o2550 2551.. option:: -f[no-]basic-block-address-map:2552 Emits a ``SHT_LLVM_BB_ADDR_MAP`` section which includes address offsets for each2553 basic block in the program, relative to the parent function address.2554 2555 2556.. option:: -fbasic-block-sections=[all, list=<arg>, none]2557 2558 Controls how Clang emits text sections for basic blocks. With values ``all``2559 and ``list=<arg>``, each basic block or a subset of basic blocks can be placed2560 in its own unique section.2561 2562 With the ``list=<arg>`` option, a file containing the subset of basic blocks2563 that need to placed in unique sections can be specified. The format of the2564 file is as follows. For example, ``list=spec.txt`` where ``spec.txt`` is the2565 following:2566 2567 ::2568 2569 !foo2570 !!22571 !_Z3barv2572 2573 will place the machine basic block with ``id 2`` in function ``foo`` in a2574 unique section. It will also place all basic blocks of functions ``bar``2575 in unique sections.2576 2577 Further, section clusters can also be specified using the ``list=<arg>``2578 option. For example, ``list=spec.txt`` where ``spec.txt`` contains:2579 2580 ::2581 2582 !foo2583 !!1 !!3 !!52584 !!2 !!4 !!62585 2586 will create two unique sections for function ``foo`` with the first2587 containing the odd numbered basic blocks and the second containing the2588 even numbered basic blocks.2589 2590 Basic block sections allow the linker to reorder basic blocks and enables2591 link-time optimizations like whole program inter-procedural basic block2592 reordering.2593 2594.. option:: -fcodegen-data-generate[=<path>]2595 2596 Emit the raw codegen (CG) data into custom sections in the object file.2597 Currently, this option also combines the raw CG data from the object files2598 into an indexed CG data file specified by the <path>, for LLD MachO only.2599 When the <path> is not specified, `default.cgdata` is created.2600 The CG data file combines all the outlining instances that occurred locally2601 in each object file.2602 2603 .. code-block:: console2604 2605 $ clang -fuse-ld=lld -Oz -fcodegen-data-generate code.cc2606 2607 For linkers that do not yet support this feature, `llvm-cgdata` can be used2608 manually to merge this CG data in object files.2609 2610 .. code-block:: console2611 2612 $ clang -c -fuse-ld=lld -Oz -fcodegen-data-generate code.cc2613 $ llvm-cgdata --merge -o default.cgdata code.o2614 2615.. option:: -fcodegen-data-use[=<path>]2616 2617 Read the codegen data from the specified path to more effectively outline2618 functions across compilation units. When the <path> is not specified,2619 `default.cgdata` is used. This option can create many identically outlined2620 functions that can be optimized by the conventional linker’s identical code2621 folding (ICF).2622 2623 .. code-block:: console2624 2625 $ clang -fuse-ld=lld -Oz -Wl,--icf=safe -fcodegen-data-use code.cc2626 2627.. _strict_aliasing:2628 2629Strict Aliasing2630---------------2631 2632The C and C++ standards require accesses to objects in memory to use l-values of2633an appropriate type for the object. This is called *strict aliasing* or2634*type-based alias analysis*. Strict aliasing enhances a variety of powerful2635memory optimizations, including reordering, combining, and eliminating memory2636accesses. These optimizations can lead to unexpected behavior in code that2637violates the strict aliasing rules. For example:2638 2639.. code-block:: c++2640 2641 void advance(size_t *index, double *data) {2642 double value = data[*index];2643 /* Clang may assume that this store does not change the contents of `data`. */2644 *index += 1;2645 /* Clang may assume that this store does not change the contents of `index`. */2646 data[*index] = value;2647 /* Either of these facts may create significant optimization opportunities2648 if Clang is able to inline this function. */2649 }2650 2651Strict aliasing can be explicitly enabled with ``-fstrict-aliasing`` and2652disabled with ``-fno-strict-aliasing``. ``clang-cl`` defaults to2653``-fno-strict-aliasing``. Otherwise, Clang defaults to ``-fstrict-aliasing``.2654 2655C and C++ specify slightly different rules for strict aliasing. To improve2656language interoperability, Clang allows two types to alias if either language2657would permit it. This includes applying the C++ similar types rule to C,2658allowing ``int **`` to alias ``int const * const *``. Clang also relaxes the2659standard aliasing rules in the following ways:2660 2661* All integer types of the same size are permitted to alias each other,2662 including signed and unsigned types.2663* ``void*`` is permitted to alias any pointer type, ``void**`` is permitted to2664 alias any pointer to pointer type, and so on.2665 2666Code which violates strict aliasing has undefined behavior. A program that2667works in one version of Clang may not work in another because of changes to the2668optimizer. Clang provides a :doc:`TypeSanitizer` to help detect2669violations of the strict aliasing rules, but it is currently still experimental.2670Code that is known to violate strict aliasing should generally be built with2671``-fno-strict-aliasing`` if the violation cannot be fixed.2672 2673Clang supports several ways to fix a violation of strict aliasing:2674 2675* L-values of the character types ``char`` and ``unsigned char`` (as well as2676 other types, depending on the standard) are permitted to access objects of2677 any type.2678 2679* Library functions such as ``memcpy`` and ``memset`` are specified as treating2680 memory as characters and therefore are not limited by strict aliasing. If a2681 value of one type must be reinterpreted as another (e.g. to read the bits of a2682 floating-point number), use ``memcpy`` to copy the representation to an object2683 of the destination type. This has no overhead over a direct l-value access2684 because Clang should reliably optimize calls to these functions to use simple2685 loads and stores when they are used with small constant sizes.2686 2687* The attribute ``may_alias`` can be added to a ``typedef`` to give l-values of2688 that type the same aliasing power as the character types.2689 2690Clang makes a best effort to avoid obvious miscompilations from strict aliasing2691by only considering type information when it cannot prove that two accesses must2692refer to the same memory. However, it is not recommended that programmers2693intentionally rely on this instead of using one of the solutions above because2694it is too easy for the compiler's analysis to be blocked in surprising ways.2695 2696In Clang 20, Clang strengthened its implementation of strict aliasing for2697accesses of pointer type. Previously, all accesses of pointer type were2698permitted to alias each other, but Clang now distinguishes different pointers2699by their pointee type, except as limited by the relaxations around qualifiers2700and ``void*`` described above. The previous behavior of treating all pointers as2701aliasing can be restored using ``-fno-pointer-tbaa``.2702 2703Profile Guided Optimization2704---------------------------2705 2706Profile information enables better optimization. For example, knowing that a2707branch is taken very frequently helps the compiler make better decisions when2708ordering basic blocks. Knowing that a function ``foo`` is called more2709frequently than another function ``bar`` helps the inliner. Optimization2710levels ``-O2`` and above are recommended for use of profile guided optimization.2711 2712Clang supports profile guided optimization with two different kinds of2713profiling. A sampling profiler can generate a profile with very low runtime2714overhead, or you can build an instrumented version of the code that collects2715more detailed profile information. Both kinds of profiles can provide execution2716counts for instructions in the code and information on branches taken and2717function invocation.2718 2719Regardless of which kind of profiling you use, be careful to collect profiles2720by running your code with inputs that are representative of the typical2721behavior. Code that is not exercised in the profile will be optimized as if it2722is unimportant, and the compiler may make poor optimization choices for code2723that is disproportionately used while profiling.2724 2725Differences Between Sampling and Instrumentation2726^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^2727 2728Although both techniques are used for similar purposes, there are important2729differences between the two:2730 27311. Profile data generated with one cannot be used by the other, and there is no2732 conversion tool that can convert one to the other. So, a profile generated2733 via ``-fprofile-generate`` or ``-fprofile-instr-generate`` must be used with2734 ``-fprofile-use`` or ``-fprofile-instr-use``. Similarly, sampling profiles2735 generated by external profilers must be converted and used with ``-fprofile-sample-use``2736 or ``-fauto-profile``.2737 27382. Instrumentation profile data can be used for code coverage analysis and2739 optimization.2740 27413. Sampling profiles can only be used for optimization. They cannot be used for2742 code coverage analysis. Although it would be technically possible to use2743 sampling profiles for code coverage, sample-based profiles are too2744 coarse-grained for code coverage purposes; it would yield poor results.2745 27464. Sampling profiles must be generated by an external tool. The profile2747 generated by that tool must then be converted into a format that can be read2748 by LLVM. The section on sampling profilers describes one of the supported2749 sampling profile formats.2750 2751 2752Using Sampling Profilers2753^^^^^^^^^^^^^^^^^^^^^^^^2754 2755Sampling profilers are used to collect runtime information, such as2756hardware counters, while your application executes. They are typically2757very efficient and do not incur a large runtime overhead. The2758sample data collected by the profiler can be used during compilation2759to determine what the most executed areas of the code are.2760 2761Using the data from a sample profiler requires some changes in the way2762a program is built. Before the compiler can use profiling information,2763the code needs to execute under the profiler. The following is the2764usual build cycle when using sample profilers for optimization:2765 27661. Build the code with source line table information. You can use all the2767 usual build flags that you always build your application with. The only2768 requirement is that DWARF debug info including source line information is2769 generated. This DWARF information is important for the profiler to be able2770 to map instructions back to source line locations. The usefulness of this2771 DWARF information can be improved with the ``-fdebug-info-for-profiling``2772 and ``-funique-internal-linkage-names`` options.2773 2774 On Linux:2775 2776 .. code-block:: console2777 2778 $ clang++ -O2 -gline-tables-only \2779 -fdebug-info-for-profiling -funique-internal-linkage-names \2780 code.cc -o code2781 2782 While MSVC-style targets default to CodeView debug information, DWARF debug2783 information is required to generate source-level LLVM profiles. Use2784 ``-gdwarf`` to include DWARF debug information:2785 2786 .. code-block:: winbatch2787 2788 > clang-cl /O2 -gdwarf -gline-tables-only ^2789 /clang:-fdebug-info-for-profiling /clang:-funique-internal-linkage-names ^2790 code.cc /Fe:code -fuse-ld=lld /link /debug:dwarf2791 2792 [OPTIONAL] Pseudo instrumentation can be used as the anchor for accurate2793 profile mapping with the ``-fpseudo-probe-for-profiling`` option.2794 2795 On Linux:2796 2797 .. code-block:: console2798 2799 $ clang++ -O2 -gline-tables-only \2800 -fpseudo-probe-for-profiling -funique-internal-linkage-names \2801 code.cc -o code2802 2803 On Windows:2804 2805 .. code-block:: winbatch2806 2807 > clang-cl /O2 -gdwarf -gline-tables-only ^2808 -fpseudo-probe-for-profiling /clang:-funique-internal-linkage-names ^2809 code.cc /Fe:code -fuse-ld=lld /link /debug:dwarf2810 2811.. note::2812 2813 :ref:`-funique-internal-linkage-names <funique_internal_linkage_names>`2814 generates unique names based on given command-line source file paths. If2815 your build system uses absolute source paths and these paths may change2816 between steps 1 and 4, then the uniqued function names may change and result2817 in unused profile data. Consider omitting this option in such cases.2818 28192. Run the executable under a sampling profiler. The specific profiler2820 you use does not really matter, as long as its output can be converted2821 into the format that the LLVM optimizer understands.2822 2823 Two such profilers are the Linux Perf profiler2824 (https://perf.wiki.kernel.org/) and Intel's Sampling Enabling Product (SEP),2825 available as part of `Intel VTune2826 <https://software.intel.com/content/www/us/en/develop/tools/oneapi/components/vtune-profiler.html>`_.2827 While Perf is Linux-specific, SEP can be used on Linux, Windows, and FreeBSD.2828 2829 The LLVM tool ``llvm-profgen`` can convert output of either Perf or SEP. An2830 external project, `AutoFDO <https://github.com/google/autofdo>`_, also2831 provides a ``create_llvm_prof`` tool which supports Linux Perf output.2832 2833 When using Perf:2834 2835 .. code-block:: console2836 2837 $ perf record -b -e BR_INST_RETIRED.NEAR_TAKEN:uppp ./code2838 2839 If the event above is unavailable, ``branches:u`` is probably next-best.2840 2841 Note the use of the ``-b`` flag. This tells Perf to use the Last Branch2842 Record (LBR) to record call chains. While this is not strictly required,2843 it provides better call information, which improves the accuracy of2844 the profile data.2845 2846 When using SEP:2847 2848 .. code-block:: console2849 2850 $ sep -start -out code.tb7 -ec BR_INST_RETIRED.NEAR_TAKEN:precise=yes:pdir -lbr no_filter:usr -perf-script brstack -app ./code2851 2852 This produces a ``code.perf.data.script`` output which can be used with2853 ``llvm-profgen``'s ``--perfscript`` input option.2854 28553. Convert the collected profile data to LLVM's sample profile format. This is2856 currently supported via the `AutoFDO <https://github.com/google/autofdo>`_2857 converter ``create_llvm_prof``. Once built and installed, you can convert2858 the ``perf.data`` file to LLVM using the command:2859 2860 .. code-block:: console2861 2862 $ create_llvm_prof --binary=./code --out=code.prof2863 2864 This will read ``perf.data`` and the binary file ``./code`` and emit2865 the profile data in ``code.prof``. Note that if you ran ``perf``2866 without the ``-b`` flag, you need to use ``--use_lbr=false`` when2867 calling ``create_llvm_prof``.2868 2869 Alternatively, the LLVM tool ``llvm-profgen`` can also be used to generate2870 the LLVM sample profile:2871 2872 .. code-block:: console2873 2874 $ llvm-profgen --binary=./code --output=code.prof --perfdata=perf.data2875 2876 Please note, ``perf.data`` must be collected with ``-b`` flag to Linux ``perf``2877 for the above step to work.2878 2879 When using SEP the output is in the textual format corresponding to2880 ``llvm-profgen --perfscript``. For example:2881 2882 .. code-block:: console2883 2884 $ llvm-profgen --binary=./code --output=code.prof --perfscript=code.perf.data.script2885 2886 28874. Build the code again using the collected profile. This step feeds2888 the profile back to the optimizers. This should result in a binary2889 that executes faster than the original one. Note that you are not2890 required to build the code with the exact same arguments that you2891 used in the first step. The only requirement is that you build the code2892 with the same debug info options and ``-fprofile-sample-use``. ``-gdwarf``2893 and ``-gline-tables-only`` can be omitted if you do not need debug info2894 in the final binary.2895 2896 On Linux:2897 2898 .. code-block:: console2899 2900 $ clang++ -O2 \2901 -fdebug-info-for-profiling -funique-internal-linkage-names \2902 -fprofile-sample-use=code.prof code.cc -o code2903 2904 On Windows:2905 2906 .. code-block:: winbatch2907 2908 > clang-cl /O2 ^2909 /clang:-fdebug-info-for-profiling /clang:-funique-internal-linkage-names ^2910 -fprofile-sample-use=code.prof code.cc /Fe:code2911 2912 [OPTIONAL] Pseudo instrumentation can be used as the anchor for accurate2913 profile mapping with the ``-fpseudo-probe-for-profiling`` option.2914 2915 On Linux:2916 2917 .. code-block:: console2918 2919 $ clang++ -O2 \2920 -fpseudo-probe-for-profiling -funique-internal-linkage-names \2921 -fprofile-sample-use=code.prof code.cc -o code2922 2923 On Windows:2924 2925 .. code-block:: winbatch2926 2927 > clang-cl /O2 ^2928 -fpseudo-probe-for-profiling /clang:-funique-internal-linkage-names ^2929 -fprofile-sample-use=code.prof code.cc /Fe:code2930 2931 [OPTIONAL] Sampling-based profiles can have inaccuracies or missing block/2932 edge counters. The profile inference algorithm (profi) can be used to infer2933 missing blocks and edge counts, and improve the quality of profile data.2934 Enable it with ``-fsample-profile-use-profi``. For example, on Linux:2935 2936 .. code-block:: console2937 2938 $ clang++ -fsample-profile-use-profi -O2 \2939 -fdebug-info-for-profiling -funique-internal-linkage-names \2940 -fprofile-sample-use=code.prof code.cc -o code2941 2942 On Windows:2943 2944 .. code-block:: winbatch2945 2946 > clang-cl /clang:-fsample-profile-use-profi /O2 ^2947 /clang:-fdebug-info-for-profiling /clang:-funique-internal-linkage-names ^2948 -fprofile-sample-use=code.prof code.cc /Fe:code2949 2950Sample Profile Formats2951""""""""""""""""""""""2952 2953Since external profilers generate profile data in a variety of custom formats,2954the data generated by the profiler must be converted into a format that can be2955read by the backend. LLVM supports three different sample profile formats:2956 29571. ASCII text. This is the easiest one to generate. The file is divided into2958 sections, which correspond to each of the functions with profile2959 information. The format is described below. It can also be generated from2960 the binary or gcov formats using the ``llvm-profdata`` tool.2961 29622. Binary encoding. This uses a more efficient encoding that yields smaller2963 profile files. This is the format generated by the ``create_llvm_prof`` tool2964 in https://github.com/google/autofdo.2965 29663. GCC encoding. This is based on the gcov format, which is accepted by GCC. It2967 is only interesting in environments where GCC and Clang co-exist. This2968 encoding is only generated by the ``create_gcov`` tool in2969 https://github.com/google/autofdo. It can be read by LLVM and2970 ``llvm-profdata``, but it cannot be generated by either.2971 2972If you are using Linux Perf to generate sampling profiles, you can use the2973conversion tool ``create_llvm_prof`` described in the previous section.2974Otherwise, you will need to write a conversion tool that converts your2975profiler's native format into one of these three.2976 2977 2978Sample Profile Text Format2979""""""""""""""""""""""""""2980 2981This section describes the ASCII text format for sampling profiles. It is,2982arguably, the easiest one to generate. If you are interested in generating any2983of the other two, consult the ``ProfileData`` library in LLVM's source tree2984(specifically, ``include/llvm/ProfileData/SampleProfReader.h``).2985 2986.. code-block:: console2987 2988 function1:total_samples:total_head_samples2989 offset1[.discriminator]: number_of_samples [fn1:num fn2:num ... ]2990 offset2[.discriminator]: number_of_samples [fn3:num fn4:num ... ]2991 ...2992 offsetN[.discriminator]: number_of_samples [fn5:num fn6:num ... ]2993 offsetA[.discriminator]: fnA:num_of_total_samples2994 offsetA1[.discriminator]: number_of_samples [fn7:num fn8:num ... ]2995 offsetA1[.discriminator]: number_of_samples [fn9:num fn10:num ... ]2996 offsetB[.discriminator]: fnB:num_of_total_samples2997 offsetB1[.discriminator]: number_of_samples [fn11:num fn12:num ... ]2998 2999This is a nested tree in which the indentation represents the nesting level3000of the inline stack. There are no blank lines in the file. And the spacing3001within a single line is fixed. Additional spaces will result in an error3002while reading the file.3003 3004Any line starting with the '#' character is completely ignored.3005 3006Inlined calls are represented with indentation. The Inline stack is a3007stack of source locations in which the top of the stack represents the3008leaf function, and the bottom of the stack represents the actual3009symbol to which the instruction belongs.3010 3011Function names must be mangled in order for the profile loader to3012match them in the current translation unit. The two numbers in the3013function header specify how many total samples were accumulated in the3014function (first number), and the total number of samples accumulated3015in the prologue of the function (second number). This head sample3016count provides an indicator of how frequently the function is invoked.3017 3018There are two types of lines in the function body.3019 3020- Sampled line represents the profile information of a source location.3021 ``offsetN[.discriminator]: number_of_samples [fn5:num fn6:num ... ]``3022 3023- Callsite line represents the profile information of an inlined callsite.3024 ``offsetA[.discriminator]: fnA:num_of_total_samples``3025 3026Each sampled line may contain several items. Some are optional (marked3027below):3028 3029a. Source line offset. This number represents the line number3030 in the function where the sample was collected. The line number is3031 always relative to the line where symbol of the function is3032 defined. So, if the function has its header at line 280, the offset3033 13 is at line 293 in the file.3034 3035 Note that this offset should never be a negative number. This could3036 happen in cases like macros. The debug machinery will register the3037 line number at the point of macro expansion. So, if the macro was3038 expanded in a line before the start of the function, the profile3039 converter should emit a 0 as the offset (this means that the optimizers3040 will not be able to associate a meaningful weight to the instructions3041 in the macro).3042 3043b. [OPTIONAL] Discriminator. This is used if the sampled program3044 was compiled with DWARF discriminator support3045 (http://wiki.dwarfstd.org/index.php?title=Path_Discriminators).3046 DWARF discriminators are unsigned integer values that allow the3047 compiler to distinguish between multiple execution paths on the3048 same source line location.3049 3050 For example, consider the line of code ``if (cond) foo(); else bar();``.3051 If the predicate ``cond`` is true 80% of the time, then the edge3052 into function ``foo`` should be considered to be taken most of the3053 time. But both calls to ``foo`` and ``bar`` are at the same source3054 line, so a sample count at that line is not sufficient. The3055 compiler needs to know which part of that line is taken more3056 frequently.3057 3058 This is what discriminators provide. In this case, the calls to3059 ``foo`` and ``bar`` will be at the same line, but will have3060 different discriminator values. This allows the compiler to correctly3061 set edge weights into ``foo`` and ``bar``.3062 3063c. Number of samples. This is an integer quantity representing the3064 number of samples collected by the profiler at this source3065 location.3066 3067d. [OPTIONAL] Potential call targets and samples. If present, this3068 line contains a call instruction. This models both direct and3069 number of samples. For example,3070 3071 .. code-block:: console3072 3073 130: 7 foo:3 bar:2 baz:73074 3075 The above means that at relative line offset 130 there is a call3076 instruction that calls one of ``foo()``, ``bar()`` and ``baz()``,3077 with ``baz()`` being the relatively more frequently called target.3078 3079As an example, consider a program with the call chain ``main -> foo -> bar``.3080When built with optimizations enabled, the compiler may inline the3081calls to ``bar`` and ``foo`` inside ``main``. The generated profile3082could then be something like this:3083 3084.. code-block:: console3085 3086 main:35504:03087 1: _Z3foov:355043088 2: _Z32bari:319773089 1.1: 319773090 2: 03091 3092This profile indicates that there were a total of 35,504 samples3093collected in main. All of those were at line 1 (the call to ``foo``).3094Of those, 31,977 were spent inside the body of ``bar``. The last line3095of the profile (``2: 0``) corresponds to line 2 inside ``main``. No3096samples were collected there.3097 3098.. _prof_instr:3099 3100Profiling with Instrumentation3101^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^3102 3103Clang also supports profiling via instrumentation. This requires building a3104special instrumented version of the code and has some runtime3105overhead during the profiling, but it provides more detailed results than a3106sampling profiler. It also provides reproducible results, at least to the3107extent that the code behaves consistently across runs.3108 3109Clang supports two types of instrumentation: frontend-based and IR-based.3110Frontend-based instrumentation can be enabled with the option ``-fprofile-instr-generate``,3111and IR-based instrumentation can be enabled with the option ``-fprofile-generate``.3112For best performance with PGO, IR-based instrumentation should be used. It has3113the benefits of lower instrumentation overhead, smaller raw profile size, and3114better runtime performance. Frontend-based instrumentation, on the other hand,3115has better source correlation, so it should be used with source line-based3116coverage testing.3117 3118The flag ``-fcs-profile-generate`` also instruments programs using the same3119instrumentation method as ``-fprofile-generate``. However, it performs a3120post-inline late instrumentation and can produce context-sensitive profiles.3121 3122 3123Here are the steps for using profile guided optimization with3124instrumentation:3125 31261. Build an instrumented version of the code by compiling and linking with the3127 ``-fprofile-generate`` or ``-fprofile-instr-generate`` option.3128 3129 .. code-block:: console3130 3131 $ clang++ -O2 -fprofile-instr-generate code.cc -o code3132 31332. Run the instrumented executable with inputs that reflect the typical usage.3134 By default, the profile data will be written to a ``default.profraw`` file3135 in the current directory. You can override that default by using option3136 ``-fprofile-instr-generate=`` or by setting the ``LLVM_PROFILE_FILE``3137 environment variable to specify an alternate file. If non-default file name3138 is specified by both the environment variable and the command line option,3139 the environment variable takes precedence. The file name pattern specified3140 can include different modifiers: ``%p``, ``%h``, ``%m``, ``%b``, ``%t``, and3141 ``%c``.3142 3143 Any instance of ``%p`` in that file name will be replaced by the process3144 ID, so that you can easily distinguish the profile output from multiple3145 runs.3146 3147 .. code-block:: console3148 3149 $ LLVM_PROFILE_FILE="code-%p.profraw" ./code3150 3151 The modifier ``%h`` can be used in scenarios where the same instrumented3152 binary is run in multiple different host machines dumping profile data3153 to a shared network based storage. The ``%h`` specifier will be substituted3154 with the hostname so that profiles collected from different hosts do not3155 clobber each other.3156 3157 While the use of ``%p`` specifier can reduce the likelihood for the profiles3158 dumped from different processes to clobber each other, such clobbering can still3159 happen because of the ``pid`` re-use by the OS. Another side-effect of using3160 ``%p`` is that the storage requirement for raw profile data files is greatly3161 increased. To avoid issues like this, the ``%m`` specifier can used in the profile3162 name. When this specifier is used, the profiler runtime will substitute ``%m``3163 with an integer identifier associated with the instrumented binary. Additionally,3164 multiple raw profiles dumped from different processes that share a file system (can be3165 on different hosts) will be automatically merged by the profiler runtime during the3166 dumping. If the program links in multiple instrumented shared libraries, each library3167 will dump the profile data into its own profile data file (with its integer3168 id embedded in the profile name). Note that the merging enabled by ``%m`` is for raw3169 profile data generated by profiler runtime. The resulting merged "raw" profile data3170 file still needs to be converted to a different format expected by the compiler (3171 see step 3 below).3172 3173 .. code-block:: console3174 3175 $ LLVM_PROFILE_FILE="code-%m.profraw" ./code3176 3177 Although rare, binary signatures used by the ``%m`` specifier can have3178 collisions. In this case, the ``%b`` specifier, which expands to the binary3179 ID (build ID in ELF and COFF), can be added. To use it, the program should be3180 compiled with the build ID linker option (``--build-id`` for GNU ld or LLD,3181 ``/build-id`` for lld-link on Windows). Linux, Windows and AIX are supported.3182 3183 See `this <SourceBasedCodeCoverage.html#running-the-instrumented-program>`_ section3184 about the ``%t``, and ``%c`` modifiers.3185 31863. Combine profiles from multiple runs and convert the "raw" profile format to3187 the input expected by clang. Use the ``merge`` command of the3188 ``llvm-profdata`` tool to do this.3189 3190 .. code-block:: console3191 3192 $ llvm-profdata merge -output=code.profdata code-*.profraw3193 3194 Note that this step is necessary even when there is only one "raw" profile,3195 since the merge operation also changes the file format.3196 31974. Build the code again using the ``-fprofile-use`` or ``-fprofile-instr-use``3198 option to specify the collected profile data.3199 3200 .. code-block:: console3201 3202 $ clang++ -O2 -fprofile-instr-use=code.profdata code.cc -o code3203 3204 You can repeat step 4 as often as you like without regenerating the3205 profile. As you make changes to your code, clang may no longer be able to3206 use the profile data. It will warn you when this happens.3207 3208Note that ``-fprofile-use`` option is semantically equivalent to3209its GCC counterpart, it *does not* handle profile formats produced by GCC.3210Both ``-fprofile-use`` and ``-fprofile-instr-use`` accept profiles in the3211indexed format, regardeless whether it is produced by frontend or the IR pass.3212 3213.. option:: -fprofile-generate[=<dirname>]3214 3215 The ``-fprofile-generate`` and ``-fprofile-generate=`` flags will use3216 an alternative instrumentation method for profile generation. When3217 given a directory name, it generates the profile file3218 ``default_%m.profraw`` in the directory named ``dirname`` if specified.3219 If ``dirname`` does not exist, it will be created at runtime. ``%m`` specifier3220 will be substituted with a unique id documented in step 2 above. In other words,3221 with ``-fprofile-generate[=<dirname>]`` option, the "raw" profile data automatic3222 merging is turned on by default, so there will no longer any risk of profile3223 clobbering from different running processes. For example,3224 3225 .. code-block:: console3226 3227 $ clang++ -O2 -fprofile-generate=yyy/zzz code.cc -o code3228 3229 When ``code`` is executed, the profile will be written to the file3230 ``yyy/zzz/default_xxxx.profraw``.3231 3232 To generate the profile data file with the compiler readable format, the3233 ``llvm-profdata`` tool can be used with the profile directory as the input:3234 3235 .. code-block:: console3236 3237 $ llvm-profdata merge -output=code.profdata yyy/zzz/3238 3239 If the user wants to turn off the auto-merging feature, or simply override the3240 the profile dumping path specified at command line, the environment variable3241 ``LLVM_PROFILE_FILE`` can still be used to override3242 the directory and filename for the profile file at runtime.3243 To override the path and filename at compile time, use3244 ``-Xclang -fprofile-instrument-path=/path/to/file_pattern.profraw``.3245 3246.. option:: -fcs-profile-generate[=<dirname>]3247 3248 The ``-fcs-profile-generate`` and ``-fcs-profile-generate=`` flags will use3249 the same instrumentation method, and generate the same profile as in the3250 ``-fprofile-generate`` and ``-fprofile-generate=`` flags. The difference is3251 that the instrumentation is performed after inlining so that the resulted3252 profile has a better context sensitive information. They cannot be used3253 together with ``-fprofile-generate`` and ``-fprofile-generate=`` flags.3254 They are typically used in conjunction with ``-fprofile-use`` flag.3255 The profile generated by ``-fcs-profile-generate`` and ``-fprofile-generate``3256 can be merged by llvm-profdata. A use example:3257 3258 .. code-block:: console3259 3260 $ clang++ -O2 -fprofile-generate=yyy/zzz code.cc -o code3261 $ ./code3262 $ llvm-profdata merge -output=code.profdata yyy/zzz/3263 3264 The first few steps are the same as that in ``-fprofile-generate``3265 compilation. Then perform a second round of instrumentation.3266 3267 .. code-block:: console3268 3269 $ clang++ -O2 -fprofile-use=code.profdata -fcs-profile-generate=sss/ttt \3270 -o cs_code3271 $ ./cs_code3272 $ llvm-profdata merge -output=cs_code.profdata sss/ttt code.profdata3273 3274 The resulted ``cs_code.prodata`` combines ``code.profdata`` and the profile3275 generated from binary ``cs_code``. Profile ``cs_code.profata`` can be used by3276 ``-fprofile-use`` compilation.3277 3278 .. code-block:: console3279 3280 $ clang++ -O2 -fprofile-use=cs_code.profdata3281 3282 The above command will read both profiles to the compiler at the identical3283 point of instrumentations.3284 3285.. option:: -fprofile-use[=<pathname>]3286 3287 Without any other arguments, ``-fprofile-use`` behaves identically to3288 ``-fprofile-instr-use``. Otherwise, if ``pathname`` is the full path to a3289 profile file, it reads from that file. If ``pathname`` is a directory name,3290 it reads from ``pathname/default.profdata``.3291 3292.. option:: -fprofile-update[=<method>]3293 3294 Unless ``-fsanitize=thread`` is specified, the default is ``single``, which3295 uses non-atomic increments. The counters can be inaccurate under thread3296 contention. ``atomic`` uses atomic increments which is accurate but has3297 overhead. ``prefer-atomic`` will be transformed to ``atomic`` when supported3298 by the target, or ``single`` otherwise.3299 3300.. option:: -fprofile-continuous3301 3302 Enables the continuous instrumentation profiling where profile counter updates3303 are continuously synced to a file. This option sets any necessary modifiers3304 (currently ``%c``) in the default profile filename and passes any necessary3305 flags to the middle-end to support this mode. Value profiling is not supported3306 in continuous mode.3307 3308 .. code-block:: console3309 3310 $ clang++ -O2 -fprofile-generate -fprofile-continuous code.cc -o code3311 3312 Running ``./code`` will collect the profile and write it to the3313 ``default_xxxx.profraw`` file. However, if ``./code`` abruptly terminates or3314 does not call ``exit()``, in continuous mode the profile collected up to the3315 point of termination will be available in ``default_xxxx.profraw`` while in3316 the non-continuous mode, no profile file is generated.3317 3318.. option:: -ftemporal-profile3319 3320 Enables the temporal profiling extension for IRPGO to improve startup time by3321 reducing ``.text`` section page faults. To do this, we instrument function3322 timestamps to measure when each function is called for the first time and use3323 this data to generate a function order to improve startup.3324 3325 The profile is generated as normal.3326 3327 .. code-block:: console3328 3329 $ clang++ -O2 -fprofile-generate -ftemporal-profile code.cc -o code3330 $ ./code3331 $ llvm-profdata merge -o code.profdata yyy/zzz3332 3333 Using the resulting profile, we can generate a function order to pass to the3334 linker via ``--symbol-ordering-file`` for ELF or ``-order_file`` for Mach-O.3335 3336 .. code-block:: console3337 3338 $ llvm-profdata order code.profdata -o code.orderfile3339 $ clang++ -O2 -Wl,--symbol-ordering-file=code.orderfile code.cc -o code3340 3341 Or the profile can be passed to LLD directly.3342 3343 .. code-block:: console3344 3345 $ clang++ -O2 -fuse-ld=lld -Wl,--irpgo-profile=code.profdata,--bp-startup-sort=function code.cc -o code3346 3347 For more information, please read the RFC:3348 https://discourse.llvm.org/t/rfc-temporal-profiling-extension-for-irpgo/680683349 3350Fine Tuning Profile Collection3351^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^3352 3353The PGO infrastructure provides user program knobs to fine tune profile3354collection. Specifically, the PGO runtime provides the following functions3355that can be used to control the regions in the program where profiles should3356be collected.3357 3358 * ``void __llvm_profile_set_filename(const char *Name)``: changes the name of3359 the profile file to ``Name``.3360 * ``void __llvm_profile_reset_counters(void)``: resets all counters to zero.3361 * ``int __llvm_profile_dump(void)``: write the profile data to disk.3362 3363For example, the following pattern can be used to skip profiling program3364initialization, profile two specific hot regions, and skip profiling program3365cleanup:3366 3367.. code-block:: c3368 3369 int main() {3370 initialize();3371 3372 // Reset all profile counters to 0 to omit profile collected during3373 // initialize()'s execution.3374 __llvm_profile_reset_counters();3375 ... hot region 13376 // Dump the profile for hot region 1.3377 __llvm_profile_set_filename("region1.profraw");3378 __llvm_profile_dump();3379 3380 // Reset counters before proceeding to hot region 2.3381 __llvm_profile_reset_counters();3382 ... hot region 23383 // Dump the profile for hot region 2.3384 __llvm_profile_set_filename("region2.profraw");3385 __llvm_profile_dump();3386 3387 // Since the profile has been dumped, no further profile data3388 // will be collected beyond the above __llvm_profile_dump().3389 cleanup();3390 return 0;3391 }3392 3393These APIs' names can be introduced to user programs in two ways.3394They can be declared as weak symbols on platforms which support3395treating weak symbols as ``null`` during linking. For example, the user can3396have3397 3398.. code-block:: c3399 3400 __attribute__((weak)) int __llvm_profile_dump(void);3401 3402 // Then later in the same source file3403 if (__llvm_profile_dump)3404 if (__llvm_profile_dump() != 0) { ... }3405 // The first if condition tests if the symbol is actually defined.3406 // Profile dumping only happens if the symbol is defined. Hence,3407 // the user program works correctly during normal (not profile-generate)3408 // executions.3409 3410Alternatively, the user program can include the header3411``profile/instr_prof_interface.h``, which contains the API names. For example,3412 3413.. code-block:: c3414 3415 #include "profile/instr_prof_interface.h"3416 3417 // Then later in the same source file3418 if (__llvm_profile_dump() != 0) { ... }3419 3420The user code does not need to check if the API names are defined, because3421these names are automatically replaced by ``(0)`` or the equivalence of noop3422if the ``clang`` is not compiling for profile generation.3423 3424Such replacement can happen because ``clang`` adds one of two macros depending3425on the ``-fprofile-generate`` and the ``-fprofile-use`` flags.3426 3427 * ``__LLVM_INSTR_PROFILE_GENERATE``: defined when one of3428 ``-fprofile[-instr]-generate``/``-fcs-profile-generate`` is in effect.3429 * ``__LLVM_INSTR_PROFILE_USE``: defined when one of3430 ``-fprofile-use``/``-fprofile-instr-use`` is in effect.3431 3432The two macros can be used to provide more flexibility so a user program3433can execute code specifically intended for profile generate or profile use.3434For example, a user program can have special logging during profile generate:3435 3436.. code-block:: c3437 3438 #if __LLVM_INSTR_PROFILE_GENERATE3439 expensive_logging_of_full_program_state();3440 #endif3441 3442The logging is automatically excluded during a normal build of the program,3443hence it does not impact performance during a normal execution.3444 3445It is advised to use such fine tuning only in a program's cold regions. The weak3446symbols can introduce extra control flow (the ``if`` checks), while the macros3447(hence declarations they guard in ``profile/instr_prof_interface.h``)3448can change the control flow of the functions that use them between profile3449generation and profile use (which can lead to discarded counters in such3450functions). Using these APIs in the program's cold regions introduces less3451overhead and leads to more optimized code.3452 3453Disabling Instrumentation3454^^^^^^^^^^^^^^^^^^^^^^^^^3455 3456In certain situations, it may be useful to disable profile generation or use3457for specific files in a build, without affecting the main compilation flags3458used for the other files in the project.3459 3460In these cases, you can use the flag ``-fno-profile-instr-generate`` (or3461``-fno-profile-generate``) to disable profile generation, and3462``-fno-profile-instr-use`` (or ``-fno-profile-use``) to disable profile use.3463 3464Note that these flags should appear after the corresponding profile3465flags to have an effect.3466 3467.. note::3468 3469 When none of the translation units inside a binary is instrumented, in the3470 case of Fuchsia the profile runtime will not be linked into the binary and3471 no profile will be produced, while on other platforms the profile runtime3472 will be linked and profile will be produced but there will not be any3473 counters.3474 3475Instrumenting only selected files or functions3476^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^3477 3478Sometimes it's useful to only instrument certain files or functions. For3479example in automated testing infrastructure, it may be desirable to only3480instrument files or functions that were modified by a patch to reduce the3481overhead of instrumenting a full system.3482 3483This can be done using the ``-fprofile-list`` option.3484 3485.. option:: -fprofile-list=<pathname>3486 3487 This option can be used to apply profile instrumentation only to selected3488 files or functions. ``pathname`` should point to a file in the3489 :doc:`SanitizerSpecialCaseList` format which selects which files and3490 functions to instrument.3491 3492 .. code-block:: console3493 3494 $ clang++ -O2 -fprofile-instr-generate -fprofile-list=fun.list code.cc -o code3495 3496 The option can be specified multiple times to pass multiple files.3497 3498 .. code-block:: console3499 3500 $ clang++ -O2 -fprofile-instr-generate -fcoverage-mapping -fprofile-list=fun.list -fprofile-list=code.list code.cc -o code3501 3502Supported sections are ``[clang]``, ``[llvm]``, ``[csllvm]``, and ``[sample-coldcov]`` representing3503clang PGO, IRPGO, CSIRPGO and sample PGO based cold function coverage, respectively. Supported prefixes 3504are ``function`` and ``source``. Supported categories are ``allow``, ``skip``, and ``forbid``.3505``skip`` adds the ``skipprofile`` attribute while ``forbid`` adds the3506``noprofile`` attribute to the appropriate function. Use3507``default:<allow|skip|forbid>`` to specify the default category.3508 3509 .. code-block:: console3510 3511 $ cat fun.list3512 # The following cases are for clang instrumentation.3513 [clang]3514 3515 # We might not want to profile functions that are inlined in many places.3516 function:inlinedLots=skip3517 3518 # We want to forbid profiling where it might be dangerous.3519 source:lib/unsafe/*.cc=forbid3520 3521 # Otherwise we allow profiling.3522 default:allow3523 3524Older Prefixes3525""""""""""""""3526 An older format is also supported, but it is only able to add the3527 ``noprofile`` attribute.3528 To filter individual functions or entire source files use ``fun:<name>`` or3529 ``src:<file>`` respectively. To exclude a function or a source file, use3530 ``!fun:<name>`` or ``!src:<file>`` respectively. The format also supports3531 wildcard expansion. The compiler generated functions are assumed to be located3532 in the main source file. It is also possible to restrict the filter to a3533 particular instrumentation type by using a named section.3534 3535 .. code-block:: none3536 3537 # all functions whose name starts with foo will be instrumented.3538 fun:foo*3539 3540 # except for foo1 which will be excluded from instrumentation.3541 !fun:foo13542 3543 # every function in path/to/foo.cc will be instrumented.3544 src:path/to/foo.cc3545 3546 # bar will be instrumented only when using backend instrumentation.3547 # Recognized section names are clang, llvm and csllvm.3548 [llvm]3549 fun:bar3550 3551 When the file contains only excludes, all files and functions except for the3552 excluded ones will be instrumented. Otherwise, only the files and functions3553 specified will be instrumented.3554 3555Instrument function groups3556^^^^^^^^^^^^^^^^^^^^^^^^^^3557 3558Sometimes it is desirable to minimize the size overhead of instrumented3559binaries. One way to do this is to partition functions into groups and only3560instrument functions in a specified group. This can be done using the3561`-fprofile-function-groups` and `-fprofile-selected-function-group` options.3562 3563.. option:: -fprofile-function-groups=<N>, -fprofile-selected-function-group=<i>3564 3565 The following uses 3 groups3566 3567 .. code-block:: console3568 3569 $ clang++ -Oz -fprofile-generate=group_0/ -fprofile-function-groups=3 -fprofile-selected-function-group=0 code.cc -o code.03570 $ clang++ -Oz -fprofile-generate=group_1/ -fprofile-function-groups=3 -fprofile-selected-function-group=1 code.cc -o code.13571 $ clang++ -Oz -fprofile-generate=group_2/ -fprofile-function-groups=3 -fprofile-selected-function-group=2 code.cc -o code.23572 3573 After collecting raw profiles from the three binaries, they can be merged into3574 a single profile like normal.3575 3576 .. code-block:: console3577 3578 $ llvm-profdata merge -output=code.profdata group_*/*.profraw3579 3580 3581Profile remapping3582^^^^^^^^^^^^^^^^^3583 3584When the program is compiled after a change that affects many symbol names,3585pre-existing profile data may no longer match the program. For example:3586 3587 * switching from libstdc++ to libc++ will result in the mangled names of all3588 functions taking standard library types to change3589 * renaming a widely-used type in C++ will result in the mangled names of all3590 functions that have parameters involving that type to change3591 * moving from a 32-bit compilation to a 64-bit compilation may change the3592 underlying type of ``size_t`` and similar types, resulting in changes to3593 manglings3594 3595Clang allows use of a profile remapping file to specify that such differences3596in mangled names should be ignored when matching the profile data against the3597program.3598 3599.. option:: -fprofile-remapping-file=<file>3600 3601 Specifies a file containing profile remapping information, that will be3602 used to match mangled names in the profile data to mangled names in the3603 program.3604 3605The profile remapping file is a text file containing lines of the form3606 3607.. code-block:: text3608 3609 fragmentkind fragment1 fragment23610 3611where ``fragmentkind`` is one of ``name``, ``type``, or ``encoding``,3612indicating whether the following mangled name fragments are3613<`name <https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangle.name>`_>s,3614<`type <https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangle.type>`_>s, or3615<`encoding <https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangle.encoding>`_>s,3616respectively.3617Blank lines and lines starting with ``#`` are ignored.3618 3619For convenience, built-in <substitution>s such as ``St`` and ``Ss``3620are accepted as <name>s (even though they technically are not <name>s).3621 3622For example, to specify that ``absl::string_view`` and ``std::string_view``3623should be treated as equivalent when matching profile data, the following3624remapping file could be used:3625 3626.. code-block:: text3627 3628 # absl::string_view is considered equivalent to std::string_view3629 type N4absl11string_viewE St17basic_string_viewIcSt11char_traitsIcEE3630 3631 # std:: might be std::__1:: in libc++ or std::__cxx11:: in libstdc++3632 name 3std St3__13633 name 3std St7__cxx113634 3635Matching profile data using a profile remapping file is supported on a3636best-effort basis. For example, information regarding indirect call targets is3637currently not remapped. For best results, you are encouraged to generate new3638profile data matching the updated program, or to remap the profile data3639using the ``llvm-cxxmap`` and ``llvm-profdata merge`` tools.3640 3641.. note::3642 3643 Profile data remapping is currently only supported for C++ mangled names3644 following the Itanium C++ ABI mangling scheme. This covers all C++ targets3645 supported by Clang other than Windows.3646 3647GCOV-based Profiling3648--------------------3649 3650GCOV is a test coverage program, it helps to know how often a line of code3651is executed. When instrumenting the code with ``--coverage`` option, some3652counters are added for each edge linking basic blocks.3653 3654At compile time, gcno files are generated containing information about3655blocks and edges between them. At runtime the counters are incremented and at3656exit the counters are dumped in gcda files.3657 3658The tool ``llvm-cov gcov`` will parse gcno, gcda and source files to generate3659a report ``.c.gcov``.3660 3661.. option:: -fprofile-filter-files=[regexes]3662 3663 Define a list of regexes separated by a semi-colon.3664 If a file name matches any of the regexes then the file is instrumented.3665 3666 .. code-block:: console3667 3668 $ clang --coverage -fprofile-filter-files=".*\.c$" foo.c3669 3670 For example, this will only instrument files finishing with ``.c``, skipping ``.h`` files.3671 3672.. option:: -fprofile-exclude-files=[regexes]3673 3674 Define a list of regexes separated by a semi-colon.3675 If a file name doesn't match all the regexes then the file is instrumented.3676 3677 .. code-block:: console3678 3679 $ clang --coverage -fprofile-exclude-files="^/usr/include/.*$" foo.c3680 3681 For example, this will instrument all the files except the ones in ``/usr/include``.3682 3683If both options are used then a file is instrumented if its name matches any3684of the regexes from ``-fprofile-filter-list`` and doesn't match all the regexes3685from ``-fprofile-exclude-list``.3686 3687.. code-block:: console3688 3689 $ clang --coverage -fprofile-exclude-files="^/usr/include/.*$" \3690 -fprofile-filter-files="^/usr/.*$"3691 3692In that case ``/usr/foo/oof.h`` is instrumented since it matches the filter regex and3693doesn't match the exclude regex, but ``/usr/include/foo.h`` doesn't since it matches3694the exclude regex.3695 3696Controlling Debug Information3697-----------------------------3698 3699Controlling Size of Debug Information3700^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^3701 3702Debug info kind generated by Clang can be set by one of the flags listed3703below. If multiple flags are present, the last one is used.3704 3705.. option:: -g03706 3707 Don't generate any debug info (default).3708 3709.. option:: -gline-tables-only3710 3711 Generate line number tables only.3712 3713 This kind of debug info allows to obtain stack traces with function names,3714 file names and line numbers (by such tools as ``gdb`` or ``addr2line``). It3715 doesn't contain any other data (e.g. description of local variables or3716 function parameters).3717 3718.. option:: -fstandalone-debug3719 3720 Clang supports a number of optimizations to reduce the size of debug3721 information in the binary. They work based on the assumption that3722 the debug type information can be spread out over multiple3723 compilation units. Specifically, the optimizations are:3724 3725 - will not emit type definitions for types that are not needed by a3726 module and could be replaced with a forward declaration.3727 - will only emit type info for a dynamic C++ class in the module that3728 contains the vtable for the class.3729 - will only emit type info for a C++ class (non-trivial, non-aggregate)3730 in the modules that contain a definition for one of its constructors.3731 - will only emit type definitions for types that are the subject of explicit3732 template instantiation declarations in the presence of an explicit3733 instantiation definition for the type.3734 3735 The **-fstandalone-debug** option turns off these optimizations.3736 This is useful when working with 3rd-party libraries that don't come3737 with debug information. Note that Clang will never emit type3738 information for types that are not referenced at all by the program.3739 3740.. option:: -fno-standalone-debug3741 3742 On Darwin **-fstandalone-debug** is enabled by default. The3743 **-fno-standalone-debug** option can be used to get to turn on the3744 vtable-based optimization described above.3745 3746.. option:: -g3747 3748 Generate complete debug info.3749 3750.. option:: -feliminate-unused-debug-types3751 3752 By default, Clang does not emit type information for types that are defined3753 but not used in a program. To retain the debug info for these unused types,3754 the negation **-fno-eliminate-unused-debug-types** can be used.3755 This can be particularly useful on Windows, when using NATVIS files that3756 can reference const symbols that would otherwise be stripped, even in full3757 debug or standalone debug modes.3758 3759Controlling Macro Debug Info Generation3760^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^3761 3762Debug info for C preprocessor macros increases the size of debug information in3763the binary. Macro debug info generated by Clang can be controlled by the flags3764listed below.3765 3766.. option:: -fdebug-macro3767 3768 Generate debug info for preprocessor macros. This flag is discarded when3769 **-g0** is enabled.3770 3771.. option:: -fno-debug-macro3772 3773 Do not generate debug info for preprocessor macros (default).3774 3775Controlling Debugger "Tuning"3776^^^^^^^^^^^^^^^^^^^^^^^^^^^^^3777 3778While Clang generally emits standard DWARF debug info (http://dwarfstd.org),3779different debuggers may know how to take advantage of different specific DWARF3780features. You can "tune" the debug info for one of several different debuggers.3781 3782.. option:: -ggdb, -glldb, -gsce, -gdbx3783 3784 Tune the debug info for the ``gdb``, ``lldb``, Sony PlayStation\ |reg|3785 debugger, or ``dbx``, respectively. Each of these options implies **-g**.3786 (Therefore, if you want both **-gline-tables-only** and debugger tuning, the3787 tuning option must come first.)3788 3789Controlling LLVM IR Output3790--------------------------3791 3792Controlling Value Names in LLVM IR3793^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^3794 3795Emitting value names in LLVM IR increases the size and verbosity of the IR.3796By default, value names are only emitted in assertion-enabled builds of Clang.3797However, when reading IR it can be useful to re-enable the emission of value3798names to improve readability.3799 3800.. option:: -fdiscard-value-names3801 3802 Discard value names when generating LLVM IR.3803 3804.. option:: -fno-discard-value-names3805 3806 Do not discard value names when generating LLVM IR. This option can be used3807 to re-enable names for release builds of Clang.3808 3809 3810Comment Parsing Options3811-----------------------3812 3813Clang parses Doxygen and non-Doxygen style documentation comments and attaches3814them to the appropriate declaration nodes. By default, it only parses3815Doxygen-style comments and ignores ordinary comments starting with ``//`` and3816``/*``.3817 3818.. option:: -Wdocumentation3819 3820 Emit warnings about use of documentation comments. This warning group is off3821 by default.3822 3823 This includes checking that ``\param`` commands name parameters that actually3824 present in the function signature, checking that ``\returns`` is used only on3825 functions that actually return a value etc.3826 3827.. option:: -Wno-documentation-unknown-command3828 3829 Don't warn when encountering an unknown Doxygen command.3830 3831.. option:: -fparse-all-comments3832 3833 Parse all comments as documentation comments (including ordinary comments3834 starting with ``//`` and ``/*``).3835 3836.. option:: -fcomment-block-commands=[commands]3837 3838 Define custom documentation commands as block commands. This allows Clang to3839 construct the correct AST for these custom commands, and silences warnings3840 about unknown commands. Several commands must be separated by a comma3841 *without trailing space*; e.g. ``-fcomment-block-commands=foo,bar`` defines3842 custom commands ``\foo`` and ``\bar``.3843 3844 It is also possible to use ``-fcomment-block-commands`` several times; e.g.3845 ``-fcomment-block-commands=foo -fcomment-block-commands=bar`` does the same3846 as above.3847 3848.. _ccc-override-options:3849 3850CCC_OVERRIDE_OPTIONS3851--------------------3852The environment variable ``CCC_OVERRIDE_OPTIONS`` can be used to edit clang's3853command line arguments. The value of this variable is a space-separated list of3854edits to perform. The edits are applied in the order in which they appear in3855``CCC_OVERRIDE_OPTIONS``. Each edit should be one of the following forms:3856 3857- ``#``: Silence information about the changes to the command line arguments.3858 3859- ``^FOO``: Add ``FOO`` as a new argument at the beginning of the command line3860 right after the name of the compiler executable.3861 3862- ``+FOO``: Add ``FOO`` as a new argument at the end of the command line.3863 3864- ``s/XXX/YYY/``: Substitute the regular expression ``XXX`` with ``YYY`` in the3865 command line.3866 3867- ``xOPTION``: Removes all instances of the literal argument ``OPTION``.3868 3869- ``XOPTION``: Removes all instances of the literal argument ``OPTION``, and the3870 following argument.3871 3872- ``Ox``: Removes all flags matching ``O`` or ``O[sz0-9]`` and adds ``Ox`` at3873 the end of the command line.3874 3875This environment variable does not affect the options added by the config files.3876 3877.. _c:3878 3879C Language Features3880===================3881 3882The support for standard C in Clang is mostly feature-complete, see the `C3883status page <https://clang.llvm.org/c_status.html>`_ for more details.3884 3885Extensions supported by clang3886-----------------------------3887 3888See :doc:`LanguageExtensions`.3889 3890Differences between various standard modes3891------------------------------------------3892 3893clang supports the ``-std`` option, which changes what language mode clang uses.3894The supported modes for C are c89, gnu89, c94, c99, gnu99, c11, gnu11, c17,3895gnu17, c23, gnu23, c2y, gnu2y, and various aliases for those modes. If no ``-std``3896option is specified, clang defaults to gnu17 mode. Many C99 and C11 features3897are supported in earlier modes as a conforming extension, with a warning. Use3898``-pedantic-errors`` to request an error if a feature from a later standard3899revision is used in an earlier mode.3900 3901Differences between all ``c*`` and ``gnu*`` modes:3902 3903- ``c*`` modes define "``__STRICT_ANSI__``".3904- Target-specific defines not prefixed by underscores, like ``linux``,3905 are defined in ``gnu*`` modes.3906- Trigraphs default to being off in ``gnu*`` modes; they can be enabled3907 by the ``-trigraphs`` option.3908- The parser recognizes ``asm`` and ``typeof`` as keywords in ``gnu*`` modes;3909 the variants ``__asm__`` and ``__typeof__`` are recognized in all modes.3910- The parser recognizes ``inline`` as a keyword in ``gnu*`` mode, in3911 addition to recognizing it in the ``*99`` and later modes for which it is3912 part of the ISO C standard. The variant ``__inline__`` is recognized in all3913 modes.3914- The Apple "blocks" extension is recognized by default in ``gnu*`` modes3915 on some platforms; it can be enabled in any mode with the ``-fblocks``3916 option.3917 3918Differences between ``*89`` and ``*94`` modes:3919 3920- Digraphs are not recognized in c89 mode.3921 3922Differences between ``*94`` and ``*99`` modes:3923 3924- The ``*99`` modes default to implementing ``inline`` / ``__inline__``3925 as specified in C99, while the ``*89`` modes implement the GNU version.3926 This can be overridden for individual functions with the ``__gnu_inline__``3927 attribute.3928- The scope of names defined inside a ``for``, ``if``, ``switch``, ``while``,3929 or ``do`` statement is different. (example: ``if ((struct x {int x;}*)0) {}``.)3930- ``__STDC_VERSION__`` is not defined in ``*89`` modes.3931- ``inline`` is not recognized as a keyword in ``c89`` mode.3932- ``restrict`` is not recognized as a keyword in ``*89`` modes.3933- Commas are allowed in integer constant expressions in ``*99`` modes.3934- Arrays which are not lvalues are not implicitly promoted to pointers3935 in ``*89`` modes.3936- Some warnings are different.3937 3938Differences between ``*99`` and ``*11`` modes:3939 3940- Warnings for use of C11 features are disabled.3941- ``__STDC_VERSION__`` is defined to ``201112L`` rather than ``199901L``.3942 3943Differences between ``*11`` and ``*17`` modes:3944 3945- ``__STDC_VERSION__`` is defined to ``201710L`` rather than ``201112L``.3946 3947Differences between ``*17`` and ``*23`` modes:3948 3949- ``__STDC_VERSION__`` is defined to ``202311L`` rather than ``201710L``.3950- ``nullptr`` and ``nullptr_t`` are supported, only in ``*23`` mode.3951- ``ATOMIC_VAR_INIT`` is removed from ``*23`` mode.3952- ``bool``, ``true``, ``false``, ``alignas``, ``alignof``, ``static_assert``,3953 and ``thread_local`` are now first-class keywords, only in ``*23`` mode.3954- ``typeof`` and ``typeof_unqual`` are supported, only ``*23`` mode.3955- Bit-precise integers (``_BitInt(N)``) are supported by default in ``*23``3956 mode, and as an extension in ``*17`` and earlier modes.3957- ``[[]]`` attributes are supported by default in ``*23`` mode, and as an3958 extension in ``*17`` and earlier modes.3959 3960Differences between ``*23`` and ``*2y`` modes:3961 3962- ``__STDC_VERSION__`` is defined to ``202400L`` rather than ``202311L``.3963 3964GCC extensions not implemented yet3965----------------------------------3966 3967clang tries to be compatible with gcc as much as possible, but some gcc3968extensions are not implemented:3969 3970- clang does not support decimal floating point types (``_Decimal32`` and3971 friends) yet.3972- clang only supports global register variables when the register specified3973 is non-allocatable (e.g. the stack pointer). Support for general global3974 register variables is unlikely to be implemented soon because it requires3975 additional LLVM backend support.3976- clang does not support static initialization of flexible array3977 members. This appears to be a rarely used extension, but could be3978 implemented pending user demand.3979- clang does not support3980 ``__builtin_va_arg_pack``/``__builtin_va_arg_pack_len``. This is3981 used rarely, but in some potentially interesting places, like the3982 glibc headers, so it may be implemented pending user demand. Note3983 that because clang pretends to be like GCC 4.2, and this extension3984 was introduced in 4.3, the glibc headers will not try to use this3985 extension with clang at the moment.3986 3987This is not a complete list; if you find an unsupported extension3988missing from this list, please file a `feature request <https://github.com/llvm/llvm-project/issues/>`_.3989This list currently excludes C++; see :ref:`C++ Language Features <cxx>`. Also,3990this list does not include bugs in mostly-implemented features; please see the3991`issues list <https://github.com/llvm/llvm-project/issues/>`_ for known existing3992bugs.3993 3994Intentionally unsupported GCC extensions3995----------------------------------------3996 3997- clang does not support the gcc extension that allows variable-length3998 arrays in structures. This is for a few reasons: one, it is tricky to3999 implement, two, the extension is completely undocumented, and three,4000 the extension appears to be rarely used. Note that clang *does*4001 support flexible array members (arrays with a zero or unspecified4002 size at the end of a structure).4003- GCC accepts many expression forms that are not valid integer constant4004 expressions in bit-field widths, enumerator constants, case labels,4005 and in array bounds at global scope. Clang also accepts additional4006 expression forms in these contexts, but constructs that GCC accepts due to4007 simplifications GCC performs while parsing, such as ``x - x`` (where ``x`` is a4008 variable) will likely never be accepted by Clang.4009- clang does not support ``__builtin_apply`` and friends; this extension4010 is extremely obscure and difficult to implement reliably.4011- clang does not support the gcc extension for forward-declaring4012 function parameters.4013- clang does not support nested functions; this is a complex feature which is4014 infrequently used, so it is unlikely to be implemented. In C++11 it can be4015 emulated by assigning lambda functions to local variables, e.g:4016 4017 .. code-block:: cpp4018 4019 auto const local_function = [&](int parameter) {4020 // Do something4021 };4022 ...4023 local_function(1);4024 4025 4026.. _c_ms:4027 4028Microsoft extensions4029--------------------4030 4031clang has support for many extensions from Microsoft Visual C++. To enable these4032extensions, use the ``-fms-extensions`` command-line option. This is the default4033for Windows targets. Clang does not implement every pragma or declspec provided4034by MSVC, but the popular ones, such as ``__declspec(dllexport)`` and ``#pragma4035comment(lib)`` are well supported.4036 4037clang has a ``-fms-compatibility`` flag that makes clang accept enough4038invalid C++ to be able to parse most Microsoft headers. For example, it4039allows `unqualified lookup of dependent base class members4040<https://clang.llvm.org/compatibility.html#dep_lookup_bases>`_, which is4041a common compatibility issue with clang. This flag is enabled by default4042for Windows targets.4043 4044``-fdelayed-template-parsing`` lets clang delay parsing of function template4045definitions until the end of a translation unit. This flag is enabled by4046default for Windows targets.4047 4048For compatibility with existing code that compiles with MSVC, clang defines the4049``_MSC_VER`` and ``_MSC_FULL_VER`` macros. When on Windows, these default to4050either the same value as the currently installed version of cl.exe, or ``1933``4051and ``193300000`` (respectively). The ``-fms-compatibility-version=`` flag4052overrides these values. It accepts a dotted version tuple, such as 19.00.23506.4053Changing the MSVC compatibility version makes clang behave more like that4054version of MSVC. For example, ``-fms-compatibility-version=19`` will enable4055C++14 features and define ``char16_t`` and ``char32_t`` as builtin types.4056 4057.. _cxx:4058 4059C++ Language Features4060=====================4061 4062clang fully implements all of standard C++98 except for exported4063templates (which were removed in C++11), all of standard C++11,4064C++14, and C++17, and most of C++20 and C++23.4065 4066See the `C++ support in Clang <https://clang.llvm.org/cxx_status.html>`_ page4067for detailed information on C++ feature support across Clang versions.4068 4069Controlling implementation limits4070---------------------------------4071 4072.. option:: -fbracket-depth=N4073 4074 Sets the limit for nested parentheses, brackets, and braces to N. The4075 default is 256.4076 4077.. option:: -fconstexpr-depth=N4078 4079 Sets the limit for constexpr function invocations to N. The default is 512.4080 4081.. option:: -fconstexpr-steps=N4082 4083 Sets the limit for the number of full-expressions evaluated in a single4084 constant expression evaluation. This also controls the maximum size4085 of array and dynamic array allocation that can be constant evaluated.4086 The default is 1048576, and the limit can be disabled with `-fconstexpr-steps=0`.4087 4088.. option:: -ftemplate-depth=N4089 4090 Sets the limit for recursively nested template instantiations to N. The4091 default is 1024.4092 4093.. option:: -foperator-arrow-depth=N4094 4095 Sets the limit for iterative calls to 'operator->' functions to N. The4096 default is 256.4097 4098.. _objc:4099 4100Objective-C Language Features4101=============================4102 4103.. _objcxx:4104 4105Objective-C++ Language Features4106===============================4107 4108.. _openmp:4109 4110OpenMP Features4111===============4112 4113Clang supports all OpenMP 4.5 directives and clauses. See :doc:`OpenMPSupport`4114for additional details.4115 4116Use `-fopenmp` to enable OpenMP. Support for OpenMP can be disabled with4117`-fno-openmp`.4118 4119Use `-fopenmp-simd` to enable OpenMP simd features only, without linking4120the runtime library; for combined constructs4121(e.g. ``#pragma omp parallel for simd``) the non-simd directives and clauses4122will be ignored. This can be disabled with `-fno-openmp-simd`.4123 4124Controlling implementation limits4125---------------------------------4126 4127.. option:: -fopenmp-use-tls4128 4129 Controls code generation for OpenMP threadprivate variables. In presence of4130 this option all threadprivate variables are generated the same way as thread4131 local variables, using TLS support. If `-fno-openmp-use-tls`4132 is provided or target does not support TLS, code generation for threadprivate4133 variables relies on OpenMP runtime library.4134 4135.. _opencl:4136 4137OpenCL Features4138===============4139 4140Clang can be used to compile OpenCL kernels for execution on a device4141(e.g. GPU). It is possible to compile the kernel into a binary (e.g. for AMDGPU)4142that can be uploaded to run directly on a device (e.g. using4143`clCreateProgramWithBinary4144<https://www.khronos.org/registry/OpenCL/specs/opencl-1.1.pdf#111>`_) or4145into generic bitcode files loadable into other toolchains.4146 4147Compiling to a binary using the default target from the installation can be done4148as follows:4149 4150 .. code-block:: console4151 4152 $ echo "kernel void k(){}" > test.cl4153 $ clang test.cl4154 4155Compiling for a specific target can be done by specifying the triple corresponding4156to the target, for example:4157 4158 .. code-block:: console4159 4160 $ clang --target=nvptx64-unknown-unknown test.cl4161 $ clang --target=amdgcn-amd-amdhsa -mcpu=gfx900 test.cl4162 4163Compiling to bitcode can be done as follows:4164 4165 .. code-block:: console4166 4167 $ clang -c -emit-llvm test.cl4168 4169This will produce a file `test.bc` that can be used in vendor toolchains4170to perform machine code generation.4171 4172Note that if compiled to bitcode for generic targets such as SPIR/SPIR-V,4173portable IR is produced that can be used with various vendor4174tools as well as open source tools such as `SPIRV-LLVM Translator4175<https://github.com/KhronosGroup/SPIRV-LLVM-Translator>`_4176to produce SPIR-V binary. More details are provided in `the offline4177compilation from OpenCL kernel sources into SPIR-V using open source4178tools4179<https://github.com/KhronosGroup/OpenCL-Guide/blob/main/chapters/os_tooling.md>`_.4180From clang 14 onwards SPIR-V can be generated directly as detailed in4181:ref:`the SPIR-V support section <spir-v>`.4182 4183Clang currently supports OpenCL C language standards up to v2.0. Clang mainly4184supports full profile. There is only very limited support of the embedded4185profile.4186From clang 9 a C++ mode is available for OpenCL (see4187:ref:`C++ for OpenCL <cxx_for_opencl>`).4188 4189OpenCL v3.0 support is complete but it remains in experimental state, see more4190details about the experimental features and limitations in :doc:`OpenCLSupport`4191page.4192 4193OpenCL Specific Options4194-----------------------4195 4196Most of the OpenCL build options from `the specification v2.0 section 5.8.44197<https://www.khronos.org/registry/cl/specs/opencl-2.0.pdf#200>`_ are available.4198 4199Examples:4200 4201 .. code-block:: console4202 4203 $ clang -cl-std=CL2.0 -cl-single-precision-constant test.cl4204 4205 4206Many flags used for the compilation for C sources can also be passed while4207compiling for OpenCL, examples: ``-c``, ``-O<1-4|s>``, ``-o``, ``-emit-llvm``, etc.4208 4209Some extra options are available to support special OpenCL features.4210 4211.. option:: -cl-no-stdinc4212 4213 Allows to disable all extra types and functions that are not native to the compiler.4214 This might reduce the compilation speed marginally but many declarations from the4215 OpenCL standard will not be accessible. For example, the following will fail to4216 compile.4217 4218 .. code-block:: console4219 4220 $ echo "bool is_wg_uniform(int i){return get_enqueued_local_size(i)==get_local_size(i);}" > test.cl4221 $ clang -cl-std=CL2.0 -cl-no-stdinc test.cl4222 error: use of undeclared identifier 'get_enqueued_local_size'4223 error: use of undeclared identifier 'get_local_size'4224 4225 More information about the standard types and functions is provided in :ref:`the4226 section on the OpenCL Header <opencl_header>`.4227 4228.. _opencl_cl_ext:4229 4230.. option:: -cl-ext4231 4232 Enables/Disables support of OpenCL extensions and optional features. All OpenCL4233 targets set a list of extensions that they support. Clang allows to amend this using4234 the ``-cl-ext`` flag with a comma-separated list of extensions prefixed with4235 ``'+'`` or ``'-'``. The syntax: ``-cl-ext=<(['-'|'+']<extension>[,])+>``, where4236 extensions can be either one of `the OpenCL published extensions4237 <https://www.khronos.org/registry/OpenCL>`_4238 or any vendor extension. Alternatively, ``'all'`` can be used to enable4239 or disable all known extensions.4240 4241 Example disabling double support for the 64-bit SPIR-V target:4242 4243 .. code-block:: console4244 4245 $ clang -c --target=spirv64 -cl-ext=-cl_khr_fp64 test.cl4246 4247 Enabling all extensions except double support in R600 AMD GPU can be done using:4248 4249 .. code-block:: console4250 4251 $ clang --target=r600 -cl-ext=-all,+cl_khr_fp16 test.cl4252 4253 Note that some generic targets e.g. SPIR/SPIR-V enable all extensions/features in4254 clang by default.4255 4256OpenCL Targets4257--------------4258 4259OpenCL targets are derived from the regular Clang target classes. The OpenCL4260specific parts of the target representation provide address space mapping as4261well as a set of supported extensions.4262 4263Specific Targets4264^^^^^^^^^^^^^^^^4265 4266There is a set of concrete HW architectures that OpenCL can be compiled for.4267 4268- For AMD target:4269 4270 .. code-block:: console4271 4272 $ clang --target=amdgcn-amd-amdhsa -mcpu=gfx900 test.cl4273 4274- For Nvidia architectures:4275 4276 .. code-block:: console4277 4278 $ clang --target=nvptx64-unknown-unknown test.cl4279 4280 4281Generic Targets4282^^^^^^^^^^^^^^^4283 4284- A SPIR-V binary can be produced for 32- or 64-bit targets.4285 4286 .. code-block:: console4287 4288 $ clang --target=spirv32 -c test.cl4289 $ clang --target=spirv64 -c test.cl4290 4291 More details can be found in :ref:`the SPIR-V support section <spir-v>`.4292 4293- SPIR is available as a generic target to allow portable bitcode to be produced4294 that can be used across GPU toolchains. The implementation follows `the SPIR4295 specification <https://www.khronos.org/spir>`_. There are two flavors4296 available for 32 and 64 bits.4297 4298 .. code-block:: console4299 4300 $ clang --target=spir test.cl -emit-llvm -c4301 $ clang --target=spir64 test.cl -emit-llvm -c4302 4303 Clang will generate SPIR v1.2 compatible IR for OpenCL versions up to 2.0 and4304 SPIR v2.0 for OpenCL v2.0 or C++ for OpenCL.4305 4306- x86 is used by some implementations that are x86 compatible and currently4307 remains for backwards compatibility (with older implementations prior to4308 SPIR target support). For "non-SPMD" targets which cannot spawn multiple4309 work-items on the fly using hardware, which covers practically all non-GPU4310 devices such as CPUs and DSPs, additional processing is needed for the kernels4311 to support multiple work-item execution. For this, a 3rd party toolchain,4312 such as for example `POCL <http://portablecl.org/>`_, can be used.4313 4314 This target does not support multiple memory segments and, therefore, the fake4315 address space map can be added using the :ref:`-ffake-address-space-map4316 <opencl_fake_address_space_map>` flag.4317 4318 All known OpenCL extensions and features are set to supported in the generic targets,4319 however :option:`-cl-ext` flag can be used to toggle individual extensions and4320 features.4321 4322.. _opencl_header:4323 4324OpenCL Header4325-------------4326 4327By default Clang will include standard headers and therefore most of OpenCL4328builtin functions and types are available during compilation. The4329default declarations of non-native compiler types and functions can be disabled4330by using flag :option:`-cl-no-stdinc`.4331 4332The following example demonstrates that OpenCL kernel sources with various4333standard builtin functions can be compiled without the need for an explicit4334includes or compiler flags.4335 4336 .. code-block:: console4337 4338 $ echo "bool is_wg_uniform(int i){return get_enqueued_local_size(i)==get_local_size(i);}" > test.cl4339 $ clang -cl-std=CL2.0 test.cl4340 4341More information about the default headers is provided in :doc:`OpenCLSupport`.4342 4343OpenCL Extensions4344-----------------4345 4346Most of the ``cl_khr_*`` extensions to OpenCL C from `the official OpenCL4347registry <https://www.khronos.org/registry/OpenCL/>`_ are available and4348configured per target depending on the support available in the specific4349architecture.4350 4351It is possible to alter the default extensions setting per target using4352``-cl-ext`` flag. (See :ref:`flags description <opencl_cl_ext>` for more details).4353 4354Vendor extensions can be added flexibly by declaring the list of types and4355functions associated with each extensions enclosed within the following4356compiler pragma directives:4357 4358 .. code-block:: c4359 4360 #pragma OPENCL EXTENSION the_new_extension_name : begin4361 // declare types and functions associated with the extension here4362 #pragma OPENCL EXTENSION the_new_extension_name : end4363 4364For example, parsing the following code adds ``my_t`` type and ``my_func``4365function to the custom ``my_ext`` extension.4366 4367 .. code-block:: c4368 4369 #pragma OPENCL EXTENSION my_ext : begin4370 typedef struct{4371 int a;4372 }my_t;4373 void my_func(my_t);4374 #pragma OPENCL EXTENSION my_ext : end4375 4376There is no conflict resolution for identifier clashes among extensions.4377It is therefore recommended that the identifiers are prefixed with a4378double underscore to avoid clashing with user space identifiers. Vendor4379extension should use reserved identifier prefix e.g. amd, arm, intel.4380 4381Clang also supports language extensions documented in `The OpenCL C Language4382Extensions Documentation4383<https://github.com/KhronosGroup/Khronosdotorg/blob/main/api/opencl/assets/OpenCL_LangExt.pdf>`_.4384 4385OpenCL-Specific Attributes4386--------------------------4387 4388OpenCL support in Clang contains a set of attribute taken directly from the4389specification as well as additional attributes.4390 4391See also :doc:`AttributeReference`.4392 4393nosvm4394^^^^^4395 4396Clang supports this attribute to comply to OpenCL v2.0 conformance, but it4397does not have any effect on the IR. For more details refer to the specification4398`section 6.7.24399<https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#49>`_4400 4401 4402opencl_unroll_hint4403^^^^^^^^^^^^^^^^^^4404 4405The implementation of this feature mirrors the unroll hint for C.4406More details on the syntax can be found in the specification4407`section 6.11.54408<https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#61>`_4409 4410convergent4411^^^^^^^^^^4412 4413To make sure no invalid optimizations occur for single program multiple data4414(SPMD) / single instruction multiple thread (SIMT) Clang provides attributes that4415can be used for special functions that have cross work item semantics.4416An example is the subgroup operations such as `intel_sub_group_shuffle4417<https://www.khronos.org/registry/cl/extensions/intel/cl_intel_subgroups.txt>`_4418 4419 .. code-block:: c4420 4421 // Define custom my_sub_group_shuffle(data, c)4422 // that makes use of intel_sub_group_shuffle4423 r1 = ...4424 if (r0) r1 = computeA();4425 // Shuffle data from r1 into r34426 // of threads id r2.4427 r3 = my_sub_group_shuffle(r1, r2);4428 if (r0) r3 = computeB();4429 4430with non-SPMD semantics this is optimized to the following equivalent code:4431 4432 .. code-block:: c4433 4434 r1 = ...4435 if (!r0)4436 // Incorrect functionality! The data in r14437 // have not been computed by all threads yet.4438 r3 = my_sub_group_shuffle(r1, r2);4439 else {4440 r1 = computeA();4441 r3 = my_sub_group_shuffle(r1, r2);4442 r3 = computeB();4443 }4444 4445Declaring the function ``my_sub_group_shuffle`` with the convergent attribute4446would prevent this:4447 4448 .. code-block:: c4449 4450 my_sub_group_shuffle() __attribute__((convergent));4451 4452Using ``convergent`` guarantees correct execution by keeping CFG equivalence4453wrt operations marked as ``convergent``. CFG ``G´`` is equivalent to ``G`` wrt4454node ``Ni`` : ``iff ∀ Nj (i≠j)`` domination and post-domination relations with4455respect to ``Ni`` remain the same in both ``G`` and ``G´``.4456 4457noduplicate4458^^^^^^^^^^^4459 4460``noduplicate`` is more restrictive with respect to optimizations than4461``convergent`` because a convergent function only preserves CFG equivalence.4462This allows some optimizations to happen as long as the control flow remains4463unmodified.4464 4465 .. code-block:: c4466 4467 for (int i=0; i<4; i++)4468 my_sub_group_shuffle()4469 4470can be modified to:4471 4472 .. code-block:: c4473 4474 my_sub_group_shuffle();4475 my_sub_group_shuffle();4476 my_sub_group_shuffle();4477 my_sub_group_shuffle();4478 4479while using ``noduplicate`` would disallow this. Also ``noduplicate`` doesn't4480have the same safe semantics of CFG as ``convergent`` and can cause changes in4481CFG that modify semantics of the original program.4482 4483``noduplicate`` is kept for backwards compatibility only and it considered to be4484deprecated for future uses.4485 4486.. _cxx_for_opencl:4487 4488C++ for OpenCL4489--------------4490 4491Starting from clang 9 kernel code can contain C++17 features: classes, templates,4492function overloading, type deduction, etc. Please note that this is not an4493implementation of `OpenCL C++4494<https://www.khronos.org/registry/OpenCL/specs/2.2/pdf/OpenCL_Cxx.pdf>`_ and4495there is no plan to support it in clang in any new releases in the near future.4496 4497Clang currently supports C++ for OpenCL 1.0 and 2021.4498For detailed information about this language refer to the C++ for OpenCL4499Programming Language Documentation available4500in `the latest build4501<https://www.khronos.org/opencl/assets/CXX_for_OpenCL.html>`_4502or in `the official release4503<https://github.com/KhronosGroup/OpenCL-Docs/releases/tag/cxxforopencl-docrev2021.12>`_.4504 4505To enable the C++ for OpenCL mode, pass one of following command line options when4506compiling ``.clcpp`` file:4507 4508- C++ for OpenCL 1.0: ``-cl-std=clc++``, ``-cl-std=CLC++``, ``-cl-std=clc++1.0``,4509 ``-cl-std=CLC++1.0``, ``-std=clc++``, ``-std=CLC++``, ``-std=clc++1.0`` or4510 ``-std=CLC++1.0``.4511 4512- C++ for OpenCL 2021: ``-cl-std=clc++2021``, ``-cl-std=CLC++2021``,4513 ``-std=clc++2021``, ``-std=CLC++2021``.4514 4515Example of use:4516 .. code-block:: c++4517 4518 template<class T> T add( T x, T y )4519 {4520 return x + y;4521 }4522 4523 __kernel void test( __global float* a, __global float* b)4524 {4525 auto index = get_global_id(0);4526 a[index] = add(b[index], b[index+1]);4527 }4528 4529 4530 .. code-block:: console4531 4532 clang -cl-std=clc++1.0 test.clcpp4533 clang -cl-std=clc++ -c --target=spirv64 test.cl4534 4535 4536By default, files with ``.clcpp`` extension are compiled with the C++ for4537OpenCL 1.0 mode.4538 4539 .. code-block:: console4540 4541 clang test.clcpp4542 4543For backward compatibility files with ``.cl`` extensions can also be compiled4544in C++ for OpenCL mode but the desirable language mode must be activated with4545a flag.4546 4547 .. code-block:: console4548 4549 clang -cl-std=clc++ test.cl4550 4551Support of C++ for OpenCL 2021 is currently in experimental phase, refer to4552:doc:`OpenCLSupport` for more details.4553 4554C++ for OpenCL kernel sources can also be compiled online in drivers supporting4555`cl_ext_cxx_for_opencl4556<https://www.khronos.org/registry/OpenCL/extensions/ext/cl_ext_cxx_for_opencl.html>`_4557extension.4558 4559Constructing and destroying global objects4560^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^4561 4562Global objects with non-trivial constructors require the constructors to be run4563before the first kernel using the global objects is executed. Similarly global4564objects with non-trivial destructors require destructor invocation just after4565the last kernel using the program objects is executed.4566In OpenCL versions earlier than v2.2 there is no support for invoking global4567constructors. However, an easy workaround is to manually enqueue the4568constructor initialization kernel that has the following name scheme4569``_GLOBAL__sub_I_<compiled file name>``.4570This kernel is only present if there are global objects with non-trivial4571constructors present in the compiled binary. One way to check this is by4572passing ``CL_PROGRAM_KERNEL_NAMES`` to ``clGetProgramInfo`` (OpenCL v2.04573s5.8.7) and then checking whether any kernel name matches the naming scheme of4574global constructor initialization kernel above.4575 4576Note that if multiple files are compiled and linked into libraries, multiple4577kernels that initialize global objects for multiple modules would have to be4578invoked.4579 4580Applications are currently required to run initialization of global objects4581manually before running any kernels in which the objects are used.4582 4583 .. code-block:: console4584 4585 clang -cl-std=clc++ test.cl4586 4587If there are any global objects to be initialized, the final binary will4588contain the ``_GLOBAL__sub_I_test.cl`` kernel to be enqueued.4589 4590Note that the manual workaround only applies to objects declared at the4591program scope. There is no manual workaround for the construction of static4592objects with non-trivial constructors inside functions.4593 4594Global destructors can not be invoked manually in the OpenCL v2.0 drivers.4595However, all memory used for program scope objects should be released on4596``clReleaseProgram``.4597 4598Libraries4599^^^^^^^^^4600Limited experimental support of C++ standard libraries for OpenCL is4601described in :doc:`OpenCLSupport` page.4602 4603.. _target_features:4604 4605Target-Specific Features and Limitations4606========================================4607 4608CPU Architectures Features and Limitations4609------------------------------------------4610 4611X864612^^^4613 4614The support for X86 (both 32-bit and 64-bit) is considered stable on4615Darwin (macOS), Linux, FreeBSD, and Dragonfly BSD: it has been tested4616to correctly compile many large C, C++, Objective-C, and Objective-C++4617codebases.4618 4619On ``x86_64-mingw32``, passing i128(by value) is incompatible with the4620Microsoft x64 calling convention. You might need to tweak4621``WinX86_64ABIInfo::classify()`` in ``lib/CodeGen/Targets/X86.cpp``.4622 4623For the X86 target, clang supports the `-m16` command line4624argument which enables 16-bit code output. This is broadly similar to4625using ``asm(".code16gcc")`` with the GNU toolchain. The generated code4626and the ABI remains 32-bit but the assembler emits instructions4627appropriate for a CPU running in 16-bit mode, with address-size and4628operand-size prefixes to enable 32-bit addressing and operations.4629 4630Several micro-architecture levels as specified by the x86-64 psABI are defined.4631They are cumulative in the sense that features from previous levels are4632implicitly included in later levels.4633 4634- ``-march=x86-64``: CMOV, CMPXCHG8B, FPU, FXSR, MMX, FXSR, SCE, SSE, SSE24635- ``-march=x86-64-v2``: (close to Nehalem) CMPXCHG16B, LAHF-SAHF, POPCNT, SSE3, SSE4.1, SSE4.2, SSSE34636- ``-march=x86-64-v3``: (close to Haswell) AVX, AVX2, BMI1, BMI2, F16C, FMA, LZCNT, MOVBE, XSAVE4637- ``-march=x86-64-v4``: AVX512F, AVX512BW, AVX512CD, AVX512DQ, AVX512VL4638 4639`Intel AVX10 ISA <https://cdrdv2.intel.com/v1/dl/getContent/784343>`_ is4640a major new vector ISA incorporating the modern vectorization aspects of4641Intel AVX-512. This ISA will be supported on all future Intel processors.4642Users are supposed to use the new options ``-mavx10.N`` on these processors4643and should not use traditional AVX512 options anymore. The ``N`` in4644``-mavx10.N`` represents a continuous integer number starting4645from ``1``. Current binaries built with AVX512 features can run on Intel AVX104646capable processors without re-compile.4647 4648ARM4649^^^4650 4651The support for ARM (specifically ARMv6 and ARMv7) is considered stable4652on Darwin (iOS): it has been tested to correctly compile many large C,4653C++, Objective-C, and Objective-C++ codebases. Clang only supports a4654limited number of ARM architectures. It does not yet fully support4655ARMv5, for example.4656 4657PowerPC4658^^^^^^^4659 4660The support for PowerPC (especially PowerPC64) is considered stable4661on Linux and FreeBSD: it has been tested to correctly compile many4662large C and C++ codebases. PowerPC (32bit) is still missing certain4663features (e.g. PIC code on ELF platforms).4664 4665Other platforms4666^^^^^^^^^^^^^^^4667 4668clang currently contains some support for other architectures (e.g. Sparc);4669however, significant pieces of code generation are still missing, and they4670haven't undergone significant testing.4671 4672clang contains limited support for the MSP430 embedded processor, but4673both the clang support and the LLVM backend support are highly4674experimental.4675 4676Other platforms are completely unsupported at the moment. Adding the4677minimal support needed for parsing and semantic analysis on a new4678platform is quite easy; see ``lib/Basic/Targets.cpp`` in the clang source4679tree. This level of support is also sufficient for conversion to LLVM IR4680for simple programs. Proper support for conversion to LLVM IR requires4681adding code to ``lib/CodeGen/CGCall.cpp`` at the moment; this is likely to4682change soon, though. Generating assembly requires a suitable LLVM4683backend.4684 4685Operating System Features and Limitations4686-----------------------------------------4687 4688Windows4689^^^^^^^4690 4691Clang has experimental support for targeting "Cygming" (Cygwin / MinGW)4692platforms.4693 4694See also :ref:`Microsoft Extensions <c_ms>`.4695 4696Cygwin4697""""""4698 4699Clang works on Cygwin-1.7.4700 4701MinGW324702"""""""4703 4704Clang works on some mingw32 distributions. Clang assumes directories as4705below;4706 4707- ``C:/mingw/include``4708- ``C:/mingw/lib``4709- ``C:/mingw/lib/gcc/mingw32/4.[3-5].0/include/c++``4710 4711On MSYS, a few tests might fail.4712 4713MinGW-w644714"""""""""4715 4716For 32-bit (i686-w64-mingw32), and 64-bit (x86\_64-w64-mingw32), Clang4717assumes as below;4718 4719- ``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)``4720- ``some_directory/bin/gcc.exe``4721- ``some_directory/bin/clang.exe``4722- ``some_directory/bin/clang++.exe``4723- ``some_directory/bin/../include/c++/GCC_version``4724- ``some_directory/bin/../include/c++/GCC_version/x86_64-w64-mingw32``4725- ``some_directory/bin/../include/c++/GCC_version/i686-w64-mingw32``4726- ``some_directory/bin/../include/c++/GCC_version/backward``4727- ``some_directory/bin/../x86_64-w64-mingw32/include``4728- ``some_directory/bin/../i686-w64-mingw32/include``4729- ``some_directory/bin/../include``4730 4731This directory layout is standard for any toolchain you will find on the4732official `MinGW-w64 website <http://mingw-w64.sourceforge.net>`_.4733 4734Clang expects the GCC executable "gcc.exe" compiled for4735``i686-w64-mingw32`` (or ``x86_64-w64-mingw32``) to be present on PATH.4736 4737`Some tests might fail <https://bugs.llvm.org/show_bug.cgi?id=9072>`_ on4738``x86_64-w64-mingw32``.4739 4740AIX4741^^^4742TOC Data Transformation4743"""""""""""""""""""""""4744TOC data transformation is off by default (``-mno-tocdata``).4745When ``-mtocdata`` is specified, the TOC data transformation will be applied to4746all suitable variables with static storage duration, including static data4747members of classes and block-scope static variables (if not marked as exceptions,4748see further below).4749 4750Suitable variables must:4751 4752- have complete types4753- be independently generated (i.e., not placed in a pool)4754- be at most as large as a pointer4755- not be aligned more strictly than a pointer4756- not be structs containing flexible array members4757- not have internal linkage4758- not have aliases4759- not have section attributes4760- not be thread local storage4761 4762The TOC data transformation results in the variable, not its address,4763being placed in the TOC. This eliminates the need to load the address of the4764variable from the TOC.4765 4766Note:4767If the TOC data transformation is applied to a variable whose definition4768is imported, the linker will generate fixup code for reading or writing to the4769variable.4770 4771When multiple toc-data options are used, the last option used has the affect.4772For example: ``-mno-tocdata=g5,g1 -mtocdata=g1,g2 -mno-tocdata=g2 -mtocdata=g3,g4``4773results in ``-mtocdata=g1,g3,g4``4774 4775Names of variables not having external linkage will be ignored.4776 4777**Options:**4778 4779.. option:: -mno-tocdata4780 4781 This is the default behaviour. Only variables explicitly specified with4782 ``-mtocdata=`` will have the TOC data transformation applied.4783 4784.. option:: -mtocdata4785 4786 Apply the TOC data transformation to all suitable variables with static4787 storage duration (including static data members of classes and block-scope4788 static variables) that are not explicitly specified with ``-mno-tocdata=``.4789 4790.. option:: -mno-tocdata=4791 4792 Can be used in conjunction with ``-mtocdata`` to mark the comma-separated4793 list of external linkage variables, specified using their mangled names, as4794 exceptions to ``-mtocdata``.4795 4796.. option:: -mtocdata=4797 4798 Apply the TOC data transformation to the comma-separated list of external4799 linkage variables, specified using their mangled names, if they are suitable.4800 Emit diagnostics for all unsuitable variables specified.4801 4802Default Visibility Export Mapping4803"""""""""""""""""""""""""""""""""4804The ``-mdefault-visibility-export-mapping=`` option can be used to control4805mapping of default visibility to an explicit shared object export4806(i.e. XCOFF exported visibility). Three values are provided for the option:4807 4808* ``-mdefault-visibility-export-mapping=none``: no additional export4809 information is created for entities with default visibility.4810* ``-mdefault-visibility-export-mapping=explicit``: mark entities for export4811 if they have explicit (e.g. via an attribute) default visibility from the4812 source, including RTTI.4813* ``-mdefault-visibility-export-mapping=all``: set XCOFF exported visibility4814 for all entities with default visibility from any source. This gives a4815 export behavior similar to ELF platforms where all entities with default4816 visibility are exported.4817 4818.. _spir-v:4819 4820SPIR-V support4821--------------4822 4823Clang supports generation of SPIR-V conformant to `the OpenCL Environment4824Specification4825<https://www.khronos.org/registry/OpenCL/specs/3.0-unified/html/OpenCL_Env.html>`_.4826 4827To generate SPIR-V binaries, Clang uses the in-tree LLVM SPIR-V backend.4828 4829Example usage for OpenCL kernel compilation:4830 4831 .. code-block:: console4832 4833 $ clang --target=spirv32 -c test.cl4834 $ clang --target=spirv64 -c test.cl4835 4836Both invocations of Clang will result in the generation of a SPIR-V binary file4837`test.o` for 32 bit and 64 bit respectively. This file can be imported4838by an OpenCL driver that support SPIR-V consumption or it can be compiled4839further by offline SPIR-V consumer tools.4840 4841Converting to SPIR-V produced with the optimization levels other than `-O0` is4842currently available as an experimental feature and it is not guaranteed to work4843in all cases.4844 4845Linking is done using ``spirv-link`` from `the SPIRV-Tools project4846<https://github.com/KhronosGroup/SPIRV-Tools#linker>`_. Similar to other external4847linkers, Clang will expect ``spirv-link`` to be installed separately and to be4848present in the ``PATH`` environment variable. Please refer to `the build and4849installation instructions4850<https://github.com/KhronosGroup/SPIRV-Tools#build>`_.4851 4852 .. code-block:: console4853 4854 $ clang --target=spirv64 test1.cl test2.cl4855 4856More information about the SPIR-V target settings and supported versions of SPIR-V4857format can be found in `the SPIR-V target guide4858<https://llvm.org/docs/SPIRVUsage.html>`__.4859 4860.. _clang-cl:4861 4862clang-cl4863========4864 4865clang-cl is an alternative command-line interface to Clang, designed for4866compatibility with the Visual C++ compiler, cl.exe.4867 4868To enable clang-cl to find system headers, libraries, and the linker when run4869from the command-line, it should be executed inside a Visual Studio Native Tools4870Command Prompt or a regular Command Prompt where the environment has been set4871up using e.g. `vcvarsall.bat <https://msdn.microsoft.com/en-us/library/f2ccy3wt.aspx>`_.4872 4873clang-cl can also be used from inside Visual Studio by selecting the LLVM4874Platform Toolset. The toolset is not part of the installer, but may be installed4875separately from the4876`Visual Studio Marketplace <https://marketplace.visualstudio.com/items?itemName=LLVMExtensions.llvm-toolchain>`_.4877To use the toolset, select a project in Solution Explorer, open its Property4878Page (Alt+F7), and in the "General" section of "Configuration Properties"4879change "Platform Toolset" to LLVM. Doing so enables an additional Property4880Page for selecting the clang-cl executable to use for builds.4881 4882To use the toolset with MSBuild directly, invoke it with e.g.4883``/p:PlatformToolset=LLVM``. This allows trying out the clang-cl toolchain4884without modifying your project files.4885 4886It's also possible to point MSBuild at clang-cl without changing toolset by4887passing ``/p:CLToolPath=c:\llvm\bin /p:CLToolExe=clang-cl.exe``.4888 4889When using CMake and the Visual Studio generators, the toolset can be set with the ``-T`` flag:4890 4891 ::4892 4893 cmake -G"Visual Studio 16 2019" -T LLVM ..4894 4895When using CMake with the Ninja generator, set the ``CMAKE_C_COMPILER`` and4896``CMAKE_CXX_COMPILER`` variables to clang-cl:4897 4898 ::4899 4900 cmake -GNinja -DCMAKE_C_COMPILER="c:/Program Files (x86)/LLVM/bin/clang-cl.exe"4901 -DCMAKE_CXX_COMPILER="c:/Program Files (x86)/LLVM/bin/clang-cl.exe" ..4902 4903 4904Command-Line Options4905--------------------4906 4907To be compatible with cl.exe, clang-cl supports most of the same command-line4908options. Those options can start with either ``/`` or ``-``. It also supports4909some of Clang's core options, such as the ``-W`` options.4910 4911Options that are known to clang-cl, but not currently supported, are ignored4912with a warning. For example:4913 4914 ::4915 4916 clang-cl.exe: warning: argument unused during compilation: '/AI'4917 4918To suppress warnings about unused arguments, use the ``-Qunused-arguments`` option.4919 4920Options that are not known to clang-cl will be ignored by default. Use the4921``-Werror=unknown-argument`` option in order to treat them as errors. If these4922options are spelled with a leading ``/``, they will be mistaken for a filename:4923 4924 ::4925 4926 clang-cl.exe: error: no such file or directory: '/foobar'4927 4928Please `file a bug <https://github.com/llvm/llvm-project/issues/new?labels=clang-cl>`_4929for any valid cl.exe flags that clang-cl does not understand.4930 4931Execute ``clang-cl /?`` to see a list of supported options:4932 4933 ::4934 4935 CL.EXE COMPATIBILITY OPTIONS:4936 /? Display available options4937 /arch:<value> Set architecture for code generation4938 /Brepro- Emit an object file which cannot be reproduced over time4939 /Brepro Emit an object file which can be reproduced over time4940 /clang:<arg> Pass <arg> to the clang driver4941 /C Don't discard comments when preprocessing4942 /c Compile only4943 /d1PP Retain macro definitions in /E mode4944 /d1reportAllClassLayout Dump record layout information4945 /diagnostics:caret Enable caret and column diagnostics (on by default)4946 /diagnostics:classic Disable column and caret diagnostics4947 /diagnostics:column Disable caret diagnostics but keep column info4948 /D <macro[=value]> Define macro4949 /EH<value> Exception handling model4950 /EP Disable linemarker output and preprocess to stdout4951 /execution-charset:<value>4952 Runtime encoding, supports only UTF-84953 /E Preprocess to stdout4954 /FA Output assembly code file during compilation4955 /Fa<file or directory> Output assembly code to this file during compilation (with /FA)4956 /Fe<file or directory> Set output executable file or directory (ends in / or \)4957 /FI <value> Include file before parsing4958 /Fi<file> Set preprocess output file name (with /P)4959 /Fo<file or directory> Set output object file, or directory (ends in / or \) (with /c)4960 /fp:except-4961 /fp:except4962 /fp:fast4963 /fp:precise4964 /fp:strict4965 /Fp<filename> Set pch filename (with /Yc and /Yu)4966 /GA Assume thread-local variables are defined in the executable4967 /Gd Set __cdecl as a default calling convention4968 /GF- Disable string pooling4969 /GF Enable string pooling (default)4970 /GR- Disable emission of RTTI data4971 /Gregcall Set __regcall as a default calling convention4972 /GR Enable emission of RTTI data4973 /Gr Set __fastcall as a default calling convention4974 /GS- Disable buffer security check4975 /GS Enable buffer security check (default)4976 /Gs Use stack probes (default)4977 /Gs<value> Set stack probe size (default 4096)4978 /guard:<value> Enable Control Flow Guard with /guard:cf,4979 or only the table with /guard:cf,nochecks.4980 Enable EH Continuation Guard with /guard:ehcont4981 /Gv Set __vectorcall as a default calling convention4982 /Gw- Don't put each data item in its own section4983 /Gw Put each data item in its own section4984 /GX- Disable exception handling4985 /GX Enable exception handling4986 /Gy- Don't put each function in its own section (default)4987 /Gy Put each function in its own section4988 /Gz Set __stdcall as a default calling convention4989 /help Display available options4990 /imsvc <dir> Add directory to system include search path, as if part of %INCLUDE%4991 /I <dir> Add directory to include search path4992 /J Make char type unsigned4993 /LDd Create debug DLL4994 /LD Create DLL4995 /link <options> Forward options to the linker4996 /MDd Use DLL debug run-time4997 /MD Use DLL run-time4998 /MTd Use static debug run-time4999 /MT Use static run-time5000 /O0 Disable optimization5001 /O1 Optimize for size (same as /Og /Os /Oy /Ob2 /GF /Gy)5002 /O2 Optimize for speed (same as /Og /Oi /Ot /Oy /Ob2 /GF /Gy)5003 /Ob0 Disable function inlining5004 /Ob1 Only inline functions which are (explicitly or implicitly) marked inline5005 /Ob2 Inline functions as deemed beneficial by the compiler5006 /Ob3 Same as /Ob25007 /Od Disable optimization5008 /Og No effect5009 /Oi- Disable use of builtin functions5010 /Oi Enable use of builtin functions5011 /Os Optimize for size (like clang -Os)5012 /Ot Optimize for speed (like clang -O3)5013 /Ox Deprecated (same as /Og /Oi /Ot /Oy /Ob2); use /O2 instead5014 /Oy- Disable frame pointer omission (x86 only, default)5015 /Oy Enable frame pointer omission (x86 only)5016 /O<flags> Set multiple /O flags at once; e.g. '/O2y-' for '/O2 /Oy-'5017 /o <file or directory> Set output file or directory (ends in / or \)5018 /P Preprocess to file5019 /Qvec- Disable the loop vectorization passes5020 /Qvec Enable the loop vectorization passes5021 /showFilenames- Don't print the name of each compiled file (default)5022 /showFilenames Print the name of each compiled file5023 /showIncludes Print info about included files to stderr5024 /source-charset:<value> Source encoding, supports only UTF-85025 /std:<value> Language standard to compile for5026 /TC Treat all source files as C5027 /Tc <filename> Specify a C source file5028 /TP Treat all source files as C++5029 /Tp <filename> Specify a C++ source file5030 /utf-8 Set source and runtime encoding to UTF-8 (default)5031 /U <macro> Undefine macro5032 /vd<value> Control vtordisp placement5033 /vmb Use a best-case representation method for member pointers5034 /vmg Use a most-general representation for member pointers5035 /vmm Set the default most-general representation to multiple inheritance5036 /vms Set the default most-general representation to single inheritance5037 /vmv Set the default most-general representation to virtual inheritance5038 /volatile:iso Volatile loads and stores have standard semantics5039 /volatile:ms Volatile loads and stores have acquire and release semantics5040 /W0 Disable all warnings5041 /W1 Enable -Wall5042 /W2 Enable -Wall5043 /W3 Enable -Wall5044 /W4 Enable -Wall and -Wextra5045 /Wall Enable -Weverything5046 /WX- Do not treat warnings as errors5047 /WX Treat warnings as errors5048 /w Disable all warnings5049 /X Don't add %INCLUDE% to the include search path5050 /Y- Disable precompiled headers, overrides /Yc and /Yu5051 /Yc<filename> Generate a pch file for all code up to and including <filename>5052 /Yu<filename> Load a pch file and use it instead of all code up to and including <filename>5053 /Z7 Enable CodeView debug information in object files5054 /Zc:char8_t Enable C++20 char8_t type5055 /Zc:char8_t- Disable C++20 char8_t type5056 /Zc:dllexportInlines- Don't dllexport/dllimport inline member functions of dllexport/import classes5057 /Zc:dllexportInlines dllexport/dllimport inline member functions of dllexport/import classes (default)5058 /Zc:sizedDealloc- Disable C++14 sized global deallocation functions5059 /Zc:sizedDealloc Enable C++14 sized global deallocation functions5060 /Zc:strictStrings Treat string literals as const5061 /Zc:threadSafeInit- Disable thread-safe initialization of static variables5062 /Zc:threadSafeInit Enable thread-safe initialization of static variables5063 /Zc:trigraphs- Disable trigraphs (default)5064 /Zc:trigraphs Enable trigraphs5065 /Zc:twoPhase- Disable two-phase name lookup in templates5066 /Zc:twoPhase Enable two-phase name lookup in templates5067 /Zi Alias for /Z7. Does not produce PDBs.5068 /Zl Don't mention any default libraries in the object file5069 /Zp Set the default maximum struct packing alignment to 15070 /Zp<value> Specify the default maximum struct packing alignment5071 /Zs Run the preprocessor, parser and semantic analysis stages5072 5073 OPTIONS:5074 -### Print (but do not run) the commands to run for this compilation5075 --analyze Run the static analyzer5076 -faddrsig Emit an address-significance table5077 -fansi-escape-codes Use ANSI escape codes for diagnostics5078 -fblocks Enable the 'blocks' language feature5079 -fcf-protection=<value> Instrument control-flow architecture protection. Options: return, branch, full, none.5080 -fcf-protection Enable cf-protection in 'full' mode5081 -fcolor-diagnostics Use colors in diagnostics5082 -fcomplete-member-pointers5083 Require member pointer base types to be complete if they would be significant under the Microsoft ABI5084 -fcoverage-mapping Generate coverage mapping to enable code coverage analysis5085 -fcrash-diagnostics-dir=<dir>5086 Put crash-report files in <dir>5087 -fdebug-macro Emit macro debug information5088 -fdelayed-template-parsing5089 Parse templated function definitions at the end of the translation unit5090 -fdiagnostics-absolute-paths5091 Print absolute paths in diagnostics5092 -fdiagnostics-parseable-fixits5093 Print fix-its in machine parseable form5094 -flto=<value> Set LTO mode to either 'full' or 'thin'5095 -flto Enable LTO in 'full' mode5096 -fmerge-all-constants Allow merging of constants5097 -fmodule-file=<module_name>=<module-file>5098 Use the specified module file that provides the module <module_name>5099 -fmodule-header=<header>5100 Build <header> as a C++20 header unit5101 -fmodule-output=<path>5102 Save intermediate module file results when compiling a standard C++ module unit.5103 -fms-compatibility-version=<value>5104 Dot-separated value representing the Microsoft compiler version5105 number to report in _MSC_VER (0 = don't define it; default is same value as installed cl.exe, or 1933)5106 -fms-compatibility Enable full Microsoft Visual C++ compatibility5107 -fms-extensions Accept some non-standard constructs supported by the Microsoft compiler5108 -fmsc-version=<value> Microsoft compiler version number to report in _MSC_VER5109 (0 = don't define it; default is same value as installed cl.exe, or 1933)5110 -fno-addrsig Don't emit an address-significance table5111 -fno-builtin-<value> Disable implicit builtin knowledge of a specific function5112 -fno-builtin Disable implicit builtin knowledge of functions5113 -fno-complete-member-pointers5114 Do not require member pointer base types to be complete if they would be significant under the Microsoft ABI5115 -fno-coverage-mapping Disable code coverage analysis5116 -fno-crash-diagnostics Disable auto-generation of preprocessed source files and a script for reproduction during a clang crash5117 -fno-debug-macro Do not emit macro debug information5118 -fno-delayed-template-parsing5119 Disable delayed template parsing5120 -fno-sanitize-address-poison-custom-array-cookie5121 Disable poisoning array cookies when using custom operator new[] in AddressSanitizer5122 -fno-sanitize-address-use-after-scope5123 Disable use-after-scope detection in AddressSanitizer5124 -fno-sanitize-address-use-odr-indicator5125 Disable ODR indicator globals5126 -fno-sanitize-ignorelist Don't use ignorelist file for sanitizers5127 -fno-sanitize-cfi-cross-dso5128 Disable control flow integrity (CFI) checks for cross-DSO calls.5129 -fno-sanitize-coverage=<value>5130 Disable specified features of coverage instrumentation for Sanitizers5131 -fno-sanitize-memory-track-origins5132 Disable origins tracking in MemorySanitizer5133 -fno-sanitize-memory-use-after-dtor5134 Disable use-after-destroy detection in MemorySanitizer5135 -fno-sanitize-recover=<value>5136 Disable recovery for specified sanitizers5137 -fno-sanitize-stats Disable sanitizer statistics gathering.5138 -fno-sanitize-thread-atomics5139 Disable atomic operations instrumentation in ThreadSanitizer5140 -fno-sanitize-thread-func-entry-exit5141 Disable function entry/exit instrumentation in ThreadSanitizer5142 -fno-sanitize-thread-memory-access5143 Disable memory access instrumentation in ThreadSanitizer5144 -fno-sanitize-trap=<value>5145 Disable trapping for specified sanitizers5146 -fno-standalone-debug Limit debug information produced to reduce size of debug binary5147 -fno-strict-aliasing Disable optimizations based on strict aliasing rules (default)5148 -fobjc-runtime=<value> Specify the target Objective-C runtime kind and version5149 -fprofile-exclude-files=<value>5150 Instrument only functions from files where names don't match all the regexes separated by a semi-colon5151 -fprofile-filter-files=<value>5152 Instrument only functions from files where names match any regex separated by a semi-colon5153 -fprofile-generate=<dirname>5154 Generate instrumented code to collect execution counts into a raw profile file in the directory specified by the argument. The filename uses default_%m.profraw pattern5155 (overridden by ``LLVM_PROFILE_FILE`` env var)5156 -fprofile-generate5157 Generate instrumented code to collect execution counts into default_%m.profraw file5158 (overridden by '=' form of option or ``LLVM_PROFILE_FILE`` env var)5159 -fprofile-instr-generate=<file_name_pattern>5160 Generate instrumented code to collect execution counts into the file whose name pattern is specified as the argument5161 (overridden by ``LLVM_PROFILE_FILE`` env var)5162 -fprofile-instr-generate5163 Generate instrumented code to collect execution counts into default.profraw file5164 (overridden by '=' form of option or ``LLVM_PROFILE_FILE`` env var)5165 -fprofile-instr-use=<value>5166 Use instrumentation data for coverage testing or profile-guided optimization5167 -fprofile-use=<value>5168 Use instrumentation data for profile-guided optimization5169 -fprofile-remapping-file=<file>5170 Use the remappings described in <file> to match the profile data against names in the program5171 -fprofile-list=<file>5172 Filename defining the list of functions/files to instrument5173 -fsanitize-address-field-padding=<value>5174 Level of field padding for AddressSanitizer5175 -fsanitize-address-globals-dead-stripping5176 Enable linker dead stripping of globals in AddressSanitizer5177 -fsanitize-address-poison-custom-array-cookie5178 Enable poisoning array cookies when using custom operator new[] in AddressSanitizer5179 -fsanitize-address-use-after-return=<mode>5180 Select the mode of detecting stack use-after-return in AddressSanitizer: never | runtime (default) | always5181 -fsanitize-address-use-after-scope5182 Enable use-after-scope detection in AddressSanitizer5183 -fsanitize-address-use-odr-indicator5184 Enable ODR indicator globals to avoid false ODR violation reports in partially sanitized programs at the cost of an increase in binary size5185 -fsanitize-ignorelist=<value>5186 Path to ignorelist file for sanitizers5187 -fsanitize-cfi-cross-dso5188 Enable control flow integrity (CFI) checks for cross-DSO calls.5189 -fsanitize-cfi-icall-generalize-pointers5190 Generalize pointers in CFI indirect call type signature checks5191 -fsanitize-coverage=<value>5192 Specify the type of coverage instrumentation for Sanitizers5193 -fsanitize-hwaddress-abi=<value>5194 Select the HWAddressSanitizer ABI to target (interceptor or platform, default interceptor)5195 -fsanitize-memory-track-origins=<value>5196 Enable origins tracking in MemorySanitizer5197 -fsanitize-memory-track-origins5198 Enable origins tracking in MemorySanitizer5199 -fsanitize-memory-use-after-dtor5200 Enable use-after-destroy detection in MemorySanitizer5201 -fsanitize-recover=<value>5202 Enable recovery for specified sanitizers5203 -fsanitize-stats Enable sanitizer statistics gathering.5204 -fsanitize-thread-atomics5205 Enable atomic operations instrumentation in ThreadSanitizer (default)5206 -fsanitize-thread-func-entry-exit5207 Enable function entry/exit instrumentation in ThreadSanitizer (default)5208 -fsanitize-thread-memory-access5209 Enable memory access instrumentation in ThreadSanitizer (default)5210 -fsanitize-trap=<value> Enable trapping for specified sanitizers5211 -fsanitize-undefined-strip-path-components=<number>5212 Strip (or keep only, if negative) a given number of path components when emitting check metadata.5213 -fsanitize=<check> Turn on runtime checks for various forms of undefined or suspicious5214 behavior. See user manual for available checks5215 -fsplit-lto-unit Enables splitting of the LTO unit.5216 -fstandalone-debug Emit full debug info for all types used by the program5217 -fstrict-aliasing Enable optimizations based on strict aliasing rules5218 -fsyntax-only Run the preprocessor, parser and semantic analysis stages5219 -fwhole-program-vtables Enables whole-program vtable optimization. Requires -flto5220 -gcodeview-ghash Emit type record hashes in a .debug$H section5221 -gcodeview Generate CodeView debug information5222 -gline-directives-only Emit debug line info directives only5223 -gline-tables-only Emit debug line number tables only5224 -miamcu Use Intel MCU ABI5225 -mllvm <value> Additional arguments to forward to LLVM's option processing5226 -nobuiltininc Disable builtin #include directories5227 -Qunused-arguments Don't emit warning for unused driver arguments5228 -R<remark> Enable the specified remark5229 --target=<value> Generate code for the given target5230 --version Print version information5231 -v Show commands to run and use verbose output5232 -W<warning> Enable the specified warning5233 -Xclang <arg> Pass <arg> to the clang compiler5234 -Xclangas <arg> Pass <arg> to the clang assembler5235 5236The /clang: Option5237^^^^^^^^^^^^^^^^^^5238 5239When clang-cl is run with a set of ``/clang:<arg>`` options, it will gather all5240of the ``<arg>`` arguments and process them as if they were passed to the clang5241driver. This mechanism allows you to pass flags that are not exposed in the5242clang-cl options or flags that have a different meaning when passed to the clang5243driver. Regardless of where they appear in the command line, the ``/clang:``5244arguments are treated as if they were passed at the end of the clang-cl command5245line.5246 5247The /Zc:dllexportInlines- Option5248^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^5249 5250This causes the class-level `dllexport` and `dllimport` attributes to not apply5251to inline member functions, as they otherwise would. For example, in the code5252below `S::foo()` would normally be defined and exported by the DLL, but when5253using the ``/Zc:dllexportInlines-`` flag it is not:5254 5255.. code-block:: c5256 5257 struct __declspec(dllexport) S {5258 void foo() {}5259 }5260 5261This has the benefit that the compiler doesn't need to emit a definition of5262`S::foo()` in every translation unit where the declaration is included, as it5263would otherwise do to ensure there's a definition in the DLL even if it's not5264used there. If the declaration occurs in a header file that's widely used, this5265can save significant compilation time and output size. It also reduces the5266number of functions exported by the DLL similarly to what5267``-fvisibility-inlines-hidden`` does for shared objects on ELF and Mach-O.5268Since the function declaration comes with an inline definition, users of the5269library can use that definition directly instead of importing it from the DLL.5270 5271Note that the Microsoft Visual C++ compiler does not support this option, and5272if code in a DLL is compiled with ``/Zc:dllexportInlines-``, the code using the5273DLL must be compiled in the same way so that it doesn't attempt to dllimport5274the inline member functions. The reverse scenario should generally work though:5275a DLL compiled without this flag (such as a system library compiled with Visual5276C++) can be referenced from code compiled using the flag, meaning that the5277referencing code will use the inline definitions instead of importing them from5278the DLL.5279 5280Also note that like when using ``-fvisibility-inlines-hidden``, the address of5281`S::foo()` will be different inside and outside the DLL, breaking the C/C++5282standard requirement that functions have a unique address.5283 5284The flag does not apply to explicit class template instantiation definitions or5285declarations, as those are typically used to explicitly provide a single5286definition in a DLL, (dllexported instantiation definition) or to signal that5287the definition is available elsewhere (dllimport instantiation declaration). It5288also doesn't apply to inline members with static local variables, to ensure5289that the same instance of the variable is used inside and outside the DLL.5290 5291Using this flag can cause problems when inline functions that would otherwise5292be dllexported refer to internal symbols of a DLL. For example:5293 5294.. code-block:: c5295 5296 void internal();5297 5298 struct __declspec(dllimport) S {5299 void foo() { internal(); }5300 }5301 5302Normally, references to `S::foo()` would use the definition in the DLL from5303which it was exported, and which presumably also has the definition of5304`internal()`. However, when using ``/Zc:dllexportInlines-``, the inline5305definition of `S::foo()` is used directly, resulting in a link error since5306`internal()` is not available. Even worse, if there is an inline definition of5307`internal()` containing a static local variable, we will now refer to a5308different instance of that variable than in the DLL:5309 5310.. code-block:: c5311 5312 inline int internal() { static int x; return x++; }5313 5314 struct __declspec(dllimport) S {5315 int foo() { return internal(); }5316 }5317 5318This could lead to very subtle bugs. Using ``-fvisibility-inlines-hidden`` can5319lead to the same issue. To avoid it in this case, make `S::foo()` or5320`internal()` non-inline, or mark them `dllimport/dllexport` explicitly.5321 5322Finding Clang runtime libraries5323^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^5324 5325clang-cl supports several features that require runtime library support:5326 5327- Address Sanitizer (ASan): ``-fsanitize=address``5328- Undefined Behavior Sanitizer (UBSan): ``-fsanitize=undefined``5329- Code coverage: ``-fprofile-instr-generate -fcoverage-mapping``5330- Profile Guided Optimization (PGO): ``-fprofile-generate``5331- Certain math operations (int128 division) require the builtins library5332 5333In order to use these features, the user must link the right runtime libraries5334into their program. These libraries are distributed alongside Clang in the5335library resource directory. Clang searches for the resource directory by5336searching relative to the Clang executable. For example, if LLVM is installed5337in ``C:\Program Files\LLVM``, then the profile runtime library will be located5338at the path5339``C:\Program Files\LLVM\lib\clang\11.0.0\lib\windows\clang_rt.profile-x86_64.lib``.5340 5341For UBSan, PGO, and coverage, Clang will emit object files that auto-link the5342appropriate runtime library, but the user generally needs to help the linker5343(whether it is ``lld-link.exe`` or MSVC ``link.exe``) find the library resource5344directory. Using the example installation above, this would mean passing5345``/LIBPATH:C:\Program Files\LLVM\lib\clang\11.0.0\lib\windows`` to the linker.5346If the user links the program with the ``clang`` or ``clang-cl`` drivers, the5347driver will pass this flag for them.5348 5349The auto-linking can be disabled with -fno-rtlib-defaultlib. If that flag is5350used, pass the complete flag to required libraries as described for ASan below.5351 5352If the linker cannot find the appropriate library, it will emit an error like5353this::5354 5355 $ clang-cl -c -fsanitize=undefined t.cpp5356 5357 $ lld-link t.obj -dll5358 lld-link: error: could not open 'clang_rt.ubsan_standalone-x86_64.lib': no such file or directory5359 lld-link: error: could not open 'clang_rt.ubsan_standalone_cxx-x86_64.lib': no such file or directory5360 5361 $ link t.obj -dll -nologo5362 LINK : fatal error LNK1104: cannot open file 'clang_rt.ubsan_standalone-x86_64.lib'5363 5364To fix the error, add the appropriate ``/libpath:`` flag to the link line.5365 5366For ASan, as of this writing, the user is also responsible for linking against5367the correct ASan libraries.5368 5369If the user is using the dynamic CRT (``/MD``), then they should add5370``clang_rt.asan_dynamic-x86_64.lib`` to the link line as a regular input. For5371other architectures, replace x86_64 with the appropriate name here and below.5372 5373If the user is using the static CRT (``/MT``), then different runtimes are used5374to produce DLLs and EXEs. To link a DLL, pass5375``clang_rt.asan_dll_thunk-x86_64.lib``. To link an EXE, pass5376``-wholearchive:clang_rt.asan-x86_64.lib``.5377 5378Windows System Headers and Library Lookup5379^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^5380 5381clang-cl uses a set of different approaches to locate the right system libraries5382to link against when building code. The Windows environment uses libraries from5383three distinct sources:5384 53851. Windows SDK53862. UCRT (Universal C Runtime)53873. Visual C++ Tools (VCRuntime)5388 5389The Windows SDK provides the import libraries and headers required to build5390programs against the Windows system packages. Underlying the Windows SDK is the5391UCRT, the universal C runtime.5392 5393This difference is best illustrated by the various headers that one would find5394in the different categories. The WinSDK would contain headers such as5395`WinSock2.h` which is part of the Windows API surface, providing the Windows5396socketing interfaces for networking. UCRT provides the C library headers,5397including e.g. `stdio.h`. Finally, the Visual C++ tools provides the underlying5398Visual C++ Runtime headers such as `stdint.h` or `crtdefs.h`.5399 5400There are various controls that allow the user control over where clang-cl will5401locate these headers. The default behaviour for the Windows SDK and UCRT is as5402follows:5403 54041. Consult the command line.5405 5406 Anything the user specifies is always given precedence. The following5407 extensions are part of the clang-cl toolset:5408 5409 - `/winsysroot:`5410 5411 The `/winsysroot:` is used as an equivalent to `-sysroot` on Unix5412 environments. It allows the control of an alternate location to be treated5413 as a system root. When specified, it will be used as the root where the5414 `Windows Kits` is located.5415 5416 - `/winsdkversion:`5417 - `/winsdkdir:`5418 5419 If `/winsysroot:` is not specified, the `/winsdkdir:` argument is consulted5420 as a location to identify where the Windows SDK is located. Contrary to5421 `/winsysroot:`, `/winsdkdir:` is expected to be the complete path rather5422 than a root to locate `Windows Kits`.5423 5424 The `/winsdkversion:` flag allows the user to specify a version identifier5425 for the SDK to prefer. When this is specified, no additional validation is5426 performed and this version is preferred. If the version is not specified,5427 the highest detected version number will be used.5428 54292. Consult the environment.5430 5431 TODO: This is not yet implemented.5432 5433 This will consult the environment variables:5434 5435 - `WindowsSdkDir`5436 - `UCRTVersion`5437 54383. Fallback to the registry.5439 5440 If no arguments are used to indicate where the SDK is present, and the5441 compiler is running on Windows, the registry is consulted to locate the5442 installation.5443 5444The Visual C++ Toolset has a slightly more elaborate mechanism for detection.5445 54461. Consult the command line.5447 5448 - `/winsysroot:`5449 5450 The `/winsysroot:` is used as an equivalent to `-sysroot` on Unix5451 environments. It allows the control of an alternate location to be treated5452 as a system root. When specified, it will be used as the root where the5453 `VC` directory is located.5454 5455 - `/vctoolsdir:`5456 - `/vctoolsversion:`5457 5458 If `/winsysroot:` is not specified, the `/vctoolsdir:` argument is consulted5459 as a location to identify where the Visual C++ Tools are located. If5460 `/vctoolsversion:` is specified, that version is preferred, otherwise, the5461 highest version detected is used.5462 54632. Consult the environment.5464 5465 - `/external:[VARIABLE]`5466 5467 This specifies a user identified environment variable which is treated as5468 a path delimiter (`;`) separated list of paths to map into `-imsvc`5469 arguments which are treated as `-isystem`.5470 5471 - `INCLUDE` and `EXTERNAL_INCLUDE`5472 5473 The path delimiter (`;`) separated list of paths will be mapped to5474 `-imsvc` arguments which are treated as `-isystem`.5475 5476 - `LIB` (indirectly)5477 5478 The linker `link.exe` or `lld-link.exe` will honour the environment5479 variable `LIB` which is a path delimiter (`;`) set of paths to consult for5480 the import libraries to use when linking the final target.5481 5482 The following environment variables will be consulted and used to form paths5483 to validate and load content from as appropriate:5484 5485 - `VCToolsInstallDir`5486 - `VCINSTALLDIR`5487 - `Path`5488 54893. Consult `ISetupConfiguration` [Windows Only]5490 5491 Assuming that the toolchain is built with `USE_MSVC_SETUP_API` defined and5492 is running on Windows, the Visual Studio COM interface `ISetupConfiguration`5493 will be used to locate the installation of the MSVC toolset.5494 54954. Fallback to the registry [DEPRECATED]5496 5497 The registry information is used to help locate the installation as a final5498 fallback. This is only possible for pre-VS2017 installations and is5499 considered deprecated.5500 5501Restrictions and Limitations compared to Clang5502----------------------------------------------5503 5504Strict aliasing (TBAA) is always off by default in clang-cl whereas in clang,5505strict aliasing is turned on by default for all optimization levels. For more5506details, see :ref:`Strict aliasing <strict_aliasing>`.5507