blob: 57f06316b1b1055f2c12c73f2b2eac23525bf9e8 [file] [log] [blame]
Benjamin Kramer665a8dc2012-01-15 15:26:07 +00001<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
2 "http://www.w3.org/TR/html4/strict.dtd">
Ted Kremenek17a295d2008-06-11 06:19:49 +00003<html>
4<head>
Chris Lattner552de0a2008-11-23 08:16:56 +00005<title>"Clang" CFE Internals Manual</title>
Benjamin Kramer665a8dc2012-01-15 15:26:07 +00006<link type="text/css" rel="stylesheet" href="../menu.css">
7<link type="text/css" rel="stylesheet" href="../content.css">
Sebastian Redl68168562008-11-22 22:16:45 +00008<style type="text/css">
9td {
10 vertical-align: top;
11}
12</style>
Ted Kremenek17a295d2008-06-11 06:19:49 +000013</head>
14<body>
15
16<!--#include virtual="../menu.html.incl"-->
17
18<div id="content">
Chris Lattner86920d32007-07-31 05:42:17 +000019
Chris Lattner552de0a2008-11-23 08:16:56 +000020<h1>"Clang" CFE Internals Manual</h1>
Chris Lattner86920d32007-07-31 05:42:17 +000021
22<ul>
23<li><a href="#intro">Introduction</a></li>
Peter Collingbourne967c1182011-10-15 16:59:24 +000024<li><a href="#libsupport">LLVM Support Library</a></li>
Chris Lattner552de0a2008-11-23 08:16:56 +000025<li><a href="#libbasic">The Clang 'Basic' Library</a>
Chris Lattner86920d32007-07-31 05:42:17 +000026 <ul>
Chris Lattner62fd2782008-11-22 21:41:31 +000027 <li><a href="#Diagnostics">The Diagnostics Subsystem</a></li>
Chris Lattner86920d32007-07-31 05:42:17 +000028 <li><a href="#SourceLocation">The SourceLocation and SourceManager
29 classes</a></li>
Douglas Gregor715c92a2010-10-27 16:02:28 +000030 <li><a href="#SourceRange">SourceRange and CharSourceRange</a></li>
Chris Lattner86920d32007-07-31 05:42:17 +000031 </ul>
32</li>
Daniel Dunbar27d9e9f2009-03-30 06:50:01 +000033<li><a href="#libdriver">The Driver Library</a>
Daniel Dunbar27d9e9f2009-03-30 06:50:01 +000034</li>
Douglas Gregor32110df2009-05-20 00:16:32 +000035<li><a href="#pch">Precompiled Headers</a>
Daniel Dunbar27d9e9f2009-03-30 06:50:01 +000036<li><a href="#libfrontend">The Frontend Library</a>
Daniel Dunbar27d9e9f2009-03-30 06:50:01 +000037</li>
Chris Lattner86920d32007-07-31 05:42:17 +000038<li><a href="#liblex">The Lexer and Preprocessor Library</a>
39 <ul>
40 <li><a href="#Token">The Token class</a></li>
41 <li><a href="#Lexer">The Lexer class</a></li>
Chris Lattner3932fe02009-01-06 06:02:08 +000042 <li><a href="#AnnotationToken">Annotation Tokens</a></li>
Chris Lattner79281252008-03-09 02:27:26 +000043 <li><a href="#TokenLexer">The TokenLexer class</a></li>
Chris Lattner86920d32007-07-31 05:42:17 +000044 <li><a href="#MultipleIncludeOpt">The MultipleIncludeOpt class</a></li>
45 </ul>
46</li>
47<li><a href="#libparse">The Parser Library</a>
Chris Lattner86920d32007-07-31 05:42:17 +000048</li>
49<li><a href="#libast">The AST Library</a>
50 <ul>
51 <li><a href="#Type">The Type class and its subclasses</a></li>
52 <li><a href="#QualType">The QualType class</a></li>
Douglas Gregor2e1cd422008-11-17 14:58:09 +000053 <li><a href="#DeclarationName">Declaration names</a></li>
Douglas Gregor074149e2009-01-05 19:45:36 +000054 <li><a href="#DeclContext">Declaration contexts</a>
55 <ul>
56 <li><a href="#Redeclarations">Redeclarations and Overloads</a></li>
57 <li><a href="#LexicalAndSemanticContexts">Lexical and Semantic
58 Contexts</a></li>
59 <li><a href="#TransparentContexts">Transparent Declaration Contexts</a></li>
60 <li><a href="#MultiDeclContext">Multiply-Defined Declaration Contexts</a></li>
61 </ul>
62 </li>
Ted Kremenek8bc05712007-10-10 23:01:43 +000063 <li><a href="#CFG">The CFG class</a></li>
Chris Lattner7bad1992008-11-16 21:48:07 +000064 <li><a href="#Constants">Constant Folding in the Clang AST</a></li>
Chris Lattner86920d32007-07-31 05:42:17 +000065 </ul>
66</li>
Jeffrey Yasskin28dadd62011-01-28 23:41:54 +000067<li><a href="#Howtos">Howto guides</a>
68 <ul>
69 <li><a href="#AddingAttributes">How to add an attribute</a></li>
Douglas Gregor1f634c62011-09-30 21:32:37 +000070 <li><a href="#AddingExprStmt">How to add a new expression or statement</a></li>
Jeffrey Yasskin28dadd62011-01-28 23:41:54 +000071 </ul>
72</li>
Chris Lattner86920d32007-07-31 05:42:17 +000073</ul>
74
75
76<!-- ======================================================================= -->
77<h2 id="intro">Introduction</h2>
78<!-- ======================================================================= -->
79
80<p>This document describes some of the more important APIs and internal design
Chris Lattner552de0a2008-11-23 08:16:56 +000081decisions made in the Clang C front-end. The purpose of this document is to
Chris Lattner86920d32007-07-31 05:42:17 +000082both capture some of this high level information and also describe some of the
83design decisions behind it. This is meant for people interested in hacking on
Chris Lattner552de0a2008-11-23 08:16:56 +000084Clang, not for end-users. The description below is categorized by
Chris Lattner86920d32007-07-31 05:42:17 +000085libraries, and does not describe any of the clients of the libraries.</p>
86
87<!-- ======================================================================= -->
Peter Collingbourne967c1182011-10-15 16:59:24 +000088<h2 id="libsupport">LLVM Support Library</h2>
Chris Lattner86920d32007-07-31 05:42:17 +000089<!-- ======================================================================= -->
90
Peter Collingbourne967c1182011-10-15 16:59:24 +000091<p>The LLVM libsupport library provides many underlying libraries and
92<a href="http://llvm.org/docs/ProgrammersManual.html">data-structures</a>,
93including command line option processing, various containers and a system
94abstraction layer, which is used for file system access.</p>
Chris Lattner86920d32007-07-31 05:42:17 +000095
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
Sebastian Redl9bc2a992010-07-07 23:42:27 +0000121(at the minimum) a unique ID, an English translation associated with it, a <a
122href="#SourceLocation">SourceLocation</a> to "put the caret", and a severity (e.g.
Chris Lattner62fd2782008-11-22 21:41:31 +0000123<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
Sebastian Redl9bc2a992010-07-07 23:42:27 +0000130implemented. A representative example of a diagnostic is:</p>
Chris Lattner62fd2782008-11-22 21:41:31 +0000131
132<pre>
133t.c:38:15: error: invalid operands to binary expression ('int *' and '_Complex float')
Benjamin Kramer665a8dc2012-01-15 15:26:07 +0000134 <span style="color:darkgreen">P = (P-42) + Gamma*4;</span>
135 <span style="color:blue">~~~~~~ ^ ~~~~~~~</span>
Chris Lattner62fd2782008-11-22 21:41:31 +0000136</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
Chris Lattnercc2ac1e2011-02-14 06:42:50 +0000148<!-- ============================= -->
149<h4>The Diagnostic*Kinds.td files</h4>
150<!-- ============================= -->
Chris Lattner62fd2782008-11-22 21:41:31 +0000151
Chris Lattner4c50b692010-05-01 17:35:19 +0000152<p>Diagnostics are created by adding an entry to one of the <tt>
Chris Lattnercc2ac1e2011-02-14 06:42:50 +0000153clang/Basic/Diagnostic*Kinds.td</tt> files, depending on what library will
154be using it. From this file, tblgen generates the unique ID of the diagnostic,
155the severity of the diagnostic and the English translation + format string.</p>
Chris Lattner62fd2782008-11-22 21:41:31 +0000156
157<p>There is little sanity with the naming of the unique ID's right now. Some
158start with err_, warn_, ext_ to encode the severity into the name. Since the
159enum is referenced in the C++ code that produces the diagnostic, it is somewhat
160useful for it to be reasonably short.</p>
161
162<p>The severity of the diagnostic comes from the set {<tt>NOTE</tt>,
163<tt>WARNING</tt>, <tt>EXTENSION</tt>, <tt>EXTWARN</tt>, <tt>ERROR</tt>}. The
164<tt>ERROR</tt> severity is used for diagnostics indicating the program is never
165acceptable under any circumstances. When an error is emitted, the AST for the
166input code may not be fully built. The <tt>EXTENSION</tt> and <tt>EXTWARN</tt>
167severities are used for extensions to the language that Clang accepts. This
168means that Clang fully understands and can represent them in the AST, but we
169produce diagnostics to tell the user their code is non-portable. The difference
170is that the former are ignored by default, and the later warn by default. The
171<tt>WARNING</tt> severity is used for constructs that are valid in the currently
172selected source language but that are dubious in some way. The <tt>NOTE</tt>
Daniel Dunbar426b8632009-02-17 15:49:03 +0000173level is used to staple more information onto previous diagnostics.</p>
Chris Lattner62fd2782008-11-22 21:41:31 +0000174
175<p>These <em>severities</em> are mapped into a smaller set (the
176Diagnostic::Level enum, {<tt>Ignored</tt>, <tt>Note</tt>, <tt>Warning</tt>,
Chris Lattner0aad2972009-02-05 22:49:08 +0000177<tt>Error</tt>, <tt>Fatal</tt> }) of output <em>levels</em> by the diagnostics
Chris Lattnera180fdd2009-02-17 07:07:29 +0000178subsystem based on various configuration options. Clang internally supports a
179fully fine grained mapping mechanism that allows you to map almost any
180diagnostic to the output level that you want. The only diagnostics that cannot
181be mapped are <tt>NOTE</tt>s, which always follow the severity of the previously
182emitted diagnostic and <tt>ERROR</tt>s, which can only be mapped to
183<tt>Fatal</tt> (it is not possible to turn an error into a warning,
184for example).</p>
185
186<p>Diagnostic mappings are used in many ways. For example, if the user
187specifies <tt>-pedantic</tt>, <tt>EXTENSION</tt> maps to <tt>Warning</tt>, if
188they specify <tt>-pedantic-errors</tt>, it turns into <tt>Error</tt>. This is
189used to implement options like <tt>-Wunused_macros</tt>, <tt>-Wundef</tt> etc.
190</p>
191
192<p>
193Mapping to <tt>Fatal</tt> should only be used for diagnostics that are
194considered so severe that error recovery won't be able to recover sensibly from
195them (thus spewing a ton of bogus errors). One example of this class of error
196are failure to #include a file.
197</p>
Chris Lattner62fd2782008-11-22 21:41:31 +0000198
199<!-- ================= -->
200<h4>The Format String</h4>
201<!-- ================= -->
202
203<p>The format string for the diagnostic is very simple, but it has some power.
204It takes the form of a string in English with markers that indicate where and
205how arguments to the diagnostic are inserted and formatted. For example, here
206are some simple format strings:</p>
207
208<pre>
209 "binary integer literals are an extension"
210 "format string contains '\\0' within the string body"
211 "more '<b>%%</b>' conversions than data arguments"
Chris Lattner545b3682008-11-23 20:27:13 +0000212 "invalid operands to binary expression (<b>%0</b> and <b>%1</b>)"
Chris Lattner62fd2782008-11-22 21:41:31 +0000213 "overloaded '<b>%0</b>' must be a <b>%select{unary|binary|unary or binary}2</b> operator"
214 " (has <b>%1</b> parameter<b>%s1</b>)"
215</pre>
216
217<p>These examples show some important points of format strings. You can use any
218 plain ASCII character in the diagnostic string except "%" without a problem,
219 but these are C strings, so you have to use and be aware of all the C escape
220 sequences (as in the second example). If you want to produce a "%" in the
221 output, use the "%%" escape sequence, like the third diagnostic. Finally,
Chris Lattner552de0a2008-11-23 08:16:56 +0000222 Clang uses the "%...[digit]" sequences to specify where and how arguments to
Chris Lattner62fd2782008-11-22 21:41:31 +0000223 the diagnostic are formatted.</p>
224
225<p>Arguments to the diagnostic are numbered according to how they are specified
226 by the C++ code that <a href="#producingdiag">produces them</a>, and are
227 referenced by <tt>%0</tt> .. <tt>%9</tt>. If you have more than 10 arguments
Chris Lattner552de0a2008-11-23 08:16:56 +0000228 to your diagnostic, you are doing something wrong :). Unlike printf, there
Chris Lattner62fd2782008-11-22 21:41:31 +0000229 is no requirement that arguments to the diagnostic end up in the output in
230 the same order as they are specified, you could have a format string with
231 <tt>"%1 %0"</tt> that swaps them, for example. The text in between the
232 percent and digit are formatting instructions. If there are no instructions,
233 the argument is just turned into a string and substituted in.</p>
234
235<p>Here are some "best practices" for writing the English format string:</p>
236
237<ul>
238<li>Keep the string short. It should ideally fit in the 80 column limit of the
Chris Lattnercc2ac1e2011-02-14 06:42:50 +0000239 <tt>DiagnosticKinds.td</tt> file. This avoids the diagnostic wrapping when
Chris Lattner62fd2782008-11-22 21:41:31 +0000240 printed, and forces you to think about the important point you are conveying
241 with the diagnostic.</li>
242<li>Take advantage of location information. The user will be able to see the
243 line and location of the caret, so you don't need to tell them that the
244 problem is with the 4th argument to the function: just point to it.</li>
245<li>Do not capitalize the diagnostic string, and do not end it with a
246 period.</li>
247<li>If you need to quote something in the diagnostic string, use single
248 quotes.</li>
249</ul>
250
251<p>Diagnostics should never take random English strings as arguments: you
252shouldn't use <tt>"you have a problem with %0"</tt> and pass in things like
253<tt>"your argument"</tt> or <tt>"your return value"</tt> as arguments. Doing
Chris Lattnercc2ac1e2011-02-14 06:42:50 +0000254this prevents <a href="#translation">translating</a> the Clang diagnostics to
Chris Lattner62fd2782008-11-22 21:41:31 +0000255other languages (because they'll get random English words in their otherwise
256localized diagnostic). The exceptions to this are C/C++ language keywords
257(e.g. auto, const, mutable, etc) and C/C++ operators (<tt>/=</tt>). Note
258that things like "pointer" and "reference" are not keywords. On the other
259hand, you <em>can</em> include anything that comes from the user's source code,
Chris Lattner552de0a2008-11-23 08:16:56 +0000260including variable names, types, labels, etc. The 'select' format can be
261used to achieve this sort of thing in a localizable way, see below.</p>
Chris Lattner62fd2782008-11-22 21:41:31 +0000262
263<!-- ==================================== -->
Benjamin Kramer665a8dc2012-01-15 15:26:07 +0000264<h4>Formatting a Diagnostic Argument</h4>
Chris Lattner62fd2782008-11-22 21:41:31 +0000265<!-- ==================================== -->
266
267<p>Arguments to diagnostics are fully typed internally, and come from a couple
268different classes: integers, types, names, and random strings. Depending on
269the class of the argument, it can be optionally formatted in different ways.
270This gives the DiagnosticClient information about what the argument means
271without requiring it to use a specific presentation (consider this MVC for
272Clang :).</p>
273
274<p>Here are the different diagnostic argument formats currently supported by
275Clang:</p>
276
277<table>
278<tr><td colspan="2"><b>"s" format</b></td></tr>
279<tr><td>Example:</td><td><tt>"requires %1 parameter%s1"</tt></td></tr>
Chris Lattner552de0a2008-11-23 08:16:56 +0000280<tr><td>Class:</td><td>Integers</td></tr>
Chris Lattner62fd2782008-11-22 21:41:31 +0000281<tr><td>Description:</td><td>This is a simple formatter for integers that is
282 useful when producing English diagnostics. When the integer is 1, it prints
283 as nothing. When the integer is not 1, it prints as "s". This allows some
Chris Lattner627b7052008-11-23 00:28:33 +0000284 simple grammatical forms to be to be handled correctly, and eliminates the
285 need to use gross things like <tt>"requires %1 parameter(s)"</tt>.</td></tr>
Chris Lattner62fd2782008-11-22 21:41:31 +0000286
287<tr><td colspan="2"><b>"select" format</b></td></tr>
288<tr><td>Example:</td><td><tt>"must be a %select{unary|binary|unary or binary}2
289 operator"</tt></td></tr>
Chris Lattner552de0a2008-11-23 08:16:56 +0000290<tr><td>Class:</td><td>Integers</td></tr>
John McCall3a47e232010-01-14 19:12:17 +0000291<tr><td>Description:</td><td><p>This format specifier is used to merge multiple
Chris Lattnercc543342008-11-22 23:50:47 +0000292 related diagnostics together into one common one, without requiring the
Chris Lattner552de0a2008-11-23 08:16:56 +0000293 difference to be specified as an English string argument. Instead of
Chris Lattnercc543342008-11-22 23:50:47 +0000294 specifying the string, the diagnostic gets an integer argument and the
295 format string selects the numbered option. In this case, the "%2" value
296 must be an integer in the range [0..2]. If it is 0, it prints 'unary', if
297 it is 1 it prints 'binary' if it is 2, it prints 'unary or binary'. This
298 allows other language translations to substitute reasonable words (or entire
299 phrases) based on the semantics of the diagnostic instead of having to do
John McCall3a47e232010-01-14 19:12:17 +0000300 things textually.</p>
301 <p>The selected string does undergo formatting.</p></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
John McCall3a47e232010-01-14 19:12:17 +0000333<tr><td colspan="2"><b>"ordinal" format</b></td></tr>
334<tr><td>Example:</td><td><tt>"ambiguity in %ordinal0 argument"</tt></td></tr>
335<tr><td>Class:</td><td>Integers</td></tr>
336<tr><td>Description:</td><td><p>This is a formatter which represents the
337 argument number as an ordinal: the value <tt>1</tt> becomes <tt>1st</tt>,
338 <tt>3</tt> becomes <tt>3rd</tt>, and so on. Values less than <tt>1</tt>
339 are not supported.</p>
340 <p>This formatter is currently hard-coded to use English ordinals.</p></td></tr>
341
Chris Lattner077bf5e2008-11-24 03:33:13 +0000342<tr><td colspan="2"><b>"objcclass" format</b></td></tr>
343<tr><td>Example:</td><td><tt>"method %objcclass0 not found"</tt></td></tr>
344<tr><td>Class:</td><td>DeclarationName</td></tr>
345<tr><td>Description:</td><td><p>This is a simple formatter that indicates the
346 DeclarationName corresponds to an Objective-C class method selector. As
347 such, it prints the selector with a leading '+'.</p></td></tr>
348
349<tr><td colspan="2"><b>"objcinstance" format</b></td></tr>
350<tr><td>Example:</td><td><tt>"method %objcinstance0 not found"</tt></td></tr>
351<tr><td>Class:</td><td>DeclarationName</td></tr>
352<tr><td>Description:</td><td><p>This is a simple formatter that indicates the
353 DeclarationName corresponds to an Objective-C instance method selector. As
354 such, it prints the selector with a leading '-'.</p></td></tr>
355
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000356<tr><td colspan="2"><b>"q" format</b></td></tr>
357<tr><td>Example:</td><td><tt>"candidate found by name lookup is %q0"</tt></td></tr>
358<tr><td>Class:</td><td>NamedDecl*</td></tr>
359<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>
Richard Trieue59331a2012-06-27 02:00:20 +0000360
361<tr><td colspan="2"><b>"diff" format</b></td></tr>
362<tr><td>Example:</td><td><tt>"no known conversion %diff{from | to | }1,2"</tt></td></tr>
363<tr><td>Class:</td><td>QualType</td></tr>
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +0000364<tr><td>Description</td><td><p>This formatter takes two QualTypes and attempts to print a template difference between the two. If tree printing is off, the text inside the braces before the pipe is printed, with the formatted text replacing the $. If tree printing is on, the text after the pipe is printed and a type tree is printed after the diagnostic message.
Richard Trieu529cdf42012-06-29 21:12:16 +0000365</p></td></tr>
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000366
Chris Lattner62fd2782008-11-22 21:41:31 +0000367</table>
368
Chris Lattnercc543342008-11-22 23:50:47 +0000369<p>It is really easy to add format specifiers to the Clang diagnostics system,
Chris Lattner552de0a2008-11-23 08:16:56 +0000370but they should be discussed before they are added. If you are creating a lot
371of repetitive diagnostics and/or have an idea for a useful formatter, please
372bring it up on the cfe-dev mailing list.</p>
Chris Lattnercc543342008-11-22 23:50:47 +0000373
Chris Lattner62fd2782008-11-22 21:41:31 +0000374<!-- ===================================================== -->
Chris Lattnercc2ac1e2011-02-14 06:42:50 +0000375<h4 id="producingdiag">Producing the Diagnostic</h4>
Chris Lattner62fd2782008-11-22 21:41:31 +0000376<!-- ===================================================== -->
377
Chris Lattnercc2ac1e2011-02-14 06:42:50 +0000378<p>Now that you've created the diagnostic in the DiagnosticKinds.td file, you
Chris Lattner552de0a2008-11-23 08:16:56 +0000379need to write the code that detects the condition in question and emits the
380new diagnostic. Various components of Clang (e.g. the preprocessor, Sema,
Chris Lattner627b7052008-11-23 00:28:33 +0000381etc) provide a helper function named "Diag". It creates a diagnostic and
382accepts the arguments, ranges, and other information that goes along with
383it.</p>
Chris Lattner62fd2782008-11-22 21:41:31 +0000384
Chris Lattner552de0a2008-11-23 08:16:56 +0000385<p>For example, the binary expression error comes from code like this:</p>
Chris Lattner627b7052008-11-23 00:28:33 +0000386
387<pre>
388 if (various things that are bad)
389 Diag(Loc, diag::err_typecheck_invalid_operands)
390 &lt;&lt; lex-&gt;getType() &lt;&lt; rex-&gt;getType()
391 &lt;&lt; lex-&gt;getSourceRange() &lt;&lt; rex-&gt;getSourceRange();
392</pre>
393
394<p>This shows that use of the Diag method: they take a location (a <a
395href="#SourceLocation">SourceLocation</a> object) and a diagnostic enum value
Chris Lattnercc2ac1e2011-02-14 06:42:50 +0000396(which matches the name from DiagnosticKinds.td). If the diagnostic takes
Chris Lattner627b7052008-11-23 00:28:33 +0000397arguments, they are specified with the &lt;&lt; operator: the first argument
398becomes %0, the second becomes %1, etc. The diagnostic interface allows you to
Chris Lattnerfd408ea2008-11-23 00:42:53 +0000399specify arguments of many different types, including <tt>int</tt> and
400<tt>unsigned</tt> for integer arguments, <tt>const char*</tt> and
401<tt>std::string</tt> for string arguments, <tt>DeclarationName</tt> and
402<tt>const IdentifierInfo*</tt> for names, <tt>QualType</tt> for types, etc.
403SourceRanges are also specified with the &lt;&lt; operator, but do not have a
404specific ordering requirement.</p>
Chris Lattner627b7052008-11-23 00:28:33 +0000405
406<p>As you can see, adding and producing a diagnostic is pretty straightforward.
407The hard part is deciding exactly what you need to say to help the user, picking
408a suitable wording, and providing the information needed to format it correctly.
Chris Lattnerfd408ea2008-11-23 00:42:53 +0000409The good news is that the call site that issues a diagnostic should be
410completely independent of how the diagnostic is formatted and in what language
411it is rendered.
Chris Lattner627b7052008-11-23 00:28:33 +0000412</p>
Chris Lattner62fd2782008-11-22 21:41:31 +0000413
Douglas Gregorb2fb6de2009-02-27 17:53:17 +0000414<!-- ==================================================== -->
Peter Collingbourne38448d32011-03-21 01:45:18 +0000415<h4 id="fix-it-hints">Fix-It Hints</h4>
Douglas Gregorb2fb6de2009-02-27 17:53:17 +0000416<!-- ==================================================== -->
417
418<p>In some cases, the front end emits diagnostics when it is clear
419that some small change to the source code would fix the problem. For
420example, a missing semicolon at the end of a statement or a use of
Chris Lattner34c05332009-02-27 19:31:12 +0000421deprecated syntax that is easily rewritten into a more modern form.
422Clang tries very hard to emit the diagnostic and recover gracefully
423in these and other cases.</p>
Douglas Gregorb2fb6de2009-02-27 17:53:17 +0000424
Peter Collingbourne38448d32011-03-21 01:45:18 +0000425<p>However, for these cases where the fix is obvious, the diagnostic
426can be annotated with a hint (referred to as a "fix-it hint") that
427describes how to change the code referenced by the diagnostic to fix
428the problem. For example, it might add the missing semicolon at the
429end of the statement or rewrite the use of a deprecated construct
430into something more palatable. Here is one such example from the C++
431front end, where we warn about the right-shift operator changing
David Blaikie5090e9f2011-10-18 05:49:30 +0000432meaning from C++98 to C++11:</p>
Douglas Gregorb2fb6de2009-02-27 17:53:17 +0000433
434<pre>
David Blaikie5090e9f2011-10-18 05:49:30 +0000435test.cpp:3:7: warning: use of right-shift operator ('&gt;&gt;') in template argument will require parentheses in C++11
Douglas Gregorb2fb6de2009-02-27 17:53:17 +0000436A&lt;100 &gt;&gt; 2&gt; *a;
437 ^
438 ( )
439</pre>
440
Peter Collingbourne38448d32011-03-21 01:45:18 +0000441<p>Here, the fix-it hint is suggesting that parentheses be added,
442and showing exactly where those parentheses would be inserted into the
443source code. The fix-it hints themselves describe what changes to make
444to the source code in an abstract manner, which the text diagnostic
445printer renders as a line of "insertions" below the caret line. <a
446href="#DiagnosticClient">Other diagnostic clients</a> might choose
447to render the code differently (e.g., as markup inline) or even give
448the user the ability to automatically fix the problem.</p>
Douglas Gregorb2fb6de2009-02-27 17:53:17 +0000449
Nico Weber80039632012-06-04 21:56:14 +0000450<p>Fix-it hints on errors and warnings need to obey these rules:</p>
451
452<ul>
453<li>Since they are automatically applied if <code>-Xclang -fixit</code>
454is passed to the driver, they should only be used when it's very likely they
455match the user's intent.</li>
Chris Lattnerf6385a52012-07-10 05:03:05 +0000456<li>Clang must recover from errors as if the fix-it had been applied.</li>
Nico Weber80039632012-06-04 21:56:14 +0000457</ul>
458
459<p>If a fix-it can't obey these rules, put the fix-it on a note. Fix-its on
460notes are not applied automatically.</p>
461
Peter Collingbourne38448d32011-03-21 01:45:18 +0000462<p>All fix-it hints are described by the <code>FixItHint</code> class,
463instances of which should be attached to the diagnostic using the
464&lt;&lt; operator in the same way that highlighted source ranges and
465arguments are passed to the diagnostic. Fix-it hints can be created
466with one of three constructors:</p>
Douglas Gregorb2fb6de2009-02-27 17:53:17 +0000467
468<dl>
Peter Collingbourne38448d32011-03-21 01:45:18 +0000469 <dt><code>FixItHint::CreateInsertion(Loc, Code)</code></dt>
Douglas Gregorb2fb6de2009-02-27 17:53:17 +0000470 <dd>Specifies that the given <code>Code</code> (a string) should be inserted
471 before the source location <code>Loc</code>.</dd>
472
Peter Collingbourne38448d32011-03-21 01:45:18 +0000473 <dt><code>FixItHint::CreateRemoval(Range)</code></dt>
Douglas Gregorb2fb6de2009-02-27 17:53:17 +0000474 <dd>Specifies that the code in the given source <code>Range</code>
475 should be removed.</dd>
476
Peter Collingbourne38448d32011-03-21 01:45:18 +0000477 <dt><code>FixItHint::CreateReplacement(Range, Code)</code></dt>
Douglas Gregorb2fb6de2009-02-27 17:53:17 +0000478 <dd>Specifies that the code in the given source <code>Range</code>
479 should be removed, and replaced with the given <code>Code</code> string.</dd>
480</dl>
481
Chris Lattner62fd2782008-11-22 21:41:31 +0000482<!-- ============================================================= -->
483<h4><a name="DiagnosticClient">The DiagnosticClient Interface</a></h4>
484<!-- ============================================================= -->
485
Chris Lattner627b7052008-11-23 00:28:33 +0000486<p>Once code generates a diagnostic with all of the arguments and the rest of
487the relevant information, Clang needs to know what to do with it. As previously
488mentioned, the diagnostic machinery goes through some filtering to map a
489severity onto a diagnostic level, then (assuming the diagnostic is not mapped to
490"<tt>Ignore</tt>") it invokes an object that implements the DiagnosticClient
491interface with the information.</p>
492
493<p>It is possible to implement this interface in many different ways. For
494example, the normal Clang DiagnosticClient (named 'TextDiagnosticPrinter') turns
495the arguments into strings (according to the various formatting rules), prints
496out the file/line/column information and the string, then prints out the line of
497code, the source ranges, and the caret. However, this behavior isn't required.
498</p>
499
500<p>Another implementation of the DiagnosticClient interface is the
Chris Lattner552de0a2008-11-23 08:16:56 +0000501'TextDiagnosticBuffer' class, which is used when Clang is in -verify mode.
Chris Lattnerfd408ea2008-11-23 00:42:53 +0000502Instead of formatting and printing out the diagnostics, this implementation just
503captures and remembers the diagnostics as they fly by. Then -verify compares
Chris Lattner552de0a2008-11-23 08:16:56 +0000504the list of produced diagnostics to the list of expected ones. If they disagree,
Andy Gibbs266dba32012-10-19 12:49:32 +0000505it prints out its own output. Full documentation for the -verify mode can be
506found in the Clang API documentation for VerifyDiagnosticConsumer, <a
507href="/doxygen/classclang_1_1VerifyDiagnosticConsumer.html#details">here</a>.
Chris Lattner627b7052008-11-23 00:28:33 +0000508</p>
509
Chris Lattnerfd408ea2008-11-23 00:42:53 +0000510<p>There are many other possible implementations of this interface, and this is
511why we prefer diagnostics to pass down rich structured information in arguments.
512For example, an HTML output might want declaration names be linkified to where
513they come from in the source. Another example is that a GUI might let you click
514on typedefs to expand them. This application would want to pass significantly
515more information about types through to the GUI than a simple flat string. The
516interface allows this to happen.</p>
Chris Lattner62fd2782008-11-22 21:41:31 +0000517
518<!-- ====================================================== -->
519<h4><a name="translation">Adding Translations to Clang</a></h4>
520<!-- ====================================================== -->
521
Chris Lattner627b7052008-11-23 00:28:33 +0000522<p>Not possible yet! Diagnostic strings should be written in UTF-8, the client
Chris Lattnerfd408ea2008-11-23 00:42:53 +0000523can translate to the relevant code page if needed. Each translation completely
524replaces the format string for the diagnostic.</p>
Chris Lattner62fd2782008-11-22 21:41:31 +0000525
526
Chris Lattner86920d32007-07-31 05:42:17 +0000527<!-- ======================================================================= -->
528<h3 id="SourceLocation">The SourceLocation and SourceManager classes</h3>
529<!-- ======================================================================= -->
530
531<p>Strangely enough, the SourceLocation class represents a location within the
532source code of the program. Important design points include:</p>
533
534<ol>
535<li>sizeof(SourceLocation) must be extremely small, as these are embedded into
536 many AST nodes and are passed around often. Currently it is 32 bits.</li>
537<li>SourceLocation must be a simple value object that can be efficiently
538 copied.</li>
539<li>We should be able to represent a source location for any byte of any input
540 file. This includes in the middle of tokens, in whitespace, in trigraphs,
541 etc.</li>
542<li>A SourceLocation must encode the current #include stack that was active when
543 the location was processed. For example, if the location corresponds to a
544 token, it should contain the set of #includes active when the token was
545 lexed. This allows us to print the #include stack for a diagnostic.</li>
546<li>SourceLocation must be able to describe macro expansions, capturing both
547 the ultimate instantiation point and the source of the original character
548 data.</li>
549</ol>
550
551<p>In practice, the SourceLocation works together with the SourceManager class
Nick Lewycky77561e52010-05-26 21:48:10 +0000552to encode two pieces of information about a location: its spelling location
553and its instantiation location. For most tokens, these will be the same.
554However, for a macro expansion (or tokens that came from a _Pragma directive)
555these will describe the location of the characters corresponding to the token
556and the location where the token was used (i.e. the macro instantiation point
557or the location of the _Pragma itself).</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000558
Chris Lattner552de0a2008-11-23 08:16:56 +0000559<p>The Clang front-end inherently depends on the location of a token being
Chris Lattner86920d32007-07-31 05:42:17 +0000560tracked correctly. If it is ever incorrect, the front-end may get confused and
561die. The reason for this is that the notion of the 'spelling' of a Token in
Chris Lattner552de0a2008-11-23 08:16:56 +0000562Clang depends on being able to find the original input characters for the token.
Chris Lattner18376dd2009-01-16 07:00:50 +0000563This concept maps directly to the "spelling location" for the token.</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000564
Douglas Gregor715c92a2010-10-27 16:02:28 +0000565
566<!-- ======================================================================= -->
567<h3 id="SourceRange">SourceRange and CharSourceRange</h3>
568<!-- ======================================================================= -->
569<!-- mostly taken from
570 http://lists.cs.uiuc.edu/pipermail/cfe-dev/2010-August/010595.html -->
571
572<p>Clang represents most source ranges by [first, last], where first and last
573each point to the beginning of their respective tokens. For example
574consider the SourceRange of the following statement:</p>
575<pre>
576x = foo + bar;
577^first ^last
578</pre>
579
580<p>To map from this representation to a character-based
581representation, the 'last' location needs to be adjusted to point to
582(or past) the end of that token with either
583<code>Lexer::MeasureTokenLength()</code> or
Chris Lattner7ef5c272010-11-17 07:05:50 +0000584<code>Lexer::getLocForEndOfToken()</code>. For the rare cases
Douglas Gregor715c92a2010-10-27 16:02:28 +0000585where character-level source ranges information is needed we use
586the <code>CharSourceRange</code> class.</p>
587
588
Chris Lattner86920d32007-07-31 05:42:17 +0000589<!-- ======================================================================= -->
Daniel Dunbar27d9e9f2009-03-30 06:50:01 +0000590<h2 id="libdriver">The Driver Library</h2>
591<!-- ======================================================================= -->
592
Ted Kremenekcfa8d572009-04-09 18:08:18 +0000593<p>The clang Driver and library are documented <a
Benjamin Kramer665a8dc2012-01-15 15:26:07 +0000594href="DriverInternals.html">here</a>.<p>
Ted Kremenekcfa8d572009-04-09 18:08:18 +0000595
596<!-- ======================================================================= -->
Douglas Gregor32110df2009-05-20 00:16:32 +0000597<h2 id="pch">Precompiled Headers</h2>
Ted Kremenekcfa8d572009-04-09 18:08:18 +0000598<!-- ======================================================================= -->
599
Douglas Gregor32110df2009-05-20 00:16:32 +0000600<p>Clang supports two implementations of precompiled headers. The
601 default implementation, precompiled headers (<a
602 href="PCHInternals.html">PCH</a>) uses a serialized representation
603 of Clang's internal data structures, encoded with the <a
604 href="http://llvm.org/docs/BitCodeFormat.html">LLVM bitstream
605 format</a>. Pretokenized headers (<a
606 href="PTHInternals.html">PTH</a>), on the other hand, contain a
607 serialized representation of the tokens encountered when
608 preprocessing a header (and anything that header includes).</p>
609
Daniel Dunbar27d9e9f2009-03-30 06:50:01 +0000610
611<!-- ======================================================================= -->
612<h2 id="libfrontend">The Frontend Library</h2>
613<!-- ======================================================================= -->
614
615<p>The Frontend library contains functionality useful for building
616tools on top of the clang libraries, for example several methods for
617outputting diagnostics.</p>
618
619<!-- ======================================================================= -->
Chris Lattner86920d32007-07-31 05:42:17 +0000620<h2 id="liblex">The Lexer and Preprocessor Library</h2>
621<!-- ======================================================================= -->
622
623<p>The Lexer library contains several tightly-connected classes that are involved
624with the nasty process of lexing and preprocessing C source code. The main
625interface to this library for outside clients is the large <a
626href="#Preprocessor">Preprocessor</a> class.
627It contains the various pieces of state that are required to coherently read
628tokens out of a translation unit.</p>
629
630<p>The core interface to the Preprocessor object (once it is set up) is the
631Preprocessor::Lex method, which returns the next <a href="#Token">Token</a> from
632the preprocessor stream. There are two types of token providers that the
633preprocessor is capable of reading from: a buffer lexer (provided by the <a
634href="#Lexer">Lexer</a> class) and a buffered token stream (provided by the <a
Chris Lattner79281252008-03-09 02:27:26 +0000635href="#TokenLexer">TokenLexer</a> class).
Chris Lattner86920d32007-07-31 05:42:17 +0000636
637
638<!-- ======================================================================= -->
639<h3 id="Token">The Token class</h3>
640<!-- ======================================================================= -->
641
642<p>The Token class is used to represent a single lexed token. Tokens are
643intended to be used by the lexer/preprocess and parser libraries, but are not
644intended to live beyond them (for example, they should not live in the ASTs).<p>
645
646<p>Tokens most often live on the stack (or some other location that is efficient
647to access) as the parser is running, but occasionally do get buffered up. For
648example, macro definitions are stored as a series of tokens, and the C++
Chris Lattner3fcbb892008-11-23 08:32:53 +0000649front-end periodically needs to buffer tokens up for tentative parsing and
Chris Lattner86920d32007-07-31 05:42:17 +0000650various pieces of look-ahead. As such, the size of a Token matter. On a 32-bit
651system, sizeof(Token) is currently 16 bytes.</p>
652
Chris Lattner3932fe02009-01-06 06:02:08 +0000653<p>Tokens occur in two forms: "<a href="#AnnotationToken">Annotation
654Tokens</a>" and normal tokens. Normal tokens are those returned by the lexer,
655annotation tokens represent semantic information and are produced by the parser,
656replacing normal tokens in the token stream. Normal tokens contain the
657following information:</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000658
659<ul>
660<li><b>A SourceLocation</b> - This indicates the location of the start of the
661token.</li>
662
663<li><b>A length</b> - This stores the length of the token as stored in the
664SourceBuffer. For tokens that include them, this length includes trigraphs and
665escaped newlines which are ignored by later phases of the compiler. By pointing
666into the original source buffer, it is always possible to get the original
667spelling of a token completely accurately.</li>
668
669<li><b>IdentifierInfo</b> - If a token takes the form of an identifier, and if
670identifier lookup was enabled when the token was lexed (e.g. the lexer was not
671reading in 'raw' mode) this contains a pointer to the unique hash value for the
672identifier. Because the lookup happens before keyword identification, this
673field is set even for language keywords like 'for'.</li>
674
675<li><b>TokenKind</b> - This indicates the kind of token as classified by the
676lexer. This includes things like <tt>tok::starequal</tt> (for the "*="
677operator), <tt>tok::ampamp</tt> for the "&amp;&amp;" token, and keyword values
678(e.g. <tt>tok::kw_for</tt>) for identifiers that correspond to keywords. Note
679that some tokens can be spelled multiple ways. For example, C++ supports
680"operator keywords", where things like "and" are treated exactly like the
681"&amp;&amp;" operator. In these cases, the kind value is set to
682<tt>tok::ampamp</tt>, which is good for the parser, which doesn't have to
683consider both forms. For something that cares about which form is used (e.g.
684the preprocessor 'stringize' operator) the spelling indicates the original
685form.</li>
686
687<li><b>Flags</b> - There are currently four flags tracked by the
688lexer/preprocessor system on a per-token basis:
689
690 <ol>
691 <li><b>StartOfLine</b> - This was the first token that occurred on its input
692 source line.</li>
693 <li><b>LeadingSpace</b> - There was a space character either immediately
694 before the token or transitively before the token as it was expanded
695 through a macro. The definition of this flag is very closely defined by
696 the stringizing requirements of the preprocessor.</li>
697 <li><b>DisableExpand</b> - This flag is used internally to the preprocessor to
698 represent identifier tokens which have macro expansion disabled. This
699 prevents them from being considered as candidates for macro expansion ever
700 in the future.</li>
701 <li><b>NeedsCleaning</b> - This flag is set if the original spelling for the
702 token includes a trigraph or escaped newline. Since this is uncommon,
703 many pieces of code can fast-path on tokens that did not need cleaning.
Chris Lattner86920d32007-07-31 05:42:17 +0000704 </ol>
705</li>
706</ul>
707
Chris Lattner3932fe02009-01-06 06:02:08 +0000708<p>One interesting (and somewhat unusual) aspect of normal tokens is that they
709don't contain any semantic information about the lexed value. For example, if
710the token was a pp-number token, we do not represent the value of the number
711that was lexed (this is left for later pieces of code to decide). Additionally,
712the lexer library has no notion of typedef names vs variable names: both are
Chris Lattner86920d32007-07-31 05:42:17 +0000713returned as identifiers, and the parser is left to decide whether a specific
714identifier is a typedef or a variable (tracking this requires scope information
Chris Lattner3932fe02009-01-06 06:02:08 +0000715among other things). The parser can do this translation by replacing tokens
716returned by the preprocessor with "Annotation Tokens".</p>
717
718<!-- ======================================================================= -->
719<h3 id="AnnotationToken">Annotation Tokens</h3>
720<!-- ======================================================================= -->
721
722<p>Annotation Tokens are tokens that are synthesized by the parser and injected
723into the preprocessor's token stream (replacing existing tokens) to record
724semantic information found by the parser. For example, if "foo" is found to be
725a typedef, the "foo" <tt>tok::identifier</tt> token is replaced with an
726<tt>tok::annot_typename</tt>. This is useful for a couple of reasons: 1) this
727makes it easy to handle qualified type names (e.g. "foo::bar::baz&lt;42&gt;::t")
728in C++ as a single "token" in the parser. 2) if the parser backtracks, the
729reparse does not need to redo semantic analysis to determine whether a token
730sequence is a variable, type, template, etc.</p>
731
732<p>Annotation Tokens are created by the parser and reinjected into the parser's
733token stream (when backtracking is enabled). Because they can only exist in
734tokens that the preprocessor-proper is done with, it doesn't need to keep around
735flags like "start of line" that the preprocessor uses to do its job.
736Additionally, an annotation token may "cover" a sequence of preprocessor tokens
737(e.g. <tt>a::b::c</tt> is five preprocessor tokens). As such, the valid fields
738of an annotation token are different than the fields for a normal token (but
739they are multiplexed into the normal Token fields):</p>
740
741<ul>
742<li><b>SourceLocation "Location"</b> - The SourceLocation for the annotation
743token indicates the first token replaced by the annotation token. In the example
744above, it would be the location of the "a" identifier.</li>
745
746<li><b>SourceLocation "AnnotationEndLoc"</b> - This holds the location of the
747last token replaced with the annotation token. In the example above, it would
748be the location of the "c" identifier.</li>
749
John McCall027ac442010-09-03 05:07:55 +0000750<li><b>void* "AnnotationValue"</b> - This contains an opaque object
751that the parser gets from Sema. The parser merely preserves the
752information for Sema to later interpret based on the annotation token
753kind.</li>
Chris Lattner3932fe02009-01-06 06:02:08 +0000754
755<li><b>TokenKind "Kind"</b> - This indicates the kind of Annotation token this
756is. See below for the different valid kinds.</li>
757</ul>
758
759<p>Annotation tokens currently come in three kinds:</p>
760
761<ol>
762<li><b>tok::annot_typename</b>: This annotation token represents a
John McCall027ac442010-09-03 05:07:55 +0000763resolved typename token that is potentially qualified. The
764AnnotationValue field contains the <tt>QualType</tt> returned by
765Sema::getTypeName(), possibly with source location information
766attached.</li>
Chris Lattner3932fe02009-01-06 06:02:08 +0000767
John McCall027ac442010-09-03 05:07:55 +0000768<li><b>tok::annot_cxxscope</b>: This annotation token represents a C++
769scope specifier, such as "A::B::". This corresponds to the grammar
770productions "::" and ":: [opt] nested-name-specifier". The
771AnnotationValue pointer is a <tt>NestedNameSpecifier*</tt> returned by
772the Sema::ActOnCXXGlobalScopeSpecifier and
773Sema::ActOnCXXNestedNameSpecifier callbacks.</li>
Chris Lattner3932fe02009-01-06 06:02:08 +0000774
Douglas Gregor39a8de12009-02-25 19:37:18 +0000775<li><b>tok::annot_template_id</b>: This annotation token represents a
776C++ template-id such as "foo&lt;int, 4&gt;", where "foo" is the name
777of a template. The AnnotationValue pointer is a pointer to a malloc'd
John McCall027ac442010-09-03 05:07:55 +0000778TemplateIdAnnotation object. Depending on the context, a parsed
779template-id that names a type might become a typename annotation token
780(if all we care about is the named type, e.g., because it occurs in a
781type specifier) or might remain a template-id token (if we want to
782retain more source location information or produce a new type, e.g.,
783in a declaration of a class template specialization). template-id
784annotation tokens that refer to a type can be "upgraded" to typename
785annotation tokens by the parser.</li>
Chris Lattner3932fe02009-01-06 06:02:08 +0000786
787</ol>
788
Cedric Venetda76b282009-01-06 16:22:54 +0000789<p>As mentioned above, annotation tokens are not returned by the preprocessor,
Chris Lattner3932fe02009-01-06 06:02:08 +0000790they are formed on demand by the parser. This means that the parser has to be
791aware of cases where an annotation could occur and form it where appropriate.
792This is somewhat similar to how the parser handles Translation Phase 6 of C99:
793String Concatenation (see C99 5.1.1.2). In the case of string concatenation,
794the preprocessor just returns distinct tok::string_literal and
795tok::wide_string_literal tokens and the parser eats a sequence of them wherever
796the grammar indicates that a string literal can occur.</p>
797
798<p>In order to do this, whenever the parser expects a tok::identifier or
799tok::coloncolon, it should call the TryAnnotateTypeOrScopeToken or
800TryAnnotateCXXScopeToken methods to form the annotation token. These methods
801will maximally form the specified annotation tokens and replace the current
802token with them, if applicable. If the current tokens is not valid for an
803annotation token, it will remain an identifier or :: token.</p>
804
805
Chris Lattner86920d32007-07-31 05:42:17 +0000806
807<!-- ======================================================================= -->
808<h3 id="Lexer">The Lexer class</h3>
809<!-- ======================================================================= -->
810
811<p>The Lexer class provides the mechanics of lexing tokens out of a source
812buffer and deciding what they mean. The Lexer is complicated by the fact that
813it operates on raw buffers that have not had spelling eliminated (this is a
814necessity to get decent performance), but this is countered with careful coding
815as well as standard performance techniques (for example, the comment handling
816code is vectorized on X86 and PowerPC hosts).</p>
817
818<p>The lexer has a couple of interesting modal features:</p>
819
820<ul>
821<li>The lexer can operate in 'raw' mode. This mode has several features that
822 make it possible to quickly lex the file (e.g. it stops identifier lookup,
823 doesn't specially handle preprocessor tokens, handles EOF differently, etc).
824 This mode is used for lexing within an "<tt>#if 0</tt>" block, for
825 example.</li>
826<li>The lexer can capture and return comments as tokens. This is required to
827 support the -C preprocessor mode, which passes comments through, and is
828 used by the diagnostic checker to identifier expect-error annotations.</li>
829<li>The lexer can be in ParsingFilename mode, which happens when preprocessing
Chris Lattner84386242007-09-16 19:25:23 +0000830 after reading a #include directive. This mode changes the parsing of '&lt;'
Chris Lattner86920d32007-07-31 05:42:17 +0000831 to return an "angled string" instead of a bunch of tokens for each thing
832 within the filename.</li>
833<li>When parsing a preprocessor directive (after "<tt>#</tt>") the
834 ParsingPreprocessorDirective mode is entered. This changes the parser to
Peter Collingbourne84021552011-02-28 02:37:51 +0000835 return EOD at a newline.</li>
Chris Lattner86920d32007-07-31 05:42:17 +0000836<li>The Lexer uses a LangOptions object to know whether trigraphs are enabled,
837 whether C++ or ObjC keywords are recognized, etc.</li>
838</ul>
839
840<p>In addition to these modes, the lexer keeps track of a couple of other
841 features that are local to a lexed buffer, which change as the buffer is
842 lexed:</p>
843
844<ul>
845<li>The Lexer uses BufferPtr to keep track of the current character being
846 lexed.</li>
847<li>The Lexer uses IsAtStartOfLine to keep track of whether the next lexed token
848 will start with its "start of line" bit set.</li>
849<li>The Lexer keeps track of the current #if directives that are active (which
850 can be nested).</li>
851<li>The Lexer keeps track of an <a href="#MultipleIncludeOpt">
852 MultipleIncludeOpt</a> object, which is used to
853 detect whether the buffer uses the standard "<tt>#ifndef XX</tt> /
854 <tt>#define XX</tt>" idiom to prevent multiple inclusion. If a buffer does,
855 subsequent includes can be ignored if the XX macro is defined.</li>
856</ul>
857
858<!-- ======================================================================= -->
Chris Lattner79281252008-03-09 02:27:26 +0000859<h3 id="TokenLexer">The TokenLexer class</h3>
Chris Lattner86920d32007-07-31 05:42:17 +0000860<!-- ======================================================================= -->
861
Chris Lattner79281252008-03-09 02:27:26 +0000862<p>The TokenLexer class is a token provider that returns tokens from a list
Chris Lattner86920d32007-07-31 05:42:17 +0000863of tokens that came from somewhere else. It typically used for two things: 1)
864returning tokens from a macro definition as it is being expanded 2) returning
865tokens from an arbitrary buffer of tokens. The later use is used by _Pragma and
866will most likely be used to handle unbounded look-ahead for the C++ parser.</p>
867
868<!-- ======================================================================= -->
869<h3 id="MultipleIncludeOpt">The MultipleIncludeOpt class</h3>
870<!-- ======================================================================= -->
871
872<p>The MultipleIncludeOpt class implements a really simple little state machine
873that is used to detect the standard "<tt>#ifndef XX</tt> / <tt>#define XX</tt>"
874idiom that people typically use to prevent multiple inclusion of headers. If a
875buffer uses this idiom and is subsequently #include'd, the preprocessor can
876simply check to see whether the guarding condition is defined or not. If so,
877the preprocessor can completely ignore the include of the header.</p>
878
879
880
881<!-- ======================================================================= -->
882<h2 id="libparse">The Parser Library</h2>
883<!-- ======================================================================= -->
884
885<!-- ======================================================================= -->
886<h2 id="libast">The AST Library</h2>
887<!-- ======================================================================= -->
888
889<!-- ======================================================================= -->
890<h3 id="Type">The Type class and its subclasses</h3>
891<!-- ======================================================================= -->
892
893<p>The Type class (and its subclasses) are an important part of the AST. Types
894are accessed through the ASTContext class, which implicitly creates and uniques
895them as they are needed. Types have a couple of non-obvious features: 1) they
896do not capture type qualifiers like const or volatile (See
897<a href="#QualType">QualType</a>), and 2) they implicitly capture typedef
Chris Lattner8a2bc622007-07-31 06:37:39 +0000898information. Once created, types are immutable (unlike decls).</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000899
900<p>Typedefs in C make semantic analysis a bit more complex than it would
901be without them. The issue is that we want to capture typedef information
902and represent it in the AST perfectly, but the semantics of operations need to
903"see through" typedefs. For example, consider this code:</p>
904
905<code>
906void func() {<br>
Bill Wendling30d17752007-10-06 01:56:01 +0000907&nbsp;&nbsp;typedef int foo;<br>
908&nbsp;&nbsp;foo X, *Y;<br>
909&nbsp;&nbsp;typedef foo* bar;<br>
910&nbsp;&nbsp;bar Z;<br>
911&nbsp;&nbsp;*X; <i>// error</i><br>
912&nbsp;&nbsp;**Y; <i>// error</i><br>
913&nbsp;&nbsp;**Z; <i>// error</i><br>
Chris Lattner86920d32007-07-31 05:42:17 +0000914}<br>
915</code>
916
917<p>The code above is illegal, and thus we expect there to be diagnostics emitted
918on the annotated lines. In this example, we expect to get:</p>
919
920<pre>
Chris Lattner8a2bc622007-07-31 06:37:39 +0000921<b>test.c:6:1: error: indirection requires pointer operand ('foo' invalid)</b>
Chris Lattner86920d32007-07-31 05:42:17 +0000922*X; // error
Benjamin Kramer665a8dc2012-01-15 15:26:07 +0000923<span style="color:blue">^~</span>
Chris Lattner8a2bc622007-07-31 06:37:39 +0000924<b>test.c:7:1: error: indirection requires pointer operand ('foo' invalid)</b>
Chris Lattner86920d32007-07-31 05:42:17 +0000925**Y; // error
Benjamin Kramer665a8dc2012-01-15 15:26:07 +0000926<span style="color:blue">^~~</span>
Chris Lattner8a2bc622007-07-31 06:37:39 +0000927<b>test.c:8:1: error: indirection requires pointer operand ('foo' invalid)</b>
928**Z; // error
Benjamin Kramer665a8dc2012-01-15 15:26:07 +0000929<span style="color:blue">^~~</span>
Chris Lattner86920d32007-07-31 05:42:17 +0000930</pre>
931
932<p>While this example is somewhat silly, it illustrates the point: we want to
933retain typedef information where possible, so that we can emit errors about
934"<tt>std::string</tt>" instead of "<tt>std::basic_string&lt;char, std:...</tt>".
935Doing this requires properly keeping typedef information (for example, the type
936of "X" is "foo", not "int"), and requires properly propagating it through the
Chris Lattner8a2bc622007-07-31 06:37:39 +0000937various operators (for example, the type of *Y is "foo", not "int"). In order
938to retain this information, the type of these expressions is an instance of the
939TypedefType class, which indicates that the type of these expressions is a
940typedef for foo.
941</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000942
Chris Lattner8a2bc622007-07-31 06:37:39 +0000943<p>Representing types like this is great for diagnostics, because the
944user-specified type is always immediately available. There are two problems
945with this: first, various semantic checks need to make judgements about the
Douglas Gregor2d1e21a2011-12-19 19:50:23 +0000946<em>actual structure</em> of a type, ignoring typedefs. Second, we need an
Chris Lattner33fc68a2007-07-31 18:54:50 +0000947efficient way to query whether two types are structurally identical to each
948other, ignoring typedefs. The solution to both of these problems is the idea of
Chris Lattner8a2bc622007-07-31 06:37:39 +0000949canonical types.</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000950
Chris Lattner62fd2782008-11-22 21:41:31 +0000951<!-- =============== -->
Chris Lattner8a2bc622007-07-31 06:37:39 +0000952<h4>Canonical Types</h4>
Chris Lattner62fd2782008-11-22 21:41:31 +0000953<!-- =============== -->
Chris Lattner86920d32007-07-31 05:42:17 +0000954
Chris Lattner8a2bc622007-07-31 06:37:39 +0000955<p>Every instance of the Type class contains a canonical type pointer. For
956simple types with no typedefs involved (e.g. "<tt>int</tt>", "<tt>int*</tt>",
957"<tt>int**</tt>"), the type just points to itself. For types that have a
958typedef somewhere in their structure (e.g. "<tt>foo</tt>", "<tt>foo*</tt>",
959"<tt>foo**</tt>", "<tt>bar</tt>"), the canonical type pointer points to their
960structurally equivalent type without any typedefs (e.g. "<tt>int</tt>",
961"<tt>int*</tt>", "<tt>int**</tt>", and "<tt>int*</tt>" respectively).</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000962
Chris Lattner8a2bc622007-07-31 06:37:39 +0000963<p>This design provides a constant time operation (dereferencing the canonical
964type pointer) that gives us access to the structure of types. For example,
965we can trivially tell that "bar" and "foo*" are the same type by dereferencing
966their canonical type pointers and doing a pointer comparison (they both point
967to the single "<tt>int*</tt>" type).</p>
968
969<p>Canonical types and typedef types bring up some complexities that must be
970carefully managed. Specifically, the "isa/cast/dyncast" operators generally
971shouldn't be used in code that is inspecting the AST. For example, when type
972checking the indirection operator (unary '*' on a pointer), the type checker
973must verify that the operand has a pointer type. It would not be correct to
974check that with "<tt>isa&lt;PointerType&gt;(SubExpr-&gt;getType())</tt>",
975because this predicate would fail if the subexpression had a typedef type.</p>
976
977<p>The solution to this problem are a set of helper methods on Type, used to
978check their properties. In this case, it would be correct to use
979"<tt>SubExpr-&gt;getType()-&gt;isPointerType()</tt>" to do the check. This
980predicate will return true if the <em>canonical type is a pointer</em>, which is
981true any time the type is structurally a pointer type. The only hard part here
982is remembering not to use the <tt>isa/cast/dyncast</tt> operations.</p>
983
984<p>The second problem we face is how to get access to the pointer type once we
985know it exists. To continue the example, the result type of the indirection
986operator is the pointee type of the subexpression. In order to determine the
987type, we need to get the instance of PointerType that best captures the typedef
988information in the program. If the type of the expression is literally a
989PointerType, we can return that, otherwise we have to dig through the
990typedefs to find the pointer type. For example, if the subexpression had type
991"<tt>foo*</tt>", we could return that type as the result. If the subexpression
992had type "<tt>bar</tt>", we want to return "<tt>foo*</tt>" (note that we do
993<em>not</em> want "<tt>int*</tt>"). In order to provide all of this, Type has
Chris Lattner11406c12007-07-31 16:50:51 +0000994a getAsPointerType() method that checks whether the type is structurally a
Chris Lattner8a2bc622007-07-31 06:37:39 +0000995PointerType and, if so, returns the best one. If not, it returns a null
996pointer.</p>
997
998<p>This structure is somewhat mystical, but after meditating on it, it will
999make sense to you :).</p>
Chris Lattner86920d32007-07-31 05:42:17 +00001000
1001<!-- ======================================================================= -->
1002<h3 id="QualType">The QualType class</h3>
1003<!-- ======================================================================= -->
1004
John McCall027ac442010-09-03 05:07:55 +00001005<p>The QualType class is designed as a trivial value class that is
1006small, passed by-value and is efficient to query. The idea of
1007QualType is that it stores the type qualifiers (const, volatile,
1008restrict, plus some extended qualifiers required by language
1009extensions) separately from the types themselves. QualType is
1010conceptually a pair of "Type*" and the bits for these type qualifiers.</p>
Chris Lattner86920d32007-07-31 05:42:17 +00001011
1012<p>By storing the type qualifiers as bits in the conceptual pair, it is
1013extremely efficient to get the set of qualifiers on a QualType (just return the
1014field of the pair), add a type qualifier (which is a trivial constant-time
1015operation that sets a bit), and remove one or more type qualifiers (just return
1016a QualType with the bitfield set to empty).</p>
1017
1018<p>Further, because the bits are stored outside of the type itself, we do not
1019need to create duplicates of types with different sets of qualifiers (i.e. there
1020is only a single heap allocated "int" type: "const int" and "volatile const int"
1021both point to the same heap allocated "int" type). This reduces the heap size
1022used to represent bits and also means we do not have to consider qualifiers when
1023uniquing types (<a href="#Type">Type</a> does not even contain qualifiers).</p>
1024
John McCall027ac442010-09-03 05:07:55 +00001025<p>In practice, the two most common type qualifiers (const and
1026restrict) are stored in the low bits of the pointer to the Type
1027object, together with a flag indicating whether extended qualifiers
1028are present (which must be heap-allocated). This means that QualType
1029is exactly the same size as a pointer.</p>
Ted Kremenek8bc05712007-10-10 23:01:43 +00001030
1031<!-- ======================================================================= -->
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001032<h3 id="DeclarationName">Declaration names</h3>
1033<!-- ======================================================================= -->
1034
1035<p>The <tt>DeclarationName</tt> class represents the name of a
1036 declaration in Clang. Declarations in the C family of languages can
Chris Lattner3fcbb892008-11-23 08:32:53 +00001037 take several different forms. Most declarations are named by
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001038 simple identifiers, e.g., "<code>f</code>" and "<code>x</code>" in
1039 the function declaration <code>f(int x)</code>. In C++, declaration
1040 names can also name class constructors ("<code>Class</code>"
1041 in <code>struct Class { Class(); }</code>), class destructors
1042 ("<code>~Class</code>"), overloaded operator names ("operator+"),
1043 and conversion functions ("<code>operator void const *</code>"). In
1044 Objective-C, declaration names can refer to the names of Objective-C
1045 methods, which involve the method name and the parameters,
Chris Lattner3fcbb892008-11-23 08:32:53 +00001046 collectively called a <i>selector</i>, e.g.,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001047 "<code>setWidth:height:</code>". Since all of these kinds of
Chris Lattner3fcbb892008-11-23 08:32:53 +00001048 entities - variables, functions, Objective-C methods, C++
1049 constructors, destructors, and operators - are represented as
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001050 subclasses of Clang's common <code>NamedDecl</code>
1051 class, <code>DeclarationName</code> is designed to efficiently
1052 represent any kind of name.</p>
1053
1054<p>Given
1055 a <code>DeclarationName</code> <code>N</code>, <code>N.getNameKind()</code>
Douglas Gregor2def4832008-11-17 20:34:05 +00001056 will produce a value that describes what kind of name <code>N</code>
Douglas Gregore94ca9e42008-11-18 14:39:36 +00001057 stores. There are 8 options (all of the names are inside
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001058 the <code>DeclarationName</code> class)</p>
1059<dl>
1060 <dt>Identifier</dt>
1061 <dd>The name is a simple
1062 identifier. Use <code>N.getAsIdentifierInfo()</code> to retrieve the
1063 corresponding <code>IdentifierInfo*</code> pointing to the actual
1064 identifier. Note that C++ overloaded operators (e.g.,
1065 "<code>operator+</code>") are represented as special kinds of
1066 identifiers. Use <code>IdentifierInfo</code>'s <code>getOverloadedOperatorID</code>
1067 function to determine whether an identifier is an overloaded
1068 operator name.</dd>
1069
1070 <dt>ObjCZeroArgSelector, ObjCOneArgSelector,
1071 ObjCMultiArgSelector</dt>
1072 <dd>The name is an Objective-C selector, which can be retrieved as a
1073 <code>Selector</code> instance
1074 via <code>N.getObjCSelector()</code>. The three possible name
1075 kinds for Objective-C reflect an optimization within
1076 the <code>DeclarationName</code> class: both zero- and
1077 one-argument selectors are stored as a
1078 masked <code>IdentifierInfo</code> pointer, and therefore require
1079 very little space, since zero- and one-argument selectors are far
1080 more common than multi-argument selectors (which use a different
1081 structure).</dd>
1082
1083 <dt>CXXConstructorName</dt>
1084 <dd>The name is a C++ constructor
1085 name. Use <code>N.getCXXNameType()</code> to retrieve
1086 the <a href="#QualType">type</a> that this constructor is meant to
1087 construct. The type is always the canonical type, since all
1088 constructors for a given type have the same name.</dd>
1089
1090 <dt>CXXDestructorName</dt>
1091 <dd>The name is a C++ destructor
1092 name. Use <code>N.getCXXNameType()</code> to retrieve
1093 the <a href="#QualType">type</a> whose destructor is being
1094 named. This type is always a canonical type.</dd>
1095
1096 <dt>CXXConversionFunctionName</dt>
1097 <dd>The name is a C++ conversion function. Conversion functions are
1098 named according to the type they convert to, e.g., "<code>operator void
1099 const *</code>". Use <code>N.getCXXNameType()</code> to retrieve
1100 the type that this conversion function converts to. This type is
1101 always a canonical type.</dd>
Douglas Gregore94ca9e42008-11-18 14:39:36 +00001102
1103 <dt>CXXOperatorName</dt>
1104 <dd>The name is a C++ overloaded operator name. Overloaded operators
1105 are named according to their spelling, e.g.,
1106 "<code>operator+</code>" or "<code>operator new
1107 []</code>". Use <code>N.getCXXOverloadedOperator()</code> to
1108 retrieve the overloaded operator (a value of
1109 type <code>OverloadedOperatorKind</code>).</dd>
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001110</dl>
1111
1112<p><code>DeclarationName</code>s are cheap to create, copy, and
1113 compare. They require only a single pointer's worth of storage in
Douglas Gregore94ca9e42008-11-18 14:39:36 +00001114 the common cases (identifiers, zero-
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001115 and one-argument Objective-C selectors) and use dense, uniqued
1116 storage for the other kinds of
1117 names. Two <code>DeclarationName</code>s can be compared for
1118 equality (<code>==</code>, <code>!=</code>) using a simple bitwise
1119 comparison, can be ordered
1120 with <code>&lt;</code>, <code>&gt;</code>, <code>&lt;=</code>,
1121 and <code>&gt;=</code> (which provide a lexicographical ordering for
1122 normal identifiers but an unspecified ordering for other kinds of
1123 names), and can be placed into LLVM <code>DenseMap</code>s
1124 and <code>DenseSet</code>s.</p>
1125
1126<p><code>DeclarationName</code> instances can be created in different
1127 ways depending on what kind of name the instance will store. Normal
Douglas Gregore94ca9e42008-11-18 14:39:36 +00001128 identifiers (<code>IdentifierInfo</code> pointers) and Objective-C selectors
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001129 (<code>Selector</code>) can be implicitly converted
1130 to <code>DeclarationName</code>s. Names for C++ constructors,
Douglas Gregore94ca9e42008-11-18 14:39:36 +00001131 destructors, conversion functions, and overloaded operators can be retrieved from
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001132 the <code>DeclarationNameTable</code>, an instance of which is
1133 available as <code>ASTContext::DeclarationNames</code>. The member
1134 functions <code>getCXXConstructorName</code>, <code>getCXXDestructorName</code>,
Douglas Gregore94ca9e42008-11-18 14:39:36 +00001135 <code>getCXXConversionFunctionName</code>, and <code>getCXXOperatorName</code>, respectively,
1136 return <code>DeclarationName</code> instances for the four kinds of
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001137 C++ special function names.</p>
1138
1139<!-- ======================================================================= -->
Douglas Gregor074149e2009-01-05 19:45:36 +00001140<h3 id="DeclContext">Declaration contexts</h3>
1141<!-- ======================================================================= -->
1142<p>Every declaration in a program exists within some <i>declaration
1143 context</i>, such as a translation unit, namespace, class, or
1144 function. Declaration contexts in Clang are represented by
1145 the <code>DeclContext</code> class, from which the various
1146 declaration-context AST nodes
1147 (<code>TranslationUnitDecl</code>, <code>NamespaceDecl</code>, <code>RecordDecl</code>, <code>FunctionDecl</code>,
1148 etc.) will derive. The <code>DeclContext</code> class provides
1149 several facilities common to each declaration context:</p>
1150<dl>
1151 <dt>Source-centric vs. Semantics-centric View of Declarations</dt>
1152 <dd><code>DeclContext</code> provides two views of the declarations
1153 stored within a declaration context. The source-centric view
1154 accurately represents the program source code as written, including
1155 multiple declarations of entities where present (see the
1156 section <a href="#Redeclarations">Redeclarations and
1157 Overloads</a>), while the semantics-centric view represents the
1158 program semantics. The two views are kept synchronized by semantic
1159 analysis while the ASTs are being constructed.</dd>
1160
1161 <dt>Storage of declarations within that context</dt>
1162 <dd>Every declaration context can contain some number of
1163 declarations. For example, a C++ class (represented
1164 by <code>RecordDecl</code>) contains various member functions,
1165 fields, nested types, and so on. All of these declarations will be
1166 stored within the <code>DeclContext</code>, and one can iterate
1167 over the declarations via
1168 [<code>DeclContext::decls_begin()</code>,
1169 <code>DeclContext::decls_end()</code>). This mechanism provides
1170 the source-centric view of declarations in the context.</dd>
1171
1172 <dt>Lookup of declarations within that context</dt>
1173 <dd>The <code>DeclContext</code> structure provides efficient name
1174 lookup for names within that declaration context. For example,
1175 if <code>N</code> is a namespace we can look for the
1176 name <code>N::f</code>
1177 using <code>DeclContext::lookup</code>. The lookup itself is
1178 based on a lazily-constructed array (for declaration contexts
1179 with a small number of declarations) or hash table (for
1180 declaration contexts with more declarations). The lookup
1181 operation provides the semantics-centric view of the declarations
1182 in the context.</dd>
1183
1184 <dt>Ownership of declarations</dt>
1185 <dd>The <code>DeclContext</code> owns all of the declarations that
1186 were declared within its declaration context, and is responsible
1187 for the management of their memory as well as their
1188 (de-)serialization.</dd>
1189</dl>
1190
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001191<p>All declarations are stored within a declaration context, and one
1192 can query
1193 information about the context in which each declaration lives. One
Douglas Gregor074149e2009-01-05 19:45:36 +00001194 can retrieve the <code>DeclContext</code> that contains a
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001195 particular <code>Decl</code>
1196 using <code>Decl::getDeclContext</code>. However, see the
Douglas Gregor074149e2009-01-05 19:45:36 +00001197 section <a href="#LexicalAndSemanticContexts">Lexical and Semantic
1198 Contexts</a> for more information about how to interpret this
1199 context information.</p>
1200
1201<h4 id="Redeclarations">Redeclarations and Overloads</h4>
1202<p>Within a translation unit, it is common for an entity to be
1203declared several times. For example, we might declare a function "f"
1204 and then later re-declare it as part of an inlined definition:</p>
1205
1206<pre>
1207void f(int x, int y, int z = 1);
1208
1209inline void f(int x, int y, int z) { /* ... */ }
1210</pre>
1211
1212<p>The representation of "f" differs in the source-centric and
1213 semantics-centric views of a declaration context. In the
1214 source-centric view, all redeclarations will be present, in the
1215 order they occurred in the source code, making
1216 this view suitable for clients that wish to see the structure of
1217 the source code. In the semantics-centric view, only the most recent "f"
1218 will be found by the lookup, since it effectively replaces the first
1219 declaration of "f".</p>
1220
1221<p>In the semantics-centric view, overloading of functions is
1222 represented explicitly. For example, given two declarations of a
1223 function "g" that are overloaded, e.g.,</p>
1224<pre>
1225void g();
1226void g(int);
1227</pre>
1228<p>the <code>DeclContext::lookup</code> operation will return
Jonathan D. Turnerd3224292011-07-06 18:12:36 +00001229 a <code>DeclContext::lookup_result</code> that contains a range of iterators
1230 over declarations of "g". Clients that perform semantic analysis on a
Douglas Gregor074149e2009-01-05 19:45:36 +00001231 program that is not concerned with the actual source code will
1232 primarily use this semantics-centric view.</p>
1233
1234<h4 id="LexicalAndSemanticContexts">Lexical and Semantic Contexts</h4>
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001235<p>Each declaration has two potentially different
Douglas Gregor074149e2009-01-05 19:45:36 +00001236 declaration contexts: a <i>lexical</i> context, which corresponds to
1237 the source-centric view of the declaration context, and
1238 a <i>semantic</i> context, which corresponds to the
1239 semantics-centric view. The lexical context is accessible
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001240 via <code>Decl::getLexicalDeclContext</code> while the
Douglas Gregor074149e2009-01-05 19:45:36 +00001241 semantic context is accessible
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001242 via <code>Decl::getDeclContext</code>, both of which return
Douglas Gregor074149e2009-01-05 19:45:36 +00001243 <code>DeclContext</code> pointers. For most declarations, the two
1244 contexts are identical. For example:</p>
1245
1246<pre>
1247class X {
1248public:
1249 void f(int x);
1250};
1251</pre>
1252
1253<p>Here, the semantic and lexical contexts of <code>X::f</code> are
1254 the <code>DeclContext</code> associated with the
1255 class <code>X</code> (itself stored as a <code>RecordDecl</code> AST
1256 node). However, we can now define <code>X::f</code> out-of-line:</p>
1257
1258<pre>
1259void X::f(int x = 17) { /* ... */ }
1260</pre>
1261
1262<p>This definition of has different lexical and semantic
1263 contexts. The lexical context corresponds to the declaration
1264 context in which the actual declaration occurred in the source
1265 code, e.g., the translation unit containing <code>X</code>. Thus,
1266 this declaration of <code>X::f</code> can be found by traversing
1267 the declarations provided by
1268 [<code>decls_begin()</code>, <code>decls_end()</code>) in the
1269 translation unit.</p>
1270
1271<p>The semantic context of <code>X::f</code> corresponds to the
1272 class <code>X</code>, since this member function is (semantically) a
1273 member of <code>X</code>. Lookup of the name <code>f</code> into
1274 the <code>DeclContext</code> associated with <code>X</code> will
1275 then return the definition of <code>X::f</code> (including
1276 information about the default argument).</p>
1277
1278<h4 id="TransparentContexts">Transparent Declaration Contexts</h4>
1279<p>In C and C++, there are several contexts in which names that are
1280 logically declared inside another declaration will actually "leak"
1281 out into the enclosing scope from the perspective of name
1282 lookup. The most obvious instance of this behavior is in
1283 enumeration types, e.g.,</p>
1284<pre>
1285enum Color {
1286 Red,
1287 Green,
1288 Blue
1289};
1290</pre>
1291
1292<p>Here, <code>Color</code> is an enumeration, which is a declaration
1293 context that contains the
1294 enumerators <code>Red</code>, <code>Green</code>,
1295 and <code>Blue</code>. Thus, traversing the list of declarations
1296 contained in the enumeration <code>Color</code> will
1297 yield <code>Red</code>, <code>Green</code>,
1298 and <code>Blue</code>. However, outside of the scope
1299 of <code>Color</code> one can name the enumerator <code>Red</code>
1300 without qualifying the name, e.g.,</p>
1301
1302<pre>
1303Color c = Red;
1304</pre>
1305
1306<p>There are other entities in C++ that provide similar behavior. For
1307 example, linkage specifications that use curly braces:</p>
1308
1309<pre>
1310extern "C" {
1311 void f(int);
1312 void g(int);
1313}
1314// f and g are visible here
1315</pre>
1316
1317<p>For source-level accuracy, we treat the linkage specification and
1318 enumeration type as a
1319 declaration context in which its enclosed declarations ("Red",
1320 "Green", and "Blue"; "f" and "g")
1321 are declared. However, these declarations are visible outside of the
1322 scope of the declaration context.</p>
1323
1324<p>These language features (and several others, described below) have
1325 roughly the same set of
1326 requirements: declarations are declared within a particular lexical
1327 context, but the declarations are also found via name lookup in
1328 scopes enclosing the declaration itself. This feature is implemented
1329 via <i>transparent</i> declaration contexts
1330 (see <code>DeclContext::isTransparentContext()</code>), whose
1331 declarations are visible in the nearest enclosing non-transparent
1332 declaration context. This means that the lexical context of the
1333 declaration (e.g., an enumerator) will be the
1334 transparent <code>DeclContext</code> itself, as will the semantic
1335 context, but the declaration will be visible in every outer context
1336 up to and including the first non-transparent declaration context (since
1337 transparent declaration contexts can be nested).</p>
1338
1339<p>The transparent <code>DeclContexts</code> are:</p>
1340<ul>
David Blaikie5090e9f2011-10-18 05:49:30 +00001341 <li>Enumerations (but not C++11 "scoped enumerations"):
Douglas Gregor074149e2009-01-05 19:45:36 +00001342 <pre>
1343enum Color {
1344 Red,
1345 Green,
1346 Blue
1347};
1348// Red, Green, and Blue are in scope
1349 </pre></li>
1350 <li>C++ linkage specifications:
1351 <pre>
1352extern "C" {
1353 void f(int);
1354 void g(int);
1355}
1356// f and g are in scope
1357 </pre></li>
1358 <li>Anonymous unions and structs:
1359 <pre>
1360struct LookupTable {
1361 bool IsVector;
1362 union {
1363 std::vector&lt;Item&gt; *Vector;
1364 std::set&lt;Item&gt; *Set;
1365 };
1366};
1367
1368LookupTable LT;
1369LT.Vector = 0; // Okay: finds Vector inside the unnamed union
1370 </pre>
1371 </li>
David Blaikie5090e9f2011-10-18 05:49:30 +00001372 <li>C++11 inline namespaces:
Douglas Gregor074149e2009-01-05 19:45:36 +00001373<pre>
1374namespace mylib {
1375 inline namespace debug {
1376 class X;
1377 }
1378}
1379mylib::X *xp; // okay: mylib::X refers to mylib::debug::X
1380</pre>
1381</li>
1382</ul>
1383
1384
1385<h4 id="MultiDeclContext">Multiply-Defined Declaration Contexts</h4>
1386<p>C++ namespaces have the interesting--and, so far, unique--property that
1387the namespace can be defined multiple times, and the declarations
1388provided by each namespace definition are effectively merged (from
1389the semantic point of view). For example, the following two code
1390snippets are semantically indistinguishable:</p>
1391<pre>
1392// Snippet #1:
1393namespace N {
1394 void f();
1395}
1396namespace N {
1397 void f(int);
1398}
1399
1400// Snippet #2:
1401namespace N {
1402 void f();
1403 void f(int);
1404}
1405</pre>
1406
1407<p>In Clang's representation, the source-centric view of declaration
1408 contexts will actually have two separate <code>NamespaceDecl</code>
1409 nodes in Snippet #1, each of which is a declaration context that
1410 contains a single declaration of "f". However, the semantics-centric
1411 view provided by name lookup into the namespace <code>N</code> for
Jonathan D. Turnerd3224292011-07-06 18:12:36 +00001412 "f" will return a <code>DeclContext::lookup_result</code> that contains
1413 a range of iterators over declarations of "f".</p>
Douglas Gregor074149e2009-01-05 19:45:36 +00001414
1415<p><code>DeclContext</code> manages multiply-defined declaration
1416 contexts internally. The
1417 function <code>DeclContext::getPrimaryContext</code> retrieves the
1418 "primary" context for a given <code>DeclContext</code> instance,
1419 which is the <code>DeclContext</code> responsible for maintaining
1420 the lookup table used for the semantics-centric view. Given the
1421 primary context, one can follow the chain
1422 of <code>DeclContext</code> nodes that define additional
1423 declarations via <code>DeclContext::getNextContext</code>. Note that
1424 these functions are used internally within the lookup and insertion
1425 methods of the <code>DeclContext</code>, so the vast majority of
1426 clients can ignore them.</p>
1427
1428<!-- ======================================================================= -->
Ted Kremenek8bc05712007-10-10 23:01:43 +00001429<h3 id="CFG">The <tt>CFG</tt> class</h3>
1430<!-- ======================================================================= -->
1431
1432<p>The <tt>CFG</tt> class is designed to represent a source-level
1433control-flow graph for a single statement (<tt>Stmt*</tt>). Typically
1434instances of <tt>CFG</tt> are constructed for function bodies (usually
1435an instance of <tt>CompoundStmt</tt>), but can also be instantiated to
1436represent the control-flow of any class that subclasses <tt>Stmt</tt>,
1437which includes simple expressions. Control-flow graphs are especially
1438useful for performing
1439<a href="http://en.wikipedia.org/wiki/Data_flow_analysis#Sensitivities">flow-
1440or path-sensitive</a> program analyses on a given function.</p>
1441
Chris Lattner62fd2782008-11-22 21:41:31 +00001442<!-- ============ -->
Ted Kremenek8bc05712007-10-10 23:01:43 +00001443<h4>Basic Blocks</h4>
Chris Lattner62fd2782008-11-22 21:41:31 +00001444<!-- ============ -->
Ted Kremenek8bc05712007-10-10 23:01:43 +00001445
1446<p>Concretely, an instance of <tt>CFG</tt> is a collection of basic
1447blocks. Each basic block is an instance of <tt>CFGBlock</tt>, which
1448simply contains an ordered sequence of <tt>Stmt*</tt> (each referring
1449to statements in the AST). The ordering of statements within a block
1450indicates unconditional flow of control from one statement to the
1451next. <a href="#ConditionalControlFlow">Conditional control-flow</a>
1452is represented using edges between basic blocks. The statements
1453within a given <tt>CFGBlock</tt> can be traversed using
1454the <tt>CFGBlock::*iterator</tt> interface.</p>
1455
1456<p>
Ted Kremenek18e17e72007-10-18 22:50:52 +00001457A <tt>CFG</tt> object owns the instances of <tt>CFGBlock</tt> within
Ted Kremenek8bc05712007-10-10 23:01:43 +00001458the control-flow graph it represents. Each <tt>CFGBlock</tt> within a
1459CFG is also uniquely numbered (accessible
1460via <tt>CFGBlock::getBlockID()</tt>). Currently the number is
1461based on the ordering the blocks were created, but no assumptions
1462should be made on how <tt>CFGBlock</tt>s are numbered other than their
1463numbers are unique and that they are numbered from 0..N-1 (where N is
1464the number of basic blocks in the CFG).</p>
1465
Chris Lattner62fd2782008-11-22 21:41:31 +00001466<!-- ===================== -->
Ted Kremenek8bc05712007-10-10 23:01:43 +00001467<h4>Entry and Exit Blocks</h4>
Chris Lattner62fd2782008-11-22 21:41:31 +00001468<!-- ===================== -->
Ted Kremenek8bc05712007-10-10 23:01:43 +00001469
1470Each instance of <tt>CFG</tt> contains two special blocks:
1471an <i>entry</i> block (accessible via <tt>CFG::getEntry()</tt>), which
1472has no incoming edges, and an <i>exit</i> block (accessible
1473via <tt>CFG::getExit()</tt>), which has no outgoing edges. Neither
1474block contains any statements, and they serve the role of providing a
1475clear entrance and exit for a body of code such as a function body.
1476The presence of these empty blocks greatly simplifies the
1477implementation of many analyses built on top of CFGs.
1478
Chris Lattner62fd2782008-11-22 21:41:31 +00001479<!-- ===================================================== -->
Ted Kremenek8bc05712007-10-10 23:01:43 +00001480<h4 id ="ConditionalControlFlow">Conditional Control-Flow</h4>
Chris Lattner62fd2782008-11-22 21:41:31 +00001481<!-- ===================================================== -->
Ted Kremenek8bc05712007-10-10 23:01:43 +00001482
1483<p>Conditional control-flow (such as those induced by if-statements
1484and loops) is represented as edges between <tt>CFGBlock</tt>s.
1485Because different C language constructs can induce control-flow,
1486each <tt>CFGBlock</tt> also records an extra <tt>Stmt*</tt> that
1487represents the <i>terminator</i> of the block. A terminator is simply
1488the statement that caused the control-flow, and is used to identify
1489the nature of the conditional control-flow between blocks. For
1490example, in the case of an if-statement, the terminator refers to
1491the <tt>IfStmt</tt> object in the AST that represented the given
1492branch.</p>
1493
1494<p>To illustrate, consider the following code example:</p>
1495
1496<code>
1497int foo(int x) {<br>
1498&nbsp;&nbsp;x = x + 1;<br>
1499<br>
1500&nbsp;&nbsp;if (x > 2) x++;<br>
1501&nbsp;&nbsp;else {<br>
1502&nbsp;&nbsp;&nbsp;&nbsp;x += 2;<br>
1503&nbsp;&nbsp;&nbsp;&nbsp;x *= 2;<br>
1504&nbsp;&nbsp;}<br>
1505<br>
1506&nbsp;&nbsp;return x;<br>
1507}
1508</code>
1509
1510<p>After invoking the parser+semantic analyzer on this code fragment,
1511the AST of the body of <tt>foo</tt> is referenced by a
1512single <tt>Stmt*</tt>. We can then construct an instance
1513of <tt>CFG</tt> representing the control-flow graph of this function
1514body by single call to a static class method:</p>
1515
1516<code>
1517&nbsp;&nbsp;Stmt* FooBody = ...<br>
1518&nbsp;&nbsp;CFG* FooCFG = <b>CFG::buildCFG</b>(FooBody);
1519</code>
1520
1521<p>It is the responsibility of the caller of <tt>CFG::buildCFG</tt>
1522to <tt>delete</tt> the returned <tt>CFG*</tt> when the CFG is no
1523longer needed.</p>
1524
1525<p>Along with providing an interface to iterate over
1526its <tt>CFGBlock</tt>s, the <tt>CFG</tt> class also provides methods
1527that are useful for debugging and visualizing CFGs. For example, the
1528method
1529<tt>CFG::dump()</tt> dumps a pretty-printed version of the CFG to
1530standard error. This is especially useful when one is using a
1531debugger such as gdb. For example, here is the output
1532of <tt>FooCFG->dump()</tt>:</p>
1533
1534<code>
1535&nbsp;[ B5 (ENTRY) ]<br>
1536&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (0):<br>
1537&nbsp;&nbsp;&nbsp;&nbsp;Successors (1): B4<br>
1538<br>
1539&nbsp;[ B4 ]<br>
1540&nbsp;&nbsp;&nbsp;&nbsp;1: x = x + 1<br>
1541&nbsp;&nbsp;&nbsp;&nbsp;2: (x > 2)<br>
1542&nbsp;&nbsp;&nbsp;&nbsp;<b>T: if [B4.2]</b><br>
1543&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (1): B5<br>
1544&nbsp;&nbsp;&nbsp;&nbsp;Successors (2): B3 B2<br>
1545<br>
1546&nbsp;[ B3 ]<br>
1547&nbsp;&nbsp;&nbsp;&nbsp;1: x++<br>
1548&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (1): B4<br>
1549&nbsp;&nbsp;&nbsp;&nbsp;Successors (1): B1<br>
1550<br>
1551&nbsp;[ B2 ]<br>
1552&nbsp;&nbsp;&nbsp;&nbsp;1: x += 2<br>
1553&nbsp;&nbsp;&nbsp;&nbsp;2: x *= 2<br>
1554&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (1): B4<br>
1555&nbsp;&nbsp;&nbsp;&nbsp;Successors (1): B1<br>
1556<br>
1557&nbsp;[ B1 ]<br>
1558&nbsp;&nbsp;&nbsp;&nbsp;1: return x;<br>
1559&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (2): B2 B3<br>
1560&nbsp;&nbsp;&nbsp;&nbsp;Successors (1): B0<br>
1561<br>
1562&nbsp;[ B0 (EXIT) ]<br>
1563&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (1): B1<br>
1564&nbsp;&nbsp;&nbsp;&nbsp;Successors (0):
1565</code>
1566
1567<p>For each block, the pretty-printed output displays for each block
1568the number of <i>predecessor</i> blocks (blocks that have outgoing
1569control-flow to the given block) and <i>successor</i> blocks (blocks
1570that have control-flow that have incoming control-flow from the given
1571block). We can also clearly see the special entry and exit blocks at
1572the beginning and end of the pretty-printed output. For the entry
1573block (block B5), the number of predecessor blocks is 0, while for the
1574exit block (block B0) the number of successor blocks is 0.</p>
1575
1576<p>The most interesting block here is B4, whose outgoing control-flow
1577represents the branching caused by the sole if-statement
1578in <tt>foo</tt>. Of particular interest is the second statement in
1579the block, <b><tt>(x > 2)</tt></b>, and the terminator, printed
1580as <b><tt>if [B4.2]</tt></b>. The second statement represents the
1581evaluation of the condition of the if-statement, which occurs before
1582the actual branching of control-flow. Within the <tt>CFGBlock</tt>
1583for B4, the <tt>Stmt*</tt> for the second statement refers to the
1584actual expression in the AST for <b><tt>(x > 2)</tt></b>. Thus
1585pointers to subclasses of <tt>Expr</tt> can appear in the list of
1586statements in a block, and not just subclasses of <tt>Stmt</tt> that
1587refer to proper C statements.</p>
1588
1589<p>The terminator of block B4 is a pointer to the <tt>IfStmt</tt>
1590object in the AST. The pretty-printer outputs <b><tt>if
1591[B4.2]</tt></b> because the condition expression of the if-statement
1592has an actual place in the basic block, and thus the terminator is
1593essentially
1594<i>referring</i> to the expression that is the second statement of
1595block B4 (i.e., B4.2). In this manner, conditions for control-flow
1596(which also includes conditions for loops and switch statements) are
1597hoisted into the actual basic block.</p>
1598
Chris Lattner62fd2782008-11-22 21:41:31 +00001599<!-- ===================== -->
1600<!-- <h4>Implicit Control-Flow</h4> -->
1601<!-- ===================== -->
Ted Kremenek8bc05712007-10-10 23:01:43 +00001602
1603<!--
1604<p>A key design principle of the <tt>CFG</tt> class was to not require
1605any transformations to the AST in order to represent control-flow.
1606Thus the <tt>CFG</tt> does not perform any "lowering" of the
1607statements in an AST: loops are not transformed into guarded gotos,
1608short-circuit operations are not converted to a set of if-statements,
1609and so on.</p>
1610-->
Ted Kremenek17a295d2008-06-11 06:19:49 +00001611
Chris Lattner7bad1992008-11-16 21:48:07 +00001612
1613<!-- ======================================================================= -->
1614<h3 id="Constants">Constant Folding in the Clang AST</h3>
1615<!-- ======================================================================= -->
1616
1617<p>There are several places where constants and constant folding matter a lot to
1618the Clang front-end. First, in general, we prefer the AST to retain the source
1619code as close to how the user wrote it as possible. This means that if they
1620wrote "5+4", we want to keep the addition and two constants in the AST, we don't
1621want to fold to "9". This means that constant folding in various ways turns
1622into a tree walk that needs to handle the various cases.</p>
1623
1624<p>However, there are places in both C and C++ that require constants to be
1625folded. For example, the C standard defines what an "integer constant
1626expression" (i-c-e) is with very precise and specific requirements. The
1627language then requires i-c-e's in a lot of places (for example, the size of a
1628bitfield, the value for a case statement, etc). For these, we have to be able
1629to constant fold the constants, to do semantic checks (e.g. verify bitfield size
1630is non-negative and that case statements aren't duplicated). We aim for Clang
1631to be very pedantic about this, diagnosing cases when the code does not use an
1632i-c-e where one is required, but accepting the code unless running with
1633<tt>-pedantic-errors</tt>.</p>
1634
1635<p>Things get a little bit more tricky when it comes to compatibility with
1636real-world source code. Specifically, GCC has historically accepted a huge
1637superset of expressions as i-c-e's, and a lot of real world code depends on this
1638unfortuate accident of history (including, e.g., the glibc system headers). GCC
1639accepts anything its "fold" optimizer is capable of reducing to an integer
1640constant, which means that the definition of what it accepts changes as its
1641optimizer does. One example is that GCC accepts things like "case X-X:" even
1642when X is a variable, because it can fold this to 0.</p>
1643
1644<p>Another issue are how constants interact with the extensions we support, such
1645as __builtin_constant_p, __builtin_inf, __extension__ and many others. C99
1646obviously does not specify the semantics of any of these extensions, and the
1647definition of i-c-e does not include them. However, these extensions are often
1648used in real code, and we have to have a way to reason about them.</p>
1649
1650<p>Finally, this is not just a problem for semantic analysis. The code
1651generator and other clients have to be able to fold constants (e.g. to
1652initialize global variables) and has to handle a superset of what C99 allows.
1653Further, these clients can benefit from extended information. For example, we
1654know that "foo()||1" always evaluates to true, but we can't replace the
1655expression with true because it has side effects.</p>
1656
1657<!-- ======================= -->
1658<h4>Implementation Approach</h4>
1659<!-- ======================= -->
1660
1661<p>After trying several different approaches, we've finally converged on a
1662design (Note, at the time of this writing, not all of this has been implemented,
1663consider this a design goal!). Our basic approach is to define a single
1664recursive method evaluation method (<tt>Expr::Evaluate</tt>), which is
1665implemented in <tt>AST/ExprConstant.cpp</tt>. Given an expression with 'scalar'
1666type (integer, fp, complex, or pointer) this method returns the following
1667information:</p>
1668
1669<ul>
1670<li>Whether the expression is an integer constant expression, a general
1671 constant that was folded but has no side effects, a general constant that
1672 was folded but that does have side effects, or an uncomputable/unfoldable
1673 value.
1674</li>
1675<li>If the expression was computable in any way, this method returns the APValue
1676 for the result of the expression.</li>
1677<li>If the expression is not evaluatable at all, this method returns
1678 information on one of the problems with the expression. This includes a
1679 SourceLocation for where the problem is, and a diagnostic ID that explains
1680 the problem. The diagnostic should be have ERROR type.</li>
1681<li>If the expression is not an integer constant expression, this method returns
1682 information on one of the problems with the expression. This includes a
1683 SourceLocation for where the problem is, and a diagnostic ID that explains
1684 the problem. The diagnostic should be have EXTENSION type.</li>
1685</ul>
1686
1687<p>This information gives various clients the flexibility that they want, and we
1688will eventually have some helper methods for various extensions. For example,
1689Sema should have a <tt>Sema::VerifyIntegerConstantExpression</tt> method, which
1690calls Evaluate on the expression. If the expression is not foldable, the error
1691is emitted, and it would return true. If the expression is not an i-c-e, the
1692EXTENSION diagnostic is emitted. Finally it would return false to indicate that
1693the AST is ok.</p>
1694
1695<p>Other clients can use the information in other ways, for example, codegen can
1696just use expressions that are foldable in any way.</p>
1697
1698<!-- ========== -->
1699<h4>Extensions</h4>
1700<!-- ========== -->
1701
Chris Lattner552de0a2008-11-23 08:16:56 +00001702<p>This section describes how some of the various extensions Clang supports
Chris Lattner7bad1992008-11-16 21:48:07 +00001703interacts with constant evaluation:</p>
1704
1705<ul>
1706<li><b><tt>__extension__</tt></b>: The expression form of this extension causes
1707 any evaluatable subexpression to be accepted as an integer constant
1708 expression.</li>
Sylvestre Ledru2a700b12012-07-25 22:02:37 +00001709<li><b><tt>__builtin_constant_p</tt></b>: This returns true (as an integer
Richard Smith8a0f1552011-12-09 03:40:28 +00001710 constant expression) if the operand evaluates to either a numeric value
1711 (that is, not a pointer cast to integral type) of integral, enumeration,
1712 floating or complex type, or if it evaluates to the address of the first
1713 character of a string literal (possibly cast to some other type). As a
Chris Lattner28daa532008-12-12 06:55:44 +00001714 special case, if <tt>__builtin_constant_p</tt> is the (potentially
1715 parenthesized) condition of a conditional operator expression ("?:"), only
Chris Lattner42b83dd2008-12-12 18:00:51 +00001716 the true side of the conditional operator is considered, and it is evaluated
1717 with full constant folding.</li>
Chris Lattner7bad1992008-11-16 21:48:07 +00001718<li><b><tt>__builtin_choose_expr</tt></b>: The condition is required to be an
1719 integer constant expression, but we accept any constant as an "extension of
1720 an extension". This only evaluates one operand depending on which way the
1721 condition evaluates.</li>
1722<li><b><tt>__builtin_classify_type</tt></b>: This always returns an integer
1723 constant expression.</li>
1724<li><b><tt>__builtin_inf,nan,..</tt></b>: These are treated just like a
1725 floating-point literal.</li>
1726<li><b><tt>__builtin_abs,copysign,..</tt></b>: These are constant folded as
1727 general constant expressions.</li>
Richard Smith8a0f1552011-12-09 03:40:28 +00001728<li><b><tt>__builtin_strlen</tt></b> and <b><tt>strlen</tt></b>: These are
1729 constant folded as integer constant expressions if the argument is a string
1730 literal.</li>
Chris Lattner7bad1992008-11-16 21:48:07 +00001731</ul>
1732
1733
Jeffrey Yasskin28dadd62011-01-28 23:41:54 +00001734<!-- ======================================================================= -->
1735<h2 id="Howtos">How to change Clang</h2>
1736<!-- ======================================================================= -->
Chris Lattner7bad1992008-11-16 21:48:07 +00001737
Jeffrey Yasskin28dadd62011-01-28 23:41:54 +00001738<!-- ======================================================================= -->
1739<h3 id="AddingAttributes">How to add an attribute</h3>
1740<!-- ======================================================================= -->
1741
1742<p>To add an attribute, you'll have to add it to the list of attributes, add it
1743to the parsing phase, and look for it in the AST scan.
Benjamin Kramer665a8dc2012-01-15 15:26:07 +00001744<a href="http://llvm.org/viewvc/llvm-project?view=rev&amp;revision=124217">r124217</a>
Jeffrey Yasskin28dadd62011-01-28 23:41:54 +00001745has a good example of adding a warning attribute.</p>
1746
1747<p>(Beware that this hasn't been reviewed/fixed by the people who designed the
1748attributes system yet.)</p>
1749
1750<h4><a
1751href="http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/Attr.td?view=markup">include/clang/Basic/Attr.td</a></h4>
1752
1753<p>Each attribute gets a <tt>def</tt> inheriting from <tt>Attr</tt> or one of
1754its subclasses. <tt>InheritableAttr</tt> means that the attribute also applies
1755to subsequent declarations of the same name.</p>
1756
1757<p><tt>Spellings</tt> lists the strings that can appear in
1758<tt>__attribute__((here))</tt> or <tt>[[here]]</tt>. All such strings
David Blaikie5090e9f2011-10-18 05:49:30 +00001759will be synonymous. If you want to allow the <tt>[[]]</tt> C++11
Jeffrey Yasskin28dadd62011-01-28 23:41:54 +00001760syntax, you have to define a list of <tt>Namespaces</tt>, which will
1761let users write <tt>[[namespace:spelling]]</tt>. Using the empty
1762string for a namespace will allow users to write just the spelling
1763with no "<tt>:</tt>".</p>
1764
1765<p><tt>Subjects</tt> restricts what kinds of AST node to which this attribute
1766can appertain (roughly, attach).</p>
1767
1768<p><tt>Args</tt> names the arguments the attribute takes, in order. If
1769<tt>Args</tt> is <tt>[StringArgument&lt;"Arg1">, IntArgument&lt;"Arg2">]</tt>
1770then <tt>__attribute__((myattribute("Hello", 3)))</tt> will be a valid use.</p>
1771
1772<h4>Boilerplate</h4>
1773
Jeffrey Yasskin28dadd62011-01-28 23:41:54 +00001774<p>Write a new <tt>HandleYourAttr()</tt> function in <a
1775href="http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaDeclAttr.cpp?view=markup">lib/Sema/SemaDeclAttr.cpp</a>,
1776and add a case to the switch in <tt>ProcessNonInheritableDeclAttr()</tt> or
1777<tt>ProcessInheritableDeclAttr()</tt> forwarding to it.</p>
1778
1779<p>If your attribute causes extra warnings to fire, define a <tt>DiagGroup</tt>
1780in <a
1781href="http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticGroups.td?view=markup">include/clang/Basic/DiagnosticGroups.td</a>
1782named after the attribute's <tt>Spelling</tt> with "_"s replaced by "-"s. If
1783you're only defining one diagnostic, you can skip <tt>DiagnosticGroups.td</tt>
1784and use <tt>InGroup&lt;DiagGroup&lt;"your-attribute">></tt> directly in <a
1785href="http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td?view=markup">DiagnosticSemaKinds.td</a></p>
1786
1787<h4>The meat of your attribute</h4>
1788
1789<p>Find an appropriate place in Clang to do whatever your attribute needs to do.
1790Check for the attribute's presence using <tt>Decl::getAttr&lt;YourAttr>()</tt>.</p>
1791
1792<p>Update the <a href="LanguageExtensions.html">Clang Language Extensions</a>
1793document to describe your new attribute.</p>
Chris Lattner7bad1992008-11-16 21:48:07 +00001794
Douglas Gregor1f634c62011-09-30 21:32:37 +00001795<!-- ======================================================================= -->
1796<h3 id="AddingExprStmt">How to add an expression or statement</h3>
1797<!-- ======================================================================= -->
1798
1799<p>Expressions and statements are one of the most fundamental constructs within a
1800compiler, because they interact with many different parts of the AST,
1801semantic analysis, and IR generation. Therefore, adding a new
1802expression or statement kind into Clang requires some care. The following list
1803details the various places in Clang where an expression or statement needs to be
1804introduced, along with patterns to follow to ensure that the new
1805expression or statement works well across all of the C languages. We
1806focus on expressions, but statements are similar.</p>
1807
1808<ol>
1809 <li>Introduce parsing actions into the parser. Recursive-descent
1810 parsing is mostly self-explanatory, but there are a few things that
1811 are worth keeping in mind:
1812 <ul>
1813 <li>Keep as much source location information as possible! You'll
1814 want it later to produce great diagnostics and support Clang's
1815 various features that map between source code and the AST.</li>
1816 <li>Write tests for all of the "bad" parsing cases, to make sure
1817 your recovery is good. If you have matched delimiters (e.g.,
1818 parentheses, square brackets, etc.), use
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001819 <tt>Parser::BalancedDelimiterTracker</tt> to give nice diagnostics when
Douglas Gregor1f634c62011-09-30 21:32:37 +00001820 things go wrong.</li>
1821 </ul>
1822 </li>
1823
1824 <li>Introduce semantic analysis actions into <tt>Sema</tt>. Semantic
1825 analysis should always involve two functions: an <tt>ActOnXXX</tt>
1826 function that will be called directly from the parser, and a
1827 <tt>BuildXXX</tt> function that performs the actual semantic
1828 analysis and will (eventually!) build the AST node. It's fairly
1829 common for the <tt>ActOnCXX</tt> function to do very little (often
1830 just some minor translation from the parser's representation to
1831 <tt>Sema</tt>'s representation of the same thing), but the separation
1832 is still important: C++ template instantiation, for example,
1833 should always call the <tt>BuildXXX</tt> variant. Several notes on
1834 semantic analysis before we get into construction of the AST:
1835 <ul>
1836 <li>Your expression probably involves some types and some
1837 subexpressions. Make sure to fully check that those types, and the
1838 types of those subexpressions, meet your expectations. Add
1839 implicit conversions where necessary to make sure that all of the
1840 types line up exactly the way you want them. Write extensive tests
1841 to check that you're getting good diagnostics for mistakes and
1842 that you can use various forms of subexpressions with your
1843 expression.</li>
1844 <li>When type-checking a type or subexpression, make sure to first
1845 check whether the type is "dependent"
1846 (<tt>Type::isDependentType()</tt>) or whether a subexpression is
1847 type-dependent (<tt>Expr::isTypeDependent()</tt>). If any of these
1848 return true, then you're inside a template and you can't do much
1849 type-checking now. That's normal, and your AST node (when you get
1850 there) will have to deal with this case. At this point, you can
1851 write tests that use your expression within templates, but don't
1852 try to instantiate the templates.</li>
1853 <li>For each subexpression, be sure to call
1854 <tt>Sema::CheckPlaceholderExpr()</tt> to deal with "weird"
1855 expressions that don't behave well as subexpressions. Then,
1856 determine whether you need to perform
1857 lvalue-to-rvalue conversions
1858 (<tt>Sema::DefaultLvalueConversion</tt>e) or
1859 the usual unary conversions
1860 (<tt>Sema::UsualUnaryConversions</tt>), for places where the
1861 subexpression is producing a value you intend to use.</li>
1862 <li>Your <tt>BuildXXX</tt> function will probably just return
1863 <tt>ExprError()</tt> at this point, since you don't have an AST.
1864 That's perfectly fine, and shouldn't impact your testing.</li>
1865 </ul>
1866 </li>
1867
1868 <li>Introduce an AST node for your new expression. This starts with
1869 declaring the node in <tt>include/Basic/StmtNodes.td</tt> and
1870 creating a new class for your expression in the appropriate
1871 <tt>include/AST/Expr*.h</tt> header. It's best to look at the class
1872 for a similar expression to get ideas, and there are some specific
1873 things to watch for:
1874 <ul>
1875 <li>If you need to allocate memory, use the <tt>ASTContext</tt>
1876 allocator to allocate memory. Never use raw <tt>malloc</tt> or
1877 <tt>new</tt>, and never hold any resources in an AST node, because
1878 the destructor of an AST node is never called.</li>
1879
1880 <li>Make sure that <tt>getSourceRange()</tt> covers the exact
1881 source range of your expression. This is needed for diagnostics
1882 and for IDE support.</li>
1883
1884 <li>Make sure that <tt>children()</tt> visits all of the
1885 subexpressions. This is important for a number of features (e.g., IDE
1886 support, C++ variadic templates). If you have sub-types, you'll
1887 also need to visit those sub-types in the
1888 <tt>RecursiveASTVisitor</tt>.</li>
1889
1890 <li>Add printing support (<tt>StmtPrinter.cpp</tt>) and dumping
1891 support (<tt>StmtDumper.cpp</tt>) for your expression.</li>
1892
1893 <li>Add profiling support (<tt>StmtProfile.cpp</tt>) for your AST
1894 node, noting the distinguishing (non-source location)
1895 characteristics of an instance of your expression. Omitting this
1896 step will lead to hard-to-diagnose failures regarding matching of
1897 template declarations.</li>
1898 </ul>
1899 </li>
1900
1901 <li>Teach semantic analysis to build your AST node! At this point,
1902 you can wire up your <tt>Sema::BuildXXX</tt> function to actually
1903 create your AST. A few things to check at this point:
1904 <ul>
1905 <li>If your expression can construct a new C++ class or return a
1906 new Objective-C object, be sure to update and then call
1907 <tt>Sema::MaybeBindToTemporary</tt> for your just-created AST node
1908 to be sure that the object gets properly destructed. An easy way
1909 to test this is to return a C++ class with a private destructor:
1910 semantic analysis should flag an error here with the attempt to
1911 call the destructor.</li>
1912 <li>Inspect the generated AST by printing it using <tt>clang -cc1
1913 -ast-print</tt>, to make sure you're capturing all of the
1914 important information about how the AST was written.</li>
1915 <li>Inspect the generated AST under <tt>clang -cc1 -ast-dump</tt>
1916 to verify that all of the types in the generated AST line up the
1917 way you want them. Remember that clients of the AST should never
1918 have to "think" to understand what's going on. For example, all
1919 implicit conversions should show up explicitly in the AST.</li>
1920 <li>Write tests that use your expression as a subexpression of
1921 other, well-known expressions. Can you call a function using your
1922 expression as an argument? Can you use the ternary operator?</li>
1923 </ul>
1924 </li>
1925
1926 <li>Teach code generation to create IR to your AST node. This step
1927 is the first (and only) that requires knowledge of LLVM IR. There
1928 are several things to keep in mind:
1929 <ul>
1930 <li>Code generation is separated into scalar/aggregate/complex and
1931 lvalue/rvalue paths, depending on what kind of result your
1932 expression produces. On occasion, this requires some careful
1933 factoring of code to avoid duplication.</li>
1934
1935 <li><tt>CodeGenFunction</tt> contains functions
1936 <tt>ConvertType</tt> and <tt>ConvertTypeForMem</tt> that convert
1937 Clang's types (<tt>clang::Type*</tt> or <tt>clang::QualType</tt>)
1938 to LLVM types.
1939 Use the former for values, and the later for memory locations:
1940 test with the C++ "bool" type to check this. If you find
1941 that you are having to use LLVM bitcasts to make
1942 the subexpressions of your expression have the type that your
1943 expression expects, STOP! Go fix semantic analysis and the AST so
1944 that you don't need these bitcasts.</li>
1945
1946 <li>The <tt>CodeGenFunction</tt> class has a number of helper
1947 functions to make certain operations easy, such as generating code
1948 to produce an lvalue or an rvalue, or to initialize a memory
1949 location with a given value. Prefer to use these functions rather
1950 than directly writing loads and stores, because these functions
1951 take care of some of the tricky details for you (e.g., for
1952 exceptions).</li>
1953
1954 <li>If your expression requires some special behavior in the event
1955 of an exception, look at the <tt>push*Cleanup</tt> functions in
1956 <tt>CodeGenFunction</tt> to introduce a cleanup. You shouldn't
1957 have to deal with exception-handling directly.</li>
1958
1959 <li>Testing is extremely important in IR generation. Use <tt>clang
1960 -cc1 -emit-llvm</tt> and <a
1961 href="http://llvm.org/cmds/FileCheck.html">FileCheck</a> to verify
1962 that you're generating the right IR.</li>
1963 </ul>
1964 </li>
1965
1966 <li>Teach template instantiation how to cope with your AST
1967 node, which requires some fairly simple code:
1968 <ul>
1969 <li>Make sure that your expression's constructor properly
1970 computes the flags for type dependence (i.e., the type your
1971 expression produces can change from one instantiation to the
1972 next), value dependence (i.e., the constant value your expression
1973 produces can change from one instantiation to the next),
Douglas Gregord1cb2dc2011-10-14 00:54:15 +00001974 instantiation dependence (i.e., a template parameter occurs
Douglas Gregor1f634c62011-09-30 21:32:37 +00001975 anywhere in your expression), and whether your expression contains
1976 a parameter pack (for variadic templates). Often, computing these
1977 flags just means combining the results from the various types and
1978 subexpressions.</li>
1979
1980 <li>Add <tt>TransformXXX</tt> and <tt>RebuildXXX</tt> functions to
1981 the
1982 <tt>TreeTransform</tt> class template in <tt>Sema</tt>.
1983 <tt>TransformXXX</tt> should (recursively) transform all of the
1984 subexpressions and types
1985 within your expression, using <tt>getDerived().TransformYYY</tt>.
1986 If all of the subexpressions and types transform without error, it
1987 will then call the <tt>RebuildXXX</tt> function, which will in
1988 turn call <tt>getSema().BuildXXX</tt> to perform semantic analysis
1989 and build your expression.</li>
1990
1991 <li>To test template instantiation, take those tests you wrote to
1992 make sure that you were type checking with type-dependent
1993 expressions and dependent types (from step #2) and instantiate
1994 those templates with various types, some of which type-check and
1995 some that don't, and test the error messages in each case.</li>
1996 </ul>
1997 </li>
1998
1999 <li>There are some "extras" that make other features work better.
2000 It's worth handling these extras to give your expression complete
2001 integration into Clang:
2002 <ul>
2003 <li>Add code completion support for your expression in
2004 <tt>SemaCodeComplete.cpp</tt>.</li>
2005
2006 <li>If your expression has types in it, or has any "interesting"
2007 features other than subexpressions, extend libclang's
2008 <tt>CursorVisitor</tt> to provide proper visitation for your
2009 expression, enabling various IDE features such as syntax
2010 highlighting, cross-referencing, and so on. The
2011 <tt>c-index-test</tt> helper program can be used to test these
2012 features.</li>
2013 </ul>
2014 </li>
2015</ol>
2016
Ted Kremenek17a295d2008-06-11 06:19:49 +00002017</div>
2018</body>
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002019</html>