blob: f39224f47dc56ae88766f2fd5de39a2068d0b1fd [file] [log] [blame]
Ted Kremenek17a295d2008-06-11 06:19:49 +00001<html>
2<head>
Chris Lattner552de0a2008-11-23 08:16:56 +00003<title>"Clang" CFE Internals Manual</title>
Ted Kremenek17a295d2008-06-11 06:19:49 +00004<link type="text/css" rel="stylesheet" href="../menu.css" />
5<link type="text/css" rel="stylesheet" href="../content.css" />
Sebastian Redl68168562008-11-22 22:16:45 +00006<style type="text/css">
7td {
8 vertical-align: top;
9}
10</style>
Ted Kremenek17a295d2008-06-11 06:19:49 +000011</head>
12<body>
13
14<!--#include virtual="../menu.html.incl"-->
15
16<div id="content">
Chris Lattner86920d32007-07-31 05:42:17 +000017
Chris Lattner552de0a2008-11-23 08:16:56 +000018<h1>"Clang" CFE Internals Manual</h1>
Chris Lattner86920d32007-07-31 05:42:17 +000019
20<ul>
21<li><a href="#intro">Introduction</a></li>
22<li><a href="#libsystem">LLVM System and Support Libraries</a></li>
Chris Lattner552de0a2008-11-23 08:16:56 +000023<li><a href="#libbasic">The Clang 'Basic' Library</a>
Chris Lattner86920d32007-07-31 05:42:17 +000024 <ul>
Chris Lattner62fd2782008-11-22 21:41:31 +000025 <li><a href="#Diagnostics">The Diagnostics Subsystem</a></li>
Chris Lattner86920d32007-07-31 05:42:17 +000026 <li><a href="#SourceLocation">The SourceLocation and SourceManager
27 classes</a></li>
28 </ul>
29</li>
Daniel Dunbar27d9e9f2009-03-30 06:50:01 +000030<li><a href="#libdriver">The Driver Library</a>
31 <ul>
32 </ul>
33</li>
Douglas Gregor32110df2009-05-20 00:16:32 +000034<li><a href="#pch">Precompiled Headers</a>
Daniel Dunbar27d9e9f2009-03-30 06:50:01 +000035<li><a href="#libfrontend">The Frontend Library</a>
36 <ul>
37 </ul>
38</li>
Chris Lattner86920d32007-07-31 05:42:17 +000039<li><a href="#liblex">The Lexer and Preprocessor Library</a>
40 <ul>
41 <li><a href="#Token">The Token class</a></li>
42 <li><a href="#Lexer">The Lexer class</a></li>
Chris Lattner3932fe02009-01-06 06:02:08 +000043 <li><a href="#AnnotationToken">Annotation Tokens</a></li>
Chris Lattner79281252008-03-09 02:27:26 +000044 <li><a href="#TokenLexer">The TokenLexer class</a></li>
Chris Lattner86920d32007-07-31 05:42:17 +000045 <li><a href="#MultipleIncludeOpt">The MultipleIncludeOpt class</a></li>
46 </ul>
47</li>
48<li><a href="#libparse">The Parser Library</a>
49 <ul>
50 </ul>
51</li>
52<li><a href="#libast">The AST Library</a>
53 <ul>
54 <li><a href="#Type">The Type class and its subclasses</a></li>
55 <li><a href="#QualType">The QualType class</a></li>
Douglas Gregor2e1cd422008-11-17 14:58:09 +000056 <li><a href="#DeclarationName">Declaration names</a></li>
Douglas Gregor074149e2009-01-05 19:45:36 +000057 <li><a href="#DeclContext">Declaration contexts</a>
58 <ul>
59 <li><a href="#Redeclarations">Redeclarations and Overloads</a></li>
60 <li><a href="#LexicalAndSemanticContexts">Lexical and Semantic
61 Contexts</a></li>
62 <li><a href="#TransparentContexts">Transparent Declaration Contexts</a></li>
63 <li><a href="#MultiDeclContext">Multiply-Defined Declaration Contexts</a></li>
64 </ul>
65 </li>
Ted Kremenek8bc05712007-10-10 23:01:43 +000066 <li><a href="#CFG">The CFG class</a></li>
Chris Lattner7bad1992008-11-16 21:48:07 +000067 <li><a href="#Constants">Constant Folding in the Clang AST</a></li>
Chris Lattner86920d32007-07-31 05:42:17 +000068 </ul>
69</li>
Argyrios Kyrtzidis7240d772009-07-10 03:41:36 +000070<li><a href="libIndex.html">The Index Library</a></li>
Chris Lattner86920d32007-07-31 05:42:17 +000071</ul>
72
73
74<!-- ======================================================================= -->
75<h2 id="intro">Introduction</h2>
76<!-- ======================================================================= -->
77
78<p>This document describes some of the more important APIs and internal design
Chris Lattner552de0a2008-11-23 08:16:56 +000079decisions made in the Clang C front-end. The purpose of this document is to
Chris Lattner86920d32007-07-31 05:42:17 +000080both capture some of this high level information and also describe some of the
81design decisions behind it. This is meant for people interested in hacking on
Chris Lattner552de0a2008-11-23 08:16:56 +000082Clang, not for end-users. The description below is categorized by
Chris Lattner86920d32007-07-31 05:42:17 +000083libraries, and does not describe any of the clients of the libraries.</p>
84
85<!-- ======================================================================= -->
86<h2 id="libsystem">LLVM System and Support Libraries</h2>
87<!-- ======================================================================= -->
88
Chris Lattner552de0a2008-11-23 08:16:56 +000089<p>The LLVM libsystem library provides the basic Clang system abstraction layer,
Chris Lattner86920d32007-07-31 05:42:17 +000090which is used for file system access. The LLVM libsupport library provides many
91underlying libraries and <a
92href="http://llvm.org/docs/ProgrammersManual.html">data-structures</a>,
93 including command line option
94processing and various containers.</p>
95
96<!-- ======================================================================= -->
Chris Lattner552de0a2008-11-23 08:16:56 +000097<h2 id="libbasic">The Clang 'Basic' Library</h2>
Chris Lattner86920d32007-07-31 05:42:17 +000098<!-- ======================================================================= -->
99
100<p>This library certainly needs a better name. The 'basic' library contains a
101number of low-level utilities for tracking and manipulating source buffers,
102locations within the source buffers, diagnostics, tokens, target abstraction,
103and information about the subset of the language being compiled for.</p>
104
105<p>Part of this infrastructure is specific to C (such as the TargetInfo class),
106other parts could be reused for other non-C-based languages (SourceLocation,
107SourceManager, Diagnostics, FileManager). When and if there is future demand
108we can figure out if it makes sense to introduce a new library, move the general
109classes somewhere else, or introduce some other solution.</p>
110
111<p>We describe the roles of these classes in order of their dependencies.</p>
112
Chris Lattner62fd2782008-11-22 21:41:31 +0000113
114<!-- ======================================================================= -->
115<h3 id="Diagnostics">The Diagnostics Subsystem</h3>
116<!-- ======================================================================= -->
117
118<p>The Clang Diagnostics subsystem is an important part of how the compiler
119communicates with the human. Diagnostics are the warnings and errors produced
120when the code is incorrect or dubious. In Clang, each diagnostic produced has
121(at the minimum) a unique ID, a <a href="#SourceLocation">SourceLocation</a> to
122"put the caret", an English translation associated with it, and a severity (e.g.
123<tt>WARNING</tt> or <tt>ERROR</tt>). They can also optionally include a number
124of arguments to the dianostic (which fill in "%0"'s in the string) as well as a
125number of source ranges that related to the diagnostic.</p>
126
Chris Lattner552de0a2008-11-23 08:16:56 +0000127<p>In this section, we'll be giving examples produced by the Clang command line
Chris Lattner62fd2782008-11-22 21:41:31 +0000128driver, but diagnostics can be <a href="#DiagnosticClient">rendered in many
129different ways</a> depending on how the DiagnosticClient interface is
130implemented. A representative example of a diagonstic is:</p>
131
132<pre>
133t.c:38:15: error: invalid operands to binary expression ('int *' and '_Complex float')
134 <font color="darkgreen">P = (P-42) + Gamma*4;</font>
135 <font color="blue">~~~~~~ ^ ~~~~~~~</font>
136</pre>
137
138<p>In this example, you can see the English translation, the severity (error),
139you can see the source location (the caret ("^") and file/line/column info),
140the source ranges "~~~~", arguments to the diagnostic ("int*" and "_Complex
141float"). You'll have to believe me that there is a unique ID backing the
142diagnostic :).</p>
143
144<p>Getting all of this to happen has several steps and involves many moving
145pieces, this section describes them and talks about best practices when adding
146a new diagnostic.</p>
147
148<!-- ============================ -->
149<h4>The DiagnosticKinds.def file</h4>
150<!-- ============================ -->
151
152<p>Diagnostics are created by adding an entry to the <tt><a
153href="http://llvm.org/svn/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticKinds.def"
154>DiagnosticKinds.def</a></tt> file. This file encodes the unique ID of the
155diagnostic (as an enum, the first argument), the severity of the diagnostic
156(second argument) and the English translation + format string.</p>
157
158<p>There is little sanity with the naming of the unique ID's right now. Some
159start with err_, warn_, ext_ to encode the severity into the name. Since the
160enum is referenced in the C++ code that produces the diagnostic, it is somewhat
161useful for it to be reasonably short.</p>
162
163<p>The severity of the diagnostic comes from the set {<tt>NOTE</tt>,
164<tt>WARNING</tt>, <tt>EXTENSION</tt>, <tt>EXTWARN</tt>, <tt>ERROR</tt>}. The
165<tt>ERROR</tt> severity is used for diagnostics indicating the program is never
166acceptable under any circumstances. When an error is emitted, the AST for the
167input code may not be fully built. The <tt>EXTENSION</tt> and <tt>EXTWARN</tt>
168severities are used for extensions to the language that Clang accepts. This
169means that Clang fully understands and can represent them in the AST, but we
170produce diagnostics to tell the user their code is non-portable. The difference
171is that the former are ignored by default, and the later warn by default. The
172<tt>WARNING</tt> severity is used for constructs that are valid in the currently
173selected source language but that are dubious in some way. The <tt>NOTE</tt>
Daniel Dunbar426b8632009-02-17 15:49:03 +0000174level is used to staple more information onto previous diagnostics.</p>
Chris Lattner62fd2782008-11-22 21:41:31 +0000175
176<p>These <em>severities</em> are mapped into a smaller set (the
177Diagnostic::Level enum, {<tt>Ignored</tt>, <tt>Note</tt>, <tt>Warning</tt>,
Chris Lattner0aad2972009-02-05 22:49:08 +0000178<tt>Error</tt>, <tt>Fatal</tt> }) of output <em>levels</em> by the diagnostics
Chris Lattnera180fdd2009-02-17 07:07:29 +0000179subsystem based on various configuration options. Clang internally supports a
180fully fine grained mapping mechanism that allows you to map almost any
181diagnostic to the output level that you want. The only diagnostics that cannot
182be mapped are <tt>NOTE</tt>s, which always follow the severity of the previously
183emitted diagnostic and <tt>ERROR</tt>s, which can only be mapped to
184<tt>Fatal</tt> (it is not possible to turn an error into a warning,
185for example).</p>
186
187<p>Diagnostic mappings are used in many ways. For example, if the user
188specifies <tt>-pedantic</tt>, <tt>EXTENSION</tt> maps to <tt>Warning</tt>, if
189they specify <tt>-pedantic-errors</tt>, it turns into <tt>Error</tt>. This is
190used to implement options like <tt>-Wunused_macros</tt>, <tt>-Wundef</tt> etc.
191</p>
192
193<p>
194Mapping to <tt>Fatal</tt> should only be used for diagnostics that are
195considered so severe that error recovery won't be able to recover sensibly from
196them (thus spewing a ton of bogus errors). One example of this class of error
197are failure to #include a file.
198</p>
Chris Lattner62fd2782008-11-22 21:41:31 +0000199
200<!-- ================= -->
201<h4>The Format String</h4>
202<!-- ================= -->
203
204<p>The format string for the diagnostic is very simple, but it has some power.
205It takes the form of a string in English with markers that indicate where and
206how arguments to the diagnostic are inserted and formatted. For example, here
207are some simple format strings:</p>
208
209<pre>
210 "binary integer literals are an extension"
211 "format string contains '\\0' within the string body"
212 "more '<b>%%</b>' conversions than data arguments"
Chris Lattner545b3682008-11-23 20:27:13 +0000213 "invalid operands to binary expression (<b>%0</b> and <b>%1</b>)"
Chris Lattner62fd2782008-11-22 21:41:31 +0000214 "overloaded '<b>%0</b>' must be a <b>%select{unary|binary|unary or binary}2</b> operator"
215 " (has <b>%1</b> parameter<b>%s1</b>)"
216</pre>
217
218<p>These examples show some important points of format strings. You can use any
219 plain ASCII character in the diagnostic string except "%" without a problem,
220 but these are C strings, so you have to use and be aware of all the C escape
221 sequences (as in the second example). If you want to produce a "%" in the
222 output, use the "%%" escape sequence, like the third diagnostic. Finally,
Chris Lattner552de0a2008-11-23 08:16:56 +0000223 Clang uses the "%...[digit]" sequences to specify where and how arguments to
Chris Lattner62fd2782008-11-22 21:41:31 +0000224 the diagnostic are formatted.</p>
225
226<p>Arguments to the diagnostic are numbered according to how they are specified
227 by the C++ code that <a href="#producingdiag">produces them</a>, and are
228 referenced by <tt>%0</tt> .. <tt>%9</tt>. If you have more than 10 arguments
Chris Lattner552de0a2008-11-23 08:16:56 +0000229 to your diagnostic, you are doing something wrong :). Unlike printf, there
Chris Lattner62fd2782008-11-22 21:41:31 +0000230 is no requirement that arguments to the diagnostic end up in the output in
231 the same order as they are specified, you could have a format string with
232 <tt>"%1 %0"</tt> that swaps them, for example. The text in between the
233 percent and digit are formatting instructions. If there are no instructions,
234 the argument is just turned into a string and substituted in.</p>
235
236<p>Here are some "best practices" for writing the English format string:</p>
237
238<ul>
239<li>Keep the string short. It should ideally fit in the 80 column limit of the
240 <tt>DiagnosticKinds.def</tt> file. This avoids the diagnostic wrapping when
241 printed, and forces you to think about the important point you are conveying
242 with the diagnostic.</li>
243<li>Take advantage of location information. The user will be able to see the
244 line and location of the caret, so you don't need to tell them that the
245 problem is with the 4th argument to the function: just point to it.</li>
246<li>Do not capitalize the diagnostic string, and do not end it with a
247 period.</li>
248<li>If you need to quote something in the diagnostic string, use single
249 quotes.</li>
250</ul>
251
252<p>Diagnostics should never take random English strings as arguments: you
253shouldn't use <tt>"you have a problem with %0"</tt> and pass in things like
254<tt>"your argument"</tt> or <tt>"your return value"</tt> as arguments. Doing
255this prevents <a href="translation">translating</a> the Clang diagnostics to
256other languages (because they'll get random English words in their otherwise
257localized diagnostic). The exceptions to this are C/C++ language keywords
258(e.g. auto, const, mutable, etc) and C/C++ operators (<tt>/=</tt>). Note
259that things like "pointer" and "reference" are not keywords. On the other
260hand, you <em>can</em> include anything that comes from the user's source code,
Chris Lattner552de0a2008-11-23 08:16:56 +0000261including variable names, types, labels, etc. The 'select' format can be
262used to achieve this sort of thing in a localizable way, see below.</p>
Chris Lattner62fd2782008-11-22 21:41:31 +0000263
264<!-- ==================================== -->
265<h4>Formatting a Diagnostic Argument</a></h4>
266<!-- ==================================== -->
267
268<p>Arguments to diagnostics are fully typed internally, and come from a couple
269different classes: integers, types, names, and random strings. Depending on
270the class of the argument, it can be optionally formatted in different ways.
271This gives the DiagnosticClient information about what the argument means
272without requiring it to use a specific presentation (consider this MVC for
273Clang :).</p>
274
275<p>Here are the different diagnostic argument formats currently supported by
276Clang:</p>
277
278<table>
279<tr><td colspan="2"><b>"s" format</b></td></tr>
280<tr><td>Example:</td><td><tt>"requires %1 parameter%s1"</tt></td></tr>
Chris Lattner552de0a2008-11-23 08:16:56 +0000281<tr><td>Class:</td><td>Integers</td></tr>
Chris Lattner62fd2782008-11-22 21:41:31 +0000282<tr><td>Description:</td><td>This is a simple formatter for integers that is
283 useful when producing English diagnostics. When the integer is 1, it prints
284 as nothing. When the integer is not 1, it prints as "s". This allows some
Chris Lattner627b7052008-11-23 00:28:33 +0000285 simple grammatical forms to be to be handled correctly, and eliminates the
286 need to use gross things like <tt>"requires %1 parameter(s)"</tt>.</td></tr>
Chris Lattner62fd2782008-11-22 21:41:31 +0000287
288<tr><td colspan="2"><b>"select" format</b></td></tr>
289<tr><td>Example:</td><td><tt>"must be a %select{unary|binary|unary or binary}2
290 operator"</tt></td></tr>
Chris Lattner552de0a2008-11-23 08:16:56 +0000291<tr><td>Class:</td><td>Integers</td></tr>
Chris Lattnercc543342008-11-22 23:50:47 +0000292<tr><td>Description:</td><td>This format specifier is used to merge multiple
293 related diagnostics together into one common one, without requiring the
Chris Lattner552de0a2008-11-23 08:16:56 +0000294 difference to be specified as an English string argument. Instead of
Chris Lattnercc543342008-11-22 23:50:47 +0000295 specifying the string, the diagnostic gets an integer argument and the
296 format string selects the numbered option. In this case, the "%2" value
297 must be an integer in the range [0..2]. If it is 0, it prints 'unary', if
298 it is 1 it prints 'binary' if it is 2, it prints 'unary or binary'. This
299 allows other language translations to substitute reasonable words (or entire
300 phrases) based on the semantics of the diagnostic instead of having to do
301 things textually.</td></tr>
Chris Lattner62fd2782008-11-22 21:41:31 +0000302
303<tr><td colspan="2"><b>"plural" format</b></td></tr>
Sebastian Redl68168562008-11-22 22:16:45 +0000304<tr><td>Example:</td><td><tt>"you have %1 %plural{1:mouse|:mice}1 connected to
305 your computer"</tt></td></tr>
Chris Lattner552de0a2008-11-23 08:16:56 +0000306<tr><td>Class:</td><td>Integers</td></tr>
Sebastian Redl68168562008-11-22 22:16:45 +0000307<tr><td>Description:</td><td><p>This is a formatter for complex plural forms.
308 It is designed to handle even the requirements of languages with very
309 complex plural forms, as many Baltic languages have. The argument consists
310 of a series of expression/form pairs, separated by ':', where the first form
311 whose expression evaluates to true is the result of the modifier.</p>
312 <p>An expression can be empty, in which case it is always true. See the
313 example at the top. Otherwise, it is a series of one or more numeric
314 conditions, separated by ','. If any condition matches, the expression
315 matches. Each numeric condition can take one of three forms.</p>
316 <ul>
317 <li>number: A simple decimal number matches if the argument is the same
Chris Lattner627b7052008-11-23 00:28:33 +0000318 as the number. Example: <tt>"%plural{1:mouse|:mice}4"</tt></li>
Sebastian Redl68168562008-11-22 22:16:45 +0000319 <li>range: A range in square brackets matches if the argument is within
Chris Lattner552de0a2008-11-23 08:16:56 +0000320 the range. Then range is inclusive on both ends. Example:
Chris Lattner627b7052008-11-23 00:28:33 +0000321 <tt>"%plural{0:none|1:one|[2,5]:some|:many}2"</tt></li>
322 <li>modulo: A modulo operator is followed by a number, and
323 equals sign and either a number or a range. The tests are the
324 same as for plain
Sebastian Redl68168562008-11-22 22:16:45 +0000325 numbers and ranges, but the argument is taken modulo the number first.
Chris Lattner627b7052008-11-23 00:28:33 +0000326 Example: <tt>"%plural{%100=0:even hundred|%100=[1,50]:lower half|:everything
327 else}1"</tt></li>
Sebastian Redl68168562008-11-22 22:16:45 +0000328 </ul>
329 <p>The parser is very unforgiving. A syntax error, even whitespace, will
330 abort, as will a failure to match the argument against any
331 expression.</p></td></tr>
Chris Lattner62fd2782008-11-22 21:41:31 +0000332
Chris Lattner077bf5e2008-11-24 03:33:13 +0000333<tr><td colspan="2"><b>"objcclass" format</b></td></tr>
334<tr><td>Example:</td><td><tt>"method %objcclass0 not found"</tt></td></tr>
335<tr><td>Class:</td><td>DeclarationName</td></tr>
336<tr><td>Description:</td><td><p>This is a simple formatter that indicates the
337 DeclarationName corresponds to an Objective-C class method selector. As
338 such, it prints the selector with a leading '+'.</p></td></tr>
339
340<tr><td colspan="2"><b>"objcinstance" format</b></td></tr>
341<tr><td>Example:</td><td><tt>"method %objcinstance0 not found"</tt></td></tr>
342<tr><td>Class:</td><td>DeclarationName</td></tr>
343<tr><td>Description:</td><td><p>This is a simple formatter that indicates the
344 DeclarationName corresponds to an Objective-C instance method selector. As
345 such, it prints the selector with a leading '-'.</p></td></tr>
346
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000347<tr><td colspan="2"><b>"q" format</b></td></tr>
348<tr><td>Example:</td><td><tt>"candidate found by name lookup is %q0"</tt></td></tr>
349<tr><td>Class:</td><td>NamedDecl*</td></tr>
350<tr><td>Description</td><td><p>This formatter indicates that the fully-qualified name of the declaration should be printed, e.g., "std::vector" rather than "vector".</p></td></tr>
351
Chris Lattner62fd2782008-11-22 21:41:31 +0000352</table>
353
Chris Lattnercc543342008-11-22 23:50:47 +0000354<p>It is really easy to add format specifiers to the Clang diagnostics system,
Chris Lattner552de0a2008-11-23 08:16:56 +0000355but they should be discussed before they are added. If you are creating a lot
356of repetitive diagnostics and/or have an idea for a useful formatter, please
357bring it up on the cfe-dev mailing list.</p>
Chris Lattnercc543342008-11-22 23:50:47 +0000358
Chris Lattner62fd2782008-11-22 21:41:31 +0000359<!-- ===================================================== -->
360<h4><a name="#producingdiag">Producing the Diagnostic</a></h4>
361<!-- ===================================================== -->
362
Chris Lattner627b7052008-11-23 00:28:33 +0000363<p>Now that you've created the diagnostic in the DiagnosticKinds.def file, you
Chris Lattner552de0a2008-11-23 08:16:56 +0000364need to write the code that detects the condition in question and emits the
365new diagnostic. Various components of Clang (e.g. the preprocessor, Sema,
Chris Lattner627b7052008-11-23 00:28:33 +0000366etc) provide a helper function named "Diag". It creates a diagnostic and
367accepts the arguments, ranges, and other information that goes along with
368it.</p>
Chris Lattner62fd2782008-11-22 21:41:31 +0000369
Chris Lattner552de0a2008-11-23 08:16:56 +0000370<p>For example, the binary expression error comes from code like this:</p>
Chris Lattner627b7052008-11-23 00:28:33 +0000371
372<pre>
373 if (various things that are bad)
374 Diag(Loc, diag::err_typecheck_invalid_operands)
375 &lt;&lt; lex-&gt;getType() &lt;&lt; rex-&gt;getType()
376 &lt;&lt; lex-&gt;getSourceRange() &lt;&lt; rex-&gt;getSourceRange();
377</pre>
378
379<p>This shows that use of the Diag method: they take a location (a <a
380href="#SourceLocation">SourceLocation</a> object) and a diagnostic enum value
381(which matches the name from DiagnosticKinds.def). If the diagnostic takes
382arguments, they are specified with the &lt;&lt; operator: the first argument
383becomes %0, the second becomes %1, etc. The diagnostic interface allows you to
Chris Lattnerfd408ea2008-11-23 00:42:53 +0000384specify arguments of many different types, including <tt>int</tt> and
385<tt>unsigned</tt> for integer arguments, <tt>const char*</tt> and
386<tt>std::string</tt> for string arguments, <tt>DeclarationName</tt> and
387<tt>const IdentifierInfo*</tt> for names, <tt>QualType</tt> for types, etc.
388SourceRanges are also specified with the &lt;&lt; operator, but do not have a
389specific ordering requirement.</p>
Chris Lattner627b7052008-11-23 00:28:33 +0000390
391<p>As you can see, adding and producing a diagnostic is pretty straightforward.
392The hard part is deciding exactly what you need to say to help the user, picking
393a suitable wording, and providing the information needed to format it correctly.
Chris Lattnerfd408ea2008-11-23 00:42:53 +0000394The good news is that the call site that issues a diagnostic should be
395completely independent of how the diagnostic is formatted and in what language
396it is rendered.
Chris Lattner627b7052008-11-23 00:28:33 +0000397</p>
Chris Lattner62fd2782008-11-22 21:41:31 +0000398
Douglas Gregorb2fb6de2009-02-27 17:53:17 +0000399<!-- ==================================================== -->
400<h4 id="code-modification-hints">Code Modification Hints</h4>
401<!-- ==================================================== -->
402
403<p>In some cases, the front end emits diagnostics when it is clear
404that some small change to the source code would fix the problem. For
405example, a missing semicolon at the end of a statement or a use of
Chris Lattner34c05332009-02-27 19:31:12 +0000406deprecated syntax that is easily rewritten into a more modern form.
407Clang tries very hard to emit the diagnostic and recover gracefully
408in these and other cases.</p>
Douglas Gregorb2fb6de2009-02-27 17:53:17 +0000409
Chris Lattner34c05332009-02-27 19:31:12 +0000410<p>However, for these cases where the fix is obvious, the diagnostic
411can be annotated with a code
412modification "hint" that describes how to change the code referenced
Douglas Gregorb2fb6de2009-02-27 17:53:17 +0000413by the diagnostic to fix the problem. For example, it might add the
414missing semicolon at the end of the statement or rewrite the use of a
415deprecated construct into something more palatable. Here is one such
416example C++ front end, where we warn about the right-shift operator
417changing meaning from C++98 to C++0x:</p>
418
419<pre>
420test.cpp:3:7: warning: use of right-shift operator ('&gt;&gt;') in template argument will require parentheses in C++0x
421A&lt;100 &gt;&gt; 2&gt; *a;
422 ^
423 ( )
424</pre>
425
426<p>Here, the code modification hint is suggesting that parentheses be
427added, and showing exactly where those parentheses would be inserted
428into the source code. The code modification hints themselves describe
429what changes to make to the source code in an abstract manner, which
430the text diagnostic printer renders as a line of "insertions" below
431the caret line. <a href="#DiagnosticClient">Other diagnostic
432clients</a> might choose to render the code differently (e.g., as
433markup inline) or even give the user the ability to automatically fix
434the problem.</p>
435
436<p>All code modification hints are described by the
437<code>CodeModificationHint</code> class, instances of which should be
438attached to the diagnostic using the &lt;&lt; operator in the same way
439that highlighted source ranges and arguments are passed to the
440diagnostic. Code modification hints can be created with one of three
441constructors:</p>
442
443<dl>
444 <dt><code>CodeModificationHint::CreateInsertion(Loc, Code)</code></dt>
445 <dd>Specifies that the given <code>Code</code> (a string) should be inserted
446 before the source location <code>Loc</code>.</dd>
447
448 <dt><code>CodeModificationHint::CreateRemoval(Range)</code></dt>
449 <dd>Specifies that the code in the given source <code>Range</code>
450 should be removed.</dd>
451
452 <dt><code>CodeModificationHint::CreateReplacement(Range, Code)</code></dt>
453 <dd>Specifies that the code in the given source <code>Range</code>
454 should be removed, and replaced with the given <code>Code</code> string.</dd>
455</dl>
456
Chris Lattner62fd2782008-11-22 21:41:31 +0000457<!-- ============================================================= -->
458<h4><a name="DiagnosticClient">The DiagnosticClient Interface</a></h4>
459<!-- ============================================================= -->
460
Chris Lattner627b7052008-11-23 00:28:33 +0000461<p>Once code generates a diagnostic with all of the arguments and the rest of
462the relevant information, Clang needs to know what to do with it. As previously
463mentioned, the diagnostic machinery goes through some filtering to map a
464severity onto a diagnostic level, then (assuming the diagnostic is not mapped to
465"<tt>Ignore</tt>") it invokes an object that implements the DiagnosticClient
466interface with the information.</p>
467
468<p>It is possible to implement this interface in many different ways. For
469example, the normal Clang DiagnosticClient (named 'TextDiagnosticPrinter') turns
470the arguments into strings (according to the various formatting rules), prints
471out the file/line/column information and the string, then prints out the line of
472code, the source ranges, and the caret. However, this behavior isn't required.
473</p>
474
475<p>Another implementation of the DiagnosticClient interface is the
Chris Lattner552de0a2008-11-23 08:16:56 +0000476'TextDiagnosticBuffer' class, which is used when Clang is in -verify mode.
Chris Lattnerfd408ea2008-11-23 00:42:53 +0000477Instead of formatting and printing out the diagnostics, this implementation just
478captures and remembers the diagnostics as they fly by. Then -verify compares
Chris Lattner552de0a2008-11-23 08:16:56 +0000479the list of produced diagnostics to the list of expected ones. If they disagree,
Chris Lattnerfd408ea2008-11-23 00:42:53 +0000480it prints out its own output.
Chris Lattner627b7052008-11-23 00:28:33 +0000481</p>
482
Chris Lattnerfd408ea2008-11-23 00:42:53 +0000483<p>There are many other possible implementations of this interface, and this is
484why we prefer diagnostics to pass down rich structured information in arguments.
485For example, an HTML output might want declaration names be linkified to where
486they come from in the source. Another example is that a GUI might let you click
487on typedefs to expand them. This application would want to pass significantly
488more information about types through to the GUI than a simple flat string. The
489interface allows this to happen.</p>
Chris Lattner62fd2782008-11-22 21:41:31 +0000490
491<!-- ====================================================== -->
492<h4><a name="translation">Adding Translations to Clang</a></h4>
493<!-- ====================================================== -->
494
Chris Lattner627b7052008-11-23 00:28:33 +0000495<p>Not possible yet! Diagnostic strings should be written in UTF-8, the client
Chris Lattnerfd408ea2008-11-23 00:42:53 +0000496can translate to the relevant code page if needed. Each translation completely
497replaces the format string for the diagnostic.</p>
Chris Lattner62fd2782008-11-22 21:41:31 +0000498
499
Chris Lattner86920d32007-07-31 05:42:17 +0000500<!-- ======================================================================= -->
501<h3 id="SourceLocation">The SourceLocation and SourceManager classes</h3>
502<!-- ======================================================================= -->
503
504<p>Strangely enough, the SourceLocation class represents a location within the
505source code of the program. Important design points include:</p>
506
507<ol>
508<li>sizeof(SourceLocation) must be extremely small, as these are embedded into
509 many AST nodes and are passed around often. Currently it is 32 bits.</li>
510<li>SourceLocation must be a simple value object that can be efficiently
511 copied.</li>
512<li>We should be able to represent a source location for any byte of any input
513 file. This includes in the middle of tokens, in whitespace, in trigraphs,
514 etc.</li>
515<li>A SourceLocation must encode the current #include stack that was active when
516 the location was processed. For example, if the location corresponds to a
517 token, it should contain the set of #includes active when the token was
518 lexed. This allows us to print the #include stack for a diagnostic.</li>
519<li>SourceLocation must be able to describe macro expansions, capturing both
520 the ultimate instantiation point and the source of the original character
521 data.</li>
522</ol>
523
524<p>In practice, the SourceLocation works together with the SourceManager class
Chris Lattner18376dd2009-01-16 07:00:50 +0000525to encode two pieces of information about a location: it's spelling location
Chris Lattner88054de2009-01-16 07:15:35 +0000526and it's instantiation location. For most tokens, these will be the same. However,
Chris Lattner86920d32007-07-31 05:42:17 +0000527for a macro expansion (or tokens that came from a _Pragma directive) these will
528describe the location of the characters corresponding to the token and the
529location where the token was used (i.e. the macro instantiation point or the
530location of the _Pragma itself).</p>
531
Chris Lattner552de0a2008-11-23 08:16:56 +0000532<p>The Clang front-end inherently depends on the location of a token being
Chris Lattner86920d32007-07-31 05:42:17 +0000533tracked correctly. If it is ever incorrect, the front-end may get confused and
534die. The reason for this is that the notion of the 'spelling' of a Token in
Chris Lattner552de0a2008-11-23 08:16:56 +0000535Clang depends on being able to find the original input characters for the token.
Chris Lattner18376dd2009-01-16 07:00:50 +0000536This concept maps directly to the "spelling location" for the token.</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000537
538<!-- ======================================================================= -->
Daniel Dunbar27d9e9f2009-03-30 06:50:01 +0000539<h2 id="libdriver">The Driver Library</h2>
540<!-- ======================================================================= -->
541
Ted Kremenekcfa8d572009-04-09 18:08:18 +0000542<p>The clang Driver and library are documented <a
543href="DriverInternals.html">here<a>.<p>
544
545<!-- ======================================================================= -->
Douglas Gregor32110df2009-05-20 00:16:32 +0000546<h2 id="pch">Precompiled Headers</h2>
Ted Kremenekcfa8d572009-04-09 18:08:18 +0000547<!-- ======================================================================= -->
548
Douglas Gregor32110df2009-05-20 00:16:32 +0000549<p>Clang supports two implementations of precompiled headers. The
550 default implementation, precompiled headers (<a
551 href="PCHInternals.html">PCH</a>) uses a serialized representation
552 of Clang's internal data structures, encoded with the <a
553 href="http://llvm.org/docs/BitCodeFormat.html">LLVM bitstream
554 format</a>. Pretokenized headers (<a
555 href="PTHInternals.html">PTH</a>), on the other hand, contain a
556 serialized representation of the tokens encountered when
557 preprocessing a header (and anything that header includes).</p>
558
Daniel Dunbar27d9e9f2009-03-30 06:50:01 +0000559
560<!-- ======================================================================= -->
561<h2 id="libfrontend">The Frontend Library</h2>
562<!-- ======================================================================= -->
563
564<p>The Frontend library contains functionality useful for building
565tools on top of the clang libraries, for example several methods for
566outputting diagnostics.</p>
567
568<!-- ======================================================================= -->
Chris Lattner86920d32007-07-31 05:42:17 +0000569<h2 id="liblex">The Lexer and Preprocessor Library</h2>
570<!-- ======================================================================= -->
571
572<p>The Lexer library contains several tightly-connected classes that are involved
573with the nasty process of lexing and preprocessing C source code. The main
574interface to this library for outside clients is the large <a
575href="#Preprocessor">Preprocessor</a> class.
576It contains the various pieces of state that are required to coherently read
577tokens out of a translation unit.</p>
578
579<p>The core interface to the Preprocessor object (once it is set up) is the
580Preprocessor::Lex method, which returns the next <a href="#Token">Token</a> from
581the preprocessor stream. There are two types of token providers that the
582preprocessor is capable of reading from: a buffer lexer (provided by the <a
583href="#Lexer">Lexer</a> class) and a buffered token stream (provided by the <a
Chris Lattner79281252008-03-09 02:27:26 +0000584href="#TokenLexer">TokenLexer</a> class).
Chris Lattner86920d32007-07-31 05:42:17 +0000585
586
587<!-- ======================================================================= -->
588<h3 id="Token">The Token class</h3>
589<!-- ======================================================================= -->
590
591<p>The Token class is used to represent a single lexed token. Tokens are
592intended to be used by the lexer/preprocess and parser libraries, but are not
593intended to live beyond them (for example, they should not live in the ASTs).<p>
594
595<p>Tokens most often live on the stack (or some other location that is efficient
596to access) as the parser is running, but occasionally do get buffered up. For
597example, macro definitions are stored as a series of tokens, and the C++
Chris Lattner3fcbb892008-11-23 08:32:53 +0000598front-end periodically needs to buffer tokens up for tentative parsing and
Chris Lattner86920d32007-07-31 05:42:17 +0000599various pieces of look-ahead. As such, the size of a Token matter. On a 32-bit
600system, sizeof(Token) is currently 16 bytes.</p>
601
Chris Lattner3932fe02009-01-06 06:02:08 +0000602<p>Tokens occur in two forms: "<a href="#AnnotationToken">Annotation
603Tokens</a>" and normal tokens. Normal tokens are those returned by the lexer,
604annotation tokens represent semantic information and are produced by the parser,
605replacing normal tokens in the token stream. Normal tokens contain the
606following information:</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000607
608<ul>
609<li><b>A SourceLocation</b> - This indicates the location of the start of the
610token.</li>
611
612<li><b>A length</b> - This stores the length of the token as stored in the
613SourceBuffer. For tokens that include them, this length includes trigraphs and
614escaped newlines which are ignored by later phases of the compiler. By pointing
615into the original source buffer, it is always possible to get the original
616spelling of a token completely accurately.</li>
617
618<li><b>IdentifierInfo</b> - If a token takes the form of an identifier, and if
619identifier lookup was enabled when the token was lexed (e.g. the lexer was not
620reading in 'raw' mode) this contains a pointer to the unique hash value for the
621identifier. Because the lookup happens before keyword identification, this
622field is set even for language keywords like 'for'.</li>
623
624<li><b>TokenKind</b> - This indicates the kind of token as classified by the
625lexer. This includes things like <tt>tok::starequal</tt> (for the "*="
626operator), <tt>tok::ampamp</tt> for the "&amp;&amp;" token, and keyword values
627(e.g. <tt>tok::kw_for</tt>) for identifiers that correspond to keywords. Note
628that some tokens can be spelled multiple ways. For example, C++ supports
629"operator keywords", where things like "and" are treated exactly like the
630"&amp;&amp;" operator. In these cases, the kind value is set to
631<tt>tok::ampamp</tt>, which is good for the parser, which doesn't have to
632consider both forms. For something that cares about which form is used (e.g.
633the preprocessor 'stringize' operator) the spelling indicates the original
634form.</li>
635
636<li><b>Flags</b> - There are currently four flags tracked by the
637lexer/preprocessor system on a per-token basis:
638
639 <ol>
640 <li><b>StartOfLine</b> - This was the first token that occurred on its input
641 source line.</li>
642 <li><b>LeadingSpace</b> - There was a space character either immediately
643 before the token or transitively before the token as it was expanded
644 through a macro. The definition of this flag is very closely defined by
645 the stringizing requirements of the preprocessor.</li>
646 <li><b>DisableExpand</b> - This flag is used internally to the preprocessor to
647 represent identifier tokens which have macro expansion disabled. This
648 prevents them from being considered as candidates for macro expansion ever
649 in the future.</li>
650 <li><b>NeedsCleaning</b> - This flag is set if the original spelling for the
651 token includes a trigraph or escaped newline. Since this is uncommon,
652 many pieces of code can fast-path on tokens that did not need cleaning.
653 </p>
654 </ol>
655</li>
656</ul>
657
Chris Lattner3932fe02009-01-06 06:02:08 +0000658<p>One interesting (and somewhat unusual) aspect of normal tokens is that they
659don't contain any semantic information about the lexed value. For example, if
660the token was a pp-number token, we do not represent the value of the number
661that was lexed (this is left for later pieces of code to decide). Additionally,
662the lexer library has no notion of typedef names vs variable names: both are
Chris Lattner86920d32007-07-31 05:42:17 +0000663returned as identifiers, and the parser is left to decide whether a specific
664identifier is a typedef or a variable (tracking this requires scope information
Chris Lattner3932fe02009-01-06 06:02:08 +0000665among other things). The parser can do this translation by replacing tokens
666returned by the preprocessor with "Annotation Tokens".</p>
667
668<!-- ======================================================================= -->
669<h3 id="AnnotationToken">Annotation Tokens</h3>
670<!-- ======================================================================= -->
671
672<p>Annotation Tokens are tokens that are synthesized by the parser and injected
673into the preprocessor's token stream (replacing existing tokens) to record
674semantic information found by the parser. For example, if "foo" is found to be
675a typedef, the "foo" <tt>tok::identifier</tt> token is replaced with an
676<tt>tok::annot_typename</tt>. This is useful for a couple of reasons: 1) this
677makes it easy to handle qualified type names (e.g. "foo::bar::baz&lt;42&gt;::t")
678in C++ as a single "token" in the parser. 2) if the parser backtracks, the
679reparse does not need to redo semantic analysis to determine whether a token
680sequence is a variable, type, template, etc.</p>
681
682<p>Annotation Tokens are created by the parser and reinjected into the parser's
683token stream (when backtracking is enabled). Because they can only exist in
684tokens that the preprocessor-proper is done with, it doesn't need to keep around
685flags like "start of line" that the preprocessor uses to do its job.
686Additionally, an annotation token may "cover" a sequence of preprocessor tokens
687(e.g. <tt>a::b::c</tt> is five preprocessor tokens). As such, the valid fields
688of an annotation token are different than the fields for a normal token (but
689they are multiplexed into the normal Token fields):</p>
690
691<ul>
692<li><b>SourceLocation "Location"</b> - The SourceLocation for the annotation
693token indicates the first token replaced by the annotation token. In the example
694above, it would be the location of the "a" identifier.</li>
695
696<li><b>SourceLocation "AnnotationEndLoc"</b> - This holds the location of the
697last token replaced with the annotation token. In the example above, it would
698be the location of the "c" identifier.</li>
699
700<li><b>void* "AnnotationValue"</b> - This contains an opaque object that the
701parser gets from Sema through an Actions module, it is passed around and Sema
702intepretes it, based on the type of annotation token.</li>
703
704<li><b>TokenKind "Kind"</b> - This indicates the kind of Annotation token this
705is. See below for the different valid kinds.</li>
706</ul>
707
708<p>Annotation tokens currently come in three kinds:</p>
709
710<ol>
711<li><b>tok::annot_typename</b>: This annotation token represents a
712resolved typename token that is potentially qualified. The AnnotationValue
Steve Naroffb43a50f2009-01-28 19:39:02 +0000713field contains a pointer returned by Action::getTypeName(). In the case of the
Chris Lattner3932fe02009-01-06 06:02:08 +0000714Sema actions module, this is a <tt>Decl*</tt> for the type.</li>
715
716<li><b>tok::annot_cxxscope</b>: This annotation token represents a C++ scope
717specifier, such as "A::B::". This corresponds to the grammar productions "::"
718and ":: [opt] nested-name-specifier". The AnnotationValue pointer is returned
719by the Action::ActOnCXXGlobalScopeSpecifier and
720Action::ActOnCXXNestedNameSpecifier callbacks. In the case of Sema, this is a
721<tt>DeclContext*</tt>.</li>
722
Douglas Gregor39a8de12009-02-25 19:37:18 +0000723<li><b>tok::annot_template_id</b>: This annotation token represents a
724C++ template-id such as "foo&lt;int, 4&gt;", where "foo" is the name
725of a template. The AnnotationValue pointer is a pointer to a malloc'd
726TemplateIdAnnotation object. Depending on the context, a parsed template-id that names a type might become a typename annotation token (if all we care about is the named type, e.g., because it occurs in a type specifier) or might remain a template-id token (if we want to retain more source location information or produce a new type, e.g., in a declaration of a class template specialization). template-id annotation tokens that refer to a type can be "upgraded" to typename annotation tokens by the parser.</li>
Chris Lattner3932fe02009-01-06 06:02:08 +0000727
728</ol>
729
Cedric Venetda76b282009-01-06 16:22:54 +0000730<p>As mentioned above, annotation tokens are not returned by the preprocessor,
Chris Lattner3932fe02009-01-06 06:02:08 +0000731they are formed on demand by the parser. This means that the parser has to be
732aware of cases where an annotation could occur and form it where appropriate.
733This is somewhat similar to how the parser handles Translation Phase 6 of C99:
734String Concatenation (see C99 5.1.1.2). In the case of string concatenation,
735the preprocessor just returns distinct tok::string_literal and
736tok::wide_string_literal tokens and the parser eats a sequence of them wherever
737the grammar indicates that a string literal can occur.</p>
738
739<p>In order to do this, whenever the parser expects a tok::identifier or
740tok::coloncolon, it should call the TryAnnotateTypeOrScopeToken or
741TryAnnotateCXXScopeToken methods to form the annotation token. These methods
742will maximally form the specified annotation tokens and replace the current
743token with them, if applicable. If the current tokens is not valid for an
744annotation token, it will remain an identifier or :: token.</p>
745
746
Chris Lattner86920d32007-07-31 05:42:17 +0000747
748<!-- ======================================================================= -->
749<h3 id="Lexer">The Lexer class</h3>
750<!-- ======================================================================= -->
751
752<p>The Lexer class provides the mechanics of lexing tokens out of a source
753buffer and deciding what they mean. The Lexer is complicated by the fact that
754it operates on raw buffers that have not had spelling eliminated (this is a
755necessity to get decent performance), but this is countered with careful coding
756as well as standard performance techniques (for example, the comment handling
757code is vectorized on X86 and PowerPC hosts).</p>
758
759<p>The lexer has a couple of interesting modal features:</p>
760
761<ul>
762<li>The lexer can operate in 'raw' mode. This mode has several features that
763 make it possible to quickly lex the file (e.g. it stops identifier lookup,
764 doesn't specially handle preprocessor tokens, handles EOF differently, etc).
765 This mode is used for lexing within an "<tt>#if 0</tt>" block, for
766 example.</li>
767<li>The lexer can capture and return comments as tokens. This is required to
768 support the -C preprocessor mode, which passes comments through, and is
769 used by the diagnostic checker to identifier expect-error annotations.</li>
770<li>The lexer can be in ParsingFilename mode, which happens when preprocessing
Chris Lattner84386242007-09-16 19:25:23 +0000771 after reading a #include directive. This mode changes the parsing of '&lt;'
Chris Lattner86920d32007-07-31 05:42:17 +0000772 to return an "angled string" instead of a bunch of tokens for each thing
773 within the filename.</li>
774<li>When parsing a preprocessor directive (after "<tt>#</tt>") the
775 ParsingPreprocessorDirective mode is entered. This changes the parser to
776 return EOM at a newline.</li>
777<li>The Lexer uses a LangOptions object to know whether trigraphs are enabled,
778 whether C++ or ObjC keywords are recognized, etc.</li>
779</ul>
780
781<p>In addition to these modes, the lexer keeps track of a couple of other
782 features that are local to a lexed buffer, which change as the buffer is
783 lexed:</p>
784
785<ul>
786<li>The Lexer uses BufferPtr to keep track of the current character being
787 lexed.</li>
788<li>The Lexer uses IsAtStartOfLine to keep track of whether the next lexed token
789 will start with its "start of line" bit set.</li>
790<li>The Lexer keeps track of the current #if directives that are active (which
791 can be nested).</li>
792<li>The Lexer keeps track of an <a href="#MultipleIncludeOpt">
793 MultipleIncludeOpt</a> object, which is used to
794 detect whether the buffer uses the standard "<tt>#ifndef XX</tt> /
795 <tt>#define XX</tt>" idiom to prevent multiple inclusion. If a buffer does,
796 subsequent includes can be ignored if the XX macro is defined.</li>
797</ul>
798
799<!-- ======================================================================= -->
Chris Lattner79281252008-03-09 02:27:26 +0000800<h3 id="TokenLexer">The TokenLexer class</h3>
Chris Lattner86920d32007-07-31 05:42:17 +0000801<!-- ======================================================================= -->
802
Chris Lattner79281252008-03-09 02:27:26 +0000803<p>The TokenLexer class is a token provider that returns tokens from a list
Chris Lattner86920d32007-07-31 05:42:17 +0000804of tokens that came from somewhere else. It typically used for two things: 1)
805returning tokens from a macro definition as it is being expanded 2) returning
806tokens from an arbitrary buffer of tokens. The later use is used by _Pragma and
807will most likely be used to handle unbounded look-ahead for the C++ parser.</p>
808
809<!-- ======================================================================= -->
810<h3 id="MultipleIncludeOpt">The MultipleIncludeOpt class</h3>
811<!-- ======================================================================= -->
812
813<p>The MultipleIncludeOpt class implements a really simple little state machine
814that is used to detect the standard "<tt>#ifndef XX</tt> / <tt>#define XX</tt>"
815idiom that people typically use to prevent multiple inclusion of headers. If a
816buffer uses this idiom and is subsequently #include'd, the preprocessor can
817simply check to see whether the guarding condition is defined or not. If so,
818the preprocessor can completely ignore the include of the header.</p>
819
820
821
822<!-- ======================================================================= -->
823<h2 id="libparse">The Parser Library</h2>
824<!-- ======================================================================= -->
825
826<!-- ======================================================================= -->
827<h2 id="libast">The AST Library</h2>
828<!-- ======================================================================= -->
829
830<!-- ======================================================================= -->
831<h3 id="Type">The Type class and its subclasses</h3>
832<!-- ======================================================================= -->
833
834<p>The Type class (and its subclasses) are an important part of the AST. Types
835are accessed through the ASTContext class, which implicitly creates and uniques
836them as they are needed. Types have a couple of non-obvious features: 1) they
837do not capture type qualifiers like const or volatile (See
838<a href="#QualType">QualType</a>), and 2) they implicitly capture typedef
Chris Lattner8a2bc622007-07-31 06:37:39 +0000839information. Once created, types are immutable (unlike decls).</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000840
841<p>Typedefs in C make semantic analysis a bit more complex than it would
842be without them. The issue is that we want to capture typedef information
843and represent it in the AST perfectly, but the semantics of operations need to
844"see through" typedefs. For example, consider this code:</p>
845
846<code>
847void func() {<br>
Bill Wendling30d17752007-10-06 01:56:01 +0000848&nbsp;&nbsp;typedef int foo;<br>
849&nbsp;&nbsp;foo X, *Y;<br>
850&nbsp;&nbsp;typedef foo* bar;<br>
851&nbsp;&nbsp;bar Z;<br>
852&nbsp;&nbsp;*X; <i>// error</i><br>
853&nbsp;&nbsp;**Y; <i>// error</i><br>
854&nbsp;&nbsp;**Z; <i>// error</i><br>
Chris Lattner86920d32007-07-31 05:42:17 +0000855}<br>
856</code>
857
858<p>The code above is illegal, and thus we expect there to be diagnostics emitted
859on the annotated lines. In this example, we expect to get:</p>
860
861<pre>
Chris Lattner8a2bc622007-07-31 06:37:39 +0000862<b>test.c:6:1: error: indirection requires pointer operand ('foo' invalid)</b>
Chris Lattner86920d32007-07-31 05:42:17 +0000863*X; // error
864<font color="blue">^~</font>
Chris Lattner8a2bc622007-07-31 06:37:39 +0000865<b>test.c:7:1: error: indirection requires pointer operand ('foo' invalid)</b>
Chris Lattner86920d32007-07-31 05:42:17 +0000866**Y; // error
867<font color="blue">^~~</font>
Chris Lattner8a2bc622007-07-31 06:37:39 +0000868<b>test.c:8:1: error: indirection requires pointer operand ('foo' invalid)</b>
869**Z; // error
870<font color="blue">^~~</font>
Chris Lattner86920d32007-07-31 05:42:17 +0000871</pre>
872
873<p>While this example is somewhat silly, it illustrates the point: we want to
874retain typedef information where possible, so that we can emit errors about
875"<tt>std::string</tt>" instead of "<tt>std::basic_string&lt;char, std:...</tt>".
876Doing this requires properly keeping typedef information (for example, the type
877of "X" is "foo", not "int"), and requires properly propagating it through the
Chris Lattner8a2bc622007-07-31 06:37:39 +0000878various operators (for example, the type of *Y is "foo", not "int"). In order
879to retain this information, the type of these expressions is an instance of the
880TypedefType class, which indicates that the type of these expressions is a
881typedef for foo.
882</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000883
Chris Lattner8a2bc622007-07-31 06:37:39 +0000884<p>Representing types like this is great for diagnostics, because the
885user-specified type is always immediately available. There are two problems
886with this: first, various semantic checks need to make judgements about the
Chris Lattner33fc68a2007-07-31 18:54:50 +0000887<em>actual structure</em> of a type, ignoring typdefs. Second, we need an
888efficient way to query whether two types are structurally identical to each
889other, ignoring typedefs. The solution to both of these problems is the idea of
Chris Lattner8a2bc622007-07-31 06:37:39 +0000890canonical types.</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000891
Chris Lattner62fd2782008-11-22 21:41:31 +0000892<!-- =============== -->
Chris Lattner8a2bc622007-07-31 06:37:39 +0000893<h4>Canonical Types</h4>
Chris Lattner62fd2782008-11-22 21:41:31 +0000894<!-- =============== -->
Chris Lattner86920d32007-07-31 05:42:17 +0000895
Chris Lattner8a2bc622007-07-31 06:37:39 +0000896<p>Every instance of the Type class contains a canonical type pointer. For
897simple types with no typedefs involved (e.g. "<tt>int</tt>", "<tt>int*</tt>",
898"<tt>int**</tt>"), the type just points to itself. For types that have a
899typedef somewhere in their structure (e.g. "<tt>foo</tt>", "<tt>foo*</tt>",
900"<tt>foo**</tt>", "<tt>bar</tt>"), the canonical type pointer points to their
901structurally equivalent type without any typedefs (e.g. "<tt>int</tt>",
902"<tt>int*</tt>", "<tt>int**</tt>", and "<tt>int*</tt>" respectively).</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000903
Chris Lattner8a2bc622007-07-31 06:37:39 +0000904<p>This design provides a constant time operation (dereferencing the canonical
905type pointer) that gives us access to the structure of types. For example,
906we can trivially tell that "bar" and "foo*" are the same type by dereferencing
907their canonical type pointers and doing a pointer comparison (they both point
908to the single "<tt>int*</tt>" type).</p>
909
910<p>Canonical types and typedef types bring up some complexities that must be
911carefully managed. Specifically, the "isa/cast/dyncast" operators generally
912shouldn't be used in code that is inspecting the AST. For example, when type
913checking the indirection operator (unary '*' on a pointer), the type checker
914must verify that the operand has a pointer type. It would not be correct to
915check that with "<tt>isa&lt;PointerType&gt;(SubExpr-&gt;getType())</tt>",
916because this predicate would fail if the subexpression had a typedef type.</p>
917
918<p>The solution to this problem are a set of helper methods on Type, used to
919check their properties. In this case, it would be correct to use
920"<tt>SubExpr-&gt;getType()-&gt;isPointerType()</tt>" to do the check. This
921predicate will return true if the <em>canonical type is a pointer</em>, which is
922true any time the type is structurally a pointer type. The only hard part here
923is remembering not to use the <tt>isa/cast/dyncast</tt> operations.</p>
924
925<p>The second problem we face is how to get access to the pointer type once we
926know it exists. To continue the example, the result type of the indirection
927operator is the pointee type of the subexpression. In order to determine the
928type, we need to get the instance of PointerType that best captures the typedef
929information in the program. If the type of the expression is literally a
930PointerType, we can return that, otherwise we have to dig through the
931typedefs to find the pointer type. For example, if the subexpression had type
932"<tt>foo*</tt>", we could return that type as the result. If the subexpression
933had type "<tt>bar</tt>", we want to return "<tt>foo*</tt>" (note that we do
934<em>not</em> want "<tt>int*</tt>"). In order to provide all of this, Type has
Chris Lattner11406c12007-07-31 16:50:51 +0000935a getAsPointerType() method that checks whether the type is structurally a
Chris Lattner8a2bc622007-07-31 06:37:39 +0000936PointerType and, if so, returns the best one. If not, it returns a null
937pointer.</p>
938
939<p>This structure is somewhat mystical, but after meditating on it, it will
940make sense to you :).</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000941
942<!-- ======================================================================= -->
943<h3 id="QualType">The QualType class</h3>
944<!-- ======================================================================= -->
945
946<p>The QualType class is designed as a trivial value class that is small,
947passed by-value and is efficient to query. The idea of QualType is that it
948stores the type qualifiers (const, volatile, restrict) separately from the types
949themselves: QualType is conceptually a pair of "Type*" and bits for the type
950qualifiers.</p>
951
952<p>By storing the type qualifiers as bits in the conceptual pair, it is
953extremely efficient to get the set of qualifiers on a QualType (just return the
954field of the pair), add a type qualifier (which is a trivial constant-time
955operation that sets a bit), and remove one or more type qualifiers (just return
956a QualType with the bitfield set to empty).</p>
957
958<p>Further, because the bits are stored outside of the type itself, we do not
959need to create duplicates of types with different sets of qualifiers (i.e. there
960is only a single heap allocated "int" type: "const int" and "volatile const int"
961both point to the same heap allocated "int" type). This reduces the heap size
962used to represent bits and also means we do not have to consider qualifiers when
963uniquing types (<a href="#Type">Type</a> does not even contain qualifiers).</p>
964
965<p>In practice, on hosts where it is safe, the 3 type qualifiers are stored in
966the low bit of the pointer to the Type object. This means that QualType is
967exactly the same size as a pointer, and this works fine on any system where
968malloc'd objects are at least 8 byte aligned.</p>
Ted Kremenek8bc05712007-10-10 23:01:43 +0000969
970<!-- ======================================================================= -->
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000971<h3 id="DeclarationName">Declaration names</h3>
972<!-- ======================================================================= -->
973
974<p>The <tt>DeclarationName</tt> class represents the name of a
975 declaration in Clang. Declarations in the C family of languages can
Chris Lattner3fcbb892008-11-23 08:32:53 +0000976 take several different forms. Most declarations are named by
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000977 simple identifiers, e.g., "<code>f</code>" and "<code>x</code>" in
978 the function declaration <code>f(int x)</code>. In C++, declaration
979 names can also name class constructors ("<code>Class</code>"
980 in <code>struct Class { Class(); }</code>), class destructors
981 ("<code>~Class</code>"), overloaded operator names ("operator+"),
982 and conversion functions ("<code>operator void const *</code>"). In
983 Objective-C, declaration names can refer to the names of Objective-C
984 methods, which involve the method name and the parameters,
Chris Lattner3fcbb892008-11-23 08:32:53 +0000985 collectively called a <i>selector</i>, e.g.,
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000986 "<code>setWidth:height:</code>". Since all of these kinds of
Chris Lattner3fcbb892008-11-23 08:32:53 +0000987 entities - variables, functions, Objective-C methods, C++
988 constructors, destructors, and operators - are represented as
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000989 subclasses of Clang's common <code>NamedDecl</code>
990 class, <code>DeclarationName</code> is designed to efficiently
991 represent any kind of name.</p>
992
993<p>Given
994 a <code>DeclarationName</code> <code>N</code>, <code>N.getNameKind()</code>
Douglas Gregor2def4832008-11-17 20:34:05 +0000995 will produce a value that describes what kind of name <code>N</code>
Douglas Gregore94ca9e42008-11-18 14:39:36 +0000996 stores. There are 8 options (all of the names are inside
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000997 the <code>DeclarationName</code> class)</p>
998<dl>
999 <dt>Identifier</dt>
1000 <dd>The name is a simple
1001 identifier. Use <code>N.getAsIdentifierInfo()</code> to retrieve the
1002 corresponding <code>IdentifierInfo*</code> pointing to the actual
1003 identifier. Note that C++ overloaded operators (e.g.,
1004 "<code>operator+</code>") are represented as special kinds of
1005 identifiers. Use <code>IdentifierInfo</code>'s <code>getOverloadedOperatorID</code>
1006 function to determine whether an identifier is an overloaded
1007 operator name.</dd>
1008
1009 <dt>ObjCZeroArgSelector, ObjCOneArgSelector,
1010 ObjCMultiArgSelector</dt>
1011 <dd>The name is an Objective-C selector, which can be retrieved as a
1012 <code>Selector</code> instance
1013 via <code>N.getObjCSelector()</code>. The three possible name
1014 kinds for Objective-C reflect an optimization within
1015 the <code>DeclarationName</code> class: both zero- and
1016 one-argument selectors are stored as a
1017 masked <code>IdentifierInfo</code> pointer, and therefore require
1018 very little space, since zero- and one-argument selectors are far
1019 more common than multi-argument selectors (which use a different
1020 structure).</dd>
1021
1022 <dt>CXXConstructorName</dt>
1023 <dd>The name is a C++ constructor
1024 name. Use <code>N.getCXXNameType()</code> to retrieve
1025 the <a href="#QualType">type</a> that this constructor is meant to
1026 construct. The type is always the canonical type, since all
1027 constructors for a given type have the same name.</dd>
1028
1029 <dt>CXXDestructorName</dt>
1030 <dd>The name is a C++ destructor
1031 name. Use <code>N.getCXXNameType()</code> to retrieve
1032 the <a href="#QualType">type</a> whose destructor is being
1033 named. This type is always a canonical type.</dd>
1034
1035 <dt>CXXConversionFunctionName</dt>
1036 <dd>The name is a C++ conversion function. Conversion functions are
1037 named according to the type they convert to, e.g., "<code>operator void
1038 const *</code>". Use <code>N.getCXXNameType()</code> to retrieve
1039 the type that this conversion function converts to. This type is
1040 always a canonical type.</dd>
Douglas Gregore94ca9e42008-11-18 14:39:36 +00001041
1042 <dt>CXXOperatorName</dt>
1043 <dd>The name is a C++ overloaded operator name. Overloaded operators
1044 are named according to their spelling, e.g.,
1045 "<code>operator+</code>" or "<code>operator new
1046 []</code>". Use <code>N.getCXXOverloadedOperator()</code> to
1047 retrieve the overloaded operator (a value of
1048 type <code>OverloadedOperatorKind</code>).</dd>
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001049</dl>
1050
1051<p><code>DeclarationName</code>s are cheap to create, copy, and
1052 compare. They require only a single pointer's worth of storage in
Douglas Gregore94ca9e42008-11-18 14:39:36 +00001053 the common cases (identifiers, zero-
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001054 and one-argument Objective-C selectors) and use dense, uniqued
1055 storage for the other kinds of
1056 names. Two <code>DeclarationName</code>s can be compared for
1057 equality (<code>==</code>, <code>!=</code>) using a simple bitwise
1058 comparison, can be ordered
1059 with <code>&lt;</code>, <code>&gt;</code>, <code>&lt;=</code>,
1060 and <code>&gt;=</code> (which provide a lexicographical ordering for
1061 normal identifiers but an unspecified ordering for other kinds of
1062 names), and can be placed into LLVM <code>DenseMap</code>s
1063 and <code>DenseSet</code>s.</p>
1064
1065<p><code>DeclarationName</code> instances can be created in different
1066 ways depending on what kind of name the instance will store. Normal
Douglas Gregore94ca9e42008-11-18 14:39:36 +00001067 identifiers (<code>IdentifierInfo</code> pointers) and Objective-C selectors
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001068 (<code>Selector</code>) can be implicitly converted
1069 to <code>DeclarationName</code>s. Names for C++ constructors,
Douglas Gregore94ca9e42008-11-18 14:39:36 +00001070 destructors, conversion functions, and overloaded operators can be retrieved from
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001071 the <code>DeclarationNameTable</code>, an instance of which is
1072 available as <code>ASTContext::DeclarationNames</code>. The member
1073 functions <code>getCXXConstructorName</code>, <code>getCXXDestructorName</code>,
Douglas Gregore94ca9e42008-11-18 14:39:36 +00001074 <code>getCXXConversionFunctionName</code>, and <code>getCXXOperatorName</code>, respectively,
1075 return <code>DeclarationName</code> instances for the four kinds of
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001076 C++ special function names.</p>
1077
1078<!-- ======================================================================= -->
Douglas Gregor074149e2009-01-05 19:45:36 +00001079<h3 id="DeclContext">Declaration contexts</h3>
1080<!-- ======================================================================= -->
1081<p>Every declaration in a program exists within some <i>declaration
1082 context</i>, such as a translation unit, namespace, class, or
1083 function. Declaration contexts in Clang are represented by
1084 the <code>DeclContext</code> class, from which the various
1085 declaration-context AST nodes
1086 (<code>TranslationUnitDecl</code>, <code>NamespaceDecl</code>, <code>RecordDecl</code>, <code>FunctionDecl</code>,
1087 etc.) will derive. The <code>DeclContext</code> class provides
1088 several facilities common to each declaration context:</p>
1089<dl>
1090 <dt>Source-centric vs. Semantics-centric View of Declarations</dt>
1091 <dd><code>DeclContext</code> provides two views of the declarations
1092 stored within a declaration context. The source-centric view
1093 accurately represents the program source code as written, including
1094 multiple declarations of entities where present (see the
1095 section <a href="#Redeclarations">Redeclarations and
1096 Overloads</a>), while the semantics-centric view represents the
1097 program semantics. The two views are kept synchronized by semantic
1098 analysis while the ASTs are being constructed.</dd>
1099
1100 <dt>Storage of declarations within that context</dt>
1101 <dd>Every declaration context can contain some number of
1102 declarations. For example, a C++ class (represented
1103 by <code>RecordDecl</code>) contains various member functions,
1104 fields, nested types, and so on. All of these declarations will be
1105 stored within the <code>DeclContext</code>, and one can iterate
1106 over the declarations via
1107 [<code>DeclContext::decls_begin()</code>,
1108 <code>DeclContext::decls_end()</code>). This mechanism provides
1109 the source-centric view of declarations in the context.</dd>
1110
1111 <dt>Lookup of declarations within that context</dt>
1112 <dd>The <code>DeclContext</code> structure provides efficient name
1113 lookup for names within that declaration context. For example,
1114 if <code>N</code> is a namespace we can look for the
1115 name <code>N::f</code>
1116 using <code>DeclContext::lookup</code>. The lookup itself is
1117 based on a lazily-constructed array (for declaration contexts
1118 with a small number of declarations) or hash table (for
1119 declaration contexts with more declarations). The lookup
1120 operation provides the semantics-centric view of the declarations
1121 in the context.</dd>
1122
1123 <dt>Ownership of declarations</dt>
1124 <dd>The <code>DeclContext</code> owns all of the declarations that
1125 were declared within its declaration context, and is responsible
1126 for the management of their memory as well as their
1127 (de-)serialization.</dd>
1128</dl>
1129
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001130<p>All declarations are stored within a declaration context, and one
1131 can query
1132 information about the context in which each declaration lives. One
Douglas Gregor074149e2009-01-05 19:45:36 +00001133 can retrieve the <code>DeclContext</code> that contains a
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001134 particular <code>Decl</code>
1135 using <code>Decl::getDeclContext</code>. However, see the
Douglas Gregor074149e2009-01-05 19:45:36 +00001136 section <a href="#LexicalAndSemanticContexts">Lexical and Semantic
1137 Contexts</a> for more information about how to interpret this
1138 context information.</p>
1139
1140<h4 id="Redeclarations">Redeclarations and Overloads</h4>
1141<p>Within a translation unit, it is common for an entity to be
1142declared several times. For example, we might declare a function "f"
1143 and then later re-declare it as part of an inlined definition:</p>
1144
1145<pre>
1146void f(int x, int y, int z = 1);
1147
1148inline void f(int x, int y, int z) { /* ... */ }
1149</pre>
1150
1151<p>The representation of "f" differs in the source-centric and
1152 semantics-centric views of a declaration context. In the
1153 source-centric view, all redeclarations will be present, in the
1154 order they occurred in the source code, making
1155 this view suitable for clients that wish to see the structure of
1156 the source code. In the semantics-centric view, only the most recent "f"
1157 will be found by the lookup, since it effectively replaces the first
1158 declaration of "f".</p>
1159
1160<p>In the semantics-centric view, overloading of functions is
1161 represented explicitly. For example, given two declarations of a
1162 function "g" that are overloaded, e.g.,</p>
1163<pre>
1164void g();
1165void g(int);
1166</pre>
1167<p>the <code>DeclContext::lookup</code> operation will return
1168 an <code>OverloadedFunctionDecl</code> that contains both
1169 declarations of "g". Clients that perform semantic analysis on a
1170 program that is not concerned with the actual source code will
1171 primarily use this semantics-centric view.</p>
1172
1173<h4 id="LexicalAndSemanticContexts">Lexical and Semantic Contexts</h4>
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001174<p>Each declaration has two potentially different
Douglas Gregor074149e2009-01-05 19:45:36 +00001175 declaration contexts: a <i>lexical</i> context, which corresponds to
1176 the source-centric view of the declaration context, and
1177 a <i>semantic</i> context, which corresponds to the
1178 semantics-centric view. The lexical context is accessible
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001179 via <code>Decl::getLexicalDeclContext</code> while the
Douglas Gregor074149e2009-01-05 19:45:36 +00001180 semantic context is accessible
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001181 via <code>Decl::getDeclContext</code>, both of which return
Douglas Gregor074149e2009-01-05 19:45:36 +00001182 <code>DeclContext</code> pointers. For most declarations, the two
1183 contexts are identical. For example:</p>
1184
1185<pre>
1186class X {
1187public:
1188 void f(int x);
1189};
1190</pre>
1191
1192<p>Here, the semantic and lexical contexts of <code>X::f</code> are
1193 the <code>DeclContext</code> associated with the
1194 class <code>X</code> (itself stored as a <code>RecordDecl</code> AST
1195 node). However, we can now define <code>X::f</code> out-of-line:</p>
1196
1197<pre>
1198void X::f(int x = 17) { /* ... */ }
1199</pre>
1200
1201<p>This definition of has different lexical and semantic
1202 contexts. The lexical context corresponds to the declaration
1203 context in which the actual declaration occurred in the source
1204 code, e.g., the translation unit containing <code>X</code>. Thus,
1205 this declaration of <code>X::f</code> can be found by traversing
1206 the declarations provided by
1207 [<code>decls_begin()</code>, <code>decls_end()</code>) in the
1208 translation unit.</p>
1209
1210<p>The semantic context of <code>X::f</code> corresponds to the
1211 class <code>X</code>, since this member function is (semantically) a
1212 member of <code>X</code>. Lookup of the name <code>f</code> into
1213 the <code>DeclContext</code> associated with <code>X</code> will
1214 then return the definition of <code>X::f</code> (including
1215 information about the default argument).</p>
1216
1217<h4 id="TransparentContexts">Transparent Declaration Contexts</h4>
1218<p>In C and C++, there are several contexts in which names that are
1219 logically declared inside another declaration will actually "leak"
1220 out into the enclosing scope from the perspective of name
1221 lookup. The most obvious instance of this behavior is in
1222 enumeration types, e.g.,</p>
1223<pre>
1224enum Color {
1225 Red,
1226 Green,
1227 Blue
1228};
1229</pre>
1230
1231<p>Here, <code>Color</code> is an enumeration, which is a declaration
1232 context that contains the
1233 enumerators <code>Red</code>, <code>Green</code>,
1234 and <code>Blue</code>. Thus, traversing the list of declarations
1235 contained in the enumeration <code>Color</code> will
1236 yield <code>Red</code>, <code>Green</code>,
1237 and <code>Blue</code>. However, outside of the scope
1238 of <code>Color</code> one can name the enumerator <code>Red</code>
1239 without qualifying the name, e.g.,</p>
1240
1241<pre>
1242Color c = Red;
1243</pre>
1244
1245<p>There are other entities in C++ that provide similar behavior. For
1246 example, linkage specifications that use curly braces:</p>
1247
1248<pre>
1249extern "C" {
1250 void f(int);
1251 void g(int);
1252}
1253// f and g are visible here
1254</pre>
1255
1256<p>For source-level accuracy, we treat the linkage specification and
1257 enumeration type as a
1258 declaration context in which its enclosed declarations ("Red",
1259 "Green", and "Blue"; "f" and "g")
1260 are declared. However, these declarations are visible outside of the
1261 scope of the declaration context.</p>
1262
1263<p>These language features (and several others, described below) have
1264 roughly the same set of
1265 requirements: declarations are declared within a particular lexical
1266 context, but the declarations are also found via name lookup in
1267 scopes enclosing the declaration itself. This feature is implemented
1268 via <i>transparent</i> declaration contexts
1269 (see <code>DeclContext::isTransparentContext()</code>), whose
1270 declarations are visible in the nearest enclosing non-transparent
1271 declaration context. This means that the lexical context of the
1272 declaration (e.g., an enumerator) will be the
1273 transparent <code>DeclContext</code> itself, as will the semantic
1274 context, but the declaration will be visible in every outer context
1275 up to and including the first non-transparent declaration context (since
1276 transparent declaration contexts can be nested).</p>
1277
1278<p>The transparent <code>DeclContexts</code> are:</p>
1279<ul>
1280 <li>Enumerations (but not C++0x "scoped enumerations"):
1281 <pre>
1282enum Color {
1283 Red,
1284 Green,
1285 Blue
1286};
1287// Red, Green, and Blue are in scope
1288 </pre></li>
1289 <li>C++ linkage specifications:
1290 <pre>
1291extern "C" {
1292 void f(int);
1293 void g(int);
1294}
1295// f and g are in scope
1296 </pre></li>
1297 <li>Anonymous unions and structs:
1298 <pre>
1299struct LookupTable {
1300 bool IsVector;
1301 union {
1302 std::vector&lt;Item&gt; *Vector;
1303 std::set&lt;Item&gt; *Set;
1304 };
1305};
1306
1307LookupTable LT;
1308LT.Vector = 0; // Okay: finds Vector inside the unnamed union
1309 </pre>
1310 </li>
1311 <li>C++0x inline namespaces:
1312<pre>
1313namespace mylib {
1314 inline namespace debug {
1315 class X;
1316 }
1317}
1318mylib::X *xp; // okay: mylib::X refers to mylib::debug::X
1319</pre>
1320</li>
1321</ul>
1322
1323
1324<h4 id="MultiDeclContext">Multiply-Defined Declaration Contexts</h4>
1325<p>C++ namespaces have the interesting--and, so far, unique--property that
1326the namespace can be defined multiple times, and the declarations
1327provided by each namespace definition are effectively merged (from
1328the semantic point of view). For example, the following two code
1329snippets are semantically indistinguishable:</p>
1330<pre>
1331// Snippet #1:
1332namespace N {
1333 void f();
1334}
1335namespace N {
1336 void f(int);
1337}
1338
1339// Snippet #2:
1340namespace N {
1341 void f();
1342 void f(int);
1343}
1344</pre>
1345
1346<p>In Clang's representation, the source-centric view of declaration
1347 contexts will actually have two separate <code>NamespaceDecl</code>
1348 nodes in Snippet #1, each of which is a declaration context that
1349 contains a single declaration of "f". However, the semantics-centric
1350 view provided by name lookup into the namespace <code>N</code> for
1351 "f" will return an <code>OverloadedFunctionDecl</code> that contains
1352 both declarations of "f".</p>
1353
1354<p><code>DeclContext</code> manages multiply-defined declaration
1355 contexts internally. The
1356 function <code>DeclContext::getPrimaryContext</code> retrieves the
1357 "primary" context for a given <code>DeclContext</code> instance,
1358 which is the <code>DeclContext</code> responsible for maintaining
1359 the lookup table used for the semantics-centric view. Given the
1360 primary context, one can follow the chain
1361 of <code>DeclContext</code> nodes that define additional
1362 declarations via <code>DeclContext::getNextContext</code>. Note that
1363 these functions are used internally within the lookup and insertion
1364 methods of the <code>DeclContext</code>, so the vast majority of
1365 clients can ignore them.</p>
1366
1367<!-- ======================================================================= -->
Ted Kremenek8bc05712007-10-10 23:01:43 +00001368<h3 id="CFG">The <tt>CFG</tt> class</h3>
1369<!-- ======================================================================= -->
1370
1371<p>The <tt>CFG</tt> class is designed to represent a source-level
1372control-flow graph for a single statement (<tt>Stmt*</tt>). Typically
1373instances of <tt>CFG</tt> are constructed for function bodies (usually
1374an instance of <tt>CompoundStmt</tt>), but can also be instantiated to
1375represent the control-flow of any class that subclasses <tt>Stmt</tt>,
1376which includes simple expressions. Control-flow graphs are especially
1377useful for performing
1378<a href="http://en.wikipedia.org/wiki/Data_flow_analysis#Sensitivities">flow-
1379or path-sensitive</a> program analyses on a given function.</p>
1380
Chris Lattner62fd2782008-11-22 21:41:31 +00001381<!-- ============ -->
Ted Kremenek8bc05712007-10-10 23:01:43 +00001382<h4>Basic Blocks</h4>
Chris Lattner62fd2782008-11-22 21:41:31 +00001383<!-- ============ -->
Ted Kremenek8bc05712007-10-10 23:01:43 +00001384
1385<p>Concretely, an instance of <tt>CFG</tt> is a collection of basic
1386blocks. Each basic block is an instance of <tt>CFGBlock</tt>, which
1387simply contains an ordered sequence of <tt>Stmt*</tt> (each referring
1388to statements in the AST). The ordering of statements within a block
1389indicates unconditional flow of control from one statement to the
1390next. <a href="#ConditionalControlFlow">Conditional control-flow</a>
1391is represented using edges between basic blocks. The statements
1392within a given <tt>CFGBlock</tt> can be traversed using
1393the <tt>CFGBlock::*iterator</tt> interface.</p>
1394
1395<p>
Ted Kremenek18e17e72007-10-18 22:50:52 +00001396A <tt>CFG</tt> object owns the instances of <tt>CFGBlock</tt> within
Ted Kremenek8bc05712007-10-10 23:01:43 +00001397the control-flow graph it represents. Each <tt>CFGBlock</tt> within a
1398CFG is also uniquely numbered (accessible
1399via <tt>CFGBlock::getBlockID()</tt>). Currently the number is
1400based on the ordering the blocks were created, but no assumptions
1401should be made on how <tt>CFGBlock</tt>s are numbered other than their
1402numbers are unique and that they are numbered from 0..N-1 (where N is
1403the number of basic blocks in the CFG).</p>
1404
Chris Lattner62fd2782008-11-22 21:41:31 +00001405<!-- ===================== -->
Ted Kremenek8bc05712007-10-10 23:01:43 +00001406<h4>Entry and Exit Blocks</h4>
Chris Lattner62fd2782008-11-22 21:41:31 +00001407<!-- ===================== -->
Ted Kremenek8bc05712007-10-10 23:01:43 +00001408
1409Each instance of <tt>CFG</tt> contains two special blocks:
1410an <i>entry</i> block (accessible via <tt>CFG::getEntry()</tt>), which
1411has no incoming edges, and an <i>exit</i> block (accessible
1412via <tt>CFG::getExit()</tt>), which has no outgoing edges. Neither
1413block contains any statements, and they serve the role of providing a
1414clear entrance and exit for a body of code such as a function body.
1415The presence of these empty blocks greatly simplifies the
1416implementation of many analyses built on top of CFGs.
1417
Chris Lattner62fd2782008-11-22 21:41:31 +00001418<!-- ===================================================== -->
Ted Kremenek8bc05712007-10-10 23:01:43 +00001419<h4 id ="ConditionalControlFlow">Conditional Control-Flow</h4>
Chris Lattner62fd2782008-11-22 21:41:31 +00001420<!-- ===================================================== -->
Ted Kremenek8bc05712007-10-10 23:01:43 +00001421
1422<p>Conditional control-flow (such as those induced by if-statements
1423and loops) is represented as edges between <tt>CFGBlock</tt>s.
1424Because different C language constructs can induce control-flow,
1425each <tt>CFGBlock</tt> also records an extra <tt>Stmt*</tt> that
1426represents the <i>terminator</i> of the block. A terminator is simply
1427the statement that caused the control-flow, and is used to identify
1428the nature of the conditional control-flow between blocks. For
1429example, in the case of an if-statement, the terminator refers to
1430the <tt>IfStmt</tt> object in the AST that represented the given
1431branch.</p>
1432
1433<p>To illustrate, consider the following code example:</p>
1434
1435<code>
1436int foo(int x) {<br>
1437&nbsp;&nbsp;x = x + 1;<br>
1438<br>
1439&nbsp;&nbsp;if (x > 2) x++;<br>
1440&nbsp;&nbsp;else {<br>
1441&nbsp;&nbsp;&nbsp;&nbsp;x += 2;<br>
1442&nbsp;&nbsp;&nbsp;&nbsp;x *= 2;<br>
1443&nbsp;&nbsp;}<br>
1444<br>
1445&nbsp;&nbsp;return x;<br>
1446}
1447</code>
1448
1449<p>After invoking the parser+semantic analyzer on this code fragment,
1450the AST of the body of <tt>foo</tt> is referenced by a
1451single <tt>Stmt*</tt>. We can then construct an instance
1452of <tt>CFG</tt> representing the control-flow graph of this function
1453body by single call to a static class method:</p>
1454
1455<code>
1456&nbsp;&nbsp;Stmt* FooBody = ...<br>
1457&nbsp;&nbsp;CFG* FooCFG = <b>CFG::buildCFG</b>(FooBody);
1458</code>
1459
1460<p>It is the responsibility of the caller of <tt>CFG::buildCFG</tt>
1461to <tt>delete</tt> the returned <tt>CFG*</tt> when the CFG is no
1462longer needed.</p>
1463
1464<p>Along with providing an interface to iterate over
1465its <tt>CFGBlock</tt>s, the <tt>CFG</tt> class also provides methods
1466that are useful for debugging and visualizing CFGs. For example, the
1467method
1468<tt>CFG::dump()</tt> dumps a pretty-printed version of the CFG to
1469standard error. This is especially useful when one is using a
1470debugger such as gdb. For example, here is the output
1471of <tt>FooCFG->dump()</tt>:</p>
1472
1473<code>
1474&nbsp;[ B5 (ENTRY) ]<br>
1475&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (0):<br>
1476&nbsp;&nbsp;&nbsp;&nbsp;Successors (1): B4<br>
1477<br>
1478&nbsp;[ B4 ]<br>
1479&nbsp;&nbsp;&nbsp;&nbsp;1: x = x + 1<br>
1480&nbsp;&nbsp;&nbsp;&nbsp;2: (x > 2)<br>
1481&nbsp;&nbsp;&nbsp;&nbsp;<b>T: if [B4.2]</b><br>
1482&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (1): B5<br>
1483&nbsp;&nbsp;&nbsp;&nbsp;Successors (2): B3 B2<br>
1484<br>
1485&nbsp;[ B3 ]<br>
1486&nbsp;&nbsp;&nbsp;&nbsp;1: x++<br>
1487&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (1): B4<br>
1488&nbsp;&nbsp;&nbsp;&nbsp;Successors (1): B1<br>
1489<br>
1490&nbsp;[ B2 ]<br>
1491&nbsp;&nbsp;&nbsp;&nbsp;1: x += 2<br>
1492&nbsp;&nbsp;&nbsp;&nbsp;2: x *= 2<br>
1493&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (1): B4<br>
1494&nbsp;&nbsp;&nbsp;&nbsp;Successors (1): B1<br>
1495<br>
1496&nbsp;[ B1 ]<br>
1497&nbsp;&nbsp;&nbsp;&nbsp;1: return x;<br>
1498&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (2): B2 B3<br>
1499&nbsp;&nbsp;&nbsp;&nbsp;Successors (1): B0<br>
1500<br>
1501&nbsp;[ B0 (EXIT) ]<br>
1502&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (1): B1<br>
1503&nbsp;&nbsp;&nbsp;&nbsp;Successors (0):
1504</code>
1505
1506<p>For each block, the pretty-printed output displays for each block
1507the number of <i>predecessor</i> blocks (blocks that have outgoing
1508control-flow to the given block) and <i>successor</i> blocks (blocks
1509that have control-flow that have incoming control-flow from the given
1510block). We can also clearly see the special entry and exit blocks at
1511the beginning and end of the pretty-printed output. For the entry
1512block (block B5), the number of predecessor blocks is 0, while for the
1513exit block (block B0) the number of successor blocks is 0.</p>
1514
1515<p>The most interesting block here is B4, whose outgoing control-flow
1516represents the branching caused by the sole if-statement
1517in <tt>foo</tt>. Of particular interest is the second statement in
1518the block, <b><tt>(x > 2)</tt></b>, and the terminator, printed
1519as <b><tt>if [B4.2]</tt></b>. The second statement represents the
1520evaluation of the condition of the if-statement, which occurs before
1521the actual branching of control-flow. Within the <tt>CFGBlock</tt>
1522for B4, the <tt>Stmt*</tt> for the second statement refers to the
1523actual expression in the AST for <b><tt>(x > 2)</tt></b>. Thus
1524pointers to subclasses of <tt>Expr</tt> can appear in the list of
1525statements in a block, and not just subclasses of <tt>Stmt</tt> that
1526refer to proper C statements.</p>
1527
1528<p>The terminator of block B4 is a pointer to the <tt>IfStmt</tt>
1529object in the AST. The pretty-printer outputs <b><tt>if
1530[B4.2]</tt></b> because the condition expression of the if-statement
1531has an actual place in the basic block, and thus the terminator is
1532essentially
1533<i>referring</i> to the expression that is the second statement of
1534block B4 (i.e., B4.2). In this manner, conditions for control-flow
1535(which also includes conditions for loops and switch statements) are
1536hoisted into the actual basic block.</p>
1537
Chris Lattner62fd2782008-11-22 21:41:31 +00001538<!-- ===================== -->
1539<!-- <h4>Implicit Control-Flow</h4> -->
1540<!-- ===================== -->
Ted Kremenek8bc05712007-10-10 23:01:43 +00001541
1542<!--
1543<p>A key design principle of the <tt>CFG</tt> class was to not require
1544any transformations to the AST in order to represent control-flow.
1545Thus the <tt>CFG</tt> does not perform any "lowering" of the
1546statements in an AST: loops are not transformed into guarded gotos,
1547short-circuit operations are not converted to a set of if-statements,
1548and so on.</p>
1549-->
Ted Kremenek17a295d2008-06-11 06:19:49 +00001550
Chris Lattner7bad1992008-11-16 21:48:07 +00001551
1552<!-- ======================================================================= -->
1553<h3 id="Constants">Constant Folding in the Clang AST</h3>
1554<!-- ======================================================================= -->
1555
1556<p>There are several places where constants and constant folding matter a lot to
1557the Clang front-end. First, in general, we prefer the AST to retain the source
1558code as close to how the user wrote it as possible. This means that if they
1559wrote "5+4", we want to keep the addition and two constants in the AST, we don't
1560want to fold to "9". This means that constant folding in various ways turns
1561into a tree walk that needs to handle the various cases.</p>
1562
1563<p>However, there are places in both C and C++ that require constants to be
1564folded. For example, the C standard defines what an "integer constant
1565expression" (i-c-e) is with very precise and specific requirements. The
1566language then requires i-c-e's in a lot of places (for example, the size of a
1567bitfield, the value for a case statement, etc). For these, we have to be able
1568to constant fold the constants, to do semantic checks (e.g. verify bitfield size
1569is non-negative and that case statements aren't duplicated). We aim for Clang
1570to be very pedantic about this, diagnosing cases when the code does not use an
1571i-c-e where one is required, but accepting the code unless running with
1572<tt>-pedantic-errors</tt>.</p>
1573
1574<p>Things get a little bit more tricky when it comes to compatibility with
1575real-world source code. Specifically, GCC has historically accepted a huge
1576superset of expressions as i-c-e's, and a lot of real world code depends on this
1577unfortuate accident of history (including, e.g., the glibc system headers). GCC
1578accepts anything its "fold" optimizer is capable of reducing to an integer
1579constant, which means that the definition of what it accepts changes as its
1580optimizer does. One example is that GCC accepts things like "case X-X:" even
1581when X is a variable, because it can fold this to 0.</p>
1582
1583<p>Another issue are how constants interact with the extensions we support, such
1584as __builtin_constant_p, __builtin_inf, __extension__ and many others. C99
1585obviously does not specify the semantics of any of these extensions, and the
1586definition of i-c-e does not include them. However, these extensions are often
1587used in real code, and we have to have a way to reason about them.</p>
1588
1589<p>Finally, this is not just a problem for semantic analysis. The code
1590generator and other clients have to be able to fold constants (e.g. to
1591initialize global variables) and has to handle a superset of what C99 allows.
1592Further, these clients can benefit from extended information. For example, we
1593know that "foo()||1" always evaluates to true, but we can't replace the
1594expression with true because it has side effects.</p>
1595
1596<!-- ======================= -->
1597<h4>Implementation Approach</h4>
1598<!-- ======================= -->
1599
1600<p>After trying several different approaches, we've finally converged on a
1601design (Note, at the time of this writing, not all of this has been implemented,
1602consider this a design goal!). Our basic approach is to define a single
1603recursive method evaluation method (<tt>Expr::Evaluate</tt>), which is
1604implemented in <tt>AST/ExprConstant.cpp</tt>. Given an expression with 'scalar'
1605type (integer, fp, complex, or pointer) this method returns the following
1606information:</p>
1607
1608<ul>
1609<li>Whether the expression is an integer constant expression, a general
1610 constant that was folded but has no side effects, a general constant that
1611 was folded but that does have side effects, or an uncomputable/unfoldable
1612 value.
1613</li>
1614<li>If the expression was computable in any way, this method returns the APValue
1615 for the result of the expression.</li>
1616<li>If the expression is not evaluatable at all, this method returns
1617 information on one of the problems with the expression. This includes a
1618 SourceLocation for where the problem is, and a diagnostic ID that explains
1619 the problem. The diagnostic should be have ERROR type.</li>
1620<li>If the expression is not an integer constant expression, this method returns
1621 information on one of the problems with the expression. This includes a
1622 SourceLocation for where the problem is, and a diagnostic ID that explains
1623 the problem. The diagnostic should be have EXTENSION type.</li>
1624</ul>
1625
1626<p>This information gives various clients the flexibility that they want, and we
1627will eventually have some helper methods for various extensions. For example,
1628Sema should have a <tt>Sema::VerifyIntegerConstantExpression</tt> method, which
1629calls Evaluate on the expression. If the expression is not foldable, the error
1630is emitted, and it would return true. If the expression is not an i-c-e, the
1631EXTENSION diagnostic is emitted. Finally it would return false to indicate that
1632the AST is ok.</p>
1633
1634<p>Other clients can use the information in other ways, for example, codegen can
1635just use expressions that are foldable in any way.</p>
1636
1637<!-- ========== -->
1638<h4>Extensions</h4>
1639<!-- ========== -->
1640
Chris Lattner552de0a2008-11-23 08:16:56 +00001641<p>This section describes how some of the various extensions Clang supports
Chris Lattner7bad1992008-11-16 21:48:07 +00001642interacts with constant evaluation:</p>
1643
1644<ul>
1645<li><b><tt>__extension__</tt></b>: The expression form of this extension causes
1646 any evaluatable subexpression to be accepted as an integer constant
1647 expression.</li>
1648<li><b><tt>__builtin_constant_p</tt></b>: This returns true (as a integer
Chris Lattner28daa532008-12-12 06:55:44 +00001649 constant expression) if the operand is any evaluatable constant. As a
1650 special case, if <tt>__builtin_constant_p</tt> is the (potentially
1651 parenthesized) condition of a conditional operator expression ("?:"), only
Chris Lattner42b83dd2008-12-12 18:00:51 +00001652 the true side of the conditional operator is considered, and it is evaluated
1653 with full constant folding.</li>
Chris Lattner7bad1992008-11-16 21:48:07 +00001654<li><b><tt>__builtin_choose_expr</tt></b>: The condition is required to be an
1655 integer constant expression, but we accept any constant as an "extension of
1656 an extension". This only evaluates one operand depending on which way the
1657 condition evaluates.</li>
1658<li><b><tt>__builtin_classify_type</tt></b>: This always returns an integer
1659 constant expression.</li>
1660<li><b><tt>__builtin_inf,nan,..</tt></b>: These are treated just like a
1661 floating-point literal.</li>
1662<li><b><tt>__builtin_abs,copysign,..</tt></b>: These are constant folded as
1663 general constant expressions.</li>
1664</ul>
1665
1666
1667
1668
Ted Kremenek17a295d2008-06-11 06:19:49 +00001669</div>
1670</body>
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001671</html>