InternalsManual.rst 93 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953
  1. ============================
  2. "Clang" CFE Internals Manual
  3. ============================
  4. .. contents::
  5. :local:
  6. Introduction
  7. ============
  8. This document describes some of the more important APIs and internal design
  9. decisions made in the Clang C front-end. The purpose of this document is to
  10. both capture some of this high level information and also describe some of the
  11. design decisions behind it. This is meant for people interested in hacking on
  12. Clang, not for end-users. The description below is categorized by libraries,
  13. and does not describe any of the clients of the libraries.
  14. LLVM Support Library
  15. ====================
  16. The LLVM ``libSupport`` library provides many underlying libraries and
  17. `data-structures <http://llvm.org/docs/ProgrammersManual.html>`_, including
  18. command line option processing, various containers and a system abstraction
  19. layer, which is used for file system access.
  20. The Clang "Basic" Library
  21. =========================
  22. This library certainly needs a better name. The "basic" library contains a
  23. number of low-level utilities for tracking and manipulating source buffers,
  24. locations within the source buffers, diagnostics, tokens, target abstraction,
  25. and information about the subset of the language being compiled for.
  26. Part of this infrastructure is specific to C (such as the ``TargetInfo``
  27. class), other parts could be reused for other non-C-based languages
  28. (``SourceLocation``, ``SourceManager``, ``Diagnostics``, ``FileManager``).
  29. When and if there is future demand we can figure out if it makes sense to
  30. introduce a new library, move the general classes somewhere else, or introduce
  31. some other solution.
  32. We describe the roles of these classes in order of their dependencies.
  33. The Diagnostics Subsystem
  34. -------------------------
  35. The Clang Diagnostics subsystem is an important part of how the compiler
  36. communicates with the human. Diagnostics are the warnings and errors produced
  37. when the code is incorrect or dubious. In Clang, each diagnostic produced has
  38. (at the minimum) a unique ID, an English translation associated with it, a
  39. :ref:`SourceLocation <SourceLocation>` to "put the caret", and a severity
  40. (e.g., ``WARNING`` or ``ERROR``). They can also optionally include a number of
  41. arguments to the dianostic (which fill in "%0"'s in the string) as well as a
  42. number of source ranges that related to the diagnostic.
  43. In this section, we'll be giving examples produced by the Clang command line
  44. driver, but diagnostics can be :ref:`rendered in many different ways
  45. <DiagnosticClient>` depending on how the ``DiagnosticClient`` interface is
  46. implemented. A representative example of a diagnostic is:
  47. .. code-block:: c++
  48. t.c:38:15: error: invalid operands to binary expression ('int *' and '_Complex float')
  49. P = (P-42) + Gamma*4;
  50. ~~~~~~ ^ ~~~~~~~
  51. In this example, you can see the English translation, the severity (error), you
  52. can see the source location (the caret ("``^``") and file/line/column info),
  53. the source ranges "``~~~~``", arguments to the diagnostic ("``int*``" and
  54. "``_Complex float``"). You'll have to believe me that there is a unique ID
  55. backing the diagnostic :).
  56. Getting all of this to happen has several steps and involves many moving
  57. pieces, this section describes them and talks about best practices when adding
  58. a new diagnostic.
  59. The ``Diagnostic*Kinds.td`` files
  60. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  61. Diagnostics are created by adding an entry to one of the
  62. ``clang/Basic/Diagnostic*Kinds.td`` files, depending on what library will be
  63. using it. From this file, :program:`tblgen` generates the unique ID of the
  64. diagnostic, the severity of the diagnostic and the English translation + format
  65. string.
  66. There is little sanity with the naming of the unique ID's right now. Some
  67. start with ``err_``, ``warn_``, ``ext_`` to encode the severity into the name.
  68. Since the enum is referenced in the C++ code that produces the diagnostic, it
  69. is somewhat useful for it to be reasonably short.
  70. The severity of the diagnostic comes from the set {``NOTE``, ``REMARK``,
  71. ``WARNING``,
  72. ``EXTENSION``, ``EXTWARN``, ``ERROR``}. The ``ERROR`` severity is used for
  73. diagnostics indicating the program is never acceptable under any circumstances.
  74. When an error is emitted, the AST for the input code may not be fully built.
  75. The ``EXTENSION`` and ``EXTWARN`` severities are used for extensions to the
  76. language that Clang accepts. This means that Clang fully understands and can
  77. represent them in the AST, but we produce diagnostics to tell the user their
  78. code is non-portable. The difference is that the former are ignored by
  79. default, and the later warn by default. The ``WARNING`` severity is used for
  80. constructs that are valid in the currently selected source language but that
  81. are dubious in some way. The ``REMARK`` severity provides generic information
  82. about the compilation that is not necessarily related to any dubious code. The
  83. ``NOTE`` level is used to staple more information onto previous diagnostics.
  84. These *severities* are mapped into a smaller set (the ``Diagnostic::Level``
  85. enum, {``Ignored``, ``Note``, ``Remark``, ``Warning``, ``Error``, ``Fatal``}) of
  86. output
  87. *levels* by the diagnostics subsystem based on various configuration options.
  88. Clang internally supports a fully fine grained mapping mechanism that allows
  89. you to map almost any diagnostic to the output level that you want. The only
  90. diagnostics that cannot be mapped are ``NOTE``\ s, which always follow the
  91. severity of the previously emitted diagnostic and ``ERROR``\ s, which can only
  92. be mapped to ``Fatal`` (it is not possible to turn an error into a warning, for
  93. example).
  94. Diagnostic mappings are used in many ways. For example, if the user specifies
  95. ``-pedantic``, ``EXTENSION`` maps to ``Warning``, if they specify
  96. ``-pedantic-errors``, it turns into ``Error``. This is used to implement
  97. options like ``-Wunused_macros``, ``-Wundef`` etc.
  98. Mapping to ``Fatal`` should only be used for diagnostics that are considered so
  99. severe that error recovery won't be able to recover sensibly from them (thus
  100. spewing a ton of bogus errors). One example of this class of error are failure
  101. to ``#include`` a file.
  102. The Format String
  103. ^^^^^^^^^^^^^^^^^
  104. The format string for the diagnostic is very simple, but it has some power. It
  105. takes the form of a string in English with markers that indicate where and how
  106. arguments to the diagnostic are inserted and formatted. For example, here are
  107. some simple format strings:
  108. .. code-block:: c++
  109. "binary integer literals are an extension"
  110. "format string contains '\\0' within the string body"
  111. "more '%%' conversions than data arguments"
  112. "invalid operands to binary expression (%0 and %1)"
  113. "overloaded '%0' must be a %select{unary|binary|unary or binary}2 operator"
  114. " (has %1 parameter%s1)"
  115. These examples show some important points of format strings. You can use any
  116. plain ASCII character in the diagnostic string except "``%``" without a
  117. problem, but these are C strings, so you have to use and be aware of all the C
  118. escape sequences (as in the second example). If you want to produce a "``%``"
  119. in the output, use the "``%%``" escape sequence, like the third diagnostic.
  120. Finally, Clang uses the "``%...[digit]``" sequences to specify where and how
  121. arguments to the diagnostic are formatted.
  122. Arguments to the diagnostic are numbered according to how they are specified by
  123. the C++ code that :ref:`produces them <internals-producing-diag>`, and are
  124. referenced by ``%0`` .. ``%9``. If you have more than 10 arguments to your
  125. diagnostic, you are doing something wrong :). Unlike ``printf``, there is no
  126. requirement that arguments to the diagnostic end up in the output in the same
  127. order as they are specified, you could have a format string with "``%1 %0``"
  128. that swaps them, for example. The text in between the percent and digit are
  129. formatting instructions. If there are no instructions, the argument is just
  130. turned into a string and substituted in.
  131. Here are some "best practices" for writing the English format string:
  132. * Keep the string short. It should ideally fit in the 80 column limit of the
  133. ``DiagnosticKinds.td`` file. This avoids the diagnostic wrapping when
  134. printed, and forces you to think about the important point you are conveying
  135. with the diagnostic.
  136. * Take advantage of location information. The user will be able to see the
  137. line and location of the caret, so you don't need to tell them that the
  138. problem is with the 4th argument to the function: just point to it.
  139. * Do not capitalize the diagnostic string, and do not end it with a period.
  140. * If you need to quote something in the diagnostic string, use single quotes.
  141. Diagnostics should never take random English strings as arguments: you
  142. shouldn't use "``you have a problem with %0``" and pass in things like "``your
  143. argument``" or "``your return value``" as arguments. Doing this prevents
  144. :ref:`translating <internals-diag-translation>` the Clang diagnostics to other
  145. languages (because they'll get random English words in their otherwise
  146. localized diagnostic). The exceptions to this are C/C++ language keywords
  147. (e.g., ``auto``, ``const``, ``mutable``, etc) and C/C++ operators (``/=``).
  148. Note that things like "pointer" and "reference" are not keywords. On the other
  149. hand, you *can* include anything that comes from the user's source code,
  150. including variable names, types, labels, etc. The "``select``" format can be
  151. used to achieve this sort of thing in a localizable way, see below.
  152. Formatting a Diagnostic Argument
  153. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  154. Arguments to diagnostics are fully typed internally, and come from a couple
  155. different classes: integers, types, names, and random strings. Depending on
  156. the class of the argument, it can be optionally formatted in different ways.
  157. This gives the ``DiagnosticClient`` information about what the argument means
  158. without requiring it to use a specific presentation (consider this MVC for
  159. Clang :).
  160. Here are the different diagnostic argument formats currently supported by
  161. Clang:
  162. **"s" format**
  163. Example:
  164. ``"requires %1 parameter%s1"``
  165. Class:
  166. Integers
  167. Description:
  168. This is a simple formatter for integers that is useful when producing English
  169. diagnostics. When the integer is 1, it prints as nothing. When the integer
  170. is not 1, it prints as "``s``". This allows some simple grammatical forms to
  171. be to be handled correctly, and eliminates the need to use gross things like
  172. ``"requires %1 parameter(s)"``.
  173. **"select" format**
  174. Example:
  175. ``"must be a %select{unary|binary|unary or binary}2 operator"``
  176. Class:
  177. Integers
  178. Description:
  179. This format specifier is used to merge multiple related diagnostics together
  180. into one common one, without requiring the difference to be specified as an
  181. English string argument. Instead of specifying the string, the diagnostic
  182. gets an integer argument and the format string selects the numbered option.
  183. In this case, the "``%2``" value must be an integer in the range [0..2]. If
  184. it is 0, it prints "unary", if it is 1 it prints "binary" if it is 2, it
  185. prints "unary or binary". This allows other language translations to
  186. substitute reasonable words (or entire phrases) based on the semantics of the
  187. diagnostic instead of having to do things textually. The selected string
  188. does undergo formatting.
  189. **"plural" format**
  190. Example:
  191. ``"you have %1 %plural{1:mouse|:mice}1 connected to your computer"``
  192. Class:
  193. Integers
  194. Description:
  195. This is a formatter for complex plural forms. It is designed to handle even
  196. the requirements of languages with very complex plural forms, as many Baltic
  197. languages have. The argument consists of a series of expression/form pairs,
  198. separated by ":", where the first form whose expression evaluates to true is
  199. the result of the modifier.
  200. An expression can be empty, in which case it is always true. See the example
  201. at the top. Otherwise, it is a series of one or more numeric conditions,
  202. separated by ",". If any condition matches, the expression matches. Each
  203. numeric condition can take one of three forms.
  204. * number: A simple decimal number matches if the argument is the same as the
  205. number. Example: ``"%plural{1:mouse|:mice}4"``
  206. * range: A range in square brackets matches if the argument is within the
  207. range. Then range is inclusive on both ends. Example:
  208. ``"%plural{0:none|1:one|[2,5]:some|:many}2"``
  209. * modulo: A modulo operator is followed by a number, and equals sign and
  210. either a number or a range. The tests are the same as for plain numbers
  211. and ranges, but the argument is taken modulo the number first. Example:
  212. ``"%plural{%100=0:even hundred|%100=[1,50]:lower half|:everything else}1"``
  213. The parser is very unforgiving. A syntax error, even whitespace, will abort,
  214. as will a failure to match the argument against any expression.
  215. **"ordinal" format**
  216. Example:
  217. ``"ambiguity in %ordinal0 argument"``
  218. Class:
  219. Integers
  220. Description:
  221. This is a formatter which represents the argument number as an ordinal: the
  222. value ``1`` becomes ``1st``, ``3`` becomes ``3rd``, and so on. Values less
  223. than ``1`` are not supported. This formatter is currently hard-coded to use
  224. English ordinals.
  225. **"objcclass" format**
  226. Example:
  227. ``"method %objcclass0 not found"``
  228. Class:
  229. ``DeclarationName``
  230. Description:
  231. This is a simple formatter that indicates the ``DeclarationName`` corresponds
  232. to an Objective-C class method selector. As such, it prints the selector
  233. with a leading "``+``".
  234. **"objcinstance" format**
  235. Example:
  236. ``"method %objcinstance0 not found"``
  237. Class:
  238. ``DeclarationName``
  239. Description:
  240. This is a simple formatter that indicates the ``DeclarationName`` corresponds
  241. to an Objective-C instance method selector. As such, it prints the selector
  242. with a leading "``-``".
  243. **"q" format**
  244. Example:
  245. ``"candidate found by name lookup is %q0"``
  246. Class:
  247. ``NamedDecl *``
  248. Description:
  249. This formatter indicates that the fully-qualified name of the declaration
  250. should be printed, e.g., "``std::vector``" rather than "``vector``".
  251. **"diff" format**
  252. Example:
  253. ``"no known conversion %diff{from $ to $|from argument type to parameter type}1,2"``
  254. Class:
  255. ``QualType``
  256. Description:
  257. This formatter takes two ``QualType``\ s and attempts to print a template
  258. difference between the two. If tree printing is off, the text inside the
  259. braces before the pipe is printed, with the formatted text replacing the $.
  260. If tree printing is on, the text after the pipe is printed and a type tree is
  261. printed after the diagnostic message.
  262. It is really easy to add format specifiers to the Clang diagnostics system, but
  263. they should be discussed before they are added. If you are creating a lot of
  264. repetitive diagnostics and/or have an idea for a useful formatter, please bring
  265. it up on the cfe-dev mailing list.
  266. .. _internals-producing-diag:
  267. Producing the Diagnostic
  268. ^^^^^^^^^^^^^^^^^^^^^^^^
  269. Now that you've created the diagnostic in the ``Diagnostic*Kinds.td`` file, you
  270. need to write the code that detects the condition in question and emits the new
  271. diagnostic. Various components of Clang (e.g., the preprocessor, ``Sema``,
  272. etc.) provide a helper function named "``Diag``". It creates a diagnostic and
  273. accepts the arguments, ranges, and other information that goes along with it.
  274. For example, the binary expression error comes from code like this:
  275. .. code-block:: c++
  276. if (various things that are bad)
  277. Diag(Loc, diag::err_typecheck_invalid_operands)
  278. << lex->getType() << rex->getType()
  279. << lex->getSourceRange() << rex->getSourceRange();
  280. This shows that use of the ``Diag`` method: it takes a location (a
  281. :ref:`SourceLocation <SourceLocation>` object) and a diagnostic enum value
  282. (which matches the name from ``Diagnostic*Kinds.td``). If the diagnostic takes
  283. arguments, they are specified with the ``<<`` operator: the first argument
  284. becomes ``%0``, the second becomes ``%1``, etc. The diagnostic interface
  285. allows you to specify arguments of many different types, including ``int`` and
  286. ``unsigned`` for integer arguments, ``const char*`` and ``std::string`` for
  287. string arguments, ``DeclarationName`` and ``const IdentifierInfo *`` for names,
  288. ``QualType`` for types, etc. ``SourceRange``\ s are also specified with the
  289. ``<<`` operator, but do not have a specific ordering requirement.
  290. As you can see, adding and producing a diagnostic is pretty straightforward.
  291. The hard part is deciding exactly what you need to say to help the user,
  292. picking a suitable wording, and providing the information needed to format it
  293. correctly. The good news is that the call site that issues a diagnostic should
  294. be completely independent of how the diagnostic is formatted and in what
  295. language it is rendered.
  296. Fix-It Hints
  297. ^^^^^^^^^^^^
  298. In some cases, the front end emits diagnostics when it is clear that some small
  299. change to the source code would fix the problem. For example, a missing
  300. semicolon at the end of a statement or a use of deprecated syntax that is
  301. easily rewritten into a more modern form. Clang tries very hard to emit the
  302. diagnostic and recover gracefully in these and other cases.
  303. However, for these cases where the fix is obvious, the diagnostic can be
  304. annotated with a hint (referred to as a "fix-it hint") that describes how to
  305. change the code referenced by the diagnostic to fix the problem. For example,
  306. it might add the missing semicolon at the end of the statement or rewrite the
  307. use of a deprecated construct into something more palatable. Here is one such
  308. example from the C++ front end, where we warn about the right-shift operator
  309. changing meaning from C++98 to C++11:
  310. .. code-block:: c++
  311. test.cpp:3:7: warning: use of right-shift operator ('>>') in template argument
  312. will require parentheses in C++11
  313. A<100 >> 2> *a;
  314. ^
  315. ( )
  316. Here, the fix-it hint is suggesting that parentheses be added, and showing
  317. exactly where those parentheses would be inserted into the source code. The
  318. fix-it hints themselves describe what changes to make to the source code in an
  319. abstract manner, which the text diagnostic printer renders as a line of
  320. "insertions" below the caret line. :ref:`Other diagnostic clients
  321. <DiagnosticClient>` might choose to render the code differently (e.g., as
  322. markup inline) or even give the user the ability to automatically fix the
  323. problem.
  324. Fix-it hints on errors and warnings need to obey these rules:
  325. * Since they are automatically applied if ``-Xclang -fixit`` is passed to the
  326. driver, they should only be used when it's very likely they match the user's
  327. intent.
  328. * Clang must recover from errors as if the fix-it had been applied.
  329. If a fix-it can't obey these rules, put the fix-it on a note. Fix-its on notes
  330. are not applied automatically.
  331. All fix-it hints are described by the ``FixItHint`` class, instances of which
  332. should be attached to the diagnostic using the ``<<`` operator in the same way
  333. that highlighted source ranges and arguments are passed to the diagnostic.
  334. Fix-it hints can be created with one of three constructors:
  335. * ``FixItHint::CreateInsertion(Loc, Code)``
  336. Specifies that the given ``Code`` (a string) should be inserted before the
  337. source location ``Loc``.
  338. * ``FixItHint::CreateRemoval(Range)``
  339. Specifies that the code in the given source ``Range`` should be removed.
  340. * ``FixItHint::CreateReplacement(Range, Code)``
  341. Specifies that the code in the given source ``Range`` should be removed,
  342. and replaced with the given ``Code`` string.
  343. .. _DiagnosticClient:
  344. The ``DiagnosticClient`` Interface
  345. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  346. Once code generates a diagnostic with all of the arguments and the rest of the
  347. relevant information, Clang needs to know what to do with it. As previously
  348. mentioned, the diagnostic machinery goes through some filtering to map a
  349. severity onto a diagnostic level, then (assuming the diagnostic is not mapped
  350. to "``Ignore``") it invokes an object that implements the ``DiagnosticClient``
  351. interface with the information.
  352. It is possible to implement this interface in many different ways. For
  353. example, the normal Clang ``DiagnosticClient`` (named
  354. ``TextDiagnosticPrinter``) turns the arguments into strings (according to the
  355. various formatting rules), prints out the file/line/column information and the
  356. string, then prints out the line of code, the source ranges, and the caret.
  357. However, this behavior isn't required.
  358. Another implementation of the ``DiagnosticClient`` interface is the
  359. ``TextDiagnosticBuffer`` class, which is used when Clang is in ``-verify``
  360. mode. Instead of formatting and printing out the diagnostics, this
  361. implementation just captures and remembers the diagnostics as they fly by.
  362. Then ``-verify`` compares the list of produced diagnostics to the list of
  363. expected ones. If they disagree, it prints out its own output. Full
  364. documentation for the ``-verify`` mode can be found in the Clang API
  365. documentation for `VerifyDiagnosticConsumer
  366. </doxygen/classclang_1_1VerifyDiagnosticConsumer.html#details>`_.
  367. There are many other possible implementations of this interface, and this is
  368. why we prefer diagnostics to pass down rich structured information in
  369. arguments. For example, an HTML output might want declaration names be
  370. linkified to where they come from in the source. Another example is that a GUI
  371. might let you click on typedefs to expand them. This application would want to
  372. pass significantly more information about types through to the GUI than a
  373. simple flat string. The interface allows this to happen.
  374. .. _internals-diag-translation:
  375. Adding Translations to Clang
  376. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  377. Not possible yet! Diagnostic strings should be written in UTF-8, the client can
  378. translate to the relevant code page if needed. Each translation completely
  379. replaces the format string for the diagnostic.
  380. .. _SourceLocation:
  381. .. _SourceManager:
  382. The ``SourceLocation`` and ``SourceManager`` classes
  383. ----------------------------------------------------
  384. Strangely enough, the ``SourceLocation`` class represents a location within the
  385. source code of the program. Important design points include:
  386. #. ``sizeof(SourceLocation)`` must be extremely small, as these are embedded
  387. into many AST nodes and are passed around often. Currently it is 32 bits.
  388. #. ``SourceLocation`` must be a simple value object that can be efficiently
  389. copied.
  390. #. We should be able to represent a source location for any byte of any input
  391. file. This includes in the middle of tokens, in whitespace, in trigraphs,
  392. etc.
  393. #. A ``SourceLocation`` must encode the current ``#include`` stack that was
  394. active when the location was processed. For example, if the location
  395. corresponds to a token, it should contain the set of ``#include``\ s active
  396. when the token was lexed. This allows us to print the ``#include`` stack
  397. for a diagnostic.
  398. #. ``SourceLocation`` must be able to describe macro expansions, capturing both
  399. the ultimate instantiation point and the source of the original character
  400. data.
  401. In practice, the ``SourceLocation`` works together with the ``SourceManager``
  402. class to encode two pieces of information about a location: its spelling
  403. location and its instantiation location. For most tokens, these will be the
  404. same. However, for a macro expansion (or tokens that came from a ``_Pragma``
  405. directive) these will describe the location of the characters corresponding to
  406. the token and the location where the token was used (i.e., the macro
  407. instantiation point or the location of the ``_Pragma`` itself).
  408. The Clang front-end inherently depends on the location of a token being tracked
  409. correctly. If it is ever incorrect, the front-end may get confused and die.
  410. The reason for this is that the notion of the "spelling" of a ``Token`` in
  411. Clang depends on being able to find the original input characters for the
  412. token. This concept maps directly to the "spelling location" for the token.
  413. ``SourceRange`` and ``CharSourceRange``
  414. ---------------------------------------
  415. .. mostly taken from http://lists.cs.uiuc.edu/pipermail/cfe-dev/2010-August/010595.html
  416. Clang represents most source ranges by [first, last], where "first" and "last"
  417. each point to the beginning of their respective tokens. For example consider
  418. the ``SourceRange`` of the following statement:
  419. .. code-block:: c++
  420. x = foo + bar;
  421. ^first ^last
  422. To map from this representation to a character-based representation, the "last"
  423. location needs to be adjusted to point to (or past) the end of that token with
  424. either ``Lexer::MeasureTokenLength()`` or ``Lexer::getLocForEndOfToken()``. For
  425. the rare cases where character-level source ranges information is needed we use
  426. the ``CharSourceRange`` class.
  427. The Driver Library
  428. ==================
  429. The clang Driver and library are documented :doc:`here <DriverInternals>`.
  430. Precompiled Headers
  431. ===================
  432. Clang supports two implementations of precompiled headers. The default
  433. implementation, precompiled headers (:doc:`PCH <PCHInternals>`) uses a
  434. serialized representation of Clang's internal data structures, encoded with the
  435. `LLVM bitstream format <http://llvm.org/docs/BitCodeFormat.html>`_.
  436. Pretokenized headers (:doc:`PTH <PTHInternals>`), on the other hand, contain a
  437. serialized representation of the tokens encountered when preprocessing a header
  438. (and anything that header includes).
  439. The Frontend Library
  440. ====================
  441. The Frontend library contains functionality useful for building tools on top of
  442. the Clang libraries, for example several methods for outputting diagnostics.
  443. The Lexer and Preprocessor Library
  444. ==================================
  445. The Lexer library contains several tightly-connected classes that are involved
  446. with the nasty process of lexing and preprocessing C source code. The main
  447. interface to this library for outside clients is the large ``Preprocessor``
  448. class. It contains the various pieces of state that are required to coherently
  449. read tokens out of a translation unit.
  450. The core interface to the ``Preprocessor`` object (once it is set up) is the
  451. ``Preprocessor::Lex`` method, which returns the next :ref:`Token <Token>` from
  452. the preprocessor stream. There are two types of token providers that the
  453. preprocessor is capable of reading from: a buffer lexer (provided by the
  454. :ref:`Lexer <Lexer>` class) and a buffered token stream (provided by the
  455. :ref:`TokenLexer <TokenLexer>` class).
  456. .. _Token:
  457. The Token class
  458. ---------------
  459. The ``Token`` class is used to represent a single lexed token. Tokens are
  460. intended to be used by the lexer/preprocess and parser libraries, but are not
  461. intended to live beyond them (for example, they should not live in the ASTs).
  462. Tokens most often live on the stack (or some other location that is efficient
  463. to access) as the parser is running, but occasionally do get buffered up. For
  464. example, macro definitions are stored as a series of tokens, and the C++
  465. front-end periodically needs to buffer tokens up for tentative parsing and
  466. various pieces of look-ahead. As such, the size of a ``Token`` matters. On a
  467. 32-bit system, ``sizeof(Token)`` is currently 16 bytes.
  468. Tokens occur in two forms: :ref:`annotation tokens <AnnotationToken>` and
  469. normal tokens. Normal tokens are those returned by the lexer, annotation
  470. tokens represent semantic information and are produced by the parser, replacing
  471. normal tokens in the token stream. Normal tokens contain the following
  472. information:
  473. * **A SourceLocation** --- This indicates the location of the start of the
  474. token.
  475. * **A length** --- This stores the length of the token as stored in the
  476. ``SourceBuffer``. For tokens that include them, this length includes
  477. trigraphs and escaped newlines which are ignored by later phases of the
  478. compiler. By pointing into the original source buffer, it is always possible
  479. to get the original spelling of a token completely accurately.
  480. * **IdentifierInfo** --- If a token takes the form of an identifier, and if
  481. identifier lookup was enabled when the token was lexed (e.g., the lexer was
  482. not reading in "raw" mode) this contains a pointer to the unique hash value
  483. for the identifier. Because the lookup happens before keyword
  484. identification, this field is set even for language keywords like "``for``".
  485. * **TokenKind** --- This indicates the kind of token as classified by the
  486. lexer. This includes things like ``tok::starequal`` (for the "``*=``"
  487. operator), ``tok::ampamp`` for the "``&&``" token, and keyword values (e.g.,
  488. ``tok::kw_for``) for identifiers that correspond to keywords. Note that
  489. some tokens can be spelled multiple ways. For example, C++ supports
  490. "operator keywords", where things like "``and``" are treated exactly like the
  491. "``&&``" operator. In these cases, the kind value is set to ``tok::ampamp``,
  492. which is good for the parser, which doesn't have to consider both forms. For
  493. something that cares about which form is used (e.g., the preprocessor
  494. "stringize" operator) the spelling indicates the original form.
  495. * **Flags** --- There are currently four flags tracked by the
  496. lexer/preprocessor system on a per-token basis:
  497. #. **StartOfLine** --- This was the first token that occurred on its input
  498. source line.
  499. #. **LeadingSpace** --- There was a space character either immediately before
  500. the token or transitively before the token as it was expanded through a
  501. macro. The definition of this flag is very closely defined by the
  502. stringizing requirements of the preprocessor.
  503. #. **DisableExpand** --- This flag is used internally to the preprocessor to
  504. represent identifier tokens which have macro expansion disabled. This
  505. prevents them from being considered as candidates for macro expansion ever
  506. in the future.
  507. #. **NeedsCleaning** --- This flag is set if the original spelling for the
  508. token includes a trigraph or escaped newline. Since this is uncommon,
  509. many pieces of code can fast-path on tokens that did not need cleaning.
  510. One interesting (and somewhat unusual) aspect of normal tokens is that they
  511. don't contain any semantic information about the lexed value. For example, if
  512. the token was a pp-number token, we do not represent the value of the number
  513. that was lexed (this is left for later pieces of code to decide).
  514. Additionally, the lexer library has no notion of typedef names vs variable
  515. names: both are returned as identifiers, and the parser is left to decide
  516. whether a specific identifier is a typedef or a variable (tracking this
  517. requires scope information among other things). The parser can do this
  518. translation by replacing tokens returned by the preprocessor with "Annotation
  519. Tokens".
  520. .. _AnnotationToken:
  521. Annotation Tokens
  522. -----------------
  523. Annotation tokens are tokens that are synthesized by the parser and injected
  524. into the preprocessor's token stream (replacing existing tokens) to record
  525. semantic information found by the parser. For example, if "``foo``" is found
  526. to be a typedef, the "``foo``" ``tok::identifier`` token is replaced with an
  527. ``tok::annot_typename``. This is useful for a couple of reasons: 1) this makes
  528. it easy to handle qualified type names (e.g., "``foo::bar::baz<42>::t``") in
  529. C++ as a single "token" in the parser. 2) if the parser backtracks, the
  530. reparse does not need to redo semantic analysis to determine whether a token
  531. sequence is a variable, type, template, etc.
  532. Annotation tokens are created by the parser and reinjected into the parser's
  533. token stream (when backtracking is enabled). Because they can only exist in
  534. tokens that the preprocessor-proper is done with, it doesn't need to keep
  535. around flags like "start of line" that the preprocessor uses to do its job.
  536. Additionally, an annotation token may "cover" a sequence of preprocessor tokens
  537. (e.g., "``a::b::c``" is five preprocessor tokens). As such, the valid fields
  538. of an annotation token are different than the fields for a normal token (but
  539. they are multiplexed into the normal ``Token`` fields):
  540. * **SourceLocation "Location"** --- The ``SourceLocation`` for the annotation
  541. token indicates the first token replaced by the annotation token. In the
  542. example above, it would be the location of the "``a``" identifier.
  543. * **SourceLocation "AnnotationEndLoc"** --- This holds the location of the last
  544. token replaced with the annotation token. In the example above, it would be
  545. the location of the "``c``" identifier.
  546. * **void* "AnnotationValue"** --- This contains an opaque object that the
  547. parser gets from ``Sema``. The parser merely preserves the information for
  548. ``Sema`` to later interpret based on the annotation token kind.
  549. * **TokenKind "Kind"** --- This indicates the kind of Annotation token this is.
  550. See below for the different valid kinds.
  551. Annotation tokens currently come in three kinds:
  552. #. **tok::annot_typename**: This annotation token represents a resolved
  553. typename token that is potentially qualified. The ``AnnotationValue`` field
  554. contains the ``QualType`` returned by ``Sema::getTypeName()``, possibly with
  555. source location information attached.
  556. #. **tok::annot_cxxscope**: This annotation token represents a C++ scope
  557. specifier, such as "``A::B::``". This corresponds to the grammar
  558. productions "*::*" and "*:: [opt] nested-name-specifier*". The
  559. ``AnnotationValue`` pointer is a ``NestedNameSpecifier *`` returned by the
  560. ``Sema::ActOnCXXGlobalScopeSpecifier`` and
  561. ``Sema::ActOnCXXNestedNameSpecifier`` callbacks.
  562. #. **tok::annot_template_id**: This annotation token represents a C++
  563. template-id such as "``foo<int, 4>``", where "``foo``" is the name of a
  564. template. The ``AnnotationValue`` pointer is a pointer to a ``malloc``'d
  565. ``TemplateIdAnnotation`` object. Depending on the context, a parsed
  566. template-id that names a type might become a typename annotation token (if
  567. all we care about is the named type, e.g., because it occurs in a type
  568. specifier) or might remain a template-id token (if we want to retain more
  569. source location information or produce a new type, e.g., in a declaration of
  570. a class template specialization). template-id annotation tokens that refer
  571. to a type can be "upgraded" to typename annotation tokens by the parser.
  572. As mentioned above, annotation tokens are not returned by the preprocessor,
  573. they are formed on demand by the parser. This means that the parser has to be
  574. aware of cases where an annotation could occur and form it where appropriate.
  575. This is somewhat similar to how the parser handles Translation Phase 6 of C99:
  576. String Concatenation (see C99 5.1.1.2). In the case of string concatenation,
  577. the preprocessor just returns distinct ``tok::string_literal`` and
  578. ``tok::wide_string_literal`` tokens and the parser eats a sequence of them
  579. wherever the grammar indicates that a string literal can occur.
  580. In order to do this, whenever the parser expects a ``tok::identifier`` or
  581. ``tok::coloncolon``, it should call the ``TryAnnotateTypeOrScopeToken`` or
  582. ``TryAnnotateCXXScopeToken`` methods to form the annotation token. These
  583. methods will maximally form the specified annotation tokens and replace the
  584. current token with them, if applicable. If the current tokens is not valid for
  585. an annotation token, it will remain an identifier or "``::``" token.
  586. .. _Lexer:
  587. The ``Lexer`` class
  588. -------------------
  589. The ``Lexer`` class provides the mechanics of lexing tokens out of a source
  590. buffer and deciding what they mean. The ``Lexer`` is complicated by the fact
  591. that it operates on raw buffers that have not had spelling eliminated (this is
  592. a necessity to get decent performance), but this is countered with careful
  593. coding as well as standard performance techniques (for example, the comment
  594. handling code is vectorized on X86 and PowerPC hosts).
  595. The lexer has a couple of interesting modal features:
  596. * The lexer can operate in "raw" mode. This mode has several features that
  597. make it possible to quickly lex the file (e.g., it stops identifier lookup,
  598. doesn't specially handle preprocessor tokens, handles EOF differently, etc).
  599. This mode is used for lexing within an "``#if 0``" block, for example.
  600. * The lexer can capture and return comments as tokens. This is required to
  601. support the ``-C`` preprocessor mode, which passes comments through, and is
  602. used by the diagnostic checker to identifier expect-error annotations.
  603. * The lexer can be in ``ParsingFilename`` mode, which happens when
  604. preprocessing after reading a ``#include`` directive. This mode changes the
  605. parsing of "``<``" to return an "angled string" instead of a bunch of tokens
  606. for each thing within the filename.
  607. * When parsing a preprocessor directive (after "``#``") the
  608. ``ParsingPreprocessorDirective`` mode is entered. This changes the parser to
  609. return EOD at a newline.
  610. * The ``Lexer`` uses a ``LangOptions`` object to know whether trigraphs are
  611. enabled, whether C++ or ObjC keywords are recognized, etc.
  612. In addition to these modes, the lexer keeps track of a couple of other features
  613. that are local to a lexed buffer, which change as the buffer is lexed:
  614. * The ``Lexer`` uses ``BufferPtr`` to keep track of the current character being
  615. lexed.
  616. * The ``Lexer`` uses ``IsAtStartOfLine`` to keep track of whether the next
  617. lexed token will start with its "start of line" bit set.
  618. * The ``Lexer`` keeps track of the current "``#if``" directives that are active
  619. (which can be nested).
  620. * The ``Lexer`` keeps track of an :ref:`MultipleIncludeOpt
  621. <MultipleIncludeOpt>` object, which is used to detect whether the buffer uses
  622. the standard "``#ifndef XX`` / ``#define XX``" idiom to prevent multiple
  623. inclusion. If a buffer does, subsequent includes can be ignored if the
  624. "``XX``" macro is defined.
  625. .. _TokenLexer:
  626. The ``TokenLexer`` class
  627. ------------------------
  628. The ``TokenLexer`` class is a token provider that returns tokens from a list of
  629. tokens that came from somewhere else. It typically used for two things: 1)
  630. returning tokens from a macro definition as it is being expanded 2) returning
  631. tokens from an arbitrary buffer of tokens. The later use is used by
  632. ``_Pragma`` and will most likely be used to handle unbounded look-ahead for the
  633. C++ parser.
  634. .. _MultipleIncludeOpt:
  635. The ``MultipleIncludeOpt`` class
  636. --------------------------------
  637. The ``MultipleIncludeOpt`` class implements a really simple little state
  638. machine that is used to detect the standard "``#ifndef XX`` / ``#define XX``"
  639. idiom that people typically use to prevent multiple inclusion of headers. If a
  640. buffer uses this idiom and is subsequently ``#include``'d, the preprocessor can
  641. simply check to see whether the guarding condition is defined or not. If so,
  642. the preprocessor can completely ignore the include of the header.
  643. The Parser Library
  644. ==================
  645. The AST Library
  646. ===============
  647. .. _Type:
  648. The ``Type`` class and its subclasses
  649. -------------------------------------
  650. The ``Type`` class (and its subclasses) are an important part of the AST.
  651. Types are accessed through the ``ASTContext`` class, which implicitly creates
  652. and uniques them as they are needed. Types have a couple of non-obvious
  653. features: 1) they do not capture type qualifiers like ``const`` or ``volatile``
  654. (see :ref:`QualType <QualType>`), and 2) they implicitly capture typedef
  655. information. Once created, types are immutable (unlike decls).
  656. Typedefs in C make semantic analysis a bit more complex than it would be without
  657. them. The issue is that we want to capture typedef information and represent it
  658. in the AST perfectly, but the semantics of operations need to "see through"
  659. typedefs. For example, consider this code:
  660. .. code-block:: c++
  661. void func() {
  662. typedef int foo;
  663. foo X, *Y;
  664. typedef foo *bar;
  665. bar Z;
  666. *X; // error
  667. **Y; // error
  668. **Z; // error
  669. }
  670. The code above is illegal, and thus we expect there to be diagnostics emitted
  671. on the annotated lines. In this example, we expect to get:
  672. .. code-block:: c++
  673. test.c:6:1: error: indirection requires pointer operand ('foo' invalid)
  674. *X; // error
  675. ^~
  676. test.c:7:1: error: indirection requires pointer operand ('foo' invalid)
  677. **Y; // error
  678. ^~~
  679. test.c:8:1: error: indirection requires pointer operand ('foo' invalid)
  680. **Z; // error
  681. ^~~
  682. While this example is somewhat silly, it illustrates the point: we want to
  683. retain typedef information where possible, so that we can emit errors about
  684. "``std::string``" instead of "``std::basic_string<char, std:...``". Doing this
  685. requires properly keeping typedef information (for example, the type of ``X``
  686. is "``foo``", not "``int``"), and requires properly propagating it through the
  687. various operators (for example, the type of ``*Y`` is "``foo``", not
  688. "``int``"). In order to retain this information, the type of these expressions
  689. is an instance of the ``TypedefType`` class, which indicates that the type of
  690. these expressions is a typedef for "``foo``".
  691. Representing types like this is great for diagnostics, because the
  692. user-specified type is always immediately available. There are two problems
  693. with this: first, various semantic checks need to make judgements about the
  694. *actual structure* of a type, ignoring typedefs. Second, we need an efficient
  695. way to query whether two types are structurally identical to each other,
  696. ignoring typedefs. The solution to both of these problems is the idea of
  697. canonical types.
  698. Canonical Types
  699. ^^^^^^^^^^^^^^^
  700. Every instance of the ``Type`` class contains a canonical type pointer. For
  701. simple types with no typedefs involved (e.g., "``int``", "``int*``",
  702. "``int**``"), the type just points to itself. For types that have a typedef
  703. somewhere in their structure (e.g., "``foo``", "``foo*``", "``foo**``",
  704. "``bar``"), the canonical type pointer points to their structurally equivalent
  705. type without any typedefs (e.g., "``int``", "``int*``", "``int**``", and
  706. "``int*``" respectively).
  707. This design provides a constant time operation (dereferencing the canonical type
  708. pointer) that gives us access to the structure of types. For example, we can
  709. trivially tell that "``bar``" and "``foo*``" are the same type by dereferencing
  710. their canonical type pointers and doing a pointer comparison (they both point
  711. to the single "``int*``" type).
  712. Canonical types and typedef types bring up some complexities that must be
  713. carefully managed. Specifically, the ``isa``/``cast``/``dyn_cast`` operators
  714. generally shouldn't be used in code that is inspecting the AST. For example,
  715. when type checking the indirection operator (unary "``*``" on a pointer), the
  716. type checker must verify that the operand has a pointer type. It would not be
  717. correct to check that with "``isa<PointerType>(SubExpr->getType())``", because
  718. this predicate would fail if the subexpression had a typedef type.
  719. The solution to this problem are a set of helper methods on ``Type``, used to
  720. check their properties. In this case, it would be correct to use
  721. "``SubExpr->getType()->isPointerType()``" to do the check. This predicate will
  722. return true if the *canonical type is a pointer*, which is true any time the
  723. type is structurally a pointer type. The only hard part here is remembering
  724. not to use the ``isa``/``cast``/``dyn_cast`` operations.
  725. The second problem we face is how to get access to the pointer type once we
  726. know it exists. To continue the example, the result type of the indirection
  727. operator is the pointee type of the subexpression. In order to determine the
  728. type, we need to get the instance of ``PointerType`` that best captures the
  729. typedef information in the program. If the type of the expression is literally
  730. a ``PointerType``, we can return that, otherwise we have to dig through the
  731. typedefs to find the pointer type. For example, if the subexpression had type
  732. "``foo*``", we could return that type as the result. If the subexpression had
  733. type "``bar``", we want to return "``foo*``" (note that we do *not* want
  734. "``int*``"). In order to provide all of this, ``Type`` has a
  735. ``getAsPointerType()`` method that checks whether the type is structurally a
  736. ``PointerType`` and, if so, returns the best one. If not, it returns a null
  737. pointer.
  738. This structure is somewhat mystical, but after meditating on it, it will make
  739. sense to you :).
  740. .. _QualType:
  741. The ``QualType`` class
  742. ----------------------
  743. The ``QualType`` class is designed as a trivial value class that is small,
  744. passed by-value and is efficient to query. The idea of ``QualType`` is that it
  745. stores the type qualifiers (``const``, ``volatile``, ``restrict``, plus some
  746. extended qualifiers required by language extensions) separately from the types
  747. themselves. ``QualType`` is conceptually a pair of "``Type*``" and the bits
  748. for these type qualifiers.
  749. By storing the type qualifiers as bits in the conceptual pair, it is extremely
  750. efficient to get the set of qualifiers on a ``QualType`` (just return the field
  751. of the pair), add a type qualifier (which is a trivial constant-time operation
  752. that sets a bit), and remove one or more type qualifiers (just return a
  753. ``QualType`` with the bitfield set to empty).
  754. Further, because the bits are stored outside of the type itself, we do not need
  755. to create duplicates of types with different sets of qualifiers (i.e. there is
  756. only a single heap allocated "``int``" type: "``const int``" and "``volatile
  757. const int``" both point to the same heap allocated "``int``" type). This
  758. reduces the heap size used to represent bits and also means we do not have to
  759. consider qualifiers when uniquing types (:ref:`Type <Type>` does not even
  760. contain qualifiers).
  761. In practice, the two most common type qualifiers (``const`` and ``restrict``)
  762. are stored in the low bits of the pointer to the ``Type`` object, together with
  763. a flag indicating whether extended qualifiers are present (which must be
  764. heap-allocated). This means that ``QualType`` is exactly the same size as a
  765. pointer.
  766. .. _DeclarationName:
  767. Declaration names
  768. -----------------
  769. The ``DeclarationName`` class represents the name of a declaration in Clang.
  770. Declarations in the C family of languages can take several different forms.
  771. Most declarations are named by simple identifiers, e.g., "``f``" and "``x``" in
  772. the function declaration ``f(int x)``. In C++, declaration names can also name
  773. class constructors ("``Class``" in ``struct Class { Class(); }``), class
  774. destructors ("``~Class``"), overloaded operator names ("``operator+``"), and
  775. conversion functions ("``operator void const *``"). In Objective-C,
  776. declaration names can refer to the names of Objective-C methods, which involve
  777. the method name and the parameters, collectively called a *selector*, e.g.,
  778. "``setWidth:height:``". Since all of these kinds of entities --- variables,
  779. functions, Objective-C methods, C++ constructors, destructors, and operators
  780. --- are represented as subclasses of Clang's common ``NamedDecl`` class,
  781. ``DeclarationName`` is designed to efficiently represent any kind of name.
  782. Given a ``DeclarationName`` ``N``, ``N.getNameKind()`` will produce a value
  783. that describes what kind of name ``N`` stores. There are 10 options (all of
  784. the names are inside the ``DeclarationName`` class).
  785. ``Identifier``
  786. The name is a simple identifier. Use ``N.getAsIdentifierInfo()`` to retrieve
  787. the corresponding ``IdentifierInfo*`` pointing to the actual identifier.
  788. ``ObjCZeroArgSelector``, ``ObjCOneArgSelector``, ``ObjCMultiArgSelector``
  789. The name is an Objective-C selector, which can be retrieved as a ``Selector``
  790. instance via ``N.getObjCSelector()``. The three possible name kinds for
  791. Objective-C reflect an optimization within the ``DeclarationName`` class:
  792. both zero- and one-argument selectors are stored as a masked
  793. ``IdentifierInfo`` pointer, and therefore require very little space, since
  794. zero- and one-argument selectors are far more common than multi-argument
  795. selectors (which use a different structure).
  796. ``CXXConstructorName``
  797. The name is a C++ constructor name. Use ``N.getCXXNameType()`` to retrieve
  798. the :ref:`type <QualType>` that this constructor is meant to construct. The
  799. type is always the canonical type, since all constructors for a given type
  800. have the same name.
  801. ``CXXDestructorName``
  802. The name is a C++ destructor name. Use ``N.getCXXNameType()`` to retrieve
  803. the :ref:`type <QualType>` whose destructor is being named. This type is
  804. always a canonical type.
  805. ``CXXConversionFunctionName``
  806. The name is a C++ conversion function. Conversion functions are named
  807. according to the type they convert to, e.g., "``operator void const *``".
  808. Use ``N.getCXXNameType()`` to retrieve the type that this conversion function
  809. converts to. This type is always a canonical type.
  810. ``CXXOperatorName``
  811. The name is a C++ overloaded operator name. Overloaded operators are named
  812. according to their spelling, e.g., "``operator+``" or "``operator new []``".
  813. Use ``N.getCXXOverloadedOperator()`` to retrieve the overloaded operator (a
  814. value of type ``OverloadedOperatorKind``).
  815. ``CXXLiteralOperatorName``
  816. The name is a C++11 user defined literal operator. User defined
  817. Literal operators are named according to the suffix they define,
  818. e.g., "``_foo``" for "``operator "" _foo``". Use
  819. ``N.getCXXLiteralIdentifier()`` to retrieve the corresponding
  820. ``IdentifierInfo*`` pointing to the identifier.
  821. ``CXXUsingDirective``
  822. The name is a C++ using directive. Using directives are not really
  823. NamedDecls, in that they all have the same name, but they are
  824. implemented as such in order to store them in DeclContext
  825. effectively.
  826. ``DeclarationName``\ s are cheap to create, copy, and compare. They require
  827. only a single pointer's worth of storage in the common cases (identifiers,
  828. zero- and one-argument Objective-C selectors) and use dense, uniqued storage
  829. for the other kinds of names. Two ``DeclarationName``\ s can be compared for
  830. equality (``==``, ``!=``) using a simple bitwise comparison, can be ordered
  831. with ``<``, ``>``, ``<=``, and ``>=`` (which provide a lexicographical ordering
  832. for normal identifiers but an unspecified ordering for other kinds of names),
  833. and can be placed into LLVM ``DenseMap``\ s and ``DenseSet``\ s.
  834. ``DeclarationName`` instances can be created in different ways depending on
  835. what kind of name the instance will store. Normal identifiers
  836. (``IdentifierInfo`` pointers) and Objective-C selectors (``Selector``) can be
  837. implicitly converted to ``DeclarationNames``. Names for C++ constructors,
  838. destructors, conversion functions, and overloaded operators can be retrieved
  839. from the ``DeclarationNameTable``, an instance of which is available as
  840. ``ASTContext::DeclarationNames``. The member functions
  841. ``getCXXConstructorName``, ``getCXXDestructorName``,
  842. ``getCXXConversionFunctionName``, and ``getCXXOperatorName``, respectively,
  843. return ``DeclarationName`` instances for the four kinds of C++ special function
  844. names.
  845. .. _DeclContext:
  846. Declaration contexts
  847. --------------------
  848. Every declaration in a program exists within some *declaration context*, such
  849. as a translation unit, namespace, class, or function. Declaration contexts in
  850. Clang are represented by the ``DeclContext`` class, from which the various
  851. declaration-context AST nodes (``TranslationUnitDecl``, ``NamespaceDecl``,
  852. ``RecordDecl``, ``FunctionDecl``, etc.) will derive. The ``DeclContext`` class
  853. provides several facilities common to each declaration context:
  854. Source-centric vs. Semantics-centric View of Declarations
  855. ``DeclContext`` provides two views of the declarations stored within a
  856. declaration context. The source-centric view accurately represents the
  857. program source code as written, including multiple declarations of entities
  858. where present (see the section :ref:`Redeclarations and Overloads
  859. <Redeclarations>`), while the semantics-centric view represents the program
  860. semantics. The two views are kept synchronized by semantic analysis while
  861. the ASTs are being constructed.
  862. Storage of declarations within that context
  863. Every declaration context can contain some number of declarations. For
  864. example, a C++ class (represented by ``RecordDecl``) contains various member
  865. functions, fields, nested types, and so on. All of these declarations will
  866. be stored within the ``DeclContext``, and one can iterate over the
  867. declarations via [``DeclContext::decls_begin()``,
  868. ``DeclContext::decls_end()``). This mechanism provides the source-centric
  869. view of declarations in the context.
  870. Lookup of declarations within that context
  871. The ``DeclContext`` structure provides efficient name lookup for names within
  872. that declaration context. For example, if ``N`` is a namespace we can look
  873. for the name ``N::f`` using ``DeclContext::lookup``. The lookup itself is
  874. based on a lazily-constructed array (for declaration contexts with a small
  875. number of declarations) or hash table (for declaration contexts with more
  876. declarations). The lookup operation provides the semantics-centric view of
  877. the declarations in the context.
  878. Ownership of declarations
  879. The ``DeclContext`` owns all of the declarations that were declared within
  880. its declaration context, and is responsible for the management of their
  881. memory as well as their (de-)serialization.
  882. All declarations are stored within a declaration context, and one can query
  883. information about the context in which each declaration lives. One can
  884. retrieve the ``DeclContext`` that contains a particular ``Decl`` using
  885. ``Decl::getDeclContext``. However, see the section
  886. :ref:`LexicalAndSemanticContexts` for more information about how to interpret
  887. this context information.
  888. .. _Redeclarations:
  889. Redeclarations and Overloads
  890. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  891. Within a translation unit, it is common for an entity to be declared several
  892. times. For example, we might declare a function "``f``" and then later
  893. re-declare it as part of an inlined definition:
  894. .. code-block:: c++
  895. void f(int x, int y, int z = 1);
  896. inline void f(int x, int y, int z) { /* ... */ }
  897. The representation of "``f``" differs in the source-centric and
  898. semantics-centric views of a declaration context. In the source-centric view,
  899. all redeclarations will be present, in the order they occurred in the source
  900. code, making this view suitable for clients that wish to see the structure of
  901. the source code. In the semantics-centric view, only the most recent "``f``"
  902. will be found by the lookup, since it effectively replaces the first
  903. declaration of "``f``".
  904. In the semantics-centric view, overloading of functions is represented
  905. explicitly. For example, given two declarations of a function "``g``" that are
  906. overloaded, e.g.,
  907. .. code-block:: c++
  908. void g();
  909. void g(int);
  910. the ``DeclContext::lookup`` operation will return a
  911. ``DeclContext::lookup_result`` that contains a range of iterators over
  912. declarations of "``g``". Clients that perform semantic analysis on a program
  913. that is not concerned with the actual source code will primarily use this
  914. semantics-centric view.
  915. .. _LexicalAndSemanticContexts:
  916. Lexical and Semantic Contexts
  917. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  918. Each declaration has two potentially different declaration contexts: a
  919. *lexical* context, which corresponds to the source-centric view of the
  920. declaration context, and a *semantic* context, which corresponds to the
  921. semantics-centric view. The lexical context is accessible via
  922. ``Decl::getLexicalDeclContext`` while the semantic context is accessible via
  923. ``Decl::getDeclContext``, both of which return ``DeclContext`` pointers. For
  924. most declarations, the two contexts are identical. For example:
  925. .. code-block:: c++
  926. class X {
  927. public:
  928. void f(int x);
  929. };
  930. Here, the semantic and lexical contexts of ``X::f`` are the ``DeclContext``
  931. associated with the class ``X`` (itself stored as a ``RecordDecl`` AST node).
  932. However, we can now define ``X::f`` out-of-line:
  933. .. code-block:: c++
  934. void X::f(int x = 17) { /* ... */ }
  935. This definition of "``f``" has different lexical and semantic contexts. The
  936. lexical context corresponds to the declaration context in which the actual
  937. declaration occurred in the source code, e.g., the translation unit containing
  938. ``X``. Thus, this declaration of ``X::f`` can be found by traversing the
  939. declarations provided by [``decls_begin()``, ``decls_end()``) in the
  940. translation unit.
  941. The semantic context of ``X::f`` corresponds to the class ``X``, since this
  942. member function is (semantically) a member of ``X``. Lookup of the name ``f``
  943. into the ``DeclContext`` associated with ``X`` will then return the definition
  944. of ``X::f`` (including information about the default argument).
  945. Transparent Declaration Contexts
  946. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  947. In C and C++, there are several contexts in which names that are logically
  948. declared inside another declaration will actually "leak" out into the enclosing
  949. scope from the perspective of name lookup. The most obvious instance of this
  950. behavior is in enumeration types, e.g.,
  951. .. code-block:: c++
  952. enum Color {
  953. Red,
  954. Green,
  955. Blue
  956. };
  957. Here, ``Color`` is an enumeration, which is a declaration context that contains
  958. the enumerators ``Red``, ``Green``, and ``Blue``. Thus, traversing the list of
  959. declarations contained in the enumeration ``Color`` will yield ``Red``,
  960. ``Green``, and ``Blue``. However, outside of the scope of ``Color`` one can
  961. name the enumerator ``Red`` without qualifying the name, e.g.,
  962. .. code-block:: c++
  963. Color c = Red;
  964. There are other entities in C++ that provide similar behavior. For example,
  965. linkage specifications that use curly braces:
  966. .. code-block:: c++
  967. extern "C" {
  968. void f(int);
  969. void g(int);
  970. }
  971. // f and g are visible here
  972. For source-level accuracy, we treat the linkage specification and enumeration
  973. type as a declaration context in which its enclosed declarations ("``Red``",
  974. "``Green``", and "``Blue``"; "``f``" and "``g``") are declared. However, these
  975. declarations are visible outside of the scope of the declaration context.
  976. These language features (and several others, described below) have roughly the
  977. same set of requirements: declarations are declared within a particular lexical
  978. context, but the declarations are also found via name lookup in scopes
  979. enclosing the declaration itself. This feature is implemented via
  980. *transparent* declaration contexts (see
  981. ``DeclContext::isTransparentContext()``), whose declarations are visible in the
  982. nearest enclosing non-transparent declaration context. This means that the
  983. lexical context of the declaration (e.g., an enumerator) will be the
  984. transparent ``DeclContext`` itself, as will the semantic context, but the
  985. declaration will be visible in every outer context up to and including the
  986. first non-transparent declaration context (since transparent declaration
  987. contexts can be nested).
  988. The transparent ``DeclContext``\ s are:
  989. * Enumerations (but not C++11 "scoped enumerations"):
  990. .. code-block:: c++
  991. enum Color {
  992. Red,
  993. Green,
  994. Blue
  995. };
  996. // Red, Green, and Blue are in scope
  997. * C++ linkage specifications:
  998. .. code-block:: c++
  999. extern "C" {
  1000. void f(int);
  1001. void g(int);
  1002. }
  1003. // f and g are in scope
  1004. * Anonymous unions and structs:
  1005. .. code-block:: c++
  1006. struct LookupTable {
  1007. bool IsVector;
  1008. union {
  1009. std::vector<Item> *Vector;
  1010. std::set<Item> *Set;
  1011. };
  1012. };
  1013. LookupTable LT;
  1014. LT.Vector = 0; // Okay: finds Vector inside the unnamed union
  1015. * C++11 inline namespaces:
  1016. .. code-block:: c++
  1017. namespace mylib {
  1018. inline namespace debug {
  1019. class X;
  1020. }
  1021. }
  1022. mylib::X *xp; // okay: mylib::X refers to mylib::debug::X
  1023. .. _MultiDeclContext:
  1024. Multiply-Defined Declaration Contexts
  1025. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1026. C++ namespaces have the interesting --- and, so far, unique --- property that
  1027. the namespace can be defined multiple times, and the declarations provided by
  1028. each namespace definition are effectively merged (from the semantic point of
  1029. view). For example, the following two code snippets are semantically
  1030. indistinguishable:
  1031. .. code-block:: c++
  1032. // Snippet #1:
  1033. namespace N {
  1034. void f();
  1035. }
  1036. namespace N {
  1037. void f(int);
  1038. }
  1039. // Snippet #2:
  1040. namespace N {
  1041. void f();
  1042. void f(int);
  1043. }
  1044. In Clang's representation, the source-centric view of declaration contexts will
  1045. actually have two separate ``NamespaceDecl`` nodes in Snippet #1, each of which
  1046. is a declaration context that contains a single declaration of "``f``".
  1047. However, the semantics-centric view provided by name lookup into the namespace
  1048. ``N`` for "``f``" will return a ``DeclContext::lookup_result`` that contains a
  1049. range of iterators over declarations of "``f``".
  1050. ``DeclContext`` manages multiply-defined declaration contexts internally. The
  1051. function ``DeclContext::getPrimaryContext`` retrieves the "primary" context for
  1052. a given ``DeclContext`` instance, which is the ``DeclContext`` responsible for
  1053. maintaining the lookup table used for the semantics-centric view. Given the
  1054. primary context, one can follow the chain of ``DeclContext`` nodes that define
  1055. additional declarations via ``DeclContext::getNextContext``. Note that these
  1056. functions are used internally within the lookup and insertion methods of the
  1057. ``DeclContext``, so the vast majority of clients can ignore them.
  1058. .. _CFG:
  1059. The ``CFG`` class
  1060. -----------------
  1061. The ``CFG`` class is designed to represent a source-level control-flow graph
  1062. for a single statement (``Stmt*``). Typically instances of ``CFG`` are
  1063. constructed for function bodies (usually an instance of ``CompoundStmt``), but
  1064. can also be instantiated to represent the control-flow of any class that
  1065. subclasses ``Stmt``, which includes simple expressions. Control-flow graphs
  1066. are especially useful for performing `flow- or path-sensitive
  1067. <http://en.wikipedia.org/wiki/Data_flow_analysis#Sensitivities>`_ program
  1068. analyses on a given function.
  1069. Basic Blocks
  1070. ^^^^^^^^^^^^
  1071. Concretely, an instance of ``CFG`` is a collection of basic blocks. Each basic
  1072. block is an instance of ``CFGBlock``, which simply contains an ordered sequence
  1073. of ``Stmt*`` (each referring to statements in the AST). The ordering of
  1074. statements within a block indicates unconditional flow of control from one
  1075. statement to the next. :ref:`Conditional control-flow
  1076. <ConditionalControlFlow>` is represented using edges between basic blocks. The
  1077. statements within a given ``CFGBlock`` can be traversed using the
  1078. ``CFGBlock::*iterator`` interface.
  1079. A ``CFG`` object owns the instances of ``CFGBlock`` within the control-flow
  1080. graph it represents. Each ``CFGBlock`` within a CFG is also uniquely numbered
  1081. (accessible via ``CFGBlock::getBlockID()``). Currently the number is based on
  1082. the ordering the blocks were created, but no assumptions should be made on how
  1083. ``CFGBlocks`` are numbered other than their numbers are unique and that they
  1084. are numbered from 0..N-1 (where N is the number of basic blocks in the CFG).
  1085. Entry and Exit Blocks
  1086. ^^^^^^^^^^^^^^^^^^^^^
  1087. Each instance of ``CFG`` contains two special blocks: an *entry* block
  1088. (accessible via ``CFG::getEntry()``), which has no incoming edges, and an
  1089. *exit* block (accessible via ``CFG::getExit()``), which has no outgoing edges.
  1090. Neither block contains any statements, and they serve the role of providing a
  1091. clear entrance and exit for a body of code such as a function body. The
  1092. presence of these empty blocks greatly simplifies the implementation of many
  1093. analyses built on top of CFGs.
  1094. .. _ConditionalControlFlow:
  1095. Conditional Control-Flow
  1096. ^^^^^^^^^^^^^^^^^^^^^^^^
  1097. Conditional control-flow (such as those induced by if-statements and loops) is
  1098. represented as edges between ``CFGBlocks``. Because different C language
  1099. constructs can induce control-flow, each ``CFGBlock`` also records an extra
  1100. ``Stmt*`` that represents the *terminator* of the block. A terminator is
  1101. simply the statement that caused the control-flow, and is used to identify the
  1102. nature of the conditional control-flow between blocks. For example, in the
  1103. case of an if-statement, the terminator refers to the ``IfStmt`` object in the
  1104. AST that represented the given branch.
  1105. To illustrate, consider the following code example:
  1106. .. code-block:: c++
  1107. int foo(int x) {
  1108. x = x + 1;
  1109. if (x > 2)
  1110. x++;
  1111. else {
  1112. x += 2;
  1113. x *= 2;
  1114. }
  1115. return x;
  1116. }
  1117. After invoking the parser+semantic analyzer on this code fragment, the AST of
  1118. the body of ``foo`` is referenced by a single ``Stmt*``. We can then construct
  1119. an instance of ``CFG`` representing the control-flow graph of this function
  1120. body by single call to a static class method:
  1121. .. code-block:: c++
  1122. Stmt *FooBody = ...
  1123. CFG *FooCFG = CFG::buildCFG(FooBody);
  1124. It is the responsibility of the caller of ``CFG::buildCFG`` to ``delete`` the
  1125. returned ``CFG*`` when the CFG is no longer needed.
  1126. Along with providing an interface to iterate over its ``CFGBlocks``, the
  1127. ``CFG`` class also provides methods that are useful for debugging and
  1128. visualizing CFGs. For example, the method ``CFG::dump()`` dumps a
  1129. pretty-printed version of the CFG to standard error. This is especially useful
  1130. when one is using a debugger such as gdb. For example, here is the output of
  1131. ``FooCFG->dump()``:
  1132. .. code-block:: c++
  1133. [ B5 (ENTRY) ]
  1134. Predecessors (0):
  1135. Successors (1): B4
  1136. [ B4 ]
  1137. 1: x = x + 1
  1138. 2: (x > 2)
  1139. T: if [B4.2]
  1140. Predecessors (1): B5
  1141. Successors (2): B3 B2
  1142. [ B3 ]
  1143. 1: x++
  1144. Predecessors (1): B4
  1145. Successors (1): B1
  1146. [ B2 ]
  1147. 1: x += 2
  1148. 2: x *= 2
  1149. Predecessors (1): B4
  1150. Successors (1): B1
  1151. [ B1 ]
  1152. 1: return x;
  1153. Predecessors (2): B2 B3
  1154. Successors (1): B0
  1155. [ B0 (EXIT) ]
  1156. Predecessors (1): B1
  1157. Successors (0):
  1158. For each block, the pretty-printed output displays for each block the number of
  1159. *predecessor* blocks (blocks that have outgoing control-flow to the given
  1160. block) and *successor* blocks (blocks that have control-flow that have incoming
  1161. control-flow from the given block). We can also clearly see the special entry
  1162. and exit blocks at the beginning and end of the pretty-printed output. For the
  1163. entry block (block B5), the number of predecessor blocks is 0, while for the
  1164. exit block (block B0) the number of successor blocks is 0.
  1165. The most interesting block here is B4, whose outgoing control-flow represents
  1166. the branching caused by the sole if-statement in ``foo``. Of particular
  1167. interest is the second statement in the block, ``(x > 2)``, and the terminator,
  1168. printed as ``if [B4.2]``. The second statement represents the evaluation of
  1169. the condition of the if-statement, which occurs before the actual branching of
  1170. control-flow. Within the ``CFGBlock`` for B4, the ``Stmt*`` for the second
  1171. statement refers to the actual expression in the AST for ``(x > 2)``. Thus
  1172. pointers to subclasses of ``Expr`` can appear in the list of statements in a
  1173. block, and not just subclasses of ``Stmt`` that refer to proper C statements.
  1174. The terminator of block B4 is a pointer to the ``IfStmt`` object in the AST.
  1175. The pretty-printer outputs ``if [B4.2]`` because the condition expression of
  1176. the if-statement has an actual place in the basic block, and thus the
  1177. terminator is essentially *referring* to the expression that is the second
  1178. statement of block B4 (i.e., B4.2). In this manner, conditions for
  1179. control-flow (which also includes conditions for loops and switch statements)
  1180. are hoisted into the actual basic block.
  1181. .. Implicit Control-Flow
  1182. .. ^^^^^^^^^^^^^^^^^^^^^
  1183. .. A key design principle of the ``CFG`` class was to not require any
  1184. .. transformations to the AST in order to represent control-flow. Thus the
  1185. .. ``CFG`` does not perform any "lowering" of the statements in an AST: loops
  1186. .. are not transformed into guarded gotos, short-circuit operations are not
  1187. .. converted to a set of if-statements, and so on.
  1188. Constant Folding in the Clang AST
  1189. ---------------------------------
  1190. There are several places where constants and constant folding matter a lot to
  1191. the Clang front-end. First, in general, we prefer the AST to retain the source
  1192. code as close to how the user wrote it as possible. This means that if they
  1193. wrote "``5+4``", we want to keep the addition and two constants in the AST, we
  1194. don't want to fold to "``9``". This means that constant folding in various
  1195. ways turns into a tree walk that needs to handle the various cases.
  1196. However, there are places in both C and C++ that require constants to be
  1197. folded. For example, the C standard defines what an "integer constant
  1198. expression" (i-c-e) is with very precise and specific requirements. The
  1199. language then requires i-c-e's in a lot of places (for example, the size of a
  1200. bitfield, the value for a case statement, etc). For these, we have to be able
  1201. to constant fold the constants, to do semantic checks (e.g., verify bitfield
  1202. size is non-negative and that case statements aren't duplicated). We aim for
  1203. Clang to be very pedantic about this, diagnosing cases when the code does not
  1204. use an i-c-e where one is required, but accepting the code unless running with
  1205. ``-pedantic-errors``.
  1206. Things get a little bit more tricky when it comes to compatibility with
  1207. real-world source code. Specifically, GCC has historically accepted a huge
  1208. superset of expressions as i-c-e's, and a lot of real world code depends on
  1209. this unfortuate accident of history (including, e.g., the glibc system
  1210. headers). GCC accepts anything its "fold" optimizer is capable of reducing to
  1211. an integer constant, which means that the definition of what it accepts changes
  1212. as its optimizer does. One example is that GCC accepts things like "``case
  1213. X-X:``" even when ``X`` is a variable, because it can fold this to 0.
  1214. Another issue are how constants interact with the extensions we support, such
  1215. as ``__builtin_constant_p``, ``__builtin_inf``, ``__extension__`` and many
  1216. others. C99 obviously does not specify the semantics of any of these
  1217. extensions, and the definition of i-c-e does not include them. However, these
  1218. extensions are often used in real code, and we have to have a way to reason
  1219. about them.
  1220. Finally, this is not just a problem for semantic analysis. The code generator
  1221. and other clients have to be able to fold constants (e.g., to initialize global
  1222. variables) and has to handle a superset of what C99 allows. Further, these
  1223. clients can benefit from extended information. For example, we know that
  1224. "``foo() || 1``" always evaluates to ``true``, but we can't replace the
  1225. expression with ``true`` because it has side effects.
  1226. Implementation Approach
  1227. ^^^^^^^^^^^^^^^^^^^^^^^
  1228. After trying several different approaches, we've finally converged on a design
  1229. (Note, at the time of this writing, not all of this has been implemented,
  1230. consider this a design goal!). Our basic approach is to define a single
  1231. recursive method evaluation method (``Expr::Evaluate``), which is implemented
  1232. in ``AST/ExprConstant.cpp``. Given an expression with "scalar" type (integer,
  1233. fp, complex, or pointer) this method returns the following information:
  1234. * Whether the expression is an integer constant expression, a general constant
  1235. that was folded but has no side effects, a general constant that was folded
  1236. but that does have side effects, or an uncomputable/unfoldable value.
  1237. * If the expression was computable in any way, this method returns the
  1238. ``APValue`` for the result of the expression.
  1239. * If the expression is not evaluatable at all, this method returns information
  1240. on one of the problems with the expression. This includes a
  1241. ``SourceLocation`` for where the problem is, and a diagnostic ID that explains
  1242. the problem. The diagnostic should have ``ERROR`` type.
  1243. * If the expression is not an integer constant expression, this method returns
  1244. information on one of the problems with the expression. This includes a
  1245. ``SourceLocation`` for where the problem is, and a diagnostic ID that
  1246. explains the problem. The diagnostic should have ``EXTENSION`` type.
  1247. This information gives various clients the flexibility that they want, and we
  1248. will eventually have some helper methods for various extensions. For example,
  1249. ``Sema`` should have a ``Sema::VerifyIntegerConstantExpression`` method, which
  1250. calls ``Evaluate`` on the expression. If the expression is not foldable, the
  1251. error is emitted, and it would return ``true``. If the expression is not an
  1252. i-c-e, the ``EXTENSION`` diagnostic is emitted. Finally it would return
  1253. ``false`` to indicate that the AST is OK.
  1254. Other clients can use the information in other ways, for example, codegen can
  1255. just use expressions that are foldable in any way.
  1256. Extensions
  1257. ^^^^^^^^^^
  1258. This section describes how some of the various extensions Clang supports
  1259. interacts with constant evaluation:
  1260. * ``__extension__``: The expression form of this extension causes any
  1261. evaluatable subexpression to be accepted as an integer constant expression.
  1262. * ``__builtin_constant_p``: This returns true (as an integer constant
  1263. expression) if the operand evaluates to either a numeric value (that is, not
  1264. a pointer cast to integral type) of integral, enumeration, floating or
  1265. complex type, or if it evaluates to the address of the first character of a
  1266. string literal (possibly cast to some other type). As a special case, if
  1267. ``__builtin_constant_p`` is the (potentially parenthesized) condition of a
  1268. conditional operator expression ("``?:``"), only the true side of the
  1269. conditional operator is considered, and it is evaluated with full constant
  1270. folding.
  1271. * ``__builtin_choose_expr``: The condition is required to be an integer
  1272. constant expression, but we accept any constant as an "extension of an
  1273. extension". This only evaluates one operand depending on which way the
  1274. condition evaluates.
  1275. * ``__builtin_classify_type``: This always returns an integer constant
  1276. expression.
  1277. * ``__builtin_inf, nan, ...``: These are treated just like a floating-point
  1278. literal.
  1279. * ``__builtin_abs, copysign, ...``: These are constant folded as general
  1280. constant expressions.
  1281. * ``__builtin_strlen`` and ``strlen``: These are constant folded as integer
  1282. constant expressions if the argument is a string literal.
  1283. How to change Clang
  1284. ===================
  1285. How to add an attribute
  1286. -----------------------
  1287. Attribute Basics
  1288. ^^^^^^^^^^^^^^^^
  1289. Attributes in clang come in two forms: parsed form, and semantic form. Both
  1290. forms are represented via a tablegen definition of the attribute, specified in
  1291. Attr.td.
  1292. ``include/clang/Basic/Attr.td``
  1293. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1294. First, add your attribute to the `include/clang/Basic/Attr.td
  1295. <http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/Attr.td?view=markup>`_
  1296. file.
  1297. Each attribute gets a ``def`` inheriting from ``Attr`` or one of its
  1298. subclasses. ``InheritableAttr`` means that the attribute also applies to
  1299. subsequent declarations of the same name. ``InheritableParamAttr`` is similar
  1300. to ``InheritableAttr``, except that the attribute is written on a parameter
  1301. instead of a declaration, type or statement. Attributes inheriting from
  1302. ``TypeAttr`` are pure type attributes which generally are not given a
  1303. representation in the AST. Attributes inheriting from ``TargetSpecificAttr``
  1304. are attributes specific to one or more target architectures. An attribute that
  1305. inherits from ``IgnoredAttr`` is parsed, but will generate an ignored attribute
  1306. diagnostic when used. The attribute type may be useful when an attribute is
  1307. supported by another vendor, but not supported by clang.
  1308. ``Spellings`` lists the strings that can appear in ``__attribute__((here))`` or
  1309. ``[[here]]``. All such strings will be synonymous. Possible ``Spellings``
  1310. are: ``GNU`` (for use with GNU-style __attribute__ spellings), ``Declspec``
  1311. (for use with Microsoft Visual Studio-style __declspec spellings), ``CXX11`
  1312. (for use with C++11-style [[foo]] and [[foo::bar]] spellings), and ``Keyword``
  1313. (for use with attributes that are implemented as keywords, like C++11's
  1314. ``override`` or ``final``). If you want to allow the ``[[]]`` C++11 syntax, you
  1315. have to define a list of ``Namespaces``, which will let users write
  1316. ``[[namespace::spelling]]``. Using the empty string for a namespace will allow
  1317. users to write just the spelling with no "``::``". Attributes which g++-4.8
  1318. or later accepts should also have a ``CXX11<"gnu", "spelling">`` spelling.
  1319. ``Subjects`` restricts what kinds of AST node to which this attribute can
  1320. appertain (roughly, attach). The subjects are specified via a ``SubjectList``,
  1321. which specify the list of subjects. Additionally, subject-related diagnostics
  1322. can be specified to be warnings or errors, with the default being a warning.
  1323. The diagnostics displayed to the user are automatically determined based on
  1324. the subjects in the list, but a custom diagnostic parameter can also be
  1325. specified in the ``SubjectList``. The diagnostics generated for subject list
  1326. violations are either ``diag::warn_attribute_wrong_decl_type`` or
  1327. ``diag::err_attribute_wrong_decl_type``, and the parameter enumeration is
  1328. found in `include/clang/Sema/AttributeList.h
  1329. <http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/AttributeList.h?view=markup>`_
  1330. If you add new Decl nodes to the ``SubjectList``, you may need to update the
  1331. logic used to automatically determine the diagnostic parameter in `utils/TableGen/ClangAttrEmitter.cpp
  1332. <http://llvm.org/viewvc/llvm-project/cfe/trunk/utils/TableGen/ClangAttrEmitter.cpp?view=markup>`_.
  1333. Diagnostic checking for attribute subject lists is automated except when
  1334. ``HasCustomParsing`` is set to ``1``.
  1335. By default, all subjects in the SubjectList must either be a Decl node defined
  1336. in ``DeclNodes.td``, or a statement node defined in ``StmtNodes.td``. However,
  1337. more complex subjects can be created by creating a ``SubsetSubject`` object.
  1338. Each such object has a base subject which it appertains to (which must be a
  1339. Decl or Stmt node, and not a SubsetSubject node), and some custom code which is
  1340. called when determining whether an attribute appertains to the subject. For
  1341. instance, a ``NonBitField`` SubsetSubject appertains to a ``FieldDecl``, and
  1342. tests whether the given FieldDecl is a bit field. When a SubsetSubject is
  1343. specified in a SubjectList, a custom diagnostic parameter must also be provided.
  1344. ``Args`` names the arguments the attribute takes, in order. If ``Args`` is
  1345. ``[StringArgument<"Arg1">, IntArgument<"Arg2">]`` then
  1346. ``__attribute__((myattribute("Hello", 3)))`` will be a valid use. Attribute
  1347. arguments specify both the parsed form and the semantic form of the attribute.
  1348. The previous example shows an attribute which requires two attributes while
  1349. parsing, and the Attr subclass' constructor for the attribute will require a
  1350. string and integer argument.
  1351. Diagnostic checking for argument counts is automated except when
  1352. ``HasCustomParsing`` is set to ``1``, or when the attribute uses an optional or
  1353. variadic argument. Diagnostic checking for argument semantics is not automated.
  1354. If the parsed form of the attribute is more complex, or differs from the
  1355. semantic form, the ``HasCustomParsing`` bit can be set to ``1`` for the class,
  1356. and the parsing code in `Parser::ParseGNUAttributeArgs
  1357. <http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Parse/ParseDecl.cpp?view=markup>`_
  1358. can be updated for the special case. Note that this only applies to arguments
  1359. with a GNU spelling -- attributes with a __declspec spelling currently ignore
  1360. this flag and are handled by ``Parser::ParseMicrosoftDeclSpec``.
  1361. Custom accessors can be generated for an attribute based on the spelling list
  1362. for that attribute. For instance, if an attribute has two different spellings:
  1363. 'Foo' and 'Bar', accessors can be created:
  1364. ``[Accessor<"isFoo", [GNU<"Foo">]>, Accessor<"isBar", [GNU<"Bar">]>]``
  1365. These accessors will be generated on the semantic form of the attribute,
  1366. accepting no arguments and returning a Boolean.
  1367. Attributes which do not require an AST node should set the ``ASTNode`` field to
  1368. ``0`` to avoid polluting the AST. Note that anything inheriting from
  1369. ``TypeAttr`` or ``IgnoredAttr`` automatically do not generate an AST node. All
  1370. other attributes generate an AST node by default. The AST node is the semantic
  1371. representation of the attribute.
  1372. Attributes which do not require custom semantic handling should set the
  1373. ``SemaHandler`` field to ``0``. Note that anything inheriting from
  1374. ``IgnoredAttr`` automatically do not get a semantic handler. All other
  1375. attributes are assumed to use a semantic handler by default. Attributes
  1376. without a semantic handler are not given a parsed attribute Kind enumeration.
  1377. The ``LangOpts`` field can be used to specify a list of language options
  1378. required by the attribute. For instance, all of the CUDA-specific attributes
  1379. specify ``[CUDA]`` for the ``LangOpts`` field, and when the CUDA language
  1380. option is not enabled, an "attribute ignored" warning diagnostic is emitted.
  1381. Since language options are not table generated nodes, new language options must
  1382. be created manually and should specify the spelling used by ``LangOptions`` class.
  1383. Target-specific attribute sometimes share a spelling with other attributes in
  1384. different targets. For instance, the ARM and MSP430 targets both have an
  1385. attribute spelled ``GNU<"interrupt">``, but with different parsing and semantic
  1386. requirements. To support this feature, an attribute inheriting from
  1387. ``TargetSpecificAttribute`` make specify a ``ParseKind`` field. This field
  1388. should be the same value between all arguments sharing a spelling, and
  1389. corresponds to the parsed attribute's Kind enumeration. This allows attributes
  1390. to share a parsed attribute kind, but have distinct semantic attribute classes.
  1391. For instance, ``AttributeList::AT_Interrupt`` is the shared parsed attribute
  1392. kind, but ARMInterruptAttr and MSP430InterruptAttr are the semantic attributes
  1393. generated.
  1394. By default, when declarations are merging attributes, an attribute will not be
  1395. duplicated. However, if an attribute can be duplicated during this merging
  1396. stage, set ``DuplicatesAllowedWhileMerging`` to ``1``, and the attribute will
  1397. be merged.
  1398. By default, attribute arguments are parsed in an evaluated context. If the
  1399. arguments for an attribute should be parsed in an unevaluated context (akin to
  1400. the way the argument to a ``sizeof`` expression is parsed), you can set
  1401. ``ParseArgumentsAsUnevaluated`` to ``1``.
  1402. If additional functionality is desired for the semantic form of the attribute,
  1403. the ``AdditionalMembers`` field specifies code to be copied verbatim into the
  1404. semantic attribute class object.
  1405. All attributes must have one or more form of documentation, which is provided
  1406. in the ``Documentation`` list. Generally, the documentation for an attribute
  1407. is a stand-alone definition in `include/clang/Basic/AttrDocs.td
  1408. <http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/AttdDocs.td?view=markup>`_
  1409. that is named after the attribute being documented. Each documentation element
  1410. is given a ``Category`` (variable, function, or type) and ``Content``. A single
  1411. attribute may contain multiple documentation elements for distinct categories.
  1412. For instance, an attribute which can appertain to both function and types (such
  1413. as a calling convention attribute), should contain two documentation elements.
  1414. The ``Content`` for an attribute uses reStructuredText (RST) syntax.
  1415. If an attribute is used internally by the compiler, but is not written by users
  1416. (such as attributes with an empty spelling list), it can use the
  1417. ``Undocumented`` documentation element.
  1418. Boilerplate
  1419. ^^^^^^^^^^^
  1420. All semantic processing of declaration attributes happens in `lib/Sema/SemaDeclAttr.cpp
  1421. <http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaDeclAttr.cpp?view=markup>`_,
  1422. and generally starts in the ``ProcessDeclAttribute`` function. If your
  1423. attribute is a "simple" attribute -- meaning that it requires no custom
  1424. semantic processing aside from what is automatically provided for you, you can
  1425. add a call to ``handleSimpleAttribute<YourAttr>(S, D, Attr);`` to the switch
  1426. statement. Otherwise, write a new ``handleYourAttr()`` function, and add that
  1427. to the switch statement.
  1428. If your attribute causes extra warnings to fire, define a ``DiagGroup`` in
  1429. `include/clang/Basic/DiagnosticGroups.td
  1430. <http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticGroups.td?view=markup>`_
  1431. named after the attribute's ``Spelling`` with "_"s replaced by "-"s. If you're
  1432. only defining one diagnostic, you can skip ``DiagnosticGroups.td`` and use
  1433. ``InGroup<DiagGroup<"your-attribute">>`` directly in `DiagnosticSemaKinds.td
  1434. <http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td?view=markup>`_
  1435. All semantic diagnostics generated for your attribute, including automatically-
  1436. generated ones (such as subjects and argument counts), should have a
  1437. corresponding test case.
  1438. The meat of your attribute
  1439. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  1440. Find an appropriate place in Clang to do whatever your attribute needs to do.
  1441. Check for the attribute's presence using ``Decl::getAttr<YourAttr>()``.
  1442. Update the :doc:`LanguageExtensions` document to describe your new attribute.
  1443. How to add an expression or statement
  1444. -------------------------------------
  1445. Expressions and statements are one of the most fundamental constructs within a
  1446. compiler, because they interact with many different parts of the AST, semantic
  1447. analysis, and IR generation. Therefore, adding a new expression or statement
  1448. kind into Clang requires some care. The following list details the various
  1449. places in Clang where an expression or statement needs to be introduced, along
  1450. with patterns to follow to ensure that the new expression or statement works
  1451. well across all of the C languages. We focus on expressions, but statements
  1452. are similar.
  1453. #. Introduce parsing actions into the parser. Recursive-descent parsing is
  1454. mostly self-explanatory, but there are a few things that are worth keeping
  1455. in mind:
  1456. * Keep as much source location information as possible! You'll want it later
  1457. to produce great diagnostics and support Clang's various features that map
  1458. between source code and the AST.
  1459. * Write tests for all of the "bad" parsing cases, to make sure your recovery
  1460. is good. If you have matched delimiters (e.g., parentheses, square
  1461. brackets, etc.), use ``Parser::BalancedDelimiterTracker`` to give nice
  1462. diagnostics when things go wrong.
  1463. #. Introduce semantic analysis actions into ``Sema``. Semantic analysis should
  1464. always involve two functions: an ``ActOnXXX`` function that will be called
  1465. directly from the parser, and a ``BuildXXX`` function that performs the
  1466. actual semantic analysis and will (eventually!) build the AST node. It's
  1467. fairly common for the ``ActOnCXX`` function to do very little (often just
  1468. some minor translation from the parser's representation to ``Sema``'s
  1469. representation of the same thing), but the separation is still important:
  1470. C++ template instantiation, for example, should always call the ``BuildXXX``
  1471. variant. Several notes on semantic analysis before we get into construction
  1472. of the AST:
  1473. * Your expression probably involves some types and some subexpressions.
  1474. Make sure to fully check that those types, and the types of those
  1475. subexpressions, meet your expectations. Add implicit conversions where
  1476. necessary to make sure that all of the types line up exactly the way you
  1477. want them. Write extensive tests to check that you're getting good
  1478. diagnostics for mistakes and that you can use various forms of
  1479. subexpressions with your expression.
  1480. * When type-checking a type or subexpression, make sure to first check
  1481. whether the type is "dependent" (``Type::isDependentType()``) or whether a
  1482. subexpression is type-dependent (``Expr::isTypeDependent()``). If any of
  1483. these return ``true``, then you're inside a template and you can't do much
  1484. type-checking now. That's normal, and your AST node (when you get there)
  1485. will have to deal with this case. At this point, you can write tests that
  1486. use your expression within templates, but don't try to instantiate the
  1487. templates.
  1488. * For each subexpression, be sure to call ``Sema::CheckPlaceholderExpr()``
  1489. to deal with "weird" expressions that don't behave well as subexpressions.
  1490. Then, determine whether you need to perform lvalue-to-rvalue conversions
  1491. (``Sema::DefaultLvalueConversions``) or the usual unary conversions
  1492. (``Sema::UsualUnaryConversions``), for places where the subexpression is
  1493. producing a value you intend to use.
  1494. * Your ``BuildXXX`` function will probably just return ``ExprError()`` at
  1495. this point, since you don't have an AST. That's perfectly fine, and
  1496. shouldn't impact your testing.
  1497. #. Introduce an AST node for your new expression. This starts with declaring
  1498. the node in ``include/Basic/StmtNodes.td`` and creating a new class for your
  1499. expression in the appropriate ``include/AST/Expr*.h`` header. It's best to
  1500. look at the class for a similar expression to get ideas, and there are some
  1501. specific things to watch for:
  1502. * If you need to allocate memory, use the ``ASTContext`` allocator to
  1503. allocate memory. Never use raw ``malloc`` or ``new``, and never hold any
  1504. resources in an AST node, because the destructor of an AST node is never
  1505. called.
  1506. * Make sure that ``getSourceRange()`` covers the exact source range of your
  1507. expression. This is needed for diagnostics and for IDE support.
  1508. * Make sure that ``children()`` visits all of the subexpressions. This is
  1509. important for a number of features (e.g., IDE support, C++ variadic
  1510. templates). If you have sub-types, you'll also need to visit those
  1511. sub-types in ``RecursiveASTVisitor`` and ``DataRecursiveASTVisitor``.
  1512. * Add printing support (``StmtPrinter.cpp``) for your expression.
  1513. * Add profiling support (``StmtProfile.cpp``) for your AST node, noting the
  1514. distinguishing (non-source location) characteristics of an instance of
  1515. your expression. Omitting this step will lead to hard-to-diagnose
  1516. failures regarding matching of template declarations.
  1517. * Add serialization support (``ASTReaderStmt.cpp``, ``ASTWriterStmt.cpp``)
  1518. for your AST node.
  1519. #. Teach semantic analysis to build your AST node. At this point, you can wire
  1520. up your ``Sema::BuildXXX`` function to actually create your AST. A few
  1521. things to check at this point:
  1522. * If your expression can construct a new C++ class or return a new
  1523. Objective-C object, be sure to update and then call
  1524. ``Sema::MaybeBindToTemporary`` for your just-created AST node to be sure
  1525. that the object gets properly destructed. An easy way to test this is to
  1526. return a C++ class with a private destructor: semantic analysis should
  1527. flag an error here with the attempt to call the destructor.
  1528. * Inspect the generated AST by printing it using ``clang -cc1 -ast-print``,
  1529. to make sure you're capturing all of the important information about how
  1530. the AST was written.
  1531. * Inspect the generated AST under ``clang -cc1 -ast-dump`` to verify that
  1532. all of the types in the generated AST line up the way you want them.
  1533. Remember that clients of the AST should never have to "think" to
  1534. understand what's going on. For example, all implicit conversions should
  1535. show up explicitly in the AST.
  1536. * Write tests that use your expression as a subexpression of other,
  1537. well-known expressions. Can you call a function using your expression as
  1538. an argument? Can you use the ternary operator?
  1539. #. Teach code generation to create IR to your AST node. This step is the first
  1540. (and only) that requires knowledge of LLVM IR. There are several things to
  1541. keep in mind:
  1542. * Code generation is separated into scalar/aggregate/complex and
  1543. lvalue/rvalue paths, depending on what kind of result your expression
  1544. produces. On occasion, this requires some careful factoring of code to
  1545. avoid duplication.
  1546. * ``CodeGenFunction`` contains functions ``ConvertType`` and
  1547. ``ConvertTypeForMem`` that convert Clang's types (``clang::Type*`` or
  1548. ``clang::QualType``) to LLVM types. Use the former for values, and the
  1549. later for memory locations: test with the C++ "``bool``" type to check
  1550. this. If you find that you are having to use LLVM bitcasts to make the
  1551. subexpressions of your expression have the type that your expression
  1552. expects, STOP! Go fix semantic analysis and the AST so that you don't
  1553. need these bitcasts.
  1554. * The ``CodeGenFunction`` class has a number of helper functions to make
  1555. certain operations easy, such as generating code to produce an lvalue or
  1556. an rvalue, or to initialize a memory location with a given value. Prefer
  1557. to use these functions rather than directly writing loads and stores,
  1558. because these functions take care of some of the tricky details for you
  1559. (e.g., for exceptions).
  1560. * If your expression requires some special behavior in the event of an
  1561. exception, look at the ``push*Cleanup`` functions in ``CodeGenFunction``
  1562. to introduce a cleanup. You shouldn't have to deal with
  1563. exception-handling directly.
  1564. * Testing is extremely important in IR generation. Use ``clang -cc1
  1565. -emit-llvm`` and `FileCheck
  1566. <http://llvm.org/docs/CommandGuide/FileCheck.html>`_ to verify that you're
  1567. generating the right IR.
  1568. #. Teach template instantiation how to cope with your AST node, which requires
  1569. some fairly simple code:
  1570. * Make sure that your expression's constructor properly computes the flags
  1571. for type dependence (i.e., the type your expression produces can change
  1572. from one instantiation to the next), value dependence (i.e., the constant
  1573. value your expression produces can change from one instantiation to the
  1574. next), instantiation dependence (i.e., a template parameter occurs
  1575. anywhere in your expression), and whether your expression contains a
  1576. parameter pack (for variadic templates). Often, computing these flags
  1577. just means combining the results from the various types and
  1578. subexpressions.
  1579. * Add ``TransformXXX`` and ``RebuildXXX`` functions to the ``TreeTransform``
  1580. class template in ``Sema``. ``TransformXXX`` should (recursively)
  1581. transform all of the subexpressions and types within your expression,
  1582. using ``getDerived().TransformYYY``. If all of the subexpressions and
  1583. types transform without error, it will then call the ``RebuildXXX``
  1584. function, which will in turn call ``getSema().BuildXXX`` to perform
  1585. semantic analysis and build your expression.
  1586. * To test template instantiation, take those tests you wrote to make sure
  1587. that you were type checking with type-dependent expressions and dependent
  1588. types (from step #2) and instantiate those templates with various types,
  1589. some of which type-check and some that don't, and test the error messages
  1590. in each case.
  1591. #. There are some "extras" that make other features work better. It's worth
  1592. handling these extras to give your expression complete integration into
  1593. Clang:
  1594. * Add code completion support for your expression in
  1595. ``SemaCodeComplete.cpp``.
  1596. * If your expression has types in it, or has any "interesting" features
  1597. other than subexpressions, extend libclang's ``CursorVisitor`` to provide
  1598. proper visitation for your expression, enabling various IDE features such
  1599. as syntax highlighting, cross-referencing, and so on. The
  1600. ``c-index-test`` helper program can be used to test these features.