blob: 91a12a93b9e9d517f38f41aeab4d81f55c2ce4be [file] [log] [blame]
Ted Kremenek17a295d2008-06-11 06:19:49 +00001<html>
2<head>
Chris Lattner552de0a2008-11-23 08:16:56 +00003<title>"Clang" CFE Internals Manual</title>
Ted Kremenek17a295d2008-06-11 06:19:49 +00004<link type="text/css" rel="stylesheet" href="../menu.css" />
5<link type="text/css" rel="stylesheet" href="../content.css" />
Sebastian Redl68168562008-11-22 22:16:45 +00006<style type="text/css">
7td {
8 vertical-align: top;
9}
10</style>
Ted Kremenek17a295d2008-06-11 06:19:49 +000011</head>
12<body>
13
14<!--#include virtual="../menu.html.incl"-->
15
16<div id="content">
Chris Lattner86920d32007-07-31 05:42:17 +000017
Chris Lattner552de0a2008-11-23 08:16:56 +000018<h1>"Clang" CFE Internals Manual</h1>
Chris Lattner86920d32007-07-31 05:42:17 +000019
20<ul>
21<li><a href="#intro">Introduction</a></li>
22<li><a href="#libsystem">LLVM System and Support Libraries</a></li>
Chris Lattner552de0a2008-11-23 08:16:56 +000023<li><a href="#libbasic">The Clang 'Basic' Library</a>
Chris Lattner86920d32007-07-31 05:42:17 +000024 <ul>
Chris Lattner62fd2782008-11-22 21:41:31 +000025 <li><a href="#Diagnostics">The Diagnostics Subsystem</a></li>
Chris Lattner86920d32007-07-31 05:42:17 +000026 <li><a href="#SourceLocation">The SourceLocation and SourceManager
27 classes</a></li>
28 </ul>
29</li>
30<li><a href="#liblex">The Lexer and Preprocessor Library</a>
31 <ul>
32 <li><a href="#Token">The Token class</a></li>
33 <li><a href="#Lexer">The Lexer class</a></li>
Chris Lattner79281252008-03-09 02:27:26 +000034 <li><a href="#TokenLexer">The TokenLexer class</a></li>
Chris Lattner86920d32007-07-31 05:42:17 +000035 <li><a href="#MultipleIncludeOpt">The MultipleIncludeOpt class</a></li>
36 </ul>
37</li>
38<li><a href="#libparse">The Parser Library</a>
39 <ul>
40 </ul>
41</li>
42<li><a href="#libast">The AST Library</a>
43 <ul>
44 <li><a href="#Type">The Type class and its subclasses</a></li>
45 <li><a href="#QualType">The QualType class</a></li>
Douglas Gregor2e1cd422008-11-17 14:58:09 +000046 <li><a href="#DeclarationName">Declaration names</a></li>
Ted Kremenek8bc05712007-10-10 23:01:43 +000047 <li><a href="#CFG">The CFG class</a></li>
Chris Lattner7bad1992008-11-16 21:48:07 +000048 <li><a href="#Constants">Constant Folding in the Clang AST</a></li>
Chris Lattner86920d32007-07-31 05:42:17 +000049 </ul>
50</li>
51</ul>
52
53
54<!-- ======================================================================= -->
55<h2 id="intro">Introduction</h2>
56<!-- ======================================================================= -->
57
58<p>This document describes some of the more important APIs and internal design
Chris Lattner552de0a2008-11-23 08:16:56 +000059decisions made in the Clang C front-end. The purpose of this document is to
Chris Lattner86920d32007-07-31 05:42:17 +000060both capture some of this high level information and also describe some of the
61design decisions behind it. This is meant for people interested in hacking on
Chris Lattner552de0a2008-11-23 08:16:56 +000062Clang, not for end-users. The description below is categorized by
Chris Lattner86920d32007-07-31 05:42:17 +000063libraries, and does not describe any of the clients of the libraries.</p>
64
65<!-- ======================================================================= -->
66<h2 id="libsystem">LLVM System and Support Libraries</h2>
67<!-- ======================================================================= -->
68
Chris Lattner552de0a2008-11-23 08:16:56 +000069<p>The LLVM libsystem library provides the basic Clang system abstraction layer,
Chris Lattner86920d32007-07-31 05:42:17 +000070which is used for file system access. The LLVM libsupport library provides many
71underlying libraries and <a
72href="http://llvm.org/docs/ProgrammersManual.html">data-structures</a>,
73 including command line option
74processing and various containers.</p>
75
76<!-- ======================================================================= -->
Chris Lattner552de0a2008-11-23 08:16:56 +000077<h2 id="libbasic">The Clang 'Basic' Library</h2>
Chris Lattner86920d32007-07-31 05:42:17 +000078<!-- ======================================================================= -->
79
80<p>This library certainly needs a better name. The 'basic' library contains a
81number of low-level utilities for tracking and manipulating source buffers,
82locations within the source buffers, diagnostics, tokens, target abstraction,
83and information about the subset of the language being compiled for.</p>
84
85<p>Part of this infrastructure is specific to C (such as the TargetInfo class),
86other parts could be reused for other non-C-based languages (SourceLocation,
87SourceManager, Diagnostics, FileManager). When and if there is future demand
88we can figure out if it makes sense to introduce a new library, move the general
89classes somewhere else, or introduce some other solution.</p>
90
91<p>We describe the roles of these classes in order of their dependencies.</p>
92
Chris Lattner62fd2782008-11-22 21:41:31 +000093
94<!-- ======================================================================= -->
95<h3 id="Diagnostics">The Diagnostics Subsystem</h3>
96<!-- ======================================================================= -->
97
98<p>The Clang Diagnostics subsystem is an important part of how the compiler
99communicates with the human. Diagnostics are the warnings and errors produced
100when the code is incorrect or dubious. In Clang, each diagnostic produced has
101(at the minimum) a unique ID, a <a href="#SourceLocation">SourceLocation</a> to
102"put the caret", an English translation associated with it, and a severity (e.g.
103<tt>WARNING</tt> or <tt>ERROR</tt>). They can also optionally include a number
104of arguments to the dianostic (which fill in "%0"'s in the string) as well as a
105number of source ranges that related to the diagnostic.</p>
106
Chris Lattner552de0a2008-11-23 08:16:56 +0000107<p>In this section, we'll be giving examples produced by the Clang command line
Chris Lattner62fd2782008-11-22 21:41:31 +0000108driver, but diagnostics can be <a href="#DiagnosticClient">rendered in many
109different ways</a> depending on how the DiagnosticClient interface is
110implemented. A representative example of a diagonstic is:</p>
111
112<pre>
113t.c:38:15: error: invalid operands to binary expression ('int *' and '_Complex float')
114 <font color="darkgreen">P = (P-42) + Gamma*4;</font>
115 <font color="blue">~~~~~~ ^ ~~~~~~~</font>
116</pre>
117
118<p>In this example, you can see the English translation, the severity (error),
119you can see the source location (the caret ("^") and file/line/column info),
120the source ranges "~~~~", arguments to the diagnostic ("int*" and "_Complex
121float"). You'll have to believe me that there is a unique ID backing the
122diagnostic :).</p>
123
124<p>Getting all of this to happen has several steps and involves many moving
125pieces, this section describes them and talks about best practices when adding
126a new diagnostic.</p>
127
128<!-- ============================ -->
129<h4>The DiagnosticKinds.def file</h4>
130<!-- ============================ -->
131
132<p>Diagnostics are created by adding an entry to the <tt><a
133href="http://llvm.org/svn/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticKinds.def"
134>DiagnosticKinds.def</a></tt> file. This file encodes the unique ID of the
135diagnostic (as an enum, the first argument), the severity of the diagnostic
136(second argument) and the English translation + format string.</p>
137
138<p>There is little sanity with the naming of the unique ID's right now. Some
139start with err_, warn_, ext_ to encode the severity into the name. Since the
140enum is referenced in the C++ code that produces the diagnostic, it is somewhat
141useful for it to be reasonably short.</p>
142
143<p>The severity of the diagnostic comes from the set {<tt>NOTE</tt>,
144<tt>WARNING</tt>, <tt>EXTENSION</tt>, <tt>EXTWARN</tt>, <tt>ERROR</tt>}. The
145<tt>ERROR</tt> severity is used for diagnostics indicating the program is never
146acceptable under any circumstances. When an error is emitted, the AST for the
147input code may not be fully built. The <tt>EXTENSION</tt> and <tt>EXTWARN</tt>
148severities are used for extensions to the language that Clang accepts. This
149means that Clang fully understands and can represent them in the AST, but we
150produce diagnostics to tell the user their code is non-portable. The difference
151is that the former are ignored by default, and the later warn by default. The
152<tt>WARNING</tt> severity is used for constructs that are valid in the currently
153selected source language but that are dubious in some way. The <tt>NOTE</tt>
154level is used to staple more information onto a previous diagnostics.</p>
155
156<p>These <em>severities</em> are mapped into a smaller set (the
157Diagnostic::Level enum, {<tt>Ignored</tt>, <tt>Note</tt>, <tt>Warning</tt>,
158<tt>Error</tt> }) of output <em>levels</em> by the diagnostics subsystem based
159on various configuration options. For example, if the user specifies
160<tt>-pedantic</tt>, <tt>EXTENSION</tt> maps to <tt>Warning</tt>, if they specify
161<tt>-pedantic-errors</tt>, it turns into <tt>Error</tt>. Clang also internally
162supports a fully fine grained mapping mechanism that allows you to map any
163diagnostic that doesn't have <tt>ERRROR</tt> severity to any output level that
164you want. This is used to implement options like <tt>-Wunused_macros</tt>,
165<tt>-Wundef</tt> etc.</p>
166
167<!-- ================= -->
168<h4>The Format String</h4>
169<!-- ================= -->
170
171<p>The format string for the diagnostic is very simple, but it has some power.
172It takes the form of a string in English with markers that indicate where and
173how arguments to the diagnostic are inserted and formatted. For example, here
174are some simple format strings:</p>
175
176<pre>
177 "binary integer literals are an extension"
178 "format string contains '\\0' within the string body"
179 "more '<b>%%</b>' conversions than data arguments"
Chris Lattner545b3682008-11-23 20:27:13 +0000180 "invalid operands to binary expression (<b>%0</b> and <b>%1</b>)"
Chris Lattner62fd2782008-11-22 21:41:31 +0000181 "overloaded '<b>%0</b>' must be a <b>%select{unary|binary|unary or binary}2</b> operator"
182 " (has <b>%1</b> parameter<b>%s1</b>)"
183</pre>
184
185<p>These examples show some important points of format strings. You can use any
186 plain ASCII character in the diagnostic string except "%" without a problem,
187 but these are C strings, so you have to use and be aware of all the C escape
188 sequences (as in the second example). If you want to produce a "%" in the
189 output, use the "%%" escape sequence, like the third diagnostic. Finally,
Chris Lattner552de0a2008-11-23 08:16:56 +0000190 Clang uses the "%...[digit]" sequences to specify where and how arguments to
Chris Lattner62fd2782008-11-22 21:41:31 +0000191 the diagnostic are formatted.</p>
192
193<p>Arguments to the diagnostic are numbered according to how they are specified
194 by the C++ code that <a href="#producingdiag">produces them</a>, and are
195 referenced by <tt>%0</tt> .. <tt>%9</tt>. If you have more than 10 arguments
Chris Lattner552de0a2008-11-23 08:16:56 +0000196 to your diagnostic, you are doing something wrong :). Unlike printf, there
Chris Lattner62fd2782008-11-22 21:41:31 +0000197 is no requirement that arguments to the diagnostic end up in the output in
198 the same order as they are specified, you could have a format string with
199 <tt>"%1 %0"</tt> that swaps them, for example. The text in between the
200 percent and digit are formatting instructions. If there are no instructions,
201 the argument is just turned into a string and substituted in.</p>
202
203<p>Here are some "best practices" for writing the English format string:</p>
204
205<ul>
206<li>Keep the string short. It should ideally fit in the 80 column limit of the
207 <tt>DiagnosticKinds.def</tt> file. This avoids the diagnostic wrapping when
208 printed, and forces you to think about the important point you are conveying
209 with the diagnostic.</li>
210<li>Take advantage of location information. The user will be able to see the
211 line and location of the caret, so you don't need to tell them that the
212 problem is with the 4th argument to the function: just point to it.</li>
213<li>Do not capitalize the diagnostic string, and do not end it with a
214 period.</li>
215<li>If you need to quote something in the diagnostic string, use single
216 quotes.</li>
217</ul>
218
219<p>Diagnostics should never take random English strings as arguments: you
220shouldn't use <tt>"you have a problem with %0"</tt> and pass in things like
221<tt>"your argument"</tt> or <tt>"your return value"</tt> as arguments. Doing
222this prevents <a href="translation">translating</a> the Clang diagnostics to
223other languages (because they'll get random English words in their otherwise
224localized diagnostic). The exceptions to this are C/C++ language keywords
225(e.g. auto, const, mutable, etc) and C/C++ operators (<tt>/=</tt>). Note
226that things like "pointer" and "reference" are not keywords. On the other
227hand, you <em>can</em> include anything that comes from the user's source code,
Chris Lattner552de0a2008-11-23 08:16:56 +0000228including variable names, types, labels, etc. The 'select' format can be
229used to achieve this sort of thing in a localizable way, see below.</p>
Chris Lattner62fd2782008-11-22 21:41:31 +0000230
231<!-- ==================================== -->
232<h4>Formatting a Diagnostic Argument</a></h4>
233<!-- ==================================== -->
234
235<p>Arguments to diagnostics are fully typed internally, and come from a couple
236different classes: integers, types, names, and random strings. Depending on
237the class of the argument, it can be optionally formatted in different ways.
238This gives the DiagnosticClient information about what the argument means
239without requiring it to use a specific presentation (consider this MVC for
240Clang :).</p>
241
242<p>Here are the different diagnostic argument formats currently supported by
243Clang:</p>
244
245<table>
246<tr><td colspan="2"><b>"s" format</b></td></tr>
247<tr><td>Example:</td><td><tt>"requires %1 parameter%s1"</tt></td></tr>
Chris Lattner552de0a2008-11-23 08:16:56 +0000248<tr><td>Class:</td><td>Integers</td></tr>
Chris Lattner62fd2782008-11-22 21:41:31 +0000249<tr><td>Description:</td><td>This is a simple formatter for integers that is
250 useful when producing English diagnostics. When the integer is 1, it prints
251 as nothing. When the integer is not 1, it prints as "s". This allows some
Chris Lattner627b7052008-11-23 00:28:33 +0000252 simple grammatical forms to be to be handled correctly, and eliminates the
253 need to use gross things like <tt>"requires %1 parameter(s)"</tt>.</td></tr>
Chris Lattner62fd2782008-11-22 21:41:31 +0000254
255<tr><td colspan="2"><b>"select" format</b></td></tr>
256<tr><td>Example:</td><td><tt>"must be a %select{unary|binary|unary or binary}2
257 operator"</tt></td></tr>
Chris Lattner552de0a2008-11-23 08:16:56 +0000258<tr><td>Class:</td><td>Integers</td></tr>
Chris Lattnercc543342008-11-22 23:50:47 +0000259<tr><td>Description:</td><td>This format specifier is used to merge multiple
260 related diagnostics together into one common one, without requiring the
Chris Lattner552de0a2008-11-23 08:16:56 +0000261 difference to be specified as an English string argument. Instead of
Chris Lattnercc543342008-11-22 23:50:47 +0000262 specifying the string, the diagnostic gets an integer argument and the
263 format string selects the numbered option. In this case, the "%2" value
264 must be an integer in the range [0..2]. If it is 0, it prints 'unary', if
265 it is 1 it prints 'binary' if it is 2, it prints 'unary or binary'. This
266 allows other language translations to substitute reasonable words (or entire
267 phrases) based on the semantics of the diagnostic instead of having to do
268 things textually.</td></tr>
Chris Lattner62fd2782008-11-22 21:41:31 +0000269
270<tr><td colspan="2"><b>"plural" format</b></td></tr>
Sebastian Redl68168562008-11-22 22:16:45 +0000271<tr><td>Example:</td><td><tt>"you have %1 %plural{1:mouse|:mice}1 connected to
272 your computer"</tt></td></tr>
Chris Lattner552de0a2008-11-23 08:16:56 +0000273<tr><td>Class:</td><td>Integers</td></tr>
Sebastian Redl68168562008-11-22 22:16:45 +0000274<tr><td>Description:</td><td><p>This is a formatter for complex plural forms.
275 It is designed to handle even the requirements of languages with very
276 complex plural forms, as many Baltic languages have. The argument consists
277 of a series of expression/form pairs, separated by ':', where the first form
278 whose expression evaluates to true is the result of the modifier.</p>
279 <p>An expression can be empty, in which case it is always true. See the
280 example at the top. Otherwise, it is a series of one or more numeric
281 conditions, separated by ','. If any condition matches, the expression
282 matches. Each numeric condition can take one of three forms.</p>
283 <ul>
284 <li>number: A simple decimal number matches if the argument is the same
Chris Lattner627b7052008-11-23 00:28:33 +0000285 as the number. Example: <tt>"%plural{1:mouse|:mice}4"</tt></li>
Sebastian Redl68168562008-11-22 22:16:45 +0000286 <li>range: A range in square brackets matches if the argument is within
Chris Lattner552de0a2008-11-23 08:16:56 +0000287 the range. Then range is inclusive on both ends. Example:
Chris Lattner627b7052008-11-23 00:28:33 +0000288 <tt>"%plural{0:none|1:one|[2,5]:some|:many}2"</tt></li>
289 <li>modulo: A modulo operator is followed by a number, and
290 equals sign and either a number or a range. The tests are the
291 same as for plain
Sebastian Redl68168562008-11-22 22:16:45 +0000292 numbers and ranges, but the argument is taken modulo the number first.
Chris Lattner627b7052008-11-23 00:28:33 +0000293 Example: <tt>"%plural{%100=0:even hundred|%100=[1,50]:lower half|:everything
294 else}1"</tt></li>
Sebastian Redl68168562008-11-22 22:16:45 +0000295 </ul>
296 <p>The parser is very unforgiving. A syntax error, even whitespace, will
297 abort, as will a failure to match the argument against any
298 expression.</p></td></tr>
Chris Lattner62fd2782008-11-22 21:41:31 +0000299
Chris Lattner62fd2782008-11-22 21:41:31 +0000300</table>
301
Chris Lattnercc543342008-11-22 23:50:47 +0000302<p>It is really easy to add format specifiers to the Clang diagnostics system,
Chris Lattner552de0a2008-11-23 08:16:56 +0000303but they should be discussed before they are added. If you are creating a lot
304of repetitive diagnostics and/or have an idea for a useful formatter, please
305bring it up on the cfe-dev mailing list.</p>
Chris Lattnercc543342008-11-22 23:50:47 +0000306
Chris Lattner62fd2782008-11-22 21:41:31 +0000307<!-- ===================================================== -->
308<h4><a name="#producingdiag">Producing the Diagnostic</a></h4>
309<!-- ===================================================== -->
310
Chris Lattner627b7052008-11-23 00:28:33 +0000311<p>Now that you've created the diagnostic in the DiagnosticKinds.def file, you
Chris Lattner552de0a2008-11-23 08:16:56 +0000312need to write the code that detects the condition in question and emits the
313new diagnostic. Various components of Clang (e.g. the preprocessor, Sema,
Chris Lattner627b7052008-11-23 00:28:33 +0000314etc) provide a helper function named "Diag". It creates a diagnostic and
315accepts the arguments, ranges, and other information that goes along with
316it.</p>
Chris Lattner62fd2782008-11-22 21:41:31 +0000317
Chris Lattner552de0a2008-11-23 08:16:56 +0000318<p>For example, the binary expression error comes from code like this:</p>
Chris Lattner627b7052008-11-23 00:28:33 +0000319
320<pre>
321 if (various things that are bad)
322 Diag(Loc, diag::err_typecheck_invalid_operands)
323 &lt;&lt; lex-&gt;getType() &lt;&lt; rex-&gt;getType()
324 &lt;&lt; lex-&gt;getSourceRange() &lt;&lt; rex-&gt;getSourceRange();
325</pre>
326
327<p>This shows that use of the Diag method: they take a location (a <a
328href="#SourceLocation">SourceLocation</a> object) and a diagnostic enum value
329(which matches the name from DiagnosticKinds.def). If the diagnostic takes
330arguments, they are specified with the &lt;&lt; operator: the first argument
331becomes %0, the second becomes %1, etc. The diagnostic interface allows you to
Chris Lattnerfd408ea2008-11-23 00:42:53 +0000332specify arguments of many different types, including <tt>int</tt> and
333<tt>unsigned</tt> for integer arguments, <tt>const char*</tt> and
334<tt>std::string</tt> for string arguments, <tt>DeclarationName</tt> and
335<tt>const IdentifierInfo*</tt> for names, <tt>QualType</tt> for types, etc.
336SourceRanges are also specified with the &lt;&lt; operator, but do not have a
337specific ordering requirement.</p>
Chris Lattner627b7052008-11-23 00:28:33 +0000338
339<p>As you can see, adding and producing a diagnostic is pretty straightforward.
340The hard part is deciding exactly what you need to say to help the user, picking
341a suitable wording, and providing the information needed to format it correctly.
Chris Lattnerfd408ea2008-11-23 00:42:53 +0000342The good news is that the call site that issues a diagnostic should be
343completely independent of how the diagnostic is formatted and in what language
344it is rendered.
Chris Lattner627b7052008-11-23 00:28:33 +0000345</p>
Chris Lattner62fd2782008-11-22 21:41:31 +0000346
347<!-- ============================================================= -->
348<h4><a name="DiagnosticClient">The DiagnosticClient Interface</a></h4>
349<!-- ============================================================= -->
350
Chris Lattner627b7052008-11-23 00:28:33 +0000351<p>Once code generates a diagnostic with all of the arguments and the rest of
352the relevant information, Clang needs to know what to do with it. As previously
353mentioned, the diagnostic machinery goes through some filtering to map a
354severity onto a diagnostic level, then (assuming the diagnostic is not mapped to
355"<tt>Ignore</tt>") it invokes an object that implements the DiagnosticClient
356interface with the information.</p>
357
358<p>It is possible to implement this interface in many different ways. For
359example, the normal Clang DiagnosticClient (named 'TextDiagnosticPrinter') turns
360the arguments into strings (according to the various formatting rules), prints
361out the file/line/column information and the string, then prints out the line of
362code, the source ranges, and the caret. However, this behavior isn't required.
363</p>
364
365<p>Another implementation of the DiagnosticClient interface is the
Chris Lattner552de0a2008-11-23 08:16:56 +0000366'TextDiagnosticBuffer' class, which is used when Clang is in -verify mode.
Chris Lattnerfd408ea2008-11-23 00:42:53 +0000367Instead of formatting and printing out the diagnostics, this implementation just
368captures and remembers the diagnostics as they fly by. Then -verify compares
Chris Lattner552de0a2008-11-23 08:16:56 +0000369the list of produced diagnostics to the list of expected ones. If they disagree,
Chris Lattnerfd408ea2008-11-23 00:42:53 +0000370it prints out its own output.
Chris Lattner627b7052008-11-23 00:28:33 +0000371</p>
372
Chris Lattnerfd408ea2008-11-23 00:42:53 +0000373<p>There are many other possible implementations of this interface, and this is
374why we prefer diagnostics to pass down rich structured information in arguments.
375For example, an HTML output might want declaration names be linkified to where
376they come from in the source. Another example is that a GUI might let you click
377on typedefs to expand them. This application would want to pass significantly
378more information about types through to the GUI than a simple flat string. The
379interface allows this to happen.</p>
Chris Lattner62fd2782008-11-22 21:41:31 +0000380
381<!-- ====================================================== -->
382<h4><a name="translation">Adding Translations to Clang</a></h4>
383<!-- ====================================================== -->
384
Chris Lattner627b7052008-11-23 00:28:33 +0000385<p>Not possible yet! Diagnostic strings should be written in UTF-8, the client
Chris Lattnerfd408ea2008-11-23 00:42:53 +0000386can translate to the relevant code page if needed. Each translation completely
387replaces the format string for the diagnostic.</p>
Chris Lattner62fd2782008-11-22 21:41:31 +0000388
389
Chris Lattner86920d32007-07-31 05:42:17 +0000390<!-- ======================================================================= -->
391<h3 id="SourceLocation">The SourceLocation and SourceManager classes</h3>
392<!-- ======================================================================= -->
393
394<p>Strangely enough, the SourceLocation class represents a location within the
395source code of the program. Important design points include:</p>
396
397<ol>
398<li>sizeof(SourceLocation) must be extremely small, as these are embedded into
399 many AST nodes and are passed around often. Currently it is 32 bits.</li>
400<li>SourceLocation must be a simple value object that can be efficiently
401 copied.</li>
402<li>We should be able to represent a source location for any byte of any input
403 file. This includes in the middle of tokens, in whitespace, in trigraphs,
404 etc.</li>
405<li>A SourceLocation must encode the current #include stack that was active when
406 the location was processed. For example, if the location corresponds to a
407 token, it should contain the set of #includes active when the token was
408 lexed. This allows us to print the #include stack for a diagnostic.</li>
409<li>SourceLocation must be able to describe macro expansions, capturing both
410 the ultimate instantiation point and the source of the original character
411 data.</li>
412</ol>
413
414<p>In practice, the SourceLocation works together with the SourceManager class
415to encode two pieces of information about a location: it's physical location
416and it's virtual location. For most tokens, these will be the same. However,
417for a macro expansion (or tokens that came from a _Pragma directive) these will
418describe the location of the characters corresponding to the token and the
419location where the token was used (i.e. the macro instantiation point or the
420location of the _Pragma itself).</p>
421
Chris Lattner3fcbb892008-11-23 08:32:53 +0000422<p>For efficiency, we only track one level of macro instantiations: if a token was
Chris Lattner86920d32007-07-31 05:42:17 +0000423produced by multiple instantiations, we only track the source and ultimate
424destination. Though we could track the intermediate instantiation points, this
425would require extra bookkeeping and no known client would benefit substantially
426from this.</p>
427
Chris Lattner552de0a2008-11-23 08:16:56 +0000428<p>The Clang front-end inherently depends on the location of a token being
Chris Lattner86920d32007-07-31 05:42:17 +0000429tracked correctly. If it is ever incorrect, the front-end may get confused and
430die. The reason for this is that the notion of the 'spelling' of a Token in
Chris Lattner552de0a2008-11-23 08:16:56 +0000431Clang depends on being able to find the original input characters for the token.
Chris Lattner86920d32007-07-31 05:42:17 +0000432This concept maps directly to the "physical" location for the token.</p>
433
434<!-- ======================================================================= -->
435<h2 id="liblex">The Lexer and Preprocessor Library</h2>
436<!-- ======================================================================= -->
437
438<p>The Lexer library contains several tightly-connected classes that are involved
439with the nasty process of lexing and preprocessing C source code. The main
440interface to this library for outside clients is the large <a
441href="#Preprocessor">Preprocessor</a> class.
442It contains the various pieces of state that are required to coherently read
443tokens out of a translation unit.</p>
444
445<p>The core interface to the Preprocessor object (once it is set up) is the
446Preprocessor::Lex method, which returns the next <a href="#Token">Token</a> from
447the preprocessor stream. There are two types of token providers that the
448preprocessor is capable of reading from: a buffer lexer (provided by the <a
449href="#Lexer">Lexer</a> class) and a buffered token stream (provided by the <a
Chris Lattner79281252008-03-09 02:27:26 +0000450href="#TokenLexer">TokenLexer</a> class).
Chris Lattner86920d32007-07-31 05:42:17 +0000451
452
453<!-- ======================================================================= -->
454<h3 id="Token">The Token class</h3>
455<!-- ======================================================================= -->
456
457<p>The Token class is used to represent a single lexed token. Tokens are
458intended to be used by the lexer/preprocess and parser libraries, but are not
459intended to live beyond them (for example, they should not live in the ASTs).<p>
460
461<p>Tokens most often live on the stack (or some other location that is efficient
462to access) as the parser is running, but occasionally do get buffered up. For
463example, macro definitions are stored as a series of tokens, and the C++
Chris Lattner3fcbb892008-11-23 08:32:53 +0000464front-end periodically needs to buffer tokens up for tentative parsing and
Chris Lattner86920d32007-07-31 05:42:17 +0000465various pieces of look-ahead. As such, the size of a Token matter. On a 32-bit
466system, sizeof(Token) is currently 16 bytes.</p>
467
468<p>Tokens contain the following information:</p>
469
470<ul>
471<li><b>A SourceLocation</b> - This indicates the location of the start of the
472token.</li>
473
474<li><b>A length</b> - This stores the length of the token as stored in the
475SourceBuffer. For tokens that include them, this length includes trigraphs and
476escaped newlines which are ignored by later phases of the compiler. By pointing
477into the original source buffer, it is always possible to get the original
478spelling of a token completely accurately.</li>
479
480<li><b>IdentifierInfo</b> - If a token takes the form of an identifier, and if
481identifier lookup was enabled when the token was lexed (e.g. the lexer was not
482reading in 'raw' mode) this contains a pointer to the unique hash value for the
483identifier. Because the lookup happens before keyword identification, this
484field is set even for language keywords like 'for'.</li>
485
486<li><b>TokenKind</b> - This indicates the kind of token as classified by the
487lexer. This includes things like <tt>tok::starequal</tt> (for the "*="
488operator), <tt>tok::ampamp</tt> for the "&amp;&amp;" token, and keyword values
489(e.g. <tt>tok::kw_for</tt>) for identifiers that correspond to keywords. Note
490that some tokens can be spelled multiple ways. For example, C++ supports
491"operator keywords", where things like "and" are treated exactly like the
492"&amp;&amp;" operator. In these cases, the kind value is set to
493<tt>tok::ampamp</tt>, which is good for the parser, which doesn't have to
494consider both forms. For something that cares about which form is used (e.g.
495the preprocessor 'stringize' operator) the spelling indicates the original
496form.</li>
497
498<li><b>Flags</b> - There are currently four flags tracked by the
499lexer/preprocessor system on a per-token basis:
500
501 <ol>
502 <li><b>StartOfLine</b> - This was the first token that occurred on its input
503 source line.</li>
504 <li><b>LeadingSpace</b> - There was a space character either immediately
505 before the token or transitively before the token as it was expanded
506 through a macro. The definition of this flag is very closely defined by
507 the stringizing requirements of the preprocessor.</li>
508 <li><b>DisableExpand</b> - This flag is used internally to the preprocessor to
509 represent identifier tokens which have macro expansion disabled. This
510 prevents them from being considered as candidates for macro expansion ever
511 in the future.</li>
512 <li><b>NeedsCleaning</b> - This flag is set if the original spelling for the
513 token includes a trigraph or escaped newline. Since this is uncommon,
514 many pieces of code can fast-path on tokens that did not need cleaning.
515 </p>
516 </ol>
517</li>
518</ul>
519
520<p>One interesting (and somewhat unusual) aspect of tokens is that they don't
521contain any semantic information about the lexed value. For example, if the
522token was a pp-number token, we do not represent the value of the number that
523was lexed (this is left for later pieces of code to decide). Additionally, the
524lexer library has no notion of typedef names vs variable names: both are
525returned as identifiers, and the parser is left to decide whether a specific
526identifier is a typedef or a variable (tracking this requires scope information
527among other things).</p>
528
529<!-- ======================================================================= -->
530<h3 id="Lexer">The Lexer class</h3>
531<!-- ======================================================================= -->
532
533<p>The Lexer class provides the mechanics of lexing tokens out of a source
534buffer and deciding what they mean. The Lexer is complicated by the fact that
535it operates on raw buffers that have not had spelling eliminated (this is a
536necessity to get decent performance), but this is countered with careful coding
537as well as standard performance techniques (for example, the comment handling
538code is vectorized on X86 and PowerPC hosts).</p>
539
540<p>The lexer has a couple of interesting modal features:</p>
541
542<ul>
543<li>The lexer can operate in 'raw' mode. This mode has several features that
544 make it possible to quickly lex the file (e.g. it stops identifier lookup,
545 doesn't specially handle preprocessor tokens, handles EOF differently, etc).
546 This mode is used for lexing within an "<tt>#if 0</tt>" block, for
547 example.</li>
548<li>The lexer can capture and return comments as tokens. This is required to
549 support the -C preprocessor mode, which passes comments through, and is
550 used by the diagnostic checker to identifier expect-error annotations.</li>
551<li>The lexer can be in ParsingFilename mode, which happens when preprocessing
Chris Lattner84386242007-09-16 19:25:23 +0000552 after reading a #include directive. This mode changes the parsing of '&lt;'
Chris Lattner86920d32007-07-31 05:42:17 +0000553 to return an "angled string" instead of a bunch of tokens for each thing
554 within the filename.</li>
555<li>When parsing a preprocessor directive (after "<tt>#</tt>") the
556 ParsingPreprocessorDirective mode is entered. This changes the parser to
557 return EOM at a newline.</li>
558<li>The Lexer uses a LangOptions object to know whether trigraphs are enabled,
559 whether C++ or ObjC keywords are recognized, etc.</li>
560</ul>
561
562<p>In addition to these modes, the lexer keeps track of a couple of other
563 features that are local to a lexed buffer, which change as the buffer is
564 lexed:</p>
565
566<ul>
567<li>The Lexer uses BufferPtr to keep track of the current character being
568 lexed.</li>
569<li>The Lexer uses IsAtStartOfLine to keep track of whether the next lexed token
570 will start with its "start of line" bit set.</li>
571<li>The Lexer keeps track of the current #if directives that are active (which
572 can be nested).</li>
573<li>The Lexer keeps track of an <a href="#MultipleIncludeOpt">
574 MultipleIncludeOpt</a> object, which is used to
575 detect whether the buffer uses the standard "<tt>#ifndef XX</tt> /
576 <tt>#define XX</tt>" idiom to prevent multiple inclusion. If a buffer does,
577 subsequent includes can be ignored if the XX macro is defined.</li>
578</ul>
579
580<!-- ======================================================================= -->
Chris Lattner79281252008-03-09 02:27:26 +0000581<h3 id="TokenLexer">The TokenLexer class</h3>
Chris Lattner86920d32007-07-31 05:42:17 +0000582<!-- ======================================================================= -->
583
Chris Lattner79281252008-03-09 02:27:26 +0000584<p>The TokenLexer class is a token provider that returns tokens from a list
Chris Lattner86920d32007-07-31 05:42:17 +0000585of tokens that came from somewhere else. It typically used for two things: 1)
586returning tokens from a macro definition as it is being expanded 2) returning
587tokens from an arbitrary buffer of tokens. The later use is used by _Pragma and
588will most likely be used to handle unbounded look-ahead for the C++ parser.</p>
589
590<!-- ======================================================================= -->
591<h3 id="MultipleIncludeOpt">The MultipleIncludeOpt class</h3>
592<!-- ======================================================================= -->
593
594<p>The MultipleIncludeOpt class implements a really simple little state machine
595that is used to detect the standard "<tt>#ifndef XX</tt> / <tt>#define XX</tt>"
596idiom that people typically use to prevent multiple inclusion of headers. If a
597buffer uses this idiom and is subsequently #include'd, the preprocessor can
598simply check to see whether the guarding condition is defined or not. If so,
599the preprocessor can completely ignore the include of the header.</p>
600
601
602
603<!-- ======================================================================= -->
604<h2 id="libparse">The Parser Library</h2>
605<!-- ======================================================================= -->
606
607<!-- ======================================================================= -->
608<h2 id="libast">The AST Library</h2>
609<!-- ======================================================================= -->
610
611<!-- ======================================================================= -->
612<h3 id="Type">The Type class and its subclasses</h3>
613<!-- ======================================================================= -->
614
615<p>The Type class (and its subclasses) are an important part of the AST. Types
616are accessed through the ASTContext class, which implicitly creates and uniques
617them as they are needed. Types have a couple of non-obvious features: 1) they
618do not capture type qualifiers like const or volatile (See
619<a href="#QualType">QualType</a>), and 2) they implicitly capture typedef
Chris Lattner8a2bc622007-07-31 06:37:39 +0000620information. Once created, types are immutable (unlike decls).</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000621
622<p>Typedefs in C make semantic analysis a bit more complex than it would
623be without them. The issue is that we want to capture typedef information
624and represent it in the AST perfectly, but the semantics of operations need to
625"see through" typedefs. For example, consider this code:</p>
626
627<code>
628void func() {<br>
Bill Wendling30d17752007-10-06 01:56:01 +0000629&nbsp;&nbsp;typedef int foo;<br>
630&nbsp;&nbsp;foo X, *Y;<br>
631&nbsp;&nbsp;typedef foo* bar;<br>
632&nbsp;&nbsp;bar Z;<br>
633&nbsp;&nbsp;*X; <i>// error</i><br>
634&nbsp;&nbsp;**Y; <i>// error</i><br>
635&nbsp;&nbsp;**Z; <i>// error</i><br>
Chris Lattner86920d32007-07-31 05:42:17 +0000636}<br>
637</code>
638
639<p>The code above is illegal, and thus we expect there to be diagnostics emitted
640on the annotated lines. In this example, we expect to get:</p>
641
642<pre>
Chris Lattner8a2bc622007-07-31 06:37:39 +0000643<b>test.c:6:1: error: indirection requires pointer operand ('foo' invalid)</b>
Chris Lattner86920d32007-07-31 05:42:17 +0000644*X; // error
645<font color="blue">^~</font>
Chris Lattner8a2bc622007-07-31 06:37:39 +0000646<b>test.c:7:1: error: indirection requires pointer operand ('foo' invalid)</b>
Chris Lattner86920d32007-07-31 05:42:17 +0000647**Y; // error
648<font color="blue">^~~</font>
Chris Lattner8a2bc622007-07-31 06:37:39 +0000649<b>test.c:8:1: error: indirection requires pointer operand ('foo' invalid)</b>
650**Z; // error
651<font color="blue">^~~</font>
Chris Lattner86920d32007-07-31 05:42:17 +0000652</pre>
653
654<p>While this example is somewhat silly, it illustrates the point: we want to
655retain typedef information where possible, so that we can emit errors about
656"<tt>std::string</tt>" instead of "<tt>std::basic_string&lt;char, std:...</tt>".
657Doing this requires properly keeping typedef information (for example, the type
658of "X" is "foo", not "int"), and requires properly propagating it through the
Chris Lattner8a2bc622007-07-31 06:37:39 +0000659various operators (for example, the type of *Y is "foo", not "int"). In order
660to retain this information, the type of these expressions is an instance of the
661TypedefType class, which indicates that the type of these expressions is a
662typedef for foo.
663</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000664
Chris Lattner8a2bc622007-07-31 06:37:39 +0000665<p>Representing types like this is great for diagnostics, because the
666user-specified type is always immediately available. There are two problems
667with this: first, various semantic checks need to make judgements about the
Chris Lattner33fc68a2007-07-31 18:54:50 +0000668<em>actual structure</em> of a type, ignoring typdefs. Second, we need an
669efficient way to query whether two types are structurally identical to each
670other, ignoring typedefs. The solution to both of these problems is the idea of
Chris Lattner8a2bc622007-07-31 06:37:39 +0000671canonical types.</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000672
Chris Lattner62fd2782008-11-22 21:41:31 +0000673<!-- =============== -->
Chris Lattner8a2bc622007-07-31 06:37:39 +0000674<h4>Canonical Types</h4>
Chris Lattner62fd2782008-11-22 21:41:31 +0000675<!-- =============== -->
Chris Lattner86920d32007-07-31 05:42:17 +0000676
Chris Lattner8a2bc622007-07-31 06:37:39 +0000677<p>Every instance of the Type class contains a canonical type pointer. For
678simple types with no typedefs involved (e.g. "<tt>int</tt>", "<tt>int*</tt>",
679"<tt>int**</tt>"), the type just points to itself. For types that have a
680typedef somewhere in their structure (e.g. "<tt>foo</tt>", "<tt>foo*</tt>",
681"<tt>foo**</tt>", "<tt>bar</tt>"), the canonical type pointer points to their
682structurally equivalent type without any typedefs (e.g. "<tt>int</tt>",
683"<tt>int*</tt>", "<tt>int**</tt>", and "<tt>int*</tt>" respectively).</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000684
Chris Lattner8a2bc622007-07-31 06:37:39 +0000685<p>This design provides a constant time operation (dereferencing the canonical
686type pointer) that gives us access to the structure of types. For example,
687we can trivially tell that "bar" and "foo*" are the same type by dereferencing
688their canonical type pointers and doing a pointer comparison (they both point
689to the single "<tt>int*</tt>" type).</p>
690
691<p>Canonical types and typedef types bring up some complexities that must be
692carefully managed. Specifically, the "isa/cast/dyncast" operators generally
693shouldn't be used in code that is inspecting the AST. For example, when type
694checking the indirection operator (unary '*' on a pointer), the type checker
695must verify that the operand has a pointer type. It would not be correct to
696check that with "<tt>isa&lt;PointerType&gt;(SubExpr-&gt;getType())</tt>",
697because this predicate would fail if the subexpression had a typedef type.</p>
698
699<p>The solution to this problem are a set of helper methods on Type, used to
700check their properties. In this case, it would be correct to use
701"<tt>SubExpr-&gt;getType()-&gt;isPointerType()</tt>" to do the check. This
702predicate will return true if the <em>canonical type is a pointer</em>, which is
703true any time the type is structurally a pointer type. The only hard part here
704is remembering not to use the <tt>isa/cast/dyncast</tt> operations.</p>
705
706<p>The second problem we face is how to get access to the pointer type once we
707know it exists. To continue the example, the result type of the indirection
708operator is the pointee type of the subexpression. In order to determine the
709type, we need to get the instance of PointerType that best captures the typedef
710information in the program. If the type of the expression is literally a
711PointerType, we can return that, otherwise we have to dig through the
712typedefs to find the pointer type. For example, if the subexpression had type
713"<tt>foo*</tt>", we could return that type as the result. If the subexpression
714had type "<tt>bar</tt>", we want to return "<tt>foo*</tt>" (note that we do
715<em>not</em> want "<tt>int*</tt>"). In order to provide all of this, Type has
Chris Lattner11406c12007-07-31 16:50:51 +0000716a getAsPointerType() method that checks whether the type is structurally a
Chris Lattner8a2bc622007-07-31 06:37:39 +0000717PointerType and, if so, returns the best one. If not, it returns a null
718pointer.</p>
719
720<p>This structure is somewhat mystical, but after meditating on it, it will
721make sense to you :).</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000722
723<!-- ======================================================================= -->
724<h3 id="QualType">The QualType class</h3>
725<!-- ======================================================================= -->
726
727<p>The QualType class is designed as a trivial value class that is small,
728passed by-value and is efficient to query. The idea of QualType is that it
729stores the type qualifiers (const, volatile, restrict) separately from the types
730themselves: QualType is conceptually a pair of "Type*" and bits for the type
731qualifiers.</p>
732
733<p>By storing the type qualifiers as bits in the conceptual pair, it is
734extremely efficient to get the set of qualifiers on a QualType (just return the
735field of the pair), add a type qualifier (which is a trivial constant-time
736operation that sets a bit), and remove one or more type qualifiers (just return
737a QualType with the bitfield set to empty).</p>
738
739<p>Further, because the bits are stored outside of the type itself, we do not
740need to create duplicates of types with different sets of qualifiers (i.e. there
741is only a single heap allocated "int" type: "const int" and "volatile const int"
742both point to the same heap allocated "int" type). This reduces the heap size
743used to represent bits and also means we do not have to consider qualifiers when
744uniquing types (<a href="#Type">Type</a> does not even contain qualifiers).</p>
745
746<p>In practice, on hosts where it is safe, the 3 type qualifiers are stored in
747the low bit of the pointer to the Type object. This means that QualType is
748exactly the same size as a pointer, and this works fine on any system where
749malloc'd objects are at least 8 byte aligned.</p>
Ted Kremenek8bc05712007-10-10 23:01:43 +0000750
751<!-- ======================================================================= -->
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000752<h3 id="DeclarationName">Declaration names</h3>
753<!-- ======================================================================= -->
754
755<p>The <tt>DeclarationName</tt> class represents the name of a
756 declaration in Clang. Declarations in the C family of languages can
Chris Lattner3fcbb892008-11-23 08:32:53 +0000757 take several different forms. Most declarations are named by
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000758 simple identifiers, e.g., "<code>f</code>" and "<code>x</code>" in
759 the function declaration <code>f(int x)</code>. In C++, declaration
760 names can also name class constructors ("<code>Class</code>"
761 in <code>struct Class { Class(); }</code>), class destructors
762 ("<code>~Class</code>"), overloaded operator names ("operator+"),
763 and conversion functions ("<code>operator void const *</code>"). In
764 Objective-C, declaration names can refer to the names of Objective-C
765 methods, which involve the method name and the parameters,
Chris Lattner3fcbb892008-11-23 08:32:53 +0000766 collectively called a <i>selector</i>, e.g.,
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000767 "<code>setWidth:height:</code>". Since all of these kinds of
Chris Lattner3fcbb892008-11-23 08:32:53 +0000768 entities - variables, functions, Objective-C methods, C++
769 constructors, destructors, and operators - are represented as
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000770 subclasses of Clang's common <code>NamedDecl</code>
771 class, <code>DeclarationName</code> is designed to efficiently
772 represent any kind of name.</p>
773
774<p>Given
775 a <code>DeclarationName</code> <code>N</code>, <code>N.getNameKind()</code>
Douglas Gregor2def4832008-11-17 20:34:05 +0000776 will produce a value that describes what kind of name <code>N</code>
Douglas Gregore94ca9e42008-11-18 14:39:36 +0000777 stores. There are 8 options (all of the names are inside
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000778 the <code>DeclarationName</code> class)</p>
779<dl>
780 <dt>Identifier</dt>
781 <dd>The name is a simple
782 identifier. Use <code>N.getAsIdentifierInfo()</code> to retrieve the
783 corresponding <code>IdentifierInfo*</code> pointing to the actual
784 identifier. Note that C++ overloaded operators (e.g.,
785 "<code>operator+</code>") are represented as special kinds of
786 identifiers. Use <code>IdentifierInfo</code>'s <code>getOverloadedOperatorID</code>
787 function to determine whether an identifier is an overloaded
788 operator name.</dd>
789
790 <dt>ObjCZeroArgSelector, ObjCOneArgSelector,
791 ObjCMultiArgSelector</dt>
792 <dd>The name is an Objective-C selector, which can be retrieved as a
793 <code>Selector</code> instance
794 via <code>N.getObjCSelector()</code>. The three possible name
795 kinds for Objective-C reflect an optimization within
796 the <code>DeclarationName</code> class: both zero- and
797 one-argument selectors are stored as a
798 masked <code>IdentifierInfo</code> pointer, and therefore require
799 very little space, since zero- and one-argument selectors are far
800 more common than multi-argument selectors (which use a different
801 structure).</dd>
802
803 <dt>CXXConstructorName</dt>
804 <dd>The name is a C++ constructor
805 name. Use <code>N.getCXXNameType()</code> to retrieve
806 the <a href="#QualType">type</a> that this constructor is meant to
807 construct. The type is always the canonical type, since all
808 constructors for a given type have the same name.</dd>
809
810 <dt>CXXDestructorName</dt>
811 <dd>The name is a C++ destructor
812 name. Use <code>N.getCXXNameType()</code> to retrieve
813 the <a href="#QualType">type</a> whose destructor is being
814 named. This type is always a canonical type.</dd>
815
816 <dt>CXXConversionFunctionName</dt>
817 <dd>The name is a C++ conversion function. Conversion functions are
818 named according to the type they convert to, e.g., "<code>operator void
819 const *</code>". Use <code>N.getCXXNameType()</code> to retrieve
820 the type that this conversion function converts to. This type is
821 always a canonical type.</dd>
Douglas Gregore94ca9e42008-11-18 14:39:36 +0000822
823 <dt>CXXOperatorName</dt>
824 <dd>The name is a C++ overloaded operator name. Overloaded operators
825 are named according to their spelling, e.g.,
826 "<code>operator+</code>" or "<code>operator new
827 []</code>". Use <code>N.getCXXOverloadedOperator()</code> to
828 retrieve the overloaded operator (a value of
829 type <code>OverloadedOperatorKind</code>).</dd>
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000830</dl>
831
832<p><code>DeclarationName</code>s are cheap to create, copy, and
833 compare. They require only a single pointer's worth of storage in
Douglas Gregore94ca9e42008-11-18 14:39:36 +0000834 the common cases (identifiers, zero-
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000835 and one-argument Objective-C selectors) and use dense, uniqued
836 storage for the other kinds of
837 names. Two <code>DeclarationName</code>s can be compared for
838 equality (<code>==</code>, <code>!=</code>) using a simple bitwise
839 comparison, can be ordered
840 with <code>&lt;</code>, <code>&gt;</code>, <code>&lt;=</code>,
841 and <code>&gt;=</code> (which provide a lexicographical ordering for
842 normal identifiers but an unspecified ordering for other kinds of
843 names), and can be placed into LLVM <code>DenseMap</code>s
844 and <code>DenseSet</code>s.</p>
845
846<p><code>DeclarationName</code> instances can be created in different
847 ways depending on what kind of name the instance will store. Normal
Douglas Gregore94ca9e42008-11-18 14:39:36 +0000848 identifiers (<code>IdentifierInfo</code> pointers) and Objective-C selectors
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000849 (<code>Selector</code>) can be implicitly converted
850 to <code>DeclarationName</code>s. Names for C++ constructors,
Douglas Gregore94ca9e42008-11-18 14:39:36 +0000851 destructors, conversion functions, and overloaded operators can be retrieved from
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000852 the <code>DeclarationNameTable</code>, an instance of which is
853 available as <code>ASTContext::DeclarationNames</code>. The member
854 functions <code>getCXXConstructorName</code>, <code>getCXXDestructorName</code>,
Douglas Gregore94ca9e42008-11-18 14:39:36 +0000855 <code>getCXXConversionFunctionName</code>, and <code>getCXXOperatorName</code>, respectively,
856 return <code>DeclarationName</code> instances for the four kinds of
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000857 C++ special function names.</p>
858
859<!-- ======================================================================= -->
Ted Kremenek8bc05712007-10-10 23:01:43 +0000860<h3 id="CFG">The <tt>CFG</tt> class</h3>
861<!-- ======================================================================= -->
862
863<p>The <tt>CFG</tt> class is designed to represent a source-level
864control-flow graph for a single statement (<tt>Stmt*</tt>). Typically
865instances of <tt>CFG</tt> are constructed for function bodies (usually
866an instance of <tt>CompoundStmt</tt>), but can also be instantiated to
867represent the control-flow of any class that subclasses <tt>Stmt</tt>,
868which includes simple expressions. Control-flow graphs are especially
869useful for performing
870<a href="http://en.wikipedia.org/wiki/Data_flow_analysis#Sensitivities">flow-
871or path-sensitive</a> program analyses on a given function.</p>
872
Chris Lattner62fd2782008-11-22 21:41:31 +0000873<!-- ============ -->
Ted Kremenek8bc05712007-10-10 23:01:43 +0000874<h4>Basic Blocks</h4>
Chris Lattner62fd2782008-11-22 21:41:31 +0000875<!-- ============ -->
Ted Kremenek8bc05712007-10-10 23:01:43 +0000876
877<p>Concretely, an instance of <tt>CFG</tt> is a collection of basic
878blocks. Each basic block is an instance of <tt>CFGBlock</tt>, which
879simply contains an ordered sequence of <tt>Stmt*</tt> (each referring
880to statements in the AST). The ordering of statements within a block
881indicates unconditional flow of control from one statement to the
882next. <a href="#ConditionalControlFlow">Conditional control-flow</a>
883is represented using edges between basic blocks. The statements
884within a given <tt>CFGBlock</tt> can be traversed using
885the <tt>CFGBlock::*iterator</tt> interface.</p>
886
887<p>
Ted Kremenek18e17e72007-10-18 22:50:52 +0000888A <tt>CFG</tt> object owns the instances of <tt>CFGBlock</tt> within
Ted Kremenek8bc05712007-10-10 23:01:43 +0000889the control-flow graph it represents. Each <tt>CFGBlock</tt> within a
890CFG is also uniquely numbered (accessible
891via <tt>CFGBlock::getBlockID()</tt>). Currently the number is
892based on the ordering the blocks were created, but no assumptions
893should be made on how <tt>CFGBlock</tt>s are numbered other than their
894numbers are unique and that they are numbered from 0..N-1 (where N is
895the number of basic blocks in the CFG).</p>
896
Chris Lattner62fd2782008-11-22 21:41:31 +0000897<!-- ===================== -->
Ted Kremenek8bc05712007-10-10 23:01:43 +0000898<h4>Entry and Exit Blocks</h4>
Chris Lattner62fd2782008-11-22 21:41:31 +0000899<!-- ===================== -->
Ted Kremenek8bc05712007-10-10 23:01:43 +0000900
901Each instance of <tt>CFG</tt> contains two special blocks:
902an <i>entry</i> block (accessible via <tt>CFG::getEntry()</tt>), which
903has no incoming edges, and an <i>exit</i> block (accessible
904via <tt>CFG::getExit()</tt>), which has no outgoing edges. Neither
905block contains any statements, and they serve the role of providing a
906clear entrance and exit for a body of code such as a function body.
907The presence of these empty blocks greatly simplifies the
908implementation of many analyses built on top of CFGs.
909
Chris Lattner62fd2782008-11-22 21:41:31 +0000910<!-- ===================================================== -->
Ted Kremenek8bc05712007-10-10 23:01:43 +0000911<h4 id ="ConditionalControlFlow">Conditional Control-Flow</h4>
Chris Lattner62fd2782008-11-22 21:41:31 +0000912<!-- ===================================================== -->
Ted Kremenek8bc05712007-10-10 23:01:43 +0000913
914<p>Conditional control-flow (such as those induced by if-statements
915and loops) is represented as edges between <tt>CFGBlock</tt>s.
916Because different C language constructs can induce control-flow,
917each <tt>CFGBlock</tt> also records an extra <tt>Stmt*</tt> that
918represents the <i>terminator</i> of the block. A terminator is simply
919the statement that caused the control-flow, and is used to identify
920the nature of the conditional control-flow between blocks. For
921example, in the case of an if-statement, the terminator refers to
922the <tt>IfStmt</tt> object in the AST that represented the given
923branch.</p>
924
925<p>To illustrate, consider the following code example:</p>
926
927<code>
928int foo(int x) {<br>
929&nbsp;&nbsp;x = x + 1;<br>
930<br>
931&nbsp;&nbsp;if (x > 2) x++;<br>
932&nbsp;&nbsp;else {<br>
933&nbsp;&nbsp;&nbsp;&nbsp;x += 2;<br>
934&nbsp;&nbsp;&nbsp;&nbsp;x *= 2;<br>
935&nbsp;&nbsp;}<br>
936<br>
937&nbsp;&nbsp;return x;<br>
938}
939</code>
940
941<p>After invoking the parser+semantic analyzer on this code fragment,
942the AST of the body of <tt>foo</tt> is referenced by a
943single <tt>Stmt*</tt>. We can then construct an instance
944of <tt>CFG</tt> representing the control-flow graph of this function
945body by single call to a static class method:</p>
946
947<code>
948&nbsp;&nbsp;Stmt* FooBody = ...<br>
949&nbsp;&nbsp;CFG* FooCFG = <b>CFG::buildCFG</b>(FooBody);
950</code>
951
952<p>It is the responsibility of the caller of <tt>CFG::buildCFG</tt>
953to <tt>delete</tt> the returned <tt>CFG*</tt> when the CFG is no
954longer needed.</p>
955
956<p>Along with providing an interface to iterate over
957its <tt>CFGBlock</tt>s, the <tt>CFG</tt> class also provides methods
958that are useful for debugging and visualizing CFGs. For example, the
959method
960<tt>CFG::dump()</tt> dumps a pretty-printed version of the CFG to
961standard error. This is especially useful when one is using a
962debugger such as gdb. For example, here is the output
963of <tt>FooCFG->dump()</tt>:</p>
964
965<code>
966&nbsp;[ B5 (ENTRY) ]<br>
967&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (0):<br>
968&nbsp;&nbsp;&nbsp;&nbsp;Successors (1): B4<br>
969<br>
970&nbsp;[ B4 ]<br>
971&nbsp;&nbsp;&nbsp;&nbsp;1: x = x + 1<br>
972&nbsp;&nbsp;&nbsp;&nbsp;2: (x > 2)<br>
973&nbsp;&nbsp;&nbsp;&nbsp;<b>T: if [B4.2]</b><br>
974&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (1): B5<br>
975&nbsp;&nbsp;&nbsp;&nbsp;Successors (2): B3 B2<br>
976<br>
977&nbsp;[ B3 ]<br>
978&nbsp;&nbsp;&nbsp;&nbsp;1: x++<br>
979&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (1): B4<br>
980&nbsp;&nbsp;&nbsp;&nbsp;Successors (1): B1<br>
981<br>
982&nbsp;[ B2 ]<br>
983&nbsp;&nbsp;&nbsp;&nbsp;1: x += 2<br>
984&nbsp;&nbsp;&nbsp;&nbsp;2: x *= 2<br>
985&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (1): B4<br>
986&nbsp;&nbsp;&nbsp;&nbsp;Successors (1): B1<br>
987<br>
988&nbsp;[ B1 ]<br>
989&nbsp;&nbsp;&nbsp;&nbsp;1: return x;<br>
990&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (2): B2 B3<br>
991&nbsp;&nbsp;&nbsp;&nbsp;Successors (1): B0<br>
992<br>
993&nbsp;[ B0 (EXIT) ]<br>
994&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (1): B1<br>
995&nbsp;&nbsp;&nbsp;&nbsp;Successors (0):
996</code>
997
998<p>For each block, the pretty-printed output displays for each block
999the number of <i>predecessor</i> blocks (blocks that have outgoing
1000control-flow to the given block) and <i>successor</i> blocks (blocks
1001that have control-flow that have incoming control-flow from the given
1002block). We can also clearly see the special entry and exit blocks at
1003the beginning and end of the pretty-printed output. For the entry
1004block (block B5), the number of predecessor blocks is 0, while for the
1005exit block (block B0) the number of successor blocks is 0.</p>
1006
1007<p>The most interesting block here is B4, whose outgoing control-flow
1008represents the branching caused by the sole if-statement
1009in <tt>foo</tt>. Of particular interest is the second statement in
1010the block, <b><tt>(x > 2)</tt></b>, and the terminator, printed
1011as <b><tt>if [B4.2]</tt></b>. The second statement represents the
1012evaluation of the condition of the if-statement, which occurs before
1013the actual branching of control-flow. Within the <tt>CFGBlock</tt>
1014for B4, the <tt>Stmt*</tt> for the second statement refers to the
1015actual expression in the AST for <b><tt>(x > 2)</tt></b>. Thus
1016pointers to subclasses of <tt>Expr</tt> can appear in the list of
1017statements in a block, and not just subclasses of <tt>Stmt</tt> that
1018refer to proper C statements.</p>
1019
1020<p>The terminator of block B4 is a pointer to the <tt>IfStmt</tt>
1021object in the AST. The pretty-printer outputs <b><tt>if
1022[B4.2]</tt></b> because the condition expression of the if-statement
1023has an actual place in the basic block, and thus the terminator is
1024essentially
1025<i>referring</i> to the expression that is the second statement of
1026block B4 (i.e., B4.2). In this manner, conditions for control-flow
1027(which also includes conditions for loops and switch statements) are
1028hoisted into the actual basic block.</p>
1029
Chris Lattner62fd2782008-11-22 21:41:31 +00001030<!-- ===================== -->
1031<!-- <h4>Implicit Control-Flow</h4> -->
1032<!-- ===================== -->
Ted Kremenek8bc05712007-10-10 23:01:43 +00001033
1034<!--
1035<p>A key design principle of the <tt>CFG</tt> class was to not require
1036any transformations to the AST in order to represent control-flow.
1037Thus the <tt>CFG</tt> does not perform any "lowering" of the
1038statements in an AST: loops are not transformed into guarded gotos,
1039short-circuit operations are not converted to a set of if-statements,
1040and so on.</p>
1041-->
Ted Kremenek17a295d2008-06-11 06:19:49 +00001042
Chris Lattner7bad1992008-11-16 21:48:07 +00001043
1044<!-- ======================================================================= -->
1045<h3 id="Constants">Constant Folding in the Clang AST</h3>
1046<!-- ======================================================================= -->
1047
1048<p>There are several places where constants and constant folding matter a lot to
1049the Clang front-end. First, in general, we prefer the AST to retain the source
1050code as close to how the user wrote it as possible. This means that if they
1051wrote "5+4", we want to keep the addition and two constants in the AST, we don't
1052want to fold to "9". This means that constant folding in various ways turns
1053into a tree walk that needs to handle the various cases.</p>
1054
1055<p>However, there are places in both C and C++ that require constants to be
1056folded. For example, the C standard defines what an "integer constant
1057expression" (i-c-e) is with very precise and specific requirements. The
1058language then requires i-c-e's in a lot of places (for example, the size of a
1059bitfield, the value for a case statement, etc). For these, we have to be able
1060to constant fold the constants, to do semantic checks (e.g. verify bitfield size
1061is non-negative and that case statements aren't duplicated). We aim for Clang
1062to be very pedantic about this, diagnosing cases when the code does not use an
1063i-c-e where one is required, but accepting the code unless running with
1064<tt>-pedantic-errors</tt>.</p>
1065
1066<p>Things get a little bit more tricky when it comes to compatibility with
1067real-world source code. Specifically, GCC has historically accepted a huge
1068superset of expressions as i-c-e's, and a lot of real world code depends on this
1069unfortuate accident of history (including, e.g., the glibc system headers). GCC
1070accepts anything its "fold" optimizer is capable of reducing to an integer
1071constant, which means that the definition of what it accepts changes as its
1072optimizer does. One example is that GCC accepts things like "case X-X:" even
1073when X is a variable, because it can fold this to 0.</p>
1074
1075<p>Another issue are how constants interact with the extensions we support, such
1076as __builtin_constant_p, __builtin_inf, __extension__ and many others. C99
1077obviously does not specify the semantics of any of these extensions, and the
1078definition of i-c-e does not include them. However, these extensions are often
1079used in real code, and we have to have a way to reason about them.</p>
1080
1081<p>Finally, this is not just a problem for semantic analysis. The code
1082generator and other clients have to be able to fold constants (e.g. to
1083initialize global variables) and has to handle a superset of what C99 allows.
1084Further, these clients can benefit from extended information. For example, we
1085know that "foo()||1" always evaluates to true, but we can't replace the
1086expression with true because it has side effects.</p>
1087
1088<!-- ======================= -->
1089<h4>Implementation Approach</h4>
1090<!-- ======================= -->
1091
1092<p>After trying several different approaches, we've finally converged on a
1093design (Note, at the time of this writing, not all of this has been implemented,
1094consider this a design goal!). Our basic approach is to define a single
1095recursive method evaluation method (<tt>Expr::Evaluate</tt>), which is
1096implemented in <tt>AST/ExprConstant.cpp</tt>. Given an expression with 'scalar'
1097type (integer, fp, complex, or pointer) this method returns the following
1098information:</p>
1099
1100<ul>
1101<li>Whether the expression is an integer constant expression, a general
1102 constant that was folded but has no side effects, a general constant that
1103 was folded but that does have side effects, or an uncomputable/unfoldable
1104 value.
1105</li>
1106<li>If the expression was computable in any way, this method returns the APValue
1107 for the result of the expression.</li>
1108<li>If the expression is not evaluatable at all, this method returns
1109 information on one of the problems with the expression. This includes a
1110 SourceLocation for where the problem is, and a diagnostic ID that explains
1111 the problem. The diagnostic should be have ERROR type.</li>
1112<li>If the expression is not an integer constant expression, this method returns
1113 information on one of the problems with the expression. This includes a
1114 SourceLocation for where the problem is, and a diagnostic ID that explains
1115 the problem. The diagnostic should be have EXTENSION type.</li>
1116</ul>
1117
1118<p>This information gives various clients the flexibility that they want, and we
1119will eventually have some helper methods for various extensions. For example,
1120Sema should have a <tt>Sema::VerifyIntegerConstantExpression</tt> method, which
1121calls Evaluate on the expression. If the expression is not foldable, the error
1122is emitted, and it would return true. If the expression is not an i-c-e, the
1123EXTENSION diagnostic is emitted. Finally it would return false to indicate that
1124the AST is ok.</p>
1125
1126<p>Other clients can use the information in other ways, for example, codegen can
1127just use expressions that are foldable in any way.</p>
1128
1129<!-- ========== -->
1130<h4>Extensions</h4>
1131<!-- ========== -->
1132
Chris Lattner552de0a2008-11-23 08:16:56 +00001133<p>This section describes how some of the various extensions Clang supports
Chris Lattner7bad1992008-11-16 21:48:07 +00001134interacts with constant evaluation:</p>
1135
1136<ul>
1137<li><b><tt>__extension__</tt></b>: The expression form of this extension causes
1138 any evaluatable subexpression to be accepted as an integer constant
1139 expression.</li>
1140<li><b><tt>__builtin_constant_p</tt></b>: This returns true (as a integer
1141 constant expression) if the operand is any evaluatable constant.</li>
1142<li><b><tt>__builtin_choose_expr</tt></b>: The condition is required to be an
1143 integer constant expression, but we accept any constant as an "extension of
1144 an extension". This only evaluates one operand depending on which way the
1145 condition evaluates.</li>
1146<li><b><tt>__builtin_classify_type</tt></b>: This always returns an integer
1147 constant expression.</li>
1148<li><b><tt>__builtin_inf,nan,..</tt></b>: These are treated just like a
1149 floating-point literal.</li>
1150<li><b><tt>__builtin_abs,copysign,..</tt></b>: These are constant folded as
1151 general constant expressions.</li>
1152</ul>
1153
1154
1155
1156
Ted Kremenek17a295d2008-06-11 06:19:49 +00001157</div>
1158</body>
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001159</html>