blob: 5170bfd026f3d405c1d129e211ba51c57e828c11 [file] [log] [blame]
Sean Silva93ca0212012-12-13 01:10:46 +00001============================
2Clang Compiler User's Manual
3============================
4
5.. contents::
6 :local:
7
8Introduction
9============
10
11The Clang Compiler is an open-source compiler for the C family of
12programming languages, aiming to be the best in class implementation of
13these languages. Clang builds on the LLVM optimizer and code generator,
14allowing it to provide high-quality optimization and code generation
15support for many targets. For more general information, please see the
16`Clang Web Site <http://clang.llvm.org>`_ or the `LLVM Web
17Site <http://llvm.org>`_.
18
19This document describes important notes about using Clang as a compiler
20for an end-user, documenting the supported features, command line
21options, etc. If you are interested in using Clang to build a tool that
Dmitri Gribenko5cc05802012-12-15 20:41:17 +000022processes code, please see :doc:`InternalsManual`. If you are interested in the
23`Clang Static Analyzer <http://clang-analyzer.llvm.org>`_, please see its web
Sean Silva93ca0212012-12-13 01:10:46 +000024page.
25
26Clang is designed to support the C family of programming languages,
27which includes :ref:`C <c>`, :ref:`Objective-C <objc>`, :ref:`C++ <cxx>`, and
28:ref:`Objective-C++ <objcxx>` as well as many dialects of those. For
29language-specific information, please see the corresponding language
30specific section:
31
32- :ref:`C Language <c>`: K&R C, ANSI C89, ISO C90, ISO C94 (C89+AMD1), ISO
33 C99 (+TC1, TC2, TC3).
34- :ref:`Objective-C Language <objc>`: ObjC 1, ObjC 2, ObjC 2.1, plus
35 variants depending on base language.
36- :ref:`C++ Language <cxx>`
37- :ref:`Objective C++ Language <objcxx>`
38
39In addition to these base languages and their dialects, Clang supports a
40broad variety of language extensions, which are documented in the
41corresponding language section. These extensions are provided to be
42compatible with the GCC, Microsoft, and other popular compilers as well
43as to improve functionality through Clang-specific features. The Clang
44driver and language features are intentionally designed to be as
45compatible with the GNU GCC compiler as reasonably possible, easing
46migration from GCC to Clang. In most cases, code "just works".
47
48In addition to language specific features, Clang has a variety of
49features that depend on what CPU architecture or operating system is
50being compiled for. Please see the :ref:`Target-Specific Features and
51Limitations <target_features>` section for more details.
52
53The rest of the introduction introduces some basic :ref:`compiler
54terminology <terminology>` that is used throughout this manual and
55contains a basic :ref:`introduction to using Clang <basicusage>` as a
56command line compiler.
57
58.. _terminology:
59
60Terminology
61-----------
62
63Front end, parser, backend, preprocessor, undefined behavior,
64diagnostic, optimizer
65
66.. _basicusage:
67
68Basic Usage
69-----------
70
71Intro to how to use a C compiler for newbies.
72
73compile + link compile then link debug info enabling optimizations
74picking a language to use, defaults to C99 by default. Autosenses based
75on extension. using a makefile
76
77Command Line Options
78====================
79
80This section is generally an index into other sections. It does not go
81into depth on the ones that are covered by other sections. However, the
82first part introduces the language selection and other high level
83options like -c, -g, etc.
84
85Options to Control Error and Warning Messages
86---------------------------------------------
87
88**-Werror**: Turn warnings into errors.
89
90**-Werror=foo**: Turn warning "foo" into an error.
91
92**-Wno-error=foo**: Turn warning "foo" into an warning even if -Werror
93is specified.
94
95**-Wfoo**: Enable warning "foo".
96
97**-Wno-foo**: Disable warning "foo".
98
99**-w**: Disable all warnings.
100
101**-Weverything**: :ref:`Enable **all**
102warnings. <diagnostics_enable_everything>`
103
104**-pedantic**: Warn on language extensions.
105
106**-pedantic-errors**: Error on language extensions.
107
108**-Wsystem-headers**: Enable warnings from system headers.
109
110**-ferror-limit=123**: Stop emitting diagnostics after 123 errors have
111been produced. The default is 20, and the error limit can be disabled
112with -ferror-limit=0.
113
114**-ftemplate-backtrace-limit=123**: Only emit up to 123 template
115instantiation notes within the template instantiation backtrace for a
116single warning or error. The default is 10, and the limit can be
117disabled with -ftemplate-backtrace-limit=0.
118
119.. _cl_diag_formatting:
120
121Formatting of Diagnostics
122^^^^^^^^^^^^^^^^^^^^^^^^^
123
124Clang aims to produce beautiful diagnostics by default, particularly for
125new users that first come to Clang. However, different people have
126different preferences, and sometimes Clang is driven by another program
127that wants to parse simple and consistent output, not a person. For
128these cases, Clang provides a wide range of options to control the exact
129output format of the diagnostics that it generates.
130
131.. _opt_fshow-column:
132
133**-f[no-]show-column**
134 Print column number in diagnostic.
135
136 This option, which defaults to on, controls whether or not Clang
137 prints the column number of a diagnostic. For example, when this is
138 enabled, Clang will print something like:
139
140 ::
141
142 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
143 #endif bad
144 ^
145 //
146
147 When this is disabled, Clang will print "test.c:28: warning..." with
148 no column number.
149
150 The printed column numbers count bytes from the beginning of the
151 line; take care if your source contains multibyte characters.
152
153.. _opt_fshow-source-location:
154
155**-f[no-]show-source-location**
156 Print source file/line/column information in diagnostic.
157
158 This option, which defaults to on, controls whether or not Clang
159 prints the filename, line number and column number of a diagnostic.
160 For example, when this is enabled, Clang will print something like:
161
162 ::
163
164 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
165 #endif bad
166 ^
167 //
168
169 When this is disabled, Clang will not print the "test.c:28:8: "
170 part.
171
172.. _opt_fcaret-diagnostics:
173
174**-f[no-]caret-diagnostics**
175 Print source line and ranges from source code in diagnostic.
176 This option, which defaults to on, controls whether or not Clang
177 prints the source line, source ranges, and caret when emitting a
178 diagnostic. For example, when this is enabled, Clang will print
179 something like:
180
181 ::
182
183 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
184 #endif bad
185 ^
186 //
187
188**-f[no-]color-diagnostics**
189 This option, which defaults to on when a color-capable terminal is
190 detected, controls whether or not Clang prints diagnostics in color.
191
192 When this option is enabled, Clang will use colors to highlight
193 specific parts of the diagnostic, e.g.,
194
195 .. nasty hack to not lose our dignity
196
197 .. raw:: html
198
199 <pre>
200 <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>
201 #endif bad
202 <span style="color:green">^</span>
203 <span style="color:green">//</span>
204 </pre>
205
206 When this is disabled, Clang will just print:
207
208 ::
209
210 test.c:2:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
211 #endif bad
212 ^
213 //
214
215**-fdiagnostics-format=clang/msvc/vi**
216 Changes diagnostic output format to better match IDEs and command line tools.
217
218 This option controls the output format of the filename, line number,
219 and column printed in diagnostic messages. The options, and their
220 affect on formatting a simple conversion diagnostic, follow:
221
222 **clang** (default)
223 ::
224
225 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int'
226
227 **msvc**
228 ::
229
230 t.c(3,11) : warning: conversion specifies type 'char *' but the argument has type 'int'
231
232 **vi**
233 ::
234
235 t.c +3:11: warning: conversion specifies type 'char *' but the argument has type 'int'
236
237**-f[no-]diagnostics-show-name**
238 Enable the display of the diagnostic name.
239 This option, which defaults to off, controls whether or not Clang
240 prints the associated name.
241
242.. _opt_fdiagnostics-show-option:
243
244**-f[no-]diagnostics-show-option**
245 Enable ``[-Woption]`` information in diagnostic line.
246
247 This option, which defaults to on, controls whether or not Clang
248 prints the associated :ref:`warning group <cl_diag_warning_groups>`
249 option name when outputting a warning diagnostic. For example, in
250 this output:
251
252 ::
253
254 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
255 #endif bad
256 ^
257 //
258
259 Passing **-fno-diagnostics-show-option** will prevent Clang from
260 printing the [:ref:`-Wextra-tokens <opt_Wextra-tokens>`] information in
261 the diagnostic. This information tells you the flag needed to enable
262 or disable the diagnostic, either from the command line or through
263 :ref:`#pragma GCC diagnostic <pragma_GCC_diagnostic>`.
264
265.. _opt_fdiagnostics-show-category:
266
267**-fdiagnostics-show-category=none/id/name**
268 Enable printing category information in diagnostic line.
269
270 This option, which defaults to "none", controls whether or not Clang
271 prints the category associated with a diagnostic when emitting it.
272 Each diagnostic may or many not have an associated category, if it
273 has one, it is listed in the diagnostic categorization field of the
274 diagnostic line (in the []'s).
275
276 For example, a format string warning will produce these three
277 renditions based on the setting of this option:
278
279 ::
280
281 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat]
282 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat,1]
283 t.c:3:11: warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat,Format String]
284
285 This category can be used by clients that want to group diagnostics
286 by category, so it should be a high level category. We want dozens
287 of these, not hundreds or thousands of them.
288
289.. _opt_fdiagnostics-fixit-info:
290
291**-f[no-]diagnostics-fixit-info**
292 Enable "FixIt" information in the diagnostics output.
293
294 This option, which defaults to on, controls whether or not Clang
295 prints the information on how to fix a specific diagnostic
296 underneath it when it knows. For example, in this output:
297
298 ::
299
300 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
301 #endif bad
302 ^
303 //
304
305 Passing **-fno-diagnostics-fixit-info** will prevent Clang from
306 printing the "//" line at the end of the message. This information
307 is useful for users who may not understand what is wrong, but can be
308 confusing for machine parsing.
309
310.. _opt_fdiagnostics-print-source-range-info:
311
312**-f[no-]diagnostics-print-source-range-info**
313 Print machine parsable information about source ranges.
314 This option, which defaults to off, controls whether or not Clang
315 prints information about source ranges in a machine parsable format
316 after the file/line/column number information. The information is a
317 simple sequence of brace enclosed ranges, where each range lists the
318 start and end line/column locations. For example, in this output:
319
320 ::
321
322 exprs.c:47:15:{47:8-47:14}{47:17-47:24}: error: invalid operands to binary expression ('int *' and '_Complex float')
323 P = (P-42) + Gamma*4;
324 ~~~~~~ ^ ~~~~~~~
325
326 The {}'s are generated by -fdiagnostics-print-source-range-info.
327
328 The printed column numbers count bytes from the beginning of the
329 line; take care if your source contains multibyte characters.
330
331**-fdiagnostics-parseable-fixits**
332 Print Fix-Its in a machine parseable form.
333
334 This option makes Clang print available Fix-Its in a machine
335 parseable format at the end of diagnostics. The following example
336 illustrates the format:
337
338 ::
339
340 fix-it:"t.cpp":{7:25-7:29}:"Gamma"
341
342 The range printed is a half-open range, so in this example the
343 characters at column 25 up to but not including column 29 on line 7
344 in t.cpp should be replaced with the string "Gamma". Either the
345 range or the replacement string may be empty (representing strict
346 insertions and strict erasures, respectively). Both the file name
347 and the insertion string escape backslash (as "\\\\"), tabs (as
348 "\\t"), newlines (as "\\n"), double quotes(as "\\"") and
349 non-printable characters (as octal "\\xxx").
350
351 The printed column numbers count bytes from the beginning of the
352 line; take care if your source contains multibyte characters.
353
354**-fno-elide-type**
355 Turns off elision in template type printing.
356
357 The default for template type printing is to elide as many template
358 arguments as possible, removing those which are the same in both
359 template types, leaving only the differences. Adding this flag will
360 print all the template arguments. If supported by the terminal,
361 highlighting will still appear on differing arguments.
362
363 Default:
364
365 ::
366
367 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;
368
369 -fno-elide-type:
370
371 ::
372
373 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;
374
375**-fdiagnostics-show-template-tree**
376 Template type diffing prints a text tree.
377
378 For diffing large templated types, this option will cause Clang to
379 display the templates as an indented text tree, one argument per
380 line, with differences marked inline. This is compatible with
381 -fno-elide-type.
382
383 Default:
384
385 ::
386
387 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;
388
389 -fdiagnostics-show-template-tree
390
391 ::
392
393 t.cc:4:5: note: candidate function not viable: no known conversion for 1st argument;
394 vector<
395 map<
396 [...],
397 map<
398 [float != float],
399 [...]>>>
400
401.. _cl_diag_warning_groups:
402
403Individual Warning Groups
404^^^^^^^^^^^^^^^^^^^^^^^^^
405
406TODO: Generate this from tblgen. Define one anchor per warning group.
407
408.. _opt_wextra-tokens:
409
410**-Wextra-tokens**
411 Warn about excess tokens at the end of a preprocessor directive.
412
413 This option, which defaults to on, enables warnings about extra
414 tokens at the end of preprocessor directives. For example:
415
416 ::
417
418 test.c:28:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
419 #endif bad
420 ^
421
422 These extra tokens are not strictly conforming, and are usually best
423 handled by commenting them out.
424
425**-Wambiguous-member-template**
426 Warn about unqualified uses of a member template whose name resolves to
427 another template at the location of the use.
428
429 This option, which defaults to on, enables a warning in the
430 following code:
431
432 ::
433
434 template<typename T> struct set{};
435 template<typename T> struct trait { typedef const T& type; };
436 struct Value {
437 template<typename T> void set(typename trait<T>::type value) {}
438 };
439 void foo() {
440 Value v;
441 v.set<double>(3.2);
442 }
443
444 C++ [basic.lookup.classref] requires this to be an error, but,
445 because it's hard to work around, Clang downgrades it to a warning
446 as an extension.
447
448**-Wbind-to-temporary-copy**
449 Warn about an unusable copy constructor when binding a reference to a
450 temporary.
451
452 This option, which defaults to on, enables warnings about binding a
453 reference to a temporary when the temporary doesn't have a usable
454 copy constructor. For example:
455
456 ::
457
458 struct NonCopyable {
459 NonCopyable();
460 private:
461 NonCopyable(const NonCopyable&);
462 };
463 void foo(const NonCopyable&);
464 void bar() {
465 foo(NonCopyable()); // Disallowed in C++98; allowed in C++11.
466 }
467
468 ::
469
470 struct NonCopyable2 {
471 NonCopyable2();
472 NonCopyable2(NonCopyable2&);
473 };
474 void foo(const NonCopyable2&);
475 void bar() {
476 foo(NonCopyable2()); // Disallowed in C++98; allowed in C++11.
477 }
478
479 Note that if ``NonCopyable2::NonCopyable2()`` has a default argument
480 whose instantiation produces a compile error, that error will still
481 be a hard error in C++98 mode even if this warning is turned off.
482
483Options to Control Clang Crash Diagnostics
484------------------------------------------
485
486As unbelievable as it may sound, Clang does crash from time to time.
487Generally, this only occurs to those living on the `bleeding
488edge <http://llvm.org/releases/download.html#svn>`_. Clang goes to great
489lengths to assist you in filing a bug report. Specifically, Clang
490generates preprocessed source file(s) and associated run script(s) upon
491a crash. These files should be attached to a bug report to ease
492reproducibility of the failure. Below are the command line options to
493control the crash diagnostics.
494
495**-fno-crash-diagnostics**: Disable auto-generation of preprocessed
496source files during a clang crash.
497
498The -fno-crash-diagnostics flag can be helpful for speeding the process
499of generating a delta reduced test case.
500
501Language and Target-Independent Features
502========================================
503
504Controlling Errors and Warnings
505-------------------------------
506
507Clang provides a number of ways to control which code constructs cause
508it to emit errors and warning messages, and how they are displayed to
509the console.
510
511Controlling How Clang Displays Diagnostics
512^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
513
514When Clang emits a diagnostic, it includes rich information in the
515output, and gives you fine-grain control over which information is
516printed. Clang has the ability to print this information, and these are
517the options that control it:
518
519#. A file/line/column indicator that shows exactly where the diagnostic
520 occurs in your code [:ref:`-fshow-column <opt_fshow-column>`,
521 :ref:`-fshow-source-location <opt_fshow-source-location>`].
522#. A categorization of the diagnostic as a note, warning, error, or
523 fatal error.
524#. A text string that describes what the problem is.
525#. An option that indicates how to control the diagnostic (for
526 diagnostics that support it)
527 [:ref:`-fdiagnostics-show-option <opt_fdiagnostics-show-option>`].
528#. A :ref:`high-level category <diagnostics_categories>` for the diagnostic
529 for clients that want to group diagnostics by class (for diagnostics
530 that support it)
531 [:ref:`-fdiagnostics-show-category <opt_fdiagnostics-show-category>`].
532#. The line of source code that the issue occurs on, along with a caret
533 and ranges that indicate the important locations
534 [:ref:`-fcaret-diagnostics <opt_fcaret-diagnostics>`].
535#. "FixIt" information, which is a concise explanation of how to fix the
536 problem (when Clang is certain it knows)
537 [:ref:`-fdiagnostics-fixit-info <opt_fdiagnostics-fixit-info>`].
538#. A machine-parsable representation of the ranges involved (off by
539 default)
540 [:ref:`-fdiagnostics-print-source-range-info <opt_fdiagnostics-print-source-range-info>`].
541
542For more information please see :ref:`Formatting of
543Diagnostics <cl_diag_formatting>`.
544
545Diagnostic Mappings
546^^^^^^^^^^^^^^^^^^^
547
548All diagnostics are mapped into one of these 5 classes:
549
550- Ignored
551- Note
552- Warning
553- Error
554- Fatal
555
556.. _diagnostics_categories:
557
558Diagnostic Categories
559^^^^^^^^^^^^^^^^^^^^^
560
561Though not shown by default, diagnostics may each be associated with a
562high-level category. This category is intended to make it possible to
563triage builds that produce a large number of errors or warnings in a
564grouped way.
565
566Categories are not shown by default, but they can be turned on with the
567:ref:`-fdiagnostics-show-category <opt_fdiagnostics-show-category>` option.
568When set to "``name``", the category is printed textually in the
569diagnostic output. When it is set to "``id``", a category number is
570printed. The mapping of category names to category id's can be obtained
571by running '``clang --print-diagnostic-categories``'.
572
573Controlling Diagnostics via Command Line Flags
574^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
575
576TODO: -W flags, -pedantic, etc
577
578.. _pragma_gcc_diagnostic:
579
580Controlling Diagnostics via Pragmas
581^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
582
583Clang can also control what diagnostics are enabled through the use of
584pragmas in the source code. This is useful for turning off specific
585warnings in a section of source code. Clang supports GCC's pragma for
586compatibility with existing source code, as well as several extensions.
587
588The pragma may control any warning that can be used from the command
589line. Warnings may be set to ignored, warning, error, or fatal. The
590following example code will tell Clang or GCC to ignore the -Wall
591warnings:
592
593::
594
595 #pragma GCC diagnostic ignored "-Wall"
596
597In addition to all of the functionality provided by GCC's pragma, Clang
598also allows you to push and pop the current warning state. This is
599particularly useful when writing a header file that will be compiled by
600other people, because you don't know what warning flags they build with.
601
602In the below example -Wmultichar is ignored for only a single line of
603code, after which the diagnostics return to whatever state had
604previously existed.
605
606::
607
608 #pragma clang diagnostic push
609 #pragma clang diagnostic ignored "-Wmultichar"
610
611 char b = 'df'; // no warning.
612
613 #pragma clang diagnostic pop
614
615The push and pop pragmas will save and restore the full diagnostic state
616of the compiler, regardless of how it was set. That means that it is
617possible to use push and pop around GCC compatible diagnostics and Clang
618will push and pop them appropriately, while GCC will ignore the pushes
619and pops as unknown pragmas. It should be noted that while Clang
620supports the GCC pragma, Clang and GCC do not support the exact same set
621of warnings, so even when using GCC compatible #pragmas there is no
622guarantee that they will have identical behaviour on both compilers.
623
624Controlling Diagnostics in System Headers
625^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
626
627Warnings are suppressed when they occur in system headers. By default,
628an included file is treated as a system header if it is found in an
629include path specified by ``-isystem``, but this can be overridden in
630several ways.
631
632The ``system_header`` pragma can be used to mark the current file as
633being a system header. No warnings will be produced from the location of
634the pragma onwards within the same file.
635
636::
637
638 char a = 'xy'; // warning
639
640 #pragma clang system_header
641
642 char b = 'ab'; // no warning
643
644The ``-isystem-prefix`` and ``-ino-system-prefix`` command-line
645arguments can be used to override whether subsets of an include path are
646treated as system headers. When the name in a ``#include`` directive is
647found within a header search path and starts with a system prefix, the
648header is treated as a system header. The last prefix on the
649command-line which matches the specified header name takes precedence.
650For instance:
651
652::
653
654 clang -Ifoo -isystem bar -isystem-prefix x/ -ino-system-prefix x/y/
655
656Here, ``#include "x/a.h"`` is treated as including a system header, even
657if the header is found in ``foo``, and ``#include "x/y/b.h"`` is treated
658as not including a system header, even if the header is found in
659``bar``.
660
661A ``#include`` directive which finds a file relative to the current
662directory is treated as including a system header if the including file
663is treated as a system header.
664
665.. _diagnostics_enable_everything:
666
667Enabling All Warnings
668^^^^^^^^^^^^^^^^^^^^^
669
670In addition to the traditional ``-W`` flags, one can enable **all**
671warnings by passing ``-Weverything``. This works as expected with
672``-Werror``, and also includes the warnings from ``-pedantic``.
673
674Note that when combined with ``-w`` (which disables all warnings), that
675flag wins.
676
677Controlling Static Analyzer Diagnostics
678^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
679
680While not strictly part of the compiler, the diagnostics from Clang's
681`static analyzer <http://clang-analyzer.llvm.org>`_ can also be
682influenced by the user via changes to the source code. See the available
683`annotations <http://clang-analyzer.llvm.org/annotations.html>`_ and the
684analyzer's `FAQ
685page <http://clang-analyzer.llvm.org/faq.html#exclude_code>`_ for more
686information.
687
Dmitri Gribenko97555a12012-12-15 21:10:51 +0000688.. _usersmanual-precompiled-headers:
689
Sean Silva93ca0212012-12-13 01:10:46 +0000690Precompiled Headers
691-------------------
692
693`Precompiled headers <http://en.wikipedia.org/wiki/Precompiled_header>`__
694are a general approach employed by many compilers to reduce compilation
695time. The underlying motivation of the approach is that it is common for
696the same (and often large) header files to be included by multiple
697source files. Consequently, compile times can often be greatly improved
698by caching some of the (redundant) work done by a compiler to process
699headers. Precompiled header files, which represent one of many ways to
700implement this optimization, are literally files that represent an
701on-disk cache that contains the vital information necessary to reduce
702some of the work needed to process a corresponding header file. While
703details of precompiled headers vary between compilers, precompiled
704headers have been shown to be highly effective at speeding up program
705compilation on systems with very large system headers (e.g., Mac OS/X).
706
707Generating a PCH File
708^^^^^^^^^^^^^^^^^^^^^
709
710To generate a PCH file using Clang, one invokes Clang with the
711**``-x <language>-header``** option. This mirrors the interface in GCC
712for generating PCH files:
713
714::
715
716 $ gcc -x c-header test.h -o test.h.gch
717 $ clang -x c-header test.h -o test.h.pch
718
719Using a PCH File
720^^^^^^^^^^^^^^^^
721
722A PCH file can then be used as a prefix header when a **``-include``**
723option is passed to ``clang``:
724
725::
726
727 $ clang -include test.h test.c -o test
728
729The ``clang`` driver will first check if a PCH file for ``test.h`` is
730available; if so, the contents of ``test.h`` (and the files it includes)
731will be processed from the PCH file. Otherwise, Clang falls back to
732directly processing the content of ``test.h``. This mirrors the behavior
733of GCC.
734
735.. note::
736 Clang does *not* automatically use PCH files for headers that are
737 directly included within a source file. For example:
738
739::
740
741 $ clang -x c-header test.h -o test.h.pch
742 $ cat test.c
743 #include "test.h"
744 $ clang test.c -o test
745
746In this example, ``clang`` will not automatically use the PCH file for
747``test.h`` since ``test.h`` was included directly in the source file and
748not specified on the command line using ``-include``.
749
750Relocatable PCH Files
751^^^^^^^^^^^^^^^^^^^^^
752
753It is sometimes necessary to build a precompiled header from headers
754that are not yet in their final, installed locations. For example, one
755might build a precompiled header within the build tree that is then
756meant to be installed alongside the headers. Clang permits the creation
757of "relocatable" precompiled headers, which are built with a given path
758(into the build directory) and can later be used from an installed
759location.
760
761To build a relocatable precompiled header, place your headers into a
762subdirectory whose structure mimics the installed location. For example,
763if you want to build a precompiled header for the header ``mylib.h``
764that will be installed into ``/usr/include``, create a subdirectory
765``build/usr/include`` and place the header ``mylib.h`` into that
766subdirectory. If ``mylib.h`` depends on other headers, then they can be
767stored within ``build/usr/include`` in a way that mimics the installed
768location.
769
770Building a relocatable precompiled header requires two additional
771arguments. First, pass the ``--relocatable-pch`` flag to indicate that
772the resulting PCH file should be relocatable. Second, pass
773``-isysroot /path/to/build``, which makes all includes for your library
774relative to the build directory. For example:
775
776::
777
778 # clang -x c-header --relocatable-pch -isysroot /path/to/build /path/to/build/mylib.h mylib.h.pch
779
780When loading the relocatable PCH file, the various headers used in the
781PCH file are found from the system header root. For example, ``mylib.h``
782can be found in ``/usr/include/mylib.h``. If the headers are installed
783in some other system root, the ``-isysroot`` option can be used provide
784a different system root from which the headers will be based. For
785example, ``-isysroot /Developer/SDKs/MacOSX10.4u.sdk`` will look for
786``mylib.h`` in ``/Developer/SDKs/MacOSX10.4u.sdk/usr/include/mylib.h``.
787
788Relocatable precompiled headers are intended to be used in a limited
789number of cases where the compilation environment is tightly controlled
790and the precompiled header cannot be generated after headers have been
791installed. Relocatable precompiled headers also have some performance
792impact, because the difference in location between the header locations
793at PCH build time vs. at the time of PCH use requires one of the PCH
794optimizations, ``stat()`` caching, to be disabled. However, this change
795is only likely to affect PCH files that reference a large number of
796headers.
797
798Controlling Code Generation
799---------------------------
800
801Clang provides a number of ways to control code generation. The options
802are listed below.
803
804**-fsanitize=check1,check2**
805 Turn on runtime checks for various forms of undefined or suspicious
806 behavior.
807
808 This option controls whether Clang adds runtime checks for various
809 forms of undefined or suspicious behavior, and is disabled by
810 default. If a check fails, a diagnostic message is produced at
811 runtime explaining the problem. The main checks are:
812
Richard Smith2dce7be2012-12-13 07:29:23 +0000813 - .. _opt_fsanitize_address:
Sean Silva93ca0212012-12-13 01:10:46 +0000814
Richard Smith2dce7be2012-12-13 07:29:23 +0000815 ``-fsanitize=address``:
Sean Silva93ca0212012-12-13 01:10:46 +0000816 :doc:`AddressSanitizer`, a memory error
817 detector.
818 - ``-fsanitize=address-full``: AddressSanitizer with all the
819 experimental features listed below.
820 - ``-fsanitize=integer``: Enables checks for undefined or
821 suspicious integer behavior.
Richard Smith2dce7be2012-12-13 07:29:23 +0000822 - .. _opt_fsanitize_thread:
823
824 ``-fsanitize=thread``: :doc:`ThreadSanitizer`,
Sean Silva93ca0212012-12-13 01:10:46 +0000825 an *experimental* data race detector. Not ready for widespread
826 use.
Richard Smith2dce7be2012-12-13 07:29:23 +0000827 - .. _opt_fsanitize_undefined:
Sean Silva93ca0212012-12-13 01:10:46 +0000828
Richard Smith2dce7be2012-12-13 07:29:23 +0000829 ``-fsanitize=undefined``: Fast and compatible undefined behavior
Sean Silva93ca0212012-12-13 01:10:46 +0000830 checker. Enables the undefined behavior checks that have small
831 runtime cost and no impact on address space layout or ABI. This
832 includes all of the checks listed below other than
833 ``unsigned-integer-overflow``.
834
835 The following more fine-grained checks are also available:
836
837 - ``-fsanitize=alignment``: Use of a misaligned pointer or creation
838 of a misaligned reference.
Richard Smith463b48b2012-12-13 07:11:50 +0000839 - ``-fsanitize=bool``: Load of a ``bool`` value which is neither
840 ``true`` nor ``false``.
Sean Silva93ca0212012-12-13 01:10:46 +0000841 - ``-fsanitize=bounds``: Out of bounds array indexing, in cases
842 where the array bound can be statically determined.
Richard Smith463b48b2012-12-13 07:11:50 +0000843 - ``-fsanitize=enum``: Load of a value of an enumerated type which
844 is not in the range of representable values for that enumerated
845 type.
Sean Silva93ca0212012-12-13 01:10:46 +0000846 - ``-fsanitize=float-cast-overflow``: Conversion to, from, or
847 between floating-point types which would overflow the
848 destination.
849 - ``-fsanitize=float-divide-by-zero``: Floating point division by
850 zero.
851 - ``-fsanitize=integer-divide-by-zero``: Integer division by zero.
852 - ``-fsanitize=null``: Use of a null pointer or creation of a null
853 reference.
854 - ``-fsanitize=object-size``: An attempt to use bytes which the
855 optimizer can determine are not part of the object being
856 accessed. The sizes of objects are determined using
857 ``__builtin_object_size``, and consequently may be able to detect
858 more problems at higher optimization levels.
859 - ``-fsanitize=return``: In C++, reaching the end of a
860 value-returning function without returning a value.
861 - ``-fsanitize=shift``: Shift operators where the amount shifted is
862 greater or equal to the promoted bit-width of the left hand side
863 or less than zero, or where the left hand side is negative. For a
864 signed left shift, also checks for signed overflow in C, and for
865 unsigned overflow in C++.
866 - ``-fsanitize=signed-integer-overflow``: Signed integer overflow,
867 including all the checks added by ``-ftrapv``, and checking for
868 overflow in signed division (``INT_MIN / -1``).
869 - ``-fsanitize=unreachable``: If control flow reaches
870 ``__builtin_unreachable``.
871 - ``-fsanitize=unsigned-integer-overflow``: Unsigned integer
872 overflows.
873 - ``-fsanitize=vla-bound``: A variable-length array whose bound
874 does not evaluate to a positive value.
875 - ``-fsanitize=vptr``: Use of an object whose vptr indicates that
876 it is of the wrong dynamic type, or that its lifetime has not
877 begun or has ended. Incompatible with ``-fno-rtti``.
878
879 Experimental features of AddressSanitizer (not ready for widespread
880 use, require explicit ``-fsanitize=address``):
881
882 - ``-fsanitize=init-order``: Check for dynamic initialization order
883 problems.
884 - ``-fsanitize=use-after-return``: Check for use-after-return
885 errors (accessing local variable after the function exit).
886 - ``-fsanitize=use-after-scope``: Check for use-after-scope errors
887 (accesing local variable after it went out of scope).
888
889 The ``-fsanitize=`` argument must also be provided when linking, in
890 order to link to the appropriate runtime library. It is not possible
891 to combine the ``-fsanitize=address`` and ``-fsanitize=thread``
892 checkers in the same program.
893**-f[no-]address-sanitizer**
894 Deprecated synonym for :ref:`-f[no-]sanitize=address
895 <opt_fsanitize_address>`.
896**-f[no-]thread-sanitizer**
897 Deprecated synonym for :ref:`-f[no-]sanitize=thread
Richard Smith2dce7be2012-12-13 07:29:23 +0000898 <opt_fsanitize_thread>`.
Sean Silva93ca0212012-12-13 01:10:46 +0000899**-fcatch-undefined-behavior**
900 Deprecated synonym for :ref:`-fsanitize=undefined
901 <opt_fsanitize_undefined>`.
902**-fno-assume-sane-operator-new**
903 Don't assume that the C++'s new operator is sane.
904
905 This option tells the compiler to do not assume that C++'s global
906 new operator will always return a pointer that does not alias any
907 other pointer when the function returns.
908
909**-ftrap-function=[name]**
910 Instruct code generator to emit a function call to the specified
911 function name for ``__builtin_trap()``.
912
913 LLVM code generator translates ``__builtin_trap()`` to a trap
914 instruction if it is supported by the target ISA. Otherwise, the
915 builtin is translated into a call to ``abort``. If this option is
916 set, then the code generator will always lower the builtin to a call
917 to the specified function regardless of whether the target ISA has a
918 trap instruction. This option is useful for environments (e.g.
919 deeply embedded) where a trap cannot be properly handled, or when
920 some custom behavior is desired.
921
922**-ftls-model=[model]**
923 Select which TLS model to use.
924
925 Valid values are: ``global-dynamic``, ``local-dynamic``,
926 ``initial-exec`` and ``local-exec``. The default value is
927 ``global-dynamic``. The compiler may use a different model if the
928 selected model is not supported by the target, or if a more
929 efficient model can be used. The TLS model can be overridden per
930 variable using the ``tls_model`` attribute.
931
932Controlling Size of Debug Information
933-------------------------------------
934
935Debug info kind generated by Clang can be set by one of the flags listed
936below. If multiple flags are present, the last one is used.
937
938**-g0**: Don't generate any debug info (default).
939
940**-gline-tables-only**: Generate line number tables only.
941
942This kind of debug info allows to obtain stack traces with function
943names, file names and line numbers (by such tools as gdb or addr2line).
944It doesn't contain any other data (e.g. description of local variables
945or function parameters).
946
947**-g**: Generate complete debug info.
948
949.. _c:
950
951C Language Features
952===================
953
954The support for standard C in clang is feature-complete except for the
955C99 floating-point pragmas.
956
957Extensions supported by clang
958-----------------------------
959
960See `clang language extensions <LanguageExtensions.html>`_.
961
962Differences between various standard modes
963------------------------------------------
964
965clang supports the -std option, which changes what language mode clang
966uses. The supported modes for C are c89, gnu89, c94, c99, gnu99 and
967various aliases for those modes. If no -std option is specified, clang
968defaults to gnu99 mode.
969
970Differences between all ``c*`` and ``gnu*`` modes:
971
972- ``c*`` modes define "``__STRICT_ANSI__``".
973- Target-specific defines not prefixed by underscores, like "linux",
974 are defined in ``gnu*`` modes.
975- Trigraphs default to being off in ``gnu*`` modes; they can be enabled by
976 the -trigraphs option.
977- The parser recognizes "asm" and "typeof" as keywords in ``gnu*`` modes;
978 the variants "``__asm__``" and "``__typeof__``" are recognized in all
979 modes.
980- The Apple "blocks" extension is recognized by default in ``gnu*`` modes
981 on some platforms; it can be enabled in any mode with the "-fblocks"
982 option.
983- Arrays that are VLA's according to the standard, but which can be
984 constant folded by the frontend are treated as fixed size arrays.
985 This occurs for things like "int X[(1, 2)];", which is technically a
986 VLA. ``c*`` modes are strictly compliant and treat these as VLAs.
987
988Differences between ``*89`` and ``*99`` modes:
989
990- The ``*99`` modes default to implementing "inline" as specified in C99,
991 while the ``*89`` modes implement the GNU version. This can be
992 overridden for individual functions with the ``__gnu_inline__``
993 attribute.
994- Digraphs are not recognized in c89 mode.
995- The scope of names defined inside a "for", "if", "switch", "while",
996 or "do" statement is different. (example: "``if ((struct x {int
997 x;}*)0) {}``".)
998- ``__STDC_VERSION__`` is not defined in ``*89`` modes.
999- "inline" is not recognized as a keyword in c89 mode.
1000- "restrict" is not recognized as a keyword in ``*89`` modes.
1001- Commas are allowed in integer constant expressions in ``*99`` modes.
1002- Arrays which are not lvalues are not implicitly promoted to pointers
1003 in ``*89`` modes.
1004- Some warnings are different.
1005
1006c94 mode is identical to c89 mode except that digraphs are enabled in
1007c94 mode (FIXME: And ``__STDC_VERSION__`` should be defined!).
1008
1009GCC extensions not implemented yet
1010----------------------------------
1011
1012clang tries to be compatible with gcc as much as possible, but some gcc
1013extensions are not implemented yet:
1014
1015- clang does not support #pragma weak (`bug
1016 3679 <http://llvm.org/bugs/show_bug.cgi?id=3679>`_). Due to the uses
1017 described in the bug, this is likely to be implemented at some point,
1018 at least partially.
1019- clang does not support decimal floating point types (``_Decimal32`` and
1020 friends) or fixed-point types (``_Fract`` and friends); nobody has
1021 expressed interest in these features yet, so it's hard to say when
1022 they will be implemented.
1023- clang does not support nested functions; this is a complex feature
1024 which is infrequently used, so it is unlikely to be implemented
1025 anytime soon. In C++11 it can be emulated by assigning lambda
1026 functions to local variables, e.g:
1027
1028 ::
1029
1030 auto const local_function = [&](int parameter) {
1031 // Do something
1032 };
1033 ...
1034 local_function(1);
1035
1036- clang does not support global register variables; this is unlikely to
1037 be implemented soon because it requires additional LLVM backend
1038 support.
1039- clang does not support static initialization of flexible array
1040 members. This appears to be a rarely used extension, but could be
1041 implemented pending user demand.
1042- clang does not support
1043 ``__builtin_va_arg_pack``/``__builtin_va_arg_pack_len``. This is
1044 used rarely, but in some potentially interesting places, like the
1045 glibc headers, so it may be implemented pending user demand. Note
1046 that because clang pretends to be like GCC 4.2, and this extension
1047 was introduced in 4.3, the glibc headers will not try to use this
1048 extension with clang at the moment.
1049- clang does not support the gcc extension for forward-declaring
1050 function parameters; this has not shown up in any real-world code
1051 yet, though, so it might never be implemented.
1052
1053This is not a complete list; if you find an unsupported extension
1054missing from this list, please send an e-mail to cfe-dev. This list
1055currently excludes C++; see :ref:`C++ Language Features <cxx>`. Also, this
1056list does not include bugs in mostly-implemented features; please see
1057the `bug
1058tracker <http://llvm.org/bugs/buglist.cgi?quicksearch=product%3Aclang+component%3A-New%2BBugs%2CAST%2CBasic%2CDriver%2CHeaders%2CLLVM%2BCodeGen%2Cparser%2Cpreprocessor%2CSemantic%2BAnalyzer>`_
1059for known existing bugs (FIXME: Is there a section for bug-reporting
1060guidelines somewhere?).
1061
1062Intentionally unsupported GCC extensions
1063----------------------------------------
1064
1065- clang does not support the gcc extension that allows variable-length
1066 arrays in structures. This is for a few reasons: one, it is tricky to
1067 implement, two, the extension is completely undocumented, and three,
1068 the extension appears to be rarely used. Note that clang *does*
1069 support flexible array members (arrays with a zero or unspecified
1070 size at the end of a structure).
1071- clang does not have an equivalent to gcc's "fold"; this means that
1072 clang doesn't accept some constructs gcc might accept in contexts
1073 where a constant expression is required, like "x-x" where x is a
1074 variable.
1075- clang does not support ``__builtin_apply`` and friends; this extension
1076 is extremely obscure and difficult to implement reliably.
1077
1078.. _c_ms:
1079
1080Microsoft extensions
1081--------------------
1082
1083clang has some experimental support for extensions from Microsoft Visual
1084C++; to enable it, use the -fms-extensions command-line option. This is
1085the default for Windows targets. Note that the support is incomplete;
1086enabling Microsoft extensions will silently drop certain constructs
1087(including ``__declspec`` and Microsoft-style asm statements).
1088
1089clang has a -fms-compatibility flag that makes clang accept enough
1090invalid C++ to be able to parse most Microsoft headers. This flag is
1091enabled by default for Windows targets.
1092
1093-fdelayed-template-parsing lets clang delay all template instantiation
1094until the end of a translation unit. This flag is enabled by default for
1095Windows targets.
1096
1097- clang allows setting ``_MSC_VER`` with ``-fmsc-version=``. It defaults to
1098 1300 which is the same as Visual C/C++ 2003. Any number is supported
1099 and can greatly affect what Windows SDK and c++stdlib headers clang
1100 can compile. This option will be removed when clang supports the full
1101 set of MS extensions required for these headers.
1102- clang does not support the Microsoft extension where anonymous record
1103 members can be declared using user defined typedefs.
1104- clang supports the Microsoft "#pragma pack" feature for controlling
1105 record layout. GCC also contains support for this feature, however
1106 where MSVC and GCC are incompatible clang follows the MSVC
1107 definition.
1108- clang defaults to C++11 for Windows targets.
1109
1110.. _cxx:
1111
1112C++ Language Features
1113=====================
1114
1115clang fully implements all of standard C++98 except for exported
1116templates (which were removed in C++11), and `many C++11
1117features <http://clang.llvm.org/cxx_status.html>`_ are also implemented.
1118
1119Controlling implementation limits
1120---------------------------------
1121
1122**-fconstexpr-depth=N**: Sets the limit for recursive constexpr function
1123invocations to N. The default is 512.
1124
1125**-ftemplate-depth=N**: Sets the limit for recursively nested template
1126instantiations to N. The default is 1024.
1127
1128.. _objc:
1129
1130Objective-C Language Features
1131=============================
1132
1133.. _objcxx:
1134
1135Objective-C++ Language Features
1136===============================
1137
1138
1139.. _target_features:
1140
1141Target-Specific Features and Limitations
1142========================================
1143
1144CPU Architectures Features and Limitations
1145------------------------------------------
1146
1147X86
1148^^^
1149
1150The support for X86 (both 32-bit and 64-bit) is considered stable on
1151Darwin (Mac OS/X), Linux, FreeBSD, and Dragonfly BSD: it has been tested
1152to correctly compile many large C, C++, Objective-C, and Objective-C++
1153codebases.
1154
1155On ``x86_64-mingw32``, passing i128(by value) is incompatible to Microsoft
1156x64 calling conversion. You might need to tweak
1157``WinX86_64ABIInfo::classify()`` in lib/CodeGen/TargetInfo.cpp.
1158
1159ARM
1160^^^
1161
1162The support for ARM (specifically ARMv6 and ARMv7) is considered stable
1163on Darwin (iOS): it has been tested to correctly compile many large C,
1164C++, Objective-C, and Objective-C++ codebases. Clang only supports a
1165limited number of ARM architectures. It does not yet fully support
1166ARMv5, for example.
1167
1168Other platforms
1169^^^^^^^^^^^^^^^
1170
1171clang currently contains some support for PPC and Sparc; however,
1172significant pieces of code generation are still missing, and they
1173haven't undergone significant testing.
1174
1175clang contains limited support for the MSP430 embedded processor, but
1176both the clang support and the LLVM backend support are highly
1177experimental.
1178
1179Other platforms are completely unsupported at the moment. Adding the
1180minimal support needed for parsing and semantic analysis on a new
1181platform is quite easy; see lib/Basic/Targets.cpp in the clang source
1182tree. This level of support is also sufficient for conversion to LLVM IR
1183for simple programs. Proper support for conversion to LLVM IR requires
1184adding code to lib/CodeGen/CGCall.cpp at the moment; this is likely to
1185change soon, though. Generating assembly requires a suitable LLVM
1186backend.
1187
1188Operating System Features and Limitations
1189-----------------------------------------
1190
1191Darwin (Mac OS/X)
1192^^^^^^^^^^^^^^^^^
1193
1194None
1195
1196Windows
1197^^^^^^^
1198
1199Experimental supports are on Cygming.
1200
1201See also `Microsoft Extensions <c_ms>`.
1202
1203Cygwin
1204""""""
1205
1206Clang works on Cygwin-1.7.
1207
1208MinGW32
1209"""""""
1210
1211Clang works on some mingw32 distributions. Clang assumes directories as
1212below;
1213
1214- ``C:/mingw/include``
1215- ``C:/mingw/lib``
1216- ``C:/mingw/lib/gcc/mingw32/4.[3-5].0/include/c++``
1217
1218On MSYS, a few tests might fail.
1219
1220MinGW-w64
1221"""""""""
1222
1223For 32-bit (i686-w64-mingw32), and 64-bit (x86\_64-w64-mingw32), Clang
1224assumes as below;
1225
1226- ``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)``
1227- ``some_directory/bin/gcc.exe``
1228- ``some_directory/bin/clang.exe``
1229- ``some_directory/bin/clang++.exe``
1230- ``some_directory/bin/../include/c++/GCC_version``
1231- ``some_directory/bin/../include/c++/GCC_version/x86_64-w64-mingw32``
1232- ``some_directory/bin/../include/c++/GCC_version/i686-w64-mingw32``
1233- ``some_directory/bin/../include/c++/GCC_version/backward``
1234- ``some_directory/bin/../x86_64-w64-mingw32/include``
1235- ``some_directory/bin/../i686-w64-mingw32/include``
1236- ``some_directory/bin/../include``
1237
1238This directory layout is standard for any toolchain you will find on the
1239official `MinGW-w64 website <http://mingw-w64.sourceforge.net>`_.
1240
1241Clang expects the GCC executable "gcc.exe" compiled for
1242``i686-w64-mingw32`` (or ``x86_64-w64-mingw32``) to be present on PATH.
1243
1244`Some tests might fail <http://llvm.org/bugs/show_bug.cgi?id=9072>`_ on
1245``x86_64-w64-mingw32``.