annotate clang/docs/InternalsManual.rst @ 168:980e56f2e095

...
author anatofuz
date Tue, 14 Apr 2020 15:43:20 +0900
parents 1d019706d866
children 0572611fdcc8
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
rev   line source
150
anatofuz
parents:
diff changeset
1 ============================
anatofuz
parents:
diff changeset
2 "Clang" CFE Internals Manual
anatofuz
parents:
diff changeset
3 ============================
anatofuz
parents:
diff changeset
4
anatofuz
parents:
diff changeset
5 .. contents::
anatofuz
parents:
diff changeset
6 :local:
anatofuz
parents:
diff changeset
7
anatofuz
parents:
diff changeset
8 Introduction
anatofuz
parents:
diff changeset
9 ============
anatofuz
parents:
diff changeset
10
anatofuz
parents:
diff changeset
11 This document describes some of the more important APIs and internal design
anatofuz
parents:
diff changeset
12 decisions made in the Clang C front-end. The purpose of this document is to
anatofuz
parents:
diff changeset
13 both capture some of this high level information and also describe some of the
anatofuz
parents:
diff changeset
14 design decisions behind it. This is meant for people interested in hacking on
anatofuz
parents:
diff changeset
15 Clang, not for end-users. The description below is categorized by libraries,
anatofuz
parents:
diff changeset
16 and does not describe any of the clients of the libraries.
anatofuz
parents:
diff changeset
17
anatofuz
parents:
diff changeset
18 LLVM Support Library
anatofuz
parents:
diff changeset
19 ====================
anatofuz
parents:
diff changeset
20
anatofuz
parents:
diff changeset
21 The LLVM ``libSupport`` library provides many underlying libraries and
anatofuz
parents:
diff changeset
22 `data-structures <https://llvm.org/docs/ProgrammersManual.html>`_, including
anatofuz
parents:
diff changeset
23 command line option processing, various containers and a system abstraction
anatofuz
parents:
diff changeset
24 layer, which is used for file system access.
anatofuz
parents:
diff changeset
25
anatofuz
parents:
diff changeset
26 The Clang "Basic" Library
anatofuz
parents:
diff changeset
27 =========================
anatofuz
parents:
diff changeset
28
anatofuz
parents:
diff changeset
29 This library certainly needs a better name. The "basic" library contains a
anatofuz
parents:
diff changeset
30 number of low-level utilities for tracking and manipulating source buffers,
anatofuz
parents:
diff changeset
31 locations within the source buffers, diagnostics, tokens, target abstraction,
anatofuz
parents:
diff changeset
32 and information about the subset of the language being compiled for.
anatofuz
parents:
diff changeset
33
anatofuz
parents:
diff changeset
34 Part of this infrastructure is specific to C (such as the ``TargetInfo``
anatofuz
parents:
diff changeset
35 class), other parts could be reused for other non-C-based languages
anatofuz
parents:
diff changeset
36 (``SourceLocation``, ``SourceManager``, ``Diagnostics``, ``FileManager``).
anatofuz
parents:
diff changeset
37 When and if there is future demand we can figure out if it makes sense to
anatofuz
parents:
diff changeset
38 introduce a new library, move the general classes somewhere else, or introduce
anatofuz
parents:
diff changeset
39 some other solution.
anatofuz
parents:
diff changeset
40
anatofuz
parents:
diff changeset
41 We describe the roles of these classes in order of their dependencies.
anatofuz
parents:
diff changeset
42
anatofuz
parents:
diff changeset
43 The Diagnostics Subsystem
anatofuz
parents:
diff changeset
44 -------------------------
anatofuz
parents:
diff changeset
45
anatofuz
parents:
diff changeset
46 The Clang Diagnostics subsystem is an important part of how the compiler
anatofuz
parents:
diff changeset
47 communicates with the human. Diagnostics are the warnings and errors produced
anatofuz
parents:
diff changeset
48 when the code is incorrect or dubious. In Clang, each diagnostic produced has
anatofuz
parents:
diff changeset
49 (at the minimum) a unique ID, an English translation associated with it, a
anatofuz
parents:
diff changeset
50 :ref:`SourceLocation <SourceLocation>` to "put the caret", and a severity
anatofuz
parents:
diff changeset
51 (e.g., ``WARNING`` or ``ERROR``). They can also optionally include a number of
anatofuz
parents:
diff changeset
52 arguments to the diagnostic (which fill in "%0"'s in the string) as well as a
anatofuz
parents:
diff changeset
53 number of source ranges that related to the diagnostic.
anatofuz
parents:
diff changeset
54
anatofuz
parents:
diff changeset
55 In this section, we'll be giving examples produced by the Clang command line
anatofuz
parents:
diff changeset
56 driver, but diagnostics can be :ref:`rendered in many different ways
anatofuz
parents:
diff changeset
57 <DiagnosticConsumer>` depending on how the ``DiagnosticConsumer`` interface is
anatofuz
parents:
diff changeset
58 implemented. A representative example of a diagnostic is:
anatofuz
parents:
diff changeset
59
anatofuz
parents:
diff changeset
60 .. code-block:: text
anatofuz
parents:
diff changeset
61
anatofuz
parents:
diff changeset
62 t.c:38:15: error: invalid operands to binary expression ('int *' and '_Complex float')
anatofuz
parents:
diff changeset
63 P = (P-42) + Gamma*4;
anatofuz
parents:
diff changeset
64 ~~~~~~ ^ ~~~~~~~
anatofuz
parents:
diff changeset
65
anatofuz
parents:
diff changeset
66 In this example, you can see the English translation, the severity (error), you
anatofuz
parents:
diff changeset
67 can see the source location (the caret ("``^``") and file/line/column info),
anatofuz
parents:
diff changeset
68 the source ranges "``~~~~``", arguments to the diagnostic ("``int*``" and
anatofuz
parents:
diff changeset
69 "``_Complex float``"). You'll have to believe me that there is a unique ID
anatofuz
parents:
diff changeset
70 backing the diagnostic :).
anatofuz
parents:
diff changeset
71
anatofuz
parents:
diff changeset
72 Getting all of this to happen has several steps and involves many moving
anatofuz
parents:
diff changeset
73 pieces, this section describes them and talks about best practices when adding
anatofuz
parents:
diff changeset
74 a new diagnostic.
anatofuz
parents:
diff changeset
75
anatofuz
parents:
diff changeset
76 The ``Diagnostic*Kinds.td`` files
anatofuz
parents:
diff changeset
77 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
anatofuz
parents:
diff changeset
78
anatofuz
parents:
diff changeset
79 Diagnostics are created by adding an entry to one of the
anatofuz
parents:
diff changeset
80 ``clang/Basic/Diagnostic*Kinds.td`` files, depending on what library will be
anatofuz
parents:
diff changeset
81 using it. From this file, :program:`tblgen` generates the unique ID of the
anatofuz
parents:
diff changeset
82 diagnostic, the severity of the diagnostic and the English translation + format
anatofuz
parents:
diff changeset
83 string.
anatofuz
parents:
diff changeset
84
anatofuz
parents:
diff changeset
85 There is little sanity with the naming of the unique ID's right now. Some
anatofuz
parents:
diff changeset
86 start with ``err_``, ``warn_``, ``ext_`` to encode the severity into the name.
anatofuz
parents:
diff changeset
87 Since the enum is referenced in the C++ code that produces the diagnostic, it
anatofuz
parents:
diff changeset
88 is somewhat useful for it to be reasonably short.
anatofuz
parents:
diff changeset
89
anatofuz
parents:
diff changeset
90 The severity of the diagnostic comes from the set {``NOTE``, ``REMARK``,
anatofuz
parents:
diff changeset
91 ``WARNING``,
anatofuz
parents:
diff changeset
92 ``EXTENSION``, ``EXTWARN``, ``ERROR``}. The ``ERROR`` severity is used for
anatofuz
parents:
diff changeset
93 diagnostics indicating the program is never acceptable under any circumstances.
anatofuz
parents:
diff changeset
94 When an error is emitted, the AST for the input code may not be fully built.
anatofuz
parents:
diff changeset
95 The ``EXTENSION`` and ``EXTWARN`` severities are used for extensions to the
anatofuz
parents:
diff changeset
96 language that Clang accepts. This means that Clang fully understands and can
anatofuz
parents:
diff changeset
97 represent them in the AST, but we produce diagnostics to tell the user their
anatofuz
parents:
diff changeset
98 code is non-portable. The difference is that the former are ignored by
anatofuz
parents:
diff changeset
99 default, and the later warn by default. The ``WARNING`` severity is used for
anatofuz
parents:
diff changeset
100 constructs that are valid in the currently selected source language but that
anatofuz
parents:
diff changeset
101 are dubious in some way. The ``REMARK`` severity provides generic information
anatofuz
parents:
diff changeset
102 about the compilation that is not necessarily related to any dubious code. The
anatofuz
parents:
diff changeset
103 ``NOTE`` level is used to staple more information onto previous diagnostics.
anatofuz
parents:
diff changeset
104
anatofuz
parents:
diff changeset
105 These *severities* are mapped into a smaller set (the ``Diagnostic::Level``
anatofuz
parents:
diff changeset
106 enum, {``Ignored``, ``Note``, ``Remark``, ``Warning``, ``Error``, ``Fatal``}) of
anatofuz
parents:
diff changeset
107 output
anatofuz
parents:
diff changeset
108 *levels* by the diagnostics subsystem based on various configuration options.
anatofuz
parents:
diff changeset
109 Clang internally supports a fully fine grained mapping mechanism that allows
anatofuz
parents:
diff changeset
110 you to map almost any diagnostic to the output level that you want. The only
anatofuz
parents:
diff changeset
111 diagnostics that cannot be mapped are ``NOTE``\ s, which always follow the
anatofuz
parents:
diff changeset
112 severity of the previously emitted diagnostic and ``ERROR``\ s, which can only
anatofuz
parents:
diff changeset
113 be mapped to ``Fatal`` (it is not possible to turn an error into a warning, for
anatofuz
parents:
diff changeset
114 example).
anatofuz
parents:
diff changeset
115
anatofuz
parents:
diff changeset
116 Diagnostic mappings are used in many ways. For example, if the user specifies
anatofuz
parents:
diff changeset
117 ``-pedantic``, ``EXTENSION`` maps to ``Warning``, if they specify
anatofuz
parents:
diff changeset
118 ``-pedantic-errors``, it turns into ``Error``. This is used to implement
anatofuz
parents:
diff changeset
119 options like ``-Wunused_macros``, ``-Wundef`` etc.
anatofuz
parents:
diff changeset
120
anatofuz
parents:
diff changeset
121 Mapping to ``Fatal`` should only be used for diagnostics that are considered so
anatofuz
parents:
diff changeset
122 severe that error recovery won't be able to recover sensibly from them (thus
anatofuz
parents:
diff changeset
123 spewing a ton of bogus errors). One example of this class of error are failure
anatofuz
parents:
diff changeset
124 to ``#include`` a file.
anatofuz
parents:
diff changeset
125
anatofuz
parents:
diff changeset
126 The Format String
anatofuz
parents:
diff changeset
127 ^^^^^^^^^^^^^^^^^
anatofuz
parents:
diff changeset
128
anatofuz
parents:
diff changeset
129 The format string for the diagnostic is very simple, but it has some power. It
anatofuz
parents:
diff changeset
130 takes the form of a string in English with markers that indicate where and how
anatofuz
parents:
diff changeset
131 arguments to the diagnostic are inserted and formatted. For example, here are
anatofuz
parents:
diff changeset
132 some simple format strings:
anatofuz
parents:
diff changeset
133
anatofuz
parents:
diff changeset
134 .. code-block:: c++
anatofuz
parents:
diff changeset
135
anatofuz
parents:
diff changeset
136 "binary integer literals are an extension"
anatofuz
parents:
diff changeset
137 "format string contains '\\0' within the string body"
anatofuz
parents:
diff changeset
138 "more '%%' conversions than data arguments"
anatofuz
parents:
diff changeset
139 "invalid operands to binary expression (%0 and %1)"
anatofuz
parents:
diff changeset
140 "overloaded '%0' must be a %select{unary|binary|unary or binary}2 operator"
anatofuz
parents:
diff changeset
141 " (has %1 parameter%s1)"
anatofuz
parents:
diff changeset
142
anatofuz
parents:
diff changeset
143 These examples show some important points of format strings. You can use any
anatofuz
parents:
diff changeset
144 plain ASCII character in the diagnostic string except "``%``" without a
anatofuz
parents:
diff changeset
145 problem, but these are C strings, so you have to use and be aware of all the C
anatofuz
parents:
diff changeset
146 escape sequences (as in the second example). If you want to produce a "``%``"
anatofuz
parents:
diff changeset
147 in the output, use the "``%%``" escape sequence, like the third diagnostic.
anatofuz
parents:
diff changeset
148 Finally, Clang uses the "``%...[digit]``" sequences to specify where and how
anatofuz
parents:
diff changeset
149 arguments to the diagnostic are formatted.
anatofuz
parents:
diff changeset
150
anatofuz
parents:
diff changeset
151 Arguments to the diagnostic are numbered according to how they are specified by
anatofuz
parents:
diff changeset
152 the C++ code that :ref:`produces them <internals-producing-diag>`, and are
anatofuz
parents:
diff changeset
153 referenced by ``%0`` .. ``%9``. If you have more than 10 arguments to your
anatofuz
parents:
diff changeset
154 diagnostic, you are doing something wrong :). Unlike ``printf``, there is no
anatofuz
parents:
diff changeset
155 requirement that arguments to the diagnostic end up in the output in the same
anatofuz
parents:
diff changeset
156 order as they are specified, you could have a format string with "``%1 %0``"
anatofuz
parents:
diff changeset
157 that swaps them, for example. The text in between the percent and digit are
anatofuz
parents:
diff changeset
158 formatting instructions. If there are no instructions, the argument is just
anatofuz
parents:
diff changeset
159 turned into a string and substituted in.
anatofuz
parents:
diff changeset
160
anatofuz
parents:
diff changeset
161 Here are some "best practices" for writing the English format string:
anatofuz
parents:
diff changeset
162
anatofuz
parents:
diff changeset
163 * Keep the string short. It should ideally fit in the 80 column limit of the
anatofuz
parents:
diff changeset
164 ``DiagnosticKinds.td`` file. This avoids the diagnostic wrapping when
anatofuz
parents:
diff changeset
165 printed, and forces you to think about the important point you are conveying
anatofuz
parents:
diff changeset
166 with the diagnostic.
anatofuz
parents:
diff changeset
167 * Take advantage of location information. The user will be able to see the
anatofuz
parents:
diff changeset
168 line and location of the caret, so you don't need to tell them that the
anatofuz
parents:
diff changeset
169 problem is with the 4th argument to the function: just point to it.
anatofuz
parents:
diff changeset
170 * Do not capitalize the diagnostic string, and do not end it with a period.
anatofuz
parents:
diff changeset
171 * If you need to quote something in the diagnostic string, use single quotes.
anatofuz
parents:
diff changeset
172
anatofuz
parents:
diff changeset
173 Diagnostics should never take random English strings as arguments: you
anatofuz
parents:
diff changeset
174 shouldn't use "``you have a problem with %0``" and pass in things like "``your
anatofuz
parents:
diff changeset
175 argument``" or "``your return value``" as arguments. Doing this prevents
anatofuz
parents:
diff changeset
176 :ref:`translating <internals-diag-translation>` the Clang diagnostics to other
anatofuz
parents:
diff changeset
177 languages (because they'll get random English words in their otherwise
anatofuz
parents:
diff changeset
178 localized diagnostic). The exceptions to this are C/C++ language keywords
anatofuz
parents:
diff changeset
179 (e.g., ``auto``, ``const``, ``mutable``, etc) and C/C++ operators (``/=``).
anatofuz
parents:
diff changeset
180 Note that things like "pointer" and "reference" are not keywords. On the other
anatofuz
parents:
diff changeset
181 hand, you *can* include anything that comes from the user's source code,
anatofuz
parents:
diff changeset
182 including variable names, types, labels, etc. The "``select``" format can be
anatofuz
parents:
diff changeset
183 used to achieve this sort of thing in a localizable way, see below.
anatofuz
parents:
diff changeset
184
anatofuz
parents:
diff changeset
185 Formatting a Diagnostic Argument
anatofuz
parents:
diff changeset
186 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
anatofuz
parents:
diff changeset
187
anatofuz
parents:
diff changeset
188 Arguments to diagnostics are fully typed internally, and come from a couple
anatofuz
parents:
diff changeset
189 different classes: integers, types, names, and random strings. Depending on
anatofuz
parents:
diff changeset
190 the class of the argument, it can be optionally formatted in different ways.
anatofuz
parents:
diff changeset
191 This gives the ``DiagnosticConsumer`` information about what the argument means
anatofuz
parents:
diff changeset
192 without requiring it to use a specific presentation (consider this MVC for
anatofuz
parents:
diff changeset
193 Clang :).
anatofuz
parents:
diff changeset
194
anatofuz
parents:
diff changeset
195 Here are the different diagnostic argument formats currently supported by
anatofuz
parents:
diff changeset
196 Clang:
anatofuz
parents:
diff changeset
197
anatofuz
parents:
diff changeset
198 **"s" format**
anatofuz
parents:
diff changeset
199
anatofuz
parents:
diff changeset
200 Example:
anatofuz
parents:
diff changeset
201 ``"requires %1 parameter%s1"``
anatofuz
parents:
diff changeset
202 Class:
anatofuz
parents:
diff changeset
203 Integers
anatofuz
parents:
diff changeset
204 Description:
anatofuz
parents:
diff changeset
205 This is a simple formatter for integers that is useful when producing English
anatofuz
parents:
diff changeset
206 diagnostics. When the integer is 1, it prints as nothing. When the integer
anatofuz
parents:
diff changeset
207 is not 1, it prints as "``s``". This allows some simple grammatical forms to
anatofuz
parents:
diff changeset
208 be to be handled correctly, and eliminates the need to use gross things like
anatofuz
parents:
diff changeset
209 ``"requires %1 parameter(s)"``.
anatofuz
parents:
diff changeset
210
anatofuz
parents:
diff changeset
211 **"select" format**
anatofuz
parents:
diff changeset
212
anatofuz
parents:
diff changeset
213 Example:
anatofuz
parents:
diff changeset
214 ``"must be a %select{unary|binary|unary or binary}2 operator"``
anatofuz
parents:
diff changeset
215 Class:
anatofuz
parents:
diff changeset
216 Integers
anatofuz
parents:
diff changeset
217 Description:
anatofuz
parents:
diff changeset
218 This format specifier is used to merge multiple related diagnostics together
anatofuz
parents:
diff changeset
219 into one common one, without requiring the difference to be specified as an
anatofuz
parents:
diff changeset
220 English string argument. Instead of specifying the string, the diagnostic
anatofuz
parents:
diff changeset
221 gets an integer argument and the format string selects the numbered option.
anatofuz
parents:
diff changeset
222 In this case, the "``%2``" value must be an integer in the range [0..2]. If
anatofuz
parents:
diff changeset
223 it is 0, it prints "unary", if it is 1 it prints "binary" if it is 2, it
anatofuz
parents:
diff changeset
224 prints "unary or binary". This allows other language translations to
anatofuz
parents:
diff changeset
225 substitute reasonable words (or entire phrases) based on the semantics of the
anatofuz
parents:
diff changeset
226 diagnostic instead of having to do things textually. The selected string
anatofuz
parents:
diff changeset
227 does undergo formatting.
anatofuz
parents:
diff changeset
228
anatofuz
parents:
diff changeset
229 **"plural" format**
anatofuz
parents:
diff changeset
230
anatofuz
parents:
diff changeset
231 Example:
anatofuz
parents:
diff changeset
232 ``"you have %1 %plural{1:mouse|:mice}1 connected to your computer"``
anatofuz
parents:
diff changeset
233 Class:
anatofuz
parents:
diff changeset
234 Integers
anatofuz
parents:
diff changeset
235 Description:
anatofuz
parents:
diff changeset
236 This is a formatter for complex plural forms. It is designed to handle even
anatofuz
parents:
diff changeset
237 the requirements of languages with very complex plural forms, as many Baltic
anatofuz
parents:
diff changeset
238 languages have. The argument consists of a series of expression/form pairs,
anatofuz
parents:
diff changeset
239 separated by ":", where the first form whose expression evaluates to true is
anatofuz
parents:
diff changeset
240 the result of the modifier.
anatofuz
parents:
diff changeset
241
anatofuz
parents:
diff changeset
242 An expression can be empty, in which case it is always true. See the example
anatofuz
parents:
diff changeset
243 at the top. Otherwise, it is a series of one or more numeric conditions,
anatofuz
parents:
diff changeset
244 separated by ",". If any condition matches, the expression matches. Each
anatofuz
parents:
diff changeset
245 numeric condition can take one of three forms.
anatofuz
parents:
diff changeset
246
anatofuz
parents:
diff changeset
247 * number: A simple decimal number matches if the argument is the same as the
anatofuz
parents:
diff changeset
248 number. Example: ``"%plural{1:mouse|:mice}4"``
anatofuz
parents:
diff changeset
249 * range: A range in square brackets matches if the argument is within the
anatofuz
parents:
diff changeset
250 range. Then range is inclusive on both ends. Example:
anatofuz
parents:
diff changeset
251 ``"%plural{0:none|1:one|[2,5]:some|:many}2"``
anatofuz
parents:
diff changeset
252 * modulo: A modulo operator is followed by a number, and equals sign and
anatofuz
parents:
diff changeset
253 either a number or a range. The tests are the same as for plain numbers
anatofuz
parents:
diff changeset
254 and ranges, but the argument is taken modulo the number first. Example:
anatofuz
parents:
diff changeset
255 ``"%plural{%100=0:even hundred|%100=[1,50]:lower half|:everything else}1"``
anatofuz
parents:
diff changeset
256
anatofuz
parents:
diff changeset
257 The parser is very unforgiving. A syntax error, even whitespace, will abort,
anatofuz
parents:
diff changeset
258 as will a failure to match the argument against any expression.
anatofuz
parents:
diff changeset
259
anatofuz
parents:
diff changeset
260 **"ordinal" format**
anatofuz
parents:
diff changeset
261
anatofuz
parents:
diff changeset
262 Example:
anatofuz
parents:
diff changeset
263 ``"ambiguity in %ordinal0 argument"``
anatofuz
parents:
diff changeset
264 Class:
anatofuz
parents:
diff changeset
265 Integers
anatofuz
parents:
diff changeset
266 Description:
anatofuz
parents:
diff changeset
267 This is a formatter which represents the argument number as an ordinal: the
anatofuz
parents:
diff changeset
268 value ``1`` becomes ``1st``, ``3`` becomes ``3rd``, and so on. Values less
anatofuz
parents:
diff changeset
269 than ``1`` are not supported. This formatter is currently hard-coded to use
anatofuz
parents:
diff changeset
270 English ordinals.
anatofuz
parents:
diff changeset
271
anatofuz
parents:
diff changeset
272 **"objcclass" format**
anatofuz
parents:
diff changeset
273
anatofuz
parents:
diff changeset
274 Example:
anatofuz
parents:
diff changeset
275 ``"method %objcclass0 not found"``
anatofuz
parents:
diff changeset
276 Class:
anatofuz
parents:
diff changeset
277 ``DeclarationName``
anatofuz
parents:
diff changeset
278 Description:
anatofuz
parents:
diff changeset
279 This is a simple formatter that indicates the ``DeclarationName`` corresponds
anatofuz
parents:
diff changeset
280 to an Objective-C class method selector. As such, it prints the selector
anatofuz
parents:
diff changeset
281 with a leading "``+``".
anatofuz
parents:
diff changeset
282
anatofuz
parents:
diff changeset
283 **"objcinstance" format**
anatofuz
parents:
diff changeset
284
anatofuz
parents:
diff changeset
285 Example:
anatofuz
parents:
diff changeset
286 ``"method %objcinstance0 not found"``
anatofuz
parents:
diff changeset
287 Class:
anatofuz
parents:
diff changeset
288 ``DeclarationName``
anatofuz
parents:
diff changeset
289 Description:
anatofuz
parents:
diff changeset
290 This is a simple formatter that indicates the ``DeclarationName`` corresponds
anatofuz
parents:
diff changeset
291 to an Objective-C instance method selector. As such, it prints the selector
anatofuz
parents:
diff changeset
292 with a leading "``-``".
anatofuz
parents:
diff changeset
293
anatofuz
parents:
diff changeset
294 **"q" format**
anatofuz
parents:
diff changeset
295
anatofuz
parents:
diff changeset
296 Example:
anatofuz
parents:
diff changeset
297 ``"candidate found by name lookup is %q0"``
anatofuz
parents:
diff changeset
298 Class:
anatofuz
parents:
diff changeset
299 ``NamedDecl *``
anatofuz
parents:
diff changeset
300 Description:
anatofuz
parents:
diff changeset
301 This formatter indicates that the fully-qualified name of the declaration
anatofuz
parents:
diff changeset
302 should be printed, e.g., "``std::vector``" rather than "``vector``".
anatofuz
parents:
diff changeset
303
anatofuz
parents:
diff changeset
304 **"diff" format**
anatofuz
parents:
diff changeset
305
anatofuz
parents:
diff changeset
306 Example:
anatofuz
parents:
diff changeset
307 ``"no known conversion %diff{from $ to $|from argument type to parameter type}1,2"``
anatofuz
parents:
diff changeset
308 Class:
anatofuz
parents:
diff changeset
309 ``QualType``
anatofuz
parents:
diff changeset
310 Description:
anatofuz
parents:
diff changeset
311 This formatter takes two ``QualType``\ s and attempts to print a template
anatofuz
parents:
diff changeset
312 difference between the two. If tree printing is off, the text inside the
anatofuz
parents:
diff changeset
313 braces before the pipe is printed, with the formatted text replacing the $.
anatofuz
parents:
diff changeset
314 If tree printing is on, the text after the pipe is printed and a type tree is
anatofuz
parents:
diff changeset
315 printed after the diagnostic message.
anatofuz
parents:
diff changeset
316
anatofuz
parents:
diff changeset
317 It is really easy to add format specifiers to the Clang diagnostics system, but
anatofuz
parents:
diff changeset
318 they should be discussed before they are added. If you are creating a lot of
anatofuz
parents:
diff changeset
319 repetitive diagnostics and/or have an idea for a useful formatter, please bring
anatofuz
parents:
diff changeset
320 it up on the cfe-dev mailing list.
anatofuz
parents:
diff changeset
321
anatofuz
parents:
diff changeset
322 **"sub" format**
anatofuz
parents:
diff changeset
323
anatofuz
parents:
diff changeset
324 Example:
anatofuz
parents:
diff changeset
325 Given the following record definition of type ``TextSubstitution``:
anatofuz
parents:
diff changeset
326
anatofuz
parents:
diff changeset
327 .. code-block:: text
anatofuz
parents:
diff changeset
328
anatofuz
parents:
diff changeset
329 def select_ovl_candidate : TextSubstitution<
anatofuz
parents:
diff changeset
330 "%select{function|constructor}0%select{| template| %2}1">;
anatofuz
parents:
diff changeset
331
anatofuz
parents:
diff changeset
332 which can be used as
anatofuz
parents:
diff changeset
333
anatofuz
parents:
diff changeset
334 .. code-block:: text
anatofuz
parents:
diff changeset
335
anatofuz
parents:
diff changeset
336 def note_ovl_candidate : Note<
anatofuz
parents:
diff changeset
337 "candidate %sub{select_ovl_candidate}3,2,1 not viable">;
anatofuz
parents:
diff changeset
338
anatofuz
parents:
diff changeset
339 and will act as if it was written
anatofuz
parents:
diff changeset
340 ``"candidate %select{function|constructor}3%select{| template| %1}2 not viable"``.
anatofuz
parents:
diff changeset
341 Description:
anatofuz
parents:
diff changeset
342 This format specifier is used to avoid repeating strings verbatim in multiple
anatofuz
parents:
diff changeset
343 diagnostics. The argument to ``%sub`` must name a ``TextSubstitution`` tblgen
anatofuz
parents:
diff changeset
344 record. The substitution must specify all arguments used by the substitution,
anatofuz
parents:
diff changeset
345 and the modifier indexes in the substitution are re-numbered accordingly. The
anatofuz
parents:
diff changeset
346 substituted text must itself be a valid format string before substitution.
anatofuz
parents:
diff changeset
347
anatofuz
parents:
diff changeset
348 .. _internals-producing-diag:
anatofuz
parents:
diff changeset
349
anatofuz
parents:
diff changeset
350 Producing the Diagnostic
anatofuz
parents:
diff changeset
351 ^^^^^^^^^^^^^^^^^^^^^^^^
anatofuz
parents:
diff changeset
352
anatofuz
parents:
diff changeset
353 Now that you've created the diagnostic in the ``Diagnostic*Kinds.td`` file, you
anatofuz
parents:
diff changeset
354 need to write the code that detects the condition in question and emits the new
anatofuz
parents:
diff changeset
355 diagnostic. Various components of Clang (e.g., the preprocessor, ``Sema``,
anatofuz
parents:
diff changeset
356 etc.) provide a helper function named "``Diag``". It creates a diagnostic and
anatofuz
parents:
diff changeset
357 accepts the arguments, ranges, and other information that goes along with it.
anatofuz
parents:
diff changeset
358
anatofuz
parents:
diff changeset
359 For example, the binary expression error comes from code like this:
anatofuz
parents:
diff changeset
360
anatofuz
parents:
diff changeset
361 .. code-block:: c++
anatofuz
parents:
diff changeset
362
anatofuz
parents:
diff changeset
363 if (various things that are bad)
anatofuz
parents:
diff changeset
364 Diag(Loc, diag::err_typecheck_invalid_operands)
anatofuz
parents:
diff changeset
365 << lex->getType() << rex->getType()
anatofuz
parents:
diff changeset
366 << lex->getSourceRange() << rex->getSourceRange();
anatofuz
parents:
diff changeset
367
anatofuz
parents:
diff changeset
368 This shows that use of the ``Diag`` method: it takes a location (a
anatofuz
parents:
diff changeset
369 :ref:`SourceLocation <SourceLocation>` object) and a diagnostic enum value
anatofuz
parents:
diff changeset
370 (which matches the name from ``Diagnostic*Kinds.td``). If the diagnostic takes
anatofuz
parents:
diff changeset
371 arguments, they are specified with the ``<<`` operator: the first argument
anatofuz
parents:
diff changeset
372 becomes ``%0``, the second becomes ``%1``, etc. The diagnostic interface
anatofuz
parents:
diff changeset
373 allows you to specify arguments of many different types, including ``int`` and
anatofuz
parents:
diff changeset
374 ``unsigned`` for integer arguments, ``const char*`` and ``std::string`` for
anatofuz
parents:
diff changeset
375 string arguments, ``DeclarationName`` and ``const IdentifierInfo *`` for names,
anatofuz
parents:
diff changeset
376 ``QualType`` for types, etc. ``SourceRange``\ s are also specified with the
anatofuz
parents:
diff changeset
377 ``<<`` operator, but do not have a specific ordering requirement.
anatofuz
parents:
diff changeset
378
anatofuz
parents:
diff changeset
379 As you can see, adding and producing a diagnostic is pretty straightforward.
anatofuz
parents:
diff changeset
380 The hard part is deciding exactly what you need to say to help the user,
anatofuz
parents:
diff changeset
381 picking a suitable wording, and providing the information needed to format it
anatofuz
parents:
diff changeset
382 correctly. The good news is that the call site that issues a diagnostic should
anatofuz
parents:
diff changeset
383 be completely independent of how the diagnostic is formatted and in what
anatofuz
parents:
diff changeset
384 language it is rendered.
anatofuz
parents:
diff changeset
385
anatofuz
parents:
diff changeset
386 Fix-It Hints
anatofuz
parents:
diff changeset
387 ^^^^^^^^^^^^
anatofuz
parents:
diff changeset
388
anatofuz
parents:
diff changeset
389 In some cases, the front end emits diagnostics when it is clear that some small
anatofuz
parents:
diff changeset
390 change to the source code would fix the problem. For example, a missing
anatofuz
parents:
diff changeset
391 semicolon at the end of a statement or a use of deprecated syntax that is
anatofuz
parents:
diff changeset
392 easily rewritten into a more modern form. Clang tries very hard to emit the
anatofuz
parents:
diff changeset
393 diagnostic and recover gracefully in these and other cases.
anatofuz
parents:
diff changeset
394
anatofuz
parents:
diff changeset
395 However, for these cases where the fix is obvious, the diagnostic can be
anatofuz
parents:
diff changeset
396 annotated with a hint (referred to as a "fix-it hint") that describes how to
anatofuz
parents:
diff changeset
397 change the code referenced by the diagnostic to fix the problem. For example,
anatofuz
parents:
diff changeset
398 it might add the missing semicolon at the end of the statement or rewrite the
anatofuz
parents:
diff changeset
399 use of a deprecated construct into something more palatable. Here is one such
anatofuz
parents:
diff changeset
400 example from the C++ front end, where we warn about the right-shift operator
anatofuz
parents:
diff changeset
401 changing meaning from C++98 to C++11:
anatofuz
parents:
diff changeset
402
anatofuz
parents:
diff changeset
403 .. code-block:: text
anatofuz
parents:
diff changeset
404
anatofuz
parents:
diff changeset
405 test.cpp:3:7: warning: use of right-shift operator ('>>') in template argument
anatofuz
parents:
diff changeset
406 will require parentheses in C++11
anatofuz
parents:
diff changeset
407 A<100 >> 2> *a;
anatofuz
parents:
diff changeset
408 ^
anatofuz
parents:
diff changeset
409 ( )
anatofuz
parents:
diff changeset
410
anatofuz
parents:
diff changeset
411 Here, the fix-it hint is suggesting that parentheses be added, and showing
anatofuz
parents:
diff changeset
412 exactly where those parentheses would be inserted into the source code. The
anatofuz
parents:
diff changeset
413 fix-it hints themselves describe what changes to make to the source code in an
anatofuz
parents:
diff changeset
414 abstract manner, which the text diagnostic printer renders as a line of
anatofuz
parents:
diff changeset
415 "insertions" below the caret line. :ref:`Other diagnostic clients
anatofuz
parents:
diff changeset
416 <DiagnosticConsumer>` might choose to render the code differently (e.g., as
anatofuz
parents:
diff changeset
417 markup inline) or even give the user the ability to automatically fix the
anatofuz
parents:
diff changeset
418 problem.
anatofuz
parents:
diff changeset
419
anatofuz
parents:
diff changeset
420 Fix-it hints on errors and warnings need to obey these rules:
anatofuz
parents:
diff changeset
421
anatofuz
parents:
diff changeset
422 * Since they are automatically applied if ``-Xclang -fixit`` is passed to the
anatofuz
parents:
diff changeset
423 driver, they should only be used when it's very likely they match the user's
anatofuz
parents:
diff changeset
424 intent.
anatofuz
parents:
diff changeset
425 * Clang must recover from errors as if the fix-it had been applied.
anatofuz
parents:
diff changeset
426 * Fix-it hints on a warning must not change the meaning of the code.
anatofuz
parents:
diff changeset
427 However, a hint may clarify the meaning as intentional, for example by adding
anatofuz
parents:
diff changeset
428 parentheses when the precedence of operators isn't obvious.
anatofuz
parents:
diff changeset
429
anatofuz
parents:
diff changeset
430 If a fix-it can't obey these rules, put the fix-it on a note. Fix-its on notes
anatofuz
parents:
diff changeset
431 are not applied automatically.
anatofuz
parents:
diff changeset
432
anatofuz
parents:
diff changeset
433 All fix-it hints are described by the ``FixItHint`` class, instances of which
anatofuz
parents:
diff changeset
434 should be attached to the diagnostic using the ``<<`` operator in the same way
anatofuz
parents:
diff changeset
435 that highlighted source ranges and arguments are passed to the diagnostic.
anatofuz
parents:
diff changeset
436 Fix-it hints can be created with one of three constructors:
anatofuz
parents:
diff changeset
437
anatofuz
parents:
diff changeset
438 * ``FixItHint::CreateInsertion(Loc, Code)``
anatofuz
parents:
diff changeset
439
anatofuz
parents:
diff changeset
440 Specifies that the given ``Code`` (a string) should be inserted before the
anatofuz
parents:
diff changeset
441 source location ``Loc``.
anatofuz
parents:
diff changeset
442
anatofuz
parents:
diff changeset
443 * ``FixItHint::CreateRemoval(Range)``
anatofuz
parents:
diff changeset
444
anatofuz
parents:
diff changeset
445 Specifies that the code in the given source ``Range`` should be removed.
anatofuz
parents:
diff changeset
446
anatofuz
parents:
diff changeset
447 * ``FixItHint::CreateReplacement(Range, Code)``
anatofuz
parents:
diff changeset
448
anatofuz
parents:
diff changeset
449 Specifies that the code in the given source ``Range`` should be removed,
anatofuz
parents:
diff changeset
450 and replaced with the given ``Code`` string.
anatofuz
parents:
diff changeset
451
anatofuz
parents:
diff changeset
452 .. _DiagnosticConsumer:
anatofuz
parents:
diff changeset
453
anatofuz
parents:
diff changeset
454 The ``DiagnosticConsumer`` Interface
anatofuz
parents:
diff changeset
455 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
anatofuz
parents:
diff changeset
456
anatofuz
parents:
diff changeset
457 Once code generates a diagnostic with all of the arguments and the rest of the
anatofuz
parents:
diff changeset
458 relevant information, Clang needs to know what to do with it. As previously
anatofuz
parents:
diff changeset
459 mentioned, the diagnostic machinery goes through some filtering to map a
anatofuz
parents:
diff changeset
460 severity onto a diagnostic level, then (assuming the diagnostic is not mapped
anatofuz
parents:
diff changeset
461 to "``Ignore``") it invokes an object that implements the ``DiagnosticConsumer``
anatofuz
parents:
diff changeset
462 interface with the information.
anatofuz
parents:
diff changeset
463
anatofuz
parents:
diff changeset
464 It is possible to implement this interface in many different ways. For
anatofuz
parents:
diff changeset
465 example, the normal Clang ``DiagnosticConsumer`` (named
anatofuz
parents:
diff changeset
466 ``TextDiagnosticPrinter``) turns the arguments into strings (according to the
anatofuz
parents:
diff changeset
467 various formatting rules), prints out the file/line/column information and the
anatofuz
parents:
diff changeset
468 string, then prints out the line of code, the source ranges, and the caret.
anatofuz
parents:
diff changeset
469 However, this behavior isn't required.
anatofuz
parents:
diff changeset
470
anatofuz
parents:
diff changeset
471 Another implementation of the ``DiagnosticConsumer`` interface is the
anatofuz
parents:
diff changeset
472 ``TextDiagnosticBuffer`` class, which is used when Clang is in ``-verify``
anatofuz
parents:
diff changeset
473 mode. Instead of formatting and printing out the diagnostics, this
anatofuz
parents:
diff changeset
474 implementation just captures and remembers the diagnostics as they fly by.
anatofuz
parents:
diff changeset
475 Then ``-verify`` compares the list of produced diagnostics to the list of
anatofuz
parents:
diff changeset
476 expected ones. If they disagree, it prints out its own output. Full
anatofuz
parents:
diff changeset
477 documentation for the ``-verify`` mode can be found in the Clang API
anatofuz
parents:
diff changeset
478 documentation for `VerifyDiagnosticConsumer
anatofuz
parents:
diff changeset
479 </doxygen/classclang_1_1VerifyDiagnosticConsumer.html#details>`_.
anatofuz
parents:
diff changeset
480
anatofuz
parents:
diff changeset
481 There are many other possible implementations of this interface, and this is
anatofuz
parents:
diff changeset
482 why we prefer diagnostics to pass down rich structured information in
anatofuz
parents:
diff changeset
483 arguments. For example, an HTML output might want declaration names be
anatofuz
parents:
diff changeset
484 linkified to where they come from in the source. Another example is that a GUI
anatofuz
parents:
diff changeset
485 might let you click on typedefs to expand them. This application would want to
anatofuz
parents:
diff changeset
486 pass significantly more information about types through to the GUI than a
anatofuz
parents:
diff changeset
487 simple flat string. The interface allows this to happen.
anatofuz
parents:
diff changeset
488
anatofuz
parents:
diff changeset
489 .. _internals-diag-translation:
anatofuz
parents:
diff changeset
490
anatofuz
parents:
diff changeset
491 Adding Translations to Clang
anatofuz
parents:
diff changeset
492 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
anatofuz
parents:
diff changeset
493
anatofuz
parents:
diff changeset
494 Not possible yet! Diagnostic strings should be written in UTF-8, the client can
anatofuz
parents:
diff changeset
495 translate to the relevant code page if needed. Each translation completely
anatofuz
parents:
diff changeset
496 replaces the format string for the diagnostic.
anatofuz
parents:
diff changeset
497
anatofuz
parents:
diff changeset
498 .. _SourceLocation:
anatofuz
parents:
diff changeset
499 .. _SourceManager:
anatofuz
parents:
diff changeset
500
anatofuz
parents:
diff changeset
501 The ``SourceLocation`` and ``SourceManager`` classes
anatofuz
parents:
diff changeset
502 ----------------------------------------------------
anatofuz
parents:
diff changeset
503
anatofuz
parents:
diff changeset
504 Strangely enough, the ``SourceLocation`` class represents a location within the
anatofuz
parents:
diff changeset
505 source code of the program. Important design points include:
anatofuz
parents:
diff changeset
506
anatofuz
parents:
diff changeset
507 #. ``sizeof(SourceLocation)`` must be extremely small, as these are embedded
anatofuz
parents:
diff changeset
508 into many AST nodes and are passed around often. Currently it is 32 bits.
anatofuz
parents:
diff changeset
509 #. ``SourceLocation`` must be a simple value object that can be efficiently
anatofuz
parents:
diff changeset
510 copied.
anatofuz
parents:
diff changeset
511 #. We should be able to represent a source location for any byte of any input
anatofuz
parents:
diff changeset
512 file. This includes in the middle of tokens, in whitespace, in trigraphs,
anatofuz
parents:
diff changeset
513 etc.
anatofuz
parents:
diff changeset
514 #. A ``SourceLocation`` must encode the current ``#include`` stack that was
anatofuz
parents:
diff changeset
515 active when the location was processed. For example, if the location
anatofuz
parents:
diff changeset
516 corresponds to a token, it should contain the set of ``#include``\ s active
anatofuz
parents:
diff changeset
517 when the token was lexed. This allows us to print the ``#include`` stack
anatofuz
parents:
diff changeset
518 for a diagnostic.
anatofuz
parents:
diff changeset
519 #. ``SourceLocation`` must be able to describe macro expansions, capturing both
anatofuz
parents:
diff changeset
520 the ultimate instantiation point and the source of the original character
anatofuz
parents:
diff changeset
521 data.
anatofuz
parents:
diff changeset
522
anatofuz
parents:
diff changeset
523 In practice, the ``SourceLocation`` works together with the ``SourceManager``
anatofuz
parents:
diff changeset
524 class to encode two pieces of information about a location: its spelling
anatofuz
parents:
diff changeset
525 location and its expansion location. For most tokens, these will be the
anatofuz
parents:
diff changeset
526 same. However, for a macro expansion (or tokens that came from a ``_Pragma``
anatofuz
parents:
diff changeset
527 directive) these will describe the location of the characters corresponding to
anatofuz
parents:
diff changeset
528 the token and the location where the token was used (i.e., the macro
anatofuz
parents:
diff changeset
529 expansion point or the location of the ``_Pragma`` itself).
anatofuz
parents:
diff changeset
530
anatofuz
parents:
diff changeset
531 The Clang front-end inherently depends on the location of a token being tracked
anatofuz
parents:
diff changeset
532 correctly. If it is ever incorrect, the front-end may get confused and die.
anatofuz
parents:
diff changeset
533 The reason for this is that the notion of the "spelling" of a ``Token`` in
anatofuz
parents:
diff changeset
534 Clang depends on being able to find the original input characters for the
anatofuz
parents:
diff changeset
535 token. This concept maps directly to the "spelling location" for the token.
anatofuz
parents:
diff changeset
536
anatofuz
parents:
diff changeset
537 ``SourceRange`` and ``CharSourceRange``
anatofuz
parents:
diff changeset
538 ---------------------------------------
anatofuz
parents:
diff changeset
539
anatofuz
parents:
diff changeset
540 .. mostly taken from https://lists.llvm.org/pipermail/cfe-dev/2010-August/010595.html
anatofuz
parents:
diff changeset
541
anatofuz
parents:
diff changeset
542 Clang represents most source ranges by [first, last], where "first" and "last"
anatofuz
parents:
diff changeset
543 each point to the beginning of their respective tokens. For example consider
anatofuz
parents:
diff changeset
544 the ``SourceRange`` of the following statement:
anatofuz
parents:
diff changeset
545
anatofuz
parents:
diff changeset
546 .. code-block:: text
anatofuz
parents:
diff changeset
547
anatofuz
parents:
diff changeset
548 x = foo + bar;
anatofuz
parents:
diff changeset
549 ^first ^last
anatofuz
parents:
diff changeset
550
anatofuz
parents:
diff changeset
551 To map from this representation to a character-based representation, the "last"
anatofuz
parents:
diff changeset
552 location needs to be adjusted to point to (or past) the end of that token with
anatofuz
parents:
diff changeset
553 either ``Lexer::MeasureTokenLength()`` or ``Lexer::getLocForEndOfToken()``. For
anatofuz
parents:
diff changeset
554 the rare cases where character-level source ranges information is needed we use
anatofuz
parents:
diff changeset
555 the ``CharSourceRange`` class.
anatofuz
parents:
diff changeset
556
anatofuz
parents:
diff changeset
557 The Driver Library
anatofuz
parents:
diff changeset
558 ==================
anatofuz
parents:
diff changeset
559
anatofuz
parents:
diff changeset
560 The clang Driver and library are documented :doc:`here <DriverInternals>`.
anatofuz
parents:
diff changeset
561
anatofuz
parents:
diff changeset
562 Precompiled Headers
anatofuz
parents:
diff changeset
563 ===================
anatofuz
parents:
diff changeset
564
anatofuz
parents:
diff changeset
565 Clang supports precompiled headers (:doc:`PCH <PCHInternals>`), which uses a
anatofuz
parents:
diff changeset
566 serialized representation of Clang's internal data structures, encoded with the
anatofuz
parents:
diff changeset
567 `LLVM bitstream format <https://llvm.org/docs/BitCodeFormat.html>`_.
anatofuz
parents:
diff changeset
568
anatofuz
parents:
diff changeset
569 The Frontend Library
anatofuz
parents:
diff changeset
570 ====================
anatofuz
parents:
diff changeset
571
anatofuz
parents:
diff changeset
572 The Frontend library contains functionality useful for building tools on top of
anatofuz
parents:
diff changeset
573 the Clang libraries, for example several methods for outputting diagnostics.
anatofuz
parents:
diff changeset
574
anatofuz
parents:
diff changeset
575 The Lexer and Preprocessor Library
anatofuz
parents:
diff changeset
576 ==================================
anatofuz
parents:
diff changeset
577
anatofuz
parents:
diff changeset
578 The Lexer library contains several tightly-connected classes that are involved
anatofuz
parents:
diff changeset
579 with the nasty process of lexing and preprocessing C source code. The main
anatofuz
parents:
diff changeset
580 interface to this library for outside clients is the large ``Preprocessor``
anatofuz
parents:
diff changeset
581 class. It contains the various pieces of state that are required to coherently
anatofuz
parents:
diff changeset
582 read tokens out of a translation unit.
anatofuz
parents:
diff changeset
583
anatofuz
parents:
diff changeset
584 The core interface to the ``Preprocessor`` object (once it is set up) is the
anatofuz
parents:
diff changeset
585 ``Preprocessor::Lex`` method, which returns the next :ref:`Token <Token>` from
anatofuz
parents:
diff changeset
586 the preprocessor stream. There are two types of token providers that the
anatofuz
parents:
diff changeset
587 preprocessor is capable of reading from: a buffer lexer (provided by the
anatofuz
parents:
diff changeset
588 :ref:`Lexer <Lexer>` class) and a buffered token stream (provided by the
anatofuz
parents:
diff changeset
589 :ref:`TokenLexer <TokenLexer>` class).
anatofuz
parents:
diff changeset
590
anatofuz
parents:
diff changeset
591 .. _Token:
anatofuz
parents:
diff changeset
592
anatofuz
parents:
diff changeset
593 The Token class
anatofuz
parents:
diff changeset
594 ---------------
anatofuz
parents:
diff changeset
595
anatofuz
parents:
diff changeset
596 The ``Token`` class is used to represent a single lexed token. Tokens are
anatofuz
parents:
diff changeset
597 intended to be used by the lexer/preprocess and parser libraries, but are not
anatofuz
parents:
diff changeset
598 intended to live beyond them (for example, they should not live in the ASTs).
anatofuz
parents:
diff changeset
599
anatofuz
parents:
diff changeset
600 Tokens most often live on the stack (or some other location that is efficient
anatofuz
parents:
diff changeset
601 to access) as the parser is running, but occasionally do get buffered up. For
anatofuz
parents:
diff changeset
602 example, macro definitions are stored as a series of tokens, and the C++
anatofuz
parents:
diff changeset
603 front-end periodically needs to buffer tokens up for tentative parsing and
anatofuz
parents:
diff changeset
604 various pieces of look-ahead. As such, the size of a ``Token`` matters. On a
anatofuz
parents:
diff changeset
605 32-bit system, ``sizeof(Token)`` is currently 16 bytes.
anatofuz
parents:
diff changeset
606
anatofuz
parents:
diff changeset
607 Tokens occur in two forms: :ref:`annotation tokens <AnnotationToken>` and
anatofuz
parents:
diff changeset
608 normal tokens. Normal tokens are those returned by the lexer, annotation
anatofuz
parents:
diff changeset
609 tokens represent semantic information and are produced by the parser, replacing
anatofuz
parents:
diff changeset
610 normal tokens in the token stream. Normal tokens contain the following
anatofuz
parents:
diff changeset
611 information:
anatofuz
parents:
diff changeset
612
anatofuz
parents:
diff changeset
613 * **A SourceLocation** --- This indicates the location of the start of the
anatofuz
parents:
diff changeset
614 token.
anatofuz
parents:
diff changeset
615
anatofuz
parents:
diff changeset
616 * **A length** --- This stores the length of the token as stored in the
anatofuz
parents:
diff changeset
617 ``SourceBuffer``. For tokens that include them, this length includes
anatofuz
parents:
diff changeset
618 trigraphs and escaped newlines which are ignored by later phases of the
anatofuz
parents:
diff changeset
619 compiler. By pointing into the original source buffer, it is always possible
anatofuz
parents:
diff changeset
620 to get the original spelling of a token completely accurately.
anatofuz
parents:
diff changeset
621
anatofuz
parents:
diff changeset
622 * **IdentifierInfo** --- If a token takes the form of an identifier, and if
anatofuz
parents:
diff changeset
623 identifier lookup was enabled when the token was lexed (e.g., the lexer was
anatofuz
parents:
diff changeset
624 not reading in "raw" mode) this contains a pointer to the unique hash value
anatofuz
parents:
diff changeset
625 for the identifier. Because the lookup happens before keyword
anatofuz
parents:
diff changeset
626 identification, this field is set even for language keywords like "``for``".
anatofuz
parents:
diff changeset
627
anatofuz
parents:
diff changeset
628 * **TokenKind** --- This indicates the kind of token as classified by the
anatofuz
parents:
diff changeset
629 lexer. This includes things like ``tok::starequal`` (for the "``*=``"
anatofuz
parents:
diff changeset
630 operator), ``tok::ampamp`` for the "``&&``" token, and keyword values (e.g.,
anatofuz
parents:
diff changeset
631 ``tok::kw_for``) for identifiers that correspond to keywords. Note that
anatofuz
parents:
diff changeset
632 some tokens can be spelled multiple ways. For example, C++ supports
anatofuz
parents:
diff changeset
633 "operator keywords", where things like "``and``" are treated exactly like the
anatofuz
parents:
diff changeset
634 "``&&``" operator. In these cases, the kind value is set to ``tok::ampamp``,
anatofuz
parents:
diff changeset
635 which is good for the parser, which doesn't have to consider both forms. For
anatofuz
parents:
diff changeset
636 something that cares about which form is used (e.g., the preprocessor
anatofuz
parents:
diff changeset
637 "stringize" operator) the spelling indicates the original form.
anatofuz
parents:
diff changeset
638
anatofuz
parents:
diff changeset
639 * **Flags** --- There are currently four flags tracked by the
anatofuz
parents:
diff changeset
640 lexer/preprocessor system on a per-token basis:
anatofuz
parents:
diff changeset
641
anatofuz
parents:
diff changeset
642 #. **StartOfLine** --- This was the first token that occurred on its input
anatofuz
parents:
diff changeset
643 source line.
anatofuz
parents:
diff changeset
644 #. **LeadingSpace** --- There was a space character either immediately before
anatofuz
parents:
diff changeset
645 the token or transitively before the token as it was expanded through a
anatofuz
parents:
diff changeset
646 macro. The definition of this flag is very closely defined by the
anatofuz
parents:
diff changeset
647 stringizing requirements of the preprocessor.
anatofuz
parents:
diff changeset
648 #. **DisableExpand** --- This flag is used internally to the preprocessor to
anatofuz
parents:
diff changeset
649 represent identifier tokens which have macro expansion disabled. This
anatofuz
parents:
diff changeset
650 prevents them from being considered as candidates for macro expansion ever
anatofuz
parents:
diff changeset
651 in the future.
anatofuz
parents:
diff changeset
652 #. **NeedsCleaning** --- This flag is set if the original spelling for the
anatofuz
parents:
diff changeset
653 token includes a trigraph or escaped newline. Since this is uncommon,
anatofuz
parents:
diff changeset
654 many pieces of code can fast-path on tokens that did not need cleaning.
anatofuz
parents:
diff changeset
655
anatofuz
parents:
diff changeset
656 One interesting (and somewhat unusual) aspect of normal tokens is that they
anatofuz
parents:
diff changeset
657 don't contain any semantic information about the lexed value. For example, if
anatofuz
parents:
diff changeset
658 the token was a pp-number token, we do not represent the value of the number
anatofuz
parents:
diff changeset
659 that was lexed (this is left for later pieces of code to decide).
anatofuz
parents:
diff changeset
660 Additionally, the lexer library has no notion of typedef names vs variable
anatofuz
parents:
diff changeset
661 names: both are returned as identifiers, and the parser is left to decide
anatofuz
parents:
diff changeset
662 whether a specific identifier is a typedef or a variable (tracking this
anatofuz
parents:
diff changeset
663 requires scope information among other things). The parser can do this
anatofuz
parents:
diff changeset
664 translation by replacing tokens returned by the preprocessor with "Annotation
anatofuz
parents:
diff changeset
665 Tokens".
anatofuz
parents:
diff changeset
666
anatofuz
parents:
diff changeset
667 .. _AnnotationToken:
anatofuz
parents:
diff changeset
668
anatofuz
parents:
diff changeset
669 Annotation Tokens
anatofuz
parents:
diff changeset
670 -----------------
anatofuz
parents:
diff changeset
671
anatofuz
parents:
diff changeset
672 Annotation tokens are tokens that are synthesized by the parser and injected
anatofuz
parents:
diff changeset
673 into the preprocessor's token stream (replacing existing tokens) to record
anatofuz
parents:
diff changeset
674 semantic information found by the parser. For example, if "``foo``" is found
anatofuz
parents:
diff changeset
675 to be a typedef, the "``foo``" ``tok::identifier`` token is replaced with an
anatofuz
parents:
diff changeset
676 ``tok::annot_typename``. This is useful for a couple of reasons: 1) this makes
anatofuz
parents:
diff changeset
677 it easy to handle qualified type names (e.g., "``foo::bar::baz<42>::t``") in
anatofuz
parents:
diff changeset
678 C++ as a single "token" in the parser. 2) if the parser backtracks, the
anatofuz
parents:
diff changeset
679 reparse does not need to redo semantic analysis to determine whether a token
anatofuz
parents:
diff changeset
680 sequence is a variable, type, template, etc.
anatofuz
parents:
diff changeset
681
anatofuz
parents:
diff changeset
682 Annotation tokens are created by the parser and reinjected into the parser's
anatofuz
parents:
diff changeset
683 token stream (when backtracking is enabled). Because they can only exist in
anatofuz
parents:
diff changeset
684 tokens that the preprocessor-proper is done with, it doesn't need to keep
anatofuz
parents:
diff changeset
685 around flags like "start of line" that the preprocessor uses to do its job.
anatofuz
parents:
diff changeset
686 Additionally, an annotation token may "cover" a sequence of preprocessor tokens
anatofuz
parents:
diff changeset
687 (e.g., "``a::b::c``" is five preprocessor tokens). As such, the valid fields
anatofuz
parents:
diff changeset
688 of an annotation token are different than the fields for a normal token (but
anatofuz
parents:
diff changeset
689 they are multiplexed into the normal ``Token`` fields):
anatofuz
parents:
diff changeset
690
anatofuz
parents:
diff changeset
691 * **SourceLocation "Location"** --- The ``SourceLocation`` for the annotation
anatofuz
parents:
diff changeset
692 token indicates the first token replaced by the annotation token. In the
anatofuz
parents:
diff changeset
693 example above, it would be the location of the "``a``" identifier.
anatofuz
parents:
diff changeset
694 * **SourceLocation "AnnotationEndLoc"** --- This holds the location of the last
anatofuz
parents:
diff changeset
695 token replaced with the annotation token. In the example above, it would be
anatofuz
parents:
diff changeset
696 the location of the "``c``" identifier.
anatofuz
parents:
diff changeset
697 * **void* "AnnotationValue"** --- This contains an opaque object that the
anatofuz
parents:
diff changeset
698 parser gets from ``Sema``. The parser merely preserves the information for
anatofuz
parents:
diff changeset
699 ``Sema`` to later interpret based on the annotation token kind.
anatofuz
parents:
diff changeset
700 * **TokenKind "Kind"** --- This indicates the kind of Annotation token this is.
anatofuz
parents:
diff changeset
701 See below for the different valid kinds.
anatofuz
parents:
diff changeset
702
anatofuz
parents:
diff changeset
703 Annotation tokens currently come in three kinds:
anatofuz
parents:
diff changeset
704
anatofuz
parents:
diff changeset
705 #. **tok::annot_typename**: This annotation token represents a resolved
anatofuz
parents:
diff changeset
706 typename token that is potentially qualified. The ``AnnotationValue`` field
anatofuz
parents:
diff changeset
707 contains the ``QualType`` returned by ``Sema::getTypeName()``, possibly with
anatofuz
parents:
diff changeset
708 source location information attached.
anatofuz
parents:
diff changeset
709 #. **tok::annot_cxxscope**: This annotation token represents a C++ scope
anatofuz
parents:
diff changeset
710 specifier, such as "``A::B::``". This corresponds to the grammar
anatofuz
parents:
diff changeset
711 productions "*::*" and "*:: [opt] nested-name-specifier*". The
anatofuz
parents:
diff changeset
712 ``AnnotationValue`` pointer is a ``NestedNameSpecifier *`` returned by the
anatofuz
parents:
diff changeset
713 ``Sema::ActOnCXXGlobalScopeSpecifier`` and
anatofuz
parents:
diff changeset
714 ``Sema::ActOnCXXNestedNameSpecifier`` callbacks.
anatofuz
parents:
diff changeset
715 #. **tok::annot_template_id**: This annotation token represents a C++
anatofuz
parents:
diff changeset
716 template-id such as "``foo<int, 4>``", where "``foo``" is the name of a
anatofuz
parents:
diff changeset
717 template. The ``AnnotationValue`` pointer is a pointer to a ``malloc``'d
anatofuz
parents:
diff changeset
718 ``TemplateIdAnnotation`` object. Depending on the context, a parsed
anatofuz
parents:
diff changeset
719 template-id that names a type might become a typename annotation token (if
anatofuz
parents:
diff changeset
720 all we care about is the named type, e.g., because it occurs in a type
anatofuz
parents:
diff changeset
721 specifier) or might remain a template-id token (if we want to retain more
anatofuz
parents:
diff changeset
722 source location information or produce a new type, e.g., in a declaration of
anatofuz
parents:
diff changeset
723 a class template specialization). template-id annotation tokens that refer
anatofuz
parents:
diff changeset
724 to a type can be "upgraded" to typename annotation tokens by the parser.
anatofuz
parents:
diff changeset
725
anatofuz
parents:
diff changeset
726 As mentioned above, annotation tokens are not returned by the preprocessor,
anatofuz
parents:
diff changeset
727 they are formed on demand by the parser. This means that the parser has to be
anatofuz
parents:
diff changeset
728 aware of cases where an annotation could occur and form it where appropriate.
anatofuz
parents:
diff changeset
729 This is somewhat similar to how the parser handles Translation Phase 6 of C99:
anatofuz
parents:
diff changeset
730 String Concatenation (see C99 5.1.1.2). In the case of string concatenation,
anatofuz
parents:
diff changeset
731 the preprocessor just returns distinct ``tok::string_literal`` and
anatofuz
parents:
diff changeset
732 ``tok::wide_string_literal`` tokens and the parser eats a sequence of them
anatofuz
parents:
diff changeset
733 wherever the grammar indicates that a string literal can occur.
anatofuz
parents:
diff changeset
734
anatofuz
parents:
diff changeset
735 In order to do this, whenever the parser expects a ``tok::identifier`` or
anatofuz
parents:
diff changeset
736 ``tok::coloncolon``, it should call the ``TryAnnotateTypeOrScopeToken`` or
anatofuz
parents:
diff changeset
737 ``TryAnnotateCXXScopeToken`` methods to form the annotation token. These
anatofuz
parents:
diff changeset
738 methods will maximally form the specified annotation tokens and replace the
anatofuz
parents:
diff changeset
739 current token with them, if applicable. If the current tokens is not valid for
anatofuz
parents:
diff changeset
740 an annotation token, it will remain an identifier or "``::``" token.
anatofuz
parents:
diff changeset
741
anatofuz
parents:
diff changeset
742 .. _Lexer:
anatofuz
parents:
diff changeset
743
anatofuz
parents:
diff changeset
744 The ``Lexer`` class
anatofuz
parents:
diff changeset
745 -------------------
anatofuz
parents:
diff changeset
746
anatofuz
parents:
diff changeset
747 The ``Lexer`` class provides the mechanics of lexing tokens out of a source
anatofuz
parents:
diff changeset
748 buffer and deciding what they mean. The ``Lexer`` is complicated by the fact
anatofuz
parents:
diff changeset
749 that it operates on raw buffers that have not had spelling eliminated (this is
anatofuz
parents:
diff changeset
750 a necessity to get decent performance), but this is countered with careful
anatofuz
parents:
diff changeset
751 coding as well as standard performance techniques (for example, the comment
anatofuz
parents:
diff changeset
752 handling code is vectorized on X86 and PowerPC hosts).
anatofuz
parents:
diff changeset
753
anatofuz
parents:
diff changeset
754 The lexer has a couple of interesting modal features:
anatofuz
parents:
diff changeset
755
anatofuz
parents:
diff changeset
756 * The lexer can operate in "raw" mode. This mode has several features that
anatofuz
parents:
diff changeset
757 make it possible to quickly lex the file (e.g., it stops identifier lookup,
anatofuz
parents:
diff changeset
758 doesn't specially handle preprocessor tokens, handles EOF differently, etc).
anatofuz
parents:
diff changeset
759 This mode is used for lexing within an "``#if 0``" block, for example.
anatofuz
parents:
diff changeset
760 * The lexer can capture and return comments as tokens. This is required to
anatofuz
parents:
diff changeset
761 support the ``-C`` preprocessor mode, which passes comments through, and is
anatofuz
parents:
diff changeset
762 used by the diagnostic checker to identifier expect-error annotations.
anatofuz
parents:
diff changeset
763 * The lexer can be in ``ParsingFilename`` mode, which happens when
anatofuz
parents:
diff changeset
764 preprocessing after reading a ``#include`` directive. This mode changes the
anatofuz
parents:
diff changeset
765 parsing of "``<``" to return an "angled string" instead of a bunch of tokens
anatofuz
parents:
diff changeset
766 for each thing within the filename.
anatofuz
parents:
diff changeset
767 * When parsing a preprocessor directive (after "``#``") the
anatofuz
parents:
diff changeset
768 ``ParsingPreprocessorDirective`` mode is entered. This changes the parser to
anatofuz
parents:
diff changeset
769 return EOD at a newline.
anatofuz
parents:
diff changeset
770 * The ``Lexer`` uses a ``LangOptions`` object to know whether trigraphs are
anatofuz
parents:
diff changeset
771 enabled, whether C++ or ObjC keywords are recognized, etc.
anatofuz
parents:
diff changeset
772
anatofuz
parents:
diff changeset
773 In addition to these modes, the lexer keeps track of a couple of other features
anatofuz
parents:
diff changeset
774 that are local to a lexed buffer, which change as the buffer is lexed:
anatofuz
parents:
diff changeset
775
anatofuz
parents:
diff changeset
776 * The ``Lexer`` uses ``BufferPtr`` to keep track of the current character being
anatofuz
parents:
diff changeset
777 lexed.
anatofuz
parents:
diff changeset
778 * The ``Lexer`` uses ``IsAtStartOfLine`` to keep track of whether the next
anatofuz
parents:
diff changeset
779 lexed token will start with its "start of line" bit set.
anatofuz
parents:
diff changeset
780 * The ``Lexer`` keeps track of the current "``#if``" directives that are active
anatofuz
parents:
diff changeset
781 (which can be nested).
anatofuz
parents:
diff changeset
782 * The ``Lexer`` keeps track of an :ref:`MultipleIncludeOpt
anatofuz
parents:
diff changeset
783 <MultipleIncludeOpt>` object, which is used to detect whether the buffer uses
anatofuz
parents:
diff changeset
784 the standard "``#ifndef XX`` / ``#define XX``" idiom to prevent multiple
anatofuz
parents:
diff changeset
785 inclusion. If a buffer does, subsequent includes can be ignored if the
anatofuz
parents:
diff changeset
786 "``XX``" macro is defined.
anatofuz
parents:
diff changeset
787
anatofuz
parents:
diff changeset
788 .. _TokenLexer:
anatofuz
parents:
diff changeset
789
anatofuz
parents:
diff changeset
790 The ``TokenLexer`` class
anatofuz
parents:
diff changeset
791 ------------------------
anatofuz
parents:
diff changeset
792
anatofuz
parents:
diff changeset
793 The ``TokenLexer`` class is a token provider that returns tokens from a list of
anatofuz
parents:
diff changeset
794 tokens that came from somewhere else. It typically used for two things: 1)
anatofuz
parents:
diff changeset
795 returning tokens from a macro definition as it is being expanded 2) returning
anatofuz
parents:
diff changeset
796 tokens from an arbitrary buffer of tokens. The later use is used by
anatofuz
parents:
diff changeset
797 ``_Pragma`` and will most likely be used to handle unbounded look-ahead for the
anatofuz
parents:
diff changeset
798 C++ parser.
anatofuz
parents:
diff changeset
799
anatofuz
parents:
diff changeset
800 .. _MultipleIncludeOpt:
anatofuz
parents:
diff changeset
801
anatofuz
parents:
diff changeset
802 The ``MultipleIncludeOpt`` class
anatofuz
parents:
diff changeset
803 --------------------------------
anatofuz
parents:
diff changeset
804
anatofuz
parents:
diff changeset
805 The ``MultipleIncludeOpt`` class implements a really simple little state
anatofuz
parents:
diff changeset
806 machine that is used to detect the standard "``#ifndef XX`` / ``#define XX``"
anatofuz
parents:
diff changeset
807 idiom that people typically use to prevent multiple inclusion of headers. If a
anatofuz
parents:
diff changeset
808 buffer uses this idiom and is subsequently ``#include``'d, the preprocessor can
anatofuz
parents:
diff changeset
809 simply check to see whether the guarding condition is defined or not. If so,
anatofuz
parents:
diff changeset
810 the preprocessor can completely ignore the include of the header.
anatofuz
parents:
diff changeset
811
anatofuz
parents:
diff changeset
812 .. _Parser:
anatofuz
parents:
diff changeset
813
anatofuz
parents:
diff changeset
814 The Parser Library
anatofuz
parents:
diff changeset
815 ==================
anatofuz
parents:
diff changeset
816
anatofuz
parents:
diff changeset
817 This library contains a recursive-descent parser that polls tokens from the
anatofuz
parents:
diff changeset
818 preprocessor and notifies a client of the parsing progress.
anatofuz
parents:
diff changeset
819
anatofuz
parents:
diff changeset
820 Historically, the parser used to talk to an abstract ``Action`` interface that
anatofuz
parents:
diff changeset
821 had virtual methods for parse events, for example ``ActOnBinOp()``. When Clang
anatofuz
parents:
diff changeset
822 grew C++ support, the parser stopped supporting general ``Action`` clients --
anatofuz
parents:
diff changeset
823 it now always talks to the :ref:`Sema library <Sema>`. However, the Parser
anatofuz
parents:
diff changeset
824 still accesses AST objects only through opaque types like ``ExprResult`` and
anatofuz
parents:
diff changeset
825 ``StmtResult``. Only :ref:`Sema <Sema>` looks at the AST node contents of these
anatofuz
parents:
diff changeset
826 wrappers.
anatofuz
parents:
diff changeset
827
anatofuz
parents:
diff changeset
828 .. _AST:
anatofuz
parents:
diff changeset
829
anatofuz
parents:
diff changeset
830 The AST Library
anatofuz
parents:
diff changeset
831 ===============
anatofuz
parents:
diff changeset
832
anatofuz
parents:
diff changeset
833 .. _ASTPhilosophy:
anatofuz
parents:
diff changeset
834
anatofuz
parents:
diff changeset
835 Design philosophy
anatofuz
parents:
diff changeset
836 -----------------
anatofuz
parents:
diff changeset
837
anatofuz
parents:
diff changeset
838 Immutability
anatofuz
parents:
diff changeset
839 ^^^^^^^^^^^^
anatofuz
parents:
diff changeset
840
anatofuz
parents:
diff changeset
841 Clang AST nodes (types, declarations, statements, expressions, and so on) are
anatofuz
parents:
diff changeset
842 generally designed to be immutable once created. This provides a number of key
anatofuz
parents:
diff changeset
843 benefits:
anatofuz
parents:
diff changeset
844
anatofuz
parents:
diff changeset
845 * Canonicalization of the "meaning" of nodes is possible as soon as the nodes
anatofuz
parents:
diff changeset
846 are created, and is not invalidated by later addition of more information.
anatofuz
parents:
diff changeset
847 For example, we :ref:`canonicalize types <CanonicalType>`, and use a
anatofuz
parents:
diff changeset
848 canonicalized representation of expressions when determining whether two
anatofuz
parents:
diff changeset
849 function template declarations involving dependent expressions declare the
anatofuz
parents:
diff changeset
850 same entity.
anatofuz
parents:
diff changeset
851 * AST nodes can be reused when they have the same meaning. For example, we
anatofuz
parents:
diff changeset
852 reuse ``Type`` nodes when representing the same type (but maintain separate
anatofuz
parents:
diff changeset
853 ``TypeLoc``\s for each instance where a type is written), and we reuse
anatofuz
parents:
diff changeset
854 non-dependent ``Stmt`` and ``Expr`` nodes across instantiations of a
anatofuz
parents:
diff changeset
855 template.
anatofuz
parents:
diff changeset
856 * Serialization and deserialization of the AST to/from AST files is simpler:
anatofuz
parents:
diff changeset
857 we do not need to track modifications made to AST nodes imported from AST
anatofuz
parents:
diff changeset
858 files and serialize separate "update records".
anatofuz
parents:
diff changeset
859
anatofuz
parents:
diff changeset
860 There are unfortunately exceptions to this general approach, such as:
anatofuz
parents:
diff changeset
861
anatofuz
parents:
diff changeset
862 * The first declaration of a redeclarable entity maintains a pointer to the
anatofuz
parents:
diff changeset
863 most recent declaration of that entity, which naturally needs to change as
anatofuz
parents:
diff changeset
864 more declarations are parsed.
anatofuz
parents:
diff changeset
865 * Name lookup tables in declaration contexts change after the namespace
anatofuz
parents:
diff changeset
866 declaration is formed.
anatofuz
parents:
diff changeset
867 * We attempt to maintain only a single declaration for an instantiation of a
anatofuz
parents:
diff changeset
868 template, rather than having distinct declarations for an instantiation of
anatofuz
parents:
diff changeset
869 the declaration versus the definition, so template instantiation often
anatofuz
parents:
diff changeset
870 updates parts of existing declarations.
anatofuz
parents:
diff changeset
871 * Some parts of declarations are required to be instantiated separately (this
anatofuz
parents:
diff changeset
872 includes default arguments and exception specifications), and such
anatofuz
parents:
diff changeset
873 instantiations update the existing declaration.
anatofuz
parents:
diff changeset
874
anatofuz
parents:
diff changeset
875 These cases tend to be fragile; mutable AST state should be avoided where
anatofuz
parents:
diff changeset
876 possible.
anatofuz
parents:
diff changeset
877
anatofuz
parents:
diff changeset
878 As a consequence of this design principle, we typically do not provide setters
anatofuz
parents:
diff changeset
879 for AST state. (Some are provided for short-term modifications intended to be
anatofuz
parents:
diff changeset
880 used immediately after an AST node is created and before it's "published" as
anatofuz
parents:
diff changeset
881 part of the complete AST, or where language semantics require after-the-fact
anatofuz
parents:
diff changeset
882 updates.)
anatofuz
parents:
diff changeset
883
anatofuz
parents:
diff changeset
884 Faithfulness
anatofuz
parents:
diff changeset
885 ^^^^^^^^^^^^
anatofuz
parents:
diff changeset
886
anatofuz
parents:
diff changeset
887 The AST intends to provide a representation of the program that is faithful to
anatofuz
parents:
diff changeset
888 the original source. We intend for it to be possible to write refactoring tools
anatofuz
parents:
diff changeset
889 using only information stored in, or easily reconstructible from, the Clang AST.
anatofuz
parents:
diff changeset
890 This means that the AST representation should either not desugar source-level
anatofuz
parents:
diff changeset
891 constructs to simpler forms, or -- where made necessary by language semantics
anatofuz
parents:
diff changeset
892 or a clear engineering tradeoff -- should desugar minimally and wrap the result
anatofuz
parents:
diff changeset
893 in a construct representing the original source form.
anatofuz
parents:
diff changeset
894
anatofuz
parents:
diff changeset
895 For example, ``CXXForRangeStmt`` directly represents the syntactic form of a
anatofuz
parents:
diff changeset
896 range-based for statement, but also holds a semantic representation of the
anatofuz
parents:
diff changeset
897 range declaration and iterator declarations. It does not contain a
anatofuz
parents:
diff changeset
898 fully-desugared ``ForStmt``, however.
anatofuz
parents:
diff changeset
899
anatofuz
parents:
diff changeset
900 Some AST nodes (for example, ``ParenExpr``) represent only syntax, and others
anatofuz
parents:
diff changeset
901 (for example, ``ImplicitCastExpr``) represent only semantics, but most nodes
anatofuz
parents:
diff changeset
902 will represent a combination of syntax and associated semantics. Inheritance
anatofuz
parents:
diff changeset
903 is typically used when representing different (but related) syntaxes for nodes
anatofuz
parents:
diff changeset
904 with the same or similar semantics.
anatofuz
parents:
diff changeset
905
anatofuz
parents:
diff changeset
906 .. _Type:
anatofuz
parents:
diff changeset
907
anatofuz
parents:
diff changeset
908 The ``Type`` class and its subclasses
anatofuz
parents:
diff changeset
909 -------------------------------------
anatofuz
parents:
diff changeset
910
anatofuz
parents:
diff changeset
911 The ``Type`` class (and its subclasses) are an important part of the AST.
anatofuz
parents:
diff changeset
912 Types are accessed through the ``ASTContext`` class, which implicitly creates
anatofuz
parents:
diff changeset
913 and uniques them as they are needed. Types have a couple of non-obvious
anatofuz
parents:
diff changeset
914 features: 1) they do not capture type qualifiers like ``const`` or ``volatile``
anatofuz
parents:
diff changeset
915 (see :ref:`QualType <QualType>`), and 2) they implicitly capture typedef
anatofuz
parents:
diff changeset
916 information. Once created, types are immutable (unlike decls).
anatofuz
parents:
diff changeset
917
anatofuz
parents:
diff changeset
918 Typedefs in C make semantic analysis a bit more complex than it would be without
anatofuz
parents:
diff changeset
919 them. The issue is that we want to capture typedef information and represent it
anatofuz
parents:
diff changeset
920 in the AST perfectly, but the semantics of operations need to "see through"
anatofuz
parents:
diff changeset
921 typedefs. For example, consider this code:
anatofuz
parents:
diff changeset
922
anatofuz
parents:
diff changeset
923 .. code-block:: c++
anatofuz
parents:
diff changeset
924
anatofuz
parents:
diff changeset
925 void func() {
anatofuz
parents:
diff changeset
926 typedef int foo;
anatofuz
parents:
diff changeset
927 foo X, *Y;
anatofuz
parents:
diff changeset
928 typedef foo *bar;
anatofuz
parents:
diff changeset
929 bar Z;
anatofuz
parents:
diff changeset
930 *X; // error
anatofuz
parents:
diff changeset
931 **Y; // error
anatofuz
parents:
diff changeset
932 **Z; // error
anatofuz
parents:
diff changeset
933 }
anatofuz
parents:
diff changeset
934
anatofuz
parents:
diff changeset
935 The code above is illegal, and thus we expect there to be diagnostics emitted
anatofuz
parents:
diff changeset
936 on the annotated lines. In this example, we expect to get:
anatofuz
parents:
diff changeset
937
anatofuz
parents:
diff changeset
938 .. code-block:: text
anatofuz
parents:
diff changeset
939
anatofuz
parents:
diff changeset
940 test.c:6:1: error: indirection requires pointer operand ('foo' invalid)
anatofuz
parents:
diff changeset
941 *X; // error
anatofuz
parents:
diff changeset
942 ^~
anatofuz
parents:
diff changeset
943 test.c:7:1: error: indirection requires pointer operand ('foo' invalid)
anatofuz
parents:
diff changeset
944 **Y; // error
anatofuz
parents:
diff changeset
945 ^~~
anatofuz
parents:
diff changeset
946 test.c:8:1: error: indirection requires pointer operand ('foo' invalid)
anatofuz
parents:
diff changeset
947 **Z; // error
anatofuz
parents:
diff changeset
948 ^~~
anatofuz
parents:
diff changeset
949
anatofuz
parents:
diff changeset
950 While this example is somewhat silly, it illustrates the point: we want to
anatofuz
parents:
diff changeset
951 retain typedef information where possible, so that we can emit errors about
anatofuz
parents:
diff changeset
952 "``std::string``" instead of "``std::basic_string<char, std:...``". Doing this
anatofuz
parents:
diff changeset
953 requires properly keeping typedef information (for example, the type of ``X``
anatofuz
parents:
diff changeset
954 is "``foo``", not "``int``"), and requires properly propagating it through the
anatofuz
parents:
diff changeset
955 various operators (for example, the type of ``*Y`` is "``foo``", not
anatofuz
parents:
diff changeset
956 "``int``"). In order to retain this information, the type of these expressions
anatofuz
parents:
diff changeset
957 is an instance of the ``TypedefType`` class, which indicates that the type of
anatofuz
parents:
diff changeset
958 these expressions is a typedef for "``foo``".
anatofuz
parents:
diff changeset
959
anatofuz
parents:
diff changeset
960 Representing types like this is great for diagnostics, because the
anatofuz
parents:
diff changeset
961 user-specified type is always immediately available. There are two problems
anatofuz
parents:
diff changeset
962 with this: first, various semantic checks need to make judgements about the
anatofuz
parents:
diff changeset
963 *actual structure* of a type, ignoring typedefs. Second, we need an efficient
anatofuz
parents:
diff changeset
964 way to query whether two types are structurally identical to each other,
anatofuz
parents:
diff changeset
965 ignoring typedefs. The solution to both of these problems is the idea of
anatofuz
parents:
diff changeset
966 canonical types.
anatofuz
parents:
diff changeset
967
anatofuz
parents:
diff changeset
968 .. _CanonicalType:
anatofuz
parents:
diff changeset
969
anatofuz
parents:
diff changeset
970 Canonical Types
anatofuz
parents:
diff changeset
971 ^^^^^^^^^^^^^^^
anatofuz
parents:
diff changeset
972
anatofuz
parents:
diff changeset
973 Every instance of the ``Type`` class contains a canonical type pointer. For
anatofuz
parents:
diff changeset
974 simple types with no typedefs involved (e.g., "``int``", "``int*``",
anatofuz
parents:
diff changeset
975 "``int**``"), the type just points to itself. For types that have a typedef
anatofuz
parents:
diff changeset
976 somewhere in their structure (e.g., "``foo``", "``foo*``", "``foo**``",
anatofuz
parents:
diff changeset
977 "``bar``"), the canonical type pointer points to their structurally equivalent
anatofuz
parents:
diff changeset
978 type without any typedefs (e.g., "``int``", "``int*``", "``int**``", and
anatofuz
parents:
diff changeset
979 "``int*``" respectively).
anatofuz
parents:
diff changeset
980
anatofuz
parents:
diff changeset
981 This design provides a constant time operation (dereferencing the canonical type
anatofuz
parents:
diff changeset
982 pointer) that gives us access to the structure of types. For example, we can
anatofuz
parents:
diff changeset
983 trivially tell that "``bar``" and "``foo*``" are the same type by dereferencing
anatofuz
parents:
diff changeset
984 their canonical type pointers and doing a pointer comparison (they both point
anatofuz
parents:
diff changeset
985 to the single "``int*``" type).
anatofuz
parents:
diff changeset
986
anatofuz
parents:
diff changeset
987 Canonical types and typedef types bring up some complexities that must be
anatofuz
parents:
diff changeset
988 carefully managed. Specifically, the ``isa``/``cast``/``dyn_cast`` operators
anatofuz
parents:
diff changeset
989 generally shouldn't be used in code that is inspecting the AST. For example,
anatofuz
parents:
diff changeset
990 when type checking the indirection operator (unary "``*``" on a pointer), the
anatofuz
parents:
diff changeset
991 type checker must verify that the operand has a pointer type. It would not be
anatofuz
parents:
diff changeset
992 correct to check that with "``isa<PointerType>(SubExpr->getType())``", because
anatofuz
parents:
diff changeset
993 this predicate would fail if the subexpression had a typedef type.
anatofuz
parents:
diff changeset
994
anatofuz
parents:
diff changeset
995 The solution to this problem are a set of helper methods on ``Type``, used to
anatofuz
parents:
diff changeset
996 check their properties. In this case, it would be correct to use
anatofuz
parents:
diff changeset
997 "``SubExpr->getType()->isPointerType()``" to do the check. This predicate will
anatofuz
parents:
diff changeset
998 return true if the *canonical type is a pointer*, which is true any time the
anatofuz
parents:
diff changeset
999 type is structurally a pointer type. The only hard part here is remembering
anatofuz
parents:
diff changeset
1000 not to use the ``isa``/``cast``/``dyn_cast`` operations.
anatofuz
parents:
diff changeset
1001
anatofuz
parents:
diff changeset
1002 The second problem we face is how to get access to the pointer type once we
anatofuz
parents:
diff changeset
1003 know it exists. To continue the example, the result type of the indirection
anatofuz
parents:
diff changeset
1004 operator is the pointee type of the subexpression. In order to determine the
anatofuz
parents:
diff changeset
1005 type, we need to get the instance of ``PointerType`` that best captures the
anatofuz
parents:
diff changeset
1006 typedef information in the program. If the type of the expression is literally
anatofuz
parents:
diff changeset
1007 a ``PointerType``, we can return that, otherwise we have to dig through the
anatofuz
parents:
diff changeset
1008 typedefs to find the pointer type. For example, if the subexpression had type
anatofuz
parents:
diff changeset
1009 "``foo*``", we could return that type as the result. If the subexpression had
anatofuz
parents:
diff changeset
1010 type "``bar``", we want to return "``foo*``" (note that we do *not* want
anatofuz
parents:
diff changeset
1011 "``int*``"). In order to provide all of this, ``Type`` has a
anatofuz
parents:
diff changeset
1012 ``getAsPointerType()`` method that checks whether the type is structurally a
anatofuz
parents:
diff changeset
1013 ``PointerType`` and, if so, returns the best one. If not, it returns a null
anatofuz
parents:
diff changeset
1014 pointer.
anatofuz
parents:
diff changeset
1015
anatofuz
parents:
diff changeset
1016 This structure is somewhat mystical, but after meditating on it, it will make
anatofuz
parents:
diff changeset
1017 sense to you :).
anatofuz
parents:
diff changeset
1018
anatofuz
parents:
diff changeset
1019 .. _QualType:
anatofuz
parents:
diff changeset
1020
anatofuz
parents:
diff changeset
1021 The ``QualType`` class
anatofuz
parents:
diff changeset
1022 ----------------------
anatofuz
parents:
diff changeset
1023
anatofuz
parents:
diff changeset
1024 The ``QualType`` class is designed as a trivial value class that is small,
anatofuz
parents:
diff changeset
1025 passed by-value and is efficient to query. The idea of ``QualType`` is that it
anatofuz
parents:
diff changeset
1026 stores the type qualifiers (``const``, ``volatile``, ``restrict``, plus some
anatofuz
parents:
diff changeset
1027 extended qualifiers required by language extensions) separately from the types
anatofuz
parents:
diff changeset
1028 themselves. ``QualType`` is conceptually a pair of "``Type*``" and the bits
anatofuz
parents:
diff changeset
1029 for these type qualifiers.
anatofuz
parents:
diff changeset
1030
anatofuz
parents:
diff changeset
1031 By storing the type qualifiers as bits in the conceptual pair, it is extremely
anatofuz
parents:
diff changeset
1032 efficient to get the set of qualifiers on a ``QualType`` (just return the field
anatofuz
parents:
diff changeset
1033 of the pair), add a type qualifier (which is a trivial constant-time operation
anatofuz
parents:
diff changeset
1034 that sets a bit), and remove one or more type qualifiers (just return a
anatofuz
parents:
diff changeset
1035 ``QualType`` with the bitfield set to empty).
anatofuz
parents:
diff changeset
1036
anatofuz
parents:
diff changeset
1037 Further, because the bits are stored outside of the type itself, we do not need
anatofuz
parents:
diff changeset
1038 to create duplicates of types with different sets of qualifiers (i.e. there is
anatofuz
parents:
diff changeset
1039 only a single heap allocated "``int``" type: "``const int``" and "``volatile
anatofuz
parents:
diff changeset
1040 const int``" both point to the same heap allocated "``int``" type). This
anatofuz
parents:
diff changeset
1041 reduces the heap size used to represent bits and also means we do not have to
anatofuz
parents:
diff changeset
1042 consider qualifiers when uniquing types (:ref:`Type <Type>` does not even
anatofuz
parents:
diff changeset
1043 contain qualifiers).
anatofuz
parents:
diff changeset
1044
anatofuz
parents:
diff changeset
1045 In practice, the two most common type qualifiers (``const`` and ``restrict``)
anatofuz
parents:
diff changeset
1046 are stored in the low bits of the pointer to the ``Type`` object, together with
anatofuz
parents:
diff changeset
1047 a flag indicating whether extended qualifiers are present (which must be
anatofuz
parents:
diff changeset
1048 heap-allocated). This means that ``QualType`` is exactly the same size as a
anatofuz
parents:
diff changeset
1049 pointer.
anatofuz
parents:
diff changeset
1050
anatofuz
parents:
diff changeset
1051 .. _DeclarationName:
anatofuz
parents:
diff changeset
1052
anatofuz
parents:
diff changeset
1053 Declaration names
anatofuz
parents:
diff changeset
1054 -----------------
anatofuz
parents:
diff changeset
1055
anatofuz
parents:
diff changeset
1056 The ``DeclarationName`` class represents the name of a declaration in Clang.
anatofuz
parents:
diff changeset
1057 Declarations in the C family of languages can take several different forms.
anatofuz
parents:
diff changeset
1058 Most declarations are named by simple identifiers, e.g., "``f``" and "``x``" in
anatofuz
parents:
diff changeset
1059 the function declaration ``f(int x)``. In C++, declaration names can also name
anatofuz
parents:
diff changeset
1060 class constructors ("``Class``" in ``struct Class { Class(); }``), class
anatofuz
parents:
diff changeset
1061 destructors ("``~Class``"), overloaded operator names ("``operator+``"), and
anatofuz
parents:
diff changeset
1062 conversion functions ("``operator void const *``"). In Objective-C,
anatofuz
parents:
diff changeset
1063 declaration names can refer to the names of Objective-C methods, which involve
anatofuz
parents:
diff changeset
1064 the method name and the parameters, collectively called a *selector*, e.g.,
anatofuz
parents:
diff changeset
1065 "``setWidth:height:``". Since all of these kinds of entities --- variables,
anatofuz
parents:
diff changeset
1066 functions, Objective-C methods, C++ constructors, destructors, and operators
anatofuz
parents:
diff changeset
1067 --- are represented as subclasses of Clang's common ``NamedDecl`` class,
anatofuz
parents:
diff changeset
1068 ``DeclarationName`` is designed to efficiently represent any kind of name.
anatofuz
parents:
diff changeset
1069
anatofuz
parents:
diff changeset
1070 Given a ``DeclarationName`` ``N``, ``N.getNameKind()`` will produce a value
anatofuz
parents:
diff changeset
1071 that describes what kind of name ``N`` stores. There are 10 options (all of
anatofuz
parents:
diff changeset
1072 the names are inside the ``DeclarationName`` class).
anatofuz
parents:
diff changeset
1073
anatofuz
parents:
diff changeset
1074 ``Identifier``
anatofuz
parents:
diff changeset
1075
anatofuz
parents:
diff changeset
1076 The name is a simple identifier. Use ``N.getAsIdentifierInfo()`` to retrieve
anatofuz
parents:
diff changeset
1077 the corresponding ``IdentifierInfo*`` pointing to the actual identifier.
anatofuz
parents:
diff changeset
1078
anatofuz
parents:
diff changeset
1079 ``ObjCZeroArgSelector``, ``ObjCOneArgSelector``, ``ObjCMultiArgSelector``
anatofuz
parents:
diff changeset
1080
anatofuz
parents:
diff changeset
1081 The name is an Objective-C selector, which can be retrieved as a ``Selector``
anatofuz
parents:
diff changeset
1082 instance via ``N.getObjCSelector()``. The three possible name kinds for
anatofuz
parents:
diff changeset
1083 Objective-C reflect an optimization within the ``DeclarationName`` class:
anatofuz
parents:
diff changeset
1084 both zero- and one-argument selectors are stored as a masked
anatofuz
parents:
diff changeset
1085 ``IdentifierInfo`` pointer, and therefore require very little space, since
anatofuz
parents:
diff changeset
1086 zero- and one-argument selectors are far more common than multi-argument
anatofuz
parents:
diff changeset
1087 selectors (which use a different structure).
anatofuz
parents:
diff changeset
1088
anatofuz
parents:
diff changeset
1089 ``CXXConstructorName``
anatofuz
parents:
diff changeset
1090
anatofuz
parents:
diff changeset
1091 The name is a C++ constructor name. Use ``N.getCXXNameType()`` to retrieve
anatofuz
parents:
diff changeset
1092 the :ref:`type <QualType>` that this constructor is meant to construct. The
anatofuz
parents:
diff changeset
1093 type is always the canonical type, since all constructors for a given type
anatofuz
parents:
diff changeset
1094 have the same name.
anatofuz
parents:
diff changeset
1095
anatofuz
parents:
diff changeset
1096 ``CXXDestructorName``
anatofuz
parents:
diff changeset
1097
anatofuz
parents:
diff changeset
1098 The name is a C++ destructor name. Use ``N.getCXXNameType()`` to retrieve
anatofuz
parents:
diff changeset
1099 the :ref:`type <QualType>` whose destructor is being named. This type is
anatofuz
parents:
diff changeset
1100 always a canonical type.
anatofuz
parents:
diff changeset
1101
anatofuz
parents:
diff changeset
1102 ``CXXConversionFunctionName``
anatofuz
parents:
diff changeset
1103
anatofuz
parents:
diff changeset
1104 The name is a C++ conversion function. Conversion functions are named
anatofuz
parents:
diff changeset
1105 according to the type they convert to, e.g., "``operator void const *``".
anatofuz
parents:
diff changeset
1106 Use ``N.getCXXNameType()`` to retrieve the type that this conversion function
anatofuz
parents:
diff changeset
1107 converts to. This type is always a canonical type.
anatofuz
parents:
diff changeset
1108
anatofuz
parents:
diff changeset
1109 ``CXXOperatorName``
anatofuz
parents:
diff changeset
1110
anatofuz
parents:
diff changeset
1111 The name is a C++ overloaded operator name. Overloaded operators are named
anatofuz
parents:
diff changeset
1112 according to their spelling, e.g., "``operator+``" or "``operator new []``".
anatofuz
parents:
diff changeset
1113 Use ``N.getCXXOverloadedOperator()`` to retrieve the overloaded operator (a
anatofuz
parents:
diff changeset
1114 value of type ``OverloadedOperatorKind``).
anatofuz
parents:
diff changeset
1115
anatofuz
parents:
diff changeset
1116 ``CXXLiteralOperatorName``
anatofuz
parents:
diff changeset
1117
anatofuz
parents:
diff changeset
1118 The name is a C++11 user defined literal operator. User defined
anatofuz
parents:
diff changeset
1119 Literal operators are named according to the suffix they define,
anatofuz
parents:
diff changeset
1120 e.g., "``_foo``" for "``operator "" _foo``". Use
anatofuz
parents:
diff changeset
1121 ``N.getCXXLiteralIdentifier()`` to retrieve the corresponding
anatofuz
parents:
diff changeset
1122 ``IdentifierInfo*`` pointing to the identifier.
anatofuz
parents:
diff changeset
1123
anatofuz
parents:
diff changeset
1124 ``CXXUsingDirective``
anatofuz
parents:
diff changeset
1125
anatofuz
parents:
diff changeset
1126 The name is a C++ using directive. Using directives are not really
anatofuz
parents:
diff changeset
1127 NamedDecls, in that they all have the same name, but they are
anatofuz
parents:
diff changeset
1128 implemented as such in order to store them in DeclContext
anatofuz
parents:
diff changeset
1129 effectively.
anatofuz
parents:
diff changeset
1130
anatofuz
parents:
diff changeset
1131 ``DeclarationName``\ s are cheap to create, copy, and compare. They require
anatofuz
parents:
diff changeset
1132 only a single pointer's worth of storage in the common cases (identifiers,
anatofuz
parents:
diff changeset
1133 zero- and one-argument Objective-C selectors) and use dense, uniqued storage
anatofuz
parents:
diff changeset
1134 for the other kinds of names. Two ``DeclarationName``\ s can be compared for
anatofuz
parents:
diff changeset
1135 equality (``==``, ``!=``) using a simple bitwise comparison, can be ordered
anatofuz
parents:
diff changeset
1136 with ``<``, ``>``, ``<=``, and ``>=`` (which provide a lexicographical ordering
anatofuz
parents:
diff changeset
1137 for normal identifiers but an unspecified ordering for other kinds of names),
anatofuz
parents:
diff changeset
1138 and can be placed into LLVM ``DenseMap``\ s and ``DenseSet``\ s.
anatofuz
parents:
diff changeset
1139
anatofuz
parents:
diff changeset
1140 ``DeclarationName`` instances can be created in different ways depending on
anatofuz
parents:
diff changeset
1141 what kind of name the instance will store. Normal identifiers
anatofuz
parents:
diff changeset
1142 (``IdentifierInfo`` pointers) and Objective-C selectors (``Selector``) can be
anatofuz
parents:
diff changeset
1143 implicitly converted to ``DeclarationNames``. Names for C++ constructors,
anatofuz
parents:
diff changeset
1144 destructors, conversion functions, and overloaded operators can be retrieved
anatofuz
parents:
diff changeset
1145 from the ``DeclarationNameTable``, an instance of which is available as
anatofuz
parents:
diff changeset
1146 ``ASTContext::DeclarationNames``. The member functions
anatofuz
parents:
diff changeset
1147 ``getCXXConstructorName``, ``getCXXDestructorName``,
anatofuz
parents:
diff changeset
1148 ``getCXXConversionFunctionName``, and ``getCXXOperatorName``, respectively,
anatofuz
parents:
diff changeset
1149 return ``DeclarationName`` instances for the four kinds of C++ special function
anatofuz
parents:
diff changeset
1150 names.
anatofuz
parents:
diff changeset
1151
anatofuz
parents:
diff changeset
1152 .. _DeclContext:
anatofuz
parents:
diff changeset
1153
anatofuz
parents:
diff changeset
1154 Declaration contexts
anatofuz
parents:
diff changeset
1155 --------------------
anatofuz
parents:
diff changeset
1156
anatofuz
parents:
diff changeset
1157 Every declaration in a program exists within some *declaration context*, such
anatofuz
parents:
diff changeset
1158 as a translation unit, namespace, class, or function. Declaration contexts in
anatofuz
parents:
diff changeset
1159 Clang are represented by the ``DeclContext`` class, from which the various
anatofuz
parents:
diff changeset
1160 declaration-context AST nodes (``TranslationUnitDecl``, ``NamespaceDecl``,
anatofuz
parents:
diff changeset
1161 ``RecordDecl``, ``FunctionDecl``, etc.) will derive. The ``DeclContext`` class
anatofuz
parents:
diff changeset
1162 provides several facilities common to each declaration context:
anatofuz
parents:
diff changeset
1163
anatofuz
parents:
diff changeset
1164 Source-centric vs. Semantics-centric View of Declarations
anatofuz
parents:
diff changeset
1165
anatofuz
parents:
diff changeset
1166 ``DeclContext`` provides two views of the declarations stored within a
anatofuz
parents:
diff changeset
1167 declaration context. The source-centric view accurately represents the
anatofuz
parents:
diff changeset
1168 program source code as written, including multiple declarations of entities
anatofuz
parents:
diff changeset
1169 where present (see the section :ref:`Redeclarations and Overloads
anatofuz
parents:
diff changeset
1170 <Redeclarations>`), while the semantics-centric view represents the program
anatofuz
parents:
diff changeset
1171 semantics. The two views are kept synchronized by semantic analysis while
anatofuz
parents:
diff changeset
1172 the ASTs are being constructed.
anatofuz
parents:
diff changeset
1173
anatofuz
parents:
diff changeset
1174 Storage of declarations within that context
anatofuz
parents:
diff changeset
1175
anatofuz
parents:
diff changeset
1176 Every declaration context can contain some number of declarations. For
anatofuz
parents:
diff changeset
1177 example, a C++ class (represented by ``RecordDecl``) contains various member
anatofuz
parents:
diff changeset
1178 functions, fields, nested types, and so on. All of these declarations will
anatofuz
parents:
diff changeset
1179 be stored within the ``DeclContext``, and one can iterate over the
anatofuz
parents:
diff changeset
1180 declarations via [``DeclContext::decls_begin()``,
anatofuz
parents:
diff changeset
1181 ``DeclContext::decls_end()``). This mechanism provides the source-centric
anatofuz
parents:
diff changeset
1182 view of declarations in the context.
anatofuz
parents:
diff changeset
1183
anatofuz
parents:
diff changeset
1184 Lookup of declarations within that context
anatofuz
parents:
diff changeset
1185
anatofuz
parents:
diff changeset
1186 The ``DeclContext`` structure provides efficient name lookup for names within
anatofuz
parents:
diff changeset
1187 that declaration context. For example, if ``N`` is a namespace we can look
anatofuz
parents:
diff changeset
1188 for the name ``N::f`` using ``DeclContext::lookup``. The lookup itself is
anatofuz
parents:
diff changeset
1189 based on a lazily-constructed array (for declaration contexts with a small
anatofuz
parents:
diff changeset
1190 number of declarations) or hash table (for declaration contexts with more
anatofuz
parents:
diff changeset
1191 declarations). The lookup operation provides the semantics-centric view of
anatofuz
parents:
diff changeset
1192 the declarations in the context.
anatofuz
parents:
diff changeset
1193
anatofuz
parents:
diff changeset
1194 Ownership of declarations
anatofuz
parents:
diff changeset
1195
anatofuz
parents:
diff changeset
1196 The ``DeclContext`` owns all of the declarations that were declared within
anatofuz
parents:
diff changeset
1197 its declaration context, and is responsible for the management of their
anatofuz
parents:
diff changeset
1198 memory as well as their (de-)serialization.
anatofuz
parents:
diff changeset
1199
anatofuz
parents:
diff changeset
1200 All declarations are stored within a declaration context, and one can query
anatofuz
parents:
diff changeset
1201 information about the context in which each declaration lives. One can
anatofuz
parents:
diff changeset
1202 retrieve the ``DeclContext`` that contains a particular ``Decl`` using
anatofuz
parents:
diff changeset
1203 ``Decl::getDeclContext``. However, see the section
anatofuz
parents:
diff changeset
1204 :ref:`LexicalAndSemanticContexts` for more information about how to interpret
anatofuz
parents:
diff changeset
1205 this context information.
anatofuz
parents:
diff changeset
1206
anatofuz
parents:
diff changeset
1207 .. _Redeclarations:
anatofuz
parents:
diff changeset
1208
anatofuz
parents:
diff changeset
1209 Redeclarations and Overloads
anatofuz
parents:
diff changeset
1210 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
anatofuz
parents:
diff changeset
1211
anatofuz
parents:
diff changeset
1212 Within a translation unit, it is common for an entity to be declared several
anatofuz
parents:
diff changeset
1213 times. For example, we might declare a function "``f``" and then later
anatofuz
parents:
diff changeset
1214 re-declare it as part of an inlined definition:
anatofuz
parents:
diff changeset
1215
anatofuz
parents:
diff changeset
1216 .. code-block:: c++
anatofuz
parents:
diff changeset
1217
anatofuz
parents:
diff changeset
1218 void f(int x, int y, int z = 1);
anatofuz
parents:
diff changeset
1219
anatofuz
parents:
diff changeset
1220 inline void f(int x, int y, int z) { /* ... */ }
anatofuz
parents:
diff changeset
1221
anatofuz
parents:
diff changeset
1222 The representation of "``f``" differs in the source-centric and
anatofuz
parents:
diff changeset
1223 semantics-centric views of a declaration context. In the source-centric view,
anatofuz
parents:
diff changeset
1224 all redeclarations will be present, in the order they occurred in the source
anatofuz
parents:
diff changeset
1225 code, making this view suitable for clients that wish to see the structure of
anatofuz
parents:
diff changeset
1226 the source code. In the semantics-centric view, only the most recent "``f``"
anatofuz
parents:
diff changeset
1227 will be found by the lookup, since it effectively replaces the first
anatofuz
parents:
diff changeset
1228 declaration of "``f``".
anatofuz
parents:
diff changeset
1229
anatofuz
parents:
diff changeset
1230 (Note that because ``f`` can be redeclared at block scope, or in a friend
anatofuz
parents:
diff changeset
1231 declaration, etc. it is possible that the declaration of ``f`` found by name
anatofuz
parents:
diff changeset
1232 lookup will not be the most recent one.)
anatofuz
parents:
diff changeset
1233
anatofuz
parents:
diff changeset
1234 In the semantics-centric view, overloading of functions is represented
anatofuz
parents:
diff changeset
1235 explicitly. For example, given two declarations of a function "``g``" that are
anatofuz
parents:
diff changeset
1236 overloaded, e.g.,
anatofuz
parents:
diff changeset
1237
anatofuz
parents:
diff changeset
1238 .. code-block:: c++
anatofuz
parents:
diff changeset
1239
anatofuz
parents:
diff changeset
1240 void g();
anatofuz
parents:
diff changeset
1241 void g(int);
anatofuz
parents:
diff changeset
1242
anatofuz
parents:
diff changeset
1243 the ``DeclContext::lookup`` operation will return a
anatofuz
parents:
diff changeset
1244 ``DeclContext::lookup_result`` that contains a range of iterators over
anatofuz
parents:
diff changeset
1245 declarations of "``g``". Clients that perform semantic analysis on a program
anatofuz
parents:
diff changeset
1246 that is not concerned with the actual source code will primarily use this
anatofuz
parents:
diff changeset
1247 semantics-centric view.
anatofuz
parents:
diff changeset
1248
anatofuz
parents:
diff changeset
1249 .. _LexicalAndSemanticContexts:
anatofuz
parents:
diff changeset
1250
anatofuz
parents:
diff changeset
1251 Lexical and Semantic Contexts
anatofuz
parents:
diff changeset
1252 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
anatofuz
parents:
diff changeset
1253
anatofuz
parents:
diff changeset
1254 Each declaration has two potentially different declaration contexts: a
anatofuz
parents:
diff changeset
1255 *lexical* context, which corresponds to the source-centric view of the
anatofuz
parents:
diff changeset
1256 declaration context, and a *semantic* context, which corresponds to the
anatofuz
parents:
diff changeset
1257 semantics-centric view. The lexical context is accessible via
anatofuz
parents:
diff changeset
1258 ``Decl::getLexicalDeclContext`` while the semantic context is accessible via
anatofuz
parents:
diff changeset
1259 ``Decl::getDeclContext``, both of which return ``DeclContext`` pointers. For
anatofuz
parents:
diff changeset
1260 most declarations, the two contexts are identical. For example:
anatofuz
parents:
diff changeset
1261
anatofuz
parents:
diff changeset
1262 .. code-block:: c++
anatofuz
parents:
diff changeset
1263
anatofuz
parents:
diff changeset
1264 class X {
anatofuz
parents:
diff changeset
1265 public:
anatofuz
parents:
diff changeset
1266 void f(int x);
anatofuz
parents:
diff changeset
1267 };
anatofuz
parents:
diff changeset
1268
anatofuz
parents:
diff changeset
1269 Here, the semantic and lexical contexts of ``X::f`` are the ``DeclContext``
anatofuz
parents:
diff changeset
1270 associated with the class ``X`` (itself stored as a ``RecordDecl`` AST node).
anatofuz
parents:
diff changeset
1271 However, we can now define ``X::f`` out-of-line:
anatofuz
parents:
diff changeset
1272
anatofuz
parents:
diff changeset
1273 .. code-block:: c++
anatofuz
parents:
diff changeset
1274
anatofuz
parents:
diff changeset
1275 void X::f(int x = 17) { /* ... */ }
anatofuz
parents:
diff changeset
1276
anatofuz
parents:
diff changeset
1277 This definition of "``f``" has different lexical and semantic contexts. The
anatofuz
parents:
diff changeset
1278 lexical context corresponds to the declaration context in which the actual
anatofuz
parents:
diff changeset
1279 declaration occurred in the source code, e.g., the translation unit containing
anatofuz
parents:
diff changeset
1280 ``X``. Thus, this declaration of ``X::f`` can be found by traversing the
anatofuz
parents:
diff changeset
1281 declarations provided by [``decls_begin()``, ``decls_end()``) in the
anatofuz
parents:
diff changeset
1282 translation unit.
anatofuz
parents:
diff changeset
1283
anatofuz
parents:
diff changeset
1284 The semantic context of ``X::f`` corresponds to the class ``X``, since this
anatofuz
parents:
diff changeset
1285 member function is (semantically) a member of ``X``. Lookup of the name ``f``
anatofuz
parents:
diff changeset
1286 into the ``DeclContext`` associated with ``X`` will then return the definition
anatofuz
parents:
diff changeset
1287 of ``X::f`` (including information about the default argument).
anatofuz
parents:
diff changeset
1288
anatofuz
parents:
diff changeset
1289 Transparent Declaration Contexts
anatofuz
parents:
diff changeset
1290 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
anatofuz
parents:
diff changeset
1291
anatofuz
parents:
diff changeset
1292 In C and C++, there are several contexts in which names that are logically
anatofuz
parents:
diff changeset
1293 declared inside another declaration will actually "leak" out into the enclosing
anatofuz
parents:
diff changeset
1294 scope from the perspective of name lookup. The most obvious instance of this
anatofuz
parents:
diff changeset
1295 behavior is in enumeration types, e.g.,
anatofuz
parents:
diff changeset
1296
anatofuz
parents:
diff changeset
1297 .. code-block:: c++
anatofuz
parents:
diff changeset
1298
anatofuz
parents:
diff changeset
1299 enum Color {
anatofuz
parents:
diff changeset
1300 Red,
anatofuz
parents:
diff changeset
1301 Green,
anatofuz
parents:
diff changeset
1302 Blue
anatofuz
parents:
diff changeset
1303 };
anatofuz
parents:
diff changeset
1304
anatofuz
parents:
diff changeset
1305 Here, ``Color`` is an enumeration, which is a declaration context that contains
anatofuz
parents:
diff changeset
1306 the enumerators ``Red``, ``Green``, and ``Blue``. Thus, traversing the list of
anatofuz
parents:
diff changeset
1307 declarations contained in the enumeration ``Color`` will yield ``Red``,
anatofuz
parents:
diff changeset
1308 ``Green``, and ``Blue``. However, outside of the scope of ``Color`` one can
anatofuz
parents:
diff changeset
1309 name the enumerator ``Red`` without qualifying the name, e.g.,
anatofuz
parents:
diff changeset
1310
anatofuz
parents:
diff changeset
1311 .. code-block:: c++
anatofuz
parents:
diff changeset
1312
anatofuz
parents:
diff changeset
1313 Color c = Red;
anatofuz
parents:
diff changeset
1314
anatofuz
parents:
diff changeset
1315 There are other entities in C++ that provide similar behavior. For example,
anatofuz
parents:
diff changeset
1316 linkage specifications that use curly braces:
anatofuz
parents:
diff changeset
1317
anatofuz
parents:
diff changeset
1318 .. code-block:: c++
anatofuz
parents:
diff changeset
1319
anatofuz
parents:
diff changeset
1320 extern "C" {
anatofuz
parents:
diff changeset
1321 void f(int);
anatofuz
parents:
diff changeset
1322 void g(int);
anatofuz
parents:
diff changeset
1323 }
anatofuz
parents:
diff changeset
1324 // f and g are visible here
anatofuz
parents:
diff changeset
1325
anatofuz
parents:
diff changeset
1326 For source-level accuracy, we treat the linkage specification and enumeration
anatofuz
parents:
diff changeset
1327 type as a declaration context in which its enclosed declarations ("``Red``",
anatofuz
parents:
diff changeset
1328 "``Green``", and "``Blue``"; "``f``" and "``g``") are declared. However, these
anatofuz
parents:
diff changeset
1329 declarations are visible outside of the scope of the declaration context.
anatofuz
parents:
diff changeset
1330
anatofuz
parents:
diff changeset
1331 These language features (and several others, described below) have roughly the
anatofuz
parents:
diff changeset
1332 same set of requirements: declarations are declared within a particular lexical
anatofuz
parents:
diff changeset
1333 context, but the declarations are also found via name lookup in scopes
anatofuz
parents:
diff changeset
1334 enclosing the declaration itself. This feature is implemented via
anatofuz
parents:
diff changeset
1335 *transparent* declaration contexts (see
anatofuz
parents:
diff changeset
1336 ``DeclContext::isTransparentContext()``), whose declarations are visible in the
anatofuz
parents:
diff changeset
1337 nearest enclosing non-transparent declaration context. This means that the
anatofuz
parents:
diff changeset
1338 lexical context of the declaration (e.g., an enumerator) will be the
anatofuz
parents:
diff changeset
1339 transparent ``DeclContext`` itself, as will the semantic context, but the
anatofuz
parents:
diff changeset
1340 declaration will be visible in every outer context up to and including the
anatofuz
parents:
diff changeset
1341 first non-transparent declaration context (since transparent declaration
anatofuz
parents:
diff changeset
1342 contexts can be nested).
anatofuz
parents:
diff changeset
1343
anatofuz
parents:
diff changeset
1344 The transparent ``DeclContext``\ s are:
anatofuz
parents:
diff changeset
1345
anatofuz
parents:
diff changeset
1346 * Enumerations (but not C++11 "scoped enumerations"):
anatofuz
parents:
diff changeset
1347
anatofuz
parents:
diff changeset
1348 .. code-block:: c++
anatofuz
parents:
diff changeset
1349
anatofuz
parents:
diff changeset
1350 enum Color {
anatofuz
parents:
diff changeset
1351 Red,
anatofuz
parents:
diff changeset
1352 Green,
anatofuz
parents:
diff changeset
1353 Blue
anatofuz
parents:
diff changeset
1354 };
anatofuz
parents:
diff changeset
1355 // Red, Green, and Blue are in scope
anatofuz
parents:
diff changeset
1356
anatofuz
parents:
diff changeset
1357 * C++ linkage specifications:
anatofuz
parents:
diff changeset
1358
anatofuz
parents:
diff changeset
1359 .. code-block:: c++
anatofuz
parents:
diff changeset
1360
anatofuz
parents:
diff changeset
1361 extern "C" {
anatofuz
parents:
diff changeset
1362 void f(int);
anatofuz
parents:
diff changeset
1363 void g(int);
anatofuz
parents:
diff changeset
1364 }
anatofuz
parents:
diff changeset
1365 // f and g are in scope
anatofuz
parents:
diff changeset
1366
anatofuz
parents:
diff changeset
1367 * Anonymous unions and structs:
anatofuz
parents:
diff changeset
1368
anatofuz
parents:
diff changeset
1369 .. code-block:: c++
anatofuz
parents:
diff changeset
1370
anatofuz
parents:
diff changeset
1371 struct LookupTable {
anatofuz
parents:
diff changeset
1372 bool IsVector;
anatofuz
parents:
diff changeset
1373 union {
anatofuz
parents:
diff changeset
1374 std::vector<Item> *Vector;
anatofuz
parents:
diff changeset
1375 std::set<Item> *Set;
anatofuz
parents:
diff changeset
1376 };
anatofuz
parents:
diff changeset
1377 };
anatofuz
parents:
diff changeset
1378
anatofuz
parents:
diff changeset
1379 LookupTable LT;
anatofuz
parents:
diff changeset
1380 LT.Vector = 0; // Okay: finds Vector inside the unnamed union
anatofuz
parents:
diff changeset
1381
anatofuz
parents:
diff changeset
1382 * C++11 inline namespaces:
anatofuz
parents:
diff changeset
1383
anatofuz
parents:
diff changeset
1384 .. code-block:: c++
anatofuz
parents:
diff changeset
1385
anatofuz
parents:
diff changeset
1386 namespace mylib {
anatofuz
parents:
diff changeset
1387 inline namespace debug {
anatofuz
parents:
diff changeset
1388 class X;
anatofuz
parents:
diff changeset
1389 }
anatofuz
parents:
diff changeset
1390 }
anatofuz
parents:
diff changeset
1391 mylib::X *xp; // okay: mylib::X refers to mylib::debug::X
anatofuz
parents:
diff changeset
1392
anatofuz
parents:
diff changeset
1393 .. _MultiDeclContext:
anatofuz
parents:
diff changeset
1394
anatofuz
parents:
diff changeset
1395 Multiply-Defined Declaration Contexts
anatofuz
parents:
diff changeset
1396 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
anatofuz
parents:
diff changeset
1397
anatofuz
parents:
diff changeset
1398 C++ namespaces have the interesting property that
anatofuz
parents:
diff changeset
1399 the namespace can be defined multiple times, and the declarations provided by
anatofuz
parents:
diff changeset
1400 each namespace definition are effectively merged (from the semantic point of
anatofuz
parents:
diff changeset
1401 view). For example, the following two code snippets are semantically
anatofuz
parents:
diff changeset
1402 indistinguishable:
anatofuz
parents:
diff changeset
1403
anatofuz
parents:
diff changeset
1404 .. code-block:: c++
anatofuz
parents:
diff changeset
1405
anatofuz
parents:
diff changeset
1406 // Snippet #1:
anatofuz
parents:
diff changeset
1407 namespace N {
anatofuz
parents:
diff changeset
1408 void f();
anatofuz
parents:
diff changeset
1409 }
anatofuz
parents:
diff changeset
1410 namespace N {
anatofuz
parents:
diff changeset
1411 void f(int);
anatofuz
parents:
diff changeset
1412 }
anatofuz
parents:
diff changeset
1413
anatofuz
parents:
diff changeset
1414 // Snippet #2:
anatofuz
parents:
diff changeset
1415 namespace N {
anatofuz
parents:
diff changeset
1416 void f();
anatofuz
parents:
diff changeset
1417 void f(int);
anatofuz
parents:
diff changeset
1418 }
anatofuz
parents:
diff changeset
1419
anatofuz
parents:
diff changeset
1420 In Clang's representation, the source-centric view of declaration contexts will
anatofuz
parents:
diff changeset
1421 actually have two separate ``NamespaceDecl`` nodes in Snippet #1, each of which
anatofuz
parents:
diff changeset
1422 is a declaration context that contains a single declaration of "``f``".
anatofuz
parents:
diff changeset
1423 However, the semantics-centric view provided by name lookup into the namespace
anatofuz
parents:
diff changeset
1424 ``N`` for "``f``" will return a ``DeclContext::lookup_result`` that contains a
anatofuz
parents:
diff changeset
1425 range of iterators over declarations of "``f``".
anatofuz
parents:
diff changeset
1426
anatofuz
parents:
diff changeset
1427 ``DeclContext`` manages multiply-defined declaration contexts internally. The
anatofuz
parents:
diff changeset
1428 function ``DeclContext::getPrimaryContext`` retrieves the "primary" context for
anatofuz
parents:
diff changeset
1429 a given ``DeclContext`` instance, which is the ``DeclContext`` responsible for
anatofuz
parents:
diff changeset
1430 maintaining the lookup table used for the semantics-centric view. Given a
anatofuz
parents:
diff changeset
1431 DeclContext, one can obtain the set of declaration contexts that are
anatofuz
parents:
diff changeset
1432 semantically connected to this declaration context, in source order, including
anatofuz
parents:
diff changeset
1433 this context (which will be the only result, for non-namespace contexts) via
anatofuz
parents:
diff changeset
1434 ``DeclContext::collectAllContexts``. Note that these functions are used
anatofuz
parents:
diff changeset
1435 internally within the lookup and insertion methods of the ``DeclContext``, so
anatofuz
parents:
diff changeset
1436 the vast majority of clients can ignore them.
anatofuz
parents:
diff changeset
1437
anatofuz
parents:
diff changeset
1438 Because the same entity can be defined multiple times in different modules,
anatofuz
parents:
diff changeset
1439 it is also possible for there to be multiple definitions of (for instance)
anatofuz
parents:
diff changeset
1440 a ``CXXRecordDecl``, all of which describe a definition of the same class.
anatofuz
parents:
diff changeset
1441 In such a case, only one of those "definitions" is considered by Clang to be
anatofuz
parents:
diff changeset
1442 the definiition of the class, and the others are treated as non-defining
anatofuz
parents:
diff changeset
1443 declarations that happen to also contain member declarations. Corresponding
anatofuz
parents:
diff changeset
1444 members in each definition of such multiply-defined classes are identified
anatofuz
parents:
diff changeset
1445 either by redeclaration chains (if the members are ``Redeclarable``)
anatofuz
parents:
diff changeset
1446 or by simply a pointer to the canonical declaration (if the declarations
anatofuz
parents:
diff changeset
1447 are not ``Redeclarable`` -- in that case, a ``Mergeable`` base class is used
anatofuz
parents:
diff changeset
1448 instead).
anatofuz
parents:
diff changeset
1449
anatofuz
parents:
diff changeset
1450 The ASTImporter
anatofuz
parents:
diff changeset
1451 ---------------
anatofuz
parents:
diff changeset
1452
anatofuz
parents:
diff changeset
1453 The ``ASTImporter`` class imports nodes of an ``ASTContext`` into another
anatofuz
parents:
diff changeset
1454 ``ASTContext``. Please refer to the document :doc:`ASTImporter: Merging Clang
anatofuz
parents:
diff changeset
1455 ASTs <LibASTImporter>` for an introduction. And please read through the
anatofuz
parents:
diff changeset
1456 high-level `description of the import algorithm
anatofuz
parents:
diff changeset
1457 <LibASTImporter.html#algorithm-of-the-import>`_, this is essential for
anatofuz
parents:
diff changeset
1458 understanding further implementation details of the importer.
anatofuz
parents:
diff changeset
1459
anatofuz
parents:
diff changeset
1460 .. _templated:
anatofuz
parents:
diff changeset
1461
anatofuz
parents:
diff changeset
1462 Abstract Syntax Graph
anatofuz
parents:
diff changeset
1463 ^^^^^^^^^^^^^^^^^^^^^
anatofuz
parents:
diff changeset
1464
anatofuz
parents:
diff changeset
1465 Despite the name, the Clang AST is not a tree. It is a directed graph with
anatofuz
parents:
diff changeset
1466 cycles. One example of a cycle is the connection between a
anatofuz
parents:
diff changeset
1467 ``ClassTemplateDecl`` and its "templated" ``CXXRecordDecl``. The *templated*
anatofuz
parents:
diff changeset
1468 ``CXXRecordDecl`` represents all the fields and methods inside the class
anatofuz
parents:
diff changeset
1469 template, while the ``ClassTemplateDecl`` holds the information which is
anatofuz
parents:
diff changeset
1470 related to being a template, i.e. template arguments, etc. We can get the
anatofuz
parents:
diff changeset
1471 *templated* class (the ``CXXRecordDecl``) of a ``ClassTemplateDecl`` with
anatofuz
parents:
diff changeset
1472 ``ClassTemplateDecl::getTemplatedDecl()``. And we can get back a pointer of the
anatofuz
parents:
diff changeset
1473 "described" class template from the *templated* class:
anatofuz
parents:
diff changeset
1474 ``CXXRecordDecl::getDescribedTemplate()``. So, this is a cycle between two
anatofuz
parents:
diff changeset
1475 nodes: between the *templated* and the *described* node. There may be various
anatofuz
parents:
diff changeset
1476 other kinds of cycles in the AST especially in case of declarations.
anatofuz
parents:
diff changeset
1477
anatofuz
parents:
diff changeset
1478 .. _structural-eq:
anatofuz
parents:
diff changeset
1479
anatofuz
parents:
diff changeset
1480 Structural Equivalency
anatofuz
parents:
diff changeset
1481 ^^^^^^^^^^^^^^^^^^^^^^
anatofuz
parents:
diff changeset
1482
anatofuz
parents:
diff changeset
1483 Importing one AST node copies that node into the destination ``ASTContext``. To
anatofuz
parents:
diff changeset
1484 copy one node means that we create a new node in the "to" context then we set
anatofuz
parents:
diff changeset
1485 its properties to be equal to the properties of the source node. Before the
anatofuz
parents:
diff changeset
1486 copy, we make sure that the source node is not *structurally equivalent* to any
anatofuz
parents:
diff changeset
1487 existing node in the destination context. If it happens to be equivalent then
anatofuz
parents:
diff changeset
1488 we skip the copy.
anatofuz
parents:
diff changeset
1489
anatofuz
parents:
diff changeset
1490 The informal definition of structural equivalency is the following:
anatofuz
parents:
diff changeset
1491 Two nodes are **structurally equivalent** if they are
anatofuz
parents:
diff changeset
1492
anatofuz
parents:
diff changeset
1493 - builtin types and refer to the same type, e.g. ``int`` and ``int`` are
anatofuz
parents:
diff changeset
1494 structurally equivalent,
anatofuz
parents:
diff changeset
1495 - function types and all their parameters have structurally equivalent types,
anatofuz
parents:
diff changeset
1496 - record types and all their fields in order of their definition have the same
anatofuz
parents:
diff changeset
1497 identifier names and structurally equivalent types,
anatofuz
parents:
diff changeset
1498 - variable or function declarations and they have the same identifier name and
anatofuz
parents:
diff changeset
1499 their types are structurally equivalent.
anatofuz
parents:
diff changeset
1500
anatofuz
parents:
diff changeset
1501 In C, two types are structurally equivalent if they are *compatible types*. For
anatofuz
parents:
diff changeset
1502 a formal definition of *compatible types*, please refer to 6.2.7/1 in the C11
anatofuz
parents:
diff changeset
1503 standard. However, there is no definition for *compatible types* in the C++
anatofuz
parents:
diff changeset
1504 standard. Still, we extend the definition of structural equivalency to
anatofuz
parents:
diff changeset
1505 templates and their instantiations similarly: besides checking the previously
anatofuz
parents:
diff changeset
1506 mentioned properties, we have to check for equivalent template
anatofuz
parents:
diff changeset
1507 parameters/arguments, etc.
anatofuz
parents:
diff changeset
1508
anatofuz
parents:
diff changeset
1509 The structural equivalent check can be and is used independently from the
anatofuz
parents:
diff changeset
1510 ASTImporter, e.g. the ``clang::Sema`` class uses it also.
anatofuz
parents:
diff changeset
1511
anatofuz
parents:
diff changeset
1512 The equivalence of nodes may depend on the equivalency of other pairs of nodes.
anatofuz
parents:
diff changeset
1513 Thus, the check is implemented as a parallel graph traversal. We traverse
anatofuz
parents:
diff changeset
1514 through the nodes of both graphs at the same time. The actual implementation is
anatofuz
parents:
diff changeset
1515 similar to breadth-first-search. Let's say we start the traverse with the <A,B>
anatofuz
parents:
diff changeset
1516 pair of nodes. Whenever the traversal reaches a pair <X,Y> then the following
anatofuz
parents:
diff changeset
1517 statements are true:
anatofuz
parents:
diff changeset
1518
anatofuz
parents:
diff changeset
1519 - A and X are nodes from the same ASTContext.
anatofuz
parents:
diff changeset
1520 - B and Y are nodes from the same ASTContext.
anatofuz
parents:
diff changeset
1521 - A and B may or may not be from the same ASTContext.
anatofuz
parents:
diff changeset
1522 - if A == X and B == Y (pointer equivalency) then (there is a cycle during the
anatofuz
parents:
diff changeset
1523 traverse)
anatofuz
parents:
diff changeset
1524
anatofuz
parents:
diff changeset
1525 - A and B are structurally equivalent if and only if
anatofuz
parents:
diff changeset
1526
anatofuz
parents:
diff changeset
1527 - All dependent nodes on the path from <A,B> to <X,Y> are structurally
anatofuz
parents:
diff changeset
1528 equivalent.
anatofuz
parents:
diff changeset
1529
anatofuz
parents:
diff changeset
1530 When we compare two classes or enums and one of them is incomplete or has
anatofuz
parents:
diff changeset
1531 unloaded external lexical declarations then we cannot descend to compare their
anatofuz
parents:
diff changeset
1532 contained declarations. So in these cases they are considered equal if they
anatofuz
parents:
diff changeset
1533 have the same names. This is the way how we compare forward declarations with
anatofuz
parents:
diff changeset
1534 definitions.
anatofuz
parents:
diff changeset
1535
anatofuz
parents:
diff changeset
1536 .. TODO Should we elaborate the actual implementation of the graph traversal,
anatofuz
parents:
diff changeset
1537 .. which is a very weird BFS traversal?
anatofuz
parents:
diff changeset
1538
anatofuz
parents:
diff changeset
1539 Redeclaration Chains
anatofuz
parents:
diff changeset
1540 ^^^^^^^^^^^^^^^^^^^^
anatofuz
parents:
diff changeset
1541
anatofuz
parents:
diff changeset
1542 The early version of the ``ASTImporter``'s merge mechanism squashed the
anatofuz
parents:
diff changeset
1543 declarations, i.e. it aimed to have only one declaration instead of maintaining
anatofuz
parents:
diff changeset
1544 a whole redeclaration chain. This early approach simply skipped importing a
anatofuz
parents:
diff changeset
1545 function prototype, but it imported a definition. To demonstrate the problem
anatofuz
parents:
diff changeset
1546 with this approach let's consider an empty "to" context and the following
anatofuz
parents:
diff changeset
1547 ``virtual`` function declarations of ``f`` in the "from" context:
anatofuz
parents:
diff changeset
1548
anatofuz
parents:
diff changeset
1549 .. code-block:: c++
anatofuz
parents:
diff changeset
1550
anatofuz
parents:
diff changeset
1551 struct B { virtual void f(); };
anatofuz
parents:
diff changeset
1552 void B::f() {} // <-- let's import this definition
anatofuz
parents:
diff changeset
1553
anatofuz
parents:
diff changeset
1554 If we imported the definition with the "squashing" approach then we would
anatofuz
parents:
diff changeset
1555 end-up having one declaration which is indeed a definition, but ``isVirtual()``
anatofuz
parents:
diff changeset
1556 returns ``false`` for it. The reason is that the definition is indeed not
anatofuz
parents:
diff changeset
1557 virtual, it is the property of the prototype!
anatofuz
parents:
diff changeset
1558
anatofuz
parents:
diff changeset
1559 Consequently, we must either set the virtual flag for the definition (but then
anatofuz
parents:
diff changeset
1560 we create a malformed AST which the parser would never create), or we import
anatofuz
parents:
diff changeset
1561 the whole redeclaration chain of the function. The most recent version of the
anatofuz
parents:
diff changeset
1562 ``ASTImporter`` uses the latter mechanism. We do import all function
anatofuz
parents:
diff changeset
1563 declarations - regardless if they are definitions or prototypes - in the order
anatofuz
parents:
diff changeset
1564 as they appear in the "from" context.
anatofuz
parents:
diff changeset
1565
anatofuz
parents:
diff changeset
1566 .. One definition
anatofuz
parents:
diff changeset
1567
anatofuz
parents:
diff changeset
1568 If we have an existing definition in the "to" context, then we cannot import
anatofuz
parents:
diff changeset
1569 another definition, we will use the existing definition. However, we can import
anatofuz
parents:
diff changeset
1570 prototype(s): we chain the newly imported prototype(s) to the existing
anatofuz
parents:
diff changeset
1571 definition. Whenever we import a new prototype from a third context, that will
anatofuz
parents:
diff changeset
1572 be added to the end of the redeclaration chain. This may result in long
anatofuz
parents:
diff changeset
1573 redeclaration chains in certain cases, e.g. if we import from several
anatofuz
parents:
diff changeset
1574 translation units which include the same header with the prototype.
anatofuz
parents:
diff changeset
1575
anatofuz
parents:
diff changeset
1576 .. Squashing prototypes
anatofuz
parents:
diff changeset
1577
anatofuz
parents:
diff changeset
1578 To mitigate the problem of long redeclaration chains of free functions, we
anatofuz
parents:
diff changeset
1579 could compare prototypes to see if they have the same properties and if yes
anatofuz
parents:
diff changeset
1580 then we could merge these prototypes. The implementation of squashing of
anatofuz
parents:
diff changeset
1581 prototypes for free functions is future work.
anatofuz
parents:
diff changeset
1582
anatofuz
parents:
diff changeset
1583 .. Exception: Cannot have more than 1 prototype in-class
anatofuz
parents:
diff changeset
1584
anatofuz
parents:
diff changeset
1585 Chaining functions this way ensures that we do copy all information from the
anatofuz
parents:
diff changeset
1586 source AST. Nonetheless, there is a problem with member functions: While we can
anatofuz
parents:
diff changeset
1587 have many prototypes for free functions, we must have only one prototype for a
anatofuz
parents:
diff changeset
1588 member function.
anatofuz
parents:
diff changeset
1589
anatofuz
parents:
diff changeset
1590 .. code-block:: c++
anatofuz
parents:
diff changeset
1591
anatofuz
parents:
diff changeset
1592 void f(); // OK
anatofuz
parents:
diff changeset
1593 void f(); // OK
anatofuz
parents:
diff changeset
1594
anatofuz
parents:
diff changeset
1595 struct X {
anatofuz
parents:
diff changeset
1596 void f(); // OK
anatofuz
parents:
diff changeset
1597 void f(); // ERROR
anatofuz
parents:
diff changeset
1598 };
anatofuz
parents:
diff changeset
1599 void X::f() {} // OK
anatofuz
parents:
diff changeset
1600
anatofuz
parents:
diff changeset
1601 Thus, prototypes of member functions must be squashed, we cannot just simply
anatofuz
parents:
diff changeset
1602 attach a new prototype to the existing in-class prototype. Consider the
anatofuz
parents:
diff changeset
1603 following contexts:
anatofuz
parents:
diff changeset
1604
anatofuz
parents:
diff changeset
1605 .. code-block:: c++
anatofuz
parents:
diff changeset
1606
anatofuz
parents:
diff changeset
1607 // "to" context
anatofuz
parents:
diff changeset
1608 struct X {
anatofuz
parents:
diff changeset
1609 void f(); // D0
anatofuz
parents:
diff changeset
1610 };
anatofuz
parents:
diff changeset
1611
anatofuz
parents:
diff changeset
1612 .. code-block:: c++
anatofuz
parents:
diff changeset
1613
anatofuz
parents:
diff changeset
1614 // "from" context
anatofuz
parents:
diff changeset
1615 struct X {
anatofuz
parents:
diff changeset
1616 void f(); // D1
anatofuz
parents:
diff changeset
1617 };
anatofuz
parents:
diff changeset
1618 void X::f() {} // D2
anatofuz
parents:
diff changeset
1619
anatofuz
parents:
diff changeset
1620 When we import the prototype and the definition of ``f`` from the "from"
anatofuz
parents:
diff changeset
1621 context, then the resulting redecl chain will look like this ``D0 -> D2'``,
anatofuz
parents:
diff changeset
1622 where ``D2'`` is the copy of ``D2`` in the "to" context.
anatofuz
parents:
diff changeset
1623
anatofuz
parents:
diff changeset
1624 .. Redecl chains of other declarations
anatofuz
parents:
diff changeset
1625
anatofuz
parents:
diff changeset
1626 Generally speaking, when we import declarations (like enums and classes) we do
anatofuz
parents:
diff changeset
1627 attach the newly imported declaration to the existing redeclaration chain (if
anatofuz
parents:
diff changeset
1628 there is structural equivalency). We do not import, however, the whole
anatofuz
parents:
diff changeset
1629 redeclaration chain as we do in case of functions. Up till now, we haven't
anatofuz
parents:
diff changeset
1630 found any essential property of forward declarations which is similar to the
anatofuz
parents:
diff changeset
1631 case of the virtual flag in a member function prototype. In the future, this
anatofuz
parents:
diff changeset
1632 may change, though.
anatofuz
parents:
diff changeset
1633
anatofuz
parents:
diff changeset
1634 Traversal during the Import
anatofuz
parents:
diff changeset
1635 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
anatofuz
parents:
diff changeset
1636
anatofuz
parents:
diff changeset
1637 The node specific import mechanisms are implemented in
anatofuz
parents:
diff changeset
1638 ``ASTNodeImporter::VisitNode()`` functions, e.g. ``VisitFunctionDecl()``.
anatofuz
parents:
diff changeset
1639 When we import a declaration then first we import everything which is needed to
anatofuz
parents:
diff changeset
1640 call the constructor of that declaration node. Everything which can be set
anatofuz
parents:
diff changeset
1641 later is set after the node is created. For example, in case of a
anatofuz
parents:
diff changeset
1642 ``FunctionDecl`` we first import the declaration context in which the function
anatofuz
parents:
diff changeset
1643 is declared, then we create the ``FunctionDecl`` and only then we import the
anatofuz
parents:
diff changeset
1644 body of the function. This means there are implicit dependencies between AST
anatofuz
parents:
diff changeset
1645 nodes. These dependencies determine the order in which we visit nodes in the
anatofuz
parents:
diff changeset
1646 "from" context. As with the regular graph traversal algorithms like DFS, we
anatofuz
parents:
diff changeset
1647 keep track which nodes we have already visited in
anatofuz
parents:
diff changeset
1648 ``ASTImporter::ImportedDecls``. Whenever we create a node then we immediately
anatofuz
parents:
diff changeset
1649 add that to the ``ImportedDecls``. We must not start the import of any other
anatofuz
parents:
diff changeset
1650 declarations before we keep track of the newly created one. This is essential,
anatofuz
parents:
diff changeset
1651 otherwise, we would not be able to handle circular dependencies. To enforce
anatofuz
parents:
diff changeset
1652 this, we wrap all constructor calls of all AST nodes in
anatofuz
parents:
diff changeset
1653 ``GetImportedOrCreateDecl()``. This wrapper ensures that all newly created
anatofuz
parents:
diff changeset
1654 declarations are immediately marked as imported; also, if a declaration is
anatofuz
parents:
diff changeset
1655 already marked as imported then we just return its counterpart in the "to"
anatofuz
parents:
diff changeset
1656 context. Consequently, calling a declaration's ``::Create()`` function directly
anatofuz
parents:
diff changeset
1657 would lead to errors, please don't do that!
anatofuz
parents:
diff changeset
1658
anatofuz
parents:
diff changeset
1659 Even with the use of ``GetImportedOrCreateDecl()`` there is still a
anatofuz
parents:
diff changeset
1660 probability of having an infinite import recursion if things are imported from
anatofuz
parents:
diff changeset
1661 each other in wrong way. Imagine that during the import of ``A``, the import of
anatofuz
parents:
diff changeset
1662 ``B`` is requested before we could create the node for ``A`` (the constructor
anatofuz
parents:
diff changeset
1663 needs a reference to ``B``). And the same could be true for the import of ``B``
anatofuz
parents:
diff changeset
1664 (``A`` is requested to be imported before we could create the node for ``B``).
anatofuz
parents:
diff changeset
1665 In case of the :ref:`templated-described swing <templated>` we take
anatofuz
parents:
diff changeset
1666 extra attention to break the cyclical dependency: we import and set the
anatofuz
parents:
diff changeset
1667 described template only after the ``CXXRecordDecl`` is created. As a best
anatofuz
parents:
diff changeset
1668 practice, before creating the node in the "to" context, avoid importing of
anatofuz
parents:
diff changeset
1669 other nodes which are not needed for the constructor of node ``A``.
anatofuz
parents:
diff changeset
1670
anatofuz
parents:
diff changeset
1671 Error Handling
anatofuz
parents:
diff changeset
1672 ^^^^^^^^^^^^^^
anatofuz
parents:
diff changeset
1673
anatofuz
parents:
diff changeset
1674 Every import function returns with either an ``llvm::Error`` or an
anatofuz
parents:
diff changeset
1675 ``llvm::Expected<T>`` object. This enforces to check the return value of the
anatofuz
parents:
diff changeset
1676 import functions. If there was an error during one import then we return with
anatofuz
parents:
diff changeset
1677 that error. (Exception: when we import the members of a class, we collect the
anatofuz
parents:
diff changeset
1678 individual errors with each member and we concatenate them in one Error
anatofuz
parents:
diff changeset
1679 object.) We cache these errors in cases of declarations. During the next import
anatofuz
parents:
diff changeset
1680 call if there is an existing error we just return with that. So, clients of the
anatofuz
parents:
diff changeset
1681 library receive an Error object, which they must check.
anatofuz
parents:
diff changeset
1682
anatofuz
parents:
diff changeset
1683 During import of a specific declaration, it may happen that some AST nodes had
anatofuz
parents:
diff changeset
1684 already been created before we recognize an error. In this case, we signal back
anatofuz
parents:
diff changeset
1685 the error to the caller, but the "to" context remains polluted with those nodes
anatofuz
parents:
diff changeset
1686 which had been created. Ideally, those nodes should not had been created, but
anatofuz
parents:
diff changeset
1687 that time we did not know about the error, the error happened later. Since the
anatofuz
parents:
diff changeset
1688 AST is immutable (most of the cases we can't remove existing nodes) we choose
anatofuz
parents:
diff changeset
1689 to mark these nodes as erroneous.
anatofuz
parents:
diff changeset
1690
anatofuz
parents:
diff changeset
1691 We cache the errors associated with declarations in the "from" context in
anatofuz
parents:
diff changeset
1692 ``ASTImporter::ImportDeclErrors`` and the ones which are associated with the
anatofuz
parents:
diff changeset
1693 "to" context in ``ASTImporterSharedState::ImportErrors``. Note that, there may
anatofuz
parents:
diff changeset
1694 be several ASTImporter objects which import into the same "to" context but from
anatofuz
parents:
diff changeset
1695 different "from" contexts; in this case, they have to share the associated
anatofuz
parents:
diff changeset
1696 errors of the "to" context.
anatofuz
parents:
diff changeset
1697
anatofuz
parents:
diff changeset
1698 When an error happens, that propagates through the call stack, through all the
anatofuz
parents:
diff changeset
1699 dependant nodes. However, in case of dependency cycles, this is not enough,
anatofuz
parents:
diff changeset
1700 because we strive to mark the erroneous nodes so clients can act upon. In those
anatofuz
parents:
diff changeset
1701 cases, we have to keep track of the errors for those nodes which are
anatofuz
parents:
diff changeset
1702 intermediate nodes of a cycle.
anatofuz
parents:
diff changeset
1703
anatofuz
parents:
diff changeset
1704 An **import path** is the list of the AST nodes which we visit during an Import
anatofuz
parents:
diff changeset
1705 call. If node ``A`` depends on node ``B`` then the path contains an ``A->B``
anatofuz
parents:
diff changeset
1706 edge. From the call stack of the import functions, we can read the very same
anatofuz
parents:
diff changeset
1707 path.
anatofuz
parents:
diff changeset
1708
anatofuz
parents:
diff changeset
1709 Now imagine the following AST, where the ``->`` represents dependency in terms
anatofuz
parents:
diff changeset
1710 of the import (all nodes are declarations).
anatofuz
parents:
diff changeset
1711
anatofuz
parents:
diff changeset
1712 .. code-block:: text
anatofuz
parents:
diff changeset
1713
anatofuz
parents:
diff changeset
1714 A->B->C->D
anatofuz
parents:
diff changeset
1715 `->E
anatofuz
parents:
diff changeset
1716
anatofuz
parents:
diff changeset
1717 We would like to import A.
anatofuz
parents:
diff changeset
1718 The import behaves like a DFS, so we will visit the nodes in this order: ABCDE.
anatofuz
parents:
diff changeset
1719 During the visitation we will have the following import paths:
anatofuz
parents:
diff changeset
1720
anatofuz
parents:
diff changeset
1721 .. code-block:: text
anatofuz
parents:
diff changeset
1722
anatofuz
parents:
diff changeset
1723 A
anatofuz
parents:
diff changeset
1724 AB
anatofuz
parents:
diff changeset
1725 ABC
anatofuz
parents:
diff changeset
1726 ABCD
anatofuz
parents:
diff changeset
1727 ABC
anatofuz
parents:
diff changeset
1728 AB
anatofuz
parents:
diff changeset
1729 ABE
anatofuz
parents:
diff changeset
1730 AB
anatofuz
parents:
diff changeset
1731 A
anatofuz
parents:
diff changeset
1732
anatofuz
parents:
diff changeset
1733 If during the visit of E there is an error then we set an error for E, then as
anatofuz
parents:
diff changeset
1734 the call stack shrinks for B, then for A:
anatofuz
parents:
diff changeset
1735
anatofuz
parents:
diff changeset
1736 .. code-block:: text
anatofuz
parents:
diff changeset
1737
anatofuz
parents:
diff changeset
1738 A
anatofuz
parents:
diff changeset
1739 AB
anatofuz
parents:
diff changeset
1740 ABC
anatofuz
parents:
diff changeset
1741 ABCD
anatofuz
parents:
diff changeset
1742 ABC
anatofuz
parents:
diff changeset
1743 AB
anatofuz
parents:
diff changeset
1744 ABE // Error! Set an error to E
anatofuz
parents:
diff changeset
1745 AB // Set an error to B
anatofuz
parents:
diff changeset
1746 A // Set an error to A
anatofuz
parents:
diff changeset
1747
anatofuz
parents:
diff changeset
1748 However, during the import we could import C and D without any error and they
anatofuz
parents:
diff changeset
1749 are independent of A,B and E. We must not set up an error for C and D. So, at
anatofuz
parents:
diff changeset
1750 the end of the import we have an entry in ``ImportDeclErrors`` for A,B,E but
anatofuz
parents:
diff changeset
1751 not for C,D.
anatofuz
parents:
diff changeset
1752
anatofuz
parents:
diff changeset
1753 Now, what happens if there is a cycle in the import path? Let's consider this
anatofuz
parents:
diff changeset
1754 AST:
anatofuz
parents:
diff changeset
1755
anatofuz
parents:
diff changeset
1756 .. code-block:: text
anatofuz
parents:
diff changeset
1757
anatofuz
parents:
diff changeset
1758 A->B->C->A
anatofuz
parents:
diff changeset
1759 `->E
anatofuz
parents:
diff changeset
1760
anatofuz
parents:
diff changeset
1761 During the visitation, we will have the below import paths and if during the
anatofuz
parents:
diff changeset
1762 visit of E there is an error then we will set up an error for E,B,A. But what's
anatofuz
parents:
diff changeset
1763 up with C?
anatofuz
parents:
diff changeset
1764
anatofuz
parents:
diff changeset
1765 .. code-block:: text
anatofuz
parents:
diff changeset
1766
anatofuz
parents:
diff changeset
1767 A
anatofuz
parents:
diff changeset
1768 AB
anatofuz
parents:
diff changeset
1769 ABC
anatofuz
parents:
diff changeset
1770 ABCA
anatofuz
parents:
diff changeset
1771 ABC
anatofuz
parents:
diff changeset
1772 AB
anatofuz
parents:
diff changeset
1773 ABE // Error! Set an error to E
anatofuz
parents:
diff changeset
1774 AB // Set an error to B
anatofuz
parents:
diff changeset
1775 A // Set an error to A
anatofuz
parents:
diff changeset
1776
anatofuz
parents:
diff changeset
1777 This time we know that both B and C are dependent on A. This means we must set
anatofuz
parents:
diff changeset
1778 up an error for C too. As the call stack reverses back we get to A and we must
anatofuz
parents:
diff changeset
1779 set up an error to all nodes which depend on A (this includes C). But C is no
anatofuz
parents:
diff changeset
1780 longer on the import path, it just had been previously. Such a situation can
anatofuz
parents:
diff changeset
1781 happen only if during the visitation we had a cycle. If we didn't have any
anatofuz
parents:
diff changeset
1782 cycle, then the normal way of passing an Error object through the call stack
anatofuz
parents:
diff changeset
1783 could handle the situation. This is why we must track cycles during the import
anatofuz
parents:
diff changeset
1784 process for each visited declaration.
anatofuz
parents:
diff changeset
1785
anatofuz
parents:
diff changeset
1786 Lookup Problems
anatofuz
parents:
diff changeset
1787 ^^^^^^^^^^^^^^^
anatofuz
parents:
diff changeset
1788
anatofuz
parents:
diff changeset
1789 When we import a declaration from the source context then we check whether we
anatofuz
parents:
diff changeset
1790 already have a structurally equivalent node with the same name in the "to"
anatofuz
parents:
diff changeset
1791 context. If the "from" node is a definition and the found one is also a
anatofuz
parents:
diff changeset
1792 definition, then we do not create a new node, instead, we mark the found node
anatofuz
parents:
diff changeset
1793 as the imported node. If the found definition and the one we want to import
anatofuz
parents:
diff changeset
1794 have the same name but they are structurally in-equivalent, then we have an ODR
anatofuz
parents:
diff changeset
1795 violation in case of C++. If the "from" node is not a definition then we add
anatofuz
parents:
diff changeset
1796 that to the redeclaration chain of the found node. This behaviour is essential
anatofuz
parents:
diff changeset
1797 when we merge ASTs from different translation units which include the same
anatofuz
parents:
diff changeset
1798 header file(s). For example, we want to have only one definition for the class
anatofuz
parents:
diff changeset
1799 template ``std::vector``, even if we included ``<vector>`` in several
anatofuz
parents:
diff changeset
1800 translation units.
anatofuz
parents:
diff changeset
1801
anatofuz
parents:
diff changeset
1802 To find a structurally equivalent node we can use the regular C/C++ lookup
anatofuz
parents:
diff changeset
1803 functions: ``DeclContext::noload_lookup()`` and
anatofuz
parents:
diff changeset
1804 ``DeclContext::localUncachedLookup()``. These functions do respect the C/C++
anatofuz
parents:
diff changeset
1805 name hiding rules, thus you cannot find certain declarations in a given
anatofuz
parents:
diff changeset
1806 declaration context. For instance, unnamed declarations (anonymous structs),
anatofuz
parents:
diff changeset
1807 non-first ``friend`` declarations and template specializations are hidden. This
anatofuz
parents:
diff changeset
1808 is a problem, because if we use the regular C/C++ lookup then we create
anatofuz
parents:
diff changeset
1809 redundant AST nodes during the merge! Also, having two instances of the same
anatofuz
parents:
diff changeset
1810 node could result in false :ref:`structural in-equivalencies <structural-eq>`
anatofuz
parents:
diff changeset
1811 of other nodes which depend on the duplicated node. Because of these reasons,
anatofuz
parents:
diff changeset
1812 we created a lookup class which has the sole purpose to register all
anatofuz
parents:
diff changeset
1813 declarations, so later they can be looked up by subsequent import requests.
anatofuz
parents:
diff changeset
1814 This is the ``ASTImporterLookupTable`` class. This lookup table should be
anatofuz
parents:
diff changeset
1815 shared amongst the different ``ASTImporter`` instances if they happen to import
anatofuz
parents:
diff changeset
1816 to the very same "to" context. This is why we can use the importer specific
anatofuz
parents:
diff changeset
1817 lookup only via the ``ASTImporterSharedState`` class.
anatofuz
parents:
diff changeset
1818
anatofuz
parents:
diff changeset
1819 ExternalASTSource
anatofuz
parents:
diff changeset
1820 ~~~~~~~~~~~~~~~~~
anatofuz
parents:
diff changeset
1821
anatofuz
parents:
diff changeset
1822 The ``ExternalASTSource`` is an abstract interface associated with the
anatofuz
parents:
diff changeset
1823 ``ASTContext`` class. It provides the ability to read the declarations stored
anatofuz
parents:
diff changeset
1824 within a declaration context either for iteration or for name lookup. A
anatofuz
parents:
diff changeset
1825 declaration context with an external AST source may load its declarations
anatofuz
parents:
diff changeset
1826 on-demand. This means that the list of declarations (represented as a linked
anatofuz
parents:
diff changeset
1827 list, the head is ``DeclContext::FirstDecl``) could be empty. However, member
anatofuz
parents:
diff changeset
1828 functions like ``DeclContext::lookup()`` may initiate a load.
anatofuz
parents:
diff changeset
1829
anatofuz
parents:
diff changeset
1830 Usually, external sources are associated with precompiled headers. For example,
anatofuz
parents:
diff changeset
1831 when we load a class from a PCH then the members are loaded only if we do want
anatofuz
parents:
diff changeset
1832 to look up something in the class' context.
anatofuz
parents:
diff changeset
1833
anatofuz
parents:
diff changeset
1834 In case of LLDB, an implementation of the ``ExternalASTSource`` interface is
anatofuz
parents:
diff changeset
1835 attached to the AST context which is related to the parsed expression. This
anatofuz
parents:
diff changeset
1836 implementation of the ``ExternalASTSource`` interface is realized with the help
anatofuz
parents:
diff changeset
1837 of the ``ASTImporter`` class. This way, LLDB can reuse Clang's parsing
anatofuz
parents:
diff changeset
1838 machinery while synthesizing the underlying AST from the debug data (e.g. from
anatofuz
parents:
diff changeset
1839 DWARF). From the view of the ``ASTImporter`` this means both the "to" and the
anatofuz
parents:
diff changeset
1840 "from" context may have declaration contexts with external lexical storage. If
anatofuz
parents:
diff changeset
1841 a ``DeclContext`` in the "to" AST context has external lexical storage then we
anatofuz
parents:
diff changeset
1842 must take extra attention to work only with the already loaded declarations!
anatofuz
parents:
diff changeset
1843 Otherwise, we would end up with an uncontrolled import process. For instance,
anatofuz
parents:
diff changeset
1844 if we used the regular ``DeclContext::lookup()`` to find the existing
anatofuz
parents:
diff changeset
1845 declarations in the "to" context then the ``lookup()`` call itself would
anatofuz
parents:
diff changeset
1846 initiate a new import while we are in the middle of importing a declaration!
anatofuz
parents:
diff changeset
1847 (By the time we initiate the lookup we haven't registered yet that we already
anatofuz
parents:
diff changeset
1848 started to import the node of the "from" context.) This is why we use
anatofuz
parents:
diff changeset
1849 ``DeclContext::noload_lookup()`` instead.
anatofuz
parents:
diff changeset
1850
anatofuz
parents:
diff changeset
1851 Class Template Instantiations
anatofuz
parents:
diff changeset
1852 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
anatofuz
parents:
diff changeset
1853
anatofuz
parents:
diff changeset
1854 Different translation units may have class template instantiations with the
anatofuz
parents:
diff changeset
1855 same template arguments, but with a different set of instantiated
anatofuz
parents:
diff changeset
1856 ``MethodDecls`` and ``FieldDecls``. Consider the following files:
anatofuz
parents:
diff changeset
1857
anatofuz
parents:
diff changeset
1858 .. code-block:: c++
anatofuz
parents:
diff changeset
1859
anatofuz
parents:
diff changeset
1860 // x.h
anatofuz
parents:
diff changeset
1861 template <typename T>
anatofuz
parents:
diff changeset
1862 struct X {
anatofuz
parents:
diff changeset
1863 int a{0}; // FieldDecl with InitListExpr
anatofuz
parents:
diff changeset
1864 X(char) : a(3) {} // (1)
anatofuz
parents:
diff changeset
1865 X(int) {} // (2)
anatofuz
parents:
diff changeset
1866 };
anatofuz
parents:
diff changeset
1867
anatofuz
parents:
diff changeset
1868 // foo.cpp
anatofuz
parents:
diff changeset
1869 void foo() {
anatofuz
parents:
diff changeset
1870 // ClassTemplateSpec with ctor (1): FieldDecl without InitlistExpr
anatofuz
parents:
diff changeset
1871 X<char> xc('c');
anatofuz
parents:
diff changeset
1872 }
anatofuz
parents:
diff changeset
1873
anatofuz
parents:
diff changeset
1874 // bar.cpp
anatofuz
parents:
diff changeset
1875 void bar() {
anatofuz
parents:
diff changeset
1876 // ClassTemplateSpec with ctor (2): FieldDecl WITH InitlistExpr
anatofuz
parents:
diff changeset
1877 X<char> xc(1);
anatofuz
parents:
diff changeset
1878 }
anatofuz
parents:
diff changeset
1879
anatofuz
parents:
diff changeset
1880 In ``foo.cpp`` we use the constructor with number ``(1)``, which explicitly
anatofuz
parents:
diff changeset
1881 initializes the member ``a`` to ``3``, thus the ``InitListExpr`` ``{0}`` is not
anatofuz
parents:
diff changeset
1882 used here and the AST node is not instantiated. However, in the case of
anatofuz
parents:
diff changeset
1883 ``bar.cpp`` we use the constructor with number ``(2)``, which does not
anatofuz
parents:
diff changeset
1884 explicitly initialize the ``a`` member, so the default ``InitListExpr`` is
anatofuz
parents:
diff changeset
1885 needed and thus instantiated. When we merge the AST of ``foo.cpp`` and
anatofuz
parents:
diff changeset
1886 ``bar.cpp`` we must create an AST node for the class template instantiation of
anatofuz
parents:
diff changeset
1887 ``X<char>`` which has all the required nodes. Therefore, when we find an
anatofuz
parents:
diff changeset
1888 existing ``ClassTemplateSpecializationDecl`` then we merge the fields of the
anatofuz
parents:
diff changeset
1889 ``ClassTemplateSpecializationDecl`` in the "from" context in a way that the
anatofuz
parents:
diff changeset
1890 ``InitListExpr`` is copied if not existent yet. The same merge mechanism should
anatofuz
parents:
diff changeset
1891 be done in the cases of instantiated default arguments and exception
anatofuz
parents:
diff changeset
1892 specifications of functions.
anatofuz
parents:
diff changeset
1893
anatofuz
parents:
diff changeset
1894 .. _visibility:
anatofuz
parents:
diff changeset
1895
anatofuz
parents:
diff changeset
1896 Visibility of Declarations
anatofuz
parents:
diff changeset
1897 ^^^^^^^^^^^^^^^^^^^^^^^^^^
anatofuz
parents:
diff changeset
1898
anatofuz
parents:
diff changeset
1899 During import of a global variable with external visibility, the lookup will
anatofuz
parents:
diff changeset
1900 find variables (with the same name) but with static visibility (linkage).
anatofuz
parents:
diff changeset
1901 Clearly, we cannot put them into the same redeclaration chain. The same is true
anatofuz
parents:
diff changeset
1902 the in case of functions. Also, we have to take care of other kinds of
anatofuz
parents:
diff changeset
1903 declarations like enums, classes, etc. if they are in anonymous namespaces.
anatofuz
parents:
diff changeset
1904 Therefore, we filter the lookup results and consider only those which have the
anatofuz
parents:
diff changeset
1905 same visibility as the declaration we currently import.
anatofuz
parents:
diff changeset
1906
anatofuz
parents:
diff changeset
1907 We consider two declarations in two anonymous namespaces to have the same
anatofuz
parents:
diff changeset
1908 visibility only if they are imported from the same AST context.
anatofuz
parents:
diff changeset
1909
anatofuz
parents:
diff changeset
1910 Strategies to Handle Conflicting Names
anatofuz
parents:
diff changeset
1911 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
anatofuz
parents:
diff changeset
1912
anatofuz
parents:
diff changeset
1913 During the import we lookup existing declarations with the same name. We filter
anatofuz
parents:
diff changeset
1914 the lookup results based on their :ref:`visibility <visibility>`. If any of the
anatofuz
parents:
diff changeset
1915 found declarations are not structurally equivalent then we bumped to a name
anatofuz
parents:
diff changeset
1916 conflict error (ODR violation in C++). In this case, we return with an
anatofuz
parents:
diff changeset
1917 ``Error`` and we set up the ``Error`` object for the declaration. However, some
anatofuz
parents:
diff changeset
1918 clients of the ``ASTImporter`` may require a different, perhaps less
anatofuz
parents:
diff changeset
1919 conservative and more liberal error handling strategy.
anatofuz
parents:
diff changeset
1920
anatofuz
parents:
diff changeset
1921 E.g. static analysis clients may benefit if the node is created even if there
anatofuz
parents:
diff changeset
1922 is a name conflict. During the CTU analysis of certain projects, we recognized
anatofuz
parents:
diff changeset
1923 that there are global declarations which collide with declarations from other
anatofuz
parents:
diff changeset
1924 translation units, but they are not referenced outside from their translation
anatofuz
parents:
diff changeset
1925 unit. These declarations should be in an unnamed namespace ideally. If we treat
anatofuz
parents:
diff changeset
1926 these collisions liberally then CTU analysis can find more results. Note, the
anatofuz
parents:
diff changeset
1927 feature be able to choose between name conflict handling strategies is still an
anatofuz
parents:
diff changeset
1928 ongoing work.
anatofuz
parents:
diff changeset
1929
anatofuz
parents:
diff changeset
1930 .. _CFG:
anatofuz
parents:
diff changeset
1931
anatofuz
parents:
diff changeset
1932 The ``CFG`` class
anatofuz
parents:
diff changeset
1933 -----------------
anatofuz
parents:
diff changeset
1934
anatofuz
parents:
diff changeset
1935 The ``CFG`` class is designed to represent a source-level control-flow graph
anatofuz
parents:
diff changeset
1936 for a single statement (``Stmt*``). Typically instances of ``CFG`` are
anatofuz
parents:
diff changeset
1937 constructed for function bodies (usually an instance of ``CompoundStmt``), but
anatofuz
parents:
diff changeset
1938 can also be instantiated to represent the control-flow of any class that
anatofuz
parents:
diff changeset
1939 subclasses ``Stmt``, which includes simple expressions. Control-flow graphs
anatofuz
parents:
diff changeset
1940 are especially useful for performing `flow- or path-sensitive
anatofuz
parents:
diff changeset
1941 <https://en.wikipedia.org/wiki/Data_flow_analysis#Sensitivities>`_ program
anatofuz
parents:
diff changeset
1942 analyses on a given function.
anatofuz
parents:
diff changeset
1943
anatofuz
parents:
diff changeset
1944 Basic Blocks
anatofuz
parents:
diff changeset
1945 ^^^^^^^^^^^^
anatofuz
parents:
diff changeset
1946
anatofuz
parents:
diff changeset
1947 Concretely, an instance of ``CFG`` is a collection of basic blocks. Each basic
anatofuz
parents:
diff changeset
1948 block is an instance of ``CFGBlock``, which simply contains an ordered sequence
anatofuz
parents:
diff changeset
1949 of ``Stmt*`` (each referring to statements in the AST). The ordering of
anatofuz
parents:
diff changeset
1950 statements within a block indicates unconditional flow of control from one
anatofuz
parents:
diff changeset
1951 statement to the next. :ref:`Conditional control-flow
anatofuz
parents:
diff changeset
1952 <ConditionalControlFlow>` is represented using edges between basic blocks. The
anatofuz
parents:
diff changeset
1953 statements within a given ``CFGBlock`` can be traversed using the
anatofuz
parents:
diff changeset
1954 ``CFGBlock::*iterator`` interface.
anatofuz
parents:
diff changeset
1955
anatofuz
parents:
diff changeset
1956 A ``CFG`` object owns the instances of ``CFGBlock`` within the control-flow
anatofuz
parents:
diff changeset
1957 graph it represents. Each ``CFGBlock`` within a CFG is also uniquely numbered
anatofuz
parents:
diff changeset
1958 (accessible via ``CFGBlock::getBlockID()``). Currently the number is based on
anatofuz
parents:
diff changeset
1959 the ordering the blocks were created, but no assumptions should be made on how
anatofuz
parents:
diff changeset
1960 ``CFGBlocks`` are numbered other than their numbers are unique and that they
anatofuz
parents:
diff changeset
1961 are numbered from 0..N-1 (where N is the number of basic blocks in the CFG).
anatofuz
parents:
diff changeset
1962
anatofuz
parents:
diff changeset
1963 Entry and Exit Blocks
anatofuz
parents:
diff changeset
1964 ^^^^^^^^^^^^^^^^^^^^^
anatofuz
parents:
diff changeset
1965
anatofuz
parents:
diff changeset
1966 Each instance of ``CFG`` contains two special blocks: an *entry* block
anatofuz
parents:
diff changeset
1967 (accessible via ``CFG::getEntry()``), which has no incoming edges, and an
anatofuz
parents:
diff changeset
1968 *exit* block (accessible via ``CFG::getExit()``), which has no outgoing edges.
anatofuz
parents:
diff changeset
1969 Neither block contains any statements, and they serve the role of providing a
anatofuz
parents:
diff changeset
1970 clear entrance and exit for a body of code such as a function body. The
anatofuz
parents:
diff changeset
1971 presence of these empty blocks greatly simplifies the implementation of many
anatofuz
parents:
diff changeset
1972 analyses built on top of CFGs.
anatofuz
parents:
diff changeset
1973
anatofuz
parents:
diff changeset
1974 .. _ConditionalControlFlow:
anatofuz
parents:
diff changeset
1975
anatofuz
parents:
diff changeset
1976 Conditional Control-Flow
anatofuz
parents:
diff changeset
1977 ^^^^^^^^^^^^^^^^^^^^^^^^
anatofuz
parents:
diff changeset
1978
anatofuz
parents:
diff changeset
1979 Conditional control-flow (such as those induced by if-statements and loops) is
anatofuz
parents:
diff changeset
1980 represented as edges between ``CFGBlocks``. Because different C language
anatofuz
parents:
diff changeset
1981 constructs can induce control-flow, each ``CFGBlock`` also records an extra
anatofuz
parents:
diff changeset
1982 ``Stmt*`` that represents the *terminator* of the block. A terminator is
anatofuz
parents:
diff changeset
1983 simply the statement that caused the control-flow, and is used to identify the
anatofuz
parents:
diff changeset
1984 nature of the conditional control-flow between blocks. For example, in the
anatofuz
parents:
diff changeset
1985 case of an if-statement, the terminator refers to the ``IfStmt`` object in the
anatofuz
parents:
diff changeset
1986 AST that represented the given branch.
anatofuz
parents:
diff changeset
1987
anatofuz
parents:
diff changeset
1988 To illustrate, consider the following code example:
anatofuz
parents:
diff changeset
1989
anatofuz
parents:
diff changeset
1990 .. code-block:: c++
anatofuz
parents:
diff changeset
1991
anatofuz
parents:
diff changeset
1992 int foo(int x) {
anatofuz
parents:
diff changeset
1993 x = x + 1;
anatofuz
parents:
diff changeset
1994 if (x > 2)
anatofuz
parents:
diff changeset
1995 x++;
anatofuz
parents:
diff changeset
1996 else {
anatofuz
parents:
diff changeset
1997 x += 2;
anatofuz
parents:
diff changeset
1998 x *= 2;
anatofuz
parents:
diff changeset
1999 }
anatofuz
parents:
diff changeset
2000
anatofuz
parents:
diff changeset
2001 return x;
anatofuz
parents:
diff changeset
2002 }
anatofuz
parents:
diff changeset
2003
anatofuz
parents:
diff changeset
2004 After invoking the parser+semantic analyzer on this code fragment, the AST of
anatofuz
parents:
diff changeset
2005 the body of ``foo`` is referenced by a single ``Stmt*``. We can then construct
anatofuz
parents:
diff changeset
2006 an instance of ``CFG`` representing the control-flow graph of this function
anatofuz
parents:
diff changeset
2007 body by single call to a static class method:
anatofuz
parents:
diff changeset
2008
anatofuz
parents:
diff changeset
2009 .. code-block:: c++
anatofuz
parents:
diff changeset
2010
anatofuz
parents:
diff changeset
2011 Stmt *FooBody = ...
anatofuz
parents:
diff changeset
2012 std::unique_ptr<CFG> FooCFG = CFG::buildCFG(FooBody);
anatofuz
parents:
diff changeset
2013
anatofuz
parents:
diff changeset
2014 Along with providing an interface to iterate over its ``CFGBlocks``, the
anatofuz
parents:
diff changeset
2015 ``CFG`` class also provides methods that are useful for debugging and
anatofuz
parents:
diff changeset
2016 visualizing CFGs. For example, the method ``CFG::dump()`` dumps a
anatofuz
parents:
diff changeset
2017 pretty-printed version of the CFG to standard error. This is especially useful
anatofuz
parents:
diff changeset
2018 when one is using a debugger such as gdb. For example, here is the output of
anatofuz
parents:
diff changeset
2019 ``FooCFG->dump()``:
anatofuz
parents:
diff changeset
2020
anatofuz
parents:
diff changeset
2021 .. code-block:: text
anatofuz
parents:
diff changeset
2022
anatofuz
parents:
diff changeset
2023 [ B5 (ENTRY) ]
anatofuz
parents:
diff changeset
2024 Predecessors (0):
anatofuz
parents:
diff changeset
2025 Successors (1): B4
anatofuz
parents:
diff changeset
2026
anatofuz
parents:
diff changeset
2027 [ B4 ]
anatofuz
parents:
diff changeset
2028 1: x = x + 1
anatofuz
parents:
diff changeset
2029 2: (x > 2)
anatofuz
parents:
diff changeset
2030 T: if [B4.2]
anatofuz
parents:
diff changeset
2031 Predecessors (1): B5
anatofuz
parents:
diff changeset
2032 Successors (2): B3 B2
anatofuz
parents:
diff changeset
2033
anatofuz
parents:
diff changeset
2034 [ B3 ]
anatofuz
parents:
diff changeset
2035 1: x++
anatofuz
parents:
diff changeset
2036 Predecessors (1): B4
anatofuz
parents:
diff changeset
2037 Successors (1): B1
anatofuz
parents:
diff changeset
2038
anatofuz
parents:
diff changeset
2039 [ B2 ]
anatofuz
parents:
diff changeset
2040 1: x += 2
anatofuz
parents:
diff changeset
2041 2: x *= 2
anatofuz
parents:
diff changeset
2042 Predecessors (1): B4
anatofuz
parents:
diff changeset
2043 Successors (1): B1
anatofuz
parents:
diff changeset
2044
anatofuz
parents:
diff changeset
2045 [ B1 ]
anatofuz
parents:
diff changeset
2046 1: return x;
anatofuz
parents:
diff changeset
2047 Predecessors (2): B2 B3
anatofuz
parents:
diff changeset
2048 Successors (1): B0
anatofuz
parents:
diff changeset
2049
anatofuz
parents:
diff changeset
2050 [ B0 (EXIT) ]
anatofuz
parents:
diff changeset
2051 Predecessors (1): B1
anatofuz
parents:
diff changeset
2052 Successors (0):
anatofuz
parents:
diff changeset
2053
anatofuz
parents:
diff changeset
2054 For each block, the pretty-printed output displays for each block the number of
anatofuz
parents:
diff changeset
2055 *predecessor* blocks (blocks that have outgoing control-flow to the given
anatofuz
parents:
diff changeset
2056 block) and *successor* blocks (blocks that have control-flow that have incoming
anatofuz
parents:
diff changeset
2057 control-flow from the given block). We can also clearly see the special entry
anatofuz
parents:
diff changeset
2058 and exit blocks at the beginning and end of the pretty-printed output. For the
anatofuz
parents:
diff changeset
2059 entry block (block B5), the number of predecessor blocks is 0, while for the
anatofuz
parents:
diff changeset
2060 exit block (block B0) the number of successor blocks is 0.
anatofuz
parents:
diff changeset
2061
anatofuz
parents:
diff changeset
2062 The most interesting block here is B4, whose outgoing control-flow represents
anatofuz
parents:
diff changeset
2063 the branching caused by the sole if-statement in ``foo``. Of particular
anatofuz
parents:
diff changeset
2064 interest is the second statement in the block, ``(x > 2)``, and the terminator,
anatofuz
parents:
diff changeset
2065 printed as ``if [B4.2]``. The second statement represents the evaluation of
anatofuz
parents:
diff changeset
2066 the condition of the if-statement, which occurs before the actual branching of
anatofuz
parents:
diff changeset
2067 control-flow. Within the ``CFGBlock`` for B4, the ``Stmt*`` for the second
anatofuz
parents:
diff changeset
2068 statement refers to the actual expression in the AST for ``(x > 2)``. Thus
anatofuz
parents:
diff changeset
2069 pointers to subclasses of ``Expr`` can appear in the list of statements in a
anatofuz
parents:
diff changeset
2070 block, and not just subclasses of ``Stmt`` that refer to proper C statements.
anatofuz
parents:
diff changeset
2071
anatofuz
parents:
diff changeset
2072 The terminator of block B4 is a pointer to the ``IfStmt`` object in the AST.
anatofuz
parents:
diff changeset
2073 The pretty-printer outputs ``if [B4.2]`` because the condition expression of
anatofuz
parents:
diff changeset
2074 the if-statement has an actual place in the basic block, and thus the
anatofuz
parents:
diff changeset
2075 terminator is essentially *referring* to the expression that is the second
anatofuz
parents:
diff changeset
2076 statement of block B4 (i.e., B4.2). In this manner, conditions for
anatofuz
parents:
diff changeset
2077 control-flow (which also includes conditions for loops and switch statements)
anatofuz
parents:
diff changeset
2078 are hoisted into the actual basic block.
anatofuz
parents:
diff changeset
2079
anatofuz
parents:
diff changeset
2080 .. Implicit Control-Flow
anatofuz
parents:
diff changeset
2081 .. ^^^^^^^^^^^^^^^^^^^^^
anatofuz
parents:
diff changeset
2082
anatofuz
parents:
diff changeset
2083 .. A key design principle of the ``CFG`` class was to not require any
anatofuz
parents:
diff changeset
2084 .. transformations to the AST in order to represent control-flow. Thus the
anatofuz
parents:
diff changeset
2085 .. ``CFG`` does not perform any "lowering" of the statements in an AST: loops
anatofuz
parents:
diff changeset
2086 .. are not transformed into guarded gotos, short-circuit operations are not
anatofuz
parents:
diff changeset
2087 .. converted to a set of if-statements, and so on.
anatofuz
parents:
diff changeset
2088
anatofuz
parents:
diff changeset
2089 Constant Folding in the Clang AST
anatofuz
parents:
diff changeset
2090 ---------------------------------
anatofuz
parents:
diff changeset
2091
anatofuz
parents:
diff changeset
2092 There are several places where constants and constant folding matter a lot to
anatofuz
parents:
diff changeset
2093 the Clang front-end. First, in general, we prefer the AST to retain the source
anatofuz
parents:
diff changeset
2094 code as close to how the user wrote it as possible. This means that if they
anatofuz
parents:
diff changeset
2095 wrote "``5+4``", we want to keep the addition and two constants in the AST, we
anatofuz
parents:
diff changeset
2096 don't want to fold to "``9``". This means that constant folding in various
anatofuz
parents:
diff changeset
2097 ways turns into a tree walk that needs to handle the various cases.
anatofuz
parents:
diff changeset
2098
anatofuz
parents:
diff changeset
2099 However, there are places in both C and C++ that require constants to be
anatofuz
parents:
diff changeset
2100 folded. For example, the C standard defines what an "integer constant
anatofuz
parents:
diff changeset
2101 expression" (i-c-e) is with very precise and specific requirements. The
anatofuz
parents:
diff changeset
2102 language then requires i-c-e's in a lot of places (for example, the size of a
anatofuz
parents:
diff changeset
2103 bitfield, the value for a case statement, etc). For these, we have to be able
anatofuz
parents:
diff changeset
2104 to constant fold the constants, to do semantic checks (e.g., verify bitfield
anatofuz
parents:
diff changeset
2105 size is non-negative and that case statements aren't duplicated). We aim for
anatofuz
parents:
diff changeset
2106 Clang to be very pedantic about this, diagnosing cases when the code does not
anatofuz
parents:
diff changeset
2107 use an i-c-e where one is required, but accepting the code unless running with
anatofuz
parents:
diff changeset
2108 ``-pedantic-errors``.
anatofuz
parents:
diff changeset
2109
anatofuz
parents:
diff changeset
2110 Things get a little bit more tricky when it comes to compatibility with
anatofuz
parents:
diff changeset
2111 real-world source code. Specifically, GCC has historically accepted a huge
anatofuz
parents:
diff changeset
2112 superset of expressions as i-c-e's, and a lot of real world code depends on
anatofuz
parents:
diff changeset
2113 this unfortunate accident of history (including, e.g., the glibc system
anatofuz
parents:
diff changeset
2114 headers). GCC accepts anything its "fold" optimizer is capable of reducing to
anatofuz
parents:
diff changeset
2115 an integer constant, which means that the definition of what it accepts changes
anatofuz
parents:
diff changeset
2116 as its optimizer does. One example is that GCC accepts things like "``case
anatofuz
parents:
diff changeset
2117 X-X:``" even when ``X`` is a variable, because it can fold this to 0.
anatofuz
parents:
diff changeset
2118
anatofuz
parents:
diff changeset
2119 Another issue are how constants interact with the extensions we support, such
anatofuz
parents:
diff changeset
2120 as ``__builtin_constant_p``, ``__builtin_inf``, ``__extension__`` and many
anatofuz
parents:
diff changeset
2121 others. C99 obviously does not specify the semantics of any of these
anatofuz
parents:
diff changeset
2122 extensions, and the definition of i-c-e does not include them. However, these
anatofuz
parents:
diff changeset
2123 extensions are often used in real code, and we have to have a way to reason
anatofuz
parents:
diff changeset
2124 about them.
anatofuz
parents:
diff changeset
2125
anatofuz
parents:
diff changeset
2126 Finally, this is not just a problem for semantic analysis. The code generator
anatofuz
parents:
diff changeset
2127 and other clients have to be able to fold constants (e.g., to initialize global
anatofuz
parents:
diff changeset
2128 variables) and have to handle a superset of what C99 allows. Further, these
anatofuz
parents:
diff changeset
2129 clients can benefit from extended information. For example, we know that
anatofuz
parents:
diff changeset
2130 "``foo() || 1``" always evaluates to ``true``, but we can't replace the
anatofuz
parents:
diff changeset
2131 expression with ``true`` because it has side effects.
anatofuz
parents:
diff changeset
2132
anatofuz
parents:
diff changeset
2133 Implementation Approach
anatofuz
parents:
diff changeset
2134 ^^^^^^^^^^^^^^^^^^^^^^^
anatofuz
parents:
diff changeset
2135
anatofuz
parents:
diff changeset
2136 After trying several different approaches, we've finally converged on a design
anatofuz
parents:
diff changeset
2137 (Note, at the time of this writing, not all of this has been implemented,
anatofuz
parents:
diff changeset
2138 consider this a design goal!). Our basic approach is to define a single
anatofuz
parents:
diff changeset
2139 recursive evaluation method (``Expr::Evaluate``), which is implemented
anatofuz
parents:
diff changeset
2140 in ``AST/ExprConstant.cpp``. Given an expression with "scalar" type (integer,
anatofuz
parents:
diff changeset
2141 fp, complex, or pointer) this method returns the following information:
anatofuz
parents:
diff changeset
2142
anatofuz
parents:
diff changeset
2143 * Whether the expression is an integer constant expression, a general constant
anatofuz
parents:
diff changeset
2144 that was folded but has no side effects, a general constant that was folded
anatofuz
parents:
diff changeset
2145 but that does have side effects, or an uncomputable/unfoldable value.
anatofuz
parents:
diff changeset
2146 * If the expression was computable in any way, this method returns the
anatofuz
parents:
diff changeset
2147 ``APValue`` for the result of the expression.
anatofuz
parents:
diff changeset
2148 * If the expression is not evaluatable at all, this method returns information
anatofuz
parents:
diff changeset
2149 on one of the problems with the expression. This includes a
anatofuz
parents:
diff changeset
2150 ``SourceLocation`` for where the problem is, and a diagnostic ID that explains
anatofuz
parents:
diff changeset
2151 the problem. The diagnostic should have ``ERROR`` type.
anatofuz
parents:
diff changeset
2152 * If the expression is not an integer constant expression, this method returns
anatofuz
parents:
diff changeset
2153 information on one of the problems with the expression. This includes a
anatofuz
parents:
diff changeset
2154 ``SourceLocation`` for where the problem is, and a diagnostic ID that
anatofuz
parents:
diff changeset
2155 explains the problem. The diagnostic should have ``EXTENSION`` type.
anatofuz
parents:
diff changeset
2156
anatofuz
parents:
diff changeset
2157 This information gives various clients the flexibility that they want, and we
anatofuz
parents:
diff changeset
2158 will eventually have some helper methods for various extensions. For example,
anatofuz
parents:
diff changeset
2159 ``Sema`` should have a ``Sema::VerifyIntegerConstantExpression`` method, which
anatofuz
parents:
diff changeset
2160 calls ``Evaluate`` on the expression. If the expression is not foldable, the
anatofuz
parents:
diff changeset
2161 error is emitted, and it would return ``true``. If the expression is not an
anatofuz
parents:
diff changeset
2162 i-c-e, the ``EXTENSION`` diagnostic is emitted. Finally it would return
anatofuz
parents:
diff changeset
2163 ``false`` to indicate that the AST is OK.
anatofuz
parents:
diff changeset
2164
anatofuz
parents:
diff changeset
2165 Other clients can use the information in other ways, for example, codegen can
anatofuz
parents:
diff changeset
2166 just use expressions that are foldable in any way.
anatofuz
parents:
diff changeset
2167
anatofuz
parents:
diff changeset
2168 Extensions
anatofuz
parents:
diff changeset
2169 ^^^^^^^^^^
anatofuz
parents:
diff changeset
2170
anatofuz
parents:
diff changeset
2171 This section describes how some of the various extensions Clang supports
anatofuz
parents:
diff changeset
2172 interacts with constant evaluation:
anatofuz
parents:
diff changeset
2173
anatofuz
parents:
diff changeset
2174 * ``__extension__``: The expression form of this extension causes any
anatofuz
parents:
diff changeset
2175 evaluatable subexpression to be accepted as an integer constant expression.
anatofuz
parents:
diff changeset
2176 * ``__builtin_constant_p``: This returns true (as an integer constant
anatofuz
parents:
diff changeset
2177 expression) if the operand evaluates to either a numeric value (that is, not
anatofuz
parents:
diff changeset
2178 a pointer cast to integral type) of integral, enumeration, floating or
anatofuz
parents:
diff changeset
2179 complex type, or if it evaluates to the address of the first character of a
anatofuz
parents:
diff changeset
2180 string literal (possibly cast to some other type). As a special case, if
anatofuz
parents:
diff changeset
2181 ``__builtin_constant_p`` is the (potentially parenthesized) condition of a
anatofuz
parents:
diff changeset
2182 conditional operator expression ("``?:``"), only the true side of the
anatofuz
parents:
diff changeset
2183 conditional operator is considered, and it is evaluated with full constant
anatofuz
parents:
diff changeset
2184 folding.
anatofuz
parents:
diff changeset
2185 * ``__builtin_choose_expr``: The condition is required to be an integer
anatofuz
parents:
diff changeset
2186 constant expression, but we accept any constant as an "extension of an
anatofuz
parents:
diff changeset
2187 extension". This only evaluates one operand depending on which way the
anatofuz
parents:
diff changeset
2188 condition evaluates.
anatofuz
parents:
diff changeset
2189 * ``__builtin_classify_type``: This always returns an integer constant
anatofuz
parents:
diff changeset
2190 expression.
anatofuz
parents:
diff changeset
2191 * ``__builtin_inf, nan, ...``: These are treated just like a floating-point
anatofuz
parents:
diff changeset
2192 literal.
anatofuz
parents:
diff changeset
2193 * ``__builtin_abs, copysign, ...``: These are constant folded as general
anatofuz
parents:
diff changeset
2194 constant expressions.
anatofuz
parents:
diff changeset
2195 * ``__builtin_strlen`` and ``strlen``: These are constant folded as integer
anatofuz
parents:
diff changeset
2196 constant expressions if the argument is a string literal.
anatofuz
parents:
diff changeset
2197
anatofuz
parents:
diff changeset
2198 .. _Sema:
anatofuz
parents:
diff changeset
2199
anatofuz
parents:
diff changeset
2200 The Sema Library
anatofuz
parents:
diff changeset
2201 ================
anatofuz
parents:
diff changeset
2202
anatofuz
parents:
diff changeset
2203 This library is called by the :ref:`Parser library <Parser>` during parsing to
anatofuz
parents:
diff changeset
2204 do semantic analysis of the input. For valid programs, Sema builds an AST for
anatofuz
parents:
diff changeset
2205 parsed constructs.
anatofuz
parents:
diff changeset
2206
anatofuz
parents:
diff changeset
2207 .. _CodeGen:
anatofuz
parents:
diff changeset
2208
anatofuz
parents:
diff changeset
2209 The CodeGen Library
anatofuz
parents:
diff changeset
2210 ===================
anatofuz
parents:
diff changeset
2211
anatofuz
parents:
diff changeset
2212 CodeGen takes an :ref:`AST <AST>` as input and produces `LLVM IR code
anatofuz
parents:
diff changeset
2213 <//llvm.org/docs/LangRef.html>`_ from it.
anatofuz
parents:
diff changeset
2214
anatofuz
parents:
diff changeset
2215 How to change Clang
anatofuz
parents:
diff changeset
2216 ===================
anatofuz
parents:
diff changeset
2217
anatofuz
parents:
diff changeset
2218 How to add an attribute
anatofuz
parents:
diff changeset
2219 -----------------------
anatofuz
parents:
diff changeset
2220 Attributes are a form of metadata that can be attached to a program construct,
anatofuz
parents:
diff changeset
2221 allowing the programmer to pass semantic information along to the compiler for
anatofuz
parents:
diff changeset
2222 various uses. For example, attributes may be used to alter the code generation
anatofuz
parents:
diff changeset
2223 for a program construct, or to provide extra semantic information for static
anatofuz
parents:
diff changeset
2224 analysis. This document explains how to add a custom attribute to Clang.
anatofuz
parents:
diff changeset
2225 Documentation on existing attributes can be found `here
anatofuz
parents:
diff changeset
2226 <//clang.llvm.org/docs/AttributeReference.html>`_.
anatofuz
parents:
diff changeset
2227
anatofuz
parents:
diff changeset
2228 Attribute Basics
anatofuz
parents:
diff changeset
2229 ^^^^^^^^^^^^^^^^
anatofuz
parents:
diff changeset
2230 Attributes in Clang are handled in three stages: parsing into a parsed attribute
anatofuz
parents:
diff changeset
2231 representation, conversion from a parsed attribute into a semantic attribute,
anatofuz
parents:
diff changeset
2232 and then the semantic handling of the attribute.
anatofuz
parents:
diff changeset
2233
anatofuz
parents:
diff changeset
2234 Parsing of the attribute is determined by the various syntactic forms attributes
anatofuz
parents:
diff changeset
2235 can take, such as GNU, C++11, and Microsoft style attributes, as well as other
anatofuz
parents:
diff changeset
2236 information provided by the table definition of the attribute. Ultimately, the
anatofuz
parents:
diff changeset
2237 parsed representation of an attribute object is an ``ParsedAttr`` object.
anatofuz
parents:
diff changeset
2238 These parsed attributes chain together as a list of parsed attributes attached
anatofuz
parents:
diff changeset
2239 to a declarator or declaration specifier. The parsing of attributes is handled
anatofuz
parents:
diff changeset
2240 automatically by Clang, except for attributes spelled as keywords. When
anatofuz
parents:
diff changeset
2241 implementing a keyword attribute, the parsing of the keyword and creation of the
anatofuz
parents:
diff changeset
2242 ``ParsedAttr`` object must be done manually.
anatofuz
parents:
diff changeset
2243
anatofuz
parents:
diff changeset
2244 Eventually, ``Sema::ProcessDeclAttributeList()`` is called with a ``Decl`` and
anatofuz
parents:
diff changeset
2245 an ``ParsedAttr``, at which point the parsed attribute can be transformed
anatofuz
parents:
diff changeset
2246 into a semantic attribute. The process by which a parsed attribute is converted
anatofuz
parents:
diff changeset
2247 into a semantic attribute depends on the attribute definition and semantic
anatofuz
parents:
diff changeset
2248 requirements of the attribute. The end result, however, is that the semantic
anatofuz
parents:
diff changeset
2249 attribute object is attached to the ``Decl`` object, and can be obtained by a
anatofuz
parents:
diff changeset
2250 call to ``Decl::getAttr<T>()``.
anatofuz
parents:
diff changeset
2251
anatofuz
parents:
diff changeset
2252 The structure of the semantic attribute is also governed by the attribute
anatofuz
parents:
diff changeset
2253 definition given in Attr.td. This definition is used to automatically generate
anatofuz
parents:
diff changeset
2254 functionality used for the implementation of the attribute, such as a class
anatofuz
parents:
diff changeset
2255 derived from ``clang::Attr``, information for the parser to use, automated
anatofuz
parents:
diff changeset
2256 semantic checking for some attributes, etc.
anatofuz
parents:
diff changeset
2257
anatofuz
parents:
diff changeset
2258
anatofuz
parents:
diff changeset
2259 ``include/clang/Basic/Attr.td``
anatofuz
parents:
diff changeset
2260 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
anatofuz
parents:
diff changeset
2261 The first step to adding a new attribute to Clang is to add its definition to
anatofuz
parents:
diff changeset
2262 `include/clang/Basic/Attr.td
anatofuz
parents:
diff changeset
2263 <https://github.com/llvm/llvm-project/blob/master/clang/include/clang/Basic/Attr.td>`_.
anatofuz
parents:
diff changeset
2264 This tablegen definition must derive from the ``Attr`` (tablegen, not
anatofuz
parents:
diff changeset
2265 semantic) type, or one of its derivatives. Most attributes will derive from the
anatofuz
parents:
diff changeset
2266 ``InheritableAttr`` type, which specifies that the attribute can be inherited by
anatofuz
parents:
diff changeset
2267 later redeclarations of the ``Decl`` it is associated with.
anatofuz
parents:
diff changeset
2268 ``InheritableParamAttr`` is similar to ``InheritableAttr``, except that the
anatofuz
parents:
diff changeset
2269 attribute is written on a parameter instead of a declaration. If the attribute
anatofuz
parents:
diff changeset
2270 is intended to apply to a type instead of a declaration, such an attribute
anatofuz
parents:
diff changeset
2271 should derive from ``TypeAttr``, and will generally not be given an AST
anatofuz
parents:
diff changeset
2272 representation. (Note that this document does not cover the creation of type
anatofuz
parents:
diff changeset
2273 attributes.) An attribute that inherits from ``IgnoredAttr`` is parsed, but will
anatofuz
parents:
diff changeset
2274 generate an ignored attribute diagnostic when used, which may be useful when an
anatofuz
parents:
diff changeset
2275 attribute is supported by another vendor but not supported by clang.
anatofuz
parents:
diff changeset
2276
anatofuz
parents:
diff changeset
2277 The definition will specify several key pieces of information, such as the
anatofuz
parents:
diff changeset
2278 semantic name of the attribute, the spellings the attribute supports, the
anatofuz
parents:
diff changeset
2279 arguments the attribute expects, and more. Most members of the ``Attr`` tablegen
anatofuz
parents:
diff changeset
2280 type do not require definitions in the derived definition as the default
anatofuz
parents:
diff changeset
2281 suffice. However, every attribute must specify at least a spelling list, a
anatofuz
parents:
diff changeset
2282 subject list, and a documentation list.
anatofuz
parents:
diff changeset
2283
anatofuz
parents:
diff changeset
2284 Spellings
anatofuz
parents:
diff changeset
2285 ~~~~~~~~~
anatofuz
parents:
diff changeset
2286 All attributes are required to specify a spelling list that denotes the ways in
anatofuz
parents:
diff changeset
2287 which the attribute can be spelled. For instance, a single semantic attribute
anatofuz
parents:
diff changeset
2288 may have a keyword spelling, as well as a C++11 spelling and a GNU spelling. An
anatofuz
parents:
diff changeset
2289 empty spelling list is also permissible and may be useful for attributes which
anatofuz
parents:
diff changeset
2290 are created implicitly. The following spellings are accepted:
anatofuz
parents:
diff changeset
2291
anatofuz
parents:
diff changeset
2292 ============ ================================================================
anatofuz
parents:
diff changeset
2293 Spelling Description
anatofuz
parents:
diff changeset
2294 ============ ================================================================
anatofuz
parents:
diff changeset
2295 ``GNU`` Spelled with a GNU-style ``__attribute__((attr))`` syntax and
anatofuz
parents:
diff changeset
2296 placement.
anatofuz
parents:
diff changeset
2297 ``CXX11`` Spelled with a C++-style ``[[attr]]`` syntax with an optional
anatofuz
parents:
diff changeset
2298 vendor-specific namespace.
anatofuz
parents:
diff changeset
2299 ``C2x`` Spelled with a C-style ``[[attr]]` syntax with an optional
anatofuz
parents:
diff changeset
2300 vendor-specific namespace.
anatofuz
parents:
diff changeset
2301 ``Declspec`` Spelled with a Microsoft-style ``__declspec(attr)`` syntax.
anatofuz
parents:
diff changeset
2302 ``Keyword`` The attribute is spelled as a keyword, and required custom
anatofuz
parents:
diff changeset
2303 parsing.
anatofuz
parents:
diff changeset
2304 ``GCC`` Specifies two spellings: the first is a GNU-style spelling, and
anatofuz
parents:
diff changeset
2305 the second is a C++-style spelling with the ``gnu`` namespace.
anatofuz
parents:
diff changeset
2306 Attributes should only specify this spelling for attributes
anatofuz
parents:
diff changeset
2307 supported by GCC.
anatofuz
parents:
diff changeset
2308 ``Clang`` Specifies two or three spellings: the first is a GNU-style
anatofuz
parents:
diff changeset
2309 spelling, the second is a C++-style spelling with the ``clang``
anatofuz
parents:
diff changeset
2310 namespace, and the third is an optional C-style spelling with
anatofuz
parents:
diff changeset
2311 the ``clang`` namespace. By default, a C-style spelling is
anatofuz
parents:
diff changeset
2312 provided.
anatofuz
parents:
diff changeset
2313 ``Pragma`` The attribute is spelled as a ``#pragma``, and requires custom
anatofuz
parents:
diff changeset
2314 processing within the preprocessor. If the attribute is meant to
anatofuz
parents:
diff changeset
2315 be used by Clang, it should set the namespace to ``"clang"``.
anatofuz
parents:
diff changeset
2316 Note that this spelling is not used for declaration attributes.
anatofuz
parents:
diff changeset
2317 ============ ================================================================
anatofuz
parents:
diff changeset
2318
anatofuz
parents:
diff changeset
2319 Subjects
anatofuz
parents:
diff changeset
2320 ~~~~~~~~
anatofuz
parents:
diff changeset
2321 Attributes appertain to one or more ``Decl`` subjects. If the attribute attempts
anatofuz
parents:
diff changeset
2322 to attach to a subject that is not in the subject list, a diagnostic is issued
anatofuz
parents:
diff changeset
2323 automatically. Whether the diagnostic is a warning or an error depends on how
anatofuz
parents:
diff changeset
2324 the attribute's ``SubjectList`` is defined, but the default behavior is to warn.
anatofuz
parents:
diff changeset
2325 The diagnostics displayed to the user are automatically determined based on the
anatofuz
parents:
diff changeset
2326 subjects in the list, but a custom diagnostic parameter can also be specified in
anatofuz
parents:
diff changeset
2327 the ``SubjectList``. The diagnostics generated for subject list violations are
anatofuz
parents:
diff changeset
2328 either ``diag::warn_attribute_wrong_decl_type`` or
anatofuz
parents:
diff changeset
2329 ``diag::err_attribute_wrong_decl_type``, and the parameter enumeration is found
anatofuz
parents:
diff changeset
2330 in `include/clang/Sema/ParsedAttr.h
anatofuz
parents:
diff changeset
2331 <https://github.com/llvm/llvm-project/blob/master/clang/include/clang/Sema/ParsedAttr.h>`_
anatofuz
parents:
diff changeset
2332 If a previously unused Decl node is added to the ``SubjectList``, the logic used
anatofuz
parents:
diff changeset
2333 to automatically determine the diagnostic parameter in `utils/TableGen/ClangAttrEmitter.cpp
anatofuz
parents:
diff changeset
2334 <https://github.com/llvm/llvm-project/blob/master/clang/utils/TableGen/ClangAttrEmitter.cpp>`_
anatofuz
parents:
diff changeset
2335 may need to be updated.
anatofuz
parents:
diff changeset
2336
anatofuz
parents:
diff changeset
2337 By default, all subjects in the SubjectList must either be a Decl node defined
anatofuz
parents:
diff changeset
2338 in ``DeclNodes.td``, or a statement node defined in ``StmtNodes.td``. However,
anatofuz
parents:
diff changeset
2339 more complex subjects can be created by creating a ``SubsetSubject`` object.
anatofuz
parents:
diff changeset
2340 Each such object has a base subject which it appertains to (which must be a
anatofuz
parents:
diff changeset
2341 Decl or Stmt node, and not a SubsetSubject node), and some custom code which is
anatofuz
parents:
diff changeset
2342 called when determining whether an attribute appertains to the subject. For
anatofuz
parents:
diff changeset
2343 instance, a ``NonBitField`` SubsetSubject appertains to a ``FieldDecl``, and
anatofuz
parents:
diff changeset
2344 tests whether the given FieldDecl is a bit field. When a SubsetSubject is
anatofuz
parents:
diff changeset
2345 specified in a SubjectList, a custom diagnostic parameter must also be provided.
anatofuz
parents:
diff changeset
2346
anatofuz
parents:
diff changeset
2347 Diagnostic checking for attribute subject lists is automated except when
anatofuz
parents:
diff changeset
2348 ``HasCustomParsing`` is set to ``1``.
anatofuz
parents:
diff changeset
2349
anatofuz
parents:
diff changeset
2350 Documentation
anatofuz
parents:
diff changeset
2351 ~~~~~~~~~~~~~
anatofuz
parents:
diff changeset
2352 All attributes must have some form of documentation associated with them.
anatofuz
parents:
diff changeset
2353 Documentation is table generated on the public web server by a server-side
anatofuz
parents:
diff changeset
2354 process that runs daily. Generally, the documentation for an attribute is a
anatofuz
parents:
diff changeset
2355 stand-alone definition in `include/clang/Basic/AttrDocs.td
anatofuz
parents:
diff changeset
2356 <https://github.com/llvm/llvm-project/blob/master/clang/include/clang/Basic/AttrDocs.td>`_
anatofuz
parents:
diff changeset
2357 that is named after the attribute being documented.
anatofuz
parents:
diff changeset
2358
anatofuz
parents:
diff changeset
2359 If the attribute is not for public consumption, or is an implicitly-created
anatofuz
parents:
diff changeset
2360 attribute that has no visible spelling, the documentation list can specify the
anatofuz
parents:
diff changeset
2361 ``Undocumented`` object. Otherwise, the attribute should have its documentation
anatofuz
parents:
diff changeset
2362 added to AttrDocs.td.
anatofuz
parents:
diff changeset
2363
anatofuz
parents:
diff changeset
2364 Documentation derives from the ``Documentation`` tablegen type. All derived
anatofuz
parents:
diff changeset
2365 types must specify a documentation category and the actual documentation itself.
anatofuz
parents:
diff changeset
2366 Additionally, it can specify a custom heading for the attribute, though a
anatofuz
parents:
diff changeset
2367 default heading will be chosen when possible.
anatofuz
parents:
diff changeset
2368
anatofuz
parents:
diff changeset
2369 There are four predefined documentation categories: ``DocCatFunction`` for
anatofuz
parents:
diff changeset
2370 attributes that appertain to function-like subjects, ``DocCatVariable`` for
anatofuz
parents:
diff changeset
2371 attributes that appertain to variable-like subjects, ``DocCatType`` for type
anatofuz
parents:
diff changeset
2372 attributes, and ``DocCatStmt`` for statement attributes. A custom documentation
anatofuz
parents:
diff changeset
2373 category should be used for groups of attributes with similar functionality.
anatofuz
parents:
diff changeset
2374 Custom categories are good for providing overview information for the attributes
anatofuz
parents:
diff changeset
2375 grouped under it. For instance, the consumed annotation attributes define a
anatofuz
parents:
diff changeset
2376 custom category, ``DocCatConsumed``, that explains what consumed annotations are
anatofuz
parents:
diff changeset
2377 at a high level.
anatofuz
parents:
diff changeset
2378
anatofuz
parents:
diff changeset
2379 Documentation content (whether it is for an attribute or a category) is written
anatofuz
parents:
diff changeset
2380 using reStructuredText (RST) syntax.
anatofuz
parents:
diff changeset
2381
anatofuz
parents:
diff changeset
2382 After writing the documentation for the attribute, it should be locally tested
anatofuz
parents:
diff changeset
2383 to ensure that there are no issues generating the documentation on the server.
anatofuz
parents:
diff changeset
2384 Local testing requires a fresh build of clang-tblgen. To generate the attribute
anatofuz
parents:
diff changeset
2385 documentation, execute the following command::
anatofuz
parents:
diff changeset
2386
anatofuz
parents:
diff changeset
2387 clang-tblgen -gen-attr-docs -I /path/to/clang/include /path/to/clang/include/clang/Basic/Attr.td -o /path/to/clang/docs/AttributeReference.rst
anatofuz
parents:
diff changeset
2388
anatofuz
parents:
diff changeset
2389 When testing locally, *do not* commit changes to ``AttributeReference.rst``.
anatofuz
parents:
diff changeset
2390 This file is generated by the server automatically, and any changes made to this
anatofuz
parents:
diff changeset
2391 file will be overwritten.
anatofuz
parents:
diff changeset
2392
anatofuz
parents:
diff changeset
2393 Arguments
anatofuz
parents:
diff changeset
2394 ~~~~~~~~~
anatofuz
parents:
diff changeset
2395 Attributes may optionally specify a list of arguments that can be passed to the
anatofuz
parents:
diff changeset
2396 attribute. Attribute arguments specify both the parsed form and the semantic
anatofuz
parents:
diff changeset
2397 form of the attribute. For example, if ``Args`` is
anatofuz
parents:
diff changeset
2398 ``[StringArgument<"Arg1">, IntArgument<"Arg2">]`` then
anatofuz
parents:
diff changeset
2399 ``__attribute__((myattribute("Hello", 3)))`` will be a valid use; it requires
anatofuz
parents:
diff changeset
2400 two arguments while parsing, and the Attr subclass' constructor for the
anatofuz
parents:
diff changeset
2401 semantic attribute will require a string and integer argument.
anatofuz
parents:
diff changeset
2402
anatofuz
parents:
diff changeset
2403 All arguments have a name and a flag that specifies whether the argument is
anatofuz
parents:
diff changeset
2404 optional. The associated C++ type of the argument is determined by the argument
anatofuz
parents:
diff changeset
2405 definition type. If the existing argument types are insufficient, new types can
anatofuz
parents:
diff changeset
2406 be created, but it requires modifying `utils/TableGen/ClangAttrEmitter.cpp
anatofuz
parents:
diff changeset
2407 <https://github.com/llvm/llvm-project/blob/master/clang/utils/TableGen/ClangAttrEmitter.cpp>`_
anatofuz
parents:
diff changeset
2408 to properly support the type.
anatofuz
parents:
diff changeset
2409
anatofuz
parents:
diff changeset
2410 Other Properties
anatofuz
parents:
diff changeset
2411 ~~~~~~~~~~~~~~~~
anatofuz
parents:
diff changeset
2412 The ``Attr`` definition has other members which control the behavior of the
anatofuz
parents:
diff changeset
2413 attribute. Many of them are special-purpose and beyond the scope of this
anatofuz
parents:
diff changeset
2414 document, however a few deserve mention.
anatofuz
parents:
diff changeset
2415
anatofuz
parents:
diff changeset
2416 If the parsed form of the attribute is more complex, or differs from the
anatofuz
parents:
diff changeset
2417 semantic form, the ``HasCustomParsing`` bit can be set to ``1`` for the class,
anatofuz
parents:
diff changeset
2418 and the parsing code in `Parser::ParseGNUAttributeArgs()
anatofuz
parents:
diff changeset
2419 <https://github.com/llvm/llvm-project/blob/master/clang/lib/Parse/ParseDecl.cpp>`_
anatofuz
parents:
diff changeset
2420 can be updated for the special case. Note that this only applies to arguments
anatofuz
parents:
diff changeset
2421 with a GNU spelling -- attributes with a __declspec spelling currently ignore
anatofuz
parents:
diff changeset
2422 this flag and are handled by ``Parser::ParseMicrosoftDeclSpec``.
anatofuz
parents:
diff changeset
2423
anatofuz
parents:
diff changeset
2424 Note that setting this member to 1 will opt out of common attribute semantic
anatofuz
parents:
diff changeset
2425 handling, requiring extra implementation efforts to ensure the attribute
anatofuz
parents:
diff changeset
2426 appertains to the appropriate subject, etc.
anatofuz
parents:
diff changeset
2427
anatofuz
parents:
diff changeset
2428 If the attribute should not be propagated from a template declaration to an
anatofuz
parents:
diff changeset
2429 instantiation of the template, set the ``Clone`` member to 0. By default, all
anatofuz
parents:
diff changeset
2430 attributes will be cloned to template instantiations.
anatofuz
parents:
diff changeset
2431
anatofuz
parents:
diff changeset
2432 Attributes that do not require an AST node should set the ``ASTNode`` field to
anatofuz
parents:
diff changeset
2433 ``0`` to avoid polluting the AST. Note that anything inheriting from
anatofuz
parents:
diff changeset
2434 ``TypeAttr`` or ``IgnoredAttr`` automatically do not generate an AST node. All
anatofuz
parents:
diff changeset
2435 other attributes generate an AST node by default. The AST node is the semantic
anatofuz
parents:
diff changeset
2436 representation of the attribute.
anatofuz
parents:
diff changeset
2437
anatofuz
parents:
diff changeset
2438 The ``LangOpts`` field specifies a list of language options required by the
anatofuz
parents:
diff changeset
2439 attribute. For instance, all of the CUDA-specific attributes specify ``[CUDA]``
anatofuz
parents:
diff changeset
2440 for the ``LangOpts`` field, and when the CUDA language option is not enabled, an
anatofuz
parents:
diff changeset
2441 "attribute ignored" warning diagnostic is emitted. Since language options are
anatofuz
parents:
diff changeset
2442 not table generated nodes, new language options must be created manually and
anatofuz
parents:
diff changeset
2443 should specify the spelling used by ``LangOptions`` class.
anatofuz
parents:
diff changeset
2444
anatofuz
parents:
diff changeset
2445 Custom accessors can be generated for an attribute based on the spelling list
anatofuz
parents:
diff changeset
2446 for that attribute. For instance, if an attribute has two different spellings:
anatofuz
parents:
diff changeset
2447 'Foo' and 'Bar', accessors can be created:
anatofuz
parents:
diff changeset
2448 ``[Accessor<"isFoo", [GNU<"Foo">]>, Accessor<"isBar", [GNU<"Bar">]>]``
anatofuz
parents:
diff changeset
2449 These accessors will be generated on the semantic form of the attribute,
anatofuz
parents:
diff changeset
2450 accepting no arguments and returning a ``bool``.
anatofuz
parents:
diff changeset
2451
anatofuz
parents:
diff changeset
2452 Attributes that do not require custom semantic handling should set the
anatofuz
parents:
diff changeset
2453 ``SemaHandler`` field to ``0``. Note that anything inheriting from
anatofuz
parents:
diff changeset
2454 ``IgnoredAttr`` automatically do not get a semantic handler. All other
anatofuz
parents:
diff changeset
2455 attributes are assumed to use a semantic handler by default. Attributes
anatofuz
parents:
diff changeset
2456 without a semantic handler are not given a parsed attribute ``Kind`` enumerator.
anatofuz
parents:
diff changeset
2457
anatofuz
parents:
diff changeset
2458 Target-specific attributes may share a spelling with other attributes in
anatofuz
parents:
diff changeset
2459 different targets. For instance, the ARM and MSP430 targets both have an
anatofuz
parents:
diff changeset
2460 attribute spelled ``GNU<"interrupt">``, but with different parsing and semantic
anatofuz
parents:
diff changeset
2461 requirements. To support this feature, an attribute inheriting from
anatofuz
parents:
diff changeset
2462 ``TargetSpecificAttribute`` may specify a ``ParseKind`` field. This field
anatofuz
parents:
diff changeset
2463 should be the same value between all arguments sharing a spelling, and
anatofuz
parents:
diff changeset
2464 corresponds to the parsed attribute's ``Kind`` enumerator. This allows
anatofuz
parents:
diff changeset
2465 attributes to share a parsed attribute kind, but have distinct semantic
anatofuz
parents:
diff changeset
2466 attribute classes. For instance, ``ParsedAttr`` is the shared
anatofuz
parents:
diff changeset
2467 parsed attribute kind, but ARMInterruptAttr and MSP430InterruptAttr are the
anatofuz
parents:
diff changeset
2468 semantic attributes generated.
anatofuz
parents:
diff changeset
2469
anatofuz
parents:
diff changeset
2470 By default, attribute arguments are parsed in an evaluated context. If the
anatofuz
parents:
diff changeset
2471 arguments for an attribute should be parsed in an unevaluated context (akin to
anatofuz
parents:
diff changeset
2472 the way the argument to a ``sizeof`` expression is parsed), set
anatofuz
parents:
diff changeset
2473 ``ParseArgumentsAsUnevaluated`` to ``1``.
anatofuz
parents:
diff changeset
2474
anatofuz
parents:
diff changeset
2475 If additional functionality is desired for the semantic form of the attribute,
anatofuz
parents:
diff changeset
2476 the ``AdditionalMembers`` field specifies code to be copied verbatim into the
anatofuz
parents:
diff changeset
2477 semantic attribute class object, with ``public`` access.
anatofuz
parents:
diff changeset
2478
anatofuz
parents:
diff changeset
2479 Boilerplate
anatofuz
parents:
diff changeset
2480 ^^^^^^^^^^^
anatofuz
parents:
diff changeset
2481 All semantic processing of declaration attributes happens in `lib/Sema/SemaDeclAttr.cpp
anatofuz
parents:
diff changeset
2482 <https://github.com/llvm/llvm-project/blob/master/clang/lib/Sema/SemaDeclAttr.cpp>`_,
anatofuz
parents:
diff changeset
2483 and generally starts in the ``ProcessDeclAttribute()`` function. If the
anatofuz
parents:
diff changeset
2484 attribute is a "simple" attribute -- meaning that it requires no custom semantic
anatofuz
parents:
diff changeset
2485 processing aside from what is automatically provided, add a call to
anatofuz
parents:
diff changeset
2486 ``handleSimpleAttribute<YourAttr>(S, D, Attr);`` to the switch statement.
anatofuz
parents:
diff changeset
2487 Otherwise, write a new ``handleYourAttr()`` function, and add that to the switch
anatofuz
parents:
diff changeset
2488 statement. Please do not implement handling logic directly in the ``case`` for
anatofuz
parents:
diff changeset
2489 the attribute.
anatofuz
parents:
diff changeset
2490
anatofuz
parents:
diff changeset
2491 Unless otherwise specified by the attribute definition, common semantic checking
anatofuz
parents:
diff changeset
2492 of the parsed attribute is handled automatically. This includes diagnosing
anatofuz
parents:
diff changeset
2493 parsed attributes that do not appertain to the given ``Decl``, ensuring the
anatofuz
parents:
diff changeset
2494 correct minimum number of arguments are passed, etc.
anatofuz
parents:
diff changeset
2495
anatofuz
parents:
diff changeset
2496 If the attribute adds additional warnings, define a ``DiagGroup`` in
anatofuz
parents:
diff changeset
2497 `include/clang/Basic/DiagnosticGroups.td
anatofuz
parents:
diff changeset
2498 <https://github.com/llvm/llvm-project/blob/master/clang/include/clang/Basic/DiagnosticGroups.td>`_
anatofuz
parents:
diff changeset
2499 named after the attribute's ``Spelling`` with "_"s replaced by "-"s. If there
anatofuz
parents:
diff changeset
2500 is only a single diagnostic, it is permissible to use ``InGroup<DiagGroup<"your-attribute">>``
anatofuz
parents:
diff changeset
2501 directly in `DiagnosticSemaKinds.td
anatofuz
parents:
diff changeset
2502 <https://github.com/llvm/llvm-project/blob/master/clang/include/clang/Basic/DiagnosticSemaKinds.td>`_
anatofuz
parents:
diff changeset
2503
anatofuz
parents:
diff changeset
2504 All semantic diagnostics generated for your attribute, including automatically-
anatofuz
parents:
diff changeset
2505 generated ones (such as subjects and argument counts), should have a
anatofuz
parents:
diff changeset
2506 corresponding test case.
anatofuz
parents:
diff changeset
2507
anatofuz
parents:
diff changeset
2508 Semantic handling
anatofuz
parents:
diff changeset
2509 ^^^^^^^^^^^^^^^^^
anatofuz
parents:
diff changeset
2510 Most attributes are implemented to have some effect on the compiler. For
anatofuz
parents:
diff changeset
2511 instance, to modify the way code is generated, or to add extra semantic checks
anatofuz
parents:
diff changeset
2512 for an analysis pass, etc. Having added the attribute definition and conversion
anatofuz
parents:
diff changeset
2513 to the semantic representation for the attribute, what remains is to implement
anatofuz
parents:
diff changeset
2514 the custom logic requiring use of the attribute.
anatofuz
parents:
diff changeset
2515
anatofuz
parents:
diff changeset
2516 The ``clang::Decl`` object can be queried for the presence or absence of an
anatofuz
parents:
diff changeset
2517 attribute using ``hasAttr<T>()``. To obtain a pointer to the semantic
anatofuz
parents:
diff changeset
2518 representation of the attribute, ``getAttr<T>`` may be used.
anatofuz
parents:
diff changeset
2519
anatofuz
parents:
diff changeset
2520 How to add an expression or statement
anatofuz
parents:
diff changeset
2521 -------------------------------------
anatofuz
parents:
diff changeset
2522
anatofuz
parents:
diff changeset
2523 Expressions and statements are one of the most fundamental constructs within a
anatofuz
parents:
diff changeset
2524 compiler, because they interact with many different parts of the AST, semantic
anatofuz
parents:
diff changeset
2525 analysis, and IR generation. Therefore, adding a new expression or statement
anatofuz
parents:
diff changeset
2526 kind into Clang requires some care. The following list details the various
anatofuz
parents:
diff changeset
2527 places in Clang where an expression or statement needs to be introduced, along
anatofuz
parents:
diff changeset
2528 with patterns to follow to ensure that the new expression or statement works
anatofuz
parents:
diff changeset
2529 well across all of the C languages. We focus on expressions, but statements
anatofuz
parents:
diff changeset
2530 are similar.
anatofuz
parents:
diff changeset
2531
anatofuz
parents:
diff changeset
2532 #. Introduce parsing actions into the parser. Recursive-descent parsing is
anatofuz
parents:
diff changeset
2533 mostly self-explanatory, but there are a few things that are worth keeping
anatofuz
parents:
diff changeset
2534 in mind:
anatofuz
parents:
diff changeset
2535
anatofuz
parents:
diff changeset
2536 * Keep as much source location information as possible! You'll want it later
anatofuz
parents:
diff changeset
2537 to produce great diagnostics and support Clang's various features that map
anatofuz
parents:
diff changeset
2538 between source code and the AST.
anatofuz
parents:
diff changeset
2539 * Write tests for all of the "bad" parsing cases, to make sure your recovery
anatofuz
parents:
diff changeset
2540 is good. If you have matched delimiters (e.g., parentheses, square
anatofuz
parents:
diff changeset
2541 brackets, etc.), use ``Parser::BalancedDelimiterTracker`` to give nice
anatofuz
parents:
diff changeset
2542 diagnostics when things go wrong.
anatofuz
parents:
diff changeset
2543
anatofuz
parents:
diff changeset
2544 #. Introduce semantic analysis actions into ``Sema``. Semantic analysis should
anatofuz
parents:
diff changeset
2545 always involve two functions: an ``ActOnXXX`` function that will be called
anatofuz
parents:
diff changeset
2546 directly from the parser, and a ``BuildXXX`` function that performs the
anatofuz
parents:
diff changeset
2547 actual semantic analysis and will (eventually!) build the AST node. It's
anatofuz
parents:
diff changeset
2548 fairly common for the ``ActOnCXX`` function to do very little (often just
anatofuz
parents:
diff changeset
2549 some minor translation from the parser's representation to ``Sema``'s
anatofuz
parents:
diff changeset
2550 representation of the same thing), but the separation is still important:
anatofuz
parents:
diff changeset
2551 C++ template instantiation, for example, should always call the ``BuildXXX``
anatofuz
parents:
diff changeset
2552 variant. Several notes on semantic analysis before we get into construction
anatofuz
parents:
diff changeset
2553 of the AST:
anatofuz
parents:
diff changeset
2554
anatofuz
parents:
diff changeset
2555 * Your expression probably involves some types and some subexpressions.
anatofuz
parents:
diff changeset
2556 Make sure to fully check that those types, and the types of those
anatofuz
parents:
diff changeset
2557 subexpressions, meet your expectations. Add implicit conversions where
anatofuz
parents:
diff changeset
2558 necessary to make sure that all of the types line up exactly the way you
anatofuz
parents:
diff changeset
2559 want them. Write extensive tests to check that you're getting good
anatofuz
parents:
diff changeset
2560 diagnostics for mistakes and that you can use various forms of
anatofuz
parents:
diff changeset
2561 subexpressions with your expression.
anatofuz
parents:
diff changeset
2562 * When type-checking a type or subexpression, make sure to first check
anatofuz
parents:
diff changeset
2563 whether the type is "dependent" (``Type::isDependentType()``) or whether a
anatofuz
parents:
diff changeset
2564 subexpression is type-dependent (``Expr::isTypeDependent()``). If any of
anatofuz
parents:
diff changeset
2565 these return ``true``, then you're inside a template and you can't do much
anatofuz
parents:
diff changeset
2566 type-checking now. That's normal, and your AST node (when you get there)
anatofuz
parents:
diff changeset
2567 will have to deal with this case. At this point, you can write tests that
anatofuz
parents:
diff changeset
2568 use your expression within templates, but don't try to instantiate the
anatofuz
parents:
diff changeset
2569 templates.
anatofuz
parents:
diff changeset
2570 * For each subexpression, be sure to call ``Sema::CheckPlaceholderExpr()``
anatofuz
parents:
diff changeset
2571 to deal with "weird" expressions that don't behave well as subexpressions.
anatofuz
parents:
diff changeset
2572 Then, determine whether you need to perform lvalue-to-rvalue conversions
anatofuz
parents:
diff changeset
2573 (``Sema::DefaultLvalueConversions``) or the usual unary conversions
anatofuz
parents:
diff changeset
2574 (``Sema::UsualUnaryConversions``), for places where the subexpression is
anatofuz
parents:
diff changeset
2575 producing a value you intend to use.
anatofuz
parents:
diff changeset
2576 * Your ``BuildXXX`` function will probably just return ``ExprError()`` at
anatofuz
parents:
diff changeset
2577 this point, since you don't have an AST. That's perfectly fine, and
anatofuz
parents:
diff changeset
2578 shouldn't impact your testing.
anatofuz
parents:
diff changeset
2579
anatofuz
parents:
diff changeset
2580 #. Introduce an AST node for your new expression. This starts with declaring
anatofuz
parents:
diff changeset
2581 the node in ``include/Basic/StmtNodes.td`` and creating a new class for your
anatofuz
parents:
diff changeset
2582 expression in the appropriate ``include/AST/Expr*.h`` header. It's best to
anatofuz
parents:
diff changeset
2583 look at the class for a similar expression to get ideas, and there are some
anatofuz
parents:
diff changeset
2584 specific things to watch for:
anatofuz
parents:
diff changeset
2585
anatofuz
parents:
diff changeset
2586 * If you need to allocate memory, use the ``ASTContext`` allocator to
anatofuz
parents:
diff changeset
2587 allocate memory. Never use raw ``malloc`` or ``new``, and never hold any
anatofuz
parents:
diff changeset
2588 resources in an AST node, because the destructor of an AST node is never
anatofuz
parents:
diff changeset
2589 called.
anatofuz
parents:
diff changeset
2590 * Make sure that ``getSourceRange()`` covers the exact source range of your
anatofuz
parents:
diff changeset
2591 expression. This is needed for diagnostics and for IDE support.
anatofuz
parents:
diff changeset
2592 * Make sure that ``children()`` visits all of the subexpressions. This is
anatofuz
parents:
diff changeset
2593 important for a number of features (e.g., IDE support, C++ variadic
anatofuz
parents:
diff changeset
2594 templates). If you have sub-types, you'll also need to visit those
anatofuz
parents:
diff changeset
2595 sub-types in ``RecursiveASTVisitor``.
anatofuz
parents:
diff changeset
2596 * Add printing support (``StmtPrinter.cpp``) for your expression.
anatofuz
parents:
diff changeset
2597 * Add profiling support (``StmtProfile.cpp``) for your AST node, noting the
anatofuz
parents:
diff changeset
2598 distinguishing (non-source location) characteristics of an instance of
anatofuz
parents:
diff changeset
2599 your expression. Omitting this step will lead to hard-to-diagnose
anatofuz
parents:
diff changeset
2600 failures regarding matching of template declarations.
anatofuz
parents:
diff changeset
2601 * Add serialization support (``ASTReaderStmt.cpp``, ``ASTWriterStmt.cpp``)
anatofuz
parents:
diff changeset
2602 for your AST node.
anatofuz
parents:
diff changeset
2603
anatofuz
parents:
diff changeset
2604 #. Teach semantic analysis to build your AST node. At this point, you can wire
anatofuz
parents:
diff changeset
2605 up your ``Sema::BuildXXX`` function to actually create your AST. A few
anatofuz
parents:
diff changeset
2606 things to check at this point:
anatofuz
parents:
diff changeset
2607
anatofuz
parents:
diff changeset
2608 * If your expression can construct a new C++ class or return a new
anatofuz
parents:
diff changeset
2609 Objective-C object, be sure to update and then call
anatofuz
parents:
diff changeset
2610 ``Sema::MaybeBindToTemporary`` for your just-created AST node to be sure
anatofuz
parents:
diff changeset
2611 that the object gets properly destructed. An easy way to test this is to
anatofuz
parents:
diff changeset
2612 return a C++ class with a private destructor: semantic analysis should
anatofuz
parents:
diff changeset
2613 flag an error here with the attempt to call the destructor.
anatofuz
parents:
diff changeset
2614 * Inspect the generated AST by printing it using ``clang -cc1 -ast-print``,
anatofuz
parents:
diff changeset
2615 to make sure you're capturing all of the important information about how
anatofuz
parents:
diff changeset
2616 the AST was written.
anatofuz
parents:
diff changeset
2617 * Inspect the generated AST under ``clang -cc1 -ast-dump`` to verify that
anatofuz
parents:
diff changeset
2618 all of the types in the generated AST line up the way you want them.
anatofuz
parents:
diff changeset
2619 Remember that clients of the AST should never have to "think" to
anatofuz
parents:
diff changeset
2620 understand what's going on. For example, all implicit conversions should
anatofuz
parents:
diff changeset
2621 show up explicitly in the AST.
anatofuz
parents:
diff changeset
2622 * Write tests that use your expression as a subexpression of other,
anatofuz
parents:
diff changeset
2623 well-known expressions. Can you call a function using your expression as
anatofuz
parents:
diff changeset
2624 an argument? Can you use the ternary operator?
anatofuz
parents:
diff changeset
2625
anatofuz
parents:
diff changeset
2626 #. Teach code generation to create IR to your AST node. This step is the first
anatofuz
parents:
diff changeset
2627 (and only) that requires knowledge of LLVM IR. There are several things to
anatofuz
parents:
diff changeset
2628 keep in mind:
anatofuz
parents:
diff changeset
2629
anatofuz
parents:
diff changeset
2630 * Code generation is separated into scalar/aggregate/complex and
anatofuz
parents:
diff changeset
2631 lvalue/rvalue paths, depending on what kind of result your expression
anatofuz
parents:
diff changeset
2632 produces. On occasion, this requires some careful factoring of code to
anatofuz
parents:
diff changeset
2633 avoid duplication.
anatofuz
parents:
diff changeset
2634 * ``CodeGenFunction`` contains functions ``ConvertType`` and
anatofuz
parents:
diff changeset
2635 ``ConvertTypeForMem`` that convert Clang's types (``clang::Type*`` or
anatofuz
parents:
diff changeset
2636 ``clang::QualType``) to LLVM types. Use the former for values, and the
anatofuz
parents:
diff changeset
2637 latter for memory locations: test with the C++ "``bool``" type to check
anatofuz
parents:
diff changeset
2638 this. If you find that you are having to use LLVM bitcasts to make the
anatofuz
parents:
diff changeset
2639 subexpressions of your expression have the type that your expression
anatofuz
parents:
diff changeset
2640 expects, STOP! Go fix semantic analysis and the AST so that you don't
anatofuz
parents:
diff changeset
2641 need these bitcasts.
anatofuz
parents:
diff changeset
2642 * The ``CodeGenFunction`` class has a number of helper functions to make
anatofuz
parents:
diff changeset
2643 certain operations easy, such as generating code to produce an lvalue or
anatofuz
parents:
diff changeset
2644 an rvalue, or to initialize a memory location with a given value. Prefer
anatofuz
parents:
diff changeset
2645 to use these functions rather than directly writing loads and stores,
anatofuz
parents:
diff changeset
2646 because these functions take care of some of the tricky details for you
anatofuz
parents:
diff changeset
2647 (e.g., for exceptions).
anatofuz
parents:
diff changeset
2648 * If your expression requires some special behavior in the event of an
anatofuz
parents:
diff changeset
2649 exception, look at the ``push*Cleanup`` functions in ``CodeGenFunction``
anatofuz
parents:
diff changeset
2650 to introduce a cleanup. You shouldn't have to deal with
anatofuz
parents:
diff changeset
2651 exception-handling directly.
anatofuz
parents:
diff changeset
2652 * Testing is extremely important in IR generation. Use ``clang -cc1
anatofuz
parents:
diff changeset
2653 -emit-llvm`` and `FileCheck
anatofuz
parents:
diff changeset
2654 <https://llvm.org/docs/CommandGuide/FileCheck.html>`_ to verify that you're
anatofuz
parents:
diff changeset
2655 generating the right IR.
anatofuz
parents:
diff changeset
2656
anatofuz
parents:
diff changeset
2657 #. Teach template instantiation how to cope with your AST node, which requires
anatofuz
parents:
diff changeset
2658 some fairly simple code:
anatofuz
parents:
diff changeset
2659
anatofuz
parents:
diff changeset
2660 * Make sure that your expression's constructor properly computes the flags
anatofuz
parents:
diff changeset
2661 for type dependence (i.e., the type your expression produces can change
anatofuz
parents:
diff changeset
2662 from one instantiation to the next), value dependence (i.e., the constant
anatofuz
parents:
diff changeset
2663 value your expression produces can change from one instantiation to the
anatofuz
parents:
diff changeset
2664 next), instantiation dependence (i.e., a template parameter occurs
anatofuz
parents:
diff changeset
2665 anywhere in your expression), and whether your expression contains a
anatofuz
parents:
diff changeset
2666 parameter pack (for variadic templates). Often, computing these flags
anatofuz
parents:
diff changeset
2667 just means combining the results from the various types and
anatofuz
parents:
diff changeset
2668 subexpressions.
anatofuz
parents:
diff changeset
2669 * Add ``TransformXXX`` and ``RebuildXXX`` functions to the ``TreeTransform``
anatofuz
parents:
diff changeset
2670 class template in ``Sema``. ``TransformXXX`` should (recursively)
anatofuz
parents:
diff changeset
2671 transform all of the subexpressions and types within your expression,
anatofuz
parents:
diff changeset
2672 using ``getDerived().TransformYYY``. If all of the subexpressions and
anatofuz
parents:
diff changeset
2673 types transform without error, it will then call the ``RebuildXXX``
anatofuz
parents:
diff changeset
2674 function, which will in turn call ``getSema().BuildXXX`` to perform
anatofuz
parents:
diff changeset
2675 semantic analysis and build your expression.
anatofuz
parents:
diff changeset
2676 * To test template instantiation, take those tests you wrote to make sure
anatofuz
parents:
diff changeset
2677 that you were type checking with type-dependent expressions and dependent
anatofuz
parents:
diff changeset
2678 types (from step #2) and instantiate those templates with various types,
anatofuz
parents:
diff changeset
2679 some of which type-check and some that don't, and test the error messages
anatofuz
parents:
diff changeset
2680 in each case.
anatofuz
parents:
diff changeset
2681
anatofuz
parents:
diff changeset
2682 #. There are some "extras" that make other features work better. It's worth
anatofuz
parents:
diff changeset
2683 handling these extras to give your expression complete integration into
anatofuz
parents:
diff changeset
2684 Clang:
anatofuz
parents:
diff changeset
2685
anatofuz
parents:
diff changeset
2686 * Add code completion support for your expression in
anatofuz
parents:
diff changeset
2687 ``SemaCodeComplete.cpp``.
anatofuz
parents:
diff changeset
2688 * If your expression has types in it, or has any "interesting" features
anatofuz
parents:
diff changeset
2689 other than subexpressions, extend libclang's ``CursorVisitor`` to provide
anatofuz
parents:
diff changeset
2690 proper visitation for your expression, enabling various IDE features such
anatofuz
parents:
diff changeset
2691 as syntax highlighting, cross-referencing, and so on. The
anatofuz
parents:
diff changeset
2692 ``c-index-test`` helper program can be used to test these features.
anatofuz
parents:
diff changeset
2693