blob: 2e44640c98966b1f32d7c81b40e8d821cea2c515 [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 Gregore94ca9e42008-11-18 14:39:36 +0000472 stores. There are 8 options (all of the names are inside
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000473 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>
Douglas Gregore94ca9e42008-11-18 14:39:36 +0000517
518 <dt>CXXOperatorName</dt>
519 <dd>The name is a C++ overloaded operator name. Overloaded operators
520 are named according to their spelling, e.g.,
521 "<code>operator+</code>" or "<code>operator new
522 []</code>". Use <code>N.getCXXOverloadedOperator()</code> to
523 retrieve the overloaded operator (a value of
524 type <code>OverloadedOperatorKind</code>).</dd>
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000525</dl>
526
527<p><code>DeclarationName</code>s are cheap to create, copy, and
528 compare. They require only a single pointer's worth of storage in
Douglas Gregore94ca9e42008-11-18 14:39:36 +0000529 the common cases (identifiers, zero-
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000530 and one-argument Objective-C selectors) and use dense, uniqued
531 storage for the other kinds of
532 names. Two <code>DeclarationName</code>s can be compared for
533 equality (<code>==</code>, <code>!=</code>) using a simple bitwise
534 comparison, can be ordered
535 with <code>&lt;</code>, <code>&gt;</code>, <code>&lt;=</code>,
536 and <code>&gt;=</code> (which provide a lexicographical ordering for
537 normal identifiers but an unspecified ordering for other kinds of
538 names), and can be placed into LLVM <code>DenseMap</code>s
539 and <code>DenseSet</code>s.</p>
540
541<p><code>DeclarationName</code> instances can be created in different
542 ways depending on what kind of name the instance will store. Normal
Douglas Gregore94ca9e42008-11-18 14:39:36 +0000543 identifiers (<code>IdentifierInfo</code> pointers) and Objective-C selectors
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000544 (<code>Selector</code>) can be implicitly converted
545 to <code>DeclarationName</code>s. Names for C++ constructors,
Douglas Gregore94ca9e42008-11-18 14:39:36 +0000546 destructors, conversion functions, and overloaded operators can be retrieved from
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000547 the <code>DeclarationNameTable</code>, an instance of which is
548 available as <code>ASTContext::DeclarationNames</code>. The member
549 functions <code>getCXXConstructorName</code>, <code>getCXXDestructorName</code>,
Douglas Gregore94ca9e42008-11-18 14:39:36 +0000550 <code>getCXXConversionFunctionName</code>, and <code>getCXXOperatorName</code>, respectively,
551 return <code>DeclarationName</code> instances for the four kinds of
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000552 C++ special function names.</p>
553
554<!-- ======================================================================= -->
Ted Kremenek8bc05712007-10-10 23:01:43 +0000555<h3 id="CFG">The <tt>CFG</tt> class</h3>
556<!-- ======================================================================= -->
557
558<p>The <tt>CFG</tt> class is designed to represent a source-level
559control-flow graph for a single statement (<tt>Stmt*</tt>). Typically
560instances of <tt>CFG</tt> are constructed for function bodies (usually
561an instance of <tt>CompoundStmt</tt>), but can also be instantiated to
562represent the control-flow of any class that subclasses <tt>Stmt</tt>,
563which includes simple expressions. Control-flow graphs are especially
564useful for performing
565<a href="http://en.wikipedia.org/wiki/Data_flow_analysis#Sensitivities">flow-
566or path-sensitive</a> program analyses on a given function.</p>
567
568<h4>Basic Blocks</h4>
569
570<p>Concretely, an instance of <tt>CFG</tt> is a collection of basic
571blocks. Each basic block is an instance of <tt>CFGBlock</tt>, which
572simply contains an ordered sequence of <tt>Stmt*</tt> (each referring
573to statements in the AST). The ordering of statements within a block
574indicates unconditional flow of control from one statement to the
575next. <a href="#ConditionalControlFlow">Conditional control-flow</a>
576is represented using edges between basic blocks. The statements
577within a given <tt>CFGBlock</tt> can be traversed using
578the <tt>CFGBlock::*iterator</tt> interface.</p>
579
580<p>
Ted Kremenek18e17e72007-10-18 22:50:52 +0000581A <tt>CFG</tt> object owns the instances of <tt>CFGBlock</tt> within
Ted Kremenek8bc05712007-10-10 23:01:43 +0000582the control-flow graph it represents. Each <tt>CFGBlock</tt> within a
583CFG is also uniquely numbered (accessible
584via <tt>CFGBlock::getBlockID()</tt>). Currently the number is
585based on the ordering the blocks were created, but no assumptions
586should be made on how <tt>CFGBlock</tt>s are numbered other than their
587numbers are unique and that they are numbered from 0..N-1 (where N is
588the number of basic blocks in the CFG).</p>
589
590<h4>Entry and Exit Blocks</h4>
591
592Each instance of <tt>CFG</tt> contains two special blocks:
593an <i>entry</i> block (accessible via <tt>CFG::getEntry()</tt>), which
594has no incoming edges, and an <i>exit</i> block (accessible
595via <tt>CFG::getExit()</tt>), which has no outgoing edges. Neither
596block contains any statements, and they serve the role of providing a
597clear entrance and exit for a body of code such as a function body.
598The presence of these empty blocks greatly simplifies the
599implementation of many analyses built on top of CFGs.
600
601<h4 id ="ConditionalControlFlow">Conditional Control-Flow</h4>
602
603<p>Conditional control-flow (such as those induced by if-statements
604and loops) is represented as edges between <tt>CFGBlock</tt>s.
605Because different C language constructs can induce control-flow,
606each <tt>CFGBlock</tt> also records an extra <tt>Stmt*</tt> that
607represents the <i>terminator</i> of the block. A terminator is simply
608the statement that caused the control-flow, and is used to identify
609the nature of the conditional control-flow between blocks. For
610example, in the case of an if-statement, the terminator refers to
611the <tt>IfStmt</tt> object in the AST that represented the given
612branch.</p>
613
614<p>To illustrate, consider the following code example:</p>
615
616<code>
617int foo(int x) {<br>
618&nbsp;&nbsp;x = x + 1;<br>
619<br>
620&nbsp;&nbsp;if (x > 2) x++;<br>
621&nbsp;&nbsp;else {<br>
622&nbsp;&nbsp;&nbsp;&nbsp;x += 2;<br>
623&nbsp;&nbsp;&nbsp;&nbsp;x *= 2;<br>
624&nbsp;&nbsp;}<br>
625<br>
626&nbsp;&nbsp;return x;<br>
627}
628</code>
629
630<p>After invoking the parser+semantic analyzer on this code fragment,
631the AST of the body of <tt>foo</tt> is referenced by a
632single <tt>Stmt*</tt>. We can then construct an instance
633of <tt>CFG</tt> representing the control-flow graph of this function
634body by single call to a static class method:</p>
635
636<code>
637&nbsp;&nbsp;Stmt* FooBody = ...<br>
638&nbsp;&nbsp;CFG* FooCFG = <b>CFG::buildCFG</b>(FooBody);
639</code>
640
641<p>It is the responsibility of the caller of <tt>CFG::buildCFG</tt>
642to <tt>delete</tt> the returned <tt>CFG*</tt> when the CFG is no
643longer needed.</p>
644
645<p>Along with providing an interface to iterate over
646its <tt>CFGBlock</tt>s, the <tt>CFG</tt> class also provides methods
647that are useful for debugging and visualizing CFGs. For example, the
648method
649<tt>CFG::dump()</tt> dumps a pretty-printed version of the CFG to
650standard error. This is especially useful when one is using a
651debugger such as gdb. For example, here is the output
652of <tt>FooCFG->dump()</tt>:</p>
653
654<code>
655&nbsp;[ B5 (ENTRY) ]<br>
656&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (0):<br>
657&nbsp;&nbsp;&nbsp;&nbsp;Successors (1): B4<br>
658<br>
659&nbsp;[ B4 ]<br>
660&nbsp;&nbsp;&nbsp;&nbsp;1: x = x + 1<br>
661&nbsp;&nbsp;&nbsp;&nbsp;2: (x > 2)<br>
662&nbsp;&nbsp;&nbsp;&nbsp;<b>T: if [B4.2]</b><br>
663&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (1): B5<br>
664&nbsp;&nbsp;&nbsp;&nbsp;Successors (2): B3 B2<br>
665<br>
666&nbsp;[ B3 ]<br>
667&nbsp;&nbsp;&nbsp;&nbsp;1: x++<br>
668&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (1): B4<br>
669&nbsp;&nbsp;&nbsp;&nbsp;Successors (1): B1<br>
670<br>
671&nbsp;[ B2 ]<br>
672&nbsp;&nbsp;&nbsp;&nbsp;1: x += 2<br>
673&nbsp;&nbsp;&nbsp;&nbsp;2: x *= 2<br>
674&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (1): B4<br>
675&nbsp;&nbsp;&nbsp;&nbsp;Successors (1): B1<br>
676<br>
677&nbsp;[ B1 ]<br>
678&nbsp;&nbsp;&nbsp;&nbsp;1: return x;<br>
679&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (2): B2 B3<br>
680&nbsp;&nbsp;&nbsp;&nbsp;Successors (1): B0<br>
681<br>
682&nbsp;[ B0 (EXIT) ]<br>
683&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (1): B1<br>
684&nbsp;&nbsp;&nbsp;&nbsp;Successors (0):
685</code>
686
687<p>For each block, the pretty-printed output displays for each block
688the number of <i>predecessor</i> blocks (blocks that have outgoing
689control-flow to the given block) and <i>successor</i> blocks (blocks
690that have control-flow that have incoming control-flow from the given
691block). We can also clearly see the special entry and exit blocks at
692the beginning and end of the pretty-printed output. For the entry
693block (block B5), the number of predecessor blocks is 0, while for the
694exit block (block B0) the number of successor blocks is 0.</p>
695
696<p>The most interesting block here is B4, whose outgoing control-flow
697represents the branching caused by the sole if-statement
698in <tt>foo</tt>. Of particular interest is the second statement in
699the block, <b><tt>(x > 2)</tt></b>, and the terminator, printed
700as <b><tt>if [B4.2]</tt></b>. The second statement represents the
701evaluation of the condition of the if-statement, which occurs before
702the actual branching of control-flow. Within the <tt>CFGBlock</tt>
703for B4, the <tt>Stmt*</tt> for the second statement refers to the
704actual expression in the AST for <b><tt>(x > 2)</tt></b>. Thus
705pointers to subclasses of <tt>Expr</tt> can appear in the list of
706statements in a block, and not just subclasses of <tt>Stmt</tt> that
707refer to proper C statements.</p>
708
709<p>The terminator of block B4 is a pointer to the <tt>IfStmt</tt>
710object in the AST. The pretty-printer outputs <b><tt>if
711[B4.2]</tt></b> because the condition expression of the if-statement
712has an actual place in the basic block, and thus the terminator is
713essentially
714<i>referring</i> to the expression that is the second statement of
715block B4 (i.e., B4.2). In this manner, conditions for control-flow
716(which also includes conditions for loops and switch statements) are
717hoisted into the actual basic block.</p>
718
Ted Kremenek98f19b62007-10-10 23:22:00 +0000719<!--
Ted Kremenek8bc05712007-10-10 23:01:43 +0000720<h4>Implicit Control-Flow</h4>
Ted Kremenek98f19b62007-10-10 23:22:00 +0000721-->
Ted Kremenek8bc05712007-10-10 23:01:43 +0000722
723<!--
724<p>A key design principle of the <tt>CFG</tt> class was to not require
725any transformations to the AST in order to represent control-flow.
726Thus the <tt>CFG</tt> does not perform any "lowering" of the
727statements in an AST: loops are not transformed into guarded gotos,
728short-circuit operations are not converted to a set of if-statements,
729and so on.</p>
730-->
Ted Kremenek17a295d2008-06-11 06:19:49 +0000731
Chris Lattner7bad1992008-11-16 21:48:07 +0000732
733<!-- ======================================================================= -->
734<h3 id="Constants">Constant Folding in the Clang AST</h3>
735<!-- ======================================================================= -->
736
737<p>There are several places where constants and constant folding matter a lot to
738the Clang front-end. First, in general, we prefer the AST to retain the source
739code as close to how the user wrote it as possible. This means that if they
740wrote "5+4", we want to keep the addition and two constants in the AST, we don't
741want to fold to "9". This means that constant folding in various ways turns
742into a tree walk that needs to handle the various cases.</p>
743
744<p>However, there are places in both C and C++ that require constants to be
745folded. For example, the C standard defines what an "integer constant
746expression" (i-c-e) is with very precise and specific requirements. The
747language then requires i-c-e's in a lot of places (for example, the size of a
748bitfield, the value for a case statement, etc). For these, we have to be able
749to constant fold the constants, to do semantic checks (e.g. verify bitfield size
750is non-negative and that case statements aren't duplicated). We aim for Clang
751to be very pedantic about this, diagnosing cases when the code does not use an
752i-c-e where one is required, but accepting the code unless running with
753<tt>-pedantic-errors</tt>.</p>
754
755<p>Things get a little bit more tricky when it comes to compatibility with
756real-world source code. Specifically, GCC has historically accepted a huge
757superset of expressions as i-c-e's, and a lot of real world code depends on this
758unfortuate accident of history (including, e.g., the glibc system headers). GCC
759accepts anything its "fold" optimizer is capable of reducing to an integer
760constant, which means that the definition of what it accepts changes as its
761optimizer does. One example is that GCC accepts things like "case X-X:" even
762when X is a variable, because it can fold this to 0.</p>
763
764<p>Another issue are how constants interact with the extensions we support, such
765as __builtin_constant_p, __builtin_inf, __extension__ and many others. C99
766obviously does not specify the semantics of any of these extensions, and the
767definition of i-c-e does not include them. However, these extensions are often
768used in real code, and we have to have a way to reason about them.</p>
769
770<p>Finally, this is not just a problem for semantic analysis. The code
771generator and other clients have to be able to fold constants (e.g. to
772initialize global variables) and has to handle a superset of what C99 allows.
773Further, these clients can benefit from extended information. For example, we
774know that "foo()||1" always evaluates to true, but we can't replace the
775expression with true because it has side effects.</p>
776
777<!-- ======================= -->
778<h4>Implementation Approach</h4>
779<!-- ======================= -->
780
781<p>After trying several different approaches, we've finally converged on a
782design (Note, at the time of this writing, not all of this has been implemented,
783consider this a design goal!). Our basic approach is to define a single
784recursive method evaluation method (<tt>Expr::Evaluate</tt>), which is
785implemented in <tt>AST/ExprConstant.cpp</tt>. Given an expression with 'scalar'
786type (integer, fp, complex, or pointer) this method returns the following
787information:</p>
788
789<ul>
790<li>Whether the expression is an integer constant expression, a general
791 constant that was folded but has no side effects, a general constant that
792 was folded but that does have side effects, or an uncomputable/unfoldable
793 value.
794</li>
795<li>If the expression was computable in any way, this method returns the APValue
796 for the result of the expression.</li>
797<li>If the expression is not evaluatable at all, this method returns
798 information on one of the problems with the expression. This includes a
799 SourceLocation for where the problem is, and a diagnostic ID that explains
800 the problem. The diagnostic should be have ERROR type.</li>
801<li>If the expression is not an integer constant expression, this method returns
802 information on one of the problems with the expression. This includes a
803 SourceLocation for where the problem is, and a diagnostic ID that explains
804 the problem. The diagnostic should be have EXTENSION type.</li>
805</ul>
806
807<p>This information gives various clients the flexibility that they want, and we
808will eventually have some helper methods for various extensions. For example,
809Sema should have a <tt>Sema::VerifyIntegerConstantExpression</tt> method, which
810calls Evaluate on the expression. If the expression is not foldable, the error
811is emitted, and it would return true. If the expression is not an i-c-e, the
812EXTENSION diagnostic is emitted. Finally it would return false to indicate that
813the AST is ok.</p>
814
815<p>Other clients can use the information in other ways, for example, codegen can
816just use expressions that are foldable in any way.</p>
817
818<!-- ========== -->
819<h4>Extensions</h4>
820<!-- ========== -->
821
822<p>This section describes how some of the various extensions clang supports
823interacts with constant evaluation:</p>
824
825<ul>
826<li><b><tt>__extension__</tt></b>: The expression form of this extension causes
827 any evaluatable subexpression to be accepted as an integer constant
828 expression.</li>
829<li><b><tt>__builtin_constant_p</tt></b>: This returns true (as a integer
830 constant expression) if the operand is any evaluatable constant.</li>
831<li><b><tt>__builtin_choose_expr</tt></b>: The condition is required to be an
832 integer constant expression, but we accept any constant as an "extension of
833 an extension". This only evaluates one operand depending on which way the
834 condition evaluates.</li>
835<li><b><tt>__builtin_classify_type</tt></b>: This always returns an integer
836 constant expression.</li>
837<li><b><tt>__builtin_inf,nan,..</tt></b>: These are treated just like a
838 floating-point literal.</li>
839<li><b><tt>__builtin_abs,copysign,..</tt></b>: These are constant folded as
840 general constant expressions.</li>
841</ul>
842
843
844
845
Ted Kremenek17a295d2008-06-11 06:19:49 +0000846</div>
847</body>
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000848</html>