InternalsManual.rst 127 KB

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