blob: 6ecc5d6149001af0eb5694631ecb1cbb52740a77 [file] [log] [blame]
Ted Kremenek17a295d2008-06-11 06:19:49 +00001<html>
2<head>
Chris Lattner86920d32007-07-31 05:42:17 +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" />
6</head>
7<body>
8
9<!--#include virtual="../menu.html.incl"-->
10
11<div id="content">
Chris Lattner86920d32007-07-31 05:42:17 +000012
13<h1>"clang" CFE Internals Manual</h1>
14
15<ul>
16<li><a href="#intro">Introduction</a></li>
17<li><a href="#libsystem">LLVM System and Support Libraries</a></li>
18<li><a href="#libbasic">The clang 'Basic' Library</a>
19 <ul>
Chris Lattner62fd2782008-11-22 21:41:31 +000020 <li><a href="#Diagnostics">The Diagnostics Subsystem</a></li>
Chris Lattner86920d32007-07-31 05:42:17 +000021 <li><a href="#SourceLocation">The SourceLocation and SourceManager
22 classes</a></li>
23 </ul>
24</li>
25<li><a href="#liblex">The Lexer and Preprocessor Library</a>
26 <ul>
27 <li><a href="#Token">The Token class</a></li>
28 <li><a href="#Lexer">The Lexer class</a></li>
Chris Lattner79281252008-03-09 02:27:26 +000029 <li><a href="#TokenLexer">The TokenLexer class</a></li>
Chris Lattner86920d32007-07-31 05:42:17 +000030 <li><a href="#MultipleIncludeOpt">The MultipleIncludeOpt class</a></li>
31 </ul>
32</li>
33<li><a href="#libparse">The Parser Library</a>
34 <ul>
35 </ul>
36</li>
37<li><a href="#libast">The AST Library</a>
38 <ul>
39 <li><a href="#Type">The Type class and its subclasses</a></li>
40 <li><a href="#QualType">The QualType class</a></li>
Douglas Gregor2e1cd422008-11-17 14:58:09 +000041 <li><a href="#DeclarationName">Declaration names</a></li>
Ted Kremenek8bc05712007-10-10 23:01:43 +000042 <li><a href="#CFG">The CFG class</a></li>
Chris Lattner7bad1992008-11-16 21:48:07 +000043 <li><a href="#Constants">Constant Folding in the Clang AST</a></li>
Chris Lattner86920d32007-07-31 05:42:17 +000044 </ul>
45</li>
46</ul>
47
48
49<!-- ======================================================================= -->
50<h2 id="intro">Introduction</h2>
51<!-- ======================================================================= -->
52
53<p>This document describes some of the more important APIs and internal design
54decisions made in the clang C front-end. The purpose of this document is to
55both capture some of this high level information and also describe some of the
56design decisions behind it. This is meant for people interested in hacking on
57clang, not for end-users. The description below is categorized by
58libraries, and does not describe any of the clients of the libraries.</p>
59
60<!-- ======================================================================= -->
61<h2 id="libsystem">LLVM System and Support Libraries</h2>
62<!-- ======================================================================= -->
63
64<p>The LLVM libsystem library provides the basic clang system abstraction layer,
65which is used for file system access. The LLVM libsupport library provides many
66underlying libraries and <a
67href="http://llvm.org/docs/ProgrammersManual.html">data-structures</a>,
68 including command line option
69processing and various containers.</p>
70
71<!-- ======================================================================= -->
72<h2 id="libbasic">The clang 'Basic' Library</h2>
73<!-- ======================================================================= -->
74
75<p>This library certainly needs a better name. The 'basic' library contains a
76number of low-level utilities for tracking and manipulating source buffers,
77locations within the source buffers, diagnostics, tokens, target abstraction,
78and information about the subset of the language being compiled for.</p>
79
80<p>Part of this infrastructure is specific to C (such as the TargetInfo class),
81other parts could be reused for other non-C-based languages (SourceLocation,
82SourceManager, Diagnostics, FileManager). When and if there is future demand
83we can figure out if it makes sense to introduce a new library, move the general
84classes somewhere else, or introduce some other solution.</p>
85
86<p>We describe the roles of these classes in order of their dependencies.</p>
87
Chris Lattner62fd2782008-11-22 21:41:31 +000088
89<!-- ======================================================================= -->
90<h3 id="Diagnostics">The Diagnostics Subsystem</h3>
91<!-- ======================================================================= -->
92
93<p>The Clang Diagnostics subsystem is an important part of how the compiler
94communicates with the human. Diagnostics are the warnings and errors produced
95when the code is incorrect or dubious. In Clang, each diagnostic produced has
96(at the minimum) a unique ID, a <a href="#SourceLocation">SourceLocation</a> to
97"put the caret", an English translation associated with it, and a severity (e.g.
98<tt>WARNING</tt> or <tt>ERROR</tt>). They can also optionally include a number
99of arguments to the dianostic (which fill in "%0"'s in the string) as well as a
100number of source ranges that related to the diagnostic.</p>
101
102<p>In this section, we'll be giving examples produced by the clang command line
103driver, but diagnostics can be <a href="#DiagnosticClient">rendered in many
104different ways</a> depending on how the DiagnosticClient interface is
105implemented. A representative example of a diagonstic is:</p>
106
107<pre>
108t.c:38:15: error: invalid operands to binary expression ('int *' and '_Complex float')
109 <font color="darkgreen">P = (P-42) + Gamma*4;</font>
110 <font color="blue">~~~~~~ ^ ~~~~~~~</font>
111</pre>
112
113<p>In this example, you can see the English translation, the severity (error),
114you can see the source location (the caret ("^") and file/line/column info),
115the source ranges "~~~~", arguments to the diagnostic ("int*" and "_Complex
116float"). You'll have to believe me that there is a unique ID backing the
117diagnostic :).</p>
118
119<p>Getting all of this to happen has several steps and involves many moving
120pieces, this section describes them and talks about best practices when adding
121a new diagnostic.</p>
122
123<!-- ============================ -->
124<h4>The DiagnosticKinds.def file</h4>
125<!-- ============================ -->
126
127<p>Diagnostics are created by adding an entry to the <tt><a
128href="http://llvm.org/svn/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticKinds.def"
129>DiagnosticKinds.def</a></tt> file. This file encodes the unique ID of the
130diagnostic (as an enum, the first argument), the severity of the diagnostic
131(second argument) and the English translation + format string.</p>
132
133<p>There is little sanity with the naming of the unique ID's right now. Some
134start with err_, warn_, ext_ to encode the severity into the name. Since the
135enum is referenced in the C++ code that produces the diagnostic, it is somewhat
136useful for it to be reasonably short.</p>
137
138<p>The severity of the diagnostic comes from the set {<tt>NOTE</tt>,
139<tt>WARNING</tt>, <tt>EXTENSION</tt>, <tt>EXTWARN</tt>, <tt>ERROR</tt>}. The
140<tt>ERROR</tt> severity is used for diagnostics indicating the program is never
141acceptable under any circumstances. When an error is emitted, the AST for the
142input code may not be fully built. The <tt>EXTENSION</tt> and <tt>EXTWARN</tt>
143severities are used for extensions to the language that Clang accepts. This
144means that Clang fully understands and can represent them in the AST, but we
145produce diagnostics to tell the user their code is non-portable. The difference
146is that the former are ignored by default, and the later warn by default. The
147<tt>WARNING</tt> severity is used for constructs that are valid in the currently
148selected source language but that are dubious in some way. The <tt>NOTE</tt>
149level is used to staple more information onto a previous diagnostics.</p>
150
151<p>These <em>severities</em> are mapped into a smaller set (the
152Diagnostic::Level enum, {<tt>Ignored</tt>, <tt>Note</tt>, <tt>Warning</tt>,
153<tt>Error</tt> }) of output <em>levels</em> by the diagnostics subsystem based
154on various configuration options. For example, if the user specifies
155<tt>-pedantic</tt>, <tt>EXTENSION</tt> maps to <tt>Warning</tt>, if they specify
156<tt>-pedantic-errors</tt>, it turns into <tt>Error</tt>. Clang also internally
157supports a fully fine grained mapping mechanism that allows you to map any
158diagnostic that doesn't have <tt>ERRROR</tt> severity to any output level that
159you want. This is used to implement options like <tt>-Wunused_macros</tt>,
160<tt>-Wundef</tt> etc.</p>
161
162<!-- ================= -->
163<h4>The Format String</h4>
164<!-- ================= -->
165
166<p>The format string for the diagnostic is very simple, but it has some power.
167It takes the form of a string in English with markers that indicate where and
168how arguments to the diagnostic are inserted and formatted. For example, here
169are some simple format strings:</p>
170
171<pre>
172 "binary integer literals are an extension"
173 "format string contains '\\0' within the string body"
174 "more '<b>%%</b>' conversions than data arguments"
175 "invalid operands to binary expression ('<b>%0</b>' and '<b>%1</b>')"
176 "overloaded '<b>%0</b>' must be a <b>%select{unary|binary|unary or binary}2</b> operator"
177 " (has <b>%1</b> parameter<b>%s1</b>)"
178</pre>
179
180<p>These examples show some important points of format strings. You can use any
181 plain ASCII character in the diagnostic string except "%" without a problem,
182 but these are C strings, so you have to use and be aware of all the C escape
183 sequences (as in the second example). If you want to produce a "%" in the
184 output, use the "%%" escape sequence, like the third diagnostic. Finally,
185 clang uses the "%...[digit]" sequences to specify where and how arguments to
186 the diagnostic are formatted.</p>
187
188<p>Arguments to the diagnostic are numbered according to how they are specified
189 by the C++ code that <a href="#producingdiag">produces them</a>, and are
190 referenced by <tt>%0</tt> .. <tt>%9</tt>. If you have more than 10 arguments
191 to your diagnostic, you are doing something wrong. :). Unlike printf, there
192 is no requirement that arguments to the diagnostic end up in the output in
193 the same order as they are specified, you could have a format string with
194 <tt>"%1 %0"</tt> that swaps them, for example. The text in between the
195 percent and digit are formatting instructions. If there are no instructions,
196 the argument is just turned into a string and substituted in.</p>
197
198<p>Here are some "best practices" for writing the English format string:</p>
199
200<ul>
201<li>Keep the string short. It should ideally fit in the 80 column limit of the
202 <tt>DiagnosticKinds.def</tt> file. This avoids the diagnostic wrapping when
203 printed, and forces you to think about the important point you are conveying
204 with the diagnostic.</li>
205<li>Take advantage of location information. The user will be able to see the
206 line and location of the caret, so you don't need to tell them that the
207 problem is with the 4th argument to the function: just point to it.</li>
208<li>Do not capitalize the diagnostic string, and do not end it with a
209 period.</li>
210<li>If you need to quote something in the diagnostic string, use single
211 quotes.</li>
212</ul>
213
214<p>Diagnostics should never take random English strings as arguments: you
215shouldn't use <tt>"you have a problem with %0"</tt> and pass in things like
216<tt>"your argument"</tt> or <tt>"your return value"</tt> as arguments. Doing
217this prevents <a href="translation">translating</a> the Clang diagnostics to
218other languages (because they'll get random English words in their otherwise
219localized diagnostic). The exceptions to this are C/C++ language keywords
220(e.g. auto, const, mutable, etc) and C/C++ operators (<tt>/=</tt>). Note
221that things like "pointer" and "reference" are not keywords. On the other
222hand, you <em>can</em> include anything that comes from the user's source code,
223including variable names, types, labels, etc.</p>
224
225<!-- ==================================== -->
226<h4>Formatting a Diagnostic Argument</a></h4>
227<!-- ==================================== -->
228
229<p>Arguments to diagnostics are fully typed internally, and come from a couple
230different classes: integers, types, names, and random strings. Depending on
231the class of the argument, it can be optionally formatted in different ways.
232This gives the DiagnosticClient information about what the argument means
233without requiring it to use a specific presentation (consider this MVC for
234Clang :).</p>
235
236<p>Here are the different diagnostic argument formats currently supported by
237Clang:</p>
238
239<table>
240<tr><td colspan="2"><b>"s" format</b></td></tr>
241<tr><td>Example:</td><td><tt>"requires %1 parameter%s1"</tt></td></tr>
242<tr><td>Classes:</td><td>Integers</td></tr>
243<tr><td>Description:</td><td>This is a simple formatter for integers that is
244 useful when producing English diagnostics. When the integer is 1, it prints
245 as nothing. When the integer is not 1, it prints as "s". This allows some
246 simple grammar to be to be handled correctly, and eliminates the need to use
247 gross things like <tt>"rewrite %1 parameter(s)"</tt>.</td></tr>
248
249<tr><td colspan="2"><b>"select" format</b></td></tr>
250<tr><td>Example:</td><td><tt>"must be a %select{unary|binary|unary or binary}2
251 operator"</tt></td></tr>
252<tr><td>Classes:</td><td>Integers</td></tr>
253<tr><td>Description:</td><td>...</td></tr>
254
255<tr><td colspan="2"><b>"plural" format</b></td></tr>
256<tr><td>Example:</td><td><tt>".."</tt></td></tr>
257<tr><td>Classes:</td><td>Integers</td></tr>
258<tr><td>Description:</td><td>...</td></tr>
259
260
261</table>
262
263
264
265
266<!-- ===================================================== -->
267<h4><a name="#producingdiag">Producing the Diagnostic</a></h4>
268<!-- ===================================================== -->
269
270<p>SemaExpr.cpp example</p>
271
272
273<!-- ============================================================= -->
274<h4><a name="DiagnosticClient">The DiagnosticClient Interface</a></h4>
275<!-- ============================================================= -->
276
277<p>Clang command line, buffering, HTMLizing, etc.</p>
278
279<!-- ====================================================== -->
280<h4><a name="translation">Adding Translations to Clang</a></h4>
281<!-- ====================================================== -->
282
283<p>Not possible yet!</p>
284
285
Chris Lattner86920d32007-07-31 05:42:17 +0000286<!-- ======================================================================= -->
287<h3 id="SourceLocation">The SourceLocation and SourceManager classes</h3>
288<!-- ======================================================================= -->
289
290<p>Strangely enough, the SourceLocation class represents a location within the
291source code of the program. Important design points include:</p>
292
293<ol>
294<li>sizeof(SourceLocation) must be extremely small, as these are embedded into
295 many AST nodes and are passed around often. Currently it is 32 bits.</li>
296<li>SourceLocation must be a simple value object that can be efficiently
297 copied.</li>
298<li>We should be able to represent a source location for any byte of any input
299 file. This includes in the middle of tokens, in whitespace, in trigraphs,
300 etc.</li>
301<li>A SourceLocation must encode the current #include stack that was active when
302 the location was processed. For example, if the location corresponds to a
303 token, it should contain the set of #includes active when the token was
304 lexed. This allows us to print the #include stack for a diagnostic.</li>
305<li>SourceLocation must be able to describe macro expansions, capturing both
306 the ultimate instantiation point and the source of the original character
307 data.</li>
308</ol>
309
310<p>In practice, the SourceLocation works together with the SourceManager class
311to encode two pieces of information about a location: it's physical location
312and it's virtual location. For most tokens, these will be the same. However,
313for a macro expansion (or tokens that came from a _Pragma directive) these will
314describe the location of the characters corresponding to the token and the
315location where the token was used (i.e. the macro instantiation point or the
316location of the _Pragma itself).</p>
317
318<p>For efficiency, we only track one level of macro instantions: if a token was
319produced by multiple instantiations, we only track the source and ultimate
320destination. Though we could track the intermediate instantiation points, this
321would require extra bookkeeping and no known client would benefit substantially
322from this.</p>
323
324<p>The clang front-end inherently depends on the location of a token being
325tracked correctly. If it is ever incorrect, the front-end may get confused and
326die. The reason for this is that the notion of the 'spelling' of a Token in
327clang depends on being able to find the original input characters for the token.
328This concept maps directly to the "physical" location for the token.</p>
329
330<!-- ======================================================================= -->
331<h2 id="liblex">The Lexer and Preprocessor Library</h2>
332<!-- ======================================================================= -->
333
334<p>The Lexer library contains several tightly-connected classes that are involved
335with the nasty process of lexing and preprocessing C source code. The main
336interface to this library for outside clients is the large <a
337href="#Preprocessor">Preprocessor</a> class.
338It contains the various pieces of state that are required to coherently read
339tokens out of a translation unit.</p>
340
341<p>The core interface to the Preprocessor object (once it is set up) is the
342Preprocessor::Lex method, which returns the next <a href="#Token">Token</a> from
343the preprocessor stream. There are two types of token providers that the
344preprocessor is capable of reading from: a buffer lexer (provided by the <a
345href="#Lexer">Lexer</a> class) and a buffered token stream (provided by the <a
Chris Lattner79281252008-03-09 02:27:26 +0000346href="#TokenLexer">TokenLexer</a> class).
Chris Lattner86920d32007-07-31 05:42:17 +0000347
348
349<!-- ======================================================================= -->
350<h3 id="Token">The Token class</h3>
351<!-- ======================================================================= -->
352
353<p>The Token class is used to represent a single lexed token. Tokens are
354intended to be used by the lexer/preprocess and parser libraries, but are not
355intended to live beyond them (for example, they should not live in the ASTs).<p>
356
357<p>Tokens most often live on the stack (or some other location that is efficient
358to access) as the parser is running, but occasionally do get buffered up. For
359example, macro definitions are stored as a series of tokens, and the C++
360front-end will eventually need to buffer tokens up for tentative parsing and
361various pieces of look-ahead. As such, the size of a Token matter. On a 32-bit
362system, sizeof(Token) is currently 16 bytes.</p>
363
364<p>Tokens contain the following information:</p>
365
366<ul>
367<li><b>A SourceLocation</b> - This indicates the location of the start of the
368token.</li>
369
370<li><b>A length</b> - This stores the length of the token as stored in the
371SourceBuffer. For tokens that include them, this length includes trigraphs and
372escaped newlines which are ignored by later phases of the compiler. By pointing
373into the original source buffer, it is always possible to get the original
374spelling of a token completely accurately.</li>
375
376<li><b>IdentifierInfo</b> - If a token takes the form of an identifier, and if
377identifier lookup was enabled when the token was lexed (e.g. the lexer was not
378reading in 'raw' mode) this contains a pointer to the unique hash value for the
379identifier. Because the lookup happens before keyword identification, this
380field is set even for language keywords like 'for'.</li>
381
382<li><b>TokenKind</b> - This indicates the kind of token as classified by the
383lexer. This includes things like <tt>tok::starequal</tt> (for the "*="
384operator), <tt>tok::ampamp</tt> for the "&amp;&amp;" token, and keyword values
385(e.g. <tt>tok::kw_for</tt>) for identifiers that correspond to keywords. Note
386that some tokens can be spelled multiple ways. For example, C++ supports
387"operator keywords", where things like "and" are treated exactly like the
388"&amp;&amp;" operator. In these cases, the kind value is set to
389<tt>tok::ampamp</tt>, which is good for the parser, which doesn't have to
390consider both forms. For something that cares about which form is used (e.g.
391the preprocessor 'stringize' operator) the spelling indicates the original
392form.</li>
393
394<li><b>Flags</b> - There are currently four flags tracked by the
395lexer/preprocessor system on a per-token basis:
396
397 <ol>
398 <li><b>StartOfLine</b> - This was the first token that occurred on its input
399 source line.</li>
400 <li><b>LeadingSpace</b> - There was a space character either immediately
401 before the token or transitively before the token as it was expanded
402 through a macro. The definition of this flag is very closely defined by
403 the stringizing requirements of the preprocessor.</li>
404 <li><b>DisableExpand</b> - This flag is used internally to the preprocessor to
405 represent identifier tokens which have macro expansion disabled. This
406 prevents them from being considered as candidates for macro expansion ever
407 in the future.</li>
408 <li><b>NeedsCleaning</b> - This flag is set if the original spelling for the
409 token includes a trigraph or escaped newline. Since this is uncommon,
410 many pieces of code can fast-path on tokens that did not need cleaning.
411 </p>
412 </ol>
413</li>
414</ul>
415
416<p>One interesting (and somewhat unusual) aspect of tokens is that they don't
417contain any semantic information about the lexed value. For example, if the
418token was a pp-number token, we do not represent the value of the number that
419was lexed (this is left for later pieces of code to decide). Additionally, the
420lexer library has no notion of typedef names vs variable names: both are
421returned as identifiers, and the parser is left to decide whether a specific
422identifier is a typedef or a variable (tracking this requires scope information
423among other things).</p>
424
425<!-- ======================================================================= -->
426<h3 id="Lexer">The Lexer class</h3>
427<!-- ======================================================================= -->
428
429<p>The Lexer class provides the mechanics of lexing tokens out of a source
430buffer and deciding what they mean. The Lexer is complicated by the fact that
431it operates on raw buffers that have not had spelling eliminated (this is a
432necessity to get decent performance), but this is countered with careful coding
433as well as standard performance techniques (for example, the comment handling
434code is vectorized on X86 and PowerPC hosts).</p>
435
436<p>The lexer has a couple of interesting modal features:</p>
437
438<ul>
439<li>The lexer can operate in 'raw' mode. This mode has several features that
440 make it possible to quickly lex the file (e.g. it stops identifier lookup,
441 doesn't specially handle preprocessor tokens, handles EOF differently, etc).
442 This mode is used for lexing within an "<tt>#if 0</tt>" block, for
443 example.</li>
444<li>The lexer can capture and return comments as tokens. This is required to
445 support the -C preprocessor mode, which passes comments through, and is
446 used by the diagnostic checker to identifier expect-error annotations.</li>
447<li>The lexer can be in ParsingFilename mode, which happens when preprocessing
Chris Lattner84386242007-09-16 19:25:23 +0000448 after reading a #include directive. This mode changes the parsing of '&lt;'
Chris Lattner86920d32007-07-31 05:42:17 +0000449 to return an "angled string" instead of a bunch of tokens for each thing
450 within the filename.</li>
451<li>When parsing a preprocessor directive (after "<tt>#</tt>") the
452 ParsingPreprocessorDirective mode is entered. This changes the parser to
453 return EOM at a newline.</li>
454<li>The Lexer uses a LangOptions object to know whether trigraphs are enabled,
455 whether C++ or ObjC keywords are recognized, etc.</li>
456</ul>
457
458<p>In addition to these modes, the lexer keeps track of a couple of other
459 features that are local to a lexed buffer, which change as the buffer is
460 lexed:</p>
461
462<ul>
463<li>The Lexer uses BufferPtr to keep track of the current character being
464 lexed.</li>
465<li>The Lexer uses IsAtStartOfLine to keep track of whether the next lexed token
466 will start with its "start of line" bit set.</li>
467<li>The Lexer keeps track of the current #if directives that are active (which
468 can be nested).</li>
469<li>The Lexer keeps track of an <a href="#MultipleIncludeOpt">
470 MultipleIncludeOpt</a> object, which is used to
471 detect whether the buffer uses the standard "<tt>#ifndef XX</tt> /
472 <tt>#define XX</tt>" idiom to prevent multiple inclusion. If a buffer does,
473 subsequent includes can be ignored if the XX macro is defined.</li>
474</ul>
475
476<!-- ======================================================================= -->
Chris Lattner79281252008-03-09 02:27:26 +0000477<h3 id="TokenLexer">The TokenLexer class</h3>
Chris Lattner86920d32007-07-31 05:42:17 +0000478<!-- ======================================================================= -->
479
Chris Lattner79281252008-03-09 02:27:26 +0000480<p>The TokenLexer class is a token provider that returns tokens from a list
Chris Lattner86920d32007-07-31 05:42:17 +0000481of tokens that came from somewhere else. It typically used for two things: 1)
482returning tokens from a macro definition as it is being expanded 2) returning
483tokens from an arbitrary buffer of tokens. The later use is used by _Pragma and
484will most likely be used to handle unbounded look-ahead for the C++ parser.</p>
485
486<!-- ======================================================================= -->
487<h3 id="MultipleIncludeOpt">The MultipleIncludeOpt class</h3>
488<!-- ======================================================================= -->
489
490<p>The MultipleIncludeOpt class implements a really simple little state machine
491that is used to detect the standard "<tt>#ifndef XX</tt> / <tt>#define XX</tt>"
492idiom that people typically use to prevent multiple inclusion of headers. If a
493buffer uses this idiom and is subsequently #include'd, the preprocessor can
494simply check to see whether the guarding condition is defined or not. If so,
495the preprocessor can completely ignore the include of the header.</p>
496
497
498
499<!-- ======================================================================= -->
500<h2 id="libparse">The Parser Library</h2>
501<!-- ======================================================================= -->
502
503<!-- ======================================================================= -->
504<h2 id="libast">The AST Library</h2>
505<!-- ======================================================================= -->
506
507<!-- ======================================================================= -->
508<h3 id="Type">The Type class and its subclasses</h3>
509<!-- ======================================================================= -->
510
511<p>The Type class (and its subclasses) are an important part of the AST. Types
512are accessed through the ASTContext class, which implicitly creates and uniques
513them as they are needed. Types have a couple of non-obvious features: 1) they
514do not capture type qualifiers like const or volatile (See
515<a href="#QualType">QualType</a>), and 2) they implicitly capture typedef
Chris Lattner8a2bc622007-07-31 06:37:39 +0000516information. Once created, types are immutable (unlike decls).</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000517
518<p>Typedefs in C make semantic analysis a bit more complex than it would
519be without them. The issue is that we want to capture typedef information
520and represent it in the AST perfectly, but the semantics of operations need to
521"see through" typedefs. For example, consider this code:</p>
522
523<code>
524void func() {<br>
Bill Wendling30d17752007-10-06 01:56:01 +0000525&nbsp;&nbsp;typedef int foo;<br>
526&nbsp;&nbsp;foo X, *Y;<br>
527&nbsp;&nbsp;typedef foo* bar;<br>
528&nbsp;&nbsp;bar Z;<br>
529&nbsp;&nbsp;*X; <i>// error</i><br>
530&nbsp;&nbsp;**Y; <i>// error</i><br>
531&nbsp;&nbsp;**Z; <i>// error</i><br>
Chris Lattner86920d32007-07-31 05:42:17 +0000532}<br>
533</code>
534
535<p>The code above is illegal, and thus we expect there to be diagnostics emitted
536on the annotated lines. In this example, we expect to get:</p>
537
538<pre>
Chris Lattner8a2bc622007-07-31 06:37:39 +0000539<b>test.c:6:1: error: indirection requires pointer operand ('foo' invalid)</b>
Chris Lattner86920d32007-07-31 05:42:17 +0000540*X; // error
541<font color="blue">^~</font>
Chris Lattner8a2bc622007-07-31 06:37:39 +0000542<b>test.c:7:1: error: indirection requires pointer operand ('foo' invalid)</b>
Chris Lattner86920d32007-07-31 05:42:17 +0000543**Y; // error
544<font color="blue">^~~</font>
Chris Lattner8a2bc622007-07-31 06:37:39 +0000545<b>test.c:8:1: error: indirection requires pointer operand ('foo' invalid)</b>
546**Z; // error
547<font color="blue">^~~</font>
Chris Lattner86920d32007-07-31 05:42:17 +0000548</pre>
549
550<p>While this example is somewhat silly, it illustrates the point: we want to
551retain typedef information where possible, so that we can emit errors about
552"<tt>std::string</tt>" instead of "<tt>std::basic_string&lt;char, std:...</tt>".
553Doing this requires properly keeping typedef information (for example, the type
554of "X" is "foo", not "int"), and requires properly propagating it through the
Chris Lattner8a2bc622007-07-31 06:37:39 +0000555various operators (for example, the type of *Y is "foo", not "int"). In order
556to retain this information, the type of these expressions is an instance of the
557TypedefType class, which indicates that the type of these expressions is a
558typedef for foo.
559</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000560
Chris Lattner8a2bc622007-07-31 06:37:39 +0000561<p>Representing types like this is great for diagnostics, because the
562user-specified type is always immediately available. There are two problems
563with this: first, various semantic checks need to make judgements about the
Chris Lattner33fc68a2007-07-31 18:54:50 +0000564<em>actual structure</em> of a type, ignoring typdefs. Second, we need an
565efficient way to query whether two types are structurally identical to each
566other, ignoring typedefs. The solution to both of these problems is the idea of
Chris Lattner8a2bc622007-07-31 06:37:39 +0000567canonical types.</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000568
Chris Lattner62fd2782008-11-22 21:41:31 +0000569<!-- =============== -->
Chris Lattner8a2bc622007-07-31 06:37:39 +0000570<h4>Canonical Types</h4>
Chris Lattner62fd2782008-11-22 21:41:31 +0000571<!-- =============== -->
Chris Lattner86920d32007-07-31 05:42:17 +0000572
Chris Lattner8a2bc622007-07-31 06:37:39 +0000573<p>Every instance of the Type class contains a canonical type pointer. For
574simple types with no typedefs involved (e.g. "<tt>int</tt>", "<tt>int*</tt>",
575"<tt>int**</tt>"), the type just points to itself. For types that have a
576typedef somewhere in their structure (e.g. "<tt>foo</tt>", "<tt>foo*</tt>",
577"<tt>foo**</tt>", "<tt>bar</tt>"), the canonical type pointer points to their
578structurally equivalent type without any typedefs (e.g. "<tt>int</tt>",
579"<tt>int*</tt>", "<tt>int**</tt>", and "<tt>int*</tt>" respectively).</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000580
Chris Lattner8a2bc622007-07-31 06:37:39 +0000581<p>This design provides a constant time operation (dereferencing the canonical
582type pointer) that gives us access to the structure of types. For example,
583we can trivially tell that "bar" and "foo*" are the same type by dereferencing
584their canonical type pointers and doing a pointer comparison (they both point
585to the single "<tt>int*</tt>" type).</p>
586
587<p>Canonical types and typedef types bring up some complexities that must be
588carefully managed. Specifically, the "isa/cast/dyncast" operators generally
589shouldn't be used in code that is inspecting the AST. For example, when type
590checking the indirection operator (unary '*' on a pointer), the type checker
591must verify that the operand has a pointer type. It would not be correct to
592check that with "<tt>isa&lt;PointerType&gt;(SubExpr-&gt;getType())</tt>",
593because this predicate would fail if the subexpression had a typedef type.</p>
594
595<p>The solution to this problem are a set of helper methods on Type, used to
596check their properties. In this case, it would be correct to use
597"<tt>SubExpr-&gt;getType()-&gt;isPointerType()</tt>" to do the check. This
598predicate will return true if the <em>canonical type is a pointer</em>, which is
599true any time the type is structurally a pointer type. The only hard part here
600is remembering not to use the <tt>isa/cast/dyncast</tt> operations.</p>
601
602<p>The second problem we face is how to get access to the pointer type once we
603know it exists. To continue the example, the result type of the indirection
604operator is the pointee type of the subexpression. In order to determine the
605type, we need to get the instance of PointerType that best captures the typedef
606information in the program. If the type of the expression is literally a
607PointerType, we can return that, otherwise we have to dig through the
608typedefs to find the pointer type. For example, if the subexpression had type
609"<tt>foo*</tt>", we could return that type as the result. If the subexpression
610had type "<tt>bar</tt>", we want to return "<tt>foo*</tt>" (note that we do
611<em>not</em> want "<tt>int*</tt>"). In order to provide all of this, Type has
Chris Lattner11406c12007-07-31 16:50:51 +0000612a getAsPointerType() method that checks whether the type is structurally a
Chris Lattner8a2bc622007-07-31 06:37:39 +0000613PointerType and, if so, returns the best one. If not, it returns a null
614pointer.</p>
615
616<p>This structure is somewhat mystical, but after meditating on it, it will
617make sense to you :).</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000618
619<!-- ======================================================================= -->
620<h3 id="QualType">The QualType class</h3>
621<!-- ======================================================================= -->
622
623<p>The QualType class is designed as a trivial value class that is small,
624passed by-value and is efficient to query. The idea of QualType is that it
625stores the type qualifiers (const, volatile, restrict) separately from the types
626themselves: QualType is conceptually a pair of "Type*" and bits for the type
627qualifiers.</p>
628
629<p>By storing the type qualifiers as bits in the conceptual pair, it is
630extremely efficient to get the set of qualifiers on a QualType (just return the
631field of the pair), add a type qualifier (which is a trivial constant-time
632operation that sets a bit), and remove one or more type qualifiers (just return
633a QualType with the bitfield set to empty).</p>
634
635<p>Further, because the bits are stored outside of the type itself, we do not
636need to create duplicates of types with different sets of qualifiers (i.e. there
637is only a single heap allocated "int" type: "const int" and "volatile const int"
638both point to the same heap allocated "int" type). This reduces the heap size
639used to represent bits and also means we do not have to consider qualifiers when
640uniquing types (<a href="#Type">Type</a> does not even contain qualifiers).</p>
641
642<p>In practice, on hosts where it is safe, the 3 type qualifiers are stored in
643the low bit of the pointer to the Type object. This means that QualType is
644exactly the same size as a pointer, and this works fine on any system where
645malloc'd objects are at least 8 byte aligned.</p>
Ted Kremenek8bc05712007-10-10 23:01:43 +0000646
647<!-- ======================================================================= -->
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000648<h3 id="DeclarationName">Declaration names</h3>
649<!-- ======================================================================= -->
650
651<p>The <tt>DeclarationName</tt> class represents the name of a
652 declaration in Clang. Declarations in the C family of languages can
653 take several different forms. Most declarations are named by are
654 simple identifiers, e.g., "<code>f</code>" and "<code>x</code>" in
655 the function declaration <code>f(int x)</code>. In C++, declaration
656 names can also name class constructors ("<code>Class</code>"
657 in <code>struct Class { Class(); }</code>), class destructors
658 ("<code>~Class</code>"), overloaded operator names ("operator+"),
659 and conversion functions ("<code>operator void const *</code>"). In
660 Objective-C, declaration names can refer to the names of Objective-C
661 methods, which involve the method name and the parameters,
662 collectively called a <i>selector</i>, e.g..,
663 "<code>setWidth:height:</code>". Since all of these kinds of
664 entities--variables, functions, Objective-C methods, C++
665 constructors, destructors, and operators---are represented as
666 subclasses of Clang's common <code>NamedDecl</code>
667 class, <code>DeclarationName</code> is designed to efficiently
668 represent any kind of name.</p>
669
670<p>Given
671 a <code>DeclarationName</code> <code>N</code>, <code>N.getNameKind()</code>
Douglas Gregor2def4832008-11-17 20:34:05 +0000672 will produce a value that describes what kind of name <code>N</code>
Douglas Gregore94ca9e42008-11-18 14:39:36 +0000673 stores. There are 8 options (all of the names are inside
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000674 the <code>DeclarationName</code> class)</p>
675<dl>
676 <dt>Identifier</dt>
677 <dd>The name is a simple
678 identifier. Use <code>N.getAsIdentifierInfo()</code> to retrieve the
679 corresponding <code>IdentifierInfo*</code> pointing to the actual
680 identifier. Note that C++ overloaded operators (e.g.,
681 "<code>operator+</code>") are represented as special kinds of
682 identifiers. Use <code>IdentifierInfo</code>'s <code>getOverloadedOperatorID</code>
683 function to determine whether an identifier is an overloaded
684 operator name.</dd>
685
686 <dt>ObjCZeroArgSelector, ObjCOneArgSelector,
687 ObjCMultiArgSelector</dt>
688 <dd>The name is an Objective-C selector, which can be retrieved as a
689 <code>Selector</code> instance
690 via <code>N.getObjCSelector()</code>. The three possible name
691 kinds for Objective-C reflect an optimization within
692 the <code>DeclarationName</code> class: both zero- and
693 one-argument selectors are stored as a
694 masked <code>IdentifierInfo</code> pointer, and therefore require
695 very little space, since zero- and one-argument selectors are far
696 more common than multi-argument selectors (which use a different
697 structure).</dd>
698
699 <dt>CXXConstructorName</dt>
700 <dd>The name is a C++ constructor
701 name. Use <code>N.getCXXNameType()</code> to retrieve
702 the <a href="#QualType">type</a> that this constructor is meant to
703 construct. The type is always the canonical type, since all
704 constructors for a given type have the same name.</dd>
705
706 <dt>CXXDestructorName</dt>
707 <dd>The name is a C++ destructor
708 name. Use <code>N.getCXXNameType()</code> to retrieve
709 the <a href="#QualType">type</a> whose destructor is being
710 named. This type is always a canonical type.</dd>
711
712 <dt>CXXConversionFunctionName</dt>
713 <dd>The name is a C++ conversion function. Conversion functions are
714 named according to the type they convert to, e.g., "<code>operator void
715 const *</code>". Use <code>N.getCXXNameType()</code> to retrieve
716 the type that this conversion function converts to. This type is
717 always a canonical type.</dd>
Douglas Gregore94ca9e42008-11-18 14:39:36 +0000718
719 <dt>CXXOperatorName</dt>
720 <dd>The name is a C++ overloaded operator name. Overloaded operators
721 are named according to their spelling, e.g.,
722 "<code>operator+</code>" or "<code>operator new
723 []</code>". Use <code>N.getCXXOverloadedOperator()</code> to
724 retrieve the overloaded operator (a value of
725 type <code>OverloadedOperatorKind</code>).</dd>
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000726</dl>
727
728<p><code>DeclarationName</code>s are cheap to create, copy, and
729 compare. They require only a single pointer's worth of storage in
Douglas Gregore94ca9e42008-11-18 14:39:36 +0000730 the common cases (identifiers, zero-
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000731 and one-argument Objective-C selectors) and use dense, uniqued
732 storage for the other kinds of
733 names. Two <code>DeclarationName</code>s can be compared for
734 equality (<code>==</code>, <code>!=</code>) using a simple bitwise
735 comparison, can be ordered
736 with <code>&lt;</code>, <code>&gt;</code>, <code>&lt;=</code>,
737 and <code>&gt;=</code> (which provide a lexicographical ordering for
738 normal identifiers but an unspecified ordering for other kinds of
739 names), and can be placed into LLVM <code>DenseMap</code>s
740 and <code>DenseSet</code>s.</p>
741
742<p><code>DeclarationName</code> instances can be created in different
743 ways depending on what kind of name the instance will store. Normal
Douglas Gregore94ca9e42008-11-18 14:39:36 +0000744 identifiers (<code>IdentifierInfo</code> pointers) and Objective-C selectors
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000745 (<code>Selector</code>) can be implicitly converted
746 to <code>DeclarationName</code>s. Names for C++ constructors,
Douglas Gregore94ca9e42008-11-18 14:39:36 +0000747 destructors, conversion functions, and overloaded operators can be retrieved from
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000748 the <code>DeclarationNameTable</code>, an instance of which is
749 available as <code>ASTContext::DeclarationNames</code>. The member
750 functions <code>getCXXConstructorName</code>, <code>getCXXDestructorName</code>,
Douglas Gregore94ca9e42008-11-18 14:39:36 +0000751 <code>getCXXConversionFunctionName</code>, and <code>getCXXOperatorName</code>, respectively,
752 return <code>DeclarationName</code> instances for the four kinds of
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000753 C++ special function names.</p>
754
755<!-- ======================================================================= -->
Ted Kremenek8bc05712007-10-10 23:01:43 +0000756<h3 id="CFG">The <tt>CFG</tt> class</h3>
757<!-- ======================================================================= -->
758
759<p>The <tt>CFG</tt> class is designed to represent a source-level
760control-flow graph for a single statement (<tt>Stmt*</tt>). Typically
761instances of <tt>CFG</tt> are constructed for function bodies (usually
762an instance of <tt>CompoundStmt</tt>), but can also be instantiated to
763represent the control-flow of any class that subclasses <tt>Stmt</tt>,
764which includes simple expressions. Control-flow graphs are especially
765useful for performing
766<a href="http://en.wikipedia.org/wiki/Data_flow_analysis#Sensitivities">flow-
767or path-sensitive</a> program analyses on a given function.</p>
768
Chris Lattner62fd2782008-11-22 21:41:31 +0000769<!-- ============ -->
Ted Kremenek8bc05712007-10-10 23:01:43 +0000770<h4>Basic Blocks</h4>
Chris Lattner62fd2782008-11-22 21:41:31 +0000771<!-- ============ -->
Ted Kremenek8bc05712007-10-10 23:01:43 +0000772
773<p>Concretely, an instance of <tt>CFG</tt> is a collection of basic
774blocks. Each basic block is an instance of <tt>CFGBlock</tt>, which
775simply contains an ordered sequence of <tt>Stmt*</tt> (each referring
776to statements in the AST). The ordering of statements within a block
777indicates unconditional flow of control from one statement to the
778next. <a href="#ConditionalControlFlow">Conditional control-flow</a>
779is represented using edges between basic blocks. The statements
780within a given <tt>CFGBlock</tt> can be traversed using
781the <tt>CFGBlock::*iterator</tt> interface.</p>
782
783<p>
Ted Kremenek18e17e72007-10-18 22:50:52 +0000784A <tt>CFG</tt> object owns the instances of <tt>CFGBlock</tt> within
Ted Kremenek8bc05712007-10-10 23:01:43 +0000785the control-flow graph it represents. Each <tt>CFGBlock</tt> within a
786CFG is also uniquely numbered (accessible
787via <tt>CFGBlock::getBlockID()</tt>). Currently the number is
788based on the ordering the blocks were created, but no assumptions
789should be made on how <tt>CFGBlock</tt>s are numbered other than their
790numbers are unique and that they are numbered from 0..N-1 (where N is
791the number of basic blocks in the CFG).</p>
792
Chris Lattner62fd2782008-11-22 21:41:31 +0000793<!-- ===================== -->
Ted Kremenek8bc05712007-10-10 23:01:43 +0000794<h4>Entry and Exit Blocks</h4>
Chris Lattner62fd2782008-11-22 21:41:31 +0000795<!-- ===================== -->
Ted Kremenek8bc05712007-10-10 23:01:43 +0000796
797Each instance of <tt>CFG</tt> contains two special blocks:
798an <i>entry</i> block (accessible via <tt>CFG::getEntry()</tt>), which
799has no incoming edges, and an <i>exit</i> block (accessible
800via <tt>CFG::getExit()</tt>), which has no outgoing edges. Neither
801block contains any statements, and they serve the role of providing a
802clear entrance and exit for a body of code such as a function body.
803The presence of these empty blocks greatly simplifies the
804implementation of many analyses built on top of CFGs.
805
Chris Lattner62fd2782008-11-22 21:41:31 +0000806<!-- ===================================================== -->
Ted Kremenek8bc05712007-10-10 23:01:43 +0000807<h4 id ="ConditionalControlFlow">Conditional Control-Flow</h4>
Chris Lattner62fd2782008-11-22 21:41:31 +0000808<!-- ===================================================== -->
Ted Kremenek8bc05712007-10-10 23:01:43 +0000809
810<p>Conditional control-flow (such as those induced by if-statements
811and loops) is represented as edges between <tt>CFGBlock</tt>s.
812Because different C language constructs can induce control-flow,
813each <tt>CFGBlock</tt> also records an extra <tt>Stmt*</tt> that
814represents the <i>terminator</i> of the block. A terminator is simply
815the statement that caused the control-flow, and is used to identify
816the nature of the conditional control-flow between blocks. For
817example, in the case of an if-statement, the terminator refers to
818the <tt>IfStmt</tt> object in the AST that represented the given
819branch.</p>
820
821<p>To illustrate, consider the following code example:</p>
822
823<code>
824int foo(int x) {<br>
825&nbsp;&nbsp;x = x + 1;<br>
826<br>
827&nbsp;&nbsp;if (x > 2) x++;<br>
828&nbsp;&nbsp;else {<br>
829&nbsp;&nbsp;&nbsp;&nbsp;x += 2;<br>
830&nbsp;&nbsp;&nbsp;&nbsp;x *= 2;<br>
831&nbsp;&nbsp;}<br>
832<br>
833&nbsp;&nbsp;return x;<br>
834}
835</code>
836
837<p>After invoking the parser+semantic analyzer on this code fragment,
838the AST of the body of <tt>foo</tt> is referenced by a
839single <tt>Stmt*</tt>. We can then construct an instance
840of <tt>CFG</tt> representing the control-flow graph of this function
841body by single call to a static class method:</p>
842
843<code>
844&nbsp;&nbsp;Stmt* FooBody = ...<br>
845&nbsp;&nbsp;CFG* FooCFG = <b>CFG::buildCFG</b>(FooBody);
846</code>
847
848<p>It is the responsibility of the caller of <tt>CFG::buildCFG</tt>
849to <tt>delete</tt> the returned <tt>CFG*</tt> when the CFG is no
850longer needed.</p>
851
852<p>Along with providing an interface to iterate over
853its <tt>CFGBlock</tt>s, the <tt>CFG</tt> class also provides methods
854that are useful for debugging and visualizing CFGs. For example, the
855method
856<tt>CFG::dump()</tt> dumps a pretty-printed version of the CFG to
857standard error. This is especially useful when one is using a
858debugger such as gdb. For example, here is the output
859of <tt>FooCFG->dump()</tt>:</p>
860
861<code>
862&nbsp;[ B5 (ENTRY) ]<br>
863&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (0):<br>
864&nbsp;&nbsp;&nbsp;&nbsp;Successors (1): B4<br>
865<br>
866&nbsp;[ B4 ]<br>
867&nbsp;&nbsp;&nbsp;&nbsp;1: x = x + 1<br>
868&nbsp;&nbsp;&nbsp;&nbsp;2: (x > 2)<br>
869&nbsp;&nbsp;&nbsp;&nbsp;<b>T: if [B4.2]</b><br>
870&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (1): B5<br>
871&nbsp;&nbsp;&nbsp;&nbsp;Successors (2): B3 B2<br>
872<br>
873&nbsp;[ B3 ]<br>
874&nbsp;&nbsp;&nbsp;&nbsp;1: x++<br>
875&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (1): B4<br>
876&nbsp;&nbsp;&nbsp;&nbsp;Successors (1): B1<br>
877<br>
878&nbsp;[ B2 ]<br>
879&nbsp;&nbsp;&nbsp;&nbsp;1: x += 2<br>
880&nbsp;&nbsp;&nbsp;&nbsp;2: x *= 2<br>
881&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (1): B4<br>
882&nbsp;&nbsp;&nbsp;&nbsp;Successors (1): B1<br>
883<br>
884&nbsp;[ B1 ]<br>
885&nbsp;&nbsp;&nbsp;&nbsp;1: return x;<br>
886&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (2): B2 B3<br>
887&nbsp;&nbsp;&nbsp;&nbsp;Successors (1): B0<br>
888<br>
889&nbsp;[ B0 (EXIT) ]<br>
890&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (1): B1<br>
891&nbsp;&nbsp;&nbsp;&nbsp;Successors (0):
892</code>
893
894<p>For each block, the pretty-printed output displays for each block
895the number of <i>predecessor</i> blocks (blocks that have outgoing
896control-flow to the given block) and <i>successor</i> blocks (blocks
897that have control-flow that have incoming control-flow from the given
898block). We can also clearly see the special entry and exit blocks at
899the beginning and end of the pretty-printed output. For the entry
900block (block B5), the number of predecessor blocks is 0, while for the
901exit block (block B0) the number of successor blocks is 0.</p>
902
903<p>The most interesting block here is B4, whose outgoing control-flow
904represents the branching caused by the sole if-statement
905in <tt>foo</tt>. Of particular interest is the second statement in
906the block, <b><tt>(x > 2)</tt></b>, and the terminator, printed
907as <b><tt>if [B4.2]</tt></b>. The second statement represents the
908evaluation of the condition of the if-statement, which occurs before
909the actual branching of control-flow. Within the <tt>CFGBlock</tt>
910for B4, the <tt>Stmt*</tt> for the second statement refers to the
911actual expression in the AST for <b><tt>(x > 2)</tt></b>. Thus
912pointers to subclasses of <tt>Expr</tt> can appear in the list of
913statements in a block, and not just subclasses of <tt>Stmt</tt> that
914refer to proper C statements.</p>
915
916<p>The terminator of block B4 is a pointer to the <tt>IfStmt</tt>
917object in the AST. The pretty-printer outputs <b><tt>if
918[B4.2]</tt></b> because the condition expression of the if-statement
919has an actual place in the basic block, and thus the terminator is
920essentially
921<i>referring</i> to the expression that is the second statement of
922block B4 (i.e., B4.2). In this manner, conditions for control-flow
923(which also includes conditions for loops and switch statements) are
924hoisted into the actual basic block.</p>
925
Chris Lattner62fd2782008-11-22 21:41:31 +0000926<!-- ===================== -->
927<!-- <h4>Implicit Control-Flow</h4> -->
928<!-- ===================== -->
Ted Kremenek8bc05712007-10-10 23:01:43 +0000929
930<!--
931<p>A key design principle of the <tt>CFG</tt> class was to not require
932any transformations to the AST in order to represent control-flow.
933Thus the <tt>CFG</tt> does not perform any "lowering" of the
934statements in an AST: loops are not transformed into guarded gotos,
935short-circuit operations are not converted to a set of if-statements,
936and so on.</p>
937-->
Ted Kremenek17a295d2008-06-11 06:19:49 +0000938
Chris Lattner7bad1992008-11-16 21:48:07 +0000939
940<!-- ======================================================================= -->
941<h3 id="Constants">Constant Folding in the Clang AST</h3>
942<!-- ======================================================================= -->
943
944<p>There are several places where constants and constant folding matter a lot to
945the Clang front-end. First, in general, we prefer the AST to retain the source
946code as close to how the user wrote it as possible. This means that if they
947wrote "5+4", we want to keep the addition and two constants in the AST, we don't
948want to fold to "9". This means that constant folding in various ways turns
949into a tree walk that needs to handle the various cases.</p>
950
951<p>However, there are places in both C and C++ that require constants to be
952folded. For example, the C standard defines what an "integer constant
953expression" (i-c-e) is with very precise and specific requirements. The
954language then requires i-c-e's in a lot of places (for example, the size of a
955bitfield, the value for a case statement, etc). For these, we have to be able
956to constant fold the constants, to do semantic checks (e.g. verify bitfield size
957is non-negative and that case statements aren't duplicated). We aim for Clang
958to be very pedantic about this, diagnosing cases when the code does not use an
959i-c-e where one is required, but accepting the code unless running with
960<tt>-pedantic-errors</tt>.</p>
961
962<p>Things get a little bit more tricky when it comes to compatibility with
963real-world source code. Specifically, GCC has historically accepted a huge
964superset of expressions as i-c-e's, and a lot of real world code depends on this
965unfortuate accident of history (including, e.g., the glibc system headers). GCC
966accepts anything its "fold" optimizer is capable of reducing to an integer
967constant, which means that the definition of what it accepts changes as its
968optimizer does. One example is that GCC accepts things like "case X-X:" even
969when X is a variable, because it can fold this to 0.</p>
970
971<p>Another issue are how constants interact with the extensions we support, such
972as __builtin_constant_p, __builtin_inf, __extension__ and many others. C99
973obviously does not specify the semantics of any of these extensions, and the
974definition of i-c-e does not include them. However, these extensions are often
975used in real code, and we have to have a way to reason about them.</p>
976
977<p>Finally, this is not just a problem for semantic analysis. The code
978generator and other clients have to be able to fold constants (e.g. to
979initialize global variables) and has to handle a superset of what C99 allows.
980Further, these clients can benefit from extended information. For example, we
981know that "foo()||1" always evaluates to true, but we can't replace the
982expression with true because it has side effects.</p>
983
984<!-- ======================= -->
985<h4>Implementation Approach</h4>
986<!-- ======================= -->
987
988<p>After trying several different approaches, we've finally converged on a
989design (Note, at the time of this writing, not all of this has been implemented,
990consider this a design goal!). Our basic approach is to define a single
991recursive method evaluation method (<tt>Expr::Evaluate</tt>), which is
992implemented in <tt>AST/ExprConstant.cpp</tt>. Given an expression with 'scalar'
993type (integer, fp, complex, or pointer) this method returns the following
994information:</p>
995
996<ul>
997<li>Whether the expression is an integer constant expression, a general
998 constant that was folded but has no side effects, a general constant that
999 was folded but that does have side effects, or an uncomputable/unfoldable
1000 value.
1001</li>
1002<li>If the expression was computable in any way, this method returns the APValue
1003 for the result of the expression.</li>
1004<li>If the expression is not evaluatable at all, this method returns
1005 information on one of the problems with the expression. This includes a
1006 SourceLocation for where the problem is, and a diagnostic ID that explains
1007 the problem. The diagnostic should be have ERROR type.</li>
1008<li>If the expression is not an integer constant expression, this method returns
1009 information on one of the problems with the expression. This includes a
1010 SourceLocation for where the problem is, and a diagnostic ID that explains
1011 the problem. The diagnostic should be have EXTENSION type.</li>
1012</ul>
1013
1014<p>This information gives various clients the flexibility that they want, and we
1015will eventually have some helper methods for various extensions. For example,
1016Sema should have a <tt>Sema::VerifyIntegerConstantExpression</tt> method, which
1017calls Evaluate on the expression. If the expression is not foldable, the error
1018is emitted, and it would return true. If the expression is not an i-c-e, the
1019EXTENSION diagnostic is emitted. Finally it would return false to indicate that
1020the AST is ok.</p>
1021
1022<p>Other clients can use the information in other ways, for example, codegen can
1023just use expressions that are foldable in any way.</p>
1024
1025<!-- ========== -->
1026<h4>Extensions</h4>
1027<!-- ========== -->
1028
1029<p>This section describes how some of the various extensions clang supports
1030interacts with constant evaluation:</p>
1031
1032<ul>
1033<li><b><tt>__extension__</tt></b>: The expression form of this extension causes
1034 any evaluatable subexpression to be accepted as an integer constant
1035 expression.</li>
1036<li><b><tt>__builtin_constant_p</tt></b>: This returns true (as a integer
1037 constant expression) if the operand is any evaluatable constant.</li>
1038<li><b><tt>__builtin_choose_expr</tt></b>: The condition is required to be an
1039 integer constant expression, but we accept any constant as an "extension of
1040 an extension". This only evaluates one operand depending on which way the
1041 condition evaluates.</li>
1042<li><b><tt>__builtin_classify_type</tt></b>: This always returns an integer
1043 constant expression.</li>
1044<li><b><tt>__builtin_inf,nan,..</tt></b>: These are treated just like a
1045 floating-point literal.</li>
1046<li><b><tt>__builtin_abs,copysign,..</tt></b>: These are constant folded as
1047 general constant expressions.</li>
1048</ul>
1049
1050
1051
1052
Ted Kremenek17a295d2008-06-11 06:19:49 +00001053</div>
1054</body>
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001055</html>