blob: d9c2701f6e13f4914ea7b4e3de60399c53f775d0 [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>
20 <li><a href="#SourceLocation">The SourceLocation and SourceManager
21 classes</a></li>
22 </ul>
23</li>
24<li><a href="#liblex">The Lexer and Preprocessor Library</a>
25 <ul>
26 <li><a href="#Token">The Token class</a></li>
27 <li><a href="#Lexer">The Lexer class</a></li>
Chris Lattner79281252008-03-09 02:27:26 +000028 <li><a href="#TokenLexer">The TokenLexer class</a></li>
Chris Lattner86920d32007-07-31 05:42:17 +000029 <li><a href="#MultipleIncludeOpt">The MultipleIncludeOpt class</a></li>
30 </ul>
31</li>
32<li><a href="#libparse">The Parser Library</a>
33 <ul>
34 </ul>
35</li>
36<li><a href="#libast">The AST Library</a>
37 <ul>
38 <li><a href="#Type">The Type class and its subclasses</a></li>
39 <li><a href="#QualType">The QualType class</a></li>
Douglas Gregor2e1cd422008-11-17 14:58:09 +000040 <li><a href="#DeclarationName">Declaration names</a></li>
Ted Kremenek8bc05712007-10-10 23:01:43 +000041 <li><a href="#CFG">The CFG class</a></li>
Chris Lattner7bad1992008-11-16 21:48:07 +000042 <li><a href="#Constants">Constant Folding in the Clang AST</a></li>
Chris Lattner86920d32007-07-31 05:42:17 +000043 </ul>
44</li>
45</ul>
46
47
48<!-- ======================================================================= -->
49<h2 id="intro">Introduction</h2>
50<!-- ======================================================================= -->
51
52<p>This document describes some of the more important APIs and internal design
53decisions made in the clang C front-end. The purpose of this document is to
54both capture some of this high level information and also describe some of the
55design decisions behind it. This is meant for people interested in hacking on
56clang, not for end-users. The description below is categorized by
57libraries, and does not describe any of the clients of the libraries.</p>
58
59<!-- ======================================================================= -->
60<h2 id="libsystem">LLVM System and Support Libraries</h2>
61<!-- ======================================================================= -->
62
63<p>The LLVM libsystem library provides the basic clang system abstraction layer,
64which is used for file system access. The LLVM libsupport library provides many
65underlying libraries and <a
66href="http://llvm.org/docs/ProgrammersManual.html">data-structures</a>,
67 including command line option
68processing and various containers.</p>
69
70<!-- ======================================================================= -->
71<h2 id="libbasic">The clang 'Basic' Library</h2>
72<!-- ======================================================================= -->
73
74<p>This library certainly needs a better name. The 'basic' library contains a
75number of low-level utilities for tracking and manipulating source buffers,
76locations within the source buffers, diagnostics, tokens, target abstraction,
77and information about the subset of the language being compiled for.</p>
78
79<p>Part of this infrastructure is specific to C (such as the TargetInfo class),
80other parts could be reused for other non-C-based languages (SourceLocation,
81SourceManager, Diagnostics, FileManager). When and if there is future demand
82we can figure out if it makes sense to introduce a new library, move the general
83classes somewhere else, or introduce some other solution.</p>
84
85<p>We describe the roles of these classes in order of their dependencies.</p>
86
87<!-- ======================================================================= -->
88<h3 id="SourceLocation">The SourceLocation and SourceManager classes</h3>
89<!-- ======================================================================= -->
90
91<p>Strangely enough, the SourceLocation class represents a location within the
92source code of the program. Important design points include:</p>
93
94<ol>
95<li>sizeof(SourceLocation) must be extremely small, as these are embedded into
96 many AST nodes and are passed around often. Currently it is 32 bits.</li>
97<li>SourceLocation must be a simple value object that can be efficiently
98 copied.</li>
99<li>We should be able to represent a source location for any byte of any input
100 file. This includes in the middle of tokens, in whitespace, in trigraphs,
101 etc.</li>
102<li>A SourceLocation must encode the current #include stack that was active when
103 the location was processed. For example, if the location corresponds to a
104 token, it should contain the set of #includes active when the token was
105 lexed. This allows us to print the #include stack for a diagnostic.</li>
106<li>SourceLocation must be able to describe macro expansions, capturing both
107 the ultimate instantiation point and the source of the original character
108 data.</li>
109</ol>
110
111<p>In practice, the SourceLocation works together with the SourceManager class
112to encode two pieces of information about a location: it's physical location
113and it's virtual location. For most tokens, these will be the same. However,
114for a macro expansion (or tokens that came from a _Pragma directive) these will
115describe the location of the characters corresponding to the token and the
116location where the token was used (i.e. the macro instantiation point or the
117location of the _Pragma itself).</p>
118
119<p>For efficiency, we only track one level of macro instantions: if a token was
120produced by multiple instantiations, we only track the source and ultimate
121destination. Though we could track the intermediate instantiation points, this
122would require extra bookkeeping and no known client would benefit substantially
123from this.</p>
124
125<p>The clang front-end inherently depends on the location of a token being
126tracked correctly. If it is ever incorrect, the front-end may get confused and
127die. The reason for this is that the notion of the 'spelling' of a Token in
128clang depends on being able to find the original input characters for the token.
129This concept maps directly to the "physical" location for the token.</p>
130
131<!-- ======================================================================= -->
132<h2 id="liblex">The Lexer and Preprocessor Library</h2>
133<!-- ======================================================================= -->
134
135<p>The Lexer library contains several tightly-connected classes that are involved
136with the nasty process of lexing and preprocessing C source code. The main
137interface to this library for outside clients is the large <a
138href="#Preprocessor">Preprocessor</a> class.
139It contains the various pieces of state that are required to coherently read
140tokens out of a translation unit.</p>
141
142<p>The core interface to the Preprocessor object (once it is set up) is the
143Preprocessor::Lex method, which returns the next <a href="#Token">Token</a> from
144the preprocessor stream. There are two types of token providers that the
145preprocessor is capable of reading from: a buffer lexer (provided by the <a
146href="#Lexer">Lexer</a> class) and a buffered token stream (provided by the <a
Chris Lattner79281252008-03-09 02:27:26 +0000147href="#TokenLexer">TokenLexer</a> class).
Chris Lattner86920d32007-07-31 05:42:17 +0000148
149
150<!-- ======================================================================= -->
151<h3 id="Token">The Token class</h3>
152<!-- ======================================================================= -->
153
154<p>The Token class is used to represent a single lexed token. Tokens are
155intended to be used by the lexer/preprocess and parser libraries, but are not
156intended to live beyond them (for example, they should not live in the ASTs).<p>
157
158<p>Tokens most often live on the stack (or some other location that is efficient
159to access) as the parser is running, but occasionally do get buffered up. For
160example, macro definitions are stored as a series of tokens, and the C++
161front-end will eventually need to buffer tokens up for tentative parsing and
162various pieces of look-ahead. As such, the size of a Token matter. On a 32-bit
163system, sizeof(Token) is currently 16 bytes.</p>
164
165<p>Tokens contain the following information:</p>
166
167<ul>
168<li><b>A SourceLocation</b> - This indicates the location of the start of the
169token.</li>
170
171<li><b>A length</b> - This stores the length of the token as stored in the
172SourceBuffer. For tokens that include them, this length includes trigraphs and
173escaped newlines which are ignored by later phases of the compiler. By pointing
174into the original source buffer, it is always possible to get the original
175spelling of a token completely accurately.</li>
176
177<li><b>IdentifierInfo</b> - If a token takes the form of an identifier, and if
178identifier lookup was enabled when the token was lexed (e.g. the lexer was not
179reading in 'raw' mode) this contains a pointer to the unique hash value for the
180identifier. Because the lookup happens before keyword identification, this
181field is set even for language keywords like 'for'.</li>
182
183<li><b>TokenKind</b> - This indicates the kind of token as classified by the
184lexer. This includes things like <tt>tok::starequal</tt> (for the "*="
185operator), <tt>tok::ampamp</tt> for the "&amp;&amp;" token, and keyword values
186(e.g. <tt>tok::kw_for</tt>) for identifiers that correspond to keywords. Note
187that some tokens can be spelled multiple ways. For example, C++ supports
188"operator keywords", where things like "and" are treated exactly like the
189"&amp;&amp;" operator. In these cases, the kind value is set to
190<tt>tok::ampamp</tt>, which is good for the parser, which doesn't have to
191consider both forms. For something that cares about which form is used (e.g.
192the preprocessor 'stringize' operator) the spelling indicates the original
193form.</li>
194
195<li><b>Flags</b> - There are currently four flags tracked by the
196lexer/preprocessor system on a per-token basis:
197
198 <ol>
199 <li><b>StartOfLine</b> - This was the first token that occurred on its input
200 source line.</li>
201 <li><b>LeadingSpace</b> - There was a space character either immediately
202 before the token or transitively before the token as it was expanded
203 through a macro. The definition of this flag is very closely defined by
204 the stringizing requirements of the preprocessor.</li>
205 <li><b>DisableExpand</b> - This flag is used internally to the preprocessor to
206 represent identifier tokens which have macro expansion disabled. This
207 prevents them from being considered as candidates for macro expansion ever
208 in the future.</li>
209 <li><b>NeedsCleaning</b> - This flag is set if the original spelling for the
210 token includes a trigraph or escaped newline. Since this is uncommon,
211 many pieces of code can fast-path on tokens that did not need cleaning.
212 </p>
213 </ol>
214</li>
215</ul>
216
217<p>One interesting (and somewhat unusual) aspect of tokens is that they don't
218contain any semantic information about the lexed value. For example, if the
219token was a pp-number token, we do not represent the value of the number that
220was lexed (this is left for later pieces of code to decide). Additionally, the
221lexer library has no notion of typedef names vs variable names: both are
222returned as identifiers, and the parser is left to decide whether a specific
223identifier is a typedef or a variable (tracking this requires scope information
224among other things).</p>
225
226<!-- ======================================================================= -->
227<h3 id="Lexer">The Lexer class</h3>
228<!-- ======================================================================= -->
229
230<p>The Lexer class provides the mechanics of lexing tokens out of a source
231buffer and deciding what they mean. The Lexer is complicated by the fact that
232it operates on raw buffers that have not had spelling eliminated (this is a
233necessity to get decent performance), but this is countered with careful coding
234as well as standard performance techniques (for example, the comment handling
235code is vectorized on X86 and PowerPC hosts).</p>
236
237<p>The lexer has a couple of interesting modal features:</p>
238
239<ul>
240<li>The lexer can operate in 'raw' mode. This mode has several features that
241 make it possible to quickly lex the file (e.g. it stops identifier lookup,
242 doesn't specially handle preprocessor tokens, handles EOF differently, etc).
243 This mode is used for lexing within an "<tt>#if 0</tt>" block, for
244 example.</li>
245<li>The lexer can capture and return comments as tokens. This is required to
246 support the -C preprocessor mode, which passes comments through, and is
247 used by the diagnostic checker to identifier expect-error annotations.</li>
248<li>The lexer can be in ParsingFilename mode, which happens when preprocessing
Chris Lattner84386242007-09-16 19:25:23 +0000249 after reading a #include directive. This mode changes the parsing of '&lt;'
Chris Lattner86920d32007-07-31 05:42:17 +0000250 to return an "angled string" instead of a bunch of tokens for each thing
251 within the filename.</li>
252<li>When parsing a preprocessor directive (after "<tt>#</tt>") the
253 ParsingPreprocessorDirective mode is entered. This changes the parser to
254 return EOM at a newline.</li>
255<li>The Lexer uses a LangOptions object to know whether trigraphs are enabled,
256 whether C++ or ObjC keywords are recognized, etc.</li>
257</ul>
258
259<p>In addition to these modes, the lexer keeps track of a couple of other
260 features that are local to a lexed buffer, which change as the buffer is
261 lexed:</p>
262
263<ul>
264<li>The Lexer uses BufferPtr to keep track of the current character being
265 lexed.</li>
266<li>The Lexer uses IsAtStartOfLine to keep track of whether the next lexed token
267 will start with its "start of line" bit set.</li>
268<li>The Lexer keeps track of the current #if directives that are active (which
269 can be nested).</li>
270<li>The Lexer keeps track of an <a href="#MultipleIncludeOpt">
271 MultipleIncludeOpt</a> object, which is used to
272 detect whether the buffer uses the standard "<tt>#ifndef XX</tt> /
273 <tt>#define XX</tt>" idiom to prevent multiple inclusion. If a buffer does,
274 subsequent includes can be ignored if the XX macro is defined.</li>
275</ul>
276
277<!-- ======================================================================= -->
Chris Lattner79281252008-03-09 02:27:26 +0000278<h3 id="TokenLexer">The TokenLexer class</h3>
Chris Lattner86920d32007-07-31 05:42:17 +0000279<!-- ======================================================================= -->
280
Chris Lattner79281252008-03-09 02:27:26 +0000281<p>The TokenLexer class is a token provider that returns tokens from a list
Chris Lattner86920d32007-07-31 05:42:17 +0000282of tokens that came from somewhere else. It typically used for two things: 1)
283returning tokens from a macro definition as it is being expanded 2) returning
284tokens from an arbitrary buffer of tokens. The later use is used by _Pragma and
285will most likely be used to handle unbounded look-ahead for the C++ parser.</p>
286
287<!-- ======================================================================= -->
288<h3 id="MultipleIncludeOpt">The MultipleIncludeOpt class</h3>
289<!-- ======================================================================= -->
290
291<p>The MultipleIncludeOpt class implements a really simple little state machine
292that is used to detect the standard "<tt>#ifndef XX</tt> / <tt>#define XX</tt>"
293idiom that people typically use to prevent multiple inclusion of headers. If a
294buffer uses this idiom and is subsequently #include'd, the preprocessor can
295simply check to see whether the guarding condition is defined or not. If so,
296the preprocessor can completely ignore the include of the header.</p>
297
298
299
300<!-- ======================================================================= -->
301<h2 id="libparse">The Parser Library</h2>
302<!-- ======================================================================= -->
303
304<!-- ======================================================================= -->
305<h2 id="libast">The AST Library</h2>
306<!-- ======================================================================= -->
307
308<!-- ======================================================================= -->
309<h3 id="Type">The Type class and its subclasses</h3>
310<!-- ======================================================================= -->
311
312<p>The Type class (and its subclasses) are an important part of the AST. Types
313are accessed through the ASTContext class, which implicitly creates and uniques
314them as they are needed. Types have a couple of non-obvious features: 1) they
315do not capture type qualifiers like const or volatile (See
316<a href="#QualType">QualType</a>), and 2) they implicitly capture typedef
Chris Lattner8a2bc622007-07-31 06:37:39 +0000317information. Once created, types are immutable (unlike decls).</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000318
319<p>Typedefs in C make semantic analysis a bit more complex than it would
320be without them. The issue is that we want to capture typedef information
321and represent it in the AST perfectly, but the semantics of operations need to
322"see through" typedefs. For example, consider this code:</p>
323
324<code>
325void func() {<br>
Bill Wendling30d17752007-10-06 01:56:01 +0000326&nbsp;&nbsp;typedef int foo;<br>
327&nbsp;&nbsp;foo X, *Y;<br>
328&nbsp;&nbsp;typedef foo* bar;<br>
329&nbsp;&nbsp;bar Z;<br>
330&nbsp;&nbsp;*X; <i>// error</i><br>
331&nbsp;&nbsp;**Y; <i>// error</i><br>
332&nbsp;&nbsp;**Z; <i>// error</i><br>
Chris Lattner86920d32007-07-31 05:42:17 +0000333}<br>
334</code>
335
336<p>The code above is illegal, and thus we expect there to be diagnostics emitted
337on the annotated lines. In this example, we expect to get:</p>
338
339<pre>
Chris Lattner8a2bc622007-07-31 06:37:39 +0000340<b>test.c:6:1: error: indirection requires pointer operand ('foo' invalid)</b>
Chris Lattner86920d32007-07-31 05:42:17 +0000341*X; // error
342<font color="blue">^~</font>
Chris Lattner8a2bc622007-07-31 06:37:39 +0000343<b>test.c:7:1: error: indirection requires pointer operand ('foo' invalid)</b>
Chris Lattner86920d32007-07-31 05:42:17 +0000344**Y; // error
345<font color="blue">^~~</font>
Chris Lattner8a2bc622007-07-31 06:37:39 +0000346<b>test.c:8:1: error: indirection requires pointer operand ('foo' invalid)</b>
347**Z; // error
348<font color="blue">^~~</font>
Chris Lattner86920d32007-07-31 05:42:17 +0000349</pre>
350
351<p>While this example is somewhat silly, it illustrates the point: we want to
352retain typedef information where possible, so that we can emit errors about
353"<tt>std::string</tt>" instead of "<tt>std::basic_string&lt;char, std:...</tt>".
354Doing this requires properly keeping typedef information (for example, the type
355of "X" is "foo", not "int"), and requires properly propagating it through the
Chris Lattner8a2bc622007-07-31 06:37:39 +0000356various operators (for example, the type of *Y is "foo", not "int"). In order
357to retain this information, the type of these expressions is an instance of the
358TypedefType class, which indicates that the type of these expressions is a
359typedef for foo.
360</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000361
Chris Lattner8a2bc622007-07-31 06:37:39 +0000362<p>Representing types like this is great for diagnostics, because the
363user-specified type is always immediately available. There are two problems
364with this: first, various semantic checks need to make judgements about the
Chris Lattner33fc68a2007-07-31 18:54:50 +0000365<em>actual structure</em> of a type, ignoring typdefs. Second, we need an
366efficient way to query whether two types are structurally identical to each
367other, ignoring typedefs. The solution to both of these problems is the idea of
Chris Lattner8a2bc622007-07-31 06:37:39 +0000368canonical types.</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000369
Chris Lattner8a2bc622007-07-31 06:37:39 +0000370<h4>Canonical Types</h4>
Chris Lattner86920d32007-07-31 05:42:17 +0000371
Chris Lattner8a2bc622007-07-31 06:37:39 +0000372<p>Every instance of the Type class contains a canonical type pointer. For
373simple types with no typedefs involved (e.g. "<tt>int</tt>", "<tt>int*</tt>",
374"<tt>int**</tt>"), the type just points to itself. For types that have a
375typedef somewhere in their structure (e.g. "<tt>foo</tt>", "<tt>foo*</tt>",
376"<tt>foo**</tt>", "<tt>bar</tt>"), the canonical type pointer points to their
377structurally equivalent type without any typedefs (e.g. "<tt>int</tt>",
378"<tt>int*</tt>", "<tt>int**</tt>", and "<tt>int*</tt>" respectively).</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000379
Chris Lattner8a2bc622007-07-31 06:37:39 +0000380<p>This design provides a constant time operation (dereferencing the canonical
381type pointer) that gives us access to the structure of types. For example,
382we can trivially tell that "bar" and "foo*" are the same type by dereferencing
383their canonical type pointers and doing a pointer comparison (they both point
384to the single "<tt>int*</tt>" type).</p>
385
386<p>Canonical types and typedef types bring up some complexities that must be
387carefully managed. Specifically, the "isa/cast/dyncast" operators generally
388shouldn't be used in code that is inspecting the AST. For example, when type
389checking the indirection operator (unary '*' on a pointer), the type checker
390must verify that the operand has a pointer type. It would not be correct to
391check that with "<tt>isa&lt;PointerType&gt;(SubExpr-&gt;getType())</tt>",
392because this predicate would fail if the subexpression had a typedef type.</p>
393
394<p>The solution to this problem are a set of helper methods on Type, used to
395check their properties. In this case, it would be correct to use
396"<tt>SubExpr-&gt;getType()-&gt;isPointerType()</tt>" to do the check. This
397predicate will return true if the <em>canonical type is a pointer</em>, which is
398true any time the type is structurally a pointer type. The only hard part here
399is remembering not to use the <tt>isa/cast/dyncast</tt> operations.</p>
400
401<p>The second problem we face is how to get access to the pointer type once we
402know it exists. To continue the example, the result type of the indirection
403operator is the pointee type of the subexpression. In order to determine the
404type, we need to get the instance of PointerType that best captures the typedef
405information in the program. If the type of the expression is literally a
406PointerType, we can return that, otherwise we have to dig through the
407typedefs to find the pointer type. For example, if the subexpression had type
408"<tt>foo*</tt>", we could return that type as the result. If the subexpression
409had type "<tt>bar</tt>", we want to return "<tt>foo*</tt>" (note that we do
410<em>not</em> want "<tt>int*</tt>"). In order to provide all of this, Type has
Chris Lattner11406c12007-07-31 16:50:51 +0000411a getAsPointerType() method that checks whether the type is structurally a
Chris Lattner8a2bc622007-07-31 06:37:39 +0000412PointerType and, if so, returns the best one. If not, it returns a null
413pointer.</p>
414
415<p>This structure is somewhat mystical, but after meditating on it, it will
416make sense to you :).</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000417
418<!-- ======================================================================= -->
419<h3 id="QualType">The QualType class</h3>
420<!-- ======================================================================= -->
421
422<p>The QualType class is designed as a trivial value class that is small,
423passed by-value and is efficient to query. The idea of QualType is that it
424stores the type qualifiers (const, volatile, restrict) separately from the types
425themselves: QualType is conceptually a pair of "Type*" and bits for the type
426qualifiers.</p>
427
428<p>By storing the type qualifiers as bits in the conceptual pair, it is
429extremely efficient to get the set of qualifiers on a QualType (just return the
430field of the pair), add a type qualifier (which is a trivial constant-time
431operation that sets a bit), and remove one or more type qualifiers (just return
432a QualType with the bitfield set to empty).</p>
433
434<p>Further, because the bits are stored outside of the type itself, we do not
435need to create duplicates of types with different sets of qualifiers (i.e. there
436is only a single heap allocated "int" type: "const int" and "volatile const int"
437both point to the same heap allocated "int" type). This reduces the heap size
438used to represent bits and also means we do not have to consider qualifiers when
439uniquing types (<a href="#Type">Type</a> does not even contain qualifiers).</p>
440
441<p>In practice, on hosts where it is safe, the 3 type qualifiers are stored in
442the low bit of the pointer to the Type object. This means that QualType is
443exactly the same size as a pointer, and this works fine on any system where
444malloc'd objects are at least 8 byte aligned.</p>
Ted Kremenek8bc05712007-10-10 23:01:43 +0000445
446<!-- ======================================================================= -->
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000447<h3 id="DeclarationName">Declaration names</h3>
448<!-- ======================================================================= -->
449
450<p>The <tt>DeclarationName</tt> class represents the name of a
451 declaration in Clang. Declarations in the C family of languages can
452 take several different forms. Most declarations are named by are
453 simple identifiers, e.g., "<code>f</code>" and "<code>x</code>" in
454 the function declaration <code>f(int x)</code>. In C++, declaration
455 names can also name class constructors ("<code>Class</code>"
456 in <code>struct Class { Class(); }</code>), class destructors
457 ("<code>~Class</code>"), overloaded operator names ("operator+"),
458 and conversion functions ("<code>operator void const *</code>"). In
459 Objective-C, declaration names can refer to the names of Objective-C
460 methods, which involve the method name and the parameters,
461 collectively called a <i>selector</i>, e.g..,
462 "<code>setWidth:height:</code>". Since all of these kinds of
463 entities--variables, functions, Objective-C methods, C++
464 constructors, destructors, and operators---are represented as
465 subclasses of Clang's common <code>NamedDecl</code>
466 class, <code>DeclarationName</code> is designed to efficiently
467 represent any kind of name.</p>
468
469<p>Given
470 a <code>DeclarationName</code> <code>N</code>, <code>N.getNameKind()</code>
Douglas Gregor2def4832008-11-17 20:34:05 +0000471 will produce a value that describes what kind of name <code>N</code>
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000472 stores. There are 7 options (all of the names are inside
473 the <code>DeclarationName</code> class)</p>
474<dl>
475 <dt>Identifier</dt>
476 <dd>The name is a simple
477 identifier. Use <code>N.getAsIdentifierInfo()</code> to retrieve the
478 corresponding <code>IdentifierInfo*</code> pointing to the actual
479 identifier. Note that C++ overloaded operators (e.g.,
480 "<code>operator+</code>") are represented as special kinds of
481 identifiers. Use <code>IdentifierInfo</code>'s <code>getOverloadedOperatorID</code>
482 function to determine whether an identifier is an overloaded
483 operator name.</dd>
484
485 <dt>ObjCZeroArgSelector, ObjCOneArgSelector,
486 ObjCMultiArgSelector</dt>
487 <dd>The name is an Objective-C selector, which can be retrieved as a
488 <code>Selector</code> instance
489 via <code>N.getObjCSelector()</code>. The three possible name
490 kinds for Objective-C reflect an optimization within
491 the <code>DeclarationName</code> class: both zero- and
492 one-argument selectors are stored as a
493 masked <code>IdentifierInfo</code> pointer, and therefore require
494 very little space, since zero- and one-argument selectors are far
495 more common than multi-argument selectors (which use a different
496 structure).</dd>
497
498 <dt>CXXConstructorName</dt>
499 <dd>The name is a C++ constructor
500 name. Use <code>N.getCXXNameType()</code> to retrieve
501 the <a href="#QualType">type</a> that this constructor is meant to
502 construct. The type is always the canonical type, since all
503 constructors for a given type have the same name.</dd>
504
505 <dt>CXXDestructorName</dt>
506 <dd>The name is a C++ destructor
507 name. Use <code>N.getCXXNameType()</code> to retrieve
508 the <a href="#QualType">type</a> whose destructor is being
509 named. This type is always a canonical type.</dd>
510
511 <dt>CXXConversionFunctionName</dt>
512 <dd>The name is a C++ conversion function. Conversion functions are
513 named according to the type they convert to, e.g., "<code>operator void
514 const *</code>". Use <code>N.getCXXNameType()</code> to retrieve
515 the type that this conversion function converts to. This type is
516 always a canonical type.</dd>
517</dl>
518
519<p><code>DeclarationName</code>s are cheap to create, copy, and
520 compare. They require only a single pointer's worth of storage in
521 the common cases (identifiers, C++ overloaded operator names, zero-
522 and one-argument Objective-C selectors) and use dense, uniqued
523 storage for the other kinds of
524 names. Two <code>DeclarationName</code>s can be compared for
525 equality (<code>==</code>, <code>!=</code>) using a simple bitwise
526 comparison, can be ordered
527 with <code>&lt;</code>, <code>&gt;</code>, <code>&lt;=</code>,
528 and <code>&gt;=</code> (which provide a lexicographical ordering for
529 normal identifiers but an unspecified ordering for other kinds of
530 names), and can be placed into LLVM <code>DenseMap</code>s
531 and <code>DenseSet</code>s.</p>
532
533<p><code>DeclarationName</code> instances can be created in different
534 ways depending on what kind of name the instance will store. Normal
535 identifiers (<code>IdentifierInfo</code> pointers), including
536 overloaded operator names, and Objective-C selectors
537 (<code>Selector</code>) can be implicitly converted
538 to <code>DeclarationName</code>s. Names for C++ constructors,
539 destructors, and conversion functions can be retrieved from
540 the <code>DeclarationNameTable</code>, an instance of which is
541 available as <code>ASTContext::DeclarationNames</code>. The member
542 functions <code>getCXXConstructorName</code>, <code>getCXXDestructorName</code>,
543 and <code>getCXXConversionFunctionName</code>, respectively,
544 return <code>DeclarationName</code> instances for the three kinds of
545 C++ special function names.</p>
546
547<!-- ======================================================================= -->
Ted Kremenek8bc05712007-10-10 23:01:43 +0000548<h3 id="CFG">The <tt>CFG</tt> class</h3>
549<!-- ======================================================================= -->
550
551<p>The <tt>CFG</tt> class is designed to represent a source-level
552control-flow graph for a single statement (<tt>Stmt*</tt>). Typically
553instances of <tt>CFG</tt> are constructed for function bodies (usually
554an instance of <tt>CompoundStmt</tt>), but can also be instantiated to
555represent the control-flow of any class that subclasses <tt>Stmt</tt>,
556which includes simple expressions. Control-flow graphs are especially
557useful for performing
558<a href="http://en.wikipedia.org/wiki/Data_flow_analysis#Sensitivities">flow-
559or path-sensitive</a> program analyses on a given function.</p>
560
561<h4>Basic Blocks</h4>
562
563<p>Concretely, an instance of <tt>CFG</tt> is a collection of basic
564blocks. Each basic block is an instance of <tt>CFGBlock</tt>, which
565simply contains an ordered sequence of <tt>Stmt*</tt> (each referring
566to statements in the AST). The ordering of statements within a block
567indicates unconditional flow of control from one statement to the
568next. <a href="#ConditionalControlFlow">Conditional control-flow</a>
569is represented using edges between basic blocks. The statements
570within a given <tt>CFGBlock</tt> can be traversed using
571the <tt>CFGBlock::*iterator</tt> interface.</p>
572
573<p>
Ted Kremenek18e17e72007-10-18 22:50:52 +0000574A <tt>CFG</tt> object owns the instances of <tt>CFGBlock</tt> within
Ted Kremenek8bc05712007-10-10 23:01:43 +0000575the control-flow graph it represents. Each <tt>CFGBlock</tt> within a
576CFG is also uniquely numbered (accessible
577via <tt>CFGBlock::getBlockID()</tt>). Currently the number is
578based on the ordering the blocks were created, but no assumptions
579should be made on how <tt>CFGBlock</tt>s are numbered other than their
580numbers are unique and that they are numbered from 0..N-1 (where N is
581the number of basic blocks in the CFG).</p>
582
583<h4>Entry and Exit Blocks</h4>
584
585Each instance of <tt>CFG</tt> contains two special blocks:
586an <i>entry</i> block (accessible via <tt>CFG::getEntry()</tt>), which
587has no incoming edges, and an <i>exit</i> block (accessible
588via <tt>CFG::getExit()</tt>), which has no outgoing edges. Neither
589block contains any statements, and they serve the role of providing a
590clear entrance and exit for a body of code such as a function body.
591The presence of these empty blocks greatly simplifies the
592implementation of many analyses built on top of CFGs.
593
594<h4 id ="ConditionalControlFlow">Conditional Control-Flow</h4>
595
596<p>Conditional control-flow (such as those induced by if-statements
597and loops) is represented as edges between <tt>CFGBlock</tt>s.
598Because different C language constructs can induce control-flow,
599each <tt>CFGBlock</tt> also records an extra <tt>Stmt*</tt> that
600represents the <i>terminator</i> of the block. A terminator is simply
601the statement that caused the control-flow, and is used to identify
602the nature of the conditional control-flow between blocks. For
603example, in the case of an if-statement, the terminator refers to
604the <tt>IfStmt</tt> object in the AST that represented the given
605branch.</p>
606
607<p>To illustrate, consider the following code example:</p>
608
609<code>
610int foo(int x) {<br>
611&nbsp;&nbsp;x = x + 1;<br>
612<br>
613&nbsp;&nbsp;if (x > 2) x++;<br>
614&nbsp;&nbsp;else {<br>
615&nbsp;&nbsp;&nbsp;&nbsp;x += 2;<br>
616&nbsp;&nbsp;&nbsp;&nbsp;x *= 2;<br>
617&nbsp;&nbsp;}<br>
618<br>
619&nbsp;&nbsp;return x;<br>
620}
621</code>
622
623<p>After invoking the parser+semantic analyzer on this code fragment,
624the AST of the body of <tt>foo</tt> is referenced by a
625single <tt>Stmt*</tt>. We can then construct an instance
626of <tt>CFG</tt> representing the control-flow graph of this function
627body by single call to a static class method:</p>
628
629<code>
630&nbsp;&nbsp;Stmt* FooBody = ...<br>
631&nbsp;&nbsp;CFG* FooCFG = <b>CFG::buildCFG</b>(FooBody);
632</code>
633
634<p>It is the responsibility of the caller of <tt>CFG::buildCFG</tt>
635to <tt>delete</tt> the returned <tt>CFG*</tt> when the CFG is no
636longer needed.</p>
637
638<p>Along with providing an interface to iterate over
639its <tt>CFGBlock</tt>s, the <tt>CFG</tt> class also provides methods
640that are useful for debugging and visualizing CFGs. For example, the
641method
642<tt>CFG::dump()</tt> dumps a pretty-printed version of the CFG to
643standard error. This is especially useful when one is using a
644debugger such as gdb. For example, here is the output
645of <tt>FooCFG->dump()</tt>:</p>
646
647<code>
648&nbsp;[ B5 (ENTRY) ]<br>
649&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (0):<br>
650&nbsp;&nbsp;&nbsp;&nbsp;Successors (1): B4<br>
651<br>
652&nbsp;[ B4 ]<br>
653&nbsp;&nbsp;&nbsp;&nbsp;1: x = x + 1<br>
654&nbsp;&nbsp;&nbsp;&nbsp;2: (x > 2)<br>
655&nbsp;&nbsp;&nbsp;&nbsp;<b>T: if [B4.2]</b><br>
656&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (1): B5<br>
657&nbsp;&nbsp;&nbsp;&nbsp;Successors (2): B3 B2<br>
658<br>
659&nbsp;[ B3 ]<br>
660&nbsp;&nbsp;&nbsp;&nbsp;1: x++<br>
661&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (1): B4<br>
662&nbsp;&nbsp;&nbsp;&nbsp;Successors (1): B1<br>
663<br>
664&nbsp;[ B2 ]<br>
665&nbsp;&nbsp;&nbsp;&nbsp;1: x += 2<br>
666&nbsp;&nbsp;&nbsp;&nbsp;2: x *= 2<br>
667&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (1): B4<br>
668&nbsp;&nbsp;&nbsp;&nbsp;Successors (1): B1<br>
669<br>
670&nbsp;[ B1 ]<br>
671&nbsp;&nbsp;&nbsp;&nbsp;1: return x;<br>
672&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (2): B2 B3<br>
673&nbsp;&nbsp;&nbsp;&nbsp;Successors (1): B0<br>
674<br>
675&nbsp;[ B0 (EXIT) ]<br>
676&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (1): B1<br>
677&nbsp;&nbsp;&nbsp;&nbsp;Successors (0):
678</code>
679
680<p>For each block, the pretty-printed output displays for each block
681the number of <i>predecessor</i> blocks (blocks that have outgoing
682control-flow to the given block) and <i>successor</i> blocks (blocks
683that have control-flow that have incoming control-flow from the given
684block). We can also clearly see the special entry and exit blocks at
685the beginning and end of the pretty-printed output. For the entry
686block (block B5), the number of predecessor blocks is 0, while for the
687exit block (block B0) the number of successor blocks is 0.</p>
688
689<p>The most interesting block here is B4, whose outgoing control-flow
690represents the branching caused by the sole if-statement
691in <tt>foo</tt>. Of particular interest is the second statement in
692the block, <b><tt>(x > 2)</tt></b>, and the terminator, printed
693as <b><tt>if [B4.2]</tt></b>. The second statement represents the
694evaluation of the condition of the if-statement, which occurs before
695the actual branching of control-flow. Within the <tt>CFGBlock</tt>
696for B4, the <tt>Stmt*</tt> for the second statement refers to the
697actual expression in the AST for <b><tt>(x > 2)</tt></b>. Thus
698pointers to subclasses of <tt>Expr</tt> can appear in the list of
699statements in a block, and not just subclasses of <tt>Stmt</tt> that
700refer to proper C statements.</p>
701
702<p>The terminator of block B4 is a pointer to the <tt>IfStmt</tt>
703object in the AST. The pretty-printer outputs <b><tt>if
704[B4.2]</tt></b> because the condition expression of the if-statement
705has an actual place in the basic block, and thus the terminator is
706essentially
707<i>referring</i> to the expression that is the second statement of
708block B4 (i.e., B4.2). In this manner, conditions for control-flow
709(which also includes conditions for loops and switch statements) are
710hoisted into the actual basic block.</p>
711
Ted Kremenek98f19b62007-10-10 23:22:00 +0000712<!--
Ted Kremenek8bc05712007-10-10 23:01:43 +0000713<h4>Implicit Control-Flow</h4>
Ted Kremenek98f19b62007-10-10 23:22:00 +0000714-->
Ted Kremenek8bc05712007-10-10 23:01:43 +0000715
716<!--
717<p>A key design principle of the <tt>CFG</tt> class was to not require
718any transformations to the AST in order to represent control-flow.
719Thus the <tt>CFG</tt> does not perform any "lowering" of the
720statements in an AST: loops are not transformed into guarded gotos,
721short-circuit operations are not converted to a set of if-statements,
722and so on.</p>
723-->
Ted Kremenek17a295d2008-06-11 06:19:49 +0000724
Chris Lattner7bad1992008-11-16 21:48:07 +0000725
726<!-- ======================================================================= -->
727<h3 id="Constants">Constant Folding in the Clang AST</h3>
728<!-- ======================================================================= -->
729
730<p>There are several places where constants and constant folding matter a lot to
731the Clang front-end. First, in general, we prefer the AST to retain the source
732code as close to how the user wrote it as possible. This means that if they
733wrote "5+4", we want to keep the addition and two constants in the AST, we don't
734want to fold to "9". This means that constant folding in various ways turns
735into a tree walk that needs to handle the various cases.</p>
736
737<p>However, there are places in both C and C++ that require constants to be
738folded. For example, the C standard defines what an "integer constant
739expression" (i-c-e) is with very precise and specific requirements. The
740language then requires i-c-e's in a lot of places (for example, the size of a
741bitfield, the value for a case statement, etc). For these, we have to be able
742to constant fold the constants, to do semantic checks (e.g. verify bitfield size
743is non-negative and that case statements aren't duplicated). We aim for Clang
744to be very pedantic about this, diagnosing cases when the code does not use an
745i-c-e where one is required, but accepting the code unless running with
746<tt>-pedantic-errors</tt>.</p>
747
748<p>Things get a little bit more tricky when it comes to compatibility with
749real-world source code. Specifically, GCC has historically accepted a huge
750superset of expressions as i-c-e's, and a lot of real world code depends on this
751unfortuate accident of history (including, e.g., the glibc system headers). GCC
752accepts anything its "fold" optimizer is capable of reducing to an integer
753constant, which means that the definition of what it accepts changes as its
754optimizer does. One example is that GCC accepts things like "case X-X:" even
755when X is a variable, because it can fold this to 0.</p>
756
757<p>Another issue are how constants interact with the extensions we support, such
758as __builtin_constant_p, __builtin_inf, __extension__ and many others. C99
759obviously does not specify the semantics of any of these extensions, and the
760definition of i-c-e does not include them. However, these extensions are often
761used in real code, and we have to have a way to reason about them.</p>
762
763<p>Finally, this is not just a problem for semantic analysis. The code
764generator and other clients have to be able to fold constants (e.g. to
765initialize global variables) and has to handle a superset of what C99 allows.
766Further, these clients can benefit from extended information. For example, we
767know that "foo()||1" always evaluates to true, but we can't replace the
768expression with true because it has side effects.</p>
769
770<!-- ======================= -->
771<h4>Implementation Approach</h4>
772<!-- ======================= -->
773
774<p>After trying several different approaches, we've finally converged on a
775design (Note, at the time of this writing, not all of this has been implemented,
776consider this a design goal!). Our basic approach is to define a single
777recursive method evaluation method (<tt>Expr::Evaluate</tt>), which is
778implemented in <tt>AST/ExprConstant.cpp</tt>. Given an expression with 'scalar'
779type (integer, fp, complex, or pointer) this method returns the following
780information:</p>
781
782<ul>
783<li>Whether the expression is an integer constant expression, a general
784 constant that was folded but has no side effects, a general constant that
785 was folded but that does have side effects, or an uncomputable/unfoldable
786 value.
787</li>
788<li>If the expression was computable in any way, this method returns the APValue
789 for the result of the expression.</li>
790<li>If the expression is not evaluatable at all, this method returns
791 information on one of the problems with the expression. This includes a
792 SourceLocation for where the problem is, and a diagnostic ID that explains
793 the problem. The diagnostic should be have ERROR type.</li>
794<li>If the expression is not an integer constant expression, this method returns
795 information on one of the problems with the expression. This includes a
796 SourceLocation for where the problem is, and a diagnostic ID that explains
797 the problem. The diagnostic should be have EXTENSION type.</li>
798</ul>
799
800<p>This information gives various clients the flexibility that they want, and we
801will eventually have some helper methods for various extensions. For example,
802Sema should have a <tt>Sema::VerifyIntegerConstantExpression</tt> method, which
803calls Evaluate on the expression. If the expression is not foldable, the error
804is emitted, and it would return true. If the expression is not an i-c-e, the
805EXTENSION diagnostic is emitted. Finally it would return false to indicate that
806the AST is ok.</p>
807
808<p>Other clients can use the information in other ways, for example, codegen can
809just use expressions that are foldable in any way.</p>
810
811<!-- ========== -->
812<h4>Extensions</h4>
813<!-- ========== -->
814
815<p>This section describes how some of the various extensions clang supports
816interacts with constant evaluation:</p>
817
818<ul>
819<li><b><tt>__extension__</tt></b>: The expression form of this extension causes
820 any evaluatable subexpression to be accepted as an integer constant
821 expression.</li>
822<li><b><tt>__builtin_constant_p</tt></b>: This returns true (as a integer
823 constant expression) if the operand is any evaluatable constant.</li>
824<li><b><tt>__builtin_choose_expr</tt></b>: The condition is required to be an
825 integer constant expression, but we accept any constant as an "extension of
826 an extension". This only evaluates one operand depending on which way the
827 condition evaluates.</li>
828<li><b><tt>__builtin_classify_type</tt></b>: This always returns an integer
829 constant expression.</li>
830<li><b><tt>__builtin_inf,nan,..</tt></b>: These are treated just like a
831 floating-point literal.</li>
832<li><b><tt>__builtin_abs,copysign,..</tt></b>: These are constant folded as
833 general constant expressions.</li>
834</ul>
835
836
837
838
Ted Kremenek17a295d2008-06-11 06:19:49 +0000839</div>
840</body>
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000841</html>