1============================ 2Clang Compiler User's Manual 3============================ 4 5.. include:: <isonum.txt> 6 7.. contents:: 8 :local: 9 10Introduction 11============ 12 13The Clang Compiler is an open-source compiler for the C family of 14programming languages, aiming to be the best in class implementation of 15these languages. Clang builds on the LLVM optimizer and code generator, 16allowing it to provide high-quality optimization and code generation 17support for many targets. For more general information, please see the 18`Clang Web Site <https://clang.llvm.org>`_ or the `LLVM Web 19Site <https://llvm.org>`_. 20 21This document describes important notes about using Clang as a compiler 22for an end-user, documenting the supported features, command line 23options, etc. If you are interested in using Clang to build a tool that 24processes code, please see :doc:`InternalsManual`. If you are interested in the 25`Clang Static Analyzer <https://clang-analyzer.llvm.org>`_, please see its web 26page. 27 28Clang is one component in a complete toolchain for C family languages. 29A separate document describes the other pieces necessary to 30:doc:`assemble a complete toolchain <Toolchain>`. 31 32Clang is designed to support the C family of programming languages, 33which includes :ref:`C <c>`, :ref:`Objective-C <objc>`, :ref:`C++ <cxx>`, and 34:ref:`Objective-C++ <objcxx>` as well as many dialects of those. For 35language-specific information, please see the corresponding language 36specific section: 37 38- :ref:`C Language <c>`: K&R C, ANSI C89, ISO C90, ISO C94 (C89+AMD1), ISO 39 C99 (+TC1, TC2, TC3). 40- :ref:`Objective-C Language <objc>`: ObjC 1, ObjC 2, ObjC 2.1, plus 41 variants depending on base language. 42- :ref:`C++ Language <cxx>` 43- :ref:`Objective C++ Language <objcxx>` 44- :ref:`OpenCL C Language <opencl>`: v1.0, v1.1, v1.2, v2.0. 45 46In addition to these base languages and their dialects, Clang supports a 47broad variety of language extensions, which are documented in the 48corresponding language section. These extensions are provided to be 49compatible with the GCC, Microsoft, and other popular compilers as well 50as to improve functionality through Clang-specific features. The Clang 51driver and language features are intentionally designed to be as 52compatible with the GNU GCC compiler as reasonably possible, easing 53migration from GCC to Clang. In most cases, code "just works". 54Clang also provides an alternative driver, :ref:`clang-cl`, that is designed 55to be compatible with the Visual C++ compiler, cl.exe. 56 57In addition to language specific features, Clang has a variety of 58features that depend on what CPU architecture or operating system is 59being compiled for. Please see the :ref:`Target-Specific Features and 60Limitations <target_features>` section for more details. 61 62The rest of the introduction introduces some basic :ref:`compiler 63terminology <terminology>` that is used throughout this manual and 64contains a basic :ref:`introduction to using Clang <basicusage>` as a 65command line compiler. 66 67.. _terminology: 68 69Terminology 70----------- 71 72Front end, parser, backend, preprocessor, undefined behavior, 73diagnostic, optimizer 74 75.. _basicusage: 76 77Basic Usage 78----------- 79 80Intro to how to use a C compiler for newbies. 81 82compile + link compile then link debug info enabling optimizations 83picking a language to use, defaults to C11 by default. Autosenses based 84on extension. using a makefile 85 86Command Line Options 87==================== 88 89This section is generally an index into other sections. It does not go 90into depth on the ones that are covered by other sections. However, the 91first part introduces the language selection and other high level 92options like :option:`-c`, :option:`-g`, etc. 93 94Options to Control Error and Warning Messages 95--------------------------------------------- 96 97.. option:: -Werror 98 99 Turn warnings into errors. 100 101.. This is in plain monospaced font because it generates the same label as 102.. -Werror, and Sphinx complains. 103 104``-Werror=foo`` 105 106 Turn warning "foo" into an error. 107 108.. option:: -Wno-error=foo 109 110 Turn warning "foo" into a warning even if :option:`-Werror` is specified. 111 112.. option:: -Wfoo 113 114 Enable warning "foo". 115 See the :doc:`diagnostics reference <DiagnosticsReference>` for a complete 116 list of the warning flags that can be specified in this way. 117 118.. option:: -Wno-foo 119 120 Disable warning "foo". 121 122.. option:: -w 123 124 Disable all diagnostics. 125 126.. option:: -Weverything 127 128 :ref:`Enable all diagnostics. <diagnostics_enable_everything>` 129 130.. option:: -pedantic 131 132 Warn on language extensions. 133 134.. option:: -pedantic-errors 135 136 Error on language extensions. 137 138.. option:: -Wsystem-headers 139 140 Enable warnings from system headers. 141 142.. option:: -ferror-limit=123 143 144 Stop emitting diagnostics after 123 errors have been produced. The default is 145 20, and the error limit can be disabled with `-ferror-limit=0`. 146 147.. option:: -ftemplate-backtrace-limit=123 148 149 Only emit up to 123 template instantiation notes within the template 150 instantiation backtrace for a single warning or error. The default is 10, and 151 the limit can be disabled with `-ftemplate-backtrace-limit=0`. 152 153.. _cl_diag_formatting: 154 155Formatting of Diagnostics 156^^^^^^^^^^^^^^^^^^^^^^^^^ 157 158Clang aims to produce beautiful diagnostics by default, particularly for 159new users that first come to Clang. However, different people have 160different preferences, and sometimes Clang is driven not by a human, 161but by a program that wants consistent and easily parsable output. For 162these cases, Clang provides a wide range of options to control the exact 163output format of the diagnostics that it generates. 164 165.. _opt_fshow-column: 166 167**-f[no-]show-column** 168 Print column number in diagnostic. 169 170 This option, which defaults to on, controls whether or not Clang 171 prints the column number of a diagnostic. For example, when this is 172 enabled, Clang will print something like: 173 174 :: 175 176 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens] 177 #endif bad 178 ^ 179 // 180 181 When this is disabled, Clang will print "test.c:28: warning..." with 182 no column number. 183 184 The printed column numbers count bytes from the beginning of the 185 line; take care if your source contains multibyte characters. 186 187.. _opt_fshow-source-location: 188 189**-f[no-]show-source-location** 190 Print source file/line/column information in diagnostic. 191 192 This option, which defaults to on, controls whether or not Clang 193 prints the filename, line number and column number of a diagnostic. 194 For example, when this is enabled, Clang will print something like: 195 196 :: 197 198 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens] 199 #endif bad 200 ^ 201 // 202 203 When this is disabled, Clang will not print the "test.c:28:8: " 204 part. 205 206.. _opt_fcaret-diagnostics: 207 208**-f[no-]caret-diagnostics** 209 Print source line and ranges from source code in diagnostic. 210 This option, which defaults to on, controls whether or not Clang 211 prints the source line, source ranges, and caret when emitting a 212 diagnostic. For example, when this is enabled, Clang will print 213 something like: 214 215 :: 216 217 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens] 218 #endif bad 219 ^ 220 // 221 222**-f[no-]color-diagnostics** 223 This option, which defaults to on when a color-capable terminal is 224 detected, controls whether or not Clang prints diagnostics in color. 225 226 When this option is enabled, Clang will use colors to highlight 227 specific parts of the diagnostic, e.g., 228 229 .. nasty hack to not lose our dignity 230 231 .. raw:: html 232 233 <pre> 234 <b><span style="color:black">test.c:28:8: <span style="color:magenta">warning</span>: extra tokens at end of #endif directive [-Wextra-tokens]</span></b> 235 #endif bad 236 <span style="color:green">^</span> 237 <span style="color:green">//</span> 238 </pre> 239 240 When this is disabled, Clang will just print: 241 242 :: 243 244 test.c:2:8: warning: extra tokens at end of #endif directive [-Wextra-tokens] 245 #endif bad 246 ^ 247 // 248 249**-fansi-escape-codes** 250 Controls whether ANSI escape codes are used instead of the Windows Console 251 API to output colored diagnostics. This option is only used on Windows and 252 defaults to off. 253 254.. option:: -fdiagnostics-format=clang/msvc/vi 255 256 Changes diagnostic output format to better match IDEs and command line tools. 257 258 This option controls the output format of the filename, line number, 259 and column printed in diagnostic messages. The options, and their 260 affect on formatting a simple conversion diagnostic, follow: 261 262 **clang** (default) 263 :: 264 265 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' 266 267 **msvc** 268 :: 269 270 t.c(3,11) : warning: conversion specifies type 'char *' but the argument has type 'int' 271 272 **vi** 273 :: 274 275 t.c +3:11: warning: conversion specifies type 'char *' but the argument has type 'int' 276 277.. _opt_fdiagnostics-show-option: 278 279**-f[no-]diagnostics-show-option** 280 Enable ``[-Woption]`` information in diagnostic line. 281 282 This option, which defaults to on, controls whether or not Clang 283 prints the associated :ref:`warning group <cl_diag_warning_groups>` 284 option name when outputting a warning diagnostic. For example, in 285 this output: 286 287 :: 288 289 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens] 290 #endif bad 291 ^ 292 // 293 294 Passing **-fno-diagnostics-show-option** will prevent Clang from 295 printing the [:ref:`-Wextra-tokens <opt_Wextra-tokens>`] information in 296 the diagnostic. This information tells you the flag needed to enable 297 or disable the diagnostic, either from the command line or through 298 :ref:`#pragma GCC diagnostic <pragma_GCC_diagnostic>`. 299 300.. _opt_fdiagnostics-show-category: 301 302.. option:: -fdiagnostics-show-category=none/id/name 303 304 Enable printing category information in diagnostic line. 305 306 This option, which defaults to "none", controls whether or not Clang 307 prints the category associated with a diagnostic when emitting it. 308 Each diagnostic may or many not have an associated category, if it 309 has one, it is listed in the diagnostic categorization field of the 310 diagnostic line (in the []'s). 311 312 For example, a format string warning will produce these three 313 renditions based on the setting of this option: 314 315 :: 316 317 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat] 318 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat,1] 319 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat,Format String] 320 321 This category can be used by clients that want to group diagnostics 322 by category, so it should be a high level category. We want dozens 323 of these, not hundreds or thousands of them. 324 325.. _opt_fsave-optimization-record: 326 327.. option:: -fsave-optimization-record[=<format>] 328 329 Write optimization remarks to a separate file. 330 331 This option, which defaults to off, controls whether Clang writes 332 optimization reports to a separate file. By recording diagnostics in a file, 333 users can parse or sort the remarks in a convenient way. 334 335 By default, the serialization format is YAML. 336 337 The supported serialization formats are: 338 339 - .. _opt_fsave_optimization_record_yaml: 340 341 ``-fsave-optimization-record=yaml``: A structured YAML format. 342 343 - .. _opt_fsave_optimization_record_bitstream: 344 345 ``-fsave-optimization-record=bitstream``: A binary format based on LLVM 346 Bitstream. 347 348.. _opt_foptimization-record-file: 349 350**-foptimization-record-file** 351 Control the file to which optimization reports are written. 352 353 When optimization reports are being output (see 354 :ref:`-fsave-optimization-record <opt_fsave-optimization-record>`), this 355 option controls the file to which those reports are written. 356 357 If this option is not used, optimization records are output to a file named 358 after the primary file being compiled. If that's "foo.c", for example, 359 optimization records are output to "foo.opt.yaml". If a specific 360 serialization format is specified, the file will be named 361 "foo.opt.<format>". 362 363.. _opt_foptimization-record-passes: 364 365**-foptimization-record-passes** 366 Only include passes which match a specified regular expression. 367 368 When optimization reports are being output (see 369 :ref:`-fsave-optimization-record <opt_fsave-optimization-record>`), this 370 option controls the passes that will be included in the final report. 371 372 If this option is not used, all the passes are included in the optimization 373 record. 374 375.. _opt_fdiagnostics-show-hotness: 376 377**-f[no-]diagnostics-show-hotness** 378 Enable profile hotness information in diagnostic line. 379 380 This option controls whether Clang prints the profile hotness associated 381 with diagnostics in the presence of profile-guided optimization information. 382 This is currently supported with optimization remarks (see 383 :ref:`Options to Emit Optimization Reports <rpass>`). The hotness information 384 allows users to focus on the hot optimization remarks that are likely to be 385 more relevant for run-time performance. 386 387 For example, in this output, the block containing the callsite of `foo` was 388 executed 3000 times according to the profile data: 389 390 :: 391 392 s.c:7:10: remark: foo inlined into bar (hotness: 3000) [-Rpass-analysis=inline] 393 sum += foo(x, x - 2); 394 ^ 395 396 This option is implied when 397 :ref:`-fsave-optimization-record <opt_fsave-optimization-record>` is used. 398 Otherwise, it defaults to off. 399 400.. _opt_fdiagnostics-hotness-threshold: 401 402**-fdiagnostics-hotness-threshold** 403 Prevent optimization remarks from being output if they do not have at least 404 this hotness value. 405 406 This option, which defaults to zero, controls the minimum hotness an 407 optimization remark would need in order to be output by Clang. This is 408 currently supported with optimization remarks (see :ref:`Options to Emit 409 Optimization Reports <rpass>`) when profile hotness information in 410 diagnostics is enabled (see 411 :ref:`-fdiagnostics-show-hotness <opt_fdiagnostics-show-hotness>`). 412 413.. _opt_fdiagnostics-fixit-info: 414 415**-f[no-]diagnostics-fixit-info** 416 Enable "FixIt" information in the diagnostics output. 417 418 This option, which defaults to on, controls whether or not Clang 419 prints the information on how to fix a specific diagnostic 420 underneath it when it knows. For example, in this output: 421 422 :: 423 424 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens] 425 #endif bad 426 ^ 427 // 428 429 Passing **-fno-diagnostics-fixit-info** will prevent Clang from 430 printing the "//" line at the end of the message. This information 431 is useful for users who may not understand what is wrong, but can be 432 confusing for machine parsing. 433 434.. _opt_fdiagnostics-print-source-range-info: 435 436**-fdiagnostics-print-source-range-info** 437 Print machine parsable information about source ranges. 438 This option makes Clang print information about source ranges in a machine 439 parsable format after the file/line/column number information. The 440 information is a simple sequence of brace enclosed ranges, where each range 441 lists the start and end line/column locations. For example, in this output: 442 443 :: 444 445 exprs.c:47:15:{47:8-47:14}{47:17-47:24}: error: invalid operands to binary expression ('int *' and '_Complex float') 446 P = (P-42) + Gamma*4; 447 ~~~~~~ ^ ~~~~~~~ 448 449 The {}'s are generated by -fdiagnostics-print-source-range-info. 450 451 The printed column numbers count bytes from the beginning of the 452 line; take care if your source contains multibyte characters. 453 454.. option:: -fdiagnostics-parseable-fixits 455 456 Print Fix-Its in a machine parseable form. 457 458 This option makes Clang print available Fix-Its in a machine 459 parseable format at the end of diagnostics. The following example 460 illustrates the format: 461 462 :: 463 464 fix-it:"t.cpp":{7:25-7:29}:"Gamma" 465 466 The range printed is a half-open range, so in this example the 467 characters at column 25 up to but not including column 29 on line 7 468 in t.cpp should be replaced with the string "Gamma". Either the 469 range or the replacement string may be empty (representing strict 470 insertions and strict erasures, respectively). Both the file name 471 and the insertion string escape backslash (as "\\\\"), tabs (as 472 "\\t"), newlines (as "\\n"), double quotes(as "\\"") and 473 non-printable characters (as octal "\\xxx"). 474 475 The printed column numbers count bytes from the beginning of the 476 line; take care if your source contains multibyte characters. 477 478.. option:: -fno-elide-type 479 480 Turns off elision in template type printing. 481 482 The default for template type printing is to elide as many template 483 arguments as possible, removing those which are the same in both 484 template types, leaving only the differences. Adding this flag will 485 print all the template arguments. If supported by the terminal, 486 highlighting will still appear on differing arguments. 487 488 Default: 489 490 :: 491 492 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; 493 494 -fno-elide-type: 495 496 :: 497 498 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; 499 500.. option:: -fdiagnostics-show-template-tree 501 502 Template type diffing prints a text tree. 503 504 For diffing large templated types, this option will cause Clang to 505 display the templates as an indented text tree, one argument per 506 line, with differences marked inline. This is compatible with 507 -fno-elide-type. 508 509 Default: 510 511 :: 512 513 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; 514 515 With :option:`-fdiagnostics-show-template-tree`: 516 517 :: 518 519 t.cc:4:5: note: candidate function not viable: no known conversion for 1st argument; 520 vector< 521 map< 522 [...], 523 map< 524 [float != double], 525 [...]>>> 526 527.. _cl_diag_warning_groups: 528 529Individual Warning Groups 530^^^^^^^^^^^^^^^^^^^^^^^^^ 531 532TODO: Generate this from tblgen. Define one anchor per warning group. 533 534.. _opt_wextra-tokens: 535 536.. option:: -Wextra-tokens 537 538 Warn about excess tokens at the end of a preprocessor directive. 539 540 This option, which defaults to on, enables warnings about extra 541 tokens at the end of preprocessor directives. For example: 542 543 :: 544 545 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens] 546 #endif bad 547 ^ 548 549 These extra tokens are not strictly conforming, and are usually best 550 handled by commenting them out. 551 552.. option:: -Wambiguous-member-template 553 554 Warn about unqualified uses of a member template whose name resolves to 555 another template at the location of the use. 556 557 This option, which defaults to on, enables a warning in the 558 following code: 559 560 :: 561 562 template<typename T> struct set{}; 563 template<typename T> struct trait { typedef const T& type; }; 564 struct Value { 565 template<typename T> void set(typename trait<T>::type value) {} 566 }; 567 void foo() { 568 Value v; 569 v.set<double>(3.2); 570 } 571 572 C++ [basic.lookup.classref] requires this to be an error, but, 573 because it's hard to work around, Clang downgrades it to a warning 574 as an extension. 575 576.. option:: -Wbind-to-temporary-copy 577 578 Warn about an unusable copy constructor when binding a reference to a 579 temporary. 580 581 This option enables warnings about binding a 582 reference to a temporary when the temporary doesn't have a usable 583 copy constructor. For example: 584 585 :: 586 587 struct NonCopyable { 588 NonCopyable(); 589 private: 590 NonCopyable(const NonCopyable&); 591 }; 592 void foo(const NonCopyable&); 593 void bar() { 594 foo(NonCopyable()); // Disallowed in C++98; allowed in C++11. 595 } 596 597 :: 598 599 struct NonCopyable2 { 600 NonCopyable2(); 601 NonCopyable2(NonCopyable2&); 602 }; 603 void foo(const NonCopyable2&); 604 void bar() { 605 foo(NonCopyable2()); // Disallowed in C++98; allowed in C++11. 606 } 607 608 Note that if ``NonCopyable2::NonCopyable2()`` has a default argument 609 whose instantiation produces a compile error, that error will still 610 be a hard error in C++98 mode even if this warning is turned off. 611 612Options to Control Clang Crash Diagnostics 613------------------------------------------ 614 615As unbelievable as it may sound, Clang does crash from time to time. 616Generally, this only occurs to those living on the `bleeding 617edge <https://llvm.org/releases/download.html#svn>`_. Clang goes to great 618lengths to assist you in filing a bug report. Specifically, Clang 619generates preprocessed source file(s) and associated run script(s) upon 620a crash. These files should be attached to a bug report to ease 621reproducibility of the failure. Below are the command line options to 622control the crash diagnostics. 623 624.. option:: -fno-crash-diagnostics 625 626 Disable auto-generation of preprocessed source files during a clang crash. 627 628The -fno-crash-diagnostics flag can be helpful for speeding the process 629of generating a delta reduced test case. 630 631Clang is also capable of generating preprocessed source file(s) and associated 632run script(s) even without a crash. This is specially useful when trying to 633generate a reproducer for warnings or errors while using modules. 634 635.. option:: -gen-reproducer 636 637 Generates preprocessed source files, a reproducer script and if relevant, a 638 cache containing: built module pcm's and all headers needed to rebuilt the 639 same modules. 640 641.. _rpass: 642 643Options to Emit Optimization Reports 644------------------------------------ 645 646Optimization reports trace, at a high-level, all the major decisions 647done by compiler transformations. For instance, when the inliner 648decides to inline function ``foo()`` into ``bar()``, or the loop unroller 649decides to unroll a loop N times, or the vectorizer decides to 650vectorize a loop body. 651 652Clang offers a family of flags which the optimizers can use to emit 653a diagnostic in three cases: 654 6551. When the pass makes a transformation (`-Rpass`). 656 6572. When the pass fails to make a transformation (`-Rpass-missed`). 658 6593. When the pass determines whether or not to make a transformation 660 (`-Rpass-analysis`). 661 662NOTE: Although the discussion below focuses on `-Rpass`, the exact 663same options apply to `-Rpass-missed` and `-Rpass-analysis`. 664 665Since there are dozens of passes inside the compiler, each of these flags 666take a regular expression that identifies the name of the pass which should 667emit the associated diagnostic. For example, to get a report from the inliner, 668compile the code with: 669 670.. code-block:: console 671 672 $ clang -O2 -Rpass=inline code.cc -o code 673 code.cc:4:25: remark: foo inlined into bar [-Rpass=inline] 674 int bar(int j) { return foo(j, j - 2); } 675 ^ 676 677Note that remarks from the inliner are identified with `[-Rpass=inline]`. 678To request a report from every optimization pass, you should use 679`-Rpass=.*` (in fact, you can use any valid POSIX regular 680expression). However, do not expect a report from every transformation 681made by the compiler. Optimization remarks do not really make sense 682outside of the major transformations (e.g., inlining, vectorization, 683loop optimizations) and not every optimization pass supports this 684feature. 685 686Note that when using profile-guided optimization information, profile hotness 687information can be included in the remarks (see 688:ref:`-fdiagnostics-show-hotness <opt_fdiagnostics-show-hotness>`). 689 690Current limitations 691^^^^^^^^^^^^^^^^^^^ 692 6931. Optimization remarks that refer to function names will display the 694 mangled name of the function. Since these remarks are emitted by the 695 back end of the compiler, it does not know anything about the input 696 language, nor its mangling rules. 697 6982. Some source locations are not displayed correctly. The front end has 699 a more detailed source location tracking than the locations included 700 in the debug info (e.g., the front end can locate code inside macro 701 expansions). However, the locations used by `-Rpass` are 702 translated from debug annotations. That translation can be lossy, 703 which results in some remarks having no location information. 704 705Other Options 706------------- 707Clang options that don't fit neatly into other categories. 708 709.. option:: -fgnuc-version= 710 711 This flag controls the value of ``__GNUC__`` and related macros. This flag 712 does not enable or disable any GCC extensions implemented in Clang. Setting 713 the version to zero causes Clang to leave ``__GNUC__`` and other 714 GNU-namespaced macros, such as ``__GXX_WEAK__``, undefined. 715 716.. option:: -MV 717 718 When emitting a dependency file, use formatting conventions appropriate 719 for NMake or Jom. Ignored unless another option causes Clang to emit a 720 dependency file. 721 722When Clang emits a dependency file (e.g., you supplied the -M option) 723most filenames can be written to the file without any special formatting. 724Different Make tools will treat different sets of characters as "special" 725and use different conventions for telling the Make tool that the character 726is actually part of the filename. Normally Clang uses backslash to "escape" 727a special character, which is the convention used by GNU Make. The -MV 728option tells Clang to put double-quotes around the entire filename, which 729is the convention used by NMake and Jom. 730 731Configuration files 732------------------- 733 734Configuration files group command-line options and allow all of them to be 735specified just by referencing the configuration file. They may be used, for 736example, to collect options required to tune compilation for particular 737target, such as -L, -I, -l, --sysroot, codegen options, etc. 738 739The command line option `--config` can be used to specify configuration 740file in a Clang invocation. For example: 741 742:: 743 744 clang --config /home/user/cfgs/testing.txt 745 clang --config debug.cfg 746 747If the provided argument contains a directory separator, it is considered as 748a file path, and options are read from that file. Otherwise the argument is 749treated as a file name and is searched for sequentially in the directories: 750 751 - user directory, 752 - system directory, 753 - the directory where Clang executable resides. 754 755Both user and system directories for configuration files are specified during 756clang build using CMake parameters, CLANG_CONFIG_FILE_USER_DIR and 757CLANG_CONFIG_FILE_SYSTEM_DIR respectively. The first file found is used. It is 758an error if the required file cannot be found. 759 760Another way to specify a configuration file is to encode it in executable name. 761For example, if the Clang executable is named `armv7l-clang` (it may be a 762symbolic link to `clang`), then Clang will search for file `armv7l.cfg` in the 763directory where Clang resides. 764 765If a driver mode is specified in invocation, Clang tries to find a file specific 766for the specified mode. For example, if the executable file is named 767`x86_64-clang-cl`, Clang first looks for `x86_64-cl.cfg` and if it is not found, 768looks for `x86_64.cfg`. 769 770If the command line contains options that effectively change target architecture 771(these are -m32, -EL, and some others) and the configuration file starts with an 772architecture name, Clang tries to load the configuration file for the effective 773architecture. For example, invocation: 774 775:: 776 777 x86_64-clang -m32 abc.c 778 779causes Clang search for a file `i368.cfg` first, and if no such file is found, 780Clang looks for the file `x86_64.cfg`. 781 782The configuration file consists of command-line options specified on one or 783more lines. Lines composed of whitespace characters only are ignored as well as 784lines in which the first non-blank character is `#`. Long options may be split 785between several lines by a trailing backslash. Here is example of a 786configuration file: 787 788:: 789 790 # Several options on line 791 -c --target=x86_64-unknown-linux-gnu 792 793 # Long option split between lines 794 -I/usr/lib/gcc/x86_64-linux-gnu/5.4.0/../../../../\ 795 include/c++/5.4.0 796 797 # other config files may be included 798 @linux.options 799 800Files included by `@file` directives in configuration files are resolved 801relative to the including file. For example, if a configuration file 802`~/.llvm/target.cfg` contains the directive `@os/linux.opts`, the file 803`linux.opts` is searched for in the directory `~/.llvm/os`. 804 805Language and Target-Independent Features 806======================================== 807 808Controlling Errors and Warnings 809------------------------------- 810 811Clang provides a number of ways to control which code constructs cause 812it to emit errors and warning messages, and how they are displayed to 813the console. 814 815Controlling How Clang Displays Diagnostics 816^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 817 818When Clang emits a diagnostic, it includes rich information in the 819output, and gives you fine-grain control over which information is 820printed. Clang has the ability to print this information, and these are 821the options that control it: 822 823#. A file/line/column indicator that shows exactly where the diagnostic 824 occurs in your code [:ref:`-fshow-column <opt_fshow-column>`, 825 :ref:`-fshow-source-location <opt_fshow-source-location>`]. 826#. A categorization of the diagnostic as a note, warning, error, or 827 fatal error. 828#. A text string that describes what the problem is. 829#. An option that indicates how to control the diagnostic (for 830 diagnostics that support it) 831 [:ref:`-fdiagnostics-show-option <opt_fdiagnostics-show-option>`]. 832#. A :ref:`high-level category <diagnostics_categories>` for the diagnostic 833 for clients that want to group diagnostics by class (for diagnostics 834 that support it) 835 [:ref:`-fdiagnostics-show-category <opt_fdiagnostics-show-category>`]. 836#. The line of source code that the issue occurs on, along with a caret 837 and ranges that indicate the important locations 838 [:ref:`-fcaret-diagnostics <opt_fcaret-diagnostics>`]. 839#. "FixIt" information, which is a concise explanation of how to fix the 840 problem (when Clang is certain it knows) 841 [:ref:`-fdiagnostics-fixit-info <opt_fdiagnostics-fixit-info>`]. 842#. A machine-parsable representation of the ranges involved (off by 843 default) 844 [:ref:`-fdiagnostics-print-source-range-info <opt_fdiagnostics-print-source-range-info>`]. 845 846For more information please see :ref:`Formatting of 847Diagnostics <cl_diag_formatting>`. 848 849Diagnostic Mappings 850^^^^^^^^^^^^^^^^^^^ 851 852All diagnostics are mapped into one of these 6 classes: 853 854- Ignored 855- Note 856- Remark 857- Warning 858- Error 859- Fatal 860 861.. _diagnostics_categories: 862 863Diagnostic Categories 864^^^^^^^^^^^^^^^^^^^^^ 865 866Though not shown by default, diagnostics may each be associated with a 867high-level category. This category is intended to make it possible to 868triage builds that produce a large number of errors or warnings in a 869grouped way. 870 871Categories are not shown by default, but they can be turned on with the 872:ref:`-fdiagnostics-show-category <opt_fdiagnostics-show-category>` option. 873When set to "``name``", the category is printed textually in the 874diagnostic output. When it is set to "``id``", a category number is 875printed. The mapping of category names to category id's can be obtained 876by running '``clang --print-diagnostic-categories``'. 877 878Controlling Diagnostics via Command Line Flags 879^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 880 881TODO: -W flags, -pedantic, etc 882 883.. _pragma_gcc_diagnostic: 884 885Controlling Diagnostics via Pragmas 886^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 887 888Clang can also control what diagnostics are enabled through the use of 889pragmas in the source code. This is useful for turning off specific 890warnings in a section of source code. Clang supports GCC's pragma for 891compatibility with existing source code, as well as several extensions. 892 893The pragma may control any warning that can be used from the command 894line. Warnings may be set to ignored, warning, error, or fatal. The 895following example code will tell Clang or GCC to ignore the -Wall 896warnings: 897 898.. code-block:: c 899 900 #pragma GCC diagnostic ignored "-Wall" 901 902In addition to all of the functionality provided by GCC's pragma, Clang 903also allows you to push and pop the current warning state. This is 904particularly useful when writing a header file that will be compiled by 905other people, because you don't know what warning flags they build with. 906 907In the below example :option:`-Wextra-tokens` is ignored for only a single line 908of code, after which the diagnostics return to whatever state had previously 909existed. 910 911.. code-block:: c 912 913 #if foo 914 #endif foo // warning: extra tokens at end of #endif directive 915 916 #pragma clang diagnostic push 917 #pragma clang diagnostic ignored "-Wextra-tokens" 918 919 #if foo 920 #endif foo // no warning 921 922 #pragma clang diagnostic pop 923 924The push and pop pragmas will save and restore the full diagnostic state 925of the compiler, regardless of how it was set. That means that it is 926possible to use push and pop around GCC compatible diagnostics and Clang 927will push and pop them appropriately, while GCC will ignore the pushes 928and pops as unknown pragmas. It should be noted that while Clang 929supports the GCC pragma, Clang and GCC do not support the exact same set 930of warnings, so even when using GCC compatible #pragmas there is no 931guarantee that they will have identical behaviour on both compilers. 932 933In addition to controlling warnings and errors generated by the compiler, it is 934possible to generate custom warning and error messages through the following 935pragmas: 936 937.. code-block:: c 938 939 // The following will produce warning messages 940 #pragma message "some diagnostic message" 941 #pragma GCC warning "TODO: replace deprecated feature" 942 943 // The following will produce an error message 944 #pragma GCC error "Not supported" 945 946These pragmas operate similarly to the ``#warning`` and ``#error`` preprocessor 947directives, except that they may also be embedded into preprocessor macros via 948the C99 ``_Pragma`` operator, for example: 949 950.. code-block:: c 951 952 #define STR(X) #X 953 #define DEFER(M,...) M(__VA_ARGS__) 954 #define CUSTOM_ERROR(X) _Pragma(STR(GCC error(X " at line " DEFER(STR,__LINE__)))) 955 956 CUSTOM_ERROR("Feature not available"); 957 958Controlling Diagnostics in System Headers 959^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 960 961Warnings are suppressed when they occur in system headers. By default, 962an included file is treated as a system header if it is found in an 963include path specified by ``-isystem``, but this can be overridden in 964several ways. 965 966The ``system_header`` pragma can be used to mark the current file as 967being a system header. No warnings will be produced from the location of 968the pragma onwards within the same file. 969 970.. code-block:: c 971 972 #if foo 973 #endif foo // warning: extra tokens at end of #endif directive 974 975 #pragma clang system_header 976 977 #if foo 978 #endif foo // no warning 979 980The `--system-header-prefix=` and `--no-system-header-prefix=` 981command-line arguments can be used to override whether subsets of an include 982path are treated as system headers. When the name in a ``#include`` directive 983is found within a header search path and starts with a system prefix, the 984header is treated as a system header. The last prefix on the 985command-line which matches the specified header name takes precedence. 986For instance: 987 988.. code-block:: console 989 990 $ clang -Ifoo -isystem bar --system-header-prefix=x/ \ 991 --no-system-header-prefix=x/y/ 992 993Here, ``#include "x/a.h"`` is treated as including a system header, even 994if the header is found in ``foo``, and ``#include "x/y/b.h"`` is treated 995as not including a system header, even if the header is found in 996``bar``. 997 998A ``#include`` directive which finds a file relative to the current 999directory is treated as including a system header if the including file 1000is treated as a system header. 1001 1002.. _diagnostics_enable_everything: 1003 1004Enabling All Diagnostics 1005^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1006 1007In addition to the traditional ``-W`` flags, one can enable **all** diagnostics 1008by passing :option:`-Weverything`. This works as expected with 1009:option:`-Werror`, and also includes the warnings from :option:`-pedantic`. Some 1010diagnostics contradict each other, therefore, users of :option:`-Weverything` 1011often disable many diagnostics such as `-Wno-c++98-compat` and `-Wno-c++-compat` 1012because they contradict recent C++ standards. 1013 1014Since :option:`-Weverything` enables every diagnostic, we generally don't 1015recommend using it. `-Wall` `-Wextra` are a better choice for most projects. 1016Using :option:`-Weverything` means that updating your compiler is more difficult 1017because you're exposed to experimental diagnostics which might be of lower 1018quality than the default ones. If you do use :option:`-Weverything` then we 1019advise that you address all new compiler diagnostics as they get added to Clang, 1020either by fixing everything they find or explicitly disabling that diagnostic 1021with its corresponding `Wno-` option. 1022 1023Note that when combined with :option:`-w` (which disables all warnings), 1024disabling all warnings wins. 1025 1026Controlling Static Analyzer Diagnostics 1027^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1028 1029While not strictly part of the compiler, the diagnostics from Clang's 1030`static analyzer <https://clang-analyzer.llvm.org>`_ can also be 1031influenced by the user via changes to the source code. See the available 1032`annotations <https://clang-analyzer.llvm.org/annotations.html>`_ and the 1033analyzer's `FAQ 1034page <https://clang-analyzer.llvm.org/faq.html#exclude_code>`_ for more 1035information. 1036 1037.. _usersmanual-precompiled-headers: 1038 1039Precompiled Headers 1040------------------- 1041 1042`Precompiled headers <https://en.wikipedia.org/wiki/Precompiled_header>`_ 1043are a general approach employed by many compilers to reduce compilation 1044time. The underlying motivation of the approach is that it is common for 1045the same (and often large) header files to be included by multiple 1046source files. Consequently, compile times can often be greatly improved 1047by caching some of the (redundant) work done by a compiler to process 1048headers. Precompiled header files, which represent one of many ways to 1049implement this optimization, are literally files that represent an 1050on-disk cache that contains the vital information necessary to reduce 1051some of the work needed to process a corresponding header file. While 1052details of precompiled headers vary between compilers, precompiled 1053headers have been shown to be highly effective at speeding up program 1054compilation on systems with very large system headers (e.g., macOS). 1055 1056Generating a PCH File 1057^^^^^^^^^^^^^^^^^^^^^ 1058 1059To generate a PCH file using Clang, one invokes Clang with the 1060`-x <language>-header` option. This mirrors the interface in GCC 1061for generating PCH files: 1062 1063.. code-block:: console 1064 1065 $ gcc -x c-header test.h -o test.h.gch 1066 $ clang -x c-header test.h -o test.h.pch 1067 1068Using a PCH File 1069^^^^^^^^^^^^^^^^ 1070 1071A PCH file can then be used as a prefix header when a :option:`-include` 1072option is passed to ``clang``: 1073 1074.. code-block:: console 1075 1076 $ clang -include test.h test.c -o test 1077 1078The ``clang`` driver will first check if a PCH file for ``test.h`` is 1079available; if so, the contents of ``test.h`` (and the files it includes) 1080will be processed from the PCH file. Otherwise, Clang falls back to 1081directly processing the content of ``test.h``. This mirrors the behavior 1082of GCC. 1083 1084.. note:: 1085 1086 Clang does *not* automatically use PCH files for headers that are directly 1087 included within a source file. For example: 1088 1089 .. code-block:: console 1090 1091 $ clang -x c-header test.h -o test.h.pch 1092 $ cat test.c 1093 #include "test.h" 1094 $ clang test.c -o test 1095 1096 In this example, ``clang`` will not automatically use the PCH file for 1097 ``test.h`` since ``test.h`` was included directly in the source file and not 1098 specified on the command line using :option:`-include`. 1099 1100Relocatable PCH Files 1101^^^^^^^^^^^^^^^^^^^^^ 1102 1103It is sometimes necessary to build a precompiled header from headers 1104that are not yet in their final, installed locations. For example, one 1105might build a precompiled header within the build tree that is then 1106meant to be installed alongside the headers. Clang permits the creation 1107of "relocatable" precompiled headers, which are built with a given path 1108(into the build directory) and can later be used from an installed 1109location. 1110 1111To build a relocatable precompiled header, place your headers into a 1112subdirectory whose structure mimics the installed location. For example, 1113if you want to build a precompiled header for the header ``mylib.h`` 1114that will be installed into ``/usr/include``, create a subdirectory 1115``build/usr/include`` and place the header ``mylib.h`` into that 1116subdirectory. If ``mylib.h`` depends on other headers, then they can be 1117stored within ``build/usr/include`` in a way that mimics the installed 1118location. 1119 1120Building a relocatable precompiled header requires two additional 1121arguments. First, pass the ``--relocatable-pch`` flag to indicate that 1122the resulting PCH file should be relocatable. Second, pass 1123``-isysroot /path/to/build``, which makes all includes for your library 1124relative to the build directory. For example: 1125 1126.. code-block:: console 1127 1128 # clang -x c-header --relocatable-pch -isysroot /path/to/build /path/to/build/mylib.h mylib.h.pch 1129 1130When loading the relocatable PCH file, the various headers used in the 1131PCH file are found from the system header root. For example, ``mylib.h`` 1132can be found in ``/usr/include/mylib.h``. If the headers are installed 1133in some other system root, the ``-isysroot`` option can be used provide 1134a different system root from which the headers will be based. For 1135example, ``-isysroot /Developer/SDKs/MacOSX10.4u.sdk`` will look for 1136``mylib.h`` in ``/Developer/SDKs/MacOSX10.4u.sdk/usr/include/mylib.h``. 1137 1138Relocatable precompiled headers are intended to be used in a limited 1139number of cases where the compilation environment is tightly controlled 1140and the precompiled header cannot be generated after headers have been 1141installed. 1142 1143.. _controlling-fp-behavior: 1144 1145Controlling Floating Point Behavior 1146----------------------------------- 1147 1148Clang provides a number of ways to control floating point behavior. The options 1149are listed below. 1150 1151.. option:: -ffast-math 1152 1153 Enable fast-math mode. This option lets the 1154 compiler make aggressive, potentially-lossy assumptions about 1155 floating-point math. These include: 1156 1157 * Floating-point math obeys regular algebraic rules for real numbers (e.g. 1158 ``+`` and ``*`` are associative, ``x/y == x * (1/y)``, and 1159 ``(a + b) * c == a * c + b * c``), 1160 * Operands to floating-point operations are not equal to ``NaN`` and 1161 ``Inf``, and 1162 * ``+0`` and ``-0`` are interchangeable. 1163 1164 ``-ffast-math`` also defines the ``__FAST_MATH__`` preprocessor 1165 macro. Some math libraries recognize this macro and change their behavior. 1166 With the exception of ``-ffp-contract=fast``, using any of the options 1167 below to disable any of the individual optimizations in ``-ffast-math`` 1168 will cause ``__FAST_MATH__`` to no longer be set. 1169 1170 This option implies: 1171 1172 * ``-fno-honor-infinities`` 1173 1174 * ``-fno-honor-nans`` 1175 1176 * ``-fno-math-errno`` 1177 1178 * ``-ffinite-math`` 1179 1180 * ``-fassociative-math`` 1181 1182 * ``-freciprocal-math`` 1183 1184 * ``-fno-signed-zeros`` 1185 1186 * ``-fno-trapping-math`` 1187 1188 * ``-ffp-contract=fast`` 1189 1190.. option:: -fdenormal-fp-math=<value> 1191 1192 Select which denormal numbers the code is permitted to require. 1193 1194 Valid values are: 1195 1196 * ``ieee`` - IEEE 754 denormal numbers 1197 * ``preserve-sign`` - the sign of a flushed-to-zero number is preserved in the sign of 0 1198 * ``positive-zero`` - denormals are flushed to positive zero 1199 1200 Defaults to ``ieee``. 1201 1202.. _opt_fstrict-float-cast-overflow: 1203 1204**-f[no-]strict-float-cast-overflow** 1205 1206 When a floating-point value is not representable in a destination integer 1207 type, the code has undefined behavior according to the language standard. 1208 By default, Clang will not guarantee any particular result in that case. 1209 With the 'no-strict' option, Clang attempts to match the overflowing behavior 1210 of the target's native float-to-int conversion instructions. 1211 1212.. _opt_fmath-errno: 1213 1214**-f[no-]math-errno** 1215 1216 Require math functions to indicate errors by setting errno. 1217 The default varies by ToolChain. ``-fno-math-errno`` allows optimizations 1218 that might cause standard C math functions to not set ``errno``. 1219 For example, on some systems, the math function ``sqrt`` is specified 1220 as setting ``errno`` to ``EDOM`` when the input is negative. On these 1221 systems, the compiler cannot normally optimize a call to ``sqrt`` to use 1222 inline code (e.g. the x86 ``sqrtsd`` instruction) without additional 1223 checking to ensure that ``errno`` is set appropriately. 1224 ``-fno-math-errno`` permits these transformations. 1225 1226 On some targets, math library functions never set ``errno``, and so 1227 ``-fno-math-errno`` is the default. This includes most BSD-derived 1228 systems, including Darwin. 1229 1230.. _opt_ftrapping-math: 1231 1232**-f[no-]trapping-math** 1233 1234 ``-fno-trapping-math`` allows optimizations that assume that 1235 floating point operations cannot generate traps such as divide-by-zero, 1236 overflow and underflow. Defaults to ``-ftrapping-math``. 1237 Currently this option has no effect. 1238 1239.. option:: -ffp-contract=<value> 1240 1241 Specify when the compiler is permitted to form fused floating-point 1242 operations, such as fused multiply-add (FMA). Fused operations are 1243 permitted to produce more precise results than performing the same 1244 operations separately. 1245 1246 The C standard permits intermediate floating-point results within an 1247 expression to be computed with more precision than their type would 1248 normally allow. This permits operation fusing, and Clang takes advantage 1249 of this by default. This behavior can be controlled with the 1250 ``FP_CONTRACT`` pragma. Please refer to the pragma documentation for a 1251 description of how the pragma interacts with this option. 1252 1253 Valid values are: 1254 1255 * ``fast`` (everywhere) 1256 * ``on`` (according to FP_CONTRACT pragma, default) 1257 * ``off`` (never fuse) 1258 1259.. _opt_fhonor-infinities: 1260 1261**-f[no-]honor-infinities** 1262 1263 If both ``-fno-honor-infinities`` and ``-fno-honor-nans`` are used, 1264 has the same effect as specifying ``-ffinite-math``. 1265 1266.. _opt_fhonor-nans: 1267 1268**-f[no-]honor-nans** 1269 1270 If both ``-fno-honor-infinities`` and ``-fno-honor-nans`` are used, 1271 has the same effect as specifying ``-ffinite-math``. 1272 1273.. _opt_fsigned-zeros: 1274 1275**-f[no-]signed-zeros** 1276 1277 Allow optimizations that ignore the sign of floating point zeros. 1278 Defaults to ``-fno-signed-zeros``. 1279 1280.. _opt_fassociative-math: 1281 1282**-f[no-]associative-math** 1283 1284 Allow floating point operations to be reassociated. 1285 Defaults to ``-fno-associative-math``. 1286 1287.. _opt_freciprocal-math: 1288 1289**-f[no-]reciprocal-math** 1290 1291 Allow division operations to be transformed into multiplication by a 1292 reciprocal. This can be significantly faster than an ordinary division 1293 but can also have significantly less precision. Defaults to 1294 ``-fno-reciprocal-math``. 1295 1296.. _opt_funsafe-math-optimizations: 1297 1298**-f[no-]unsafe-math-optimizations** 1299 1300 Allow unsafe floating-point optimizations. Also implies: 1301 1302 * ``-fassociative-math`` 1303 * ``-freciprocal-math`` 1304 * ``-fno-signed-zeroes`` 1305 * ``-fno-trapping-math``. 1306 1307 Defaults to ``-fno-unsafe-math-optimizations``. 1308 1309.. _opt_ffinite-math: 1310 1311**-f[no-]finite-math** 1312 1313 Allow floating-point optimizations that assume arguments and results are 1314 not NaNs or +-Inf. This defines the ``__FINITE_MATH_ONLY__`` preprocessor macro. 1315 Also implies: 1316 1317 * ``-fno-honor-infinities`` 1318 * ``-fno-honor-nans`` 1319 1320 Defaults to ``-fno-finite-math``. 1321 1322.. _controlling-code-generation: 1323 1324Controlling Code Generation 1325--------------------------- 1326 1327Clang provides a number of ways to control code generation. The options 1328are listed below. 1329 1330**-f[no-]sanitize=check1,check2,...** 1331 Turn on runtime checks for various forms of undefined or suspicious 1332 behavior. 1333 1334 This option controls whether Clang adds runtime checks for various 1335 forms of undefined or suspicious behavior, and is disabled by 1336 default. If a check fails, a diagnostic message is produced at 1337 runtime explaining the problem. The main checks are: 1338 1339 - .. _opt_fsanitize_address: 1340 1341 ``-fsanitize=address``: 1342 :doc:`AddressSanitizer`, a memory error 1343 detector. 1344 - .. _opt_fsanitize_thread: 1345 1346 ``-fsanitize=thread``: :doc:`ThreadSanitizer`, a data race detector. 1347 - .. _opt_fsanitize_memory: 1348 1349 ``-fsanitize=memory``: :doc:`MemorySanitizer`, 1350 a detector of uninitialized reads. Requires instrumentation of all 1351 program code. 1352 - .. _opt_fsanitize_undefined: 1353 1354 ``-fsanitize=undefined``: :doc:`UndefinedBehaviorSanitizer`, 1355 a fast and compatible undefined behavior checker. 1356 1357 - ``-fsanitize=dataflow``: :doc:`DataFlowSanitizer`, a general data 1358 flow analysis. 1359 - ``-fsanitize=cfi``: :doc:`control flow integrity <ControlFlowIntegrity>` 1360 checks. Requires ``-flto``. 1361 - ``-fsanitize=safe-stack``: :doc:`safe stack <SafeStack>` 1362 protection against stack-based memory corruption errors. 1363 1364 There are more fine-grained checks available: see 1365 the :ref:`list <ubsan-checks>` of specific kinds of 1366 undefined behavior that can be detected and the :ref:`list <cfi-schemes>` 1367 of control flow integrity schemes. 1368 1369 The ``-fsanitize=`` argument must also be provided when linking, in 1370 order to link to the appropriate runtime library. 1371 1372 It is not possible to combine more than one of the ``-fsanitize=address``, 1373 ``-fsanitize=thread``, and ``-fsanitize=memory`` checkers in the same 1374 program. 1375 1376**-f[no-]sanitize-recover=check1,check2,...** 1377 1378**-f[no-]sanitize-recover=all** 1379 1380 Controls which checks enabled by ``-fsanitize=`` flag are non-fatal. 1381 If the check is fatal, program will halt after the first error 1382 of this kind is detected and error report is printed. 1383 1384 By default, non-fatal checks are those enabled by 1385 :doc:`UndefinedBehaviorSanitizer`, 1386 except for ``-fsanitize=return`` and ``-fsanitize=unreachable``. Some 1387 sanitizers may not support recovery (or not support it by default 1388 e.g. :doc:`AddressSanitizer`), and always crash the program after the issue 1389 is detected. 1390 1391 Note that the ``-fsanitize-trap`` flag has precedence over this flag. 1392 This means that if a check has been configured to trap elsewhere on the 1393 command line, or if the check traps by default, this flag will not have 1394 any effect unless that sanitizer's trapping behavior is disabled with 1395 ``-fno-sanitize-trap``. 1396 1397 For example, if a command line contains the flags ``-fsanitize=undefined 1398 -fsanitize-trap=undefined``, the flag ``-fsanitize-recover=alignment`` 1399 will have no effect on its own; it will need to be accompanied by 1400 ``-fno-sanitize-trap=alignment``. 1401 1402**-f[no-]sanitize-trap=check1,check2,...** 1403 1404 Controls which checks enabled by the ``-fsanitize=`` flag trap. This 1405 option is intended for use in cases where the sanitizer runtime cannot 1406 be used (for instance, when building libc or a kernel module), or where 1407 the binary size increase caused by the sanitizer runtime is a concern. 1408 1409 This flag is only compatible with :doc:`control flow integrity 1410 <ControlFlowIntegrity>` schemes and :doc:`UndefinedBehaviorSanitizer` 1411 checks other than ``vptr``. If this flag 1412 is supplied together with ``-fsanitize=undefined``, the ``vptr`` sanitizer 1413 will be implicitly disabled. 1414 1415 This flag is enabled by default for sanitizers in the ``cfi`` group. 1416 1417.. option:: -fsanitize-blacklist=/path/to/blacklist/file 1418 1419 Disable or modify sanitizer checks for objects (source files, functions, 1420 variables, types) listed in the file. See 1421 :doc:`SanitizerSpecialCaseList` for file format description. 1422 1423.. option:: -fno-sanitize-blacklist 1424 1425 Don't use blacklist file, if it was specified earlier in the command line. 1426 1427**-f[no-]sanitize-coverage=[type,features,...]** 1428 1429 Enable simple code coverage in addition to certain sanitizers. 1430 See :doc:`SanitizerCoverage` for more details. 1431 1432**-f[no-]sanitize-stats** 1433 1434 Enable simple statistics gathering for the enabled sanitizers. 1435 See :doc:`SanitizerStats` for more details. 1436 1437.. option:: -fsanitize-undefined-trap-on-error 1438 1439 Deprecated alias for ``-fsanitize-trap=undefined``. 1440 1441.. option:: -fsanitize-cfi-cross-dso 1442 1443 Enable cross-DSO control flow integrity checks. This flag modifies 1444 the behavior of sanitizers in the ``cfi`` group to allow checking 1445 of cross-DSO virtual and indirect calls. 1446 1447.. option:: -fsanitize-cfi-icall-generalize-pointers 1448 1449 Generalize pointers in return and argument types in function type signatures 1450 checked by Control Flow Integrity indirect call checking. See 1451 :doc:`ControlFlowIntegrity` for more details. 1452 1453.. option:: -fstrict-vtable-pointers 1454 1455 Enable optimizations based on the strict rules for overwriting polymorphic 1456 C++ objects, i.e. the vptr is invariant during an object's lifetime. 1457 This enables better devirtualization. Turned off by default, because it is 1458 still experimental. 1459 1460.. option:: -fwhole-program-vtables 1461 1462 Enable whole-program vtable optimizations, such as single-implementation 1463 devirtualization and virtual constant propagation, for classes with 1464 :doc:`hidden LTO visibility <LTOVisibility>`. Requires ``-flto``. 1465 1466.. option:: -fforce-emit-vtables 1467 1468 In order to improve devirtualization, forces emitting of vtables even in 1469 modules where it isn't necessary. It causes more inline virtual functions 1470 to be emitted. 1471 1472.. option:: -fno-assume-sane-operator-new 1473 1474 Don't assume that the C++'s new operator is sane. 1475 1476 This option tells the compiler to do not assume that C++'s global 1477 new operator will always return a pointer that does not alias any 1478 other pointer when the function returns. 1479 1480.. option:: -ftrap-function=[name] 1481 1482 Instruct code generator to emit a function call to the specified 1483 function name for ``__builtin_trap()``. 1484 1485 LLVM code generator translates ``__builtin_trap()`` to a trap 1486 instruction if it is supported by the target ISA. Otherwise, the 1487 builtin is translated into a call to ``abort``. If this option is 1488 set, then the code generator will always lower the builtin to a call 1489 to the specified function regardless of whether the target ISA has a 1490 trap instruction. This option is useful for environments (e.g. 1491 deeply embedded) where a trap cannot be properly handled, or when 1492 some custom behavior is desired. 1493 1494.. option:: -ftls-model=[model] 1495 1496 Select which TLS model to use. 1497 1498 Valid values are: ``global-dynamic``, ``local-dynamic``, 1499 ``initial-exec`` and ``local-exec``. The default value is 1500 ``global-dynamic``. The compiler may use a different model if the 1501 selected model is not supported by the target, or if a more 1502 efficient model can be used. The TLS model can be overridden per 1503 variable using the ``tls_model`` attribute. 1504 1505.. option:: -femulated-tls 1506 1507 Select emulated TLS model, which overrides all -ftls-model choices. 1508 1509 In emulated TLS mode, all access to TLS variables are converted to 1510 calls to __emutls_get_address in the runtime library. 1511 1512.. option:: -mhwdiv=[values] 1513 1514 Select the ARM modes (arm or thumb) that support hardware division 1515 instructions. 1516 1517 Valid values are: ``arm``, ``thumb`` and ``arm,thumb``. 1518 This option is used to indicate which mode (arm or thumb) supports 1519 hardware division instructions. This only applies to the ARM 1520 architecture. 1521 1522.. option:: -m[no-]crc 1523 1524 Enable or disable CRC instructions. 1525 1526 This option is used to indicate whether CRC instructions are to 1527 be generated. This only applies to the ARM architecture. 1528 1529 CRC instructions are enabled by default on ARMv8. 1530 1531.. option:: -mgeneral-regs-only 1532 1533 Generate code which only uses the general purpose registers. 1534 1535 This option restricts the generated code to use general registers 1536 only. This only applies to the AArch64 architecture. 1537 1538.. option:: -mcompact-branches=[values] 1539 1540 Control the usage of compact branches for MIPSR6. 1541 1542 Valid values are: ``never``, ``optimal`` and ``always``. 1543 The default value is ``optimal`` which generates compact branches 1544 when a delay slot cannot be filled. ``never`` disables the usage of 1545 compact branches and ``always`` generates compact branches whenever 1546 possible. 1547 1548**-f[no-]max-type-align=[number]** 1549 Instruct the code generator to not enforce a higher alignment than the given 1550 number (of bytes) when accessing memory via an opaque pointer or reference. 1551 This cap is ignored when directly accessing a variable or when the pointee 1552 type has an explicit “aligned” attribute. 1553 1554 The value should usually be determined by the properties of the system allocator. 1555 Some builtin types, especially vector types, have very high natural alignments; 1556 when working with values of those types, Clang usually wants to use instructions 1557 that take advantage of that alignment. However, many system allocators do 1558 not promise to return memory that is more than 8-byte or 16-byte-aligned. Use 1559 this option to limit the alignment that the compiler can assume for an arbitrary 1560 pointer, which may point onto the heap. 1561 1562 This option does not affect the ABI alignment of types; the layout of structs and 1563 unions and the value returned by the alignof operator remain the same. 1564 1565 This option can be overridden on a case-by-case basis by putting an explicit 1566 “aligned” alignment on a struct, union, or typedef. For example: 1567 1568 .. code-block:: console 1569 1570 #include <immintrin.h> 1571 // Make an aligned typedef of the AVX-512 16-int vector type. 1572 typedef __v16si __aligned_v16si __attribute__((aligned(64))); 1573 1574 void initialize_vector(__aligned_v16si *v) { 1575 // The compiler may assume that ‘v’ is 64-byte aligned, regardless of the 1576 // value of -fmax-type-align. 1577 } 1578 1579.. option:: -faddrsig, -fno-addrsig 1580 1581 Controls whether Clang emits an address-significance table into the object 1582 file. Address-significance tables allow linkers to implement `safe ICF 1583 <https://research.google.com/pubs/archive/36912.pdf>`_ without the false 1584 positives that can result from other implementation techniques such as 1585 relocation scanning. Address-significance tables are enabled by default 1586 on ELF targets when using the integrated assembler. This flag currently 1587 only has an effect on ELF targets. 1588 1589Profile Guided Optimization 1590--------------------------- 1591 1592Profile information enables better optimization. For example, knowing that a 1593branch is taken very frequently helps the compiler make better decisions when 1594ordering basic blocks. Knowing that a function ``foo`` is called more 1595frequently than another function ``bar`` helps the inliner. Optimization 1596levels ``-O2`` and above are recommended for use of profile guided optimization. 1597 1598Clang supports profile guided optimization with two different kinds of 1599profiling. A sampling profiler can generate a profile with very low runtime 1600overhead, or you can build an instrumented version of the code that collects 1601more detailed profile information. Both kinds of profiles can provide execution 1602counts for instructions in the code and information on branches taken and 1603function invocation. 1604 1605Regardless of which kind of profiling you use, be careful to collect profiles 1606by running your code with inputs that are representative of the typical 1607behavior. Code that is not exercised in the profile will be optimized as if it 1608is unimportant, and the compiler may make poor optimization choices for code 1609that is disproportionately used while profiling. 1610 1611Differences Between Sampling and Instrumentation 1612^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1613 1614Although both techniques are used for similar purposes, there are important 1615differences between the two: 1616 16171. Profile data generated with one cannot be used by the other, and there is no 1618 conversion tool that can convert one to the other. So, a profile generated 1619 via ``-fprofile-instr-generate`` must be used with ``-fprofile-instr-use``. 1620 Similarly, sampling profiles generated by external profilers must be 1621 converted and used with ``-fprofile-sample-use``. 1622 16232. Instrumentation profile data can be used for code coverage analysis and 1624 optimization. 1625 16263. Sampling profiles can only be used for optimization. They cannot be used for 1627 code coverage analysis. Although it would be technically possible to use 1628 sampling profiles for code coverage, sample-based profiles are too 1629 coarse-grained for code coverage purposes; it would yield poor results. 1630 16314. Sampling profiles must be generated by an external tool. The profile 1632 generated by that tool must then be converted into a format that can be read 1633 by LLVM. The section on sampling profilers describes one of the supported 1634 sampling profile formats. 1635 1636 1637Using Sampling Profilers 1638^^^^^^^^^^^^^^^^^^^^^^^^ 1639 1640Sampling profilers are used to collect runtime information, such as 1641hardware counters, while your application executes. They are typically 1642very efficient and do not incur a large runtime overhead. The 1643sample data collected by the profiler can be used during compilation 1644to determine what the most executed areas of the code are. 1645 1646Using the data from a sample profiler requires some changes in the way 1647a program is built. Before the compiler can use profiling information, 1648the code needs to execute under the profiler. The following is the 1649usual build cycle when using sample profilers for optimization: 1650 16511. Build the code with source line table information. You can use all the 1652 usual build flags that you always build your application with. The only 1653 requirement is that you add ``-gline-tables-only`` or ``-g`` to the 1654 command line. This is important for the profiler to be able to map 1655 instructions back to source line locations. 1656 1657 .. code-block:: console 1658 1659 $ clang++ -O2 -gline-tables-only code.cc -o code 1660 16612. Run the executable under a sampling profiler. The specific profiler 1662 you use does not really matter, as long as its output can be converted 1663 into the format that the LLVM optimizer understands. Currently, there 1664 exists a conversion tool for the Linux Perf profiler 1665 (https://perf.wiki.kernel.org/), so these examples assume that you 1666 are using Linux Perf to profile your code. 1667 1668 .. code-block:: console 1669 1670 $ perf record -b ./code 1671 1672 Note the use of the ``-b`` flag. This tells Perf to use the Last Branch 1673 Record (LBR) to record call chains. While this is not strictly required, 1674 it provides better call information, which improves the accuracy of 1675 the profile data. 1676 16773. Convert the collected profile data to LLVM's sample profile format. 1678 This is currently supported via the AutoFDO converter ``create_llvm_prof``. 1679 It is available at https://github.com/google/autofdo. Once built and 1680 installed, you can convert the ``perf.data`` file to LLVM using 1681 the command: 1682 1683 .. code-block:: console 1684 1685 $ create_llvm_prof --binary=./code --out=code.prof 1686 1687 This will read ``perf.data`` and the binary file ``./code`` and emit 1688 the profile data in ``code.prof``. Note that if you ran ``perf`` 1689 without the ``-b`` flag, you need to use ``--use_lbr=false`` when 1690 calling ``create_llvm_prof``. 1691 16924. Build the code again using the collected profile. This step feeds 1693 the profile back to the optimizers. This should result in a binary 1694 that executes faster than the original one. Note that you are not 1695 required to build the code with the exact same arguments that you 1696 used in the first step. The only requirement is that you build the code 1697 with ``-gline-tables-only`` and ``-fprofile-sample-use``. 1698 1699 .. code-block:: console 1700 1701 $ clang++ -O2 -gline-tables-only -fprofile-sample-use=code.prof code.cc -o code 1702 1703 1704Sample Profile Formats 1705"""""""""""""""""""""" 1706 1707Since external profilers generate profile data in a variety of custom formats, 1708the data generated by the profiler must be converted into a format that can be 1709read by the backend. LLVM supports three different sample profile formats: 1710 17111. ASCII text. This is the easiest one to generate. The file is divided into 1712 sections, which correspond to each of the functions with profile 1713 information. The format is described below. It can also be generated from 1714 the binary or gcov formats using the ``llvm-profdata`` tool. 1715 17162. Binary encoding. This uses a more efficient encoding that yields smaller 1717 profile files. This is the format generated by the ``create_llvm_prof`` tool 1718 in https://github.com/google/autofdo. 1719 17203. GCC encoding. This is based on the gcov format, which is accepted by GCC. It 1721 is only interesting in environments where GCC and Clang co-exist. This 1722 encoding is only generated by the ``create_gcov`` tool in 1723 https://github.com/google/autofdo. It can be read by LLVM and 1724 ``llvm-profdata``, but it cannot be generated by either. 1725 1726If you are using Linux Perf to generate sampling profiles, you can use the 1727conversion tool ``create_llvm_prof`` described in the previous section. 1728Otherwise, you will need to write a conversion tool that converts your 1729profiler's native format into one of these three. 1730 1731 1732Sample Profile Text Format 1733"""""""""""""""""""""""""" 1734 1735This section describes the ASCII text format for sampling profiles. It is, 1736arguably, the easiest one to generate. If you are interested in generating any 1737of the other two, consult the ``ProfileData`` library in LLVM's source tree 1738(specifically, ``include/llvm/ProfileData/SampleProfReader.h``). 1739 1740.. code-block:: console 1741 1742 function1:total_samples:total_head_samples 1743 offset1[.discriminator]: number_of_samples [fn1:num fn2:num ... ] 1744 offset2[.discriminator]: number_of_samples [fn3:num fn4:num ... ] 1745 ... 1746 offsetN[.discriminator]: number_of_samples [fn5:num fn6:num ... ] 1747 offsetA[.discriminator]: fnA:num_of_total_samples 1748 offsetA1[.discriminator]: number_of_samples [fn7:num fn8:num ... ] 1749 offsetA1[.discriminator]: number_of_samples [fn9:num fn10:num ... ] 1750 offsetB[.discriminator]: fnB:num_of_total_samples 1751 offsetB1[.discriminator]: number_of_samples [fn11:num fn12:num ... ] 1752 1753This is a nested tree in which the indentation represents the nesting level 1754of the inline stack. There are no blank lines in the file. And the spacing 1755within a single line is fixed. Additional spaces will result in an error 1756while reading the file. 1757 1758Any line starting with the '#' character is completely ignored. 1759 1760Inlined calls are represented with indentation. The Inline stack is a 1761stack of source locations in which the top of the stack represents the 1762leaf function, and the bottom of the stack represents the actual 1763symbol to which the instruction belongs. 1764 1765Function names must be mangled in order for the profile loader to 1766match them in the current translation unit. The two numbers in the 1767function header specify how many total samples were accumulated in the 1768function (first number), and the total number of samples accumulated 1769in the prologue of the function (second number). This head sample 1770count provides an indicator of how frequently the function is invoked. 1771 1772There are two types of lines in the function body. 1773 1774- Sampled line represents the profile information of a source location. 1775 ``offsetN[.discriminator]: number_of_samples [fn5:num fn6:num ... ]`` 1776 1777- Callsite line represents the profile information of an inlined callsite. 1778 ``offsetA[.discriminator]: fnA:num_of_total_samples`` 1779 1780Each sampled line may contain several items. Some are optional (marked 1781below): 1782 1783a. Source line offset. This number represents the line number 1784 in the function where the sample was collected. The line number is 1785 always relative to the line where symbol of the function is 1786 defined. So, if the function has its header at line 280, the offset 1787 13 is at line 293 in the file. 1788 1789 Note that this offset should never be a negative number. This could 1790 happen in cases like macros. The debug machinery will register the 1791 line number at the point of macro expansion. So, if the macro was 1792 expanded in a line before the start of the function, the profile 1793 converter should emit a 0 as the offset (this means that the optimizers 1794 will not be able to associate a meaningful weight to the instructions 1795 in the macro). 1796 1797b. [OPTIONAL] Discriminator. This is used if the sampled program 1798 was compiled with DWARF discriminator support 1799 (http://wiki.dwarfstd.org/index.php?title=Path_Discriminators). 1800 DWARF discriminators are unsigned integer values that allow the 1801 compiler to distinguish between multiple execution paths on the 1802 same source line location. 1803 1804 For example, consider the line of code ``if (cond) foo(); else bar();``. 1805 If the predicate ``cond`` is true 80% of the time, then the edge 1806 into function ``foo`` should be considered to be taken most of the 1807 time. But both calls to ``foo`` and ``bar`` are at the same source 1808 line, so a sample count at that line is not sufficient. The 1809 compiler needs to know which part of that line is taken more 1810 frequently. 1811 1812 This is what discriminators provide. In this case, the calls to 1813 ``foo`` and ``bar`` will be at the same line, but will have 1814 different discriminator values. This allows the compiler to correctly 1815 set edge weights into ``foo`` and ``bar``. 1816 1817c. Number of samples. This is an integer quantity representing the 1818 number of samples collected by the profiler at this source 1819 location. 1820 1821d. [OPTIONAL] Potential call targets and samples. If present, this 1822 line contains a call instruction. This models both direct and 1823 number of samples. For example, 1824 1825 .. code-block:: console 1826 1827 130: 7 foo:3 bar:2 baz:7 1828 1829 The above means that at relative line offset 130 there is a call 1830 instruction that calls one of ``foo()``, ``bar()`` and ``baz()``, 1831 with ``baz()`` being the relatively more frequently called target. 1832 1833As an example, consider a program with the call chain ``main -> foo -> bar``. 1834When built with optimizations enabled, the compiler may inline the 1835calls to ``bar`` and ``foo`` inside ``main``. The generated profile 1836could then be something like this: 1837 1838.. code-block:: console 1839 1840 main:35504:0 1841 1: _Z3foov:35504 1842 2: _Z32bari:31977 1843 1.1: 31977 1844 2: 0 1845 1846This profile indicates that there were a total of 35,504 samples 1847collected in main. All of those were at line 1 (the call to ``foo``). 1848Of those, 31,977 were spent inside the body of ``bar``. The last line 1849of the profile (``2: 0``) corresponds to line 2 inside ``main``. No 1850samples were collected there. 1851 1852Profiling with Instrumentation 1853^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1854 1855Clang also supports profiling via instrumentation. This requires building a 1856special instrumented version of the code and has some runtime 1857overhead during the profiling, but it provides more detailed results than a 1858sampling profiler. It also provides reproducible results, at least to the 1859extent that the code behaves consistently across runs. 1860 1861Here are the steps for using profile guided optimization with 1862instrumentation: 1863 18641. Build an instrumented version of the code by compiling and linking with the 1865 ``-fprofile-instr-generate`` option. 1866 1867 .. code-block:: console 1868 1869 $ clang++ -O2 -fprofile-instr-generate code.cc -o code 1870 18712. Run the instrumented executable with inputs that reflect the typical usage. 1872 By default, the profile data will be written to a ``default.profraw`` file 1873 in the current directory. You can override that default by using option 1874 ``-fprofile-instr-generate=`` or by setting the ``LLVM_PROFILE_FILE`` 1875 environment variable to specify an alternate file. If non-default file name 1876 is specified by both the environment variable and the command line option, 1877 the environment variable takes precedence. The file name pattern specified 1878 can include different modifiers: ``%p``, ``%h``, and ``%m``. 1879 1880 Any instance of ``%p`` in that file name will be replaced by the process 1881 ID, so that you can easily distinguish the profile output from multiple 1882 runs. 1883 1884 .. code-block:: console 1885 1886 $ LLVM_PROFILE_FILE="code-%p.profraw" ./code 1887 1888 The modifier ``%h`` can be used in scenarios where the same instrumented 1889 binary is run in multiple different host machines dumping profile data 1890 to a shared network based storage. The ``%h`` specifier will be substituted 1891 with the hostname so that profiles collected from different hosts do not 1892 clobber each other. 1893 1894 While the use of ``%p`` specifier can reduce the likelihood for the profiles 1895 dumped from different processes to clobber each other, such clobbering can still 1896 happen because of the ``pid`` re-use by the OS. Another side-effect of using 1897 ``%p`` is that the storage requirement for raw profile data files is greatly 1898 increased. To avoid issues like this, the ``%m`` specifier can used in the profile 1899 name. When this specifier is used, the profiler runtime will substitute ``%m`` 1900 with a unique integer identifier associated with the instrumented binary. Additionally, 1901 multiple raw profiles dumped from different processes that share a file system (can be 1902 on different hosts) will be automatically merged by the profiler runtime during the 1903 dumping. If the program links in multiple instrumented shared libraries, each library 1904 will dump the profile data into its own profile data file (with its unique integer 1905 id embedded in the profile name). Note that the merging enabled by ``%m`` is for raw 1906 profile data generated by profiler runtime. The resulting merged "raw" profile data 1907 file still needs to be converted to a different format expected by the compiler ( 1908 see step 3 below). 1909 1910 .. code-block:: console 1911 1912 $ LLVM_PROFILE_FILE="code-%m.profraw" ./code 1913 1914 19153. Combine profiles from multiple runs and convert the "raw" profile format to 1916 the input expected by clang. Use the ``merge`` command of the 1917 ``llvm-profdata`` tool to do this. 1918 1919 .. code-block:: console 1920 1921 $ llvm-profdata merge -output=code.profdata code-*.profraw 1922 1923 Note that this step is necessary even when there is only one "raw" profile, 1924 since the merge operation also changes the file format. 1925 19264. Build the code again using the ``-fprofile-instr-use`` option to specify the 1927 collected profile data. 1928 1929 .. code-block:: console 1930 1931 $ clang++ -O2 -fprofile-instr-use=code.profdata code.cc -o code 1932 1933 You can repeat step 4 as often as you like without regenerating the 1934 profile. As you make changes to your code, clang may no longer be able to 1935 use the profile data. It will warn you when this happens. 1936 1937Profile generation using an alternative instrumentation method can be 1938controlled by the GCC-compatible flags ``-fprofile-generate`` and 1939``-fprofile-use``. Although these flags are semantically equivalent to 1940their GCC counterparts, they *do not* handle GCC-compatible profiles. 1941They are only meant to implement GCC's semantics with respect to 1942profile creation and use. Flag ``-fcs-profile-generate`` also instruments 1943programs using the same instrumentation method as ``-fprofile-generate``. 1944 1945.. option:: -fprofile-generate[=<dirname>] 1946 1947 The ``-fprofile-generate`` and ``-fprofile-generate=`` flags will use 1948 an alternative instrumentation method for profile generation. When 1949 given a directory name, it generates the profile file 1950 ``default_%m.profraw`` in the directory named ``dirname`` if specified. 1951 If ``dirname`` does not exist, it will be created at runtime. ``%m`` specifier 1952 will be substituted with a unique id documented in step 2 above. In other words, 1953 with ``-fprofile-generate[=<dirname>]`` option, the "raw" profile data automatic 1954 merging is turned on by default, so there will no longer any risk of profile 1955 clobbering from different running processes. For example, 1956 1957 .. code-block:: console 1958 1959 $ clang++ -O2 -fprofile-generate=yyy/zzz code.cc -o code 1960 1961 When ``code`` is executed, the profile will be written to the file 1962 ``yyy/zzz/default_xxxx.profraw``. 1963 1964 To generate the profile data file with the compiler readable format, the 1965 ``llvm-profdata`` tool can be used with the profile directory as the input: 1966 1967 .. code-block:: console 1968 1969 $ llvm-profdata merge -output=code.profdata yyy/zzz/ 1970 1971 If the user wants to turn off the auto-merging feature, or simply override the 1972 the profile dumping path specified at command line, the environment variable 1973 ``LLVM_PROFILE_FILE`` can still be used to override 1974 the directory and filename for the profile file at runtime. 1975 1976.. option:: -fcs-profile-generate[=<dirname>] 1977 1978 The ``-fcs-profile-generate`` and ``-fcs-profile-generate=`` flags will use 1979 the same instrumentation method, and generate the same profile as in the 1980 ``-fprofile-generate`` and ``-fprofile-generate=`` flags. The difference is 1981 that the instrumentation is performed after inlining so that the resulted 1982 profile has a better context sensitive information. They cannot be used 1983 together with ``-fprofile-generate`` and ``-fprofile-generate=`` flags. 1984 They are typically used in conjunction with ``-fprofile-use`` flag. 1985 The profile generated by ``-fcs-profile-generate`` and ``-fprofile-generate`` 1986 can be merged by llvm-profdata. A use example: 1987 1988 .. code-block:: console 1989 1990 $ clang++ -O2 -fprofile-generate=yyy/zzz code.cc -o code 1991 $ ./code 1992 $ llvm-profdata merge -output=code.profdata yyy/zzz/ 1993 1994 The first few steps are the same as that in ``-fprofile-generate`` 1995 compilation. Then perform a second round of instrumentation. 1996 1997 .. code-block:: console 1998 1999 $ clang++ -O2 -fprofile-use=code.profdata -fcs-profile-generate=sss/ttt \ 2000 -o cs_code 2001 $ ./cs_code 2002 $ llvm-profdata merge -output=cs_code.profdata sss/ttt code.profdata 2003 2004 The resulted ``cs_code.prodata`` combines ``code.profdata`` and the profile 2005 generated from binary ``cs_code``. Profile ``cs_code.profata`` can be used by 2006 ``-fprofile-use`` compilaton. 2007 2008 .. code-block:: console 2009 2010 $ clang++ -O2 -fprofile-use=cs_code.profdata 2011 2012 The above command will read both profiles to the compiler at the identical 2013 point of instrumenations. 2014 2015.. option:: -fprofile-use[=<pathname>] 2016 2017 Without any other arguments, ``-fprofile-use`` behaves identically to 2018 ``-fprofile-instr-use``. Otherwise, if ``pathname`` is the full path to a 2019 profile file, it reads from that file. If ``pathname`` is a directory name, 2020 it reads from ``pathname/default.profdata``. 2021 2022Disabling Instrumentation 2023^^^^^^^^^^^^^^^^^^^^^^^^^ 2024 2025In certain situations, it may be useful to disable profile generation or use 2026for specific files in a build, without affecting the main compilation flags 2027used for the other files in the project. 2028 2029In these cases, you can use the flag ``-fno-profile-instr-generate`` (or 2030``-fno-profile-generate``) to disable profile generation, and 2031``-fno-profile-instr-use`` (or ``-fno-profile-use``) to disable profile use. 2032 2033Note that these flags should appear after the corresponding profile 2034flags to have an effect. 2035 2036Profile remapping 2037^^^^^^^^^^^^^^^^^ 2038 2039When the program is compiled after a change that affects many symbol names, 2040pre-existing profile data may no longer match the program. For example: 2041 2042 * switching from libstdc++ to libc++ will result in the mangled names of all 2043 functions taking standard library types to change 2044 * renaming a widely-used type in C++ will result in the mangled names of all 2045 functions that have parameters involving that type to change 2046 * moving from a 32-bit compilation to a 64-bit compilation may change the 2047 underlying type of ``size_t`` and similar types, resulting in changes to 2048 manglings 2049 2050Clang allows use of a profile remapping file to specify that such differences 2051in mangled names should be ignored when matching the profile data against the 2052program. 2053 2054.. option:: -fprofile-remapping-file=<file> 2055 2056 Specifies a file containing profile remapping information, that will be 2057 used to match mangled names in the profile data to mangled names in the 2058 program. 2059 2060The profile remapping file is a text file containing lines of the form 2061 2062.. code-block:: text 2063 2064 fragmentkind fragment1 fragment2 2065 2066where ``fragmentkind`` is one of ``name``, ``type``, or ``encoding``, 2067indicating whether the following mangled name fragments are 2068<`name <https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangle.name>`_>s, 2069<`type <https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangle.type>`_>s, or 2070<`encoding <https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangle.encoding>`_>s, 2071respectively. 2072Blank lines and lines starting with ``#`` are ignored. 2073 2074For convenience, built-in <substitution>s such as ``St`` and ``Ss`` 2075are accepted as <name>s (even though they technically are not <name>s). 2076 2077For example, to specify that ``absl::string_view`` and ``std::string_view`` 2078should be treated as equivalent when matching profile data, the following 2079remapping file could be used: 2080 2081.. code-block:: text 2082 2083 # absl::string_view is considered equivalent to std::string_view 2084 type N4absl11string_viewE St17basic_string_viewIcSt11char_traitsIcEE 2085 2086 # std:: might be std::__1:: in libc++ or std::__cxx11:: in libstdc++ 2087 name 3std St3__1 2088 name 3std St7__cxx11 2089 2090Matching profile data using a profile remapping file is supported on a 2091best-effort basis. For example, information regarding indirect call targets is 2092currently not remapped. For best results, you are encouraged to generate new 2093profile data matching the updated program, or to remap the profile data 2094using the ``llvm-cxxmap`` and ``llvm-profdata merge`` tools. 2095 2096.. note:: 2097 2098 Profile data remapping support is currently only implemented for LLVM's 2099 new pass manager, which can be enabled with 2100 ``-fexperimental-new-pass-manager``. 2101 2102.. note:: 2103 2104 Profile data remapping is currently only supported for C++ mangled names 2105 following the Itanium C++ ABI mangling scheme. This covers all C++ targets 2106 supported by Clang other than Windows. 2107 2108GCOV-based Profiling 2109-------------------- 2110 2111GCOV is a test coverage program, it helps to know how often a line of code 2112is executed. When instrumenting the code with ``--coverage`` option, some 2113counters are added for each edge linking basic blocks. 2114 2115At compile time, gcno files are generated containing information about 2116blocks and edges between them. At runtime the counters are incremented and at 2117exit the counters are dumped in gcda files. 2118 2119The tool ``llvm-cov gcov`` will parse gcno, gcda and source files to generate 2120a report ``.c.gcov``. 2121 2122.. option:: -fprofile-filter-files=[regexes] 2123 2124 Define a list of regexes separated by a semi-colon. 2125 If a file name matches any of the regexes then the file is instrumented. 2126 2127 .. code-block:: console 2128 2129 $ clang --coverage -fprofile-filter-files=".*\.c$" foo.c 2130 2131 For example, this will only instrument files finishing with ``.c``, skipping ``.h`` files. 2132 2133.. option:: -fprofile-exclude-files=[regexes] 2134 2135 Define a list of regexes separated by a semi-colon. 2136 If a file name doesn't match all the regexes then the file is instrumented. 2137 2138 .. code-block:: console 2139 2140 $ clang --coverage -fprofile-exclude-files="^/usr/include/.*$" foo.c 2141 2142 For example, this will instrument all the files except the ones in ``/usr/include``. 2143 2144If both options are used then a file is instrumented if its name matches any 2145of the regexes from ``-fprofile-filter-list`` and doesn't match all the regexes 2146from ``-fprofile-exclude-list``. 2147 2148.. code-block:: console 2149 2150 $ clang --coverage -fprofile-exclude-files="^/usr/include/.*$" \ 2151 -fprofile-filter-files="^/usr/.*$" 2152 2153In that case ``/usr/foo/oof.h`` is instrumented since it matches the filter regex and 2154doesn't match the exclude regex, but ``/usr/include/foo.h`` doesn't since it matches 2155the exclude regex. 2156 2157Controlling Debug Information 2158----------------------------- 2159 2160Controlling Size of Debug Information 2161^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2162 2163Debug info kind generated by Clang can be set by one of the flags listed 2164below. If multiple flags are present, the last one is used. 2165 2166.. option:: -g0 2167 2168 Don't generate any debug info (default). 2169 2170.. option:: -gline-tables-only 2171 2172 Generate line number tables only. 2173 2174 This kind of debug info allows to obtain stack traces with function names, 2175 file names and line numbers (by such tools as ``gdb`` or ``addr2line``). It 2176 doesn't contain any other data (e.g. description of local variables or 2177 function parameters). 2178 2179.. option:: -fstandalone-debug 2180 2181 Clang supports a number of optimizations to reduce the size of debug 2182 information in the binary. They work based on the assumption that 2183 the debug type information can be spread out over multiple 2184 compilation units. For instance, Clang will not emit type 2185 definitions for types that are not needed by a module and could be 2186 replaced with a forward declaration. Further, Clang will only emit 2187 type info for a dynamic C++ class in the module that contains the 2188 vtable for the class. 2189 2190 The **-fstandalone-debug** option turns off these optimizations. 2191 This is useful when working with 3rd-party libraries that don't come 2192 with debug information. Note that Clang will never emit type 2193 information for types that are not referenced at all by the program. 2194 2195.. option:: -fno-standalone-debug 2196 2197 On Darwin **-fstandalone-debug** is enabled by default. The 2198 **-fno-standalone-debug** option can be used to get to turn on the 2199 vtable-based optimization described above. 2200 2201.. option:: -g 2202 2203 Generate complete debug info. 2204 2205Controlling Macro Debug Info Generation 2206^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2207 2208Debug info for C preprocessor macros increases the size of debug information in 2209the binary. Macro debug info generated by Clang can be controlled by the flags 2210listed below. 2211 2212.. option:: -fdebug-macro 2213 2214 Generate debug info for preprocessor macros. This flag is discarded when 2215 **-g0** is enabled. 2216 2217.. option:: -fno-debug-macro 2218 2219 Do not generate debug info for preprocessor macros (default). 2220 2221Controlling Debugger "Tuning" 2222^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2223 2224While Clang generally emits standard DWARF debug info (http://dwarfstd.org), 2225different debuggers may know how to take advantage of different specific DWARF 2226features. You can "tune" the debug info for one of several different debuggers. 2227 2228.. option:: -ggdb, -glldb, -gsce 2229 2230 Tune the debug info for the ``gdb``, ``lldb``, or Sony PlayStation\ |reg| 2231 debugger, respectively. Each of these options implies **-g**. (Therefore, if 2232 you want both **-gline-tables-only** and debugger tuning, the tuning option 2233 must come first.) 2234 2235 2236Controlling LLVM IR Output 2237-------------------------- 2238 2239Controlling Value Names in LLVM IR 2240^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2241 2242Emitting value names in LLVM IR increases the size and verbosity of the IR. 2243By default, value names are only emitted in assertion-enabled builds of Clang. 2244However, when reading IR it can be useful to re-enable the emission of value 2245names to improve readability. 2246 2247.. option:: -fdiscard-value-names 2248 2249 Discard value names when generating LLVM IR. 2250 2251.. option:: -fno-discard-value-names 2252 2253 Do not discard value names when generating LLVM IR. This option can be used 2254 to re-enable names for release builds of Clang. 2255 2256 2257Comment Parsing Options 2258----------------------- 2259 2260Clang parses Doxygen and non-Doxygen style documentation comments and attaches 2261them to the appropriate declaration nodes. By default, it only parses 2262Doxygen-style comments and ignores ordinary comments starting with ``//`` and 2263``/*``. 2264 2265.. option:: -Wdocumentation 2266 2267 Emit warnings about use of documentation comments. This warning group is off 2268 by default. 2269 2270 This includes checking that ``\param`` commands name parameters that actually 2271 present in the function signature, checking that ``\returns`` is used only on 2272 functions that actually return a value etc. 2273 2274.. option:: -Wno-documentation-unknown-command 2275 2276 Don't warn when encountering an unknown Doxygen command. 2277 2278.. option:: -fparse-all-comments 2279 2280 Parse all comments as documentation comments (including ordinary comments 2281 starting with ``//`` and ``/*``). 2282 2283.. option:: -fcomment-block-commands=[commands] 2284 2285 Define custom documentation commands as block commands. This allows Clang to 2286 construct the correct AST for these custom commands, and silences warnings 2287 about unknown commands. Several commands must be separated by a comma 2288 *without trailing space*; e.g. ``-fcomment-block-commands=foo,bar`` defines 2289 custom commands ``\foo`` and ``\bar``. 2290 2291 It is also possible to use ``-fcomment-block-commands`` several times; e.g. 2292 ``-fcomment-block-commands=foo -fcomment-block-commands=bar`` does the same 2293 as above. 2294 2295.. _c: 2296 2297C Language Features 2298=================== 2299 2300The support for standard C in clang is feature-complete except for the 2301C99 floating-point pragmas. 2302 2303Extensions supported by clang 2304----------------------------- 2305 2306See :doc:`LanguageExtensions`. 2307 2308Differences between various standard modes 2309------------------------------------------ 2310 2311clang supports the -std option, which changes what language mode clang 2312uses. The supported modes for C are c89, gnu89, c99, gnu99, c11, gnu11, 2313c17, gnu17, and various aliases for those modes. If no -std option is 2314specified, clang defaults to gnu11 mode. Many C99 and C11 features are 2315supported in earlier modes as a conforming extension, with a warning. Use 2316``-pedantic-errors`` to request an error if a feature from a later standard 2317revision is used in an earlier mode. 2318 2319Differences between all ``c*`` and ``gnu*`` modes: 2320 2321- ``c*`` modes define "``__STRICT_ANSI__``". 2322- Target-specific defines not prefixed by underscores, like "linux", 2323 are defined in ``gnu*`` modes. 2324- Trigraphs default to being off in ``gnu*`` modes; they can be enabled by 2325 the -trigraphs option. 2326- The parser recognizes "asm" and "typeof" as keywords in ``gnu*`` modes; 2327 the variants "``__asm__``" and "``__typeof__``" are recognized in all 2328 modes. 2329- The Apple "blocks" extension is recognized by default in ``gnu*`` modes 2330 on some platforms; it can be enabled in any mode with the "-fblocks" 2331 option. 2332- Arrays that are VLA's according to the standard, but which can be 2333 constant folded by the frontend are treated as fixed size arrays. 2334 This occurs for things like "int X[(1, 2)];", which is technically a 2335 VLA. ``c*`` modes are strictly compliant and treat these as VLAs. 2336 2337Differences between ``*89`` and ``*99`` modes: 2338 2339- The ``*99`` modes default to implementing "inline" as specified in C99, 2340 while the ``*89`` modes implement the GNU version. This can be 2341 overridden for individual functions with the ``__gnu_inline__`` 2342 attribute. 2343- Digraphs are not recognized in c89 mode. 2344- The scope of names defined inside a "for", "if", "switch", "while", 2345 or "do" statement is different. (example: "``if ((struct x {int 2346 x;}*)0) {}``".) 2347- ``__STDC_VERSION__`` is not defined in ``*89`` modes. 2348- "inline" is not recognized as a keyword in c89 mode. 2349- "restrict" is not recognized as a keyword in ``*89`` modes. 2350- Commas are allowed in integer constant expressions in ``*99`` modes. 2351- Arrays which are not lvalues are not implicitly promoted to pointers 2352 in ``*89`` modes. 2353- Some warnings are different. 2354 2355Differences between ``*99`` and ``*11`` modes: 2356 2357- Warnings for use of C11 features are disabled. 2358- ``__STDC_VERSION__`` is defined to ``201112L`` rather than ``199901L``. 2359 2360Differences between ``*11`` and ``*17`` modes: 2361 2362- ``__STDC_VERSION__`` is defined to ``201710L`` rather than ``201112L``. 2363 2364GCC extensions not implemented yet 2365---------------------------------- 2366 2367clang tries to be compatible with gcc as much as possible, but some gcc 2368extensions are not implemented yet: 2369 2370- clang does not support decimal floating point types (``_Decimal32`` and 2371 friends) or fixed-point types (``_Fract`` and friends); nobody has 2372 expressed interest in these features yet, so it's hard to say when 2373 they will be implemented. 2374- clang does not support nested functions; this is a complex feature 2375 which is infrequently used, so it is unlikely to be implemented 2376 anytime soon. In C++11 it can be emulated by assigning lambda 2377 functions to local variables, e.g: 2378 2379 .. code-block:: cpp 2380 2381 auto const local_function = [&](int parameter) { 2382 // Do something 2383 }; 2384 ... 2385 local_function(1); 2386 2387- clang only supports global register variables when the register specified 2388 is non-allocatable (e.g. the stack pointer). Support for general global 2389 register variables is unlikely to be implemented soon because it requires 2390 additional LLVM backend support. 2391- clang does not support static initialization of flexible array 2392 members. This appears to be a rarely used extension, but could be 2393 implemented pending user demand. 2394- clang does not support 2395 ``__builtin_va_arg_pack``/``__builtin_va_arg_pack_len``. This is 2396 used rarely, but in some potentially interesting places, like the 2397 glibc headers, so it may be implemented pending user demand. Note 2398 that because clang pretends to be like GCC 4.2, and this extension 2399 was introduced in 4.3, the glibc headers will not try to use this 2400 extension with clang at the moment. 2401- clang does not support the gcc extension for forward-declaring 2402 function parameters; this has not shown up in any real-world code 2403 yet, though, so it might never be implemented. 2404 2405This is not a complete list; if you find an unsupported extension 2406missing from this list, please send an e-mail to cfe-dev. This list 2407currently excludes C++; see :ref:`C++ Language Features <cxx>`. Also, this 2408list does not include bugs in mostly-implemented features; please see 2409the `bug 2410tracker <https://bugs.llvm.org/buglist.cgi?quicksearch=product%3Aclang+component%3A-New%2BBugs%2CAST%2CBasic%2CDriver%2CHeaders%2CLLVM%2BCodeGen%2Cparser%2Cpreprocessor%2CSemantic%2BAnalyzer>`_ 2411for known existing bugs (FIXME: Is there a section for bug-reporting 2412guidelines somewhere?). 2413 2414Intentionally unsupported GCC extensions 2415---------------------------------------- 2416 2417- clang does not support the gcc extension that allows variable-length 2418 arrays in structures. This is for a few reasons: one, it is tricky to 2419 implement, two, the extension is completely undocumented, and three, 2420 the extension appears to be rarely used. Note that clang *does* 2421 support flexible array members (arrays with a zero or unspecified 2422 size at the end of a structure). 2423- clang does not have an equivalent to gcc's "fold"; this means that 2424 clang doesn't accept some constructs gcc might accept in contexts 2425 where a constant expression is required, like "x-x" where x is a 2426 variable. 2427- clang does not support ``__builtin_apply`` and friends; this extension 2428 is extremely obscure and difficult to implement reliably. 2429 2430.. _c_ms: 2431 2432Microsoft extensions 2433-------------------- 2434 2435clang has support for many extensions from Microsoft Visual C++. To enable these 2436extensions, use the ``-fms-extensions`` command-line option. This is the default 2437for Windows targets. Clang does not implement every pragma or declspec provided 2438by MSVC, but the popular ones, such as ``__declspec(dllexport)`` and ``#pragma 2439comment(lib)`` are well supported. 2440 2441clang has a ``-fms-compatibility`` flag that makes clang accept enough 2442invalid C++ to be able to parse most Microsoft headers. For example, it 2443allows `unqualified lookup of dependent base class members 2444<https://clang.llvm.org/compatibility.html#dep_lookup_bases>`_, which is 2445a common compatibility issue with clang. This flag is enabled by default 2446for Windows targets. 2447 2448``-fdelayed-template-parsing`` lets clang delay parsing of function template 2449definitions until the end of a translation unit. This flag is enabled by 2450default for Windows targets. 2451 2452For compatibility with existing code that compiles with MSVC, clang defines the 2453``_MSC_VER`` and ``_MSC_FULL_VER`` macros. These default to the values of 1800 2454and 180000000 respectively, making clang look like an early release of Visual 2455C++ 2013. The ``-fms-compatibility-version=`` flag overrides these values. It 2456accepts a dotted version tuple, such as 19.00.23506. Changing the MSVC 2457compatibility version makes clang behave more like that version of MSVC. For 2458example, ``-fms-compatibility-version=19`` will enable C++14 features and define 2459``char16_t`` and ``char32_t`` as builtin types. 2460 2461.. _cxx: 2462 2463C++ Language Features 2464===================== 2465 2466clang fully implements all of standard C++98 except for exported 2467templates (which were removed in C++11), and all of standard C++11 2468and the current draft standard for C++1y. 2469 2470Controlling implementation limits 2471--------------------------------- 2472 2473.. option:: -fbracket-depth=N 2474 2475 Sets the limit for nested parentheses, brackets, and braces to N. The 2476 default is 256. 2477 2478.. option:: -fconstexpr-depth=N 2479 2480 Sets the limit for recursive constexpr function invocations to N. The 2481 default is 512. 2482 2483.. option:: -fconstexpr-steps=N 2484 2485 Sets the limit for the number of full-expressions evaluated in a single 2486 constant expression evaluation. The default is 1048576. 2487 2488.. option:: -ftemplate-depth=N 2489 2490 Sets the limit for recursively nested template instantiations to N. The 2491 default is 1024. 2492 2493.. option:: -foperator-arrow-depth=N 2494 2495 Sets the limit for iterative calls to 'operator->' functions to N. The 2496 default is 256. 2497 2498.. _objc: 2499 2500Objective-C Language Features 2501============================= 2502 2503.. _objcxx: 2504 2505Objective-C++ Language Features 2506=============================== 2507 2508.. _openmp: 2509 2510OpenMP Features 2511=============== 2512 2513Clang supports all OpenMP 4.5 directives and clauses. See :doc:`OpenMPSupport` 2514for additional details. 2515 2516Use `-fopenmp` to enable OpenMP. Support for OpenMP can be disabled with 2517`-fno-openmp`. 2518 2519Use `-fopenmp-simd` to enable OpenMP simd features only, without linking 2520the runtime library; for combined constructs 2521(e.g. ``#pragma omp parallel for simd``) the non-simd directives and clauses 2522will be ignored. This can be disabled with `-fno-openmp-simd`. 2523 2524Controlling implementation limits 2525--------------------------------- 2526 2527.. option:: -fopenmp-use-tls 2528 2529 Controls code generation for OpenMP threadprivate variables. In presence of 2530 this option all threadprivate variables are generated the same way as thread 2531 local variables, using TLS support. If `-fno-openmp-use-tls` 2532 is provided or target does not support TLS, code generation for threadprivate 2533 variables relies on OpenMP runtime library. 2534 2535.. _opencl: 2536 2537OpenCL Features 2538=============== 2539 2540Clang can be used to compile OpenCL kernels for execution on a device 2541(e.g. GPU). It is possible to compile the kernel into a binary (e.g. for AMD or 2542Nvidia targets) that can be uploaded to run directly on a device (e.g. using 2543`clCreateProgramWithBinary 2544<https://www.khronos.org/registry/OpenCL/specs/opencl-1.1.pdf#111>`_) or 2545into generic bitcode files loadable into other toolchains. 2546 2547Compiling to a binary using the default target from the installation can be done 2548as follows: 2549 2550 .. code-block:: console 2551 2552 $ echo "kernel void k(){}" > test.cl 2553 $ clang test.cl 2554 2555Compiling for a specific target can be done by specifying the triple corresponding 2556to the target, for example: 2557 2558 .. code-block:: console 2559 2560 $ clang -target nvptx64-unknown-unknown test.cl 2561 $ clang -target amdgcn-amd-amdhsa -mcpu=gfx900 test.cl 2562 2563Compiling to bitcode can be done as follows: 2564 2565 .. code-block:: console 2566 2567 $ clang -c -emit-llvm test.cl 2568 2569This will produce a generic test.bc file that can be used in vendor toolchains 2570to perform machine code generation. 2571 2572Clang currently supports OpenCL C language standards up to v2.0. Starting from 2573clang 9 a C++ mode is available for OpenCL (see :ref:`C++ for OpenCL <opencl_cpp>`). 2574 2575OpenCL Specific Options 2576----------------------- 2577 2578Most of the OpenCL build options from `the specification v2.0 section 5.8.4 2579<https://www.khronos.org/registry/cl/specs/opencl-2.0.pdf#200>`_ are available. 2580 2581Examples: 2582 2583 .. code-block:: console 2584 2585 $ clang -cl-std=CL2.0 -cl-single-precision-constant test.cl 2586 2587Some extra options are available to support special OpenCL features. 2588 2589.. option:: -finclude-default-header 2590 2591Loads standard includes during compilations. By default OpenCL headers are not 2592loaded and therefore standard library includes are not available. To load them 2593automatically a flag has been added to the frontend (see also :ref:`the section 2594on the OpenCL Header <opencl_header>`): 2595 2596 .. code-block:: console 2597 2598 $ clang -Xclang -finclude-default-header test.cl 2599 2600Alternatively ``-include`` or ``-I`` followed by the path to the header location 2601can be given manually. 2602 2603 .. code-block:: console 2604 2605 $ clang -I<path to clang>/lib/Headers/opencl-c.h test.cl 2606 2607In this case the kernel code should contain ``#include <opencl-c.h>`` just as a 2608regular C include. 2609 2610.. _opencl_cl_ext: 2611 2612.. option:: -cl-ext 2613 2614Disables support of OpenCL extensions. All OpenCL targets provide a list 2615of extensions that they support. Clang allows to amend this using the ``-cl-ext`` 2616flag with a comma-separated list of extensions prefixed with ``'+'`` or ``'-'``. 2617The syntax: ``-cl-ext=<(['-'|'+']<extension>[,])+>``, where extensions 2618can be either one of `the OpenCL specification extensions 2619<https://www.khronos.org/registry/cl/sdk/2.0/docs/man/xhtml/EXTENSION.html>`_ 2620or any known vendor extension. Alternatively, ``'all'`` can be used to enable 2621or disable all known extensions. 2622Example disabling double support for the 64-bit SPIR target: 2623 2624 .. code-block:: console 2625 2626 $ clang -cc1 -triple spir64-unknown-unknown -cl-ext=-cl_khr_fp64 test.cl 2627 2628Enabling all extensions except double support in R600 AMD GPU can be done using: 2629 2630 .. code-block:: console 2631 2632 $ clang -cc1 -triple r600-unknown-unknown -cl-ext=-all,+cl_khr_fp16 test.cl 2633 2634.. _opencl_fake_address_space_map: 2635 2636.. option:: -ffake-address-space-map 2637 2638Overrides the target address space map with a fake map. 2639This allows adding explicit address space IDs to the bitcode for non-segmented 2640memory architectures that don't have separate IDs for each of the OpenCL 2641logical address spaces by default. Passing ``-ffake-address-space-map`` will 2642add/override address spaces of the target compiled for with the following values: 2643``1-global``, ``2-constant``, ``3-local``, ``4-generic``. The private address 2644space is represented by the absence of an address space attribute in the IR (see 2645also :ref:`the section on the address space attribute <opencl_addrsp>`). 2646 2647 .. code-block:: console 2648 2649 $ clang -ffake-address-space-map test.cl 2650 2651Some other flags used for the compilation for C can also be passed while 2652compiling for OpenCL, examples: ``-c``, ``-O<1-4|s>``, ``-o``, ``-emit-llvm``, etc. 2653 2654OpenCL Targets 2655-------------- 2656 2657OpenCL targets are derived from the regular Clang target classes. The OpenCL 2658specific parts of the target representation provide address space mapping as 2659well as a set of supported extensions. 2660 2661Specific Targets 2662^^^^^^^^^^^^^^^^ 2663 2664There is a set of concrete HW architectures that OpenCL can be compiled for. 2665 2666- For AMD target: 2667 2668 .. code-block:: console 2669 2670 $ clang -target amdgcn-amd-amdhsa -mcpu=gfx900 test.cl 2671 2672- For Nvidia architectures: 2673 2674 .. code-block:: console 2675 2676 $ clang -target nvptx64-unknown-unknown test.cl 2677 2678 2679Generic Targets 2680^^^^^^^^^^^^^^^ 2681 2682- SPIR is available as a generic target to allow portable bitcode to be produced 2683 that can be used across GPU toolchains. The implementation follows `the SPIR 2684 specification <https://www.khronos.org/spir>`_. There are two flavors 2685 available for 32 and 64 bits. 2686 2687 .. code-block:: console 2688 2689 $ clang -target spir-unknown-unknown test.cl 2690 $ clang -target spir64-unknown-unknown test.cl 2691 2692 All known OpenCL extensions are supported in the SPIR targets. Clang will 2693 generate SPIR v1.2 compatible IR for OpenCL versions up to 2.0 and SPIR v2.0 2694 for OpenCL v2.0. 2695 2696- x86 is used by some implementations that are x86 compatible and currently 2697 remains for backwards compatibility (with older implementations prior to 2698 SPIR target support). For "non-SPMD" targets which cannot spawn multiple 2699 work-items on the fly using hardware, which covers practically all non-GPU 2700 devices such as CPUs and DSPs, additional processing is needed for the kernels 2701 to support multiple work-item execution. For this, a 3rd party toolchain, 2702 such as for example `POCL <http://portablecl.org/>`_, can be used. 2703 2704 This target does not support multiple memory segments and, therefore, the fake 2705 address space map can be added using the :ref:`-ffake-address-space-map 2706 <opencl_fake_address_space_map>` flag. 2707 2708.. _opencl_header: 2709 2710OpenCL Header 2711------------- 2712 2713By default Clang will not include standard headers and therefore OpenCL builtin 2714functions and some types (i.e. vectors) are unknown. The default CL header is, 2715however, provided in the Clang installation and can be enabled by passing the 2716``-finclude-default-header`` flag to the Clang frontend. 2717 2718 .. code-block:: console 2719 2720 $ echo "bool is_wg_uniform(int i){return get_enqueued_local_size(i)==get_local_size(i);}" > test.cl 2721 $ clang -Xclang -finclude-default-header -cl-std=CL2.0 test.cl 2722 2723Because the header is very large and long to parse, PCH (:doc:`PCHInternals`) 2724and modules (:doc:`Modules`) are used internally to improve the compilation 2725speed. 2726 2727To enable modules for OpenCL: 2728 2729 .. code-block:: console 2730 2731 $ clang -target spir-unknown-unknown -c -emit-llvm -Xclang -finclude-default-header -fmodules -fimplicit-module-maps -fmodules-cache-path=<path to the generated module> test.cl 2732 2733OpenCL Extensions 2734----------------- 2735 2736All of the ``cl_khr_*`` extensions from `the official OpenCL specification 2737<https://www.khronos.org/registry/OpenCL/sdk/2.0/docs/man/xhtml/EXTENSION.html>`_ 2738up to and including version 2.0 are available and set per target depending on the 2739support available in the specific architecture. 2740 2741It is possible to alter the default extensions setting per target using 2742``-cl-ext`` flag. (See :ref:`flags description <opencl_cl_ext>` for more details). 2743 2744Vendor extensions can be added flexibly by declaring the list of types and 2745functions associated with each extensions enclosed within the following 2746compiler pragma directives: 2747 2748 .. code-block:: c 2749 2750 #pragma OPENCL EXTENSION the_new_extension_name : begin 2751 // declare types and functions associated with the extension here 2752 #pragma OPENCL EXTENSION the_new_extension_name : end 2753 2754For example, parsing the following code adds ``my_t`` type and ``my_func`` 2755function to the custom ``my_ext`` extension. 2756 2757 .. code-block:: c 2758 2759 #pragma OPENCL EXTENSION my_ext : begin 2760 typedef struct{ 2761 int a; 2762 }my_t; 2763 void my_func(my_t); 2764 #pragma OPENCL EXTENSION my_ext : end 2765 2766Declaring the same types in different vendor extensions is disallowed. 2767 2768OpenCL Metadata 2769--------------- 2770 2771Clang uses metadata to provide additional OpenCL semantics in IR needed for 2772backends and OpenCL runtime. 2773 2774Each kernel will have function metadata attached to it, specifying the arguments. 2775Kernel argument metadata is used to provide source level information for querying 2776at runtime, for example using the `clGetKernelArgInfo 2777<https://www.khronos.org/registry/OpenCL/specs/opencl-1.2.pdf#167>`_ 2778call. 2779 2780Note that ``-cl-kernel-arg-info`` enables more information about the original CL 2781code to be added e.g. kernel parameter names will appear in the OpenCL metadata 2782along with other information. 2783 2784The IDs used to encode the OpenCL's logical address spaces in the argument info 2785metadata follows the SPIR address space mapping as defined in the SPIR 2786specification `section 2.2 2787<https://www.khronos.org/registry/spir/specs/spir_spec-2.0.pdf#18>`_ 2788 2789OpenCL-Specific Attributes 2790-------------------------- 2791 2792OpenCL support in Clang contains a set of attribute taken directly from the 2793specification as well as additional attributes. 2794 2795See also :doc:`AttributeReference`. 2796 2797nosvm 2798^^^^^ 2799 2800Clang supports this attribute to comply to OpenCL v2.0 conformance, but it 2801does not have any effect on the IR. For more details reffer to the specification 2802`section 6.7.2 2803<https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#49>`_ 2804 2805 2806opencl_unroll_hint 2807^^^^^^^^^^^^^^^^^^ 2808 2809The implementation of this feature mirrors the unroll hint for C. 2810More details on the syntax can be found in the specification 2811`section 6.11.5 2812<https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#61>`_ 2813 2814convergent 2815^^^^^^^^^^ 2816 2817To make sure no invalid optimizations occur for single program multiple data 2818(SPMD) / single instruction multiple thread (SIMT) Clang provides attributes that 2819can be used for special functions that have cross work item semantics. 2820An example is the subgroup operations such as `intel_sub_group_shuffle 2821<https://www.khronos.org/registry/cl/extensions/intel/cl_intel_subgroups.txt>`_ 2822 2823 .. code-block:: c 2824 2825 // Define custom my_sub_group_shuffle(data, c) 2826 // that makes use of intel_sub_group_shuffle 2827 r1 = ... 2828 if (r0) r1 = computeA(); 2829 // Shuffle data from r1 into r3 2830 // of threads id r2. 2831 r3 = my_sub_group_shuffle(r1, r2); 2832 if (r0) r3 = computeB(); 2833 2834with non-SPMD semantics this is optimized to the following equivalent code: 2835 2836 .. code-block:: c 2837 2838 r1 = ... 2839 if (!r0) 2840 // Incorrect functionality! The data in r1 2841 // have not been computed by all threads yet. 2842 r3 = my_sub_group_shuffle(r1, r2); 2843 else { 2844 r1 = computeA(); 2845 r3 = my_sub_group_shuffle(r1, r2); 2846 r3 = computeB(); 2847 } 2848 2849Declaring the function ``my_sub_group_shuffle`` with the convergent attribute 2850would prevent this: 2851 2852 .. code-block:: c 2853 2854 my_sub_group_shuffle() __attribute__((convergent)); 2855 2856Using ``convergent`` guarantees correct execution by keeping CFG equivalence 2857wrt operations marked as ``convergent``. CFG ``G´`` is equivalent to ``G`` wrt 2858node ``Ni`` : ``iff ∀ Nj (i≠j)`` domination and post-domination relations with 2859respect to ``Ni`` remain the same in both ``G`` and ``G´``. 2860 2861noduplicate 2862^^^^^^^^^^^ 2863 2864``noduplicate`` is more restrictive with respect to optimizations than 2865``convergent`` because a convergent function only preserves CFG equivalence. 2866This allows some optimizations to happen as long as the control flow remains 2867unmodified. 2868 2869 .. code-block:: c 2870 2871 for (int i=0; i<4; i++) 2872 my_sub_group_shuffle() 2873 2874can be modified to: 2875 2876 .. code-block:: c 2877 2878 my_sub_group_shuffle(); 2879 my_sub_group_shuffle(); 2880 my_sub_group_shuffle(); 2881 my_sub_group_shuffle(); 2882 2883while using ``noduplicate`` would disallow this. Also ``noduplicate`` doesn't 2884have the same safe semantics of CFG as ``convergent`` and can cause changes in 2885CFG that modify semantics of the original program. 2886 2887``noduplicate`` is kept for backwards compatibility only and it considered to be 2888deprecated for future uses. 2889 2890.. _opencl_addrsp: 2891 2892address_space 2893^^^^^^^^^^^^^ 2894 2895Clang has arbitrary address space support using the ``address_space(N)`` 2896attribute, where ``N`` is an integer number in the range ``0`` to ``16777215`` 2897(``0xffffffu``). 2898 2899An OpenCL implementation provides a list of standard address spaces using 2900keywords: ``private``, ``local``, ``global``, and ``generic``. In the AST and 2901in the IR local, global, or generic will be represented by the address space 2902attribute with the corresponding unique number. Note that private does not have 2903any corresponding attribute added and, therefore, is represented by the absence 2904of an address space number. The specific IDs for an address space do not have to 2905match between the AST and the IR. Typically in the AST address space numbers 2906represent logical segments while in the IR they represent physical segments. 2907Therefore, machines with flat memory segments can map all AST address space 2908numbers to the same physical segment ID or skip address space attribute 2909completely while generating the IR. However, if the address space information 2910is needed by the IR passes e.g. to improve alias analysis, it is recommended 2911to keep it and only lower to reflect physical memory segments in the late 2912machine passes. 2913 2914OpenCL builtins 2915--------------- 2916 2917There are some standard OpenCL functions that are implemented as Clang builtins: 2918 2919- All pipe functions from `section 6.13.16.2/6.13.16.3 2920 <https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#160>`_ of 2921 the OpenCL v2.0 kernel language specification. ` 2922 2923- Address space qualifier conversion functions ``to_global``/``to_local``/``to_private`` 2924 from `section 6.13.9 2925 <https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#101>`_. 2926 2927- All the ``enqueue_kernel`` functions from `section 6.13.17.1 2928 <https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#164>`_ and 2929 enqueue query functions from `section 6.13.17.5 2930 <https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#171>`_. 2931 2932.. _opencl_cpp: 2933 2934C++ for OpenCL 2935-------------- 2936 2937Starting from clang 9 kernel code can contain C++17 features: classes, templates, 2938function overloading, type deduction, etc. Please note that this is not an 2939implementation of `OpenCL C++ 2940<https://www.khronos.org/registry/OpenCL/specs/2.2/pdf/OpenCL_Cxx.pdf>`_ and 2941there is no plan to support it in clang in any new releases in the near future. 2942 2943For detailed information about restrictions to allowed C++ features please 2944refer to :doc:`LanguageExtensions`. 2945 2946Since C++ features are to be used on top of OpenCL C functionality, all existing 2947restrictions from OpenCL C v2.0 will inherently apply. All OpenCL C builtin types 2948and function libraries are supported and can be used in this mode. 2949 2950To enable the C++ for OpenCL mode, pass one of following command line options when 2951compiling ``.cl`` file ``-cl-std=clc++``, ``-cl-std=CLC++``, ``-std=clc++`` or 2952``-std=CLC++``. 2953 2954 .. code-block:: c++ 2955 2956 template<class T> T add( T x, T y ) 2957 { 2958 return x + y; 2959 } 2960 2961 __kernel void test( __global float* a, __global float* b) 2962 { 2963 auto index = get_global_id(0); 2964 a[index] = add(b[index], b[index+1]); 2965 } 2966 2967 2968 .. code-block:: console 2969 2970 clang -cl-std=clc++ test.cl 2971 2972.. _target_features: 2973 2974Target-Specific Features and Limitations 2975======================================== 2976 2977CPU Architectures Features and Limitations 2978------------------------------------------ 2979 2980X86 2981^^^ 2982 2983The support for X86 (both 32-bit and 64-bit) is considered stable on 2984Darwin (macOS), Linux, FreeBSD, and Dragonfly BSD: it has been tested 2985to correctly compile many large C, C++, Objective-C, and Objective-C++ 2986codebases. 2987 2988On ``x86_64-mingw32``, passing i128(by value) is incompatible with the 2989Microsoft x64 calling convention. You might need to tweak 2990``WinX86_64ABIInfo::classify()`` in lib/CodeGen/TargetInfo.cpp. 2991 2992For the X86 target, clang supports the `-m16` command line 2993argument which enables 16-bit code output. This is broadly similar to 2994using ``asm(".code16gcc")`` with the GNU toolchain. The generated code 2995and the ABI remains 32-bit but the assembler emits instructions 2996appropriate for a CPU running in 16-bit mode, with address-size and 2997operand-size prefixes to enable 32-bit addressing and operations. 2998 2999ARM 3000^^^ 3001 3002The support for ARM (specifically ARMv6 and ARMv7) is considered stable 3003on Darwin (iOS): it has been tested to correctly compile many large C, 3004C++, Objective-C, and Objective-C++ codebases. Clang only supports a 3005limited number of ARM architectures. It does not yet fully support 3006ARMv5, for example. 3007 3008PowerPC 3009^^^^^^^ 3010 3011The support for PowerPC (especially PowerPC64) is considered stable 3012on Linux and FreeBSD: it has been tested to correctly compile many 3013large C and C++ codebases. PowerPC (32bit) is still missing certain 3014features (e.g. PIC code on ELF platforms). 3015 3016Other platforms 3017^^^^^^^^^^^^^^^ 3018 3019clang currently contains some support for other architectures (e.g. Sparc); 3020however, significant pieces of code generation are still missing, and they 3021haven't undergone significant testing. 3022 3023clang contains limited support for the MSP430 embedded processor, but 3024both the clang support and the LLVM backend support are highly 3025experimental. 3026 3027Other platforms are completely unsupported at the moment. Adding the 3028minimal support needed for parsing and semantic analysis on a new 3029platform is quite easy; see ``lib/Basic/Targets.cpp`` in the clang source 3030tree. This level of support is also sufficient for conversion to LLVM IR 3031for simple programs. Proper support for conversion to LLVM IR requires 3032adding code to ``lib/CodeGen/CGCall.cpp`` at the moment; this is likely to 3033change soon, though. Generating assembly requires a suitable LLVM 3034backend. 3035 3036Operating System Features and Limitations 3037----------------------------------------- 3038 3039Darwin (macOS) 3040^^^^^^^^^^^^^^ 3041 3042Thread Sanitizer is not supported. 3043 3044Windows 3045^^^^^^^ 3046 3047Clang has experimental support for targeting "Cygming" (Cygwin / MinGW) 3048platforms. 3049 3050See also :ref:`Microsoft Extensions <c_ms>`. 3051 3052Cygwin 3053"""""" 3054 3055Clang works on Cygwin-1.7. 3056 3057MinGW32 3058""""""" 3059 3060Clang works on some mingw32 distributions. Clang assumes directories as 3061below; 3062 3063- ``C:/mingw/include`` 3064- ``C:/mingw/lib`` 3065- ``C:/mingw/lib/gcc/mingw32/4.[3-5].0/include/c++`` 3066 3067On MSYS, a few tests might fail. 3068 3069MinGW-w64 3070""""""""" 3071 3072For 32-bit (i686-w64-mingw32), and 64-bit (x86\_64-w64-mingw32), Clang 3073assumes as below; 3074 3075- ``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)`` 3076- ``some_directory/bin/gcc.exe`` 3077- ``some_directory/bin/clang.exe`` 3078- ``some_directory/bin/clang++.exe`` 3079- ``some_directory/bin/../include/c++/GCC_version`` 3080- ``some_directory/bin/../include/c++/GCC_version/x86_64-w64-mingw32`` 3081- ``some_directory/bin/../include/c++/GCC_version/i686-w64-mingw32`` 3082- ``some_directory/bin/../include/c++/GCC_version/backward`` 3083- ``some_directory/bin/../x86_64-w64-mingw32/include`` 3084- ``some_directory/bin/../i686-w64-mingw32/include`` 3085- ``some_directory/bin/../include`` 3086 3087This directory layout is standard for any toolchain you will find on the 3088official `MinGW-w64 website <http://mingw-w64.sourceforge.net>`_. 3089 3090Clang expects the GCC executable "gcc.exe" compiled for 3091``i686-w64-mingw32`` (or ``x86_64-w64-mingw32``) to be present on PATH. 3092 3093`Some tests might fail <https://bugs.llvm.org/show_bug.cgi?id=9072>`_ on 3094``x86_64-w64-mingw32``. 3095 3096.. _clang-cl: 3097 3098clang-cl 3099======== 3100 3101clang-cl is an alternative command-line interface to Clang, designed for 3102compatibility with the Visual C++ compiler, cl.exe. 3103 3104To enable clang-cl to find system headers, libraries, and the linker when run 3105from the command-line, it should be executed inside a Visual Studio Native Tools 3106Command Prompt or a regular Command Prompt where the environment has been set 3107up using e.g. `vcvarsall.bat <https://msdn.microsoft.com/en-us/library/f2ccy3wt.aspx>`_. 3108 3109clang-cl can also be used from inside Visual Studio by selecting the LLVM 3110Platform Toolset. The toolset is not part of the installer, but may be installed 3111separately from the 3112`Visual Studio Marketplace <https://marketplace.visualstudio.com/items?itemName=LLVMExtensions.llvm-toolchain>`_. 3113To use the toolset, select a project in Solution Explorer, open its Property 3114Page (Alt+F7), and in the "General" section of "Configuration Properties" 3115change "Platform Toolset" to LLVM. Doing so enables an additional Property 3116Page for selecting the clang-cl executable to use for builds. 3117 3118To use the toolset with MSBuild directly, invoke it with e.g. 3119``/p:PlatformToolset=LLVM``. This allows trying out the clang-cl toolchain 3120without modifying your project files. 3121 3122It's also possible to point MSBuild at clang-cl without changing toolset by 3123passing ``/p:CLToolPath=c:\llvm\bin /p:CLToolExe=clang-cl.exe``. 3124 3125When using CMake and the Visual Studio generators, the toolset can be set with the ``-T`` flag: 3126 3127 :: 3128 3129 cmake -G"Visual Studio 15 2017" -T LLVM .. 3130 3131When using CMake with the Ninja generator, set the ``CMAKE_C_COMPILER`` and 3132``CMAKE_CXX_COMPILER`` variables to clang-cl: 3133 3134 :: 3135 3136 cmake -GNinja -DCMAKE_C_COMPILER="c:/Program Files (x86)/LLVM/bin/clang-cl.exe" 3137 -DCMAKE_CXX_COMPILER="c:/Program Files (x86)/LLVM/bin/clang-cl.exe" .. 3138 3139 3140Command-Line Options 3141-------------------- 3142 3143To be compatible with cl.exe, clang-cl supports most of the same command-line 3144options. Those options can start with either ``/`` or ``-``. It also supports 3145some of Clang's core options, such as the ``-W`` options. 3146 3147Options that are known to clang-cl, but not currently supported, are ignored 3148with a warning. For example: 3149 3150 :: 3151 3152 clang-cl.exe: warning: argument unused during compilation: '/AI' 3153 3154To suppress warnings about unused arguments, use the ``-Qunused-arguments`` option. 3155 3156Options that are not known to clang-cl will be ignored by default. Use the 3157``-Werror=unknown-argument`` option in order to treat them as errors. If these 3158options are spelled with a leading ``/``, they will be mistaken for a filename: 3159 3160 :: 3161 3162 clang-cl.exe: error: no such file or directory: '/foobar' 3163 3164Please `file a bug <https://bugs.llvm.org/enter_bug.cgi?product=clang&component=Driver>`_ 3165for any valid cl.exe flags that clang-cl does not understand. 3166 3167Execute ``clang-cl /?`` to see a list of supported options: 3168 3169 :: 3170 3171 CL.EXE COMPATIBILITY OPTIONS: 3172 /? Display available options 3173 /arch:<value> Set architecture for code generation 3174 /Brepro- Emit an object file which cannot be reproduced over time 3175 /Brepro Emit an object file which can be reproduced over time 3176 /clang:<arg> Pass <arg> to the clang driver 3177 /C Don't discard comments when preprocessing 3178 /c Compile only 3179 /d1PP Retain macro definitions in /E mode 3180 /d1reportAllClassLayout Dump record layout information 3181 /diagnostics:caret Enable caret and column diagnostics (on by default) 3182 /diagnostics:classic Disable column and caret diagnostics 3183 /diagnostics:column Disable caret diagnostics but keep column info 3184 /D <macro[=value]> Define macro 3185 /EH<value> Exception handling model 3186 /EP Disable linemarker output and preprocess to stdout 3187 /execution-charset:<value> 3188 Runtime encoding, supports only UTF-8 3189 /E Preprocess to stdout 3190 /fallback Fall back to cl.exe if clang-cl fails to compile 3191 /FA Output assembly code file during compilation 3192 /Fa<file or directory> Output assembly code to this file during compilation (with /FA) 3193 /Fe<file or directory> Set output executable file or directory (ends in / or \) 3194 /FI <value> Include file before parsing 3195 /Fi<file> Set preprocess output file name (with /P) 3196 /Fo<file or directory> Set output object file, or directory (ends in / or \) (with /c) 3197 /fp:except- 3198 /fp:except 3199 /fp:fast 3200 /fp:precise 3201 /fp:strict 3202 /Fp<filename> Set pch filename (with /Yc and /Yu) 3203 /GA Assume thread-local variables are defined in the executable 3204 /Gd Set __cdecl as a default calling convention 3205 /GF- Disable string pooling 3206 /GF Enable string pooling (default) 3207 /GR- Disable emission of RTTI data 3208 /Gregcall Set __regcall as a default calling convention 3209 /GR Enable emission of RTTI data 3210 /Gr Set __fastcall as a default calling convention 3211 /GS- Disable buffer security check 3212 /GS Enable buffer security check (default) 3213 /Gs Use stack probes (default) 3214 /Gs<value> Set stack probe size (default 4096) 3215 /guard:<value> Enable Control Flow Guard with /guard:cf, 3216 or only the table with /guard:cf,nochecks 3217 /Gv Set __vectorcall as a default calling convention 3218 /Gw- Don't put each data item in its own section 3219 /Gw Put each data item in its own section 3220 /GX- Disable exception handling 3221 /GX Enable exception handling 3222 /Gy- Don't put each function in its own section (default) 3223 /Gy Put each function in its own section 3224 /Gz Set __stdcall as a default calling convention 3225 /help Display available options 3226 /imsvc <dir> Add directory to system include search path, as if part of %INCLUDE% 3227 /I <dir> Add directory to include search path 3228 /J Make char type unsigned 3229 /LDd Create debug DLL 3230 /LD Create DLL 3231 /link <options> Forward options to the linker 3232 /MDd Use DLL debug run-time 3233 /MD Use DLL run-time 3234 /MTd Use static debug run-time 3235 /MT Use static run-time 3236 /O0 Disable optimization 3237 /O1 Optimize for size (same as /Og /Os /Oy /Ob2 /GF /Gy) 3238 /O2 Optimize for speed (same as /Og /Oi /Ot /Oy /Ob2 /GF /Gy) 3239 /Ob0 Disable function inlining 3240 /Ob1 Only inline functions which are (explicitly or implicitly) marked inline 3241 /Ob2 Inline functions as deemed beneficial by the compiler 3242 /Od Disable optimization 3243 /Og No effect 3244 /Oi- Disable use of builtin functions 3245 /Oi Enable use of builtin functions 3246 /Os Optimize for size 3247 /Ot Optimize for speed 3248 /Ox Deprecated (same as /Og /Oi /Ot /Oy /Ob2); use /O2 instead 3249 /Oy- Disable frame pointer omission (x86 only, default) 3250 /Oy Enable frame pointer omission (x86 only) 3251 /O<flags> Set multiple /O flags at once; e.g. '/O2y-' for '/O2 /Oy-' 3252 /o <file or directory> Set output file or directory (ends in / or \) 3253 /P Preprocess to file 3254 /Qvec- Disable the loop vectorization passes 3255 /Qvec Enable the loop vectorization passes 3256 /showFilenames- Don't print the name of each compiled file (default) 3257 /showFilenames Print the name of each compiled file 3258 /showIncludes Print info about included files to stderr 3259 /source-charset:<value> Source encoding, supports only UTF-8 3260 /std:<value> Language standard to compile for 3261 /TC Treat all source files as C 3262 /Tc <filename> Specify a C source file 3263 /TP Treat all source files as C++ 3264 /Tp <filename> Specify a C++ source file 3265 /utf-8 Set source and runtime encoding to UTF-8 (default) 3266 /U <macro> Undefine macro 3267 /vd<value> Control vtordisp placement 3268 /vmb Use a best-case representation method for member pointers 3269 /vmg Use a most-general representation for member pointers 3270 /vmm Set the default most-general representation to multiple inheritance 3271 /vms Set the default most-general representation to single inheritance 3272 /vmv Set the default most-general representation to virtual inheritance 3273 /volatile:iso Volatile loads and stores have standard semantics 3274 /volatile:ms Volatile loads and stores have acquire and release semantics 3275 /W0 Disable all warnings 3276 /W1 Enable -Wall 3277 /W2 Enable -Wall 3278 /W3 Enable -Wall 3279 /W4 Enable -Wall and -Wextra 3280 /Wall Enable -Weverything 3281 /WX- Do not treat warnings as errors 3282 /WX Treat warnings as errors 3283 /w Disable all warnings 3284 /X Don't add %INCLUDE% to the include search path 3285 /Y- Disable precompiled headers, overrides /Yc and /Yu 3286 /Yc<filename> Generate a pch file for all code up to and including <filename> 3287 /Yu<filename> Load a pch file and use it instead of all code up to and including <filename> 3288 /Z7 Enable CodeView debug information in object files 3289 /Zc:char8_t Enable C++2a char8_t type 3290 /Zc:char8_t- Disable C++2a char8_t type 3291 /Zc:dllexportInlines- Don't dllexport/dllimport inline member functions of dllexport/import classes 3292 /Zc:dllexportInlines dllexport/dllimport inline member functions of dllexport/import classes (default) 3293 /Zc:sizedDealloc- Disable C++14 sized global deallocation functions 3294 /Zc:sizedDealloc Enable C++14 sized global deallocation functions 3295 /Zc:strictStrings Treat string literals as const 3296 /Zc:threadSafeInit- Disable thread-safe initialization of static variables 3297 /Zc:threadSafeInit Enable thread-safe initialization of static variables 3298 /Zc:trigraphs- Disable trigraphs (default) 3299 /Zc:trigraphs Enable trigraphs 3300 /Zc:twoPhase- Disable two-phase name lookup in templates 3301 /Zc:twoPhase Enable two-phase name lookup in templates 3302 /Zd Emit debug line number tables only 3303 /Zi Alias for /Z7. Does not produce PDBs. 3304 /Zl Don't mention any default libraries in the object file 3305 /Zp Set the default maximum struct packing alignment to 1 3306 /Zp<value> Specify the default maximum struct packing alignment 3307 /Zs Syntax-check only 3308 3309 OPTIONS: 3310 -### Print (but do not run) the commands to run for this compilation 3311 --analyze Run the static analyzer 3312 -faddrsig Emit an address-significance table 3313 -fansi-escape-codes Use ANSI escape codes for diagnostics 3314 -fblocks Enable the 'blocks' language feature 3315 -fcf-protection=<value> Instrument control-flow architecture protection. Options: return, branch, full, none. 3316 -fcf-protection Enable cf-protection in 'full' mode 3317 -fcolor-diagnostics Use colors in diagnostics 3318 -fcomplete-member-pointers 3319 Require member pointer base types to be complete if they would be significant under the Microsoft ABI 3320 -fcoverage-mapping Generate coverage mapping to enable code coverage analysis 3321 -fdebug-macro Emit macro debug information 3322 -fdelayed-template-parsing 3323 Parse templated function definitions at the end of the translation unit 3324 -fdiagnostics-absolute-paths 3325 Print absolute paths in diagnostics 3326 -fdiagnostics-parseable-fixits 3327 Print fix-its in machine parseable form 3328 -flto=<value> Set LTO mode to either 'full' or 'thin' 3329 -flto Enable LTO in 'full' mode 3330 -fmerge-all-constants Allow merging of constants 3331 -fms-compatibility-version=<value> 3332 Dot-separated value representing the Microsoft compiler version 3333 number to report in _MSC_VER (0 = don't define it (default)) 3334 -fms-compatibility Enable full Microsoft Visual C++ compatibility 3335 -fms-extensions Accept some non-standard constructs supported by the Microsoft compiler 3336 -fmsc-version=<value> Microsoft compiler version number to report in _MSC_VER 3337 (0 = don't define it (default)) 3338 -fno-addrsig Don't emit an address-significance table 3339 -fno-builtin-<value> Disable implicit builtin knowledge of a specific function 3340 -fno-builtin Disable implicit builtin knowledge of functions 3341 -fno-complete-member-pointers 3342 Do not require member pointer base types to be complete if they would be significant under the Microsoft ABI 3343 -fno-coverage-mapping Disable code coverage analysis 3344 -fno-crash-diagnostics Disable auto-generation of preprocessed source files and a script for reproduction during a clang crash 3345 -fno-debug-macro Do not emit macro debug information 3346 -fno-delayed-template-parsing 3347 Disable delayed template parsing 3348 -fno-sanitize-address-poison-custom-array-cookie 3349 Disable poisoning array cookies when using custom operator new[] in AddressSanitizer 3350 -fno-sanitize-address-use-after-scope 3351 Disable use-after-scope detection in AddressSanitizer 3352 -fno-sanitize-address-use-odr-indicator 3353 Disable ODR indicator globals 3354 -fno-sanitize-blacklist Don't use blacklist file for sanitizers 3355 -fno-sanitize-cfi-cross-dso 3356 Disable control flow integrity (CFI) checks for cross-DSO calls. 3357 -fno-sanitize-coverage=<value> 3358 Disable specified features of coverage instrumentation for Sanitizers 3359 -fno-sanitize-memory-track-origins 3360 Disable origins tracking in MemorySanitizer 3361 -fno-sanitize-memory-use-after-dtor 3362 Disable use-after-destroy detection in MemorySanitizer 3363 -fno-sanitize-recover=<value> 3364 Disable recovery for specified sanitizers 3365 -fno-sanitize-stats Disable sanitizer statistics gathering. 3366 -fno-sanitize-thread-atomics 3367 Disable atomic operations instrumentation in ThreadSanitizer 3368 -fno-sanitize-thread-func-entry-exit 3369 Disable function entry/exit instrumentation in ThreadSanitizer 3370 -fno-sanitize-thread-memory-access 3371 Disable memory access instrumentation in ThreadSanitizer 3372 -fno-sanitize-trap=<value> 3373 Disable trapping for specified sanitizers 3374 -fno-standalone-debug Limit debug information produced to reduce size of debug binary 3375 -fobjc-runtime=<value> Specify the target Objective-C runtime kind and version 3376 -fprofile-exclude-files=<value> 3377 Instrument only functions from files where names don't match all the regexes separated by a semi-colon 3378 -fprofile-filter-files=<value> 3379 Instrument only functions from files where names match any regex separated by a semi-colon 3380 -fprofile-instr-generate=<file> 3381 Generate instrumented code to collect execution counts into <file> 3382 (overridden by LLVM_PROFILE_FILE env var) 3383 -fprofile-instr-generate 3384 Generate instrumented code to collect execution counts into default.profraw file 3385 (overridden by '=' form of option or LLVM_PROFILE_FILE env var) 3386 -fprofile-instr-use=<value> 3387 Use instrumentation data for profile-guided optimization 3388 -fprofile-remapping-file=<file> 3389 Use the remappings described in <file> to match the profile data against names in the program 3390 -fsanitize-address-field-padding=<value> 3391 Level of field padding for AddressSanitizer 3392 -fsanitize-address-globals-dead-stripping 3393 Enable linker dead stripping of globals in AddressSanitizer 3394 -fsanitize-address-poison-custom-array-cookie 3395 Enable poisoning array cookies when using custom operator new[] in AddressSanitizer 3396 -fsanitize-address-use-after-scope 3397 Enable use-after-scope detection in AddressSanitizer 3398 -fsanitize-address-use-odr-indicator 3399 Enable ODR indicator globals to avoid false ODR violation reports in partially sanitized programs at the cost of an increase in binary size 3400 -fsanitize-blacklist=<value> 3401 Path to blacklist file for sanitizers 3402 -fsanitize-cfi-cross-dso 3403 Enable control flow integrity (CFI) checks for cross-DSO calls. 3404 -fsanitize-cfi-icall-generalize-pointers 3405 Generalize pointers in CFI indirect call type signature checks 3406 -fsanitize-coverage=<value> 3407 Specify the type of coverage instrumentation for Sanitizers 3408 -fsanitize-hwaddress-abi=<value> 3409 Select the HWAddressSanitizer ABI to target (interceptor or platform, default interceptor) 3410 -fsanitize-memory-track-origins=<value> 3411 Enable origins tracking in MemorySanitizer 3412 -fsanitize-memory-track-origins 3413 Enable origins tracking in MemorySanitizer 3414 -fsanitize-memory-use-after-dtor 3415 Enable use-after-destroy detection in MemorySanitizer 3416 -fsanitize-recover=<value> 3417 Enable recovery for specified sanitizers 3418 -fsanitize-stats Enable sanitizer statistics gathering. 3419 -fsanitize-thread-atomics 3420 Enable atomic operations instrumentation in ThreadSanitizer (default) 3421 -fsanitize-thread-func-entry-exit 3422 Enable function entry/exit instrumentation in ThreadSanitizer (default) 3423 -fsanitize-thread-memory-access 3424 Enable memory access instrumentation in ThreadSanitizer (default) 3425 -fsanitize-trap=<value> Enable trapping for specified sanitizers 3426 -fsanitize-undefined-strip-path-components=<number> 3427 Strip (or keep only, if negative) a given number of path components when emitting check metadata. 3428 -fsanitize=<check> Turn on runtime checks for various forms of undefined or suspicious 3429 behavior. See user manual for available checks 3430 -fsplit-lto-unit Enables splitting of the LTO unit. 3431 -fstandalone-debug Emit full debug info for all types used by the program 3432 -fwhole-program-vtables Enables whole-program vtable optimization. Requires -flto 3433 -gcodeview-ghash Emit type record hashes in a .debug$H section 3434 -gcodeview Generate CodeView debug information 3435 -gline-directives-only Emit debug line info directives only 3436 -gline-tables-only Emit debug line number tables only 3437 -miamcu Use Intel MCU ABI 3438 -mllvm <value> Additional arguments to forward to LLVM's option processing 3439 -nobuiltininc Disable builtin #include directories 3440 -Qunused-arguments Don't emit warning for unused driver arguments 3441 -R<remark> Enable the specified remark 3442 --target=<value> Generate code for the given target 3443 --version Print version information 3444 -v Show commands to run and use verbose output 3445 -W<warning> Enable the specified warning 3446 -Xclang <arg> Pass <arg> to the clang compiler 3447 3448The /clang: Option 3449^^^^^^^^^^^^^^^^^^ 3450 3451When clang-cl is run with a set of ``/clang:<arg>`` options, it will gather all 3452of the ``<arg>`` arguments and process them as if they were passed to the clang 3453driver. This mechanism allows you to pass flags that are not exposed in the 3454clang-cl options or flags that have a different meaning when passed to the clang 3455driver. Regardless of where they appear in the command line, the ``/clang:`` 3456arguments are treated as if they were passed at the end of the clang-cl command 3457line. 3458 3459The /Zc:dllexportInlines- Option 3460^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 3461 3462This causes the class-level `dllexport` and `dllimport` attributes to not apply 3463to inline member functions, as they otherwise would. For example, in the code 3464below `S::foo()` would normally be defined and exported by the DLL, but when 3465using the ``/Zc:dllexportInlines-`` flag it is not: 3466 3467.. code-block:: c 3468 3469 struct __declspec(dllexport) S { 3470 void foo() {} 3471 } 3472 3473This has the benefit that the compiler doesn't need to emit a definition of 3474`S::foo()` in every translation unit where the declaration is included, as it 3475would otherwise do to ensure there's a definition in the DLL even if it's not 3476used there. If the declaration occurs in a header file that's widely used, this 3477can save significant compilation time and output size. It also reduces the 3478number of functions exported by the DLL similarly to what 3479``-fvisibility-inlines-hidden`` does for shared objects on ELF and Mach-O. 3480Since the function declaration comes with an inline definition, users of the 3481library can use that definition directly instead of importing it from the DLL. 3482 3483Note that the Microsoft Visual C++ compiler does not support this option, and 3484if code in a DLL is compiled with ``/Zc:dllexportInlines-``, the code using the 3485DLL must be compiled in the same way so that it doesn't attempt to dllimport 3486the inline member functions. The reverse scenario should generally work though: 3487a DLL compiled without this flag (such as a system library compiled with Visual 3488C++) can be referenced from code compiled using the flag, meaning that the 3489referencing code will use the inline definitions instead of importing them from 3490the DLL. 3491 3492Also note that like when using ``-fvisibility-inlines-hidden``, the address of 3493`S::foo()` will be different inside and outside the DLL, breaking the C/C++ 3494standard requirement that functions have a unique address. 3495 3496The flag does not apply to explicit class template instantiation definitions or 3497declarations, as those are typically used to explicitly provide a single 3498definition in a DLL, (dllexported instantiation definition) or to signal that 3499the definition is available elsewhere (dllimport instantiation declaration). It 3500also doesn't apply to inline members with static local variables, to ensure 3501that the same instance of the variable is used inside and outside the DLL. 3502 3503Using this flag can cause problems when inline functions that would otherwise 3504be dllexported refer to internal symbols of a DLL. For example: 3505 3506.. code-block:: c 3507 3508 void internal(); 3509 3510 struct __declspec(dllimport) S { 3511 void foo() { internal(); } 3512 } 3513 3514Normally, references to `S::foo()` would use the definition in the DLL from 3515which it was exported, and which presumably also has the definition of 3516`internal()`. However, when using ``/Zc:dllexportInlines-``, the inline 3517definition of `S::foo()` is used directly, resulting in a link error since 3518`internal()` is not available. Even worse, if there is an inline definition of 3519`internal()` containing a static local variable, we will now refer to a 3520different instance of that variable than in the DLL: 3521 3522.. code-block:: c 3523 3524 inline int internal() { static int x; return x++; } 3525 3526 struct __declspec(dllimport) S { 3527 int foo() { return internal(); } 3528 } 3529 3530This could lead to very subtle bugs. Using ``-fvisibility-inlines-hidden`` can 3531lead to the same issue. To avoid it in this case, make `S::foo()` or 3532`internal()` non-inline, or mark them `dllimport/dllexport` explicitly. 3533 3534The /fallback Option 3535^^^^^^^^^^^^^^^^^^^^ 3536 3537When clang-cl is run with the ``/fallback`` option, it will first try to 3538compile files itself. For any file that it fails to compile, it will fall back 3539and try to compile the file by invoking cl.exe. 3540 3541This option is intended to be used as a temporary means to build projects where 3542clang-cl cannot successfully compile all the files. clang-cl may fail to compile 3543a file either because it cannot generate code for some C++ feature, or because 3544it cannot parse some Microsoft language extension. 3545