Debian Codegraph @

clang/docs/UsersManual.rst

raw
1 ============================
2 Clang Compiler User's Manual
3 ============================
4
5 .. include:: <isonum.txt>
6
7 .. contents::
8 :local:
9
10 Introduction
11 ============
12
13 The Clang Compiler is an open-source compiler for the C family of
14 programming languages, aiming to be the best in class implementation of
15 these languages. Clang builds on the LLVM optimizer and code generator,
16 allowing it to provide high-quality optimization and code generation
17 support for many targets. For more general information, please see the
18 `Clang Web Site <https://clang.llvm.org>`_ or the `LLVM Web
19 Site <https://llvm.org>`_.
20
21 This document describes important notes about using Clang as a compiler
22 for an end-user, documenting the supported features, command line
23 options, etc. If you are interested in using Clang to build a tool that
24 processes code, please see :doc:`InternalsManual`. If you are interested in the
25 `Clang Static Analyzer <https://clang-analyzer.llvm.org>`_, please see its web
26 page.
27
28 Clang is one component in a complete toolchain for C family languages.
29 A separate document describes the other pieces necessary to
30 :doc:`assemble a complete toolchain <Toolchain>`.
31
32 Clang is designed to support the C family of programming languages,
33 which includes :ref:`C <c>`, :ref:`Objective-C <objc>`, :ref:`C++ <cxx>`, and
34 :ref:`Objective-C++ <objcxx>` as well as many dialects of those. For
35 language-specific information, please see the corresponding language
36 specific 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 Kernel Language <opencl>`: OpenCL C 1.0, 1.1, 1.2, 2.0, 3.0,
45 and C++ for OpenCL 1.0 and 2021.
46
47 In addition to these base languages and their dialects, Clang supports a
48 broad variety of language extensions, which are documented in the
49 corresponding language section. These extensions are provided to be
50 compatible with the GCC, Microsoft, and other popular compilers as well
51 as to improve functionality through Clang-specific features. The Clang
52 driver and language features are intentionally designed to be as
53 compatible with the GNU GCC compiler as reasonably possible, easing
54 migration from GCC to Clang. In most cases, code "just works".
55 Clang also provides an alternative driver, :ref:`clang-cl`, that is designed
56 to be compatible with the Visual C++ compiler, cl.exe.
57
58 In addition to language specific features, Clang has a variety of
59 features that depend on what CPU architecture or operating system is
60 being compiled for. Please see the :ref:`Target-Specific Features and
61 Limitations <target_features>` section for more details.
62
63 The rest of the introduction introduces some basic :ref:`compiler
64 terminology <terminology>` that is used throughout this manual and
65 contains a basic :ref:`introduction to using Clang <basicusage>` as a
66 command line compiler.
67
68 .. _terminology:
69
70 Terminology
71 -----------
72
73 Front end, parser, backend, preprocessor, undefined behavior,
74 diagnostic, optimizer
75
76 .. _basicusage:
77
78 Basic Usage
79 -----------
80
81 Intro to how to use a C compiler for newbies.
82
83 compile + link compile then link debug info enabling optimizations
84 picking a language to use, defaults to C17 by default. Autosenses based
85 on extension. using a makefile
86
87 Command Line Options
88 ====================
89
90 This section is generally an index into other sections. It does not go
91 into depth on the ones that are covered by other sections. However, the
92 first part introduces the language selection and other high level
93 options like :option:`-c`, :option:`-g`, etc.
94
95 Options to Control Error and Warning Messages
96 ---------------------------------------------
97
98 .. option:: -Werror
99
100 Turn warnings into errors.
101
102 .. This is in plain monospaced font because it generates the same label as
103 .. -Werror, and Sphinx complains.
104
105 ``-Werror=foo``
106
107 Turn warning "foo" into an error.
108
109 .. option:: -Wno-error=foo
110
111 Turn warning "foo" into a warning even if :option:`-Werror` is specified.
112
113 .. option:: -Wfoo
114
115 Enable warning "foo".
116 See the :doc:`diagnostics reference <DiagnosticsReference>` for a complete
117 list of the warning flags that can be specified in this way.
118
119 .. option:: -Wno-foo
120
121 Disable warning "foo".
122
123 .. option:: -w
124
125 Disable all diagnostics.
126
127 .. option:: -Weverything
128
129 :ref:`Enable all diagnostics. <diagnostics_enable_everything>`
130
131 .. option:: -pedantic
132
133 Warn on language extensions.
134
135 .. option:: -pedantic-errors
136
137 Error on language extensions.
138
139 .. option:: -Wsystem-headers
140
141 Enable warnings from system headers.
142
143 .. option:: -ferror-limit=123
144
145 Stop emitting diagnostics after 123 errors have been produced. The default is
146 20, and the error limit can be disabled with `-ferror-limit=0`.
147
148 .. option:: -ftemplate-backtrace-limit=123
149
150 Only emit up to 123 template instantiation notes within the template
151 instantiation backtrace for a single warning or error. The default is 10, and
152 the limit can be disabled with `-ftemplate-backtrace-limit=0`.
153
154 .. _cl_diag_formatting:
155
156 Formatting of Diagnostics
157 ^^^^^^^^^^^^^^^^^^^^^^^^^
158
159 Clang aims to produce beautiful diagnostics by default, particularly for
160 new users that first come to Clang. However, different people have
161 different preferences, and sometimes Clang is driven not by a human,
162 but by a program that wants consistent and easily parsable output. For
163 these cases, Clang provides a wide range of options to control the exact
164 output format of the diagnostics that it generates.
165
166 .. _opt_fshow-column:
167
168 .. option:: -f[no-]show-column
169
170 Print column number in diagnostic.
171
172 This option, which defaults to on, controls whether or not Clang
173 prints the column number of a diagnostic. For example, when this is
174 enabled, Clang will print something like:
175
176 ::
177
178 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
179 #endif bad
180 ^
181 //
182
183 When this is disabled, Clang will print "test.c:28: warning..." with
184 no column number.
185
186 The printed column numbers count bytes from the beginning of the
187 line; take care if your source contains multibyte characters.
188
189 .. _opt_fshow-source-location:
190
191 .. option:: -f[no-]show-source-location
192
193 Print source file/line/column information in diagnostic.
194
195 This option, which defaults to on, controls whether or not Clang
196 prints the filename, line number and column number of a diagnostic.
197 For example, when this is enabled, Clang will print something like:
198
199 ::
200
201 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
202 #endif bad
203 ^
204 //
205
206 When this is disabled, Clang will not print the "test.c:28:8: "
207 part.
208
209 .. _opt_fcaret-diagnostics:
210
211 .. option:: -f[no-]caret-diagnostics
212
213 Print source line and ranges from source code in diagnostic.
214 This option, which defaults to on, controls whether or not Clang
215 prints the source line, source ranges, and caret when emitting a
216 diagnostic. For example, when this is enabled, Clang will print
217 something like:
218
219 ::
220
221 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
222 #endif bad
223 ^
224 //
225
226 .. option:: -f[no-]color-diagnostics
227
228 This option, which defaults to on when a color-capable terminal is
229 detected, controls whether or not Clang prints diagnostics in color.
230
231 When this option is enabled, Clang will use colors to highlight
232 specific parts of the diagnostic, e.g.,
233
234 .. nasty hack to not lose our dignity
235
236 .. raw:: html
237
238 <pre>
239 <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>
240 #endif bad
241 <span style="color:green">^</span>
242 <span style="color:green">//</span>
243 </pre>
244
245 When this is disabled, Clang will just print:
246
247 ::
248
249 test.c:2:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
250 #endif bad
251 ^
252 //
253
254 If the ``NO_COLOR`` environment variable is defined and not empty
255 (regardless of value), color diagnostics are disabled. If ``NO_COLOR`` is
256 defined and ``-fcolor-diagnostics`` is passed on the command line, Clang
257 will honor the command line argument.
258
259 .. option:: -fansi-escape-codes
260
261 Controls whether ANSI escape codes are used instead of the Windows Console
262 API to output colored diagnostics. This option is only used on Windows and
263 defaults to off.
264
265 .. option:: -fdiagnostics-format=clang/msvc/vi
266
267 Changes diagnostic output format to better match IDEs and command line tools.
268
269 This option controls the output format of the filename, line number,
270 and column printed in diagnostic messages. The options, and their
271 affect on formatting a simple conversion diagnostic, follow:
272
273 **clang** (default)
274 ::
275
276 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int'
277
278 **msvc**
279 ::
280
281 t.c(3,11) : warning: conversion specifies type 'char *' but the argument has type 'int'
282
283 **vi**
284 ::
285
286 t.c +3:11: warning: conversion specifies type 'char *' but the argument has type 'int'
287
288 .. _opt_fdiagnostics-show-option:
289
290 .. option:: -f[no-]diagnostics-show-option
291
292 Enable ``[-Woption]`` information in diagnostic line.
293
294 This option, which defaults to on, controls whether or not Clang
295 prints the associated :ref:`warning group <cl_diag_warning_groups>`
296 option name when outputting a warning diagnostic. For example, in
297 this output:
298
299 ::
300
301 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
302 #endif bad
303 ^
304 //
305
306 Passing **-fno-diagnostics-show-option** will prevent Clang from
307 printing the [:option:`-Wextra-tokens`] information in
308 the diagnostic. This information tells you the flag needed to enable
309 or disable the diagnostic, either from the command line or through
310 :ref:`#pragma GCC diagnostic <pragma_GCC_diagnostic>`.
311
312 .. option:: -fdiagnostics-show-category=none/id/name
313
314 Enable printing category information in diagnostic line.
315
316 This option, which defaults to "none", controls whether or not Clang
317 prints the category associated with a diagnostic when emitting it.
318 Each diagnostic may or many not have an associated category, if it
319 has one, it is listed in the diagnostic categorization field of the
320 diagnostic line (in the []'s).
321
322 For example, a format string warning will produce these three
323 renditions based on the setting of this option:
324
325 ::
326
327 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat]
328 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat,1]
329 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat,Format String]
330
331 This category can be used by clients that want to group diagnostics
332 by category, so it should be a high level category. We want dozens
333 of these, not hundreds or thousands of them.
334
335 .. _opt_fsave-optimization-record:
336
337 .. option:: -f[no-]save-optimization-record[=<format>]
338
339 Enable optimization remarks during compilation and write them to a separate
340 file.
341
342 This option, which defaults to off, controls whether Clang writes
343 optimization reports to a separate file. By recording diagnostics in a file,
344 users can parse or sort the remarks in a convenient way.
345
346 By default, the serialization format is YAML.
347
348 The supported serialization formats are:
349
350 - .. _opt_fsave_optimization_record_yaml:
351
352 ``-fsave-optimization-record=yaml``: A structured YAML format.
353
354 - .. _opt_fsave_optimization_record_bitstream:
355
356 ``-fsave-optimization-record=bitstream``: A binary format based on LLVM
357 Bitstream.
358
359 The output file is controlled by :option:`-foptimization-record-file`.
360
361 In the absence of an explicit output file, the file is chosen using the
362 following scheme:
363
364 ``<base>.opt.<format>``
365
366 where ``<base>`` is based on the output file of the compilation (whether
367 it's explicitly specified through `-o` or not) when used with `-c` or `-S`.
368 For example:
369
370 * ``clang -fsave-optimization-record -c in.c -o out.o`` will generate
371 ``out.opt.yaml``
372
373 * ``clang -fsave-optimization-record -c in.c`` will generate
374 ``in.opt.yaml``
375
376 When targeting (Thin)LTO, the base is derived from the output filename, and
377 the extension is not dropped.
378
379 When targeting ThinLTO, the following scheme is used:
380
381 ``<base>.opt.<format>.thin.<num>.<format>``
382
383 Darwin-only: when used for generating a linked binary from a source file
384 (through an intermediate object file), the driver will invoke `cc1` to
385 generate a temporary object file. The temporary remark file will be emitted
386 next to the object file, which will then be picked up by `dsymutil` and
387 emitted in the .dSYM bundle. This is available for all formats except YAML.
388
389 For example:
390
391 ``clang -fsave-optimization-record=bitstream in.c -o out`` will generate
392
393 * ``/var/folders/43/9y164hh52tv_2nrdxrj31nyw0000gn/T/a-9be59b.o``
394
395 * ``/var/folders/43/9y164hh52tv_2nrdxrj31nyw0000gn/T/a-9be59b.opt.bitstream``
396
397 * ``out``
398
399 * ``out.dSYM/Contents/Resources/Remarks/out``
400
401 Darwin-only: compiling for multiple architectures will use the following
402 scheme:
403
404 ``<base>-<arch>.opt.<format>``
405
406 Note that this is incompatible with passing the
407 :option:`-foptimization-record-file` option.
408
409 .. option:: -foptimization-record-file
410
411 Control the file to which optimization reports are written. This implies
412 :ref:`-fsave-optimization-record <opt_fsave-optimization-record>`.
413
414 On Darwin platforms, this is incompatible with passing multiple
415 ``-arch <arch>`` options.
416
417 .. option:: -foptimization-record-passes
418
419 Only include passes which match a specified regular expression.
420
421 When optimization reports are being output (see
422 :ref:`-fsave-optimization-record <opt_fsave-optimization-record>`), this
423 option controls the passes that will be included in the final report.
424
425 If this option is not used, all the passes are included in the optimization
426 record.
427
428 .. _opt_fdiagnostics-show-hotness:
429
430 .. option:: -f[no-]diagnostics-show-hotness
431
432 Enable profile hotness information in diagnostic line.
433
434 This option controls whether Clang prints the profile hotness associated
435 with diagnostics in the presence of profile-guided optimization information.
436 This is currently supported with optimization remarks (see
437 :ref:`Options to Emit Optimization Reports <rpass>`). The hotness information
438 allows users to focus on the hot optimization remarks that are likely to be
439 more relevant for run-time performance.
440
441 For example, in this output, the block containing the callsite of `foo` was
442 executed 3000 times according to the profile data:
443
444 ::
445
446 s.c:7:10: remark: foo inlined into bar (hotness: 3000) [-Rpass-analysis=inline]
447 sum += foo(x, x - 2);
448 ^
449
450 This option is implied when
451 :ref:`-fsave-optimization-record <opt_fsave-optimization-record>` is used.
452 Otherwise, it defaults to off.
453
454 .. option:: -fdiagnostics-hotness-threshold
455
456 Prevent optimization remarks from being output if they do not have at least
457 this hotness value.
458
459 This option, which defaults to zero, controls the minimum hotness an
460 optimization remark would need in order to be output by Clang. This is
461 currently supported with optimization remarks (see :ref:`Options to Emit
462 Optimization Reports <rpass>`) when profile hotness information in
463 diagnostics is enabled (see
464 :ref:`-fdiagnostics-show-hotness <opt_fdiagnostics-show-hotness>`).
465
466 .. _opt_fdiagnostics-fixit-info:
467
468 .. option:: -f[no-]diagnostics-fixit-info
469
470 Enable "FixIt" information in the diagnostics output.
471
472 This option, which defaults to on, controls whether or not Clang
473 prints the information on how to fix a specific diagnostic
474 underneath it when it knows. For example, in this output:
475
476 ::
477
478 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
479 #endif bad
480 ^
481 //
482
483 Passing **-fno-diagnostics-fixit-info** will prevent Clang from
484 printing the "//" line at the end of the message. This information
485 is useful for users who may not understand what is wrong, but can be
486 confusing for machine parsing.
487
488 .. _opt_fdiagnostics-print-source-range-info:
489
490 .. option:: -fdiagnostics-print-source-range-info
491
492 Print machine parsable information about source ranges.
493 This option makes Clang print information about source ranges in a machine
494 parsable format after the file/line/column number information. The
495 information is a simple sequence of brace enclosed ranges, where each range
496 lists the start and end line/column locations. For example, in this output:
497
498 ::
499
500 exprs.c:47:15:{47:8-47:14}{47:17-47:24}: error: invalid operands to binary expression ('int *' and '_Complex float')
501 P = (P-42) + Gamma*4;
502 ~~~~~~ ^ ~~~~~~~
503
504 The {}'s are generated by -fdiagnostics-print-source-range-info.
505
506 The printed column numbers count bytes from the beginning of the
507 line; take care if your source contains multibyte characters.
508
509 .. option:: -fdiagnostics-parseable-fixits
510
511 Print Fix-Its in a machine parseable form.
512
513 This option makes Clang print available Fix-Its in a machine
514 parseable format at the end of diagnostics. The following example
515 illustrates the format:
516
517 ::
518
519 fix-it:"t.cpp":{7:25-7:29}:"Gamma"
520
521 The range printed is a half-open range, so in this example the
522 characters at column 25 up to but not including column 29 on line 7
523 in t.cpp should be replaced with the string "Gamma". Either the
524 range or the replacement string may be empty (representing strict
525 insertions and strict erasures, respectively). Both the file name
526 and the insertion string escape backslash (as "\\\\"), tabs (as
527 "\\t"), newlines (as "\\n"), double quotes(as "\\"") and
528 non-printable characters (as octal "\\xxx").
529
530 The printed column numbers count bytes from the beginning of the
531 line; take care if your source contains multibyte characters.
532
533 .. option:: -fno-elide-type
534
535 Turns off elision in template type printing.
536
537 The default for template type printing is to elide as many template
538 arguments as possible, removing those which are the same in both
539 template types, leaving only the differences. Adding this flag will
540 print all the template arguments. If supported by the terminal,
541 highlighting will still appear on differing arguments.
542
543 Default:
544
545 ::
546
547 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;
548
549 -fno-elide-type:
550
551 ::
552
553 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;
554
555 .. option:: -fdiagnostics-show-template-tree
556
557 Template type diffing prints a text tree.
558
559 For diffing large templated types, this option will cause Clang to
560 display the templates as an indented text tree, one argument per
561 line, with differences marked inline. This is compatible with
562 -fno-elide-type.
563
564 Default:
565
566 ::
567
568 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;
569
570 With :option:`-fdiagnostics-show-template-tree`:
571
572 ::
573
574 t.cc:4:5: note: candidate function not viable: no known conversion for 1st argument;
575 vector<
576 map<
577 [...],
578 map<
579 [float != double],
580 [...]>>>
581
582
583 .. option:: -fcaret-diagnostics-max-lines:
584
585 Controls how many lines of code clang prints for diagnostics. By default,
586 clang prints a maximum of 16 lines of code.
587
588
589 .. option:: -fdiagnostics-show-line-numbers:
590
591 Controls whether clang will print a margin containing the line number on
592 the left of each line of code it prints for diagnostics.
593
594 Default:
595
596 ::
597
598 test.cpp:5:1: error: 'main' must return 'int'
599 5 | void main() {}
600 | ^~~~
601 | int
602
603
604 With -fno-diagnostics-show-line-numbers:
605
606 ::
607
608 test.cpp:5:1: error: 'main' must return 'int'
609 void main() {}
610 ^~~~
611 int
612
613
614
615 .. _cl_diag_warning_groups:
616
617 Individual Warning Groups
618 ^^^^^^^^^^^^^^^^^^^^^^^^^
619
620 TODO: Generate this from tblgen. Define one anchor per warning group.
621
622 .. option:: -Wextra-tokens
623
624 Warn about excess tokens at the end of a preprocessor directive.
625
626 This option, which defaults to on, enables warnings about extra
627 tokens at the end of preprocessor directives. For example:
628
629 ::
630
631 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
632 #endif bad
633 ^
634
635 These extra tokens are not strictly conforming, and are usually best
636 handled by commenting them out.
637
638 .. option:: -Wambiguous-member-template
639
640 Warn about unqualified uses of a member template whose name resolves to
641 another template at the location of the use.
642
643 This option, which defaults to on, enables a warning in the
644 following code:
645
646 ::
647
648 template<typename T> struct set{};
649 template<typename T> struct trait { typedef const T& type; };
650 struct Value {
651 template<typename T> void set(typename trait<T>::type value) {}
652 };
653 void foo() {
654 Value v;
655 v.set<double>(3.2);
656 }
657
658 C++ [basic.lookup.classref] requires this to be an error, but,
659 because it's hard to work around, Clang downgrades it to a warning
660 as an extension.
661
662 .. option:: -Wbind-to-temporary-copy
663
664 Warn about an unusable copy constructor when binding a reference to a
665 temporary.
666
667 This option enables warnings about binding a
668 reference to a temporary when the temporary doesn't have a usable
669 copy constructor. For example:
670
671 ::
672
673 struct NonCopyable {
674 NonCopyable();
675 private:
676 NonCopyable(const NonCopyable&);
677 };
678 void foo(const NonCopyable&);
679 void bar() {
680 foo(NonCopyable()); // Disallowed in C++98; allowed in C++11.
681 }
682
683 ::
684
685 struct NonCopyable2 {
686 NonCopyable2();
687 NonCopyable2(NonCopyable2&);
688 };
689 void foo(const NonCopyable2&);
690 void bar() {
691 foo(NonCopyable2()); // Disallowed in C++98; allowed in C++11.
692 }
693
694 Note that if ``NonCopyable2::NonCopyable2()`` has a default argument
695 whose instantiation produces a compile error, that error will still
696 be a hard error in C++98 mode even if this warning is turned off.
697
698 Options to Control Clang Crash Diagnostics
699 ------------------------------------------
700
701 As unbelievable as it may sound, Clang does crash from time to time.
702 Generally, this only occurs to those living on the `bleeding
703 edge <https://llvm.org/releases/download.html#svn>`_. Clang goes to great
704 lengths to assist you in filing a bug report. Specifically, Clang
705 generates preprocessed source file(s) and associated run script(s) upon
706 a crash. These files should be attached to a bug report to ease
707 reproducibility of the failure. Below are the command line options to
708 control the crash diagnostics.
709
710 .. option:: -fcrash-diagnostics=<val>
711
712 Valid values are:
713
714 * ``off`` (Disable auto-generation of preprocessed source files during a clang crash.)
715 * ``compiler`` (Generate diagnostics for compiler crashes (default))
716 * ``all`` (Generate diagnostics for all tools which support it)
717
718 .. option:: -fno-crash-diagnostics
719
720 Disable auto-generation of preprocessed source files during a clang crash.
721
722 The -fno-crash-diagnostics flag can be helpful for speeding the process
723 of generating a delta reduced test case.
724
725 .. option:: -fcrash-diagnostics-dir=<dir>
726
727 Specify where to write the crash diagnostics files; defaults to the
728 usual location for temporary files.
729
730 .. envvar:: CLANG_CRASH_DIAGNOSTICS_DIR=<dir>
731
732 Like ``-fcrash-diagnostics-dir=<dir>``, specifies where to write the
733 crash diagnostics files, but with lower precedence than the option.
734
735 Clang is also capable of generating preprocessed source file(s) and associated
736 run script(s) even without a crash. This is specially useful when trying to
737 generate a reproducer for warnings or errors while using modules.
738
739 .. option:: -gen-reproducer
740
741 Generates preprocessed source files, a reproducer script and if relevant, a
742 cache containing: built module pcm's and all headers needed to rebuild the
743 same modules.
744
745 .. _rpass:
746
747 Options to Emit Optimization Reports
748 ------------------------------------
749
750 Optimization reports trace, at a high-level, all the major decisions
751 done by compiler transformations. For instance, when the inliner
752 decides to inline function ``foo()`` into ``bar()``, or the loop unroller
753 decides to unroll a loop N times, or the vectorizer decides to
754 vectorize a loop body.
755
756 Clang offers a family of flags which the optimizers can use to emit
757 a diagnostic in three cases:
758
759 1. When the pass makes a transformation (`-Rpass`).
760
761 2. When the pass fails to make a transformation (`-Rpass-missed`).
762
763 3. When the pass determines whether or not to make a transformation
764 (`-Rpass-analysis`).
765
766 NOTE: Although the discussion below focuses on `-Rpass`, the exact
767 same options apply to `-Rpass-missed` and `-Rpass-analysis`.
768
769 Since there are dozens of passes inside the compiler, each of these flags
770 take a regular expression that identifies the name of the pass which should
771 emit the associated diagnostic. For example, to get a report from the inliner,
772 compile the code with:
773
774 .. code-block:: console
775
776 $ clang -O2 -Rpass=inline code.cc -o code
777 code.cc:4:25: remark: foo inlined into bar [-Rpass=inline]
778 int bar(int j) { return foo(j, j - 2); }
779 ^
780
781 Note that remarks from the inliner are identified with `[-Rpass=inline]`.
782 To request a report from every optimization pass, you should use
783 `-Rpass=.*` (in fact, you can use any valid POSIX regular
784 expression). However, do not expect a report from every transformation
785 made by the compiler. Optimization remarks do not really make sense
786 outside of the major transformations (e.g., inlining, vectorization,
787 loop optimizations) and not every optimization pass supports this
788 feature.
789
790 Note that when using profile-guided optimization information, profile hotness
791 information can be included in the remarks (see
792 :ref:`-fdiagnostics-show-hotness <opt_fdiagnostics-show-hotness>`).
793
794 Current limitations
795 ^^^^^^^^^^^^^^^^^^^
796
797 1. Optimization remarks that refer to function names will display the
798 mangled name of the function. Since these remarks are emitted by the
799 back end of the compiler, it does not know anything about the input
800 language, nor its mangling rules.
801
802 2. Some source locations are not displayed correctly. The front end has
803 a more detailed source location tracking than the locations included
804 in the debug info (e.g., the front end can locate code inside macro
805 expansions). However, the locations used by `-Rpass` are
806 translated from debug annotations. That translation can be lossy,
807 which results in some remarks having no location information.
808
809 Options to Emit Resource Consumption Reports
810 --------------------------------------------
811
812 These are options that report execution time and consumed memory of different
813 compilations steps.
814
815 .. option:: -fproc-stat-report=
816
817 This option requests driver to print used memory and execution time of each
818 compilation step. The ``clang`` driver during execution calls different tools,
819 like compiler, assembler, linker etc. With this option the driver reports
820 total execution time, the execution time spent in user mode and peak memory
821 usage of each the called tool. Value of the option specifies where the report
822 is sent to. If it specifies a regular file, the data are saved to this file in
823 CSV format:
824
825 .. code-block:: console
826
827 $ clang -fproc-stat-report=abc foo.c
828 $ cat abc
829 clang-11,"/tmp/foo-123456.o",92000,84000,87536
830 ld,"a.out",900,8000,53568
831
832 The data on each row represent:
833
834 * file name of the tool executable,
835 * output file name in quotes,
836 * total execution time in microseconds,
837 * execution time in user mode in microseconds,
838 * peak memory usage in Kb.
839
840 It is possible to specify this option without any value. In this case statistics
841 are printed on standard output in human readable format:
842
843 .. code-block:: console
844
845 $ clang -fproc-stat-report foo.c
846 clang-11: output=/tmp/foo-855a8e.o, total=68.000 ms, user=60.000 ms, mem=86920 Kb
847 ld: output=a.out, total=8.000 ms, user=4.000 ms, mem=52320 Kb
848
849 The report file specified in the option is locked for write, so this option
850 can be used to collect statistics in parallel builds. The report file is not
851 cleared, new data is appended to it, thus making possible to accumulate build
852 statistics.
853
854 You can also use environment variables to control the process statistics reporting.
855 Setting ``CC_PRINT_PROC_STAT`` to ``1`` enables the feature, the report goes to
856 stdout in human readable format.
857 Setting ``CC_PRINT_PROC_STAT_FILE`` to a fully qualified file path makes it report
858 process statistics to the given file in the CSV format. Specifying a relative
859 path will likely lead to multiple files with the same name created in different
860 directories, since the path is relative to a changing working directory.
861
862 These environment variables are handy when you need to request the statistics
863 report without changing your build scripts or alter the existing set of compiler
864 options. Note that ``-fproc-stat-report`` take precedence over ``CC_PRINT_PROC_STAT``
865 and ``CC_PRINT_PROC_STAT_FILE``.
866
867 .. code-block:: console
868
869 $ export CC_PRINT_PROC_STAT=1
870 $ export CC_PRINT_PROC_STAT_FILE=~/project-build-proc-stat.csv
871 $ make
872
873 Other Options
874 -------------
875 Clang options that don't fit neatly into other categories.
876
877 .. option:: -fgnuc-version=
878
879 This flag controls the value of ``__GNUC__`` and related macros. This flag
880 does not enable or disable any GCC extensions implemented in Clang. Setting
881 the version to zero causes Clang to leave ``__GNUC__`` and other
882 GNU-namespaced macros, such as ``__GXX_WEAK__``, undefined.
883
884 .. option:: -MV
885
886 When emitting a dependency file, use formatting conventions appropriate
887 for NMake or Jom. Ignored unless another option causes Clang to emit a
888 dependency file.
889
890 When Clang emits a dependency file (e.g., you supplied the -M option)
891 most filenames can be written to the file without any special formatting.
892 Different Make tools will treat different sets of characters as "special"
893 and use different conventions for telling the Make tool that the character
894 is actually part of the filename. Normally Clang uses backslash to "escape"
895 a special character, which is the convention used by GNU Make. The -MV
896 option tells Clang to put double-quotes around the entire filename, which
897 is the convention used by NMake and Jom.
898
899 .. option:: -femit-dwarf-unwind=<value>
900
901 When to emit DWARF unwind (EH frame) info. This is a Mach-O-specific option.
902
903 Valid values are:
904
905 * ``no-compact-unwind`` - Only emit DWARF unwind when compact unwind encodings
906 aren't available. This is the default for arm64.
907 * ``always`` - Always emit DWARF unwind regardless.
908 * ``default`` - Use the platform-specific default (``always`` for all
909 non-arm64-platforms).
910
911 ``no-compact-unwind`` is a performance optimization -- Clang will emit smaller
912 object files that are more quickly processed by the linker. This may cause
913 binary compatibility issues on older x86_64 targets, however, so use it with
914 caution.
915
916 .. option:: -fdisable-block-signature-string
917
918 Instruct clang not to emit the signature string for blocks. Disabling the
919 string can potentially break existing code that relies on it. Users should
920 carefully consider this possibiilty when using the flag.
921
922 .. _configuration-files:
923
924 Configuration files
925 -------------------
926
927 Configuration files group command-line options and allow all of them to be
928 specified just by referencing the configuration file. They may be used, for
929 example, to collect options required to tune compilation for particular
930 target, such as ``-L``, ``-I``, ``-l``, ``--sysroot``, codegen options, etc.
931
932 Configuration files can be either specified on the command line or loaded
933 from default locations. If both variants are present, the default configuration
934 files are loaded first.
935
936 The command line option ``--config=`` can be used to specify explicit
937 configuration files in a Clang invocation. If the option is used multiple times,
938 all specified files are loaded, in order. For example:
939
940 ::
941
942 clang --config=/home/user/cfgs/testing.txt
943 clang --config=debug.cfg --config=runtimes.cfg
944
945 If the provided argument contains a directory separator, it is considered as
946 a file path, and options are read from that file. Otherwise the argument is
947 treated as a file name and is searched for sequentially in the directories:
948
949 - user directory,
950 - system directory,
951 - the directory where Clang executable resides.
952
953 Both user and system directories for configuration files are specified during
954 clang build using CMake parameters, ``CLANG_CONFIG_FILE_USER_DIR`` and
955 ``CLANG_CONFIG_FILE_SYSTEM_DIR`` respectively. The first file found is used.
956 It is an error if the required file cannot be found.
957
958 The default configuration files are searched for in the same directories
959 following the rules described in the next paragraphs. Loading default
960 configuration files can be disabled entirely via passing
961 the ``--no-default-config`` flag.
962
963 First, the algorithm searches for a configuration file named
964 ``<triple>-<driver>.cfg`` where `triple` is the triple for the target being
965 built for, and `driver` is the name of the currently used driver. The algorithm
966 first attempts to use the canonical name for the driver used, then falls back
967 to the one found in the executable name.
968
969 The following canonical driver names are used:
970
971 - ``clang`` for the ``gcc`` driver (used to compile C programs)
972 - ``clang++`` for the ``gxx`` driver (used to compile C++ programs)
973 - ``clang-cpp`` for the ``cpp`` driver (pure preprocessor)
974 - ``clang-cl`` for the ``cl`` driver
975 - ``flang`` for the ``flang`` driver
976 - ``clang-dxc`` for the ``dxc`` driver
977
978 For example, when calling ``x86_64-pc-linux-gnu-clang-g++``,
979 the driver will first attempt to use the configuration file named::
980
981 x86_64-pc-linux-gnu-clang++.cfg
982
983 If this file is not found, it will attempt to use the name found
984 in the executable instead::
985
986 x86_64-pc-linux-gnu-clang-g++.cfg
987
988 Note that options such as ``--driver-mode=``, ``--target=``, ``-m32`` affect
989 the search algorithm. For example, the aforementioned executable called with
990 ``-m32`` argument will instead search for::
991
992 i386-pc-linux-gnu-clang++.cfg
993
994 If none of the aforementioned files are found, the driver will instead search
995 for separate driver and target configuration files and attempt to load both.
996 The former is named ``<driver>.cfg`` while the latter is named
997 ``<triple>.cfg``. Similarly to the previous variants, the canonical driver name
998 will be preferred, and the compiler will fall back to the actual name.
999
1000 For example, ``x86_64-pc-linux-gnu-clang-g++`` will attempt to load two
1001 configuration files named respectively::
1002
1003 clang++.cfg
1004 x86_64-pc-linux-gnu.cfg
1005
1006 with fallback to trying::
1007
1008 clang-g++.cfg
1009 x86_64-pc-linux-gnu.cfg
1010
1011 It is not an error if either of these files is not found.
1012
1013 The configuration file consists of command-line options specified on one or
1014 more lines. Lines composed of whitespace characters only are ignored as well as
1015 lines in which the first non-blank character is ``#``. Long options may be split
1016 between several lines by a trailing backslash. Here is example of a
1017 configuration file:
1018
1019 ::
1020
1021 # Several options on line
1022 -c --target=x86_64-unknown-linux-gnu
1023
1024 # Long option split between lines
1025 -I/usr/lib/gcc/x86_64-linux-gnu/5.4.0/../../../../\
1026 include/c++/5.4.0
1027
1028 # other config files may be included
1029 @linux.options
1030
1031 Files included by ``@file`` directives in configuration files are resolved
1032 relative to the including file. For example, if a configuration file
1033 ``~/.llvm/target.cfg`` contains the directive ``@os/linux.opts``, the file
1034 ``linux.opts`` is searched for in the directory ``~/.llvm/os``. Another way to
1035 include a file content is using the command line option ``--config=``. It works
1036 similarly but the included file is searched for using the rules for configuration
1037 files.
1038
1039 To generate paths relative to the configuration file, the ``<CFGDIR>`` token may
1040 be used. This will expand to the absolute path of the directory containing the
1041 configuration file.
1042
1043 In cases where a configuration file is deployed alongside SDK contents, the
1044 SDK directory can remain fully portable by using ``<CFGDIR>`` prefixed paths.
1045 In this way, the user may only need to specify a root configuration file with
1046 ``--config=`` to establish every aspect of the SDK with the compiler:
1047
1048 ::
1049
1050 --target=foo
1051 -isystem <CFGDIR>/include
1052 -L <CFGDIR>/lib
1053 -T <CFGDIR>/ldscripts/link.ld
1054
1055 Language and Target-Independent Features
1056 ========================================
1057
1058 Controlling Errors and Warnings
1059 -------------------------------
1060
1061 Clang provides a number of ways to control which code constructs cause
1062 it to emit errors and warning messages, and how they are displayed to
1063 the console.
1064
1065 Controlling How Clang Displays Diagnostics
1066 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1067
1068 When Clang emits a diagnostic, it includes rich information in the
1069 output, and gives you fine-grain control over which information is
1070 printed. Clang has the ability to print this information, and these are
1071 the options that control it:
1072
1073 #. A file/line/column indicator that shows exactly where the diagnostic
1074 occurs in your code [:ref:`-fshow-column <opt_fshow-column>`,
1075 :ref:`-fshow-source-location <opt_fshow-source-location>`].
1076 #. A categorization of the diagnostic as a note, warning, error, or
1077 fatal error.
1078 #. A text string that describes what the problem is.
1079 #. An option that indicates how to control the diagnostic (for
1080 diagnostics that support it)
1081 [:ref:`-fdiagnostics-show-option <opt_fdiagnostics-show-option>`].
1082 #. A :ref:`high-level category <diagnostics_categories>` for the diagnostic
1083 for clients that want to group diagnostics by class (for diagnostics
1084 that support it)
1085 [:option:`-fdiagnostics-show-category`].
1086 #. The line of source code that the issue occurs on, along with a caret
1087 and ranges that indicate the important locations
1088 [:ref:`-fcaret-diagnostics <opt_fcaret-diagnostics>`].
1089 #. "FixIt" information, which is a concise explanation of how to fix the
1090 problem (when Clang is certain it knows)
1091 [:ref:`-fdiagnostics-fixit-info <opt_fdiagnostics-fixit-info>`].
1092 #. A machine-parsable representation of the ranges involved (off by
1093 default)
1094 [:ref:`-fdiagnostics-print-source-range-info <opt_fdiagnostics-print-source-range-info>`].
1095
1096 For more information please see :ref:`Formatting of
1097 Diagnostics <cl_diag_formatting>`.
1098
1099 Diagnostic Mappings
1100 ^^^^^^^^^^^^^^^^^^^
1101
1102 All diagnostics are mapped into one of these 6 classes:
1103
1104 - Ignored
1105 - Note
1106 - Remark
1107 - Warning
1108 - Error
1109 - Fatal
1110
1111 .. _diagnostics_categories:
1112
1113 Diagnostic Categories
1114 ^^^^^^^^^^^^^^^^^^^^^
1115
1116 Though not shown by default, diagnostics may each be associated with a
1117 high-level category. This category is intended to make it possible to
1118 triage builds that produce a large number of errors or warnings in a
1119 grouped way.
1120
1121 Categories are not shown by default, but they can be turned on with the
1122 :option:`-fdiagnostics-show-category` option.
1123 When set to "``name``", the category is printed textually in the
1124 diagnostic output. When it is set to "``id``", a category number is
1125 printed. The mapping of category names to category id's can be obtained
1126 by running '``clang --print-diagnostic-categories``'.
1127
1128 Controlling Diagnostics via Command Line Flags
1129 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1130
1131 TODO: -W flags, -pedantic, etc
1132
1133 .. _pragma_gcc_diagnostic:
1134
1135 Controlling Diagnostics via Pragmas
1136 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1137
1138 Clang can also control what diagnostics are enabled through the use of
1139 pragmas in the source code. This is useful for turning off specific
1140 warnings in a section of source code. Clang supports GCC's pragma for
1141 compatibility with existing source code, so ``#pragma GCC diagnostic``
1142 and ``#pragma clang diagnostic`` are synonyms for Clang. GCC will ignore
1143 ``#pragma clang diagnostic``, though.
1144
1145 The pragma may control any warning that can be used from the command
1146 line. Warnings may be set to ignored, warning, error, or fatal. The
1147 following example code will tell Clang or GCC to ignore the ``-Wall``
1148 warnings:
1149
1150 .. code-block:: c
1151
1152 #pragma GCC diagnostic ignored "-Wall"
1153
1154 Clang also allows you to push and pop the current warning state. This is
1155 particularly useful when writing a header file that will be compiled by
1156 other people, because you don't know what warning flags they build with.
1157
1158 In the below example :option:`-Wextra-tokens` is ignored for only a single line
1159 of code, after which the diagnostics return to whatever state had previously
1160 existed.
1161
1162 .. code-block:: c
1163
1164 #if foo
1165 #endif foo // warning: extra tokens at end of #endif directive
1166
1167 #pragma GCC diagnostic push
1168 #pragma GCC diagnostic ignored "-Wextra-tokens"
1169
1170 #if foo
1171 #endif foo // no warning
1172
1173 #pragma GCC diagnostic pop
1174
1175 The push and pop pragmas will save and restore the full diagnostic state
1176 of the compiler, regardless of how it was set. It should be noted that while Clang
1177 supports the GCC pragma, Clang and GCC do not support the exact same set
1178 of warnings, so even when using GCC compatible #pragmas there is no
1179 guarantee that they will have identical behaviour on both compilers.
1180
1181 Clang also doesn't yet support GCC behavior for ``#pragma diagnostic pop``
1182 that doesn't have a corresponding ``#pragma diagnostic push``. In this case
1183 GCC pretends that there is a ``#pragma diagnostic push`` at the very beginning
1184 of the source file, so "unpaired" ``#pragma diagnostic pop`` matches that
1185 implicit push. This makes a difference for ``#pragma GCC diagnostic ignored``
1186 which are not guarded by push and pop. Refer to
1187 `GCC documentation <https://gcc.gnu.org/onlinedocs/gcc/Diagnostic-Pragmas.html>`_
1188 for details.
1189
1190 Like GCC, Clang accepts ``ignored``, ``warning``, ``error``, and ``fatal``
1191 severity levels. They can be used to change severity of a particular diagnostic
1192 for a region of source file. A notable difference from GCC is that diagnostic
1193 not enabled via command line arguments can't be enabled this way yet.
1194
1195 Some diagnostics associated with a ``-W`` flag have the error severity by
1196 default. They can be ignored or downgraded to warnings:
1197
1198 .. code-block:: cpp
1199
1200 // C only
1201 #pragma GCC diagnostic warning "-Wimplicit-function-declaration"
1202 int main(void) { puts(""); }
1203
1204 In addition to controlling warnings and errors generated by the compiler, it is
1205 possible to generate custom warning and error messages through the following
1206 pragmas:
1207
1208 .. code-block:: c
1209
1210 // The following will produce warning messages
1211 #pragma message "some diagnostic message"
1212 #pragma GCC warning "TODO: replace deprecated feature"
1213
1214 // The following will produce an error message
1215 #pragma GCC error "Not supported"
1216
1217 These pragmas operate similarly to the ``#warning`` and ``#error`` preprocessor
1218 directives, except that they may also be embedded into preprocessor macros via
1219 the C99 ``_Pragma`` operator, for example:
1220
1221 .. code-block:: c
1222
1223 #define STR(X) #X
1224 #define DEFER(M,...) M(__VA_ARGS__)
1225 #define CUSTOM_ERROR(X) _Pragma(STR(GCC error(X " at line " DEFER(STR,__LINE__))))
1226
1227 CUSTOM_ERROR("Feature not available");
1228
1229 Controlling Diagnostics in System Headers
1230 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1231
1232 Warnings are suppressed when they occur in system headers. By default,
1233 an included file is treated as a system header if it is found in an
1234 include path specified by ``-isystem``, but this can be overridden in
1235 several ways.
1236
1237 The ``system_header`` pragma can be used to mark the current file as
1238 being a system header. No warnings will be produced from the location of
1239 the pragma onwards within the same file.
1240
1241 .. code-block:: c
1242
1243 #if foo
1244 #endif foo // warning: extra tokens at end of #endif directive
1245
1246 #pragma clang system_header
1247
1248 #if foo
1249 #endif foo // no warning
1250
1251 The `--system-header-prefix=` and `--no-system-header-prefix=`
1252 command-line arguments can be used to override whether subsets of an include
1253 path are treated as system headers. When the name in a ``#include`` directive
1254 is found within a header search path and starts with a system prefix, the
1255 header is treated as a system header. The last prefix on the
1256 command-line which matches the specified header name takes precedence.
1257 For instance:
1258
1259 .. code-block:: console
1260
1261 $ clang -Ifoo -isystem bar --system-header-prefix=x/ \
1262 --no-system-header-prefix=x/y/
1263
1264 Here, ``#include "x/a.h"`` is treated as including a system header, even
1265 if the header is found in ``foo``, and ``#include "x/y/b.h"`` is treated
1266 as not including a system header, even if the header is found in
1267 ``bar``.
1268
1269 A ``#include`` directive which finds a file relative to the current
1270 directory is treated as including a system header if the including file
1271 is treated as a system header.
1272
1273 Controlling Deprecation Diagnostics in Clang-Provided C Runtime Headers
1274 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1275
1276 Clang is responsible for providing some of the C runtime headers that cannot be
1277 provided by a platform CRT, such as implementation limits or when compiling in
1278 freestanding mode. Define the ``_CLANG_DISABLE_CRT_DEPRECATION_WARNINGS`` macro
1279 prior to including such a C runtime header to disable the deprecation warnings.
1280 Note that the C Standard Library headers are allowed to transitively include
1281 other standard library headers (see 7.1.2p5), and so the most appropriate use
1282 of this macro is to set it within the build system using ``-D`` or before any
1283 include directives in the translation unit.
1284
1285 .. code-block:: c
1286
1287 #define _CLANG_DISABLE_CRT_DEPRECATION_WARNINGS
1288 #include <stdint.h> // Clang CRT deprecation warnings are disabled.
1289 #include <stdatomic.h> // Clang CRT deprecation warnings are disabled.
1290
1291 .. _diagnostics_enable_everything:
1292
1293 Enabling All Diagnostics
1294 ^^^^^^^^^^^^^^^^^^^^^^^^
1295
1296 In addition to the traditional ``-W`` flags, one can enable **all** diagnostics
1297 by passing :option:`-Weverything`. This works as expected with
1298 :option:`-Werror`, and also includes the warnings from :option:`-pedantic`. Some
1299 diagnostics contradict each other, therefore, users of :option:`-Weverything`
1300 often disable many diagnostics such as `-Wno-c++98-compat` and `-Wno-c++-compat`
1301 because they contradict recent C++ standards.
1302
1303 Since :option:`-Weverything` enables every diagnostic, we generally don't
1304 recommend using it. `-Wall` `-Wextra` are a better choice for most projects.
1305 Using :option:`-Weverything` means that updating your compiler is more difficult
1306 because you're exposed to experimental diagnostics which might be of lower
1307 quality than the default ones. If you do use :option:`-Weverything` then we
1308 advise that you address all new compiler diagnostics as they get added to Clang,
1309 either by fixing everything they find or explicitly disabling that diagnostic
1310 with its corresponding `Wno-` option.
1311
1312 Note that when combined with :option:`-w` (which disables all warnings),
1313 disabling all warnings wins.
1314
1315 Controlling Static Analyzer Diagnostics
1316 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1317
1318 While not strictly part of the compiler, the diagnostics from Clang's
1319 `static analyzer <https://clang-analyzer.llvm.org>`_ can also be
1320 influenced by the user via changes to the source code. See the available
1321 `annotations <https://clang-analyzer.llvm.org/annotations.html>`_ and the
1322 analyzer's `FAQ
1323 page <https://clang-analyzer.llvm.org/faq.html#exclude_code>`_ for more
1324 information.
1325
1326 .. _usersmanual-precompiled-headers:
1327
1328 Precompiled Headers
1329 -------------------
1330
1331 `Precompiled headers <https://en.wikipedia.org/wiki/Precompiled_header>`_
1332 are a general approach employed by many compilers to reduce compilation
1333 time. The underlying motivation of the approach is that it is common for
1334 the same (and often large) header files to be included by multiple
1335 source files. Consequently, compile times can often be greatly improved
1336 by caching some of the (redundant) work done by a compiler to process
1337 headers. Precompiled header files, which represent one of many ways to
1338 implement this optimization, are literally files that represent an
1339 on-disk cache that contains the vital information necessary to reduce
1340 some of the work needed to process a corresponding header file. While
1341 details of precompiled headers vary between compilers, precompiled
1342 headers have been shown to be highly effective at speeding up program
1343 compilation on systems with very large system headers (e.g., macOS).
1344
1345 Generating a PCH File
1346 ^^^^^^^^^^^^^^^^^^^^^
1347
1348 To generate a PCH file using Clang, one invokes Clang with the
1349 `-x <language>-header` option. This mirrors the interface in GCC
1350 for generating PCH files:
1351
1352 .. code-block:: console
1353
1354 $ gcc -x c-header test.h -o test.h.gch
1355 $ clang -x c-header test.h -o test.h.pch
1356
1357 Using a PCH File
1358 ^^^^^^^^^^^^^^^^
1359
1360 A PCH file can then be used as a prefix header when a ``-include-pch``
1361 option is passed to ``clang``:
1362
1363 .. code-block:: console
1364
1365 $ clang -include-pch test.h.pch test.c -o test
1366
1367 The ``clang`` driver will check if the PCH file ``test.h.pch`` is
1368 available; if so, the contents of ``test.h`` (and the files it includes)
1369 will be processed from the PCH file. Otherwise, Clang will report an error.
1370
1371 .. note::
1372
1373 Clang does *not* automatically use PCH files for headers that are directly
1374 included within a source file or indirectly via :option:`-include`.
1375 For example:
1376
1377 .. code-block:: console
1378
1379 $ clang -x c-header test.h -o test.h.pch
1380 $ cat test.c
1381 #include "test.h"
1382 $ clang test.c -o test
1383
1384 In this example, ``clang`` will not automatically use the PCH file for
1385 ``test.h`` since ``test.h`` was included directly in the source file and not
1386 specified on the command line using ``-include-pch``.
1387
1388 Relocatable PCH Files
1389 ^^^^^^^^^^^^^^^^^^^^^
1390
1391 It is sometimes necessary to build a precompiled header from headers
1392 that are not yet in their final, installed locations. For example, one
1393 might build a precompiled header within the build tree that is then
1394 meant to be installed alongside the headers. Clang permits the creation
1395 of "relocatable" precompiled headers, which are built with a given path
1396 (into the build directory) and can later be used from an installed
1397 location.
1398
1399 To build a relocatable precompiled header, place your headers into a
1400 subdirectory whose structure mimics the installed location. For example,
1401 if you want to build a precompiled header for the header ``mylib.h``
1402 that will be installed into ``/usr/include``, create a subdirectory
1403 ``build/usr/include`` and place the header ``mylib.h`` into that
1404 subdirectory. If ``mylib.h`` depends on other headers, then they can be
1405 stored within ``build/usr/include`` in a way that mimics the installed
1406 location.
1407
1408 Building a relocatable precompiled header requires two additional
1409 arguments. First, pass the ``--relocatable-pch`` flag to indicate that
1410 the resulting PCH file should be relocatable. Second, pass
1411 ``-isysroot /path/to/build``, which makes all includes for your library
1412 relative to the build directory. For example:
1413
1414 .. code-block:: console
1415
1416 # clang -x c-header --relocatable-pch -isysroot /path/to/build /path/to/build/mylib.h mylib.h.pch
1417
1418 When loading the relocatable PCH file, the various headers used in the
1419 PCH file are found from the system header root. For example, ``mylib.h``
1420 can be found in ``/usr/include/mylib.h``. If the headers are installed
1421 in some other system root, the ``-isysroot`` option can be used provide
1422 a different system root from which the headers will be based. For
1423 example, ``-isysroot /Developer/SDKs/MacOSX10.4u.sdk`` will look for
1424 ``mylib.h`` in ``/Developer/SDKs/MacOSX10.4u.sdk/usr/include/mylib.h``.
1425
1426 Relocatable precompiled headers are intended to be used in a limited
1427 number of cases where the compilation environment is tightly controlled
1428 and the precompiled header cannot be generated after headers have been
1429 installed.
1430
1431 .. _controlling-fp-behavior:
1432
1433 Controlling Floating Point Behavior
1434 -----------------------------------
1435
1436 Clang provides a number of ways to control floating point behavior, including
1437 with command line options and source pragmas. This section
1438 describes the various floating point semantic modes and the corresponding options.
1439
1440 .. csv-table:: Floating Point Semantic Modes
1441 :header: "Mode", "Values"
1442 :widths: 15, 30, 30
1443
1444 "ffp-exception-behavior", "{ignore, strict, maytrap}",
1445 "fenv_access", "{off, on}", "(none)"
1446 "frounding-math", "{dynamic, tonearest, downward, upward, towardzero}"
1447 "ffp-contract", "{on, off, fast, fast-honor-pragmas}"
1448 "fdenormal-fp-math", "{IEEE, PreserveSign, PositiveZero}"
1449 "fdenormal-fp-math-fp32", "{IEEE, PreserveSign, PositiveZero}"
1450 "fmath-errno", "{on, off}"
1451 "fhonor-nans", "{on, off}"
1452 "fhonor-infinities", "{on, off}"
1453 "fsigned-zeros", "{on, off}"
1454 "freciprocal-math", "{on, off}"
1455 "allow_approximate_fns", "{on, off}"
1456 "fassociative-math", "{on, off}"
1457
1458 This table describes the option settings that correspond to the three
1459 floating point semantic models: precise (the default), strict, and fast.
1460
1461
1462 .. csv-table:: Floating Point Models
1463 :header: "Mode", "Precise", "Strict", "Fast"
1464 :widths: 25, 15, 15, 15
1465
1466 "except_behavior", "ignore", "strict", "ignore"
1467 "fenv_access", "off", "on", "off"
1468 "rounding_mode", "tonearest", "dynamic", "tonearest"
1469 "contract", "on", "off", "fast"
1470 "support_math_errno", "on", "on", "off"
1471 "no_honor_nans", "off", "off", "on"
1472 "no_honor_infinities", "off", "off", "on"
1473 "no_signed_zeros", "off", "off", "on"
1474 "allow_reciprocal", "off", "off", "on"
1475 "allow_approximate_fns", "off", "off", "on"
1476 "allow_reassociation", "off", "off", "on"
1477
1478 The ``-ffp-model`` option does not modify the ``fdenormal-fp-math``
1479 setting, but it does have an impact on whether ``crtfastmath.o`` is
1480 linked. Because linking ``crtfastmath.o`` has a global effect on the
1481 program, and because the global denormal handling can be changed in
1482 other ways, the state of ``fdenormal-fp-math`` handling cannot
1483 be assumed in any function based on fp-model. See :ref:`crtfastmath.o`
1484 for more details.
1485
1486 .. option:: -ffast-math
1487
1488 Enable fast-math mode. This option lets the
1489 compiler make aggressive, potentially-lossy assumptions about
1490 floating-point math. These include:
1491
1492 * Floating-point math obeys regular algebraic rules for real numbers (e.g.
1493 ``+`` and ``*`` are associative, ``x/y == x * (1/y)``, and
1494 ``(a + b) * c == a * c + b * c``),
1495 * Operands to floating-point operations are not equal to ``NaN`` and
1496 ``Inf``, and
1497 * ``+0`` and ``-0`` are interchangeable.
1498
1499 ``-ffast-math`` also defines the ``__FAST_MATH__`` preprocessor
1500 macro. Some math libraries recognize this macro and change their behavior.
1501 With the exception of ``-ffp-contract=fast``, using any of the options
1502 below to disable any of the individual optimizations in ``-ffast-math``
1503 will cause ``__FAST_MATH__`` to no longer be set.
1504 ``-ffast-math`` enables ``-fcx-limited-range``.
1505
1506 This option implies:
1507
1508 * ``-fno-honor-infinities``
1509
1510 * ``-fno-honor-nans``
1511
1512 * ``-fapprox-func``
1513
1514 * ``-fno-math-errno``
1515
1516 * ``-ffinite-math-only``
1517
1518 * ``-fassociative-math``
1519
1520 * ``-freciprocal-math``
1521
1522 * ``-fno-signed-zeros``
1523
1524 * ``-fno-trapping-math``
1525
1526 * ``-fno-rounding-math``
1527
1528 * ``-ffp-contract=fast``
1529
1530 Note: ``-ffast-math`` causes ``crtfastmath.o`` to be linked with code unless
1531 ``-shared`` or ``-mno-daz-ftz`` is present. See
1532 :ref:`crtfastmath.o` for more details.
1533
1534 .. option:: -fno-fast-math
1535
1536 Disable fast-math mode. This options disables unsafe floating-point
1537 optimizations by preventing the compiler from making any transformations that
1538 could affect the results.
1539
1540 This option implies:
1541
1542 * ``-fhonor-infinities``
1543
1544 * ``-fhonor-nans``
1545
1546 * ``-fno-approx-func``
1547
1548 * ``-fno-finite-math-only``
1549
1550 * ``-fno-associative-math``
1551
1552 * ``-fno-reciprocal-math``
1553
1554 * ``-fsigned-zeros``
1555
1556 * ``-ffp-contract=on``
1557
1558 Also, this option resets following options to their target-dependent defaults.
1559
1560 * ``-f[no-]math-errno``
1561
1562 There is ambiguity about how ``-ffp-contract``, ``-ffast-math``,
1563 and ``-fno-fast-math`` behave when combined. To keep the value of
1564 ``-ffp-contract`` consistent, we define this set of rules:
1565
1566 * ``-ffast-math`` sets ``ffp-contract`` to ``fast``.
1567
1568 * ``-fno-fast-math`` sets ``-ffp-contract`` to ``on`` (``fast`` for CUDA and
1569 HIP).
1570
1571 * If ``-ffast-math`` and ``-ffp-contract`` are both seen, but
1572 ``-ffast-math`` is not followed by ``-fno-fast-math``, ``ffp-contract``
1573 will be given the value of whichever option was last seen.
1574
1575 * If ``-fno-fast-math`` is seen and ``-ffp-contract`` has been seen at least
1576 once, the ``ffp-contract`` will get the value of the last seen value of
1577 ``-ffp-contract``.
1578
1579 * If ``-fno-fast-math`` is seen and ``-ffp-contract`` has not been seen, the
1580 ``-ffp-contract`` setting is determined by the default value of
1581 ``-ffp-contract``.
1582
1583 Note: ``-fno-fast-math`` causes ``crtfastmath.o`` to not be linked with code
1584 unless ``-mdaz-ftz`` is present.
1585
1586 .. option:: -fdenormal-fp-math=<value>
1587
1588 Select which denormal numbers the code is permitted to require.
1589
1590 Valid values are:
1591
1592 * ``ieee`` - IEEE 754 denormal numbers
1593 * ``preserve-sign`` - the sign of a flushed-to-zero number is preserved in the sign of 0
1594 * ``positive-zero`` - denormals are flushed to positive zero
1595
1596 The default value depends on the target. For most targets, defaults to
1597 ``ieee``.
1598
1599 .. option:: -f[no-]strict-float-cast-overflow
1600
1601 When a floating-point value is not representable in a destination integer
1602 type, the code has undefined behavior according to the language standard.
1603 By default, Clang will not guarantee any particular result in that case.
1604 With the 'no-strict' option, Clang will saturate towards the smallest and
1605 largest representable integer values instead. NaNs will be converted to zero.
1606 Defaults to ``-fstrict-float-cast-overflow``.
1607
1608 .. option:: -f[no-]math-errno
1609
1610 Require math functions to indicate errors by setting errno.
1611 The default varies by ToolChain. ``-fno-math-errno`` allows optimizations
1612 that might cause standard C math functions to not set ``errno``.
1613 For example, on some systems, the math function ``sqrt`` is specified
1614 as setting ``errno`` to ``EDOM`` when the input is negative. On these
1615 systems, the compiler cannot normally optimize a call to ``sqrt`` to use
1616 inline code (e.g. the x86 ``sqrtsd`` instruction) without additional
1617 checking to ensure that ``errno`` is set appropriately.
1618 ``-fno-math-errno`` permits these transformations.
1619
1620 On some targets, math library functions never set ``errno``, and so
1621 ``-fno-math-errno`` is the default. This includes most BSD-derived
1622 systems, including Darwin.
1623
1624 .. option:: -f[no-]trapping-math
1625
1626 Control floating point exception behavior. ``-fno-trapping-math`` allows optimizations that assume that floating point operations cannot generate traps such as divide-by-zero, overflow and underflow.
1627
1628 - The option ``-ftrapping-math`` behaves identically to ``-ffp-exception-behavior=strict``.
1629 - The option ``-fno-trapping-math`` behaves identically to ``-ffp-exception-behavior=ignore``. This is the default.
1630
1631 .. option:: -ffp-contract=<value>
1632
1633 Specify when the compiler is permitted to form fused floating-point
1634 operations, such as fused multiply-add (FMA). Fused operations are
1635 permitted to produce more precise results than performing the same
1636 operations separately.
1637
1638 The C standard permits intermediate floating-point results within an
1639 expression to be computed with more precision than their type would
1640 normally allow. This permits operation fusing, and Clang takes advantage
1641 of this by default. This behavior can be controlled with the ``FP_CONTRACT``
1642 and ``clang fp contract`` pragmas. Please refer to the pragma documentation
1643 for a description of how the pragmas interact with this option.
1644
1645 Valid values are:
1646
1647 * ``fast`` (fuse across statements disregarding pragmas, default for CUDA)
1648 * ``on`` (fuse in the same statement unless dictated by pragmas, default for languages other than CUDA/HIP)
1649 * ``off`` (never fuse)
1650 * ``fast-honor-pragmas`` (fuse across statements unless dictated by pragmas, default for HIP)
1651
1652 .. option:: -f[no-]honor-infinities
1653
1654 Allow floating-point optimizations that assume arguments and results are
1655 not +-Inf.
1656 Defaults to ``-fhonor-infinities``.
1657
1658 If both ``-fno-honor-infinities`` and ``-fno-honor-nans`` are used,
1659 has the same effect as specifying ``-ffinite-math-only``.
1660
1661 .. option:: -f[no-]honor-nans
1662
1663 Allow floating-point optimizations that assume arguments and results are
1664 not NaNs.
1665 Defaults to ``-fhonor-nans``.
1666
1667 If both ``-fno-honor-infinities`` and ``-fno-honor-nans`` are used,
1668 has the same effect as specifying ``-ffinite-math-only``.
1669
1670 .. option:: -f[no-]approx-func
1671
1672 Allow certain math function calls (such as ``log``, ``sqrt``, ``pow``, etc)
1673 to be replaced with an approximately equivalent set of instructions
1674 or alternative math function calls. For example, a ``pow(x, 0.25)``
1675 may be replaced with ``sqrt(sqrt(x))``, despite being an inexact result
1676 in cases where ``x`` is ``-0.0`` or ``-inf``.
1677 Defaults to ``-fno-approx-func``.
1678
1679 .. option:: -f[no-]signed-zeros
1680
1681 Allow optimizations that ignore the sign of floating point zeros.
1682 Defaults to ``-fsigned-zeros``.
1683
1684 .. option:: -f[no-]associative-math
1685
1686 Allow floating point operations to be reassociated.
1687 Defaults to ``-fno-associative-math``.
1688
1689 .. option:: -f[no-]reciprocal-math
1690
1691 Allow division operations to be transformed into multiplication by a
1692 reciprocal. This can be significantly faster than an ordinary division
1693 but can also have significantly less precision. Defaults to
1694 ``-fno-reciprocal-math``.
1695
1696 .. option:: -f[no-]unsafe-math-optimizations
1697
1698 Allow unsafe floating-point optimizations.
1699 ``-funsafe-math-optimizations`` also implies:
1700
1701 * ``-fapprox-func``
1702 * ``-fassociative-math``
1703 * ``-freciprocal-math``
1704 * ``-fno-signed-zeros``
1705 * ``-fno-trapping-math``
1706 * ``-ffp-contract=fast``
1707
1708 ``-fno-unsafe-math-optimizations`` implies:
1709
1710 * ``-fno-approx-func``
1711 * ``-fno-associative-math``
1712 * ``-fno-reciprocal-math``
1713 * ``-fsigned-zeros``
1714 * ``-ffp-contract=on``
1715
1716 There is ambiguity about how ``-ffp-contract``,
1717 ``-funsafe-math-optimizations``, and ``-fno-unsafe-math-optimizations``
1718 behave when combined. Explanation in :option:`-fno-fast-math` also applies
1719 to these options.
1720
1721 Defaults to ``-fno-unsafe-math-optimizations``.
1722
1723 .. option:: -f[no-]finite-math-only
1724
1725 Allow floating-point optimizations that assume arguments and results are
1726 not NaNs or +-Inf. ``-ffinite-math-only`` defines the
1727 ``__FINITE_MATH_ONLY__`` preprocessor macro.
1728 ``-ffinite-math-only`` implies:
1729
1730 * ``-fno-honor-infinities``
1731 * ``-fno-honor-nans``
1732
1733 ``-ffno-inite-math-only`` implies:
1734
1735 * ``-fhonor-infinities``
1736 * ``-fhonor-nans``
1737
1738 Defaults to ``-fno-finite-math-only``.
1739
1740 .. option:: -f[no-]rounding-math
1741
1742 Force floating-point operations to honor the dynamically-set rounding mode by default.
1743
1744 The result of a floating-point operation often cannot be exactly represented in the result type and therefore must be rounded. IEEE 754 describes different rounding modes that control how to perform this rounding, not all of which are supported by all implementations. C provides interfaces (``fesetround`` and ``fesetenv``) for dynamically controlling the rounding mode, and while it also recommends certain conventions for changing the rounding mode, these conventions are not typically enforced in the ABI. Since the rounding mode changes the numerical result of operations, the compiler must understand something about it in order to optimize floating point operations.
1745
1746 Note that floating-point operations performed as part of constant initialization are formally performed prior to the start of the program and are therefore not subject to the current rounding mode. This includes the initialization of global variables and local ``static`` variables. Floating-point operations in these contexts will be rounded using ``FE_TONEAREST``.
1747
1748 - The option ``-fno-rounding-math`` allows the compiler to assume that the rounding mode is set to ``FE_TONEAREST``. This is the default.
1749 - The option ``-frounding-math`` forces the compiler to honor the dynamically-set rounding mode. This prevents optimizations which might affect results if the rounding mode changes or is different from the default; for example, it prevents floating-point operations from being reordered across most calls and prevents constant-folding when the result is not exactly representable.
1750
1751 .. option:: -ffp-model=<value>
1752
1753 Specify floating point behavior. ``-ffp-model`` is an umbrella
1754 option that encompasses functionality provided by other, single
1755 purpose, floating point options. Valid values are: ``precise``, ``strict``,
1756 and ``fast``.
1757 Details:
1758
1759 * ``precise`` Disables optimizations that are not value-safe on
1760 floating-point data, although FP contraction (FMA) is enabled
1761 (``-ffp-contract=on``). This is the default behavior. This value resets
1762 ``-fmath-errno`` to its target-dependent default.
1763 * ``strict`` Enables ``-frounding-math`` and
1764 ``-ffp-exception-behavior=strict``, and disables contractions (FMA). All
1765 of the ``-ffast-math`` enablements are disabled. Enables
1766 ``STDC FENV_ACCESS``: by default ``FENV_ACCESS`` is disabled. This option
1767 setting behaves as though ``#pragma STDC FENV_ACCESS ON`` appeared at the
1768 top of the source file.
1769 * ``fast`` Behaves identically to specifying both ``-ffast-math`` and
1770 ``ffp-contract=fast``
1771
1772 Note: If your command line specifies multiple instances
1773 of the ``-ffp-model`` option, or if your command line option specifies
1774 ``-ffp-model`` and later on the command line selects a floating point
1775 option that has the effect of negating part of the ``ffp-model`` that
1776 has been selected, then the compiler will issue a diagnostic warning
1777 that the override has occurred.
1778
1779 .. option:: -ffp-exception-behavior=<value>
1780
1781 Specify the floating-point exception behavior.
1782
1783 Valid values are: ``ignore``, ``maytrap``, and ``strict``.
1784 The default value is ``ignore``. Details:
1785
1786 * ``ignore`` The compiler assumes that the exception status flags will not be read and that floating point exceptions will be masked.
1787 * ``maytrap`` The compiler avoids transformations that may raise exceptions that would not have been raised by the original code. Constant folding performed by the compiler is exempt from this option.
1788 * ``strict`` The compiler ensures that all transformations strictly preserve the floating point exception semantics of the original code.
1789
1790 .. option:: -ffp-eval-method=<value>
1791
1792 Specify the floating-point evaluation method for intermediate results within
1793 a single expression of the code.
1794
1795 Valid values are: ``source``, ``double``, and ``extended``.
1796 For 64-bit targets, the default value is ``source``. For 32-bit x86 targets
1797 however, in the case of NETBSD 6.99.26 and under, the default value is
1798 ``double``; in the case of NETBSD greater than 6.99.26, with NoSSE, the
1799 default value is ``extended``, with SSE the default value is ``source``.
1800 Details:
1801
1802 * ``source`` The compiler uses the floating-point type declared in the source program as the evaluation method.
1803 * ``double`` The compiler uses ``double`` as the floating-point evaluation method for all float expressions of type that is narrower than ``double``.
1804 * ``extended`` The compiler uses ``long double`` as the floating-point evaluation method for all float expressions of type that is narrower than ``long double``.
1805
1806 .. option:: -f[no-]protect-parens
1807
1808 This option pertains to floating-point types, complex types with
1809 floating-point components, and vectors of these types. Some arithmetic
1810 expression transformations that are mathematically correct and permissible
1811 according to the C and C++ language standards may be incorrect when dealing
1812 with floating-point types, such as reassociation and distribution. Further,
1813 the optimizer may ignore parentheses when computing arithmetic expressions
1814 in circumstances where the parenthesized and unparenthesized expression
1815 express the same mathematical value. For example (a+b)+c is the same
1816 mathematical value as a+(b+c), but the optimizer is free to evaluate the
1817 additions in any order regardless of the parentheses. When enabled, this
1818 option forces the optimizer to honor the order of operations with respect
1819 to parentheses in all circumstances.
1820 Defaults to ``-fno-protect-parens``.
1821
1822 Note that floating-point contraction (option `-ffp-contract=`) is disabled
1823 when `-fprotect-parens` is enabled. Also note that in safe floating-point
1824 modes, such as `-ffp-model=precise` or `-ffp-model=strict`, this option
1825 has no effect because the optimizer is prohibited from making unsafe
1826 transformations.
1827
1828 .. option:: -fexcess-precision:
1829
1830 The C and C++ standards allow floating-point expressions to be computed as if
1831 intermediate results had more precision (and/or a wider range) than the type
1832 of the expression strictly allows. This is called excess precision
1833 arithmetic.
1834 Excess precision arithmetic can improve the accuracy of results (although not
1835 always), and it can make computation significantly faster if the target lacks
1836 direct hardware support for arithmetic in a particular type. However, it can
1837 also undermine strict floating-point reproducibility.
1838
1839 Under the standards, assignments and explicit casts force the operand to be
1840 converted to its formal type, discarding any excess precision. Because data
1841 can only flow between statements via an assignment, this means that the use
1842 of excess precision arithmetic is a reliable local property of a single
1843 statement, and results do not change based on optimization. However, when
1844 excess precision arithmetic is in use, Clang does not guarantee strict
1845 reproducibility, and future compiler releases may recognize more
1846 opportunities to use excess precision arithmetic, e.g. with floating-point
1847 builtins.
1848
1849 Clang does not use excess precision arithmetic for most types or on most
1850 targets. For example, even on pre-SSE X86 targets where ``float`` and
1851 ``double`` computations must be performed in the 80-bit X87 format, Clang
1852 rounds all intermediate results correctly for their type. Clang currently
1853 uses excess precision arithmetic by default only for the following types and
1854 targets:
1855
1856 * ``_Float16`` on X86 targets without ``AVX512-FP16``.
1857
1858 The ``-fexcess-precision=<value>`` option can be used to control the use of
1859 excess precision arithmetic. Valid values are:
1860
1861 * ``standard`` - The default. Allow the use of excess precision arithmetic
1862 under the constraints of the C and C++ standards. Has no effect except on
1863 the types and targets listed above.
1864 * ``fast`` - Accepted for GCC compatibility, but currently treated as an
1865 alias for ``standard``.
1866 * ``16`` - Forces ``_Float16`` operations to be emitted without using excess
1867 precision arithmetic.
1868
1869 .. option:: -fcomplex-arithmetic=<value>:
1870
1871 This option specifies the implementation for complex multiplication and division.
1872
1873 Valid values are: ``basic``, ``improved``, ``full`` and ``promoted``.
1874
1875 * ``basic`` Implementation of complex division and multiplication using
1876 algebraic formulas at source precision. No special handling to avoid
1877 overflow. NaN and infinite values are not handled.
1878 * ``improved`` Implementation of complex division using the Smith algorithm
1879 at source precision. Smith's algorithm for complex division.
1880 See SMITH, R. L. Algorithm 116: Complex division. Commun. ACM 5, 8 (1962).
1881 This value offers improved handling for overflow in intermediate
1882 calculations, but overflow may occur. NaN and infinite values are not
1883 handled in some cases.
1884 * ``full`` Implementation of complex division and multiplication using a
1885 call to runtime library functions (generally the case, but the BE might
1886 sometimes replace the library call if it knows enough about the potential
1887 range of the inputs). Overflow and non-finite values are handled by the
1888 library implementation. For the case of multiplication overflow will occur in
1889 accordance with normal floating-point rules. This is the default value.
1890 * ``promoted`` Implementation of complex division using algebraic formulas at
1891 higher precision. Overflow is handled. Non-finite values are handled in some
1892 cases. If the target does not have native support for a higher precision
1893 data type, the implementation for the complex operation using the Smith
1894 algorithm will be used. Overflow may still occur in some cases. NaN and
1895 infinite values are not handled.
1896
1897 .. option:: -fcx-limited-range:
1898
1899 This option is aliased to ``-fcomplex-arithmetic=basic``. It enables the
1900 naive mathematical formulas for complex division and multiplication with no
1901 NaN checking of results. The default is ``-fno-cx-limited-range`` aliased to
1902 ``-fcomplex-arithmetic=full``. This option is enabled by the ``-ffast-math``
1903 option.
1904
1905 .. option:: -fcx-fortran-rules:
1906
1907 This option is aliased to ``-fcomplex-arithmetic=improved``. It enables the
1908 naive mathematical formulas for complex multiplication and enables application
1909 of Smith's algorithm for complex division. See SMITH, R. L. Algorithm 116:
1910 Complex division. Commun. ACM 5, 8 (1962).
1911 The default is ``-fno-cx-fortran-rules`` aliased to
1912 ``-fcomplex-arithmetic=full``.
1913
1914 .. _floating-point-environment:
1915
1916 Accessing the floating point environment
1917 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1918 Many targets allow floating point operations to be configured to control things
1919 such as how inexact results should be rounded and how exceptional conditions
1920 should be handled. This configuration is called the floating point environment.
1921 C and C++ restrict access to the floating point environment by default, and the
1922 compiler is allowed to assume that all operations are performed in the default
1923 environment. When code is compiled in this default mode, operations that depend
1924 on the environment (such as floating-point arithmetic and `FLT_ROUNDS`) may have
1925 undefined behavior if the dynamic environment is not the default environment; for
1926 example, `FLT_ROUNDS` may or may not simply return its default value for the target
1927 instead of reading the dynamic environment, and floating-point operations may be
1928 optimized as if the dynamic environment were the default. Similarly, it is undefined
1929 behavior to change the floating point environment in this default mode, for example
1930 by calling the `fesetround` function.
1931 C provides two pragmas to allow code to dynamically modify the floating point environment:
1932
1933 - ``#pragma STDC FENV_ACCESS ON`` allows dynamic changes to the entire floating
1934 point environment.
1935
1936 - ``#pragma STDC FENV_ROUND FE_DYNAMIC`` allows dynamic changes to just the floating
1937 point rounding mode. This may be more optimizable than ``FENV_ACCESS ON`` because
1938 the compiler can still ignore the possibility of floating-point exceptions by default.
1939
1940 Both of these can be used either at the start of a block scope, in which case
1941 they cover all code in that scope (unless they're turned off in a child scope),
1942 or at the top level in a file, in which case they cover all subsequent function
1943 bodies until they're turned off. Note that it is undefined behavior to enter
1944 code that is *not* covered by one of these pragmas from code that *is* covered
1945 by one of these pragmas unless the floating point environment has been restored
1946 to its default state. See the C standard for more information about these pragmas.
1947
1948 The command line option ``-frounding-math`` behaves as if the translation unit
1949 began with ``#pragma STDC FENV_ROUND FE_DYNAMIC``. The command line option
1950 ``-ffp-model=strict`` behaves as if the translation unit began with ``#pragma STDC FENV_ACCESS ON``.
1951
1952 Code that just wants to use a specific rounding mode for specific floating point
1953 operations can avoid most of the hazards of the dynamic floating point environment
1954 by using ``#pragma STDC FENV_ROUND`` with a value other than ``FE_DYNAMIC``.
1955
1956 .. _crtfastmath.o:
1957
1958 A note about ``crtfastmath.o``
1959 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1960 ``-ffast-math`` and ``-funsafe-math-optimizations`` without the ``-shared``
1961 option cause ``crtfastmath.o`` to be
1962 automatically linked, which adds a static constructor that sets the FTZ/DAZ
1963 bits in MXCSR, affecting not only the current compilation unit but all static
1964 and shared libraries included in the program. This decision can be overridden
1965 by using either the flag ``-mdaz-ftz`` or ``-mno-daz-ftz`` to respectively
1966 link or not link ``crtfastmath.o``.
1967
1968 .. _FLT_EVAL_METHOD:
1969
1970 A note about ``__FLT_EVAL_METHOD__``
1971 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1972 The ``__FLT_EVAL_METHOD__`` is not defined as a traditional macro, and so it
1973 will not appear when dumping preprocessor macros. Instead, the value
1974 ``__FLT_EVAL_METHOD__`` expands to is determined at the point of expansion
1975 either from the value set by the ``-ffp-eval-method`` command line option or
1976 from the target. This is because the ``__FLT_EVAL_METHOD__`` macro
1977 cannot expand to the correct evaluation method in the presence of a ``#pragma``
1978 which alters the evaluation method. An error is issued if
1979 ``__FLT_EVAL_METHOD__`` is expanded inside a scope modified by
1980 ``#pragma clang fp eval_method``.
1981
1982 .. _fp-constant-eval:
1983
1984 A note about Floating Point Constant Evaluation
1985 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1986
1987 In C, the only place floating point operations are guaranteed to be evaluated
1988 during translation is in the initializers of variables of static storage
1989 duration, which are all notionally initialized before the program begins
1990 executing (and thus before a non-default floating point environment can be
1991 entered). But C++ has many more contexts where floating point constant
1992 evaluation occurs. Specifically: for static/thread-local variables,
1993 first try evaluating the initializer in a constant context, including in the
1994 constant floating point environment (just like in C), and then, if that fails,
1995 fall back to emitting runtime code to perform the initialization (which might
1996 in general be in a different floating point environment).
1997
1998 Consider this example when compiled with ``-frounding-math``
1999
2000 .. code-block:: console
2001
2002 constexpr float func_01(float x, float y) {
2003 return x + y;
2004 }
2005 float V1 = func_01(1.0F, 0x0.000001p0F);
2006
2007 The C++ rule is that initializers for static storage duration variables are
2008 first evaluated during translation (therefore, in the default rounding mode),
2009 and only evaluated at runtime (and therefore in the runtime rounding mode) if
2010 the compile-time evaluation fails. This is in line with the C rules;
2011 C11 F.8.5 says: *All computation for automatic initialization is done (as if)
2012 at execution time; thus, it is affected by any operative modes and raises
2013 floating-point exceptions as required by IEC 60559 (provided the state for the
2014 FENV_ACCESS pragma is ‘‘on’’). All computation for initialization of objects
2015 that have static or thread storage duration is done (as if) at translation
2016 time.* C++ generalizes this by adding another phase of initialization
2017 (at runtime) if the translation-time initialization fails, but the
2018 translation-time evaluation of the initializer of succeeds, it will be
2019 treated as a constant initializer.
2020
2021
2022 .. _controlling-code-generation:
2023
2024 Controlling Code Generation
2025 ---------------------------
2026
2027 Clang provides a number of ways to control code generation. The options
2028 are listed below.
2029
2030 .. option:: -f[no-]sanitize=check1,check2,...
2031
2032 Turn on runtime checks for various forms of undefined or suspicious
2033 behavior.
2034
2035 This option controls whether Clang adds runtime checks for various
2036 forms of undefined or suspicious behavior, and is disabled by
2037 default. If a check fails, a diagnostic message is produced at
2038 runtime explaining the problem. The main checks are:
2039
2040 - .. _opt_fsanitize_address:
2041
2042 ``-fsanitize=address``:
2043 :doc:`AddressSanitizer`, a memory error
2044 detector.
2045 - .. _opt_fsanitize_thread:
2046
2047 ``-fsanitize=thread``: :doc:`ThreadSanitizer`, a data race detector.
2048 - .. _opt_fsanitize_memory:
2049
2050 ``-fsanitize=memory``: :doc:`MemorySanitizer`,
2051 a detector of uninitialized reads. Requires instrumentation of all
2052 program code.
2053 - .. _opt_fsanitize_undefined:
2054
2055 ``-fsanitize=undefined``: :doc:`UndefinedBehaviorSanitizer`,
2056 a fast and compatible undefined behavior checker.
2057
2058 - ``-fsanitize=dataflow``: :doc:`DataFlowSanitizer`, a general data
2059 flow analysis.
2060 - ``-fsanitize=cfi``: :doc:`control flow integrity <ControlFlowIntegrity>`
2061 checks. Requires ``-flto``.
2062 - ``-fsanitize=kcfi``: kernel indirect call forward-edge control flow
2063 integrity.
2064 - ``-fsanitize=safe-stack``: :doc:`safe stack <SafeStack>`
2065 protection against stack-based memory corruption errors.
2066
2067 There are more fine-grained checks available: see
2068 the :ref:`list <ubsan-checks>` of specific kinds of
2069 undefined behavior that can be detected and the :ref:`list <cfi-schemes>`
2070 of control flow integrity schemes.
2071
2072 The ``-fsanitize=`` argument must also be provided when linking, in
2073 order to link to the appropriate runtime library.
2074
2075 It is not possible to combine more than one of the ``-fsanitize=address``,
2076 ``-fsanitize=thread``, and ``-fsanitize=memory`` checkers in the same
2077 program.
2078
2079 .. option:: -f[no-]sanitize-recover=check1,check2,...
2080
2081 .. option:: -f[no-]sanitize-recover[=all]
2082
2083 Controls which checks enabled by ``-fsanitize=`` flag are non-fatal.
2084 If the check is fatal, program will halt after the first error
2085 of this kind is detected and error report is printed.
2086
2087 By default, non-fatal checks are those enabled by
2088 :doc:`UndefinedBehaviorSanitizer`,
2089 except for ``-fsanitize=return`` and ``-fsanitize=unreachable``. Some
2090 sanitizers may not support recovery (or not support it by default
2091 e.g. :doc:`AddressSanitizer`), and always crash the program after the issue
2092 is detected.
2093
2094 Note that the ``-fsanitize-trap`` flag has precedence over this flag.
2095 This means that if a check has been configured to trap elsewhere on the
2096 command line, or if the check traps by default, this flag will not have
2097 any effect unless that sanitizer's trapping behavior is disabled with
2098 ``-fno-sanitize-trap``.
2099
2100 For example, if a command line contains the flags ``-fsanitize=undefined
2101 -fsanitize-trap=undefined``, the flag ``-fsanitize-recover=alignment``
2102 will have no effect on its own; it will need to be accompanied by
2103 ``-fno-sanitize-trap=alignment``.
2104
2105 .. option:: -f[no-]sanitize-trap=check1,check2,...
2106
2107 .. option:: -f[no-]sanitize-trap[=all]
2108
2109 Controls which checks enabled by the ``-fsanitize=`` flag trap. This
2110 option is intended for use in cases where the sanitizer runtime cannot
2111 be used (for instance, when building libc or a kernel module), or where
2112 the binary size increase caused by the sanitizer runtime is a concern.
2113
2114 This flag is only compatible with :doc:`control flow integrity
2115 <ControlFlowIntegrity>` schemes and :doc:`UndefinedBehaviorSanitizer`
2116 checks other than ``vptr``.
2117
2118 This flag is enabled by default for sanitizers in the ``cfi`` group.
2119
2120 .. option:: -fsanitize-ignorelist=/path/to/ignorelist/file
2121
2122 Disable or modify sanitizer checks for objects (source files, functions,
2123 variables, types) listed in the file. See
2124 :doc:`SanitizerSpecialCaseList` for file format description.
2125
2126 .. option:: -fno-sanitize-ignorelist
2127
2128 Don't use ignorelist file, if it was specified earlier in the command line.
2129
2130 .. option:: -f[no-]sanitize-coverage=[type,features,...]
2131
2132 Enable simple code coverage in addition to certain sanitizers.
2133 See :doc:`SanitizerCoverage` for more details.
2134
2135 .. option:: -f[no-]sanitize-address-outline-instrumentation
2136
2137 Controls how address sanitizer code is generated. If enabled will always use
2138 a function call instead of inlining the code. Turning this option on could
2139 reduce the binary size, but might result in a worse run-time performance.
2140
2141 See :doc: `AddressSanitizer` for more details.
2142
2143 .. option:: -f[no-]sanitize-stats
2144
2145 Enable simple statistics gathering for the enabled sanitizers.
2146 See :doc:`SanitizerStats` for more details.
2147
2148 .. option:: -fsanitize-undefined-trap-on-error
2149
2150 Deprecated alias for ``-fsanitize-trap=undefined``.
2151
2152 .. option:: -fsanitize-cfi-cross-dso
2153
2154 Enable cross-DSO control flow integrity checks. This flag modifies
2155 the behavior of sanitizers in the ``cfi`` group to allow checking
2156 of cross-DSO virtual and indirect calls.
2157
2158 .. option:: -fsanitize-cfi-icall-generalize-pointers
2159
2160 Generalize pointers in return and argument types in function type signatures
2161 checked by Control Flow Integrity indirect call checking. See
2162 :doc:`ControlFlowIntegrity` for more details.
2163
2164 .. option:: -fsanitize-cfi-icall-experimental-normalize-integers
2165
2166 Normalize integers in return and argument types in function type signatures
2167 checked by Control Flow Integrity indirect call checking. See
2168 :doc:`ControlFlowIntegrity` for more details.
2169
2170 This option is currently experimental.
2171
2172 .. option:: -fstrict-vtable-pointers
2173
2174 Enable optimizations based on the strict rules for overwriting polymorphic
2175 C++ objects, i.e. the vptr is invariant during an object's lifetime.
2176 This enables better devirtualization. Turned off by default, because it is
2177 still experimental.
2178
2179 .. option:: -fwhole-program-vtables
2180
2181 Enable whole-program vtable optimizations, such as single-implementation
2182 devirtualization and virtual constant propagation, for classes with
2183 :doc:`hidden LTO visibility <LTOVisibility>`. Requires ``-flto``.
2184
2185 .. option:: -f[no]split-lto-unit
2186
2187 Controls splitting the :doc:`LTO unit <LTOVisibility>` into regular LTO and
2188 :doc:`ThinLTO` portions, when compiling with -flto=thin. Defaults to false
2189 unless ``-fsanitize=cfi`` or ``-fwhole-program-vtables`` are specified, in
2190 which case it defaults to true. Splitting is required with ``fsanitize=cfi``,
2191 and it is an error to disable via ``-fno-split-lto-unit``. Splitting is
2192 optional with ``-fwhole-program-vtables``, however, it enables more
2193 aggressive whole program vtable optimizations (specifically virtual constant
2194 propagation).
2195
2196 When enabled, vtable definitions and select virtual functions are placed
2197 in the split regular LTO module, enabling more aggressive whole program
2198 vtable optimizations required for CFI and virtual constant propagation.
2199 However, this can increase the LTO link time and memory requirements over
2200 pure ThinLTO, as all split regular LTO modules are merged and LTO linked
2201 with regular LTO.
2202
2203 .. option:: -fforce-emit-vtables
2204
2205 In order to improve devirtualization, forces emitting of vtables even in
2206 modules where it isn't necessary. It causes more inline virtual functions
2207 to be emitted.
2208
2209 .. option:: -fno-assume-sane-operator-new
2210
2211 Don't assume that the C++'s new operator is sane.
2212
2213 This option tells the compiler to do not assume that C++'s global
2214 new operator will always return a pointer that does not alias any
2215 other pointer when the function returns.
2216
2217 .. option:: -fassume-nothrow-exception-dtor
2218
2219 Assume that an exception object' destructor will not throw, and generate
2220 less code for catch handlers. A throw expression of a type with a
2221 potentially-throwing destructor will lead to an error.
2222
2223 By default, Clang assumes that the exception object may have a throwing
2224 destructor. For the Itanium C++ ABI, Clang generates a landing pad to
2225 destroy local variables and call ``_Unwind_Resume`` for the code
2226 ``catch (...) { ... }``. This option tells Clang that an exception object's
2227 destructor will not throw and code simplification is possible.
2228
2229 .. option:: -ftrap-function=[name]
2230
2231 Instruct code generator to emit a function call to the specified
2232 function name for ``__builtin_trap()``.
2233
2234 LLVM code generator translates ``__builtin_trap()`` to a trap
2235 instruction if it is supported by the target ISA. Otherwise, the
2236 builtin is translated into a call to ``abort``. If this option is
2237 set, then the code generator will always lower the builtin to a call
2238 to the specified function regardless of whether the target ISA has a
2239 trap instruction. This option is useful for environments (e.g.
2240 deeply embedded) where a trap cannot be properly handled, or when
2241 some custom behavior is desired.
2242
2243 .. option:: -ftls-model=[model]
2244
2245 Select which TLS model to use.
2246
2247 Valid values are: ``global-dynamic``, ``local-dynamic``,
2248 ``initial-exec`` and ``local-exec``. The default value is
2249 ``global-dynamic``. The compiler may use a different model if the
2250 selected model is not supported by the target, or if a more
2251 efficient model can be used. The TLS model can be overridden per
2252 variable using the ``tls_model`` attribute.
2253
2254 .. option:: -femulated-tls
2255
2256 Select emulated TLS model, which overrides all -ftls-model choices.
2257
2258 In emulated TLS mode, all access to TLS variables are converted to
2259 calls to __emutls_get_address in the runtime library.
2260
2261 .. option:: -mhwdiv=[values]
2262
2263 Select the ARM modes (arm or thumb) that support hardware division
2264 instructions.
2265
2266 Valid values are: ``arm``, ``thumb`` and ``arm,thumb``.
2267 This option is used to indicate which mode (arm or thumb) supports
2268 hardware division instructions. This only applies to the ARM
2269 architecture.
2270
2271 .. option:: -m[no-]crc
2272
2273 Enable or disable CRC instructions.
2274
2275 This option is used to indicate whether CRC instructions are to
2276 be generated. This only applies to the ARM architecture.
2277
2278 CRC instructions are enabled by default on ARMv8.
2279
2280 .. option:: -mgeneral-regs-only
2281
2282 Generate code which only uses the general purpose registers.
2283
2284 This option restricts the generated code to use general registers
2285 only. This only applies to the AArch64 architecture.
2286
2287 .. option:: -mcompact-branches=[values]
2288
2289 Control the usage of compact branches for MIPSR6.
2290
2291 Valid values are: ``never``, ``optimal`` and ``always``.
2292 The default value is ``optimal`` which generates compact branches
2293 when a delay slot cannot be filled. ``never`` disables the usage of
2294 compact branches and ``always`` generates compact branches whenever
2295 possible.
2296
2297 .. option:: -f[no-]max-type-align=[number]
2298
2299 Instruct the code generator to not enforce a higher alignment than the given
2300 number (of bytes) when accessing memory via an opaque pointer or reference.
2301 This cap is ignored when directly accessing a variable or when the pointee
2302 type has an explicit “aligned” attribute.
2303
2304 The value should usually be determined by the properties of the system allocator.
2305 Some builtin types, especially vector types, have very high natural alignments;
2306 when working with values of those types, Clang usually wants to use instructions
2307 that take advantage of that alignment. However, many system allocators do
2308 not promise to return memory that is more than 8-byte or 16-byte-aligned. Use
2309 this option to limit the alignment that the compiler can assume for an arbitrary
2310 pointer, which may point onto the heap.
2311
2312 This option does not affect the ABI alignment of types; the layout of structs and
2313 unions and the value returned by the alignof operator remain the same.
2314
2315 This option can be overridden on a case-by-case basis by putting an explicit
2316 “aligned” alignment on a struct, union, or typedef. For example:
2317
2318 .. code-block:: console
2319
2320 #include <immintrin.h>
2321 // Make an aligned typedef of the AVX-512 16-int vector type.
2322 typedef __v16si __aligned_v16si __attribute__((aligned(64)));
2323
2324 void initialize_vector(__aligned_v16si *v) {
2325 // The compiler may assume that ‘v’ is 64-byte aligned, regardless of the
2326 // value of -fmax-type-align.
2327 }
2328
2329 .. option:: -faddrsig, -fno-addrsig
2330
2331 Controls whether Clang emits an address-significance table into the object
2332 file. Address-significance tables allow linkers to implement `safe ICF
2333 <https://research.google.com/pubs/archive/36912.pdf>`_ without the false
2334 positives that can result from other implementation techniques such as
2335 relocation scanning. Address-significance tables are enabled by default
2336 on ELF targets when using the integrated assembler. This flag currently
2337 only has an effect on ELF targets.
2338
2339 .. _funique_internal_linkage_names:
2340
2341 .. option:: -f[no]-unique-internal-linkage-names
2342
2343 Controls whether Clang emits a unique (best-effort) symbol name for internal
2344 linkage symbols. When this option is set, compiler hashes the main source
2345 file path from the command line and appends it to all internal symbols. If a
2346 program contains multiple objects compiled with the same command-line source
2347 file path, the symbols are not guaranteed to be unique. This option is
2348 particularly useful in attributing profile information to the correct
2349 function when multiple functions with the same private linkage name exist
2350 in the binary.
2351
2352 It should be noted that this option cannot guarantee uniqueness and the
2353 following is an example where it is not unique when two modules contain
2354 symbols with the same private linkage name:
2355
2356 .. code-block:: console
2357
2358 $ cd $P/foo && clang -c -funique-internal-linkage-names name_conflict.c
2359 $ cd $P/bar && clang -c -funique-internal-linkage-names name_conflict.c
2360 $ cd $P && clang foo/name_conflict.o && bar/name_conflict.o
2361
2362 .. option:: -fbasic-block-sections=[labels, all, list=<arg>, none]
2363
2364 Controls how Clang emits text sections for basic blocks. With values ``all``
2365 and ``list=<arg>``, each basic block or a subset of basic blocks can be placed
2366 in its own unique section. With the "labels" value, normal text sections are
2367 emitted, but a ``.bb_addr_map`` section is emitted which includes address
2368 offsets for each basic block in the program, relative to the parent function
2369 address.
2370
2371 With the ``list=<arg>`` option, a file containing the subset of basic blocks
2372 that need to placed in unique sections can be specified. The format of the
2373 file is as follows. For example, ``list=spec.txt`` where ``spec.txt`` is the
2374 following:
2375
2376 ::
2377
2378 !foo
2379 !!2
2380 !_Z3barv
2381
2382 will place the machine basic block with ``id 2`` in function ``foo`` in a
2383 unique section. It will also place all basic blocks of functions ``bar``
2384 in unique sections.
2385
2386 Further, section clusters can also be specified using the ``list=<arg>``
2387 option. For example, ``list=spec.txt`` where ``spec.txt`` contains:
2388
2389 ::
2390
2391 !foo
2392 !!1 !!3 !!5
2393 !!2 !!4 !!6
2394
2395 will create two unique sections for function ``foo`` with the first
2396 containing the odd numbered basic blocks and the second containing the
2397 even numbered basic blocks.
2398
2399 Basic block sections allow the linker to reorder basic blocks and enables
2400 link-time optimizations like whole program inter-procedural basic block
2401 reordering.
2402
2403 Profile Guided Optimization
2404 ---------------------------
2405
2406 Profile information enables better optimization. For example, knowing that a
2407 branch is taken very frequently helps the compiler make better decisions when
2408 ordering basic blocks. Knowing that a function ``foo`` is called more
2409 frequently than another function ``bar`` helps the inliner. Optimization
2410 levels ``-O2`` and above are recommended for use of profile guided optimization.
2411
2412 Clang supports profile guided optimization with two different kinds of
2413 profiling. A sampling profiler can generate a profile with very low runtime
2414 overhead, or you can build an instrumented version of the code that collects
2415 more detailed profile information. Both kinds of profiles can provide execution
2416 counts for instructions in the code and information on branches taken and
2417 function invocation.
2418
2419 Regardless of which kind of profiling you use, be careful to collect profiles
2420 by running your code with inputs that are representative of the typical
2421 behavior. Code that is not exercised in the profile will be optimized as if it
2422 is unimportant, and the compiler may make poor optimization choices for code
2423 that is disproportionately used while profiling.
2424
2425 Differences Between Sampling and Instrumentation
2426 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2427
2428 Although both techniques are used for similar purposes, there are important
2429 differences between the two:
2430
2431 1. Profile data generated with one cannot be used by the other, and there is no
2432 conversion tool that can convert one to the other. So, a profile generated
2433 via ``-fprofile-generate`` or ``-fprofile-instr-generate`` must be used with
2434 ``-fprofile-use`` or ``-fprofile-instr-use``. Similarly, sampling profiles
2435 generated by external profilers must be converted and used with ``-fprofile-sample-use``
2436 or ``-fauto-profile``.
2437
2438 2. Instrumentation profile data can be used for code coverage analysis and
2439 optimization.
2440
2441 3. Sampling profiles can only be used for optimization. They cannot be used for
2442 code coverage analysis. Although it would be technically possible to use
2443 sampling profiles for code coverage, sample-based profiles are too
2444 coarse-grained for code coverage purposes; it would yield poor results.
2445
2446 4. Sampling profiles must be generated by an external tool. The profile
2447 generated by that tool must then be converted into a format that can be read
2448 by LLVM. The section on sampling profilers describes one of the supported
2449 sampling profile formats.
2450
2451
2452 Using Sampling Profilers
2453 ^^^^^^^^^^^^^^^^^^^^^^^^
2454
2455 Sampling profilers are used to collect runtime information, such as
2456 hardware counters, while your application executes. They are typically
2457 very efficient and do not incur a large runtime overhead. The
2458 sample data collected by the profiler can be used during compilation
2459 to determine what the most executed areas of the code are.
2460
2461 Using the data from a sample profiler requires some changes in the way
2462 a program is built. Before the compiler can use profiling information,
2463 the code needs to execute under the profiler. The following is the
2464 usual build cycle when using sample profilers for optimization:
2465
2466 1. Build the code with source line table information. You can use all the
2467 usual build flags that you always build your application with. The only
2468 requirement is that DWARF debug info including source line information is
2469 generated. This DWARF information is important for the profiler to be able
2470 to map instructions back to source line locations. The usefulness of this
2471 DWARF information can be improved with the ``-fdebug-info-for-profiling``
2472 and ``-funique-internal-linkage-names`` options.
2473
2474 On Linux:
2475
2476 .. code-block:: console
2477
2478 $ clang++ -O2 -gline-tables-only \
2479 -fdebug-info-for-profiling -funique-internal-linkage-names \
2480 code.cc -o code
2481
2482 While MSVC-style targets default to CodeView debug information, DWARF debug
2483 information is required to generate source-level LLVM profiles. Use
2484 ``-gdwarf`` to include DWARF debug information:
2485
2486 .. code-block:: winbatch
2487
2488 > clang-cl /O2 -gdwarf -gline-tables-only ^
2489 /clang:-fdebug-info-for-profiling /clang:-funique-internal-linkage-names ^
2490 code.cc /Fe:code /fuse-ld=lld /link /debug:dwarf
2491
2492 .. note::
2493
2494 :ref:`-funique-internal-linkage-names <funique_internal_linkage_names>`
2495 generates unique names based on given command-line source file paths. If
2496 your build system uses absolute source paths and these paths may change
2497 between steps 1 and 4, then the uniqued function names may change and result
2498 in unused profile data. Consider omitting this option in such cases.
2499
2500 2. Run the executable under a sampling profiler. The specific profiler
2501 you use does not really matter, as long as its output can be converted
2502 into the format that the LLVM optimizer understands.
2503
2504 Two such profilers are the Linux Perf profiler
2505 (https://perf.wiki.kernel.org/) and Intel's Sampling Enabling Product (SEP),
2506 available as part of `Intel VTune
2507 <https://software.intel.com/content/www/us/en/develop/tools/oneapi/components/vtune-profiler.html>`_.
2508 While Perf is Linux-specific, SEP can be used on Linux, Windows, and FreeBSD.
2509
2510 The LLVM tool ``llvm-profgen`` can convert output of either Perf or SEP. An
2511 external project, `AutoFDO <https://github.com/google/autofdo>`_, also
2512 provides a ``create_llvm_prof`` tool which supports Linux Perf output.
2513
2514 When using Perf:
2515
2516 .. code-block:: console
2517
2518 $ perf record -b -e BR_INST_RETIRED.NEAR_TAKEN:uppp ./code
2519
2520 If the event above is unavailable, ``branches:u`` is probably next-best.
2521
2522 Note the use of the ``-b`` flag. This tells Perf to use the Last Branch
2523 Record (LBR) to record call chains. While this is not strictly required,
2524 it provides better call information, which improves the accuracy of
2525 the profile data.
2526
2527 When using SEP:
2528
2529 .. code-block:: console
2530
2531 $ sep -start -out code.tb7 -ec BR_INST_RETIRED.NEAR_TAKEN:precise=yes:pdir -lbr no_filter:usr -perf-script brstack -app ./code
2532
2533 This produces a ``code.perf.data.script`` output which can be used with
2534 ``llvm-profgen``'s ``--perfscript`` input option.
2535
2536 3. Convert the collected profile data to LLVM's sample profile format. This is
2537 currently supported via the `AutoFDO <https://github.com/google/autofdo>`_
2538 converter ``create_llvm_prof``. Once built and installed, you can convert
2539 the ``perf.data`` file to LLVM using the command:
2540
2541 .. code-block:: console
2542
2543 $ create_llvm_prof --binary=./code --out=code.prof
2544
2545 This will read ``perf.data`` and the binary file ``./code`` and emit
2546 the profile data in ``code.prof``. Note that if you ran ``perf``
2547 without the ``-b`` flag, you need to use ``--use_lbr=false`` when
2548 calling ``create_llvm_prof``.
2549
2550 Alternatively, the LLVM tool ``llvm-profgen`` can also be used to generate
2551 the LLVM sample profile:
2552
2553 .. code-block:: console
2554
2555 $ llvm-profgen --binary=./code --output=code.prof --perfdata=perf.data
2556
2557 When using SEP the output is in the textual format corresponding to
2558 ``llvm-profgen --perfscript``. For example:
2559
2560 .. code-block:: console
2561
2562 $ llvm-profgen --binary=./code --output=code.prof --perfscript=code.perf.data.script
2563
2564
2565 4. Build the code again using the collected profile. This step feeds
2566 the profile back to the optimizers. This should result in a binary
2567 that executes faster than the original one. Note that you are not
2568 required to build the code with the exact same arguments that you
2569 used in the first step. The only requirement is that you build the code
2570 with the same debug info options and ``-fprofile-sample-use``.
2571
2572 On Linux:
2573
2574 .. code-block:: console
2575
2576 $ clang++ -O2 -gline-tables-only \
2577 -fdebug-info-for-profiling -funique-internal-linkage-names \
2578 -fprofile-sample-use=code.prof code.cc -o code
2579
2580 On Windows:
2581
2582 .. code-block:: winbatch
2583
2584 > clang-cl /O2 -gdwarf -gline-tables-only ^
2585 /clang:-fdebug-info-for-profiling /clang:-funique-internal-linkage-names ^
2586 /fprofile-sample-use=code.prof code.cc /Fe:code /fuse-ld=lld /link /debug:dwarf
2587
2588 [OPTIONAL] Sampling-based profiles can have inaccuracies or missing block/
2589 edge counters. The profile inference algorithm (profi) can be used to infer
2590 missing blocks and edge counts, and improve the quality of profile data.
2591 Enable it with ``-fsample-profile-use-profi``. For example, on Linux:
2592
2593 .. code-block:: console
2594
2595 $ clang++ -fsample-profile-use-profi -O2 -gline-tables-only \
2596 -fdebug-info-for-profiling -funique-internal-linkage-names \
2597 -fprofile-sample-use=code.prof code.cc -o code
2598
2599 On Windows:
2600
2601 .. code-block:: winbatch
2602
2603 > clang-cl /clang:-fsample-profile-use-profi /O2 -gdwarf -gline-tables-only ^
2604 /clang:-fdebug-info-for-profiling /clang:-funique-internal-linkage-names ^
2605 /fprofile-sample-use=code.prof code.cc /Fe:code /fuse-ld=lld /link /debug:dwarf
2606
2607 Sample Profile Formats
2608 """"""""""""""""""""""
2609
2610 Since external profilers generate profile data in a variety of custom formats,
2611 the data generated by the profiler must be converted into a format that can be
2612 read by the backend. LLVM supports three different sample profile formats:
2613
2614 1. ASCII text. This is the easiest one to generate. The file is divided into
2615 sections, which correspond to each of the functions with profile
2616 information. The format is described below. It can also be generated from
2617 the binary or gcov formats using the ``llvm-profdata`` tool.
2618
2619 2. Binary encoding. This uses a more efficient encoding that yields smaller
2620 profile files. This is the format generated by the ``create_llvm_prof`` tool
2621 in https://github.com/google/autofdo.
2622
2623 3. GCC encoding. This is based on the gcov format, which is accepted by GCC. It
2624 is only interesting in environments where GCC and Clang co-exist. This
2625 encoding is only generated by the ``create_gcov`` tool in
2626 https://github.com/google/autofdo. It can be read by LLVM and
2627 ``llvm-profdata``, but it cannot be generated by either.
2628
2629 If you are using Linux Perf to generate sampling profiles, you can use the
2630 conversion tool ``create_llvm_prof`` described in the previous section.
2631 Otherwise, you will need to write a conversion tool that converts your
2632 profiler's native format into one of these three.
2633
2634
2635 Sample Profile Text Format
2636 """"""""""""""""""""""""""
2637
2638 This section describes the ASCII text format for sampling profiles. It is,
2639 arguably, the easiest one to generate. If you are interested in generating any
2640 of the other two, consult the ``ProfileData`` library in LLVM's source tree
2641 (specifically, ``include/llvm/ProfileData/SampleProfReader.h``).
2642
2643 .. code-block:: console
2644
2645 function1:total_samples:total_head_samples
2646 offset1[.discriminator]: number_of_samples [fn1:num fn2:num ... ]
2647 offset2[.discriminator]: number_of_samples [fn3:num fn4:num ... ]
2648 ...
2649 offsetN[.discriminator]: number_of_samples [fn5:num fn6:num ... ]
2650 offsetA[.discriminator]: fnA:num_of_total_samples
2651 offsetA1[.discriminator]: number_of_samples [fn7:num fn8:num ... ]
2652 offsetA1[.discriminator]: number_of_samples [fn9:num fn10:num ... ]
2653 offsetB[.discriminator]: fnB:num_of_total_samples
2654 offsetB1[.discriminator]: number_of_samples [fn11:num fn12:num ... ]
2655
2656 This is a nested tree in which the indentation represents the nesting level
2657 of the inline stack. There are no blank lines in the file. And the spacing
2658 within a single line is fixed. Additional spaces will result in an error
2659 while reading the file.
2660
2661 Any line starting with the '#' character is completely ignored.
2662
2663 Inlined calls are represented with indentation. The Inline stack is a
2664 stack of source locations in which the top of the stack represents the
2665 leaf function, and the bottom of the stack represents the actual
2666 symbol to which the instruction belongs.
2667
2668 Function names must be mangled in order for the profile loader to
2669 match them in the current translation unit. The two numbers in the
2670 function header specify how many total samples were accumulated in the
2671 function (first number), and the total number of samples accumulated
2672 in the prologue of the function (second number). This head sample
2673 count provides an indicator of how frequently the function is invoked.
2674
2675 There are two types of lines in the function body.
2676
2677 - Sampled line represents the profile information of a source location.
2678 ``offsetN[.discriminator]: number_of_samples [fn5:num fn6:num ... ]``
2679
2680 - Callsite line represents the profile information of an inlined callsite.
2681 ``offsetA[.discriminator]: fnA:num_of_total_samples``
2682
2683 Each sampled line may contain several items. Some are optional (marked
2684 below):
2685
2686 a. Source line offset. This number represents the line number
2687 in the function where the sample was collected. The line number is
2688 always relative to the line where symbol of the function is
2689 defined. So, if the function has its header at line 280, the offset
2690 13 is at line 293 in the file.
2691
2692 Note that this offset should never be a negative number. This could
2693 happen in cases like macros. The debug machinery will register the
2694 line number at the point of macro expansion. So, if the macro was
2695 expanded in a line before the start of the function, the profile
2696 converter should emit a 0 as the offset (this means that the optimizers
2697 will not be able to associate a meaningful weight to the instructions
2698 in the macro).
2699
2700 b. [OPTIONAL] Discriminator. This is used if the sampled program
2701 was compiled with DWARF discriminator support
2702 (http://wiki.dwarfstd.org/index.php?title=Path_Discriminators).
2703 DWARF discriminators are unsigned integer values that allow the
2704 compiler to distinguish between multiple execution paths on the
2705 same source line location.
2706
2707 For example, consider the line of code ``if (cond) foo(); else bar();``.
2708 If the predicate ``cond`` is true 80% of the time, then the edge
2709 into function ``foo`` should be considered to be taken most of the
2710 time. But both calls to ``foo`` and ``bar`` are at the same source
2711 line, so a sample count at that line is not sufficient. The
2712 compiler needs to know which part of that line is taken more
2713 frequently.
2714
2715 This is what discriminators provide. In this case, the calls to
2716 ``foo`` and ``bar`` will be at the same line, but will have
2717 different discriminator values. This allows the compiler to correctly
2718 set edge weights into ``foo`` and ``bar``.
2719
2720 c. Number of samples. This is an integer quantity representing the
2721 number of samples collected by the profiler at this source
2722 location.
2723
2724 d. [OPTIONAL] Potential call targets and samples. If present, this
2725 line contains a call instruction. This models both direct and
2726 number of samples. For example,
2727
2728 .. code-block:: console
2729
2730 130: 7 foo:3 bar:2 baz:7
2731
2732 The above means that at relative line offset 130 there is a call
2733 instruction that calls one of ``foo()``, ``bar()`` and ``baz()``,
2734 with ``baz()`` being the relatively more frequently called target.
2735
2736 As an example, consider a program with the call chain ``main -> foo -> bar``.
2737 When built with optimizations enabled, the compiler may inline the
2738 calls to ``bar`` and ``foo`` inside ``main``. The generated profile
2739 could then be something like this:
2740
2741 .. code-block:: console
2742
2743 main:35504:0
2744 1: _Z3foov:35504
2745 2: _Z32bari:31977
2746 1.1: 31977
2747 2: 0
2748
2749 This profile indicates that there were a total of 35,504 samples
2750 collected in main. All of those were at line 1 (the call to ``foo``).
2751 Of those, 31,977 were spent inside the body of ``bar``. The last line
2752 of the profile (``2: 0``) corresponds to line 2 inside ``main``. No
2753 samples were collected there.
2754
2755 .. _prof_instr:
2756
2757 Profiling with Instrumentation
2758 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2759
2760 Clang also supports profiling via instrumentation. This requires building a
2761 special instrumented version of the code and has some runtime
2762 overhead during the profiling, but it provides more detailed results than a
2763 sampling profiler. It also provides reproducible results, at least to the
2764 extent that the code behaves consistently across runs.
2765
2766 Clang supports two types of instrumentation: frontend-based and IR-based.
2767 Frontend-based instrumentation can be enabled with the option ``-fprofile-instr-generate``,
2768 and IR-based instrumentation can be enabled with the option ``-fprofile-generate``.
2769 For best performance with PGO, IR-based instrumentation should be used. It has
2770 the benefits of lower instrumentation overhead, smaller raw profile size, and
2771 better runtime performance. Frontend-based instrumentation, on the other hand,
2772 has better source correlation, so it should be used with source line-based
2773 coverage testing.
2774
2775 The flag ``-fcs-profile-generate`` also instruments programs using the same
2776 instrumentation method as ``-fprofile-generate``. However, it performs a
2777 post-inline late instrumentation and can produce context-sensitive profiles.
2778
2779
2780 Here are the steps for using profile guided optimization with
2781 instrumentation:
2782
2783 1. Build an instrumented version of the code by compiling and linking with the
2784 ``-fprofile-generate`` or ``-fprofile-instr-generate`` option.
2785
2786 .. code-block:: console
2787
2788 $ clang++ -O2 -fprofile-instr-generate code.cc -o code
2789
2790 2. Run the instrumented executable with inputs that reflect the typical usage.
2791 By default, the profile data will be written to a ``default.profraw`` file
2792 in the current directory. You can override that default by using option
2793 ``-fprofile-instr-generate=`` or by setting the ``LLVM_PROFILE_FILE``
2794 environment variable to specify an alternate file. If non-default file name
2795 is specified by both the environment variable and the command line option,
2796 the environment variable takes precedence. The file name pattern specified
2797 can include different modifiers: ``%p``, ``%h``, ``%m``, ``%t``, and ``%c``.
2798
2799 Any instance of ``%p`` in that file name will be replaced by the process
2800 ID, so that you can easily distinguish the profile output from multiple
2801 runs.
2802
2803 .. code-block:: console
2804
2805 $ LLVM_PROFILE_FILE="code-%p.profraw" ./code
2806
2807 The modifier ``%h`` can be used in scenarios where the same instrumented
2808 binary is run in multiple different host machines dumping profile data
2809 to a shared network based storage. The ``%h`` specifier will be substituted
2810 with the hostname so that profiles collected from different hosts do not
2811 clobber each other.
2812
2813 While the use of ``%p`` specifier can reduce the likelihood for the profiles
2814 dumped from different processes to clobber each other, such clobbering can still
2815 happen because of the ``pid`` re-use by the OS. Another side-effect of using
2816 ``%p`` is that the storage requirement for raw profile data files is greatly
2817 increased. To avoid issues like this, the ``%m`` specifier can used in the profile
2818 name. When this specifier is used, the profiler runtime will substitute ``%m``
2819 with a unique integer identifier associated with the instrumented binary. Additionally,
2820 multiple raw profiles dumped from different processes that share a file system (can be
2821 on different hosts) will be automatically merged by the profiler runtime during the
2822 dumping. If the program links in multiple instrumented shared libraries, each library
2823 will dump the profile data into its own profile data file (with its unique integer
2824 id embedded in the profile name). Note that the merging enabled by ``%m`` is for raw
2825 profile data generated by profiler runtime. The resulting merged "raw" profile data
2826 file still needs to be converted to a different format expected by the compiler (
2827 see step 3 below).
2828
2829 .. code-block:: console
2830
2831 $ LLVM_PROFILE_FILE="code-%m.profraw" ./code
2832
2833 See `this <SourceBasedCodeCoverage.html#running-the-instrumented-program>`_ section
2834 about the ``%t``, and ``%c`` modifiers.
2835
2836 3. Combine profiles from multiple runs and convert the "raw" profile format to
2837 the input expected by clang. Use the ``merge`` command of the
2838 ``llvm-profdata`` tool to do this.
2839
2840 .. code-block:: console
2841
2842 $ llvm-profdata merge -output=code.profdata code-*.profraw
2843
2844 Note that this step is necessary even when there is only one "raw" profile,
2845 since the merge operation also changes the file format.
2846
2847 4. Build the code again using the ``-fprofile-use`` or ``-fprofile-instr-use``
2848 option to specify the collected profile data.
2849
2850 .. code-block:: console
2851
2852 $ clang++ -O2 -fprofile-instr-use=code.profdata code.cc -o code
2853
2854 You can repeat step 4 as often as you like without regenerating the
2855 profile. As you make changes to your code, clang may no longer be able to
2856 use the profile data. It will warn you when this happens.
2857
2858 Note that ``-fprofile-use`` option is semantically equivalent to
2859 its GCC counterpart, it *does not* handle profile formats produced by GCC.
2860 Both ``-fprofile-use`` and ``-fprofile-instr-use`` accept profiles in the
2861 indexed format, regardeless whether it is produced by frontend or the IR pass.
2862
2863 .. option:: -fprofile-generate[=<dirname>]
2864
2865 The ``-fprofile-generate`` and ``-fprofile-generate=`` flags will use
2866 an alternative instrumentation method for profile generation. When
2867 given a directory name, it generates the profile file
2868 ``default_%m.profraw`` in the directory named ``dirname`` if specified.
2869 If ``dirname`` does not exist, it will be created at runtime. ``%m`` specifier
2870 will be substituted with a unique id documented in step 2 above. In other words,
2871 with ``-fprofile-generate[=<dirname>]`` option, the "raw" profile data automatic
2872 merging is turned on by default, so there will no longer any risk of profile
2873 clobbering from different running processes. For example,
2874
2875 .. code-block:: console
2876
2877 $ clang++ -O2 -fprofile-generate=yyy/zzz code.cc -o code
2878
2879 When ``code`` is executed, the profile will be written to the file
2880 ``yyy/zzz/default_xxxx.profraw``.
2881
2882 To generate the profile data file with the compiler readable format, the
2883 ``llvm-profdata`` tool can be used with the profile directory as the input:
2884
2885 .. code-block:: console
2886
2887 $ llvm-profdata merge -output=code.profdata yyy/zzz/
2888
2889 If the user wants to turn off the auto-merging feature, or simply override the
2890 the profile dumping path specified at command line, the environment variable
2891 ``LLVM_PROFILE_FILE`` can still be used to override
2892 the directory and filename for the profile file at runtime.
2893 To override the path and filename at compile time, use
2894 ``-Xclang -fprofile-instrument-path=/path/to/file_pattern.profraw``.
2895
2896 .. option:: -fcs-profile-generate[=<dirname>]
2897
2898 The ``-fcs-profile-generate`` and ``-fcs-profile-generate=`` flags will use
2899 the same instrumentation method, and generate the same profile as in the
2900 ``-fprofile-generate`` and ``-fprofile-generate=`` flags. The difference is
2901 that the instrumentation is performed after inlining so that the resulted
2902 profile has a better context sensitive information. They cannot be used
2903 together with ``-fprofile-generate`` and ``-fprofile-generate=`` flags.
2904 They are typically used in conjunction with ``-fprofile-use`` flag.
2905 The profile generated by ``-fcs-profile-generate`` and ``-fprofile-generate``
2906 can be merged by llvm-profdata. A use example:
2907
2908 .. code-block:: console
2909
2910 $ clang++ -O2 -fprofile-generate=yyy/zzz code.cc -o code
2911 $ ./code
2912 $ llvm-profdata merge -output=code.profdata yyy/zzz/
2913
2914 The first few steps are the same as that in ``-fprofile-generate``
2915 compilation. Then perform a second round of instrumentation.
2916
2917 .. code-block:: console
2918
2919 $ clang++ -O2 -fprofile-use=code.profdata -fcs-profile-generate=sss/ttt \
2920 -o cs_code
2921 $ ./cs_code
2922 $ llvm-profdata merge -output=cs_code.profdata sss/ttt code.profdata
2923
2924 The resulted ``cs_code.prodata`` combines ``code.profdata`` and the profile
2925 generated from binary ``cs_code``. Profile ``cs_code.profata`` can be used by
2926 ``-fprofile-use`` compilation.
2927
2928 .. code-block:: console
2929
2930 $ clang++ -O2 -fprofile-use=cs_code.profdata
2931
2932 The above command will read both profiles to the compiler at the identical
2933 point of instrumentations.
2934
2935 .. option:: -fprofile-use[=<pathname>]
2936
2937 Without any other arguments, ``-fprofile-use`` behaves identically to
2938 ``-fprofile-instr-use``. Otherwise, if ``pathname`` is the full path to a
2939 profile file, it reads from that file. If ``pathname`` is a directory name,
2940 it reads from ``pathname/default.profdata``.
2941
2942 .. option:: -fprofile-update[=<method>]
2943
2944 Unless ``-fsanitize=thread`` is specified, the default is ``single``, which
2945 uses non-atomic increments. The counters can be inaccurate under thread
2946 contention. ``atomic`` uses atomic increments which is accurate but has
2947 overhead. ``prefer-atomic`` will be transformed to ``atomic`` when supported
2948 by the target, or ``single`` otherwise.
2949
2950 Fine Tuning Profile Collection
2951 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2952
2953 The PGO infrastructure provides user program knobs to fine tune profile
2954 collection. Specifically, the PGO runtime provides the following functions
2955 that can be used to control the regions in the program where profiles should
2956 be collected.
2957
2958 * ``void __llvm_profile_set_filename(const char *Name)``: changes the name of
2959 the profile file to ``Name``.
2960 * ``void __llvm_profile_reset_counters(void)``: resets all counters to zero.
2961 * ``int __llvm_profile_dump(void)``: write the profile data to disk.
2962 * ``int __llvm_orderfile_dump(void)``: write the order file to disk.
2963
2964 For example, the following pattern can be used to skip profiling program
2965 initialization, profile two specific hot regions, and skip profiling program
2966 cleanup:
2967
2968 .. code-block:: c
2969
2970 int main() {
2971 initialize();
2972
2973 // Reset all profile counters to 0 to omit profile collected during
2974 // initialize()'s execution.
2975 __llvm_profile_reset_counters();
2976 ... hot region 1
2977 // Dump the profile for hot region 1.
2978 __llvm_profile_set_filename("region1.profraw");
2979 __llvm_profile_dump();
2980
2981 // Reset counters before proceeding to hot region 2.
2982 __llvm_profile_reset_counters();
2983 ... hot region 2
2984 // Dump the profile for hot region 2.
2985 __llvm_profile_set_filename("region2.profraw");
2986 __llvm_profile_dump();
2987
2988 // Since the profile has been dumped, no further profile data
2989 // will be collected beyond the above __llvm_profile_dump().
2990 cleanup();
2991 return 0;
2992 }
2993
2994 These APIs' names can be introduced to user programs in two ways.
2995 They can be declared as weak symbols on platforms which support
2996 treating weak symbols as ``null`` during linking. For example, the user can
2997 have
2998
2999 .. code-block:: c
3000
3001 __attribute__((weak)) int __llvm_profile_dump(void);
3002
3003 // Then later in the same source file
3004 if (__llvm_profile_dump)
3005 if (__llvm_profile_dump() != 0) { ... }
3006 // The first if condition tests if the symbol is actually defined.
3007 // Profile dumping only happens if the symbol is defined. Hence,
3008 // the user program works correctly during normal (not profile-generate)
3009 // executions.
3010
3011 Alternatively, the user program can include the header
3012 ``profile/instr_prof_interface.h``, which contains the API names. For example,
3013
3014 .. code-block:: c
3015
3016 #include "profile/instr_prof_interface.h"
3017
3018 // Then later in the same source file
3019 if (__llvm_profile_dump() != 0) { ... }
3020
3021 The user code does not need to check if the API names are defined, because
3022 these names are automatically replaced by ``(0)`` or the equivalence of noop
3023 if the ``clang`` is not compiling for profile generation.
3024
3025 Such replacement can happen because ``clang`` adds one of two macros depending
3026 on the ``-fprofile-generate`` and the ``-fprofile-use`` flags.
3027
3028 * ``__LLVM_INSTR_PROFILE_GENERATE``: defined when one of
3029 ``-fprofile[-instr]-generate``/``-fcs-profile-generate`` is in effect.
3030 * ``__LLVM_INSTR_PROFILE_USE``: defined when one of
3031 ``-fprofile-use``/``-fprofile-instr-use`` is in effect.
3032
3033 The two macros can be used to provide more flexibiilty so a user program
3034 can execute code specifically intended for profile generate or profile use.
3035 For example, a user program can have special logging during profile generate:
3036
3037 .. code-block:: c
3038
3039 #if __LLVM_INSTR_PROFILE_GENERATE
3040 expensive_logging_of_full_program_state();
3041 #endif
3042
3043 The logging is automatically excluded during a normal build of the program,
3044 hence it does not impact performance during a normal execution.
3045
3046 It is advised to use such fine tuning only in a program's cold regions. The weak
3047 symbols can introduce extra control flow (the ``if`` checks), while the macros
3048 (hence declarations they guard in ``profile/instr_prof_interface.h``)
3049 can change the control flow of the functions that use them between profile
3050 generation and profile use (which can lead to discarded counters in such
3051 functions). Using these APIs in the program's cold regions introduces less
3052 overhead and leads to more optimized code.
3053
3054 Disabling Instrumentation
3055 ^^^^^^^^^^^^^^^^^^^^^^^^^
3056
3057 In certain situations, it may be useful to disable profile generation or use
3058 for specific files in a build, without affecting the main compilation flags
3059 used for the other files in the project.
3060
3061 In these cases, you can use the flag ``-fno-profile-instr-generate`` (or
3062 ``-fno-profile-generate``) to disable profile generation, and
3063 ``-fno-profile-instr-use`` (or ``-fno-profile-use``) to disable profile use.
3064
3065 Note that these flags should appear after the corresponding profile
3066 flags to have an effect.
3067
3068 .. note::
3069
3070 When none of the translation units inside a binary is instrumented, in the
3071 case of Fuchsia the profile runtime will not be linked into the binary and
3072 no profile will be produced, while on other platforms the profile runtime
3073 will be linked and profile will be produced but there will not be any
3074 counters.
3075
3076 Instrumenting only selected files or functions
3077 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3078
3079 Sometimes it's useful to only instrument certain files or functions. For
3080 example in automated testing infrastructure, it may be desirable to only
3081 instrument files or functions that were modified by a patch to reduce the
3082 overhead of instrumenting a full system.
3083
3084 This can be done using the ``-fprofile-list`` option.
3085
3086 .. option:: -fprofile-list=<pathname>
3087
3088 This option can be used to apply profile instrumentation only to selected
3089 files or functions. ``pathname`` should point to a file in the
3090 :doc:`SanitizerSpecialCaseList` format which selects which files and
3091 functions to instrument.
3092
3093 .. code-block:: console
3094
3095 $ clang++ -O2 -fprofile-instr-generate -fprofile-list=fun.list code.cc -o code
3096
3097 The option can be specified multiple times to pass multiple files.
3098
3099 .. code-block:: console
3100
3101 $ clang++ -O2 -fprofile-instr-generate -fcoverage-mapping -fprofile-list=fun.list -fprofile-list=code.list code.cc -o code
3102
3103 Supported sections are ``[clang]``, ``[llvm]``, and ``[csllvm]`` representing
3104 clang PGO, IRPGO, and CSIRPGO, respectively. Supported prefixes are ``function``
3105 and ``source``. Supported categories are ``allow``, ``skip``, and ``forbid``.
3106 ``skip`` adds the ``skipprofile`` attribute while ``forbid`` adds the
3107 ``noprofile`` attribute to the appropriate function. Use
3108 ``default:<allow|skip|forbid>`` to specify the default category.
3109
3110 .. code-block:: console
3111
3112 $ cat fun.list
3113 # The following cases are for clang instrumentation.
3114 [clang]
3115
3116 # We might not want to profile functions that are inlined in many places.
3117 function:inlinedLots=skip
3118
3119 # We want to forbid profiling where it might be dangerous.
3120 source:lib/unsafe/*.cc=forbid
3121
3122 # Otherwise we allow profiling.
3123 default:allow
3124
3125 Older Prefixes
3126 """"""""""""""
3127 An older format is also supported, but it is only able to add the
3128 ``noprofile`` attribute.
3129 To filter individual functions or entire source files use ``fun:<name>`` or
3130 ``src:<file>`` respectively. To exclude a function or a source file, use
3131 ``!fun:<name>`` or ``!src:<file>`` respectively. The format also supports
3132 wildcard expansion. The compiler generated functions are assumed to be located
3133 in the main source file. It is also possible to restrict the filter to a
3134 particular instrumentation type by using a named section.
3135
3136 .. code-block:: none
3137
3138 # all functions whose name starts with foo will be instrumented.
3139 fun:foo*
3140
3141 # except for foo1 which will be excluded from instrumentation.
3142 !fun:foo1
3143
3144 # every function in path/to/foo.cc will be instrumented.
3145 src:path/to/foo.cc
3146
3147 # bar will be instrumented only when using backend instrumentation.
3148 # Recognized section names are clang, llvm and csllvm.
3149 [llvm]
3150 fun:bar
3151
3152 When the file contains only excludes, all files and functions except for the
3153 excluded ones will be instrumented. Otherwise, only the files and functions
3154 specified will be instrumented.
3155
3156 Instrument function groups
3157 ^^^^^^^^^^^^^^^^^^^^^^^^^^
3158
3159 Sometimes it is desirable to minimize the size overhead of instrumented
3160 binaries. One way to do this is to partition functions into groups and only
3161 instrument functions in a specified group. This can be done using the
3162 `-fprofile-function-groups` and `-fprofile-selected-function-group` options.
3163
3164 .. option:: -fprofile-function-groups=<N>, -fprofile-selected-function-group=<i>
3165
3166 The following uses 3 groups
3167
3168 .. code-block:: console
3169
3170 $ clang++ -Oz -fprofile-generate=group_0/ -fprofile-function-groups=3 -fprofile-selected-function-group=0 code.cc -o code.0
3171 $ clang++ -Oz -fprofile-generate=group_1/ -fprofile-function-groups=3 -fprofile-selected-function-group=1 code.cc -o code.1
3172 $ clang++ -Oz -fprofile-generate=group_2/ -fprofile-function-groups=3 -fprofile-selected-function-group=2 code.cc -o code.2
3173
3174 After collecting raw profiles from the three binaries, they can be merged into
3175 a single profile like normal.
3176
3177 .. code-block:: console
3178
3179 $ llvm-profdata merge -output=code.profdata group_*/*.profraw
3180
3181
3182 Profile remapping
3183 ^^^^^^^^^^^^^^^^^
3184
3185 When the program is compiled after a change that affects many symbol names,
3186 pre-existing profile data may no longer match the program. For example:
3187
3188 * switching from libstdc++ to libc++ will result in the mangled names of all
3189 functions taking standard library types to change
3190 * renaming a widely-used type in C++ will result in the mangled names of all
3191 functions that have parameters involving that type to change
3192 * moving from a 32-bit compilation to a 64-bit compilation may change the
3193 underlying type of ``size_t`` and similar types, resulting in changes to
3194 manglings
3195
3196 Clang allows use of a profile remapping file to specify that such differences
3197 in mangled names should be ignored when matching the profile data against the
3198 program.
3199
3200 .. option:: -fprofile-remapping-file=<file>
3201
3202 Specifies a file containing profile remapping information, that will be
3203 used to match mangled names in the profile data to mangled names in the
3204 program.
3205
3206 The profile remapping file is a text file containing lines of the form
3207
3208 .. code-block:: text
3209
3210 fragmentkind fragment1 fragment2
3211
3212 where ``fragmentkind`` is one of ``name``, ``type``, or ``encoding``,
3213 indicating whether the following mangled name fragments are
3214 <`name <https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangle.name>`_>s,
3215 <`type <https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangle.type>`_>s, or
3216 <`encoding <https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangle.encoding>`_>s,
3217 respectively.
3218 Blank lines and lines starting with ``#`` are ignored.
3219
3220 For convenience, built-in <substitution>s such as ``St`` and ``Ss``
3221 are accepted as <name>s (even though they technically are not <name>s).
3222
3223 For example, to specify that ``absl::string_view`` and ``std::string_view``
3224 should be treated as equivalent when matching profile data, the following
3225 remapping file could be used:
3226
3227 .. code-block:: text
3228
3229 # absl::string_view is considered equivalent to std::string_view
3230 type N4absl11string_viewE St17basic_string_viewIcSt11char_traitsIcEE
3231
3232 # std:: might be std::__1:: in libc++ or std::__cxx11:: in libstdc++
3233 name 3std St3__1
3234 name 3std St7__cxx11
3235
3236 Matching profile data using a profile remapping file is supported on a
3237 best-effort basis. For example, information regarding indirect call targets is
3238 currently not remapped. For best results, you are encouraged to generate new
3239 profile data matching the updated program, or to remap the profile data
3240 using the ``llvm-cxxmap`` and ``llvm-profdata merge`` tools.
3241
3242 .. note::
3243
3244 Profile data remapping is currently only supported for C++ mangled names
3245 following the Itanium C++ ABI mangling scheme. This covers all C++ targets
3246 supported by Clang other than Windows.
3247
3248 GCOV-based Profiling
3249 --------------------
3250
3251 GCOV is a test coverage program, it helps to know how often a line of code
3252 is executed. When instrumenting the code with ``--coverage`` option, some
3253 counters are added for each edge linking basic blocks.
3254
3255 At compile time, gcno files are generated containing information about
3256 blocks and edges between them. At runtime the counters are incremented and at
3257 exit the counters are dumped in gcda files.
3258
3259 The tool ``llvm-cov gcov`` will parse gcno, gcda and source files to generate
3260 a report ``.c.gcov``.
3261
3262 .. option:: -fprofile-filter-files=[regexes]
3263
3264 Define a list of regexes separated by a semi-colon.
3265 If a file name matches any of the regexes then the file is instrumented.
3266
3267 .. code-block:: console
3268
3269 $ clang --coverage -fprofile-filter-files=".*\.c$" foo.c
3270
3271 For example, this will only instrument files finishing with ``.c``, skipping ``.h`` files.
3272
3273 .. option:: -fprofile-exclude-files=[regexes]
3274
3275 Define a list of regexes separated by a semi-colon.
3276 If a file name doesn't match all the regexes then the file is instrumented.
3277
3278 .. code-block:: console
3279
3280 $ clang --coverage -fprofile-exclude-files="^/usr/include/.*$" foo.c
3281
3282 For example, this will instrument all the files except the ones in ``/usr/include``.
3283
3284 If both options are used then a file is instrumented if its name matches any
3285 of the regexes from ``-fprofile-filter-list`` and doesn't match all the regexes
3286 from ``-fprofile-exclude-list``.
3287
3288 .. code-block:: console
3289
3290 $ clang --coverage -fprofile-exclude-files="^/usr/include/.*$" \
3291 -fprofile-filter-files="^/usr/.*$"
3292
3293 In that case ``/usr/foo/oof.h`` is instrumented since it matches the filter regex and
3294 doesn't match the exclude regex, but ``/usr/include/foo.h`` doesn't since it matches
3295 the exclude regex.
3296
3297 Controlling Debug Information
3298 -----------------------------
3299
3300 Controlling Size of Debug Information
3301 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3302
3303 Debug info kind generated by Clang can be set by one of the flags listed
3304 below. If multiple flags are present, the last one is used.
3305
3306 .. option:: -g0
3307
3308 Don't generate any debug info (default).
3309
3310 .. option:: -gline-tables-only
3311
3312 Generate line number tables only.
3313
3314 This kind of debug info allows to obtain stack traces with function names,
3315 file names and line numbers (by such tools as ``gdb`` or ``addr2line``). It
3316 doesn't contain any other data (e.g. description of local variables or
3317 function parameters).
3318
3319 .. option:: -fstandalone-debug
3320
3321 Clang supports a number of optimizations to reduce the size of debug
3322 information in the binary. They work based on the assumption that
3323 the debug type information can be spread out over multiple
3324 compilation units. Specifically, the optimizations are:
3325
3326 - will not emit type definitions for types that are not needed by a
3327 module and could be replaced with a forward declaration.
3328 - will only emit type info for a dynamic C++ class in the module that
3329 contains the vtable for the class.
3330 - will only emit type info for a C++ class (non-trivial, non-aggregate)
3331 in the modules that contain a definition for one of its constructors.
3332 - will only emit type definitions for types that are the subject of explicit
3333 template instantiation declarations in the presence of an explicit
3334 instantiation definition for the type.
3335
3336 The **-fstandalone-debug** option turns off these optimizations.
3337 This is useful when working with 3rd-party libraries that don't come
3338 with debug information. Note that Clang will never emit type
3339 information for types that are not referenced at all by the program.
3340
3341 .. option:: -fno-standalone-debug
3342
3343 On Darwin **-fstandalone-debug** is enabled by default. The
3344 **-fno-standalone-debug** option can be used to get to turn on the
3345 vtable-based optimization described above.
3346
3347 .. option:: -g
3348
3349 Generate complete debug info.
3350
3351 .. option:: -feliminate-unused-debug-types
3352
3353 By default, Clang does not emit type information for types that are defined
3354 but not used in a program. To retain the debug info for these unused types,
3355 the negation **-fno-eliminate-unused-debug-types** can be used.
3356 This can be particulary useful on Windows, when using NATVIS files that
3357 can reference const symbols that would otherwise be stripped, even in full
3358 debug or standalone debug modes.
3359
3360 Controlling Macro Debug Info Generation
3361 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3362
3363 Debug info for C preprocessor macros increases the size of debug information in
3364 the binary. Macro debug info generated by Clang can be controlled by the flags
3365 listed below.
3366
3367 .. option:: -fdebug-macro
3368
3369 Generate debug info for preprocessor macros. This flag is discarded when
3370 **-g0** is enabled.
3371
3372 .. option:: -fno-debug-macro
3373
3374 Do not generate debug info for preprocessor macros (default).
3375
3376 Controlling Debugger "Tuning"
3377 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3378
3379 While Clang generally emits standard DWARF debug info (http://dwarfstd.org),
3380 different debuggers may know how to take advantage of different specific DWARF
3381 features. You can "tune" the debug info for one of several different debuggers.
3382
3383 .. option:: -ggdb, -glldb, -gsce, -gdbx
3384
3385 Tune the debug info for the ``gdb``, ``lldb``, Sony PlayStation\ |reg|
3386 debugger, or ``dbx``, respectively. Each of these options implies **-g**.
3387 (Therefore, if you want both **-gline-tables-only** and debugger tuning, the
3388 tuning option must come first.)
3389
3390 Controlling LLVM IR Output
3391 --------------------------
3392
3393 Controlling Value Names in LLVM IR
3394 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3395
3396 Emitting value names in LLVM IR increases the size and verbosity of the IR.
3397 By default, value names are only emitted in assertion-enabled builds of Clang.
3398 However, when reading IR it can be useful to re-enable the emission of value
3399 names to improve readability.
3400
3401 .. option:: -fdiscard-value-names
3402
3403 Discard value names when generating LLVM IR.
3404
3405 .. option:: -fno-discard-value-names
3406
3407 Do not discard value names when generating LLVM IR. This option can be used
3408 to re-enable names for release builds of Clang.
3409
3410
3411 Comment Parsing Options
3412 -----------------------
3413
3414 Clang parses Doxygen and non-Doxygen style documentation comments and attaches
3415 them to the appropriate declaration nodes. By default, it only parses
3416 Doxygen-style comments and ignores ordinary comments starting with ``//`` and
3417 ``/*``.
3418
3419 .. option:: -Wdocumentation
3420
3421 Emit warnings about use of documentation comments. This warning group is off
3422 by default.
3423
3424 This includes checking that ``\param`` commands name parameters that actually
3425 present in the function signature, checking that ``\returns`` is used only on
3426 functions that actually return a value etc.
3427
3428 .. option:: -Wno-documentation-unknown-command
3429
3430 Don't warn when encountering an unknown Doxygen command.
3431
3432 .. option:: -fparse-all-comments
3433
3434 Parse all comments as documentation comments (including ordinary comments
3435 starting with ``//`` and ``/*``).
3436
3437 .. option:: -fcomment-block-commands=[commands]
3438
3439 Define custom documentation commands as block commands. This allows Clang to
3440 construct the correct AST for these custom commands, and silences warnings
3441 about unknown commands. Several commands must be separated by a comma
3442 *without trailing space*; e.g. ``-fcomment-block-commands=foo,bar`` defines
3443 custom commands ``\foo`` and ``\bar``.
3444
3445 It is also possible to use ``-fcomment-block-commands`` several times; e.g.
3446 ``-fcomment-block-commands=foo -fcomment-block-commands=bar`` does the same
3447 as above.
3448
3449 .. _c:
3450
3451 C Language Features
3452 ===================
3453
3454 The support for standard C in clang is feature-complete except for the
3455 C99 floating-point pragmas.
3456
3457 Extensions supported by clang
3458 -----------------------------
3459
3460 See :doc:`LanguageExtensions`.
3461
3462 Differences between various standard modes
3463 ------------------------------------------
3464
3465 clang supports the -std option, which changes what language mode clang uses.
3466 The supported modes for C are c89, gnu89, c94, c99, gnu99, c11, gnu11, c17,
3467 gnu17, c23, gnu23, c2y, gnu2y, and various aliases for those modes. If no -std
3468 option is specified, clang defaults to gnu17 mode. Many C99 and C11 features
3469 are supported in earlier modes as a conforming extension, with a warning. Use
3470 ``-pedantic-errors`` to request an error if a feature from a later standard
3471 revision is used in an earlier mode.
3472
3473 Differences between all ``c*`` and ``gnu*`` modes:
3474
3475 - ``c*`` modes define "``__STRICT_ANSI__``".
3476 - Target-specific defines not prefixed by underscores, like ``linux``,
3477 are defined in ``gnu*`` modes.
3478 - Trigraphs default to being off in ``gnu*`` modes; they can be enabled
3479 by the ``-trigraphs`` option.
3480 - The parser recognizes ``asm`` and ``typeof`` as keywords in ``gnu*`` modes;
3481 the variants ``__asm__`` and ``__typeof__`` are recognized in all modes.
3482 - The parser recognizes ``inline`` as a keyword in ``gnu*`` mode, in
3483 addition to recognizing it in the ``*99`` and later modes for which it is
3484 part of the ISO C standard. The variant ``__inline__`` is recognized in all
3485 modes.
3486 - The Apple "blocks" extension is recognized by default in ``gnu*`` modes
3487 on some platforms; it can be enabled in any mode with the ``-fblocks``
3488 option.
3489
3490 Differences between ``*89`` and ``*94`` modes:
3491
3492 - Digraphs are not recognized in c89 mode.
3493
3494 Differences between ``*94`` and ``*99`` modes:
3495
3496 - The ``*99`` modes default to implementing ``inline`` / ``__inline__``
3497 as specified in C99, while the ``*89`` modes implement the GNU version.
3498 This can be overridden for individual functions with the ``__gnu_inline__``
3499 attribute.
3500 - The scope of names defined inside a ``for``, ``if``, ``switch``, ``while``,
3501 or ``do`` statement is different. (example: ``if ((struct x {int x;}*)0) {}``.)
3502 - ``__STDC_VERSION__`` is not defined in ``*89`` modes.
3503 - ``inline`` is not recognized as a keyword in ``c89`` mode.
3504 - ``restrict`` is not recognized as a keyword in ``*89`` modes.
3505 - Commas are allowed in integer constant expressions in ``*99`` modes.
3506 - Arrays which are not lvalues are not implicitly promoted to pointers
3507 in ``*89`` modes.
3508 - Some warnings are different.
3509
3510 Differences between ``*99`` and ``*11`` modes:
3511
3512 - Warnings for use of C11 features are disabled.
3513 - ``__STDC_VERSION__`` is defined to ``201112L`` rather than ``199901L``.
3514
3515 Differences between ``*11`` and ``*17`` modes:
3516
3517 - ``__STDC_VERSION__`` is defined to ``201710L`` rather than ``201112L``.
3518
3519 Differences between ``*17`` and ``*23`` modes:
3520
3521 - ``__STDC_VERSION__`` is defined to ``202311L`` rather than ``201710L``.
3522 - ``nullptr`` and ``nullptr_t`` are supported, only in ``*23`` mode.
3523 - ``ATOMIC_VAR_INIT`` is removed from ``*23`` mode.
3524 - ``bool``, ``true``, ``false``, ``alignas``, ``alignof``, ``static_assert``,
3525 and ``thread_local`` are now first-class keywords, only in ``*23`` mode.
3526 - ``typeof`` and ``typeof_unqual`` are supported, only ``*23`` mode.
3527 - Bit-precise integers (``_BitInt(N)``) are supported by default in ``*23``
3528 mode, and as an extension in ``*17`` and earlier modes.
3529 - ``[[]]`` attributes are supported by default in ``*23`` mode, and as an
3530 extension in ``*17`` and earlier modes.
3531
3532 Differences between ``*23`` and ``*2y`` modes:
3533
3534 - ``__STDC_VERSION__`` is defined to ``202400L`` rather than ``202311L``.
3535
3536 GCC extensions not implemented yet
3537 ----------------------------------
3538
3539 clang tries to be compatible with gcc as much as possible, but some gcc
3540 extensions are not implemented yet:
3541
3542 - clang does not support decimal floating point types (``_Decimal32`` and
3543 friends) yet.
3544 - clang does not support nested functions; this is a complex feature
3545 which is infrequently used, so it is unlikely to be implemented
3546 anytime soon. In C++11 it can be emulated by assigning lambda
3547 functions to local variables, e.g:
3548
3549 .. code-block:: cpp
3550
3551 auto const local_function = [&](int parameter) {
3552 // Do something
3553 };
3554 ...
3555 local_function(1);
3556
3557 - clang only supports global register variables when the register specified
3558 is non-allocatable (e.g. the stack pointer). Support for general global
3559 register variables is unlikely to be implemented soon because it requires
3560 additional LLVM backend support.
3561 - clang does not support static initialization of flexible array
3562 members. This appears to be a rarely used extension, but could be
3563 implemented pending user demand.
3564 - clang does not support
3565 ``__builtin_va_arg_pack``/``__builtin_va_arg_pack_len``. This is
3566 used rarely, but in some potentially interesting places, like the
3567 glibc headers, so it may be implemented pending user demand. Note
3568 that because clang pretends to be like GCC 4.2, and this extension
3569 was introduced in 4.3, the glibc headers will not try to use this
3570 extension with clang at the moment.
3571 - clang does not support the gcc extension for forward-declaring
3572 function parameters; this has not shown up in any real-world code
3573 yet, though, so it might never be implemented.
3574
3575 This is not a complete list; if you find an unsupported extension
3576 missing from this list, please send an e-mail to cfe-dev. This list
3577 currently excludes C++; see :ref:`C++ Language Features <cxx>`. Also, this
3578 list does not include bugs in mostly-implemented features; please see
3579 the `bug
3580 tracker <https://bugs.llvm.org/buglist.cgi?quicksearch=product%3Aclang+component%3A-New%2BBugs%2CAST%2CBasic%2CDriver%2CHeaders%2CLLVM%2BCodeGen%2Cparser%2Cpreprocessor%2CSemantic%2BAnalyzer>`_
3581 for known existing bugs (FIXME: Is there a section for bug-reporting
3582 guidelines somewhere?).
3583
3584 Intentionally unsupported GCC extensions
3585 ----------------------------------------
3586
3587 - clang does not support the gcc extension that allows variable-length
3588 arrays in structures. This is for a few reasons: one, it is tricky to
3589 implement, two, the extension is completely undocumented, and three,
3590 the extension appears to be rarely used. Note that clang *does*
3591 support flexible array members (arrays with a zero or unspecified
3592 size at the end of a structure).
3593 - GCC accepts many expression forms that are not valid integer constant
3594 expressions in bit-field widths, enumerator constants, case labels,
3595 and in array bounds at global scope. Clang also accepts additional
3596 expression forms in these contexts, but constructs that GCC accepts due to
3597 simplifications GCC performs while parsing, such as ``x - x`` (where ``x`` is a
3598 variable) will likely never be accepted by Clang.
3599 - clang does not support ``__builtin_apply`` and friends; this extension
3600 is extremely obscure and difficult to implement reliably.
3601
3602 .. _c_ms:
3603
3604 Microsoft extensions
3605 --------------------
3606
3607 clang has support for many extensions from Microsoft Visual C++. To enable these
3608 extensions, use the ``-fms-extensions`` command-line option. This is the default
3609 for Windows targets. Clang does not implement every pragma or declspec provided
3610 by MSVC, but the popular ones, such as ``__declspec(dllexport)`` and ``#pragma
3611 comment(lib)`` are well supported.
3612
3613 clang has a ``-fms-compatibility`` flag that makes clang accept enough
3614 invalid C++ to be able to parse most Microsoft headers. For example, it
3615 allows `unqualified lookup of dependent base class members
3616 <https://clang.llvm.org/compatibility.html#dep_lookup_bases>`_, which is
3617 a common compatibility issue with clang. This flag is enabled by default
3618 for Windows targets.
3619
3620 ``-fdelayed-template-parsing`` lets clang delay parsing of function template
3621 definitions until the end of a translation unit. This flag is enabled by
3622 default for Windows targets.
3623
3624 For compatibility with existing code that compiles with MSVC, clang defines the
3625 ``_MSC_VER`` and ``_MSC_FULL_VER`` macros. When on Windows, these default to
3626 either the same value as the currently installed version of cl.exe, or ``1933``
3627 and ``193300000`` (respectively). The ``-fms-compatibility-version=`` flag
3628 overrides these values. It accepts a dotted version tuple, such as 19.00.23506.
3629 Changing the MSVC compatibility version makes clang behave more like that
3630 version of MSVC. For example, ``-fms-compatibility-version=19`` will enable
3631 C++14 features and define ``char16_t`` and ``char32_t`` as builtin types.
3632
3633 .. _cxx:
3634
3635 C++ Language Features
3636 =====================
3637
3638 clang fully implements all of standard C++98 except for exported
3639 templates (which were removed in C++11), all of standard C++11,
3640 C++14, and C++17, and most of C++20.
3641
3642 See the `C++ support in Clang <https://clang.llvm.org/cxx_status.html>`_ page
3643 for detailed information on C++ feature support across Clang versions.
3644
3645 Controlling implementation limits
3646 ---------------------------------
3647
3648 .. option:: -fbracket-depth=N
3649
3650 Sets the limit for nested parentheses, brackets, and braces to N. The
3651 default is 256.
3652
3653 .. option:: -fconstexpr-depth=N
3654
3655 Sets the limit for constexpr function invocations to N. The default is 512.
3656
3657 .. option:: -fconstexpr-steps=N
3658
3659 Sets the limit for the number of full-expressions evaluated in a single
3660 constant expression evaluation. This also controls the maximum size
3661 of array and dynamic array allocation that can be constant evaluated.
3662 The default is 1048576.
3663
3664 .. option:: -ftemplate-depth=N
3665
3666 Sets the limit for recursively nested template instantiations to N. The
3667 default is 1024.
3668
3669 .. option:: -foperator-arrow-depth=N
3670
3671 Sets the limit for iterative calls to 'operator->' functions to N. The
3672 default is 256.
3673
3674 .. _objc:
3675
3676 Objective-C Language Features
3677 =============================
3678
3679 .. _objcxx:
3680
3681 Objective-C++ Language Features
3682 ===============================
3683
3684 .. _openmp:
3685
3686 OpenMP Features
3687 ===============
3688
3689 Clang supports all OpenMP 4.5 directives and clauses. See :doc:`OpenMPSupport`
3690 for additional details.
3691
3692 Use `-fopenmp` to enable OpenMP. Support for OpenMP can be disabled with
3693 `-fno-openmp`.
3694
3695 Use `-fopenmp-simd` to enable OpenMP simd features only, without linking
3696 the runtime library; for combined constructs
3697 (e.g. ``#pragma omp parallel for simd``) the non-simd directives and clauses
3698 will be ignored. This can be disabled with `-fno-openmp-simd`.
3699
3700 Controlling implementation limits
3701 ---------------------------------
3702
3703 .. option:: -fopenmp-use-tls
3704
3705 Controls code generation for OpenMP threadprivate variables. In presence of
3706 this option all threadprivate variables are generated the same way as thread
3707 local variables, using TLS support. If `-fno-openmp-use-tls`
3708 is provided or target does not support TLS, code generation for threadprivate
3709 variables relies on OpenMP runtime library.
3710
3711 .. _opencl:
3712
3713 OpenCL Features
3714 ===============
3715
3716 Clang can be used to compile OpenCL kernels for execution on a device
3717 (e.g. GPU). It is possible to compile the kernel into a binary (e.g. for AMDGPU)
3718 that can be uploaded to run directly on a device (e.g. using
3719 `clCreateProgramWithBinary
3720 <https://www.khronos.org/registry/OpenCL/specs/opencl-1.1.pdf#111>`_) or
3721 into generic bitcode files loadable into other toolchains.
3722
3723 Compiling to a binary using the default target from the installation can be done
3724 as follows:
3725
3726 .. code-block:: console
3727
3728 $ echo "kernel void k(){}" > test.cl
3729 $ clang test.cl
3730
3731 Compiling for a specific target can be done by specifying the triple corresponding
3732 to the target, for example:
3733
3734 .. code-block:: console
3735
3736 $ clang --target=nvptx64-unknown-unknown test.cl
3737 $ clang --target=amdgcn-amd-amdhsa -mcpu=gfx900 test.cl
3738
3739 Compiling to bitcode can be done as follows:
3740
3741 .. code-block:: console
3742
3743 $ clang -c -emit-llvm test.cl
3744
3745 This will produce a file `test.bc` that can be used in vendor toolchains
3746 to perform machine code generation.
3747
3748 Note that if compiled to bitcode for generic targets such as SPIR/SPIR-V,
3749 portable IR is produced that can be used with various vendor
3750 tools as well as open source tools such as `SPIRV-LLVM Translator
3751 <https://github.com/KhronosGroup/SPIRV-LLVM-Translator>`_
3752 to produce SPIR-V binary. More details are provided in `the offline
3753 compilation from OpenCL kernel sources into SPIR-V using open source
3754 tools
3755 <https://github.com/KhronosGroup/OpenCL-Guide/blob/main/chapters/os_tooling.md>`_.
3756 From clang 14 onwards SPIR-V can be generated directly as detailed in
3757 :ref:`the SPIR-V support section <spir-v>`.
3758
3759 Clang currently supports OpenCL C language standards up to v2.0. Clang mainly
3760 supports full profile. There is only very limited support of the embedded
3761 profile.
3762 From clang 9 a C++ mode is available for OpenCL (see
3763 :ref:`C++ for OpenCL <cxx_for_opencl>`).
3764
3765 OpenCL v3.0 support is complete but it remains in experimental state, see more
3766 details about the experimental features and limitations in :doc:`OpenCLSupport`
3767 page.
3768
3769 OpenCL Specific Options
3770 -----------------------
3771
3772 Most of the OpenCL build options from `the specification v2.0 section 5.8.4
3773 <https://www.khronos.org/registry/cl/specs/opencl-2.0.pdf#200>`_ are available.
3774
3775 Examples:
3776
3777 .. code-block:: console
3778
3779 $ clang -cl-std=CL2.0 -cl-single-precision-constant test.cl
3780
3781
3782 Many flags used for the compilation for C sources can also be passed while
3783 compiling for OpenCL, examples: ``-c``, ``-O<1-4|s>``, ``-o``, ``-emit-llvm``, etc.
3784
3785 Some extra options are available to support special OpenCL features.
3786
3787 .. option:: -cl-no-stdinc
3788
3789 Allows to disable all extra types and functions that are not native to the compiler.
3790 This might reduce the compilation speed marginally but many declarations from the
3791 OpenCL standard will not be accessible. For example, the following will fail to
3792 compile.
3793
3794 .. code-block:: console
3795
3796 $ echo "bool is_wg_uniform(int i){return get_enqueued_local_size(i)==get_local_size(i);}" > test.cl
3797 $ clang -cl-std=CL2.0 -cl-no-stdinc test.cl
3798 error: use of undeclared identifier 'get_enqueued_local_size'
3799 error: use of undeclared identifier 'get_local_size'
3800
3801 More information about the standard types and functions is provided in :ref:`the
3802 section on the OpenCL Header <opencl_header>`.
3803
3804 .. _opencl_cl_ext:
3805
3806 .. option:: -cl-ext
3807
3808 Enables/Disables support of OpenCL extensions and optional features. All OpenCL
3809 targets set a list of extensions that they support. Clang allows to amend this using
3810 the ``-cl-ext`` flag with a comma-separated list of extensions prefixed with
3811 ``'+'`` or ``'-'``. The syntax: ``-cl-ext=<(['-'|'+']<extension>[,])+>``, where
3812 extensions can be either one of `the OpenCL published extensions
3813 <https://www.khronos.org/registry/OpenCL>`_
3814 or any vendor extension. Alternatively, ``'all'`` can be used to enable
3815 or disable all known extensions.
3816
3817 Example disabling double support for the 64-bit SPIR-V target:
3818
3819 .. code-block:: console
3820
3821 $ clang -c --target=spirv64 -cl-ext=-cl_khr_fp64 test.cl
3822
3823 Enabling all extensions except double support in R600 AMD GPU can be done using:
3824
3825 .. code-block:: console
3826
3827 $ clang --target=r600 -cl-ext=-all,+cl_khr_fp16 test.cl
3828
3829 Note that some generic targets e.g. SPIR/SPIR-V enable all extensions/features in
3830 clang by default.
3831
3832 OpenCL Targets
3833 --------------
3834
3835 OpenCL targets are derived from the regular Clang target classes. The OpenCL
3836 specific parts of the target representation provide address space mapping as
3837 well as a set of supported extensions.
3838
3839 Specific Targets
3840 ^^^^^^^^^^^^^^^^
3841
3842 There is a set of concrete HW architectures that OpenCL can be compiled for.
3843
3844 - For AMD target:
3845
3846 .. code-block:: console
3847
3848 $ clang --target=amdgcn-amd-amdhsa -mcpu=gfx900 test.cl
3849
3850 - For Nvidia architectures:
3851
3852 .. code-block:: console
3853
3854 $ clang --target=nvptx64-unknown-unknown test.cl
3855
3856
3857 Generic Targets
3858 ^^^^^^^^^^^^^^^
3859
3860 - A SPIR-V binary can be produced for 32 or 64 bit targets.
3861
3862 .. code-block:: console
3863
3864 $ clang --target=spirv32 -c test.cl
3865 $ clang --target=spirv64 -c test.cl
3866
3867 More details can be found in :ref:`the SPIR-V support section <spir-v>`.
3868
3869 - SPIR is available as a generic target to allow portable bitcode to be produced
3870 that can be used across GPU toolchains. The implementation follows `the SPIR
3871 specification <https://www.khronos.org/spir>`_. There are two flavors
3872 available for 32 and 64 bits.
3873
3874 .. code-block:: console
3875
3876 $ clang --target=spir test.cl -emit-llvm -c
3877 $ clang --target=spir64 test.cl -emit-llvm -c
3878
3879 Clang will generate SPIR v1.2 compatible IR for OpenCL versions up to 2.0 and
3880 SPIR v2.0 for OpenCL v2.0 or C++ for OpenCL.
3881
3882 - x86 is used by some implementations that are x86 compatible and currently
3883 remains for backwards compatibility (with older implementations prior to
3884 SPIR target support). For "non-SPMD" targets which cannot spawn multiple
3885 work-items on the fly using hardware, which covers practically all non-GPU
3886 devices such as CPUs and DSPs, additional processing is needed for the kernels
3887 to support multiple work-item execution. For this, a 3rd party toolchain,
3888 such as for example `POCL <http://portablecl.org/>`_, can be used.
3889
3890 This target does not support multiple memory segments and, therefore, the fake
3891 address space map can be added using the :ref:`-ffake-address-space-map
3892 <opencl_fake_address_space_map>` flag.
3893
3894 All known OpenCL extensions and features are set to supported in the generic targets,
3895 however :option:`-cl-ext` flag can be used to toggle individual extensions and
3896 features.
3897
3898 .. _opencl_header:
3899
3900 OpenCL Header
3901 -------------
3902
3903 By default Clang will include standard headers and therefore most of OpenCL
3904 builtin functions and types are available during compilation. The
3905 default declarations of non-native compiler types and functions can be disabled
3906 by using flag :option:`-cl-no-stdinc`.
3907
3908 The following example demonstrates that OpenCL kernel sources with various
3909 standard builtin functions can be compiled without the need for an explicit
3910 includes or compiler flags.
3911
3912 .. code-block:: console
3913
3914 $ echo "bool is_wg_uniform(int i){return get_enqueued_local_size(i)==get_local_size(i);}" > test.cl
3915 $ clang -cl-std=CL2.0 test.cl
3916
3917 More information about the default headers is provided in :doc:`OpenCLSupport`.
3918
3919 OpenCL Extensions
3920 -----------------
3921
3922 Most of the ``cl_khr_*`` extensions to OpenCL C from `the official OpenCL
3923 registry <https://www.khronos.org/registry/OpenCL/>`_ are available and
3924 configured per target depending on the support available in the specific
3925 architecture.
3926
3927 It is possible to alter the default extensions setting per target using
3928 ``-cl-ext`` flag. (See :ref:`flags description <opencl_cl_ext>` for more details).
3929
3930 Vendor extensions can be added flexibly by declaring the list of types and
3931 functions associated with each extensions enclosed within the following
3932 compiler pragma directives:
3933
3934 .. code-block:: c
3935
3936 #pragma OPENCL EXTENSION the_new_extension_name : begin
3937 // declare types and functions associated with the extension here
3938 #pragma OPENCL EXTENSION the_new_extension_name : end
3939
3940 For example, parsing the following code adds ``my_t`` type and ``my_func``
3941 function to the custom ``my_ext`` extension.
3942
3943 .. code-block:: c
3944
3945 #pragma OPENCL EXTENSION my_ext : begin
3946 typedef struct{
3947 int a;
3948 }my_t;
3949 void my_func(my_t);
3950 #pragma OPENCL EXTENSION my_ext : end
3951
3952 There is no conflict resolution for identifier clashes among extensions.
3953 It is therefore recommended that the identifiers are prefixed with a
3954 double underscore to avoid clashing with user space identifiers. Vendor
3955 extension should use reserved identifier prefix e.g. amd, arm, intel.
3956
3957 Clang also supports language extensions documented in `The OpenCL C Language
3958 Extensions Documentation
3959 <https://github.com/KhronosGroup/Khronosdotorg/blob/main/api/opencl/assets/OpenCL_LangExt.pdf>`_.
3960
3961 OpenCL-Specific Attributes
3962 --------------------------
3963
3964 OpenCL support in Clang contains a set of attribute taken directly from the
3965 specification as well as additional attributes.
3966
3967 See also :doc:`AttributeReference`.
3968
3969 nosvm
3970 ^^^^^
3971
3972 Clang supports this attribute to comply to OpenCL v2.0 conformance, but it
3973 does not have any effect on the IR. For more details reffer to the specification
3974 `section 6.7.2
3975 <https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#49>`_
3976
3977
3978 opencl_unroll_hint
3979 ^^^^^^^^^^^^^^^^^^
3980
3981 The implementation of this feature mirrors the unroll hint for C.
3982 More details on the syntax can be found in the specification
3983 `section 6.11.5
3984 <https://www.khronos.org/registry/cl/specs/opencl-2.0-openclc.pdf#61>`_
3985
3986 convergent
3987 ^^^^^^^^^^
3988
3989 To make sure no invalid optimizations occur for single program multiple data
3990 (SPMD) / single instruction multiple thread (SIMT) Clang provides attributes that
3991 can be used for special functions that have cross work item semantics.
3992 An example is the subgroup operations such as `intel_sub_group_shuffle
3993 <https://www.khronos.org/registry/cl/extensions/intel/cl_intel_subgroups.txt>`_
3994
3995 .. code-block:: c
3996
3997 // Define custom my_sub_group_shuffle(data, c)
3998 // that makes use of intel_sub_group_shuffle
3999 r1 = ...
4000 if (r0) r1 = computeA();
4001 // Shuffle data from r1 into r3
4002 // of threads id r2.
4003 r3 = my_sub_group_shuffle(r1, r2);
4004 if (r0) r3 = computeB();
4005
4006 with non-SPMD semantics this is optimized to the following equivalent code:
4007
4008 .. code-block:: c
4009
4010 r1 = ...
4011 if (!r0)
4012 // Incorrect functionality! The data in r1
4013 // have not been computed by all threads yet.
4014 r3 = my_sub_group_shuffle(r1, r2);
4015 else {
4016 r1 = computeA();
4017 r3 = my_sub_group_shuffle(r1, r2);
4018 r3 = computeB();
4019 }
4020
4021 Declaring the function ``my_sub_group_shuffle`` with the convergent attribute
4022 would prevent this:
4023
4024 .. code-block:: c
4025
4026 my_sub_group_shuffle() __attribute__((convergent));
4027
4028 Using ``convergent`` guarantees correct execution by keeping CFG equivalence
4029 wrt operations marked as ``convergent``. CFG ``G´`` is equivalent to ``G`` wrt
4030 node ``Ni`` : ``iff ∀ Nj (i≠j)`` domination and post-domination relations with
4031 respect to ``Ni`` remain the same in both ``G`` and ``G´``.
4032
4033 noduplicate
4034 ^^^^^^^^^^^
4035
4036 ``noduplicate`` is more restrictive with respect to optimizations than
4037 ``convergent`` because a convergent function only preserves CFG equivalence.
4038 This allows some optimizations to happen as long as the control flow remains
4039 unmodified.
4040
4041 .. code-block:: c
4042
4043 for (int i=0; i<4; i++)
4044 my_sub_group_shuffle()
4045
4046 can be modified to:
4047
4048 .. code-block:: c
4049
4050 my_sub_group_shuffle();
4051 my_sub_group_shuffle();
4052 my_sub_group_shuffle();
4053 my_sub_group_shuffle();
4054
4055 while using ``noduplicate`` would disallow this. Also ``noduplicate`` doesn't
4056 have the same safe semantics of CFG as ``convergent`` and can cause changes in
4057 CFG that modify semantics of the original program.
4058
4059 ``noduplicate`` is kept for backwards compatibility only and it considered to be
4060 deprecated for future uses.
4061
4062 .. _cxx_for_opencl:
4063
4064 C++ for OpenCL
4065 --------------
4066
4067 Starting from clang 9 kernel code can contain C++17 features: classes, templates,
4068 function overloading, type deduction, etc. Please note that this is not an
4069 implementation of `OpenCL C++
4070 <https://www.khronos.org/registry/OpenCL/specs/2.2/pdf/OpenCL_Cxx.pdf>`_ and
4071 there is no plan to support it in clang in any new releases in the near future.
4072
4073 Clang currently supports C++ for OpenCL 1.0 and 2021.
4074 For detailed information about this language refer to the C++ for OpenCL
4075 Programming Language Documentation available
4076 in `the latest build
4077 <https://www.khronos.org/opencl/assets/CXX_for_OpenCL.html>`_
4078 or in `the official release
4079 <https://github.com/KhronosGroup/OpenCL-Docs/releases/tag/cxxforopencl-docrev2021.12>`_.
4080
4081 To enable the C++ for OpenCL mode, pass one of following command line options when
4082 compiling ``.clcpp`` file:
4083
4084 - C++ for OpenCL 1.0: ``-cl-std=clc++``, ``-cl-std=CLC++``, ``-cl-std=clc++1.0``,
4085 ``-cl-std=CLC++1.0``, ``-std=clc++``, ``-std=CLC++``, ``-std=clc++1.0`` or
4086 ``-std=CLC++1.0``.
4087
4088 - C++ for OpenCL 2021: ``-cl-std=clc++2021``, ``-cl-std=CLC++2021``,
4089 ``-std=clc++2021``, ``-std=CLC++2021``.
4090
4091 Example of use:
4092 .. code-block:: c++
4093
4094 template<class T> T add( T x, T y )
4095 {
4096 return x + y;
4097 }
4098
4099 __kernel void test( __global float* a, __global float* b)
4100 {
4101 auto index = get_global_id(0);
4102 a[index] = add(b[index], b[index+1]);
4103 }
4104
4105
4106 .. code-block:: console
4107
4108 clang -cl-std=clc++1.0 test.clcpp
4109 clang -cl-std=clc++ -c --target=spirv64 test.cl
4110
4111
4112 By default, files with ``.clcpp`` extension are compiled with the C++ for
4113 OpenCL 1.0 mode.
4114
4115 .. code-block:: console
4116
4117 clang test.clcpp
4118
4119 For backward compatibility files with ``.cl`` extensions can also be compiled
4120 in C++ for OpenCL mode but the desirable language mode must be activated with
4121 a flag.
4122
4123 .. code-block:: console
4124
4125 clang -cl-std=clc++ test.cl
4126
4127 Support of C++ for OpenCL 2021 is currently in experimental phase, refer to
4128 :doc:`OpenCLSupport` for more details.
4129
4130 C++ for OpenCL kernel sources can also be compiled online in drivers supporting
4131 `cl_ext_cxx_for_opencl
4132 <https://www.khronos.org/registry/OpenCL/extensions/ext/cl_ext_cxx_for_opencl.html>`_
4133 extension.
4134
4135 Constructing and destroying global objects
4136 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4137
4138 Global objects with non-trivial constructors require the constructors to be run
4139 before the first kernel using the global objects is executed. Similarly global
4140 objects with non-trivial destructors require destructor invocation just after
4141 the last kernel using the program objects is executed.
4142 In OpenCL versions earlier than v2.2 there is no support for invoking global
4143 constructors. However, an easy workaround is to manually enqueue the
4144 constructor initialization kernel that has the following name scheme
4145 ``_GLOBAL__sub_I_<compiled file name>``.
4146 This kernel is only present if there are global objects with non-trivial
4147 constructors present in the compiled binary. One way to check this is by
4148 passing ``CL_PROGRAM_KERNEL_NAMES`` to ``clGetProgramInfo`` (OpenCL v2.0
4149 s5.8.7) and then checking whether any kernel name matches the naming scheme of
4150 global constructor initialization kernel above.
4151
4152 Note that if multiple files are compiled and linked into libraries, multiple
4153 kernels that initialize global objects for multiple modules would have to be
4154 invoked.
4155
4156 Applications are currently required to run initialization of global objects
4157 manually before running any kernels in which the objects are used.
4158
4159 .. code-block:: console
4160
4161 clang -cl-std=clc++ test.cl
4162
4163 If there are any global objects to be initialized, the final binary will
4164 contain the ``_GLOBAL__sub_I_test.cl`` kernel to be enqueued.
4165
4166 Note that the manual workaround only applies to objects declared at the
4167 program scope. There is no manual workaround for the construction of static
4168 objects with non-trivial constructors inside functions.
4169
4170 Global destructors can not be invoked manually in the OpenCL v2.0 drivers.
4171 However, all memory used for program scope objects should be released on
4172 ``clReleaseProgram``.
4173
4174 Libraries
4175 ^^^^^^^^^
4176 Limited experimental support of C++ standard libraries for OpenCL is
4177 described in :doc:`OpenCLSupport` page.
4178
4179 .. _target_features:
4180
4181 Target-Specific Features and Limitations
4182 ========================================
4183
4184 CPU Architectures Features and Limitations
4185 ------------------------------------------
4186
4187 X86
4188 ^^^
4189
4190 The support for X86 (both 32-bit and 64-bit) is considered stable on
4191 Darwin (macOS), Linux, FreeBSD, and Dragonfly BSD: it has been tested
4192 to correctly compile many large C, C++, Objective-C, and Objective-C++
4193 codebases.
4194
4195 On ``x86_64-mingw32``, passing i128(by value) is incompatible with the
4196 Microsoft x64 calling convention. You might need to tweak
4197 ``WinX86_64ABIInfo::classify()`` in lib/CodeGen/Targets/X86.cpp.
4198
4199 For the X86 target, clang supports the `-m16` command line
4200 argument which enables 16-bit code output. This is broadly similar to
4201 using ``asm(".code16gcc")`` with the GNU toolchain. The generated code
4202 and the ABI remains 32-bit but the assembler emits instructions
4203 appropriate for a CPU running in 16-bit mode, with address-size and
4204 operand-size prefixes to enable 32-bit addressing and operations.
4205
4206 Several micro-architecture levels as specified by the x86-64 psABI are defined.
4207 They are cumulative in the sense that features from previous levels are
4208 implicitly included in later levels.
4209
4210 - ``-march=x86-64``: CMOV, CMPXCHG8B, FPU, FXSR, MMX, FXSR, SCE, SSE, SSE2
4211 - ``-march=x86-64-v2``: (close to Nehalem) CMPXCHG16B, LAHF-SAHF, POPCNT, SSE3, SSE4.1, SSE4.2, SSSE3
4212 - ``-march=x86-64-v3``: (close to Haswell) AVX, AVX2, BMI1, BMI2, F16C, FMA, LZCNT, MOVBE, XSAVE
4213 - ``-march=x86-64-v4``: AVX512F, AVX512BW, AVX512CD, AVX512DQ, AVX512VL
4214
4215 `Intel AVX10 ISA <https://cdrdv2.intel.com/v1/dl/getContent/784267>`_ is
4216 a major new vector ISA incorporating the modern vectorization aspects of
4217 Intel AVX-512. This ISA will be supported on all future Intel processors.
4218 Users are supposed to use the new options ``-mavx10.N`` and ``-mavx10.N-512``
4219 on these processors and should not use traditional AVX512 options anymore.
4220
4221 The ``N`` in ``-mavx10.N`` represents a continuous integer number starting
4222 from ``1``. ``-mavx10.N`` is an alias of ``-mavx10.N-256``, which means to
4223 enable all instructions within AVX10 version N at a maximum vector length of
4224 256 bits. ``-mavx10.N-512`` enables all instructions at a maximum vector
4225 length of 512 bits, which is a superset of instructions ``-mavx10.N`` enabled.
4226
4227 Current binaries built with AVX512 features can run on Intel AVX10/512 capable
4228 processors without re-compile, but cannot run on AVX10/256 capable processors.
4229 Users need to re-compile their code with ``-mavx10.N``, and maybe update some
4230 code that calling to 512-bit X86 specific intrinsics and passing or returning
4231 512-bit vector types in function call, if they want to run on AVX10/256 capable
4232 processors. Binaries built with ``-mavx10.N`` can run on both AVX10/256 and
4233 AVX10/512 capable processors.
4234
4235 Users can add a ``-mno-evex512`` in the command line with AVX512 options if
4236 they want to run the binary on both legacy AVX512 and new AVX10/256 capable
4237 processors. The option has the same constraints as ``-mavx10.N``, i.e.,
4238 cannot call to 512-bit X86 specific intrinsics and pass or return 512-bit vector
4239 types in function call.
4240
4241 Users should avoid using AVX512 features in function target attributes when
4242 developing code for AVX10. If they have to do so, they need to add an explicit
4243 ``evex512`` or ``no-evex512`` together with AVX512 features for 512-bit or
4244 non-512-bit functions respectively to avoid unexpected code generation. Both
4245 command line option and target attribute of EVEX512 feature can only be used
4246 with AVX512. They don't affect vector size of AVX10.
4247
4248 User should not mix the use AVX10 and AVX512 options together at any time,
4249 because the option combinations are conflicting sometimes. For example, a
4250 combination of ``-mavx512f -mavx10.1-256`` doesn't show a clear intention to
4251 compiler, since instructions in AVX512F and AVX10.1/256 intersect but do not
4252 overlap. In this case, compiler will emit warning for it, but the behavior
4253 is determined. It will generate the same code as option ``-mavx10.1-512``.
4254 A similar case is ``-mavx512f -mavx10.2-256``, which equals to
4255 ``-mavx10.1-512 -mavx10.2-256``, because ``avx10.2-256`` implies ``avx10.1-256``
4256 and ``-mavx512f -mavx10.1-256`` equals to ``-mavx10.1-512``.
4257
4258 There are some new macros introduced with AVX10 support. ``-mavx10.1-256`` will
4259 enable ``__AVX10_1__`` and ``__EVEX256__``, while ``-mavx10.1-512`` enables
4260 ``__AVX10_1__``, ``__EVEX256__``, ``__EVEX512__`` and ``__AVX10_1_512__``.
4261 Besides, both ``-mavx10.1-256`` and ``-mavx10.1-512`` will enable all AVX512
4262 feature specific macros. A AVX512 feature will enable both ``__EVEX256__``,
4263 ``__EVEX512__`` and its own macro. So ``__EVEX512__`` can be used to guard code
4264 that can run on both legacy AVX512 and AVX10/512 capable processors but cannot
4265 run on AVX10/256, while a AVX512 macro like ``__AVX512F__`` cannot tell the
4266 difference among the three options. Users need to check additional macros
4267 ``__AVX10_1__`` and ``__EVEX512__`` if they want to make distinction.
4268
4269 ARM
4270 ^^^
4271
4272 The support for ARM (specifically ARMv6 and ARMv7) is considered stable
4273 on Darwin (iOS): it has been tested to correctly compile many large C,
4274 C++, Objective-C, and Objective-C++ codebases. Clang only supports a
4275 limited number of ARM architectures. It does not yet fully support
4276 ARMv5, for example.
4277
4278 PowerPC
4279 ^^^^^^^
4280
4281 The support for PowerPC (especially PowerPC64) is considered stable
4282 on Linux and FreeBSD: it has been tested to correctly compile many
4283 large C and C++ codebases. PowerPC (32bit) is still missing certain
4284 features (e.g. PIC code on ELF platforms).
4285
4286 Other platforms
4287 ^^^^^^^^^^^^^^^
4288
4289 clang currently contains some support for other architectures (e.g. Sparc);
4290 however, significant pieces of code generation are still missing, and they
4291 haven't undergone significant testing.
4292
4293 clang contains limited support for the MSP430 embedded processor, but
4294 both the clang support and the LLVM backend support are highly
4295 experimental.
4296
4297 Other platforms are completely unsupported at the moment. Adding the
4298 minimal support needed for parsing and semantic analysis on a new
4299 platform is quite easy; see ``lib/Basic/Targets.cpp`` in the clang source
4300 tree. This level of support is also sufficient for conversion to LLVM IR
4301 for simple programs. Proper support for conversion to LLVM IR requires
4302 adding code to ``lib/CodeGen/CGCall.cpp`` at the moment; this is likely to
4303 change soon, though. Generating assembly requires a suitable LLVM
4304 backend.
4305
4306 Operating System Features and Limitations
4307 -----------------------------------------
4308
4309 Windows
4310 ^^^^^^^
4311
4312 Clang has experimental support for targeting "Cygming" (Cygwin / MinGW)
4313 platforms.
4314
4315 See also :ref:`Microsoft Extensions <c_ms>`.
4316
4317 Cygwin
4318 """"""
4319
4320 Clang works on Cygwin-1.7.
4321
4322 MinGW32
4323 """""""
4324
4325 Clang works on some mingw32 distributions. Clang assumes directories as
4326 below;
4327
4328 - ``C:/mingw/include``
4329 - ``C:/mingw/lib``
4330 - ``C:/mingw/lib/gcc/mingw32/4.[3-5].0/include/c++``
4331
4332 On MSYS, a few tests might fail.
4333
4334 MinGW-w64
4335 """""""""
4336
4337 For 32-bit (i686-w64-mingw32), and 64-bit (x86\_64-w64-mingw32), Clang
4338 assumes as below;
4339
4340 - ``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)``
4341 - ``some_directory/bin/gcc.exe``
4342 - ``some_directory/bin/clang.exe``
4343 - ``some_directory/bin/clang++.exe``
4344 - ``some_directory/bin/../include/c++/GCC_version``
4345 - ``some_directory/bin/../include/c++/GCC_version/x86_64-w64-mingw32``
4346 - ``some_directory/bin/../include/c++/GCC_version/i686-w64-mingw32``
4347 - ``some_directory/bin/../include/c++/GCC_version/backward``
4348 - ``some_directory/bin/../x86_64-w64-mingw32/include``
4349 - ``some_directory/bin/../i686-w64-mingw32/include``
4350 - ``some_directory/bin/../include``
4351
4352 This directory layout is standard for any toolchain you will find on the
4353 official `MinGW-w64 website <http://mingw-w64.sourceforge.net>`_.
4354
4355 Clang expects the GCC executable "gcc.exe" compiled for
4356 ``i686-w64-mingw32`` (or ``x86_64-w64-mingw32``) to be present on PATH.
4357
4358 `Some tests might fail <https://bugs.llvm.org/show_bug.cgi?id=9072>`_ on
4359 ``x86_64-w64-mingw32``.
4360
4361 AIX
4362 ^^^
4363 TOC Data Transformation
4364 """""""""""""""""""""""
4365 TOC data transformation is off by default (``-mno-tocdata``).
4366 When ``-mtocdata`` is specified, the TOC data transformation will be applied to
4367 all suitable variables with static storage duration, including static data
4368 members of classes and block-scope static variables (if not marked as exceptions,
4369 see further below).
4370
4371 Suitable variables must:
4372
4373 - have complete types
4374 - be independently generated (i.e., not placed in a pool)
4375 - be at most as large as a pointer
4376 - not be aligned more strictly than a pointer
4377 - not be structs containing flexible array members
4378 - not have internal linkage
4379 - not have aliases
4380 - not have section attributes
4381 - not be thread local storage
4382
4383 The TOC data transformation results in the variable, not its address,
4384 being placed in the TOC. This eliminates the need to load the address of the
4385 variable from the TOC.
4386
4387 Note:
4388 If the TOC data transformation is applied to a variable whose definition
4389 is imported, the linker will generate fixup code for reading or writing to the
4390 variable.
4391
4392 When multiple toc-data options are used, the last option used has the affect.
4393 For example: -mno-tocdata=g5,g1 -mtocdata=g1,g2 -mno-tocdata=g2 -mtocdata=g3,g4
4394 results in -mtocdata=g1,g3,g4
4395
4396 Names of variables not having external linkage will be ignored.
4397
4398 **Options:**
4399
4400 .. option:: -mno-tocdata
4401
4402 This is the default behaviour. Only variables explicitly specified with
4403 ``-mtocdata=`` will have the TOC data transformation applied.
4404
4405 .. option:: -mtocdata
4406
4407 Apply the TOC data transformation to all suitable variables with static
4408 storage duration (including static data members of classes and block-scope
4409 static variables) that are not explicitly specified with ``-mno-tocdata=``.
4410
4411 .. option:: -mno-tocdata=
4412
4413 Can be used in conjunction with ``-mtocdata`` to mark the comma-separated
4414 list of external linkage variables, specified using their mangled names, as
4415 exceptions to ``-mtocdata``.
4416
4417 .. option:: -mtocdata=
4418
4419 Apply the TOC data transformation to the comma-separated list of external
4420 linkage variables, specified using their mangled names, if they are suitable.
4421 Emit diagnostics for all unsuitable variables specified.
4422
4423 Default Visibility Export Mapping
4424 """""""""""""""""""""""""""""""""
4425 The ``-mdefault-visibility-export-mapping=`` option can be used to control
4426 mapping of default visibility to an explicit shared object export
4427 (i.e. XCOFF exported visibility). Three values are provided for the option:
4428
4429 * ``-mdefault-visibility-export-mapping=none``: no additional export
4430 information is created for entities with default visibility.
4431 * ``-mdefault-visibility-export-mapping=explicit``: mark entities for export
4432 if they have explicit (e.g. via an attribute) default visibility from the
4433 source, including RTTI.
4434 * ``-mdefault-visibility-export-mapping=all``: set XCOFF exported visibility
4435 for all entities with default visibility from any source. This gives a
4436 export behavior similar to ELF platforms where all entities with default
4437 visibility are exported.
4438
4439 .. _spir-v:
4440
4441 SPIR-V support
4442 --------------
4443
4444 Clang supports generation of SPIR-V conformant to `the OpenCL Environment
4445 Specification
4446 <https://www.khronos.org/registry/OpenCL/specs/3.0-unified/html/OpenCL_Env.html>`_.
4447
4448 To generate SPIR-V binaries, Clang uses the external ``llvm-spirv`` tool from the
4449 `SPIRV-LLVM-Translator repo
4450 <https://github.com/KhronosGroup/SPIRV-LLVM-Translator>`_.
4451
4452 Prior to the generation of SPIR-V binary with Clang, ``llvm-spirv``
4453 should be built or installed. Please refer to `the following instructions
4454 <https://github.com/KhronosGroup/SPIRV-LLVM-Translator#build-instructions>`_
4455 for more details. Clang will look for ``llvm-spirv-<LLVM-major-version>`` and
4456 ``llvm-spirv`` executables, in this order, in the ``PATH`` environment variable.
4457 Clang uses ``llvm-spirv`` with `the widely adopted assembly syntax package
4458 <https://github.com/KhronosGroup/SPIRV-LLVM-Translator/#build-with-spirv-tools>`_.
4459
4460 `The versioning
4461 <https://github.com/KhronosGroup/SPIRV-LLVM-Translator/releases>`_ of
4462 ``llvm-spirv`` is aligned with Clang major releases. The same applies to the
4463 main development branch. It is therefore important to ensure the ``llvm-spirv``
4464 version is in alignment with the Clang version. For troubleshooting purposes
4465 ``llvm-spirv`` can be `tested in isolation
4466 <https://github.com/KhronosGroup/SPIRV-LLVM-Translator#test-instructions>`_.
4467
4468 Example usage for OpenCL kernel compilation:
4469
4470 .. code-block:: console
4471
4472 $ clang --target=spirv32 -c test.cl
4473 $ clang --target=spirv64 -c test.cl
4474
4475 Both invocations of Clang will result in the generation of a SPIR-V binary file
4476 `test.o` for 32 bit and 64 bit respectively. This file can be imported
4477 by an OpenCL driver that support SPIR-V consumption or it can be compiled
4478 further by offline SPIR-V consumer tools.
4479
4480 Converting to SPIR-V produced with the optimization levels other than `-O0` is
4481 currently available as an experimental feature and it is not guaranteed to work
4482 in all cases.
4483
4484 Clang also supports integrated generation of SPIR-V without use of ``llvm-spirv``
4485 tool as an experimental feature when ``-fintegrated-objemitter`` flag is passed in
4486 the command line.
4487
4488 .. code-block:: console
4489
4490 $ clang --target=spirv32 -fintegrated-objemitter -c test.cl
4491
4492 Note that only very basic functionality is supported at this point and therefore
4493 it is not suitable for arbitrary use cases. This feature is only enabled when clang
4494 build is configured with ``-DLLVM_EXPERIMENTAL_TARGETS_TO_BUILD=SPIRV`` option.
4495
4496 Linking is done using ``spirv-link`` from `the SPIRV-Tools project
4497 <https://github.com/KhronosGroup/SPIRV-Tools#linker>`_. Similar to other external
4498 linkers, Clang will expect ``spirv-link`` to be installed separately and to be
4499 present in the ``PATH`` environment variable. Please refer to `the build and
4500 installation instructions
4501 <https://github.com/KhronosGroup/SPIRV-Tools#build>`_.
4502
4503 .. code-block:: console
4504
4505 $ clang --target=spirv64 test1.cl test2.cl
4506
4507 More information about the SPIR-V target settings and supported versions of SPIR-V
4508 format can be found in `the SPIR-V target guide
4509 <https://llvm.org/docs/SPIRVUsage.html>`__.
4510
4511 .. _clang-cl:
4512
4513 clang-cl
4514 ========
4515
4516 clang-cl is an alternative command-line interface to Clang, designed for
4517 compatibility with the Visual C++ compiler, cl.exe.
4518
4519 To enable clang-cl to find system headers, libraries, and the linker when run
4520 from the command-line, it should be executed inside a Visual Studio Native Tools
4521 Command Prompt or a regular Command Prompt where the environment has been set
4522 up using e.g. `vcvarsall.bat <https://msdn.microsoft.com/en-us/library/f2ccy3wt.aspx>`_.
4523
4524 clang-cl can also be used from inside Visual Studio by selecting the LLVM
4525 Platform Toolset. The toolset is not part of the installer, but may be installed
4526 separately from the
4527 `Visual Studio Marketplace <https://marketplace.visualstudio.com/items?itemName=LLVMExtensions.llvm-toolchain>`_.
4528 To use the toolset, select a project in Solution Explorer, open its Property
4529 Page (Alt+F7), and in the "General" section of "Configuration Properties"
4530 change "Platform Toolset" to LLVM. Doing so enables an additional Property
4531 Page for selecting the clang-cl executable to use for builds.
4532
4533 To use the toolset with MSBuild directly, invoke it with e.g.
4534 ``/p:PlatformToolset=LLVM``. This allows trying out the clang-cl toolchain
4535 without modifying your project files.
4536
4537 It's also possible to point MSBuild at clang-cl without changing toolset by
4538 passing ``/p:CLToolPath=c:\llvm\bin /p:CLToolExe=clang-cl.exe``.
4539
4540 When using CMake and the Visual Studio generators, the toolset can be set with the ``-T`` flag:
4541
4542 ::
4543
4544 cmake -G"Visual Studio 16 2019" -T LLVM ..
4545
4546 When using CMake with the Ninja generator, set the ``CMAKE_C_COMPILER`` and
4547 ``CMAKE_CXX_COMPILER`` variables to clang-cl:
4548
4549 ::
4550
4551 cmake -GNinja -DCMAKE_C_COMPILER="c:/Program Files (x86)/LLVM/bin/clang-cl.exe"
4552 -DCMAKE_CXX_COMPILER="c:/Program Files (x86)/LLVM/bin/clang-cl.exe" ..
4553
4554
4555 Command-Line Options
4556 --------------------
4557
4558 To be compatible with cl.exe, clang-cl supports most of the same command-line
4559 options. Those options can start with either ``/`` or ``-``. It also supports
4560 some of Clang's core options, such as the ``-W`` options.
4561
4562 Options that are known to clang-cl, but not currently supported, are ignored
4563 with a warning. For example:
4564
4565 ::
4566
4567 clang-cl.exe: warning: argument unused during compilation: '/AI'
4568
4569 To suppress warnings about unused arguments, use the ``-Qunused-arguments`` option.
4570
4571 Options that are not known to clang-cl will be ignored by default. Use the
4572 ``-Werror=unknown-argument`` option in order to treat them as errors. If these
4573 options are spelled with a leading ``/``, they will be mistaken for a filename:
4574
4575 ::
4576
4577 clang-cl.exe: error: no such file or directory: '/foobar'
4578
4579 Please `file a bug <https://github.com/llvm/llvm-project/issues/new?labels=clang-cl>`_
4580 for any valid cl.exe flags that clang-cl does not understand.
4581
4582 Execute ``clang-cl /?`` to see a list of supported options:
4583
4584 ::
4585
4586 CL.EXE COMPATIBILITY OPTIONS:
4587 /? Display available options
4588 /arch:<value> Set architecture for code generation
4589 /Brepro- Emit an object file which cannot be reproduced over time
4590 /Brepro Emit an object file which can be reproduced over time
4591 /clang:<arg> Pass <arg> to the clang driver
4592 /C Don't discard comments when preprocessing
4593 /c Compile only
4594 /d1PP Retain macro definitions in /E mode
4595 /d1reportAllClassLayout Dump record layout information
4596 /diagnostics:caret Enable caret and column diagnostics (on by default)
4597 /diagnostics:classic Disable column and caret diagnostics
4598 /diagnostics:column Disable caret diagnostics but keep column info
4599 /D <macro[=value]> Define macro
4600 /EH<value> Exception handling model
4601 /EP Disable linemarker output and preprocess to stdout
4602 /execution-charset:<value>
4603 Runtime encoding, supports only UTF-8
4604 /E Preprocess to stdout
4605 /FA Output assembly code file during compilation
4606 /Fa<file or directory> Output assembly code to this file during compilation (with /FA)
4607 /Fe<file or directory> Set output executable file or directory (ends in / or \)
4608 /FI <value> Include file before parsing
4609 /Fi<file> Set preprocess output file name (with /P)
4610 /Fo<file or directory> Set output object file, or directory (ends in / or \) (with /c)
4611 /fp:except-
4612 /fp:except
4613 /fp:fast
4614 /fp:precise
4615 /fp:strict
4616 /Fp<filename> Set pch filename (with /Yc and /Yu)
4617 /GA Assume thread-local variables are defined in the executable
4618 /Gd Set __cdecl as a default calling convention
4619 /GF- Disable string pooling
4620 /GF Enable string pooling (default)
4621 /GR- Disable emission of RTTI data
4622 /Gregcall Set __regcall as a default calling convention
4623 /GR Enable emission of RTTI data
4624 /Gr Set __fastcall as a default calling convention
4625 /GS- Disable buffer security check
4626 /GS Enable buffer security check (default)
4627 /Gs Use stack probes (default)
4628 /Gs<value> Set stack probe size (default 4096)
4629 /guard:<value> Enable Control Flow Guard with /guard:cf,
4630 or only the table with /guard:cf,nochecks.
4631 Enable EH Continuation Guard with /guard:ehcont
4632 /Gv Set __vectorcall as a default calling convention
4633 /Gw- Don't put each data item in its own section
4634 /Gw Put each data item in its own section
4635 /GX- Disable exception handling
4636 /GX Enable exception handling
4637 /Gy- Don't put each function in its own section (default)
4638 /Gy Put each function in its own section
4639 /Gz Set __stdcall as a default calling convention
4640 /help Display available options
4641 /imsvc <dir> Add directory to system include search path, as if part of %INCLUDE%
4642 /I <dir> Add directory to include search path
4643 /J Make char type unsigned
4644 /LDd Create debug DLL
4645 /LD Create DLL
4646 /link <options> Forward options to the linker
4647 /MDd Use DLL debug run-time
4648 /MD Use DLL run-time
4649 /MTd Use static debug run-time
4650 /MT Use static run-time
4651 /O0 Disable optimization
4652 /O1 Optimize for size (same as /Og /Os /Oy /Ob2 /GF /Gy)
4653 /O2 Optimize for speed (same as /Og /Oi /Ot /Oy /Ob2 /GF /Gy)
4654 /Ob0 Disable function inlining
4655 /Ob1 Only inline functions which are (explicitly or implicitly) marked inline
4656 /Ob2 Inline functions as deemed beneficial by the compiler
4657 /Ob3 Same as /Ob2
4658 /Od Disable optimization
4659 /Og No effect
4660 /Oi- Disable use of builtin functions
4661 /Oi Enable use of builtin functions
4662 /Os Optimize for size (like clang -Os)
4663 /Ot Optimize for speed (like clang -O3)
4664 /Ox Deprecated (same as /Og /Oi /Ot /Oy /Ob2); use /O2 instead
4665 /Oy- Disable frame pointer omission (x86 only, default)
4666 /Oy Enable frame pointer omission (x86 only)
4667 /O<flags> Set multiple /O flags at once; e.g. '/O2y-' for '/O2 /Oy-'
4668 /o <file or directory> Set output file or directory (ends in / or \)
4669 /P Preprocess to file
4670 /Qvec- Disable the loop vectorization passes
4671 /Qvec Enable the loop vectorization passes
4672 /showFilenames- Don't print the name of each compiled file (default)
4673 /showFilenames Print the name of each compiled file
4674 /showIncludes Print info about included files to stderr
4675 /source-charset:<value> Source encoding, supports only UTF-8
4676 /std:<value> Language standard to compile for
4677 /TC Treat all source files as C
4678 /Tc <filename> Specify a C source file
4679 /TP Treat all source files as C++
4680 /Tp <filename> Specify a C++ source file
4681 /utf-8 Set source and runtime encoding to UTF-8 (default)
4682 /U <macro> Undefine macro
4683 /vd<value> Control vtordisp placement
4684 /vmb Use a best-case representation method for member pointers
4685 /vmg Use a most-general representation for member pointers
4686 /vmm Set the default most-general representation to multiple inheritance
4687 /vms Set the default most-general representation to single inheritance
4688 /vmv Set the default most-general representation to virtual inheritance
4689 /volatile:iso Volatile loads and stores have standard semantics
4690 /volatile:ms Volatile loads and stores have acquire and release semantics
4691 /W0 Disable all warnings
4692 /W1 Enable -Wall
4693 /W2 Enable -Wall
4694 /W3 Enable -Wall
4695 /W4 Enable -Wall and -Wextra
4696 /Wall Enable -Weverything
4697 /WX- Do not treat warnings as errors
4698 /WX Treat warnings as errors
4699 /w Disable all warnings
4700 /X Don't add %INCLUDE% to the include search path
4701 /Y- Disable precompiled headers, overrides /Yc and /Yu
4702 /Yc<filename> Generate a pch file for all code up to and including <filename>
4703 /Yu<filename> Load a pch file and use it instead of all code up to and including <filename>
4704 /Z7 Enable CodeView debug information in object files
4705 /Zc:char8_t Enable C++20 char8_t type
4706 /Zc:char8_t- Disable C++20 char8_t type
4707 /Zc:dllexportInlines- Don't dllexport/dllimport inline member functions of dllexport/import classes
4708 /Zc:dllexportInlines dllexport/dllimport inline member functions of dllexport/import classes (default)
4709 /Zc:sizedDealloc- Disable C++14 sized global deallocation functions
4710 /Zc:sizedDealloc Enable C++14 sized global deallocation functions
4711 /Zc:strictStrings Treat string literals as const
4712 /Zc:threadSafeInit- Disable thread-safe initialization of static variables
4713 /Zc:threadSafeInit Enable thread-safe initialization of static variables
4714 /Zc:trigraphs- Disable trigraphs (default)
4715 /Zc:trigraphs Enable trigraphs
4716 /Zc:twoPhase- Disable two-phase name lookup in templates
4717 /Zc:twoPhase Enable two-phase name lookup in templates
4718 /Zi Alias for /Z7. Does not produce PDBs.
4719 /Zl Don't mention any default libraries in the object file
4720 /Zp Set the default maximum struct packing alignment to 1
4721 /Zp<value> Specify the default maximum struct packing alignment
4722 /Zs Run the preprocessor, parser and semantic analysis stages
4723
4724 OPTIONS:
4725 -### Print (but do not run) the commands to run for this compilation
4726 --analyze Run the static analyzer
4727 -faddrsig Emit an address-significance table
4728 -fansi-escape-codes Use ANSI escape codes for diagnostics
4729 -fblocks Enable the 'blocks' language feature
4730 -fcf-protection=<value> Instrument control-flow architecture protection. Options: return, branch, full, none.
4731 -fcf-protection Enable cf-protection in 'full' mode
4732 -fcolor-diagnostics Use colors in diagnostics
4733 -fcomplete-member-pointers
4734 Require member pointer base types to be complete if they would be significant under the Microsoft ABI
4735 -fcoverage-mapping Generate coverage mapping to enable code coverage analysis
4736 -fcrash-diagnostics-dir=<dir>
4737 Put crash-report files in <dir>
4738 -fdebug-macro Emit macro debug information
4739 -fdelayed-template-parsing
4740 Parse templated function definitions at the end of the translation unit
4741 -fdiagnostics-absolute-paths
4742 Print absolute paths in diagnostics
4743 -fdiagnostics-parseable-fixits
4744 Print fix-its in machine parseable form
4745 -flto=<value> Set LTO mode to either 'full' or 'thin'
4746 -flto Enable LTO in 'full' mode
4747 -fmerge-all-constants Allow merging of constants
4748 -fmodule-file=<module_name>=<module-file>
4749 Use the specified module file that provides the module <module_name>
4750 -fmodule-header=<header>
4751 Build <header> as a C++20 header unit
4752 -fmodule-output=<path>
4753 Save intermediate module file results when compiling a standard C++ module unit.
4754 -fms-compatibility-version=<value>
4755 Dot-separated value representing the Microsoft compiler version
4756 number to report in _MSC_VER (0 = don't define it; default is same value as installed cl.exe, or 1933)
4757 -fms-compatibility Enable full Microsoft Visual C++ compatibility
4758 -fms-extensions Accept some non-standard constructs supported by the Microsoft compiler
4759 -fmsc-version=<value> Microsoft compiler version number to report in _MSC_VER
4760 (0 = don't define it; default is same value as installed cl.exe, or 1933)
4761 -fno-addrsig Don't emit an address-significance table
4762 -fno-builtin-<value> Disable implicit builtin knowledge of a specific function
4763 -fno-builtin Disable implicit builtin knowledge of functions
4764 -fno-complete-member-pointers
4765 Do not require member pointer base types to be complete if they would be significant under the Microsoft ABI
4766 -fno-coverage-mapping Disable code coverage analysis
4767 -fno-crash-diagnostics Disable auto-generation of preprocessed source files and a script for reproduction during a clang crash
4768 -fno-debug-macro Do not emit macro debug information
4769 -fno-delayed-template-parsing
4770 Disable delayed template parsing
4771 -fno-sanitize-address-poison-custom-array-cookie
4772 Disable poisoning array cookies when using custom operator new[] in AddressSanitizer
4773 -fno-sanitize-address-use-after-scope
4774 Disable use-after-scope detection in AddressSanitizer
4775 -fno-sanitize-address-use-odr-indicator
4776 Disable ODR indicator globals
4777 -fno-sanitize-ignorelist Don't use ignorelist file for sanitizers
4778 -fno-sanitize-cfi-cross-dso
4779 Disable control flow integrity (CFI) checks for cross-DSO calls.
4780 -fno-sanitize-coverage=<value>
4781 Disable specified features of coverage instrumentation for Sanitizers
4782 -fno-sanitize-memory-track-origins
4783 Disable origins tracking in MemorySanitizer
4784 -fno-sanitize-memory-use-after-dtor
4785 Disable use-after-destroy detection in MemorySanitizer
4786 -fno-sanitize-recover=<value>
4787 Disable recovery for specified sanitizers
4788 -fno-sanitize-stats Disable sanitizer statistics gathering.
4789 -fno-sanitize-thread-atomics
4790 Disable atomic operations instrumentation in ThreadSanitizer
4791 -fno-sanitize-thread-func-entry-exit
4792 Disable function entry/exit instrumentation in ThreadSanitizer
4793 -fno-sanitize-thread-memory-access
4794 Disable memory access instrumentation in ThreadSanitizer
4795 -fno-sanitize-trap=<value>
4796 Disable trapping for specified sanitizers
4797 -fno-standalone-debug Limit debug information produced to reduce size of debug binary
4798 -fno-strict-aliasing Disable optimizations based on strict aliasing rules (default)
4799 -fobjc-runtime=<value> Specify the target Objective-C runtime kind and version
4800 -fprofile-exclude-files=<value>
4801 Instrument only functions from files where names don't match all the regexes separated by a semi-colon
4802 -fprofile-filter-files=<value>
4803 Instrument only functions from files where names match any regex separated by a semi-colon
4804 -fprofile-generate=<dirname>
4805 Generate instrumented code to collect execution counts into a raw profile file in the directory specified by the argument. The filename uses default_%m.profraw pattern
4806 (overridden by LLVM_PROFILE_FILE env var)
4807 -fprofile-generate
4808 Generate instrumented code to collect execution counts into default_%m.profraw file
4809 (overridden by '=' form of option or LLVM_PROFILE_FILE env var)
4810 -fprofile-instr-generate=<file_name_pattern>
4811 Generate instrumented code to collect execution counts into the file whose name pattern is specified as the argument
4812 (overridden by LLVM_PROFILE_FILE env var)
4813 -fprofile-instr-generate
4814 Generate instrumented code to collect execution counts into default.profraw file
4815 (overridden by '=' form of option or LLVM_PROFILE_FILE env var)
4816 -fprofile-instr-use=<value>
4817 Use instrumentation data for coverage testing or profile-guided optimization
4818 -fprofile-use=<value>
4819 Use instrumentation data for profile-guided optimization
4820 -fprofile-remapping-file=<file>
4821 Use the remappings described in <file> to match the profile data against names in the program
4822 -fprofile-list=<file>
4823 Filename defining the list of functions/files to instrument
4824 -fsanitize-address-field-padding=<value>
4825 Level of field padding for AddressSanitizer
4826 -fsanitize-address-globals-dead-stripping
4827 Enable linker dead stripping of globals in AddressSanitizer
4828 -fsanitize-address-poison-custom-array-cookie
4829 Enable poisoning array cookies when using custom operator new[] in AddressSanitizer
4830 -fsanitize-address-use-after-return=<mode>
4831 Select the mode of detecting stack use-after-return in AddressSanitizer: never | runtime (default) | always
4832 -fsanitize-address-use-after-scope
4833 Enable use-after-scope detection in AddressSanitizer
4834 -fsanitize-address-use-odr-indicator
4835 Enable ODR indicator globals to avoid false ODR violation reports in partially sanitized programs at the cost of an increase in binary size
4836 -fsanitize-ignorelist=<value>
4837 Path to ignorelist file for sanitizers
4838 -fsanitize-cfi-cross-dso
4839 Enable control flow integrity (CFI) checks for cross-DSO calls.
4840 -fsanitize-cfi-icall-generalize-pointers
4841 Generalize pointers in CFI indirect call type signature checks
4842 -fsanitize-coverage=<value>
4843 Specify the type of coverage instrumentation for Sanitizers
4844 -fsanitize-hwaddress-abi=<value>
4845 Select the HWAddressSanitizer ABI to target (interceptor or platform, default interceptor)
4846 -fsanitize-memory-track-origins=<value>
4847 Enable origins tracking in MemorySanitizer
4848 -fsanitize-memory-track-origins
4849 Enable origins tracking in MemorySanitizer
4850 -fsanitize-memory-use-after-dtor
4851 Enable use-after-destroy detection in MemorySanitizer
4852 -fsanitize-recover=<value>
4853 Enable recovery for specified sanitizers
4854 -fsanitize-stats Enable sanitizer statistics gathering.
4855 -fsanitize-thread-atomics
4856 Enable atomic operations instrumentation in ThreadSanitizer (default)
4857 -fsanitize-thread-func-entry-exit
4858 Enable function entry/exit instrumentation in ThreadSanitizer (default)
4859 -fsanitize-thread-memory-access
4860 Enable memory access instrumentation in ThreadSanitizer (default)
4861 -fsanitize-trap=<value> Enable trapping for specified sanitizers
4862 -fsanitize-undefined-strip-path-components=<number>
4863 Strip (or keep only, if negative) a given number of path components when emitting check metadata.
4864 -fsanitize=<check> Turn on runtime checks for various forms of undefined or suspicious
4865 behavior. See user manual for available checks
4866 -fsplit-lto-unit Enables splitting of the LTO unit.
4867 -fstandalone-debug Emit full debug info for all types used by the program
4868 -fstrict-aliasing Enable optimizations based on strict aliasing rules
4869 -fsyntax-only Run the preprocessor, parser and semantic analysis stages
4870 -fwhole-program-vtables Enables whole-program vtable optimization. Requires -flto
4871 -gcodeview-ghash Emit type record hashes in a .debug$H section
4872 -gcodeview Generate CodeView debug information
4873 -gline-directives-only Emit debug line info directives only
4874 -gline-tables-only Emit debug line number tables only
4875 -miamcu Use Intel MCU ABI
4876 -mllvm <value> Additional arguments to forward to LLVM's option processing
4877 -nobuiltininc Disable builtin #include directories
4878 -Qunused-arguments Don't emit warning for unused driver arguments
4879 -R<remark> Enable the specified remark
4880 --target=<value> Generate code for the given target
4881 --version Print version information
4882 -v Show commands to run and use verbose output
4883 -W<warning> Enable the specified warning
4884 -Xclang <arg> Pass <arg> to the clang compiler
4885
4886 The /clang: Option
4887 ^^^^^^^^^^^^^^^^^^
4888
4889 When clang-cl is run with a set of ``/clang:<arg>`` options, it will gather all
4890 of the ``<arg>`` arguments and process them as if they were passed to the clang
4891 driver. This mechanism allows you to pass flags that are not exposed in the
4892 clang-cl options or flags that have a different meaning when passed to the clang
4893 driver. Regardless of where they appear in the command line, the ``/clang:``
4894 arguments are treated as if they were passed at the end of the clang-cl command
4895 line.
4896
4897 The /Zc:dllexportInlines- Option
4898 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4899
4900 This causes the class-level `dllexport` and `dllimport` attributes to not apply
4901 to inline member functions, as they otherwise would. For example, in the code
4902 below `S::foo()` would normally be defined and exported by the DLL, but when
4903 using the ``/Zc:dllexportInlines-`` flag it is not:
4904
4905 .. code-block:: c
4906
4907 struct __declspec(dllexport) S {
4908 void foo() {}
4909 }
4910
4911 This has the benefit that the compiler doesn't need to emit a definition of
4912 `S::foo()` in every translation unit where the declaration is included, as it
4913 would otherwise do to ensure there's a definition in the DLL even if it's not
4914 used there. If the declaration occurs in a header file that's widely used, this
4915 can save significant compilation time and output size. It also reduces the
4916 number of functions exported by the DLL similarly to what
4917 ``-fvisibility-inlines-hidden`` does for shared objects on ELF and Mach-O.
4918 Since the function declaration comes with an inline definition, users of the
4919 library can use that definition directly instead of importing it from the DLL.
4920
4921 Note that the Microsoft Visual C++ compiler does not support this option, and
4922 if code in a DLL is compiled with ``/Zc:dllexportInlines-``, the code using the
4923 DLL must be compiled in the same way so that it doesn't attempt to dllimport
4924 the inline member functions. The reverse scenario should generally work though:
4925 a DLL compiled without this flag (such as a system library compiled with Visual
4926 C++) can be referenced from code compiled using the flag, meaning that the
4927 referencing code will use the inline definitions instead of importing them from
4928 the DLL.
4929
4930 Also note that like when using ``-fvisibility-inlines-hidden``, the address of
4931 `S::foo()` will be different inside and outside the DLL, breaking the C/C++
4932 standard requirement that functions have a unique address.
4933
4934 The flag does not apply to explicit class template instantiation definitions or
4935 declarations, as those are typically used to explicitly provide a single
4936 definition in a DLL, (dllexported instantiation definition) or to signal that
4937 the definition is available elsewhere (dllimport instantiation declaration). It
4938 also doesn't apply to inline members with static local variables, to ensure
4939 that the same instance of the variable is used inside and outside the DLL.
4940
4941 Using this flag can cause problems when inline functions that would otherwise
4942 be dllexported refer to internal symbols of a DLL. For example:
4943
4944 .. code-block:: c
4945
4946 void internal();
4947
4948 struct __declspec(dllimport) S {
4949 void foo() { internal(); }
4950 }
4951
4952 Normally, references to `S::foo()` would use the definition in the DLL from
4953 which it was exported, and which presumably also has the definition of
4954 `internal()`. However, when using ``/Zc:dllexportInlines-``, the inline
4955 definition of `S::foo()` is used directly, resulting in a link error since
4956 `internal()` is not available. Even worse, if there is an inline definition of
4957 `internal()` containing a static local variable, we will now refer to a
4958 different instance of that variable than in the DLL:
4959
4960 .. code-block:: c
4961
4962 inline int internal() { static int x; return x++; }
4963
4964 struct __declspec(dllimport) S {
4965 int foo() { return internal(); }
4966 }
4967
4968 This could lead to very subtle bugs. Using ``-fvisibility-inlines-hidden`` can
4969 lead to the same issue. To avoid it in this case, make `S::foo()` or
4970 `internal()` non-inline, or mark them `dllimport/dllexport` explicitly.
4971
4972 Finding Clang runtime libraries
4973 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4974
4975 clang-cl supports several features that require runtime library support:
4976
4977 - Address Sanitizer (ASan): ``-fsanitize=address``
4978 - Undefined Behavior Sanitizer (UBSan): ``-fsanitize=undefined``
4979 - Code coverage: ``-fprofile-instr-generate -fcoverage-mapping``
4980 - Profile Guided Optimization (PGO): ``-fprofile-generate``
4981 - Certain math operations (int128 division) require the builtins library
4982
4983 In order to use these features, the user must link the right runtime libraries
4984 into their program. These libraries are distributed alongside Clang in the
4985 library resource directory. Clang searches for the resource directory by
4986 searching relative to the Clang executable. For example, if LLVM is installed
4987 in ``C:\Program Files\LLVM``, then the profile runtime library will be located
4988 at the path
4989 ``C:\Program Files\LLVM\lib\clang\11.0.0\lib\windows\clang_rt.profile-x86_64.lib``.
4990
4991 For UBSan, PGO, and coverage, Clang will emit object files that auto-link the
4992 appropriate runtime library, but the user generally needs to help the linker
4993 (whether it is ``lld-link.exe`` or MSVC ``link.exe``) find the library resource
4994 directory. Using the example installation above, this would mean passing
4995 ``/LIBPATH:C:\Program Files\LLVM\lib\clang\11.0.0\lib\windows`` to the linker.
4996 If the user links the program with the ``clang`` or ``clang-cl`` drivers, the
4997 driver will pass this flag for them.
4998
4999 The auto-linking can be disabled with -fno-rtlib-defaultlib. If that flag is
5000 used, pass the complete flag to required libraries as described for ASan below.
5001
5002 If the linker cannot find the appropriate library, it will emit an error like
5003 this::
5004
5005 $ clang-cl -c -fsanitize=undefined t.cpp
5006
5007 $ lld-link t.obj -dll
5008 lld-link: error: could not open 'clang_rt.ubsan_standalone-x86_64.lib': no such file or directory
5009 lld-link: error: could not open 'clang_rt.ubsan_standalone_cxx-x86_64.lib': no such file or directory
5010
5011 $ link t.obj -dll -nologo
5012 LINK : fatal error LNK1104: cannot open file 'clang_rt.ubsan_standalone-x86_64.lib'
5013
5014 To fix the error, add the appropriate ``/libpath:`` flag to the link line.
5015
5016 For ASan, as of this writing, the user is also responsible for linking against
5017 the correct ASan libraries.
5018
5019 If the user is using the dynamic CRT (``/MD``), then they should add
5020 ``clang_rt.asan_dynamic-x86_64.lib`` to the link line as a regular input. For
5021 other architectures, replace x86_64 with the appropriate name here and below.
5022
5023 If the user is using the static CRT (``/MT``), then different runtimes are used
5024 to produce DLLs and EXEs. To link a DLL, pass
5025 ``clang_rt.asan_dll_thunk-x86_64.lib``. To link an EXE, pass
5026 ``-wholearchive:clang_rt.asan-x86_64.lib``.
5027
5028 Windows System Headers and Library Lookup
5029 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
5030
5031 clang-cl uses a set of different approaches to locate the right system libraries
5032 to link against when building code. The Windows environment uses libraries from
5033 three distinct sources:
5034
5035 1. Windows SDK
5036 2. UCRT (Universal C Runtime)
5037 3. Visual C++ Tools (VCRuntime)
5038
5039 The Windows SDK provides the import libraries and headers required to build
5040 programs against the Windows system packages. Underlying the Windows SDK is the
5041 UCRT, the universal C runtime.
5042
5043 This difference is best illustrated by the various headers that one would find
5044 in the different categories. The WinSDK would contain headers such as
5045 `WinSock2.h` which is part of the Windows API surface, providing the Windows
5046 socketing interfaces for networking. UCRT provides the C library headers,
5047 including e.g. `stdio.h`. Finally, the Visual C++ tools provides the underlying
5048 Visual C++ Runtime headers such as `stdint.h` or `crtdefs.h`.
5049
5050 There are various controls that allow the user control over where clang-cl will
5051 locate these headers. The default behaviour for the Windows SDK and UCRT is as
5052 follows:
5053
5054 1. Consult the command line.
5055
5056 Anything the user specifies is always given precedence. The following
5057 extensions are part of the clang-cl toolset:
5058
5059 - `/winsysroot:`
5060
5061 The `/winsysroot:` is used as an equivalent to `-sysroot` on Unix
5062 environments. It allows the control of an alternate location to be treated
5063 as a system root. When specified, it will be used as the root where the
5064 `Windows Kits` is located.
5065
5066 - `/winsdkversion:`
5067 - `/winsdkdir:`
5068
5069 If `/winsysroot:` is not specified, the `/winsdkdir:` argument is consulted
5070 as a location to identify where the Windows SDK is located. Contrary to
5071 `/winsysroot:`, `/winsdkdir:` is expected to be the complete path rather
5072 than a root to locate `Windows Kits`.
5073
5074 The `/winsdkversion:` flag allows the user to specify a version identifier
5075 for the SDK to prefer. When this is specified, no additional validation is
5076 performed and this version is preferred. If the version is not specified,
5077 the highest detected version number will be used.
5078
5079 2. Consult the environment.
5080
5081 TODO: This is not yet implemented.
5082
5083 This will consult the environment variables:
5084
5085 - `WindowsSdkDir`
5086 - `UCRTVersion`
5087
5088 3. Fallback to the registry.
5089
5090 If no arguments are used to indicate where the SDK is present, and the
5091 compiler is running on Windows, the registry is consulted to locate the
5092 installation.
5093
5094 The Visual C++ Toolset has a slightly more elaborate mechanism for detection.
5095
5096 1. Consult the command line.
5097
5098 - `/winsysroot:`
5099
5100 The `/winsysroot:` is used as an equivalent to `-sysroot` on Unix
5101 environments. It allows the control of an alternate location to be treated
5102 as a system root. When specified, it will be used as the root where the
5103 `VC` directory is located.
5104
5105 - `/vctoolsdir:`
5106 - `/vctoolsversion:`
5107
5108 If `/winsysroot:` is not specified, the `/vctoolsdir:` argument is consulted
5109 as a location to identify where the Visual C++ Tools are located. If
5110 `/vctoolsversion:` is specified, that version is preferred, otherwise, the
5111 highest version detected is used.
5112
5113 2. Consult the environment.
5114
5115 - `/external:[VARIABLE]`
5116
5117 This specifies a user identified environment variable which is treated as
5118 a path delimiter (`;`) separated list of paths to map into `-imsvc`
5119 arguments which are treated as `-isystem`.
5120
5121 - `INCLUDE` and `EXTERNAL_INCLUDE`
5122
5123 The path delimiter (`;`) separated list of paths will be mapped to
5124 `-imsvc` arguments which are treated as `-isystem`.
5125
5126 - `LIB` (indirectly)
5127
5128 The linker `link.exe` or `lld-link.exe` will honour the environment
5129 variable `LIB` which is a path delimiter (`;`) set of paths to consult for
5130 the import libraries to use when linking the final target.
5131
5132 The following environment variables will be consulted and used to form paths
5133 to validate and load content from as appropriate:
5134
5135 - `VCToolsInstallDir`
5136 - `VCINSTALLDIR`
5137 - `Path`
5138
5139 3. Consult `ISetupConfiguration` [Windows Only]
5140
5141 Assuming that the toolchain is built with `USE_MSVC_SETUP_API` defined and
5142 is running on Windows, the Visual Studio COM interface `ISetupConfiguration`
5143 will be used to locate the installation of the MSVC toolset.
5144
5145 4. Fallback to the registry [DEPRECATED]
5146
5147 The registry information is used to help locate the installation as a final
5148 fallback. This is only possible for pre-VS2017 installations and is
5149 considered deprecated.
5150
5151 Restrictions and Limitations compared to Clang
5152 ----------------------------------------------
5153
5154 Strict Aliasing
5155 ^^^^^^^^^^^^^^^
5156
5157 Strict aliasing (TBAA) is always off by default in clang-cl. Whereas in clang,
5158 strict aliasing is turned on by default for all optimization levels.
5159
5160 To enable LLVM optimizations based on strict aliasing rules (e.g., optimizations
5161 based on type of expressions in C/C++), user will need to explicitly pass
5162 `-fstrict-aliasing` to clang-cl.