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