SourceLevelDebugging.rst 89 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139
  1. ================================
  2. Source Level Debugging with LLVM
  3. ================================
  4. .. contents::
  5. :local:
  6. Introduction
  7. ============
  8. This document is the central repository for all information pertaining to debug
  9. information in LLVM. It describes the :ref:`actual format that the LLVM debug
  10. information takes <format>`, which is useful for those interested in creating
  11. front-ends or dealing directly with the information. Further, this document
  12. provides specific examples of what debug information for C/C++ looks like.
  13. Philosophy behind LLVM debugging information
  14. --------------------------------------------
  15. The idea of the LLVM debugging information is to capture how the important
  16. pieces of the source-language's Abstract Syntax Tree map onto LLVM code.
  17. Several design aspects have shaped the solution that appears here. The
  18. important ones are:
  19. * Debugging information should have very little impact on the rest of the
  20. compiler. No transformations, analyses, or code generators should need to
  21. be modified because of debugging information.
  22. * LLVM optimizations should interact in :ref:`well-defined and easily described
  23. ways <intro_debugopt>` with the debugging information.
  24. * Because LLVM is designed to support arbitrary programming languages,
  25. LLVM-to-LLVM tools should not need to know anything about the semantics of
  26. the source-level-language.
  27. * Source-level languages are often **widely** different from one another.
  28. LLVM should not put any restrictions of the flavor of the source-language,
  29. and the debugging information should work with any language.
  30. * With code generator support, it should be possible to use an LLVM compiler
  31. to compile a program to native machine code and standard debugging
  32. formats. This allows compatibility with traditional machine-code level
  33. debuggers, like GDB or DBX.
  34. The approach used by the LLVM implementation is to use a small set of
  35. :ref:`intrinsic functions <format_common_intrinsics>` to define a mapping
  36. between LLVM program objects and the source-level objects. The description of
  37. the source-level program is maintained in LLVM metadata in an
  38. :ref:`implementation-defined format <ccxx_frontend>` (the C/C++ front-end
  39. currently uses working draft 7 of the `DWARF 3 standard
  40. <http://www.eagercon.com/dwarf/dwarf3std.htm>`_).
  41. When a program is being debugged, a debugger interacts with the user and turns
  42. the stored debug information into source-language specific information. As
  43. such, a debugger must be aware of the source-language, and is thus tied to a
  44. specific language or family of languages.
  45. Debug information consumers
  46. ---------------------------
  47. The role of debug information is to provide meta information normally stripped
  48. away during the compilation process. This meta information provides an LLVM
  49. user a relationship between generated code and the original program source
  50. code.
  51. Currently, there are two backend consumers of debug info: DwarfDebug and
  52. CodeViewDebug. DwarfDebug produces DWARF suitable for use with GDB, LLDB, and
  53. other DWARF-based debuggers. :ref:`CodeViewDebug <codeview>` produces CodeView,
  54. the Microsoft debug info format, which is usable with Microsoft debuggers such
  55. as Visual Studio and WinDBG. LLVM's debug information format is mostly derived
  56. from and inspired by DWARF, but it is feasible to translate into other target
  57. debug info formats such as STABS.
  58. It would also be reasonable to use debug information to feed profiling tools
  59. for analysis of generated code, or, tools for reconstructing the original
  60. source from generated code.
  61. .. _intro_debugopt:
  62. Debug information and optimizations
  63. -----------------------------------
  64. An extremely high priority of LLVM debugging information is to make it interact
  65. well with optimizations and analysis. In particular, the LLVM debug
  66. information provides the following guarantees:
  67. * LLVM debug information **always provides information to accurately read
  68. the source-level state of the program**, regardless of which LLVM
  69. optimizations have been run, and without any modification to the
  70. optimizations themselves. However, some optimizations may impact the
  71. ability to modify the current state of the program with a debugger, such
  72. as setting program variables, or calling functions that have been
  73. deleted.
  74. * As desired, LLVM optimizations can be upgraded to be aware of debugging
  75. information, allowing them to update the debugging information as they
  76. perform aggressive optimizations. This means that, with effort, the LLVM
  77. optimizers could optimize debug code just as well as non-debug code.
  78. * LLVM debug information does not prevent optimizations from
  79. happening (for example inlining, basic block reordering/merging/cleanup,
  80. tail duplication, etc).
  81. * LLVM debug information is automatically optimized along with the rest of
  82. the program, using existing facilities. For example, duplicate
  83. information is automatically merged by the linker, and unused information
  84. is automatically removed.
  85. Basically, the debug information allows you to compile a program with
  86. "``-O0 -g``" and get full debug information, allowing you to arbitrarily modify
  87. the program as it executes from a debugger. Compiling a program with
  88. "``-O3 -g``" gives you full debug information that is always available and
  89. accurate for reading (e.g., you get accurate stack traces despite tail call
  90. elimination and inlining), but you might lose the ability to modify the program
  91. and call functions which were optimized out of the program, or inlined away
  92. completely.
  93. The :doc:`LLVM test-suite <TestSuiteMakefileGuide>` provides a framework to
  94. test the optimizer's handling of debugging information. It can be run like
  95. this:
  96. .. code-block:: bash
  97. % cd llvm/projects/test-suite/MultiSource/Benchmarks # or some other level
  98. % make TEST=dbgopt
  99. This will test impact of debugging information on optimization passes. If
  100. debugging information influences optimization passes then it will be reported
  101. as a failure. See :doc:`TestingGuide` for more information on LLVM test
  102. infrastructure and how to run various tests.
  103. .. _format:
  104. Debugging information format
  105. ============================
  106. LLVM debugging information has been carefully designed to make it possible for
  107. the optimizer to optimize the program and debugging information without
  108. necessarily having to know anything about debugging information. In
  109. particular, the use of metadata avoids duplicated debugging information from
  110. the beginning, and the global dead code elimination pass automatically deletes
  111. debugging information for a function if it decides to delete the function.
  112. To do this, most of the debugging information (descriptors for types,
  113. variables, functions, source files, etc) is inserted by the language front-end
  114. in the form of LLVM metadata.
  115. Debug information is designed to be agnostic about the target debugger and
  116. debugging information representation (e.g. DWARF/Stabs/etc). It uses a generic
  117. pass to decode the information that represents variables, types, functions,
  118. namespaces, etc: this allows for arbitrary source-language semantics and
  119. type-systems to be used, as long as there is a module written for the target
  120. debugger to interpret the information.
  121. To provide basic functionality, the LLVM debugger does have to make some
  122. assumptions about the source-level language being debugged, though it keeps
  123. these to a minimum. The only common features that the LLVM debugger assumes
  124. exist are `source files <LangRef.html#difile>`_, and `program objects
  125. <LangRef.html#diglobalvariable>`_. These abstract objects are used by a
  126. debugger to form stack traces, show information about local variables, etc.
  127. This section of the documentation first describes the representation aspects
  128. common to any source-language. :ref:`ccxx_frontend` describes the data layout
  129. conventions used by the C and C++ front-ends.
  130. Debug information descriptors are `specialized metadata nodes
  131. <LangRef.html#specialized-metadata>`_, first-class subclasses of ``Metadata``.
  132. .. _format_common_intrinsics:
  133. Debugger intrinsic functions
  134. ----------------------------
  135. LLVM uses several intrinsic functions (name prefixed with "``llvm.dbg``") to
  136. track source local variables through optimization and code generation.
  137. ``llvm.dbg.addr``
  138. ^^^^^^^^^^^^^^^^^^^^
  139. .. code-block:: llvm
  140. void @llvm.dbg.addr(metadata, metadata, metadata)
  141. This intrinsic provides information about a local element (e.g., variable).
  142. The first argument is metadata holding the address of variable, typically a
  143. static alloca in the function entry block. The second argument is a
  144. `local variable <LangRef.html#dilocalvariable>`_ containing a description of
  145. the variable. The third argument is a `complex expression
  146. <LangRef.html#diexpression>`_. An `llvm.dbg.addr` intrinsic describes the
  147. *address* of a source variable.
  148. .. code-block:: text
  149. %i.addr = alloca i32, align 4
  150. call void @llvm.dbg.addr(metadata i32* %i.addr, metadata !1,
  151. metadata !DIExpression()), !dbg !2
  152. !1 = !DILocalVariable(name: "i", ...) ; int i
  153. !2 = !DILocation(...)
  154. ...
  155. %buffer = alloca [256 x i8], align 8
  156. ; The address of i is buffer+64.
  157. call void @llvm.dbg.addr(metadata [256 x i8]* %buffer, metadata !3,
  158. metadata !DIExpression(DW_OP_plus, 64)), !dbg !4
  159. !3 = !DILocalVariable(name: "i", ...) ; int i
  160. !4 = !DILocation(...)
  161. A frontend should generate exactly one call to ``llvm.dbg.addr`` at the point
  162. of declaration of a source variable. Optimization passes that fully promote the
  163. variable from memory to SSA values will replace this call with possibly
  164. multiple calls to `llvm.dbg.value`. Passes that delete stores are effectively
  165. partial promotion, and they will insert a mix of calls to ``llvm.dbg.value``
  166. and ``llvm.dbg.addr`` to track the source variable value when it is available.
  167. After optimization, there may be multiple calls to ``llvm.dbg.addr`` describing
  168. the program points where the variables lives in memory. All calls for the same
  169. concrete source variable must agree on the memory location.
  170. ``llvm.dbg.declare``
  171. ^^^^^^^^^^^^^^^^^^^^
  172. .. code-block:: llvm
  173. void @llvm.dbg.declare(metadata, metadata, metadata)
  174. This intrinsic is identical to `llvm.dbg.addr`, except that there can only be
  175. one call to `llvm.dbg.declare` for a given concrete `local variable
  176. <LangRef.html#dilocalvariable>`_. It is not control-dependent, meaning that if
  177. a call to `llvm.dbg.declare` exists and has a valid location argument, that
  178. address is considered to be the true home of the variable across its entire
  179. lifetime. This makes it hard for optimizations to preserve accurate debug info
  180. in the presence of ``llvm.dbg.declare``, so we are transitioning away from it,
  181. and we plan to deprecate it in future LLVM releases.
  182. ``llvm.dbg.value``
  183. ^^^^^^^^^^^^^^^^^^
  184. .. code-block:: llvm
  185. void @llvm.dbg.value(metadata, metadata, metadata)
  186. This intrinsic provides information when a user source variable is set to a new
  187. value. The first argument is the new value (wrapped as metadata). The second
  188. argument is a `local variable <LangRef.html#dilocalvariable>`_ containing a
  189. description of the variable. The third argument is a `complex expression
  190. <LangRef.html#diexpression>`_.
  191. An `llvm.dbg.value` intrinsic describes the *value* of a source variable
  192. directly, not its address. Note that the value operand of this intrinsic may
  193. be indirect (i.e, a pointer to the source variable), provided that interpreting
  194. the complex expression derives the direct value.
  195. Object lifetimes and scoping
  196. ============================
  197. In many languages, the local variables in functions can have their lifetimes or
  198. scopes limited to a subset of a function. In the C family of languages, for
  199. example, variables are only live (readable and writable) within the source
  200. block that they are defined in. In functional languages, values are only
  201. readable after they have been defined. Though this is a very obvious concept,
  202. it is non-trivial to model in LLVM, because it has no notion of scoping in this
  203. sense, and does not want to be tied to a language's scoping rules.
  204. In order to handle this, the LLVM debug format uses the metadata attached to
  205. llvm instructions to encode line number and scoping information. Consider the
  206. following C fragment, for example:
  207. .. code-block:: c
  208. 1. void foo() {
  209. 2. int X = 21;
  210. 3. int Y = 22;
  211. 4. {
  212. 5. int Z = 23;
  213. 6. Z = X;
  214. 7. }
  215. 8. X = Y;
  216. 9. }
  217. .. FIXME: Update the following example to use llvm.dbg.addr once that is the
  218. default in clang.
  219. Compiled to LLVM, this function would be represented like this:
  220. .. code-block:: text
  221. ; Function Attrs: nounwind ssp uwtable
  222. define void @foo() #0 !dbg !4 {
  223. entry:
  224. %X = alloca i32, align 4
  225. %Y = alloca i32, align 4
  226. %Z = alloca i32, align 4
  227. call void @llvm.dbg.declare(metadata i32* %X, metadata !11, metadata !13), !dbg !14
  228. store i32 21, i32* %X, align 4, !dbg !14
  229. call void @llvm.dbg.declare(metadata i32* %Y, metadata !15, metadata !13), !dbg !16
  230. store i32 22, i32* %Y, align 4, !dbg !16
  231. call void @llvm.dbg.declare(metadata i32* %Z, metadata !17, metadata !13), !dbg !19
  232. store i32 23, i32* %Z, align 4, !dbg !19
  233. %0 = load i32, i32* %X, align 4, !dbg !20
  234. store i32 %0, i32* %Z, align 4, !dbg !21
  235. %1 = load i32, i32* %Y, align 4, !dbg !22
  236. store i32 %1, i32* %X, align 4, !dbg !23
  237. ret void, !dbg !24
  238. }
  239. ; Function Attrs: nounwind readnone
  240. declare void @llvm.dbg.declare(metadata, metadata, metadata) #1
  241. attributes #0 = { nounwind ssp uwtable "less-precise-fpmad"="false" "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "stack-protector-buffer-size"="8" "unsafe-fp-math"="false" "use-soft-float"="false" }
  242. attributes #1 = { nounwind readnone }
  243. !llvm.dbg.cu = !{!0}
  244. !llvm.module.flags = !{!7, !8, !9}
  245. !llvm.ident = !{!10}
  246. !0 = !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "clang version 3.7.0 (trunk 231150) (llvm/trunk 231154)", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !2, retainedTypes: !2, subprograms: !3, globals: !2, imports: !2)
  247. !1 = !DIFile(filename: "/dev/stdin", directory: "/Users/dexonsmith/data/llvm/debug-info")
  248. !2 = !{}
  249. !3 = !{!4}
  250. !4 = distinct !DISubprogram(name: "foo", scope: !1, file: !1, line: 1, type: !5, isLocal: false, isDefinition: true, scopeLine: 1, isOptimized: false, variables: !2)
  251. !5 = !DISubroutineType(types: !6)
  252. !6 = !{null}
  253. !7 = !{i32 2, !"Dwarf Version", i32 2}
  254. !8 = !{i32 2, !"Debug Info Version", i32 3}
  255. !9 = !{i32 1, !"PIC Level", i32 2}
  256. !10 = !{!"clang version 3.7.0 (trunk 231150) (llvm/trunk 231154)"}
  257. !11 = !DILocalVariable(name: "X", scope: !4, file: !1, line: 2, type: !12)
  258. !12 = !DIBasicType(name: "int", size: 32, align: 32, encoding: DW_ATE_signed)
  259. !13 = !DIExpression()
  260. !14 = !DILocation(line: 2, column: 9, scope: !4)
  261. !15 = !DILocalVariable(name: "Y", scope: !4, file: !1, line: 3, type: !12)
  262. !16 = !DILocation(line: 3, column: 9, scope: !4)
  263. !17 = !DILocalVariable(name: "Z", scope: !18, file: !1, line: 5, type: !12)
  264. !18 = distinct !DILexicalBlock(scope: !4, file: !1, line: 4, column: 5)
  265. !19 = !DILocation(line: 5, column: 11, scope: !18)
  266. !20 = !DILocation(line: 6, column: 11, scope: !18)
  267. !21 = !DILocation(line: 6, column: 9, scope: !18)
  268. !22 = !DILocation(line: 8, column: 9, scope: !4)
  269. !23 = !DILocation(line: 8, column: 7, scope: !4)
  270. !24 = !DILocation(line: 9, column: 3, scope: !4)
  271. This example illustrates a few important details about LLVM debugging
  272. information. In particular, it shows how the ``llvm.dbg.declare`` intrinsic and
  273. location information, which are attached to an instruction, are applied
  274. together to allow a debugger to analyze the relationship between statements,
  275. variable definitions, and the code used to implement the function.
  276. .. code-block:: llvm
  277. call void @llvm.dbg.declare(metadata i32* %X, metadata !11, metadata !13), !dbg !14
  278. ; [debug line = 2:7] [debug variable = X]
  279. The first intrinsic ``%llvm.dbg.declare`` encodes debugging information for the
  280. variable ``X``. The metadata ``!dbg !14`` attached to the intrinsic provides
  281. scope information for the variable ``X``.
  282. .. code-block:: text
  283. !14 = !DILocation(line: 2, column: 9, scope: !4)
  284. !4 = distinct !DISubprogram(name: "foo", scope: !1, file: !1, line: 1, type: !5,
  285. isLocal: false, isDefinition: true, scopeLine: 1,
  286. isOptimized: false, variables: !2)
  287. Here ``!14`` is metadata providing `location information
  288. <LangRef.html#dilocation>`_. In this example, scope is encoded by ``!4``, a
  289. `subprogram descriptor <LangRef.html#disubprogram>`_. This way the location
  290. information attached to the intrinsics indicates that the variable ``X`` is
  291. declared at line number 2 at a function level scope in function ``foo``.
  292. Now lets take another example.
  293. .. code-block:: llvm
  294. call void @llvm.dbg.declare(metadata i32* %Z, metadata !17, metadata !13), !dbg !19
  295. ; [debug line = 5:9] [debug variable = Z]
  296. The third intrinsic ``%llvm.dbg.declare`` encodes debugging information for
  297. variable ``Z``. The metadata ``!dbg !19`` attached to the intrinsic provides
  298. scope information for the variable ``Z``.
  299. .. code-block:: text
  300. !18 = distinct !DILexicalBlock(scope: !4, file: !1, line: 4, column: 5)
  301. !19 = !DILocation(line: 5, column: 11, scope: !18)
  302. Here ``!19`` indicates that ``Z`` is declared at line number 5 and column
  303. number 11 inside of lexical scope ``!18``. The lexical scope itself resides
  304. inside of subprogram ``!4`` described above.
  305. The scope information attached with each instruction provides a straightforward
  306. way to find instructions covered by a scope.
  307. Object lifetime in optimized code
  308. =================================
  309. In the example above, every variable assignment uniquely corresponds to a
  310. memory store to the variable's position on the stack. However in heavily
  311. optimized code LLVM promotes most variables into SSA values, which can
  312. eventually be placed in physical registers or memory locations. To track SSA
  313. values through compilation, when objects are promoted to SSA values an
  314. ``llvm.dbg.value`` intrinsic is created for each assignment, recording the
  315. variable's new location. Compared with the ``llvm.dbg.declare`` intrinsic:
  316. * A dbg.value terminates the effect of any preceeding dbg.values for (any
  317. overlapping fragments of) the specified variable.
  318. * The dbg.value's position in the IR defines where in the instruction stream
  319. the variable's value changes.
  320. * Operands can be constants, indicating the variable is assigned a
  321. constant value.
  322. Care must be taken to update ``llvm.dbg.value`` intrinsics when optimization
  323. passes alter or move instructions and blocks -- the developer could observe such
  324. changes reflected in the value of variables when debugging the program. For any
  325. execution of the optimized program, the set of variable values presented to the
  326. developer by the debugger should not show a state that would never have existed
  327. in the execution of the unoptimized program, given the same input. Doing so
  328. risks misleading the developer by reporting a state that does not exist,
  329. damaging their understanding of the optimized program and undermining their
  330. trust in the debugger.
  331. Sometimes perfectly preserving variable locations is not possible, often when a
  332. redundant calculation is optimized out. In such cases, a ``llvm.dbg.value``
  333. with operand ``undef`` should be used, to terminate earlier variable locations
  334. and let the debugger present ``optimized out`` to the developer. Withholding
  335. these potentially stale variable values from the developer diminishes the
  336. amount of available debug information, but increases the reliability of the
  337. remaining information.
  338. To illustrate some potential issues, consider the following example:
  339. .. code-block:: llvm
  340. define i32 @foo(i32 %bar, i1 %cond) {
  341. entry:
  342. call @llvm.dbg.value(metadata i32 0, metadata !1, metadata !2)
  343. br i1 %cond, label %truebr, label %falsebr
  344. truebr:
  345. %tval = add i32 %bar, 1
  346. call @llvm.dbg.value(metadata i32 %tval, metadata !1, metadata !2)
  347. %g1 = call i32 @gazonk()
  348. br label %exit
  349. falsebr:
  350. %fval = add i32 %bar, 2
  351. call @llvm.dbg.value(metadata i32 %fval, metadata !1, metadata !2)
  352. %g2 = call i32 @gazonk()
  353. br label %exit
  354. exit:
  355. %merge = phi [ %tval, %truebr ], [ %fval, %falsebr ]
  356. %g = phi [ %g1, %truebr ], [ %g2, %falsebr ]
  357. call @llvm.dbg.value(metadata i32 %merge, metadata !1, metadata !2)
  358. call @llvm.dbg.value(metadata i32 %g, metadata !3, metadata !2)
  359. %plusten = add i32 %merge, 10
  360. %toret = add i32 %plusten, %g
  361. call @llvm.dbg.value(metadata i32 %toret, metadata !1, metadata !2)
  362. ret i32 %toret
  363. }
  364. Containing two source-level variables in ``!1`` and ``!3``. The function could,
  365. perhaps, be optimized into the following code:
  366. .. code-block:: llvm
  367. define i32 @foo(i32 %bar, i1 %cond) {
  368. entry:
  369. %g = call i32 @gazonk()
  370. %addoper = select i1 %cond, i32 11, i32 12
  371. %plusten = add i32 %bar, %addoper
  372. %toret = add i32 %plusten, %g
  373. ret i32 %toret
  374. }
  375. What ``llvm.dbg.value`` intrinsics should be placed to represent the original variable
  376. locations in this code? Unfortunately the the second, third and fourth
  377. dbg.values for ``!1`` in the source function have had their operands
  378. (%tval, %fval, %merge) optimized out. Assuming we cannot recover them, we
  379. might consider this placement of dbg.values:
  380. .. code-block:: llvm
  381. define i32 @foo(i32 %bar, i1 %cond) {
  382. entry:
  383. call @llvm.dbg.value(metadata i32 0, metadata !1, metadata !2)
  384. %g = call i32 @gazonk()
  385. call @llvm.dbg.value(metadata i32 %g, metadata !3, metadata !2)
  386. %addoper = select i1 %cond, i32 11, i32 12
  387. %plusten = add i32 %bar, %addoper
  388. %toret = add i32 %plusten, %g
  389. call @llvm.dbg.value(metadata i32 %toret, metadata !1, metadata !2)
  390. ret i32 %toret
  391. }
  392. However, this will cause ``!3`` to have the return value of ``@gazonk()`` at
  393. the same time as ``!1`` has the constant value zero -- a pair of assignments
  394. that never occurred in the unoptimized program. To avoid this, we must terminate
  395. the range that ``!1`` has the constant value assignment by inserting an undef
  396. dbg.value before the dbg.value for ``!3``:
  397. .. code-block:: llvm
  398. define i32 @foo(i32 %bar, i1 %cond) {
  399. entry:
  400. call @llvm.dbg.value(metadata i32 0, metadata !1, metadata !2)
  401. %g = call i32 @gazonk()
  402. call @llvm.dbg.value(metadata i32 undef, metadata !1, metadata !2)
  403. call @llvm.dbg.value(metadata i32 %g, metadata !3, metadata !2)
  404. %addoper = select i1 %cond, i32 11, i32 12
  405. %plusten = add i32 %bar, %addoper
  406. %toret = add i32 %plusten, %g
  407. call @llvm.dbg.value(metadata i32 %toret, metadata !1, metadata !2)
  408. ret i32 %toret
  409. }
  410. In general, if any dbg.value has its operand optimized out and cannot be
  411. recovered, then an undef dbg.value is necessary to terminate earlier variable
  412. locations. Additional undef dbg.values may be necessary when the debugger can
  413. observe re-ordering of assignments.
  414. How variable location metadata is transformed during CodeGen
  415. ============================================================
  416. LLVM preserves debug information throughout mid-level and backend passes,
  417. ultimately producing a mapping between source-level information and
  418. instruction ranges. This
  419. is relatively straightforwards for line number information, as mapping
  420. instructions to line numbers is a simple association. For variable locations
  421. however the story is more complex. As each ``llvm.dbg.value`` intrinsic
  422. represents a source-level assignment of a value to a source variable, the
  423. variable location intrinsics effectively embed a small imperative program
  424. within the LLVM IR. By the end of CodeGen, this becomes a mapping from each
  425. variable to their machine locations over ranges of instructions.
  426. From IR to object emission, the major transformations which affect variable
  427. location fidelity are:
  428. 1. Instruction Selection
  429. 2. Register allocation
  430. 3. Block layout
  431. each of which are discussed below. In addition, instruction scheduling can
  432. significantly change the ordering of the program, and occurs in a number of
  433. different passes.
  434. Some variable locations are not transformed during CodeGen. Stack locations
  435. specified by ``llvm.dbg.declare`` are valid and unchanging for the entire
  436. duration of the function, and are recorded in a simple MachineFunction table.
  437. Location changes in the prologue and epilogue of a function are also ignored:
  438. frame setup and destruction may take several instructions, require a
  439. disproportionate amount of debugging information in the output binary to
  440. describe, and should be stepped over by debuggers anyway.
  441. Variable locations in Instruction Selection and MIR
  442. ---------------------------------------------------
  443. Instruction selection creates a MIR function from an IR function, and just as
  444. it transforms ``intermediate`` instructions into machine instructions, so must
  445. ``intermediate`` variable locations become machine variable locations.
  446. Within IR, variable locations are always identified by a Value, but in MIR
  447. there can be different types of variable locations. In addition, some IR
  448. locations become unavailable, for example if the operation of multiple IR
  449. instructions are combined into one machine instruction (such as
  450. multiply-and-accumulate) then intermediate Values are lost. To track variable
  451. locations through instruction selection, they are first separated into
  452. locations that do not depend on code generation (constants, stack locations,
  453. allocated virtual registers) and those that do. For those that do, debug
  454. metadata is attached to SDNodes in SelectionDAGs. After instruction selection
  455. has occurred and a MIR function is created, if the SDNode associated with debug
  456. metadata is allocated a virtual register, that virtual register is used as the
  457. variable location. If the SDNode is folded into a machine instruction or
  458. otherwise transformed into a non-register, the variable location becomes
  459. unavailable.
  460. Locations that are unavailable are treated as if they have been optimized out:
  461. in IR the location would be assigned ``undef`` by a debug intrinsic, and in MIR
  462. the equivalent location is used.
  463. After MIR locations are assigned to each variable, machine pseudo-instructions
  464. corresponding to each ``llvm.dbg.value`` and ``llvm.dbg.addr`` intrinsic are
  465. inserted. These ``DBG_VALUE`` instructions appear thus:
  466. .. code-block:: text
  467. DBG_VALUE %1, $noreg, !123, !DIExpression()
  468. And have the following operands:
  469. * The first operand can record the variable location as a register,
  470. a frame index, an immediate, or the base address register if the original
  471. debug intrinsic referred to memory. ``$noreg`` indicates the variable
  472. location is undefined, equivalent to an ``undef`` dbg.value operand.
  473. * The type of the second operand indicates whether the variable location is
  474. directly referred to by the DBG_VALUE, or whether it is indirect. The
  475. ``$noreg`` register signifies the former, an immediate operand (0) the
  476. latter.
  477. * Operand 3 is the Variable field of the original debug intrinsic.
  478. * Operand 4 is the Expression field of the original debug intrinsic.
  479. The position at which the DBG_VALUEs are inserted should correspond to the
  480. positions of their matching ``llvm.dbg.value`` intrinsics in the IR block. As
  481. with optimization, LLVM aims to preserve the order in which variable
  482. assignments occurred in the source program. However SelectionDAG performs some
  483. instruction scheduling, which can reorder assignments (discussed below).
  484. Function parameter locations are moved to the beginning of the function if
  485. they're not already, to ensure they're immediately available on function entry.
  486. To demonstrate variable locations during instruction selection, consider
  487. the following example:
  488. .. code-block:: llvm
  489. define i32 @foo(i32* %addr) {
  490. entry:
  491. call void @llvm.dbg.value(metadata i32 0, metadata !3, metadata !DIExpression()), !dbg !5
  492. br label %bb1, !dbg !5
  493. bb1: ; preds = %bb1, %entry
  494. %bar.0 = phi i32 [ 0, %entry ], [ %add, %bb1 ]
  495. call void @llvm.dbg.value(metadata i32 %bar.0, metadata !3, metadata !DIExpression()), !dbg !5
  496. %addr1 = getelementptr i32, i32 *%addr, i32 1, !dbg !5
  497. call void @llvm.dbg.value(metadata i32 *%addr1, metadata !3, metadata !DIExpression()), !dbg !5
  498. %loaded1 = load i32, i32* %addr1, !dbg !5
  499. %addr2 = getelementptr i32, i32 *%addr, i32 %bar.0, !dbg !5
  500. call void @llvm.dbg.value(metadata i32 *%addr2, metadata !3, metadata !DIExpression()), !dbg !5
  501. %loaded2 = load i32, i32* %addr2, !dbg !5
  502. %add = add i32 %bar.0, 1, !dbg !5
  503. call void @llvm.dbg.value(metadata i32 %add, metadata !3, metadata !DIExpression()), !dbg !5
  504. %added = add i32 %loaded1, %loaded2
  505. %cond = icmp ult i32 %added, %bar.0, !dbg !5
  506. br i1 %cond, label %bb1, label %bb2, !dbg !5
  507. bb2: ; preds = %bb1
  508. ret i32 0, !dbg !5
  509. }
  510. If one compiles this IR with ``llc -o - -start-after=codegen-prepare -stop-after=expand-isel-pseudos -mtriple=x86_64--``, the following MIR is produced:
  511. .. code-block:: text
  512. bb.0.entry:
  513. successors: %bb.1(0x80000000)
  514. liveins: $rdi
  515. %2:gr64 = COPY $rdi
  516. %3:gr32 = MOV32r0 implicit-def dead $eflags
  517. DBG_VALUE 0, $noreg, !3, !DIExpression(), debug-location !5
  518. bb.1.bb1:
  519. successors: %bb.1(0x7c000000), %bb.2(0x04000000)
  520. %0:gr32 = PHI %3, %bb.0, %1, %bb.1
  521. DBG_VALUE %0, $noreg, !3, !DIExpression(), debug-location !5
  522. DBG_VALUE %2, $noreg, !3, !DIExpression(DW_OP_plus_uconst, 4, DW_OP_stack_value), debug-location !5
  523. %4:gr32 = MOV32rm %2, 1, $noreg, 4, $noreg, debug-location !5 :: (load 4 from %ir.addr1)
  524. %5:gr64_nosp = MOVSX64rr32 %0, debug-location !5
  525. DBG_VALUE $noreg, $noreg, !3, !DIExpression(), debug-location !5
  526. %1:gr32 = INC32r %0, implicit-def dead $eflags, debug-location !5
  527. DBG_VALUE %1, $noreg, !3, !DIExpression(), debug-location !5
  528. %6:gr32 = ADD32rm %4, %2, 4, killed %5, 0, $noreg, implicit-def dead $eflags :: (load 4 from %ir.addr2)
  529. %7:gr32 = SUB32rr %6, %0, implicit-def $eflags, debug-location !5
  530. JB_1 %bb.1, implicit $eflags, debug-location !5
  531. JMP_1 %bb.2, debug-location !5
  532. bb.2.bb2:
  533. %8:gr32 = MOV32r0 implicit-def dead $eflags
  534. $eax = COPY %8, debug-location !5
  535. RET 0, $eax, debug-location !5
  536. Observe first that there is a DBG_VALUE instruction for every ``llvm.dbg.value``
  537. intrinsic in the source IR, ensuring no source level assignments go missing.
  538. Then consider the different ways in which variable locations have been recorded:
  539. * For the first dbg.value an immediate operand is used to record a zero value.
  540. * The dbg.value of the PHI instruction leads to a DBG_VALUE of virtual register
  541. ``%0``.
  542. * The first GEP has its effect folded into the first load instruction
  543. (as a 4-byte offset), but the variable location is salvaged by folding
  544. the GEPs effect into the DIExpression.
  545. * The second GEP is also folded into the corresponding load. However, it is
  546. insufficiently simple to be salvaged, and is emitted as a ``$noreg``
  547. DBG_VALUE, indicating that the variable takes on an undefined location.
  548. * The final dbg.value has its Value placed in virtual register ``%1``.
  549. Instruction Scheduling
  550. ----------------------
  551. A number of passes can reschedule instructions, notably instruction selection
  552. and the pre-and-post RA machine schedulers. Instruction scheduling can
  553. significantly change the nature of the program -- in the (very unlikely) worst
  554. case the instruction sequence could be completely reversed. In such
  555. circumstances LLVM follows the principle applied to optimizations, that it is
  556. better for the debugger not to display any state than a misleading state.
  557. Thus, whenever instructions are advanced in order of execution, any
  558. corresponding DBG_VALUE is kept in its original position, and if an instruction
  559. is delayed then the variable is given an undefined location for the duration
  560. of the delay. To illustrate, consider this pseudo-MIR:
  561. .. code-block:: text
  562. %1:gr32 = MOV32rm %0, 1, $noreg, 4, $noreg, debug-location !5 :: (load 4 from %ir.addr1)
  563. DBG_VALUE %1, $noreg, !1, !2
  564. %4:gr32 = ADD32rr %3, %2, implicit-def dead $eflags
  565. DBG_VALUE %4, $noreg, !3, !4
  566. %7:gr32 = SUB32rr %6, %5, implicit-def dead $eflags
  567. DBG_VALUE %7, $noreg, !5, !6
  568. Imagine that the SUB32rr were moved forward to give us the following MIR:
  569. .. code-block:: text
  570. %7:gr32 = SUB32rr %6, %5, implicit-def dead $eflags
  571. %1:gr32 = MOV32rm %0, 1, $noreg, 4, $noreg, debug-location !5 :: (load 4 from %ir.addr1)
  572. DBG_VALUE %1, $noreg, !1, !2
  573. %4:gr32 = ADD32rr %3, %2, implicit-def dead $eflags
  574. DBG_VALUE %4, $noreg, !3, !4
  575. DBG_VALUE %7, $noreg, !5, !6
  576. In this circumstance LLVM would leave the MIR as shown above. Were we to move
  577. the DBG_VALUE of virtual register %7 upwards with the SUB32rr, we would re-order
  578. assignments and introduce a new state of the program. Wheras with the solution
  579. above, the debugger will see one fewer combination of variable values, because
  580. ``!3`` and ``!5`` will change value at the same time. This is preferred over
  581. misrepresenting the original program.
  582. In comparison, if one sunk the MOV32rm, LLVM would produce the following:
  583. .. code-block:: text
  584. DBG_VALUE $noreg, $noreg, !1, !2
  585. %4:gr32 = ADD32rr %3, %2, implicit-def dead $eflags
  586. DBG_VALUE %4, $noreg, !3, !4
  587. %7:gr32 = SUB32rr %6, %5, implicit-def dead $eflags
  588. DBG_VALUE %7, $noreg, !5, !6
  589. %1:gr32 = MOV32rm %0, 1, $noreg, 4, $noreg, debug-location !5 :: (load 4 from %ir.addr1)
  590. DBG_VALUE %1, $noreg, !1, !2
  591. Here, to avoid presenting a state in which the first assignment to ``!1``
  592. disappears, the DBG_VALUE at the top of the block assigns the variable the
  593. undefined location, until its value is available at the end of the block where
  594. an additional DBG_VALUE is added. Were any other DBG_VALUE for ``!1`` to occur
  595. in the instructions that the MOV32rm was sunk past, the DBG_VALUE for ``%1``
  596. would be dropped and the debugger would never observe it in the variable. This
  597. accurately reflects that the value is not available during the corresponding
  598. portion of the original program.
  599. Variable locations during Register Allocation
  600. ---------------------------------------------
  601. To avoid debug instructions interfering with the register allocator, the
  602. LiveDebugVariables pass extracts variable locations from a MIR function and
  603. deletes the corresponding DBG_VALUE instructions. Some localized copy
  604. propagation is performed within blocks. After register allocation, the
  605. VirtRegRewriter pass re-inserts DBG_VALUE instructions in their orignal
  606. positions, translating virtual register references into their physical
  607. machine locations. To avoid encoding incorrect variable locations, in this
  608. pass any DBG_VALUE of a virtual register that is not live, is replaced by
  609. the undefined location.
  610. LiveDebugValues expansion of variable locations
  611. -----------------------------------------------
  612. After all optimizations have run and shortly before emission, the
  613. LiveDebugValues pass runs to achieve two aims:
  614. * To propagate the location of variables through copies and register spills,
  615. * For every block, to record every valid variable location in that block.
  616. After this pass the DBG_VALUE instruction changes meaning: rather than
  617. corresponding to a source-level assignment where the variable may change value,
  618. it asserts the location of a variable in a block, and loses effect outside the
  619. block. Propagating variable locations through copies and spills is
  620. straightforwards: determining the variable location in every basic block
  621. requries the consideraton of control flow. Consider the following IR, which
  622. presents several difficulties:
  623. .. code-block:: text
  624. define dso_local i32 @foo(i1 %cond, i32 %input) !dbg !12 {
  625. entry:
  626. br i1 %cond, label %truebr, label %falsebr
  627. bb1:
  628. %value = phi i32 [ %value1, %truebr ], [ %value2, %falsebr ]
  629. br label %exit, !dbg !26
  630. truebr:
  631. call void @llvm.dbg.value(metadata i32 %input, metadata !30, metadata !DIExpression()), !dbg !24
  632. call void @llvm.dbg.value(metadata i32 1, metadata !23, metadata !DIExpression()), !dbg !24
  633. %value1 = add i32 %input, 1
  634. br label %bb1
  635. falsebr:
  636. call void @llvm.dbg.value(metadata i32 %input, metadata !30, metadata !DIExpression()), !dbg !24
  637. call void @llvm.dbg.value(metadata i32 2, metadata !23, metadata !DIExpression()), !dbg !24
  638. %value = add i32 %input, 2
  639. br label %bb1
  640. exit:
  641. ret i32 %value, !dbg !30
  642. }
  643. Here the difficulties are:
  644. * The control flow is roughly the opposite of basic block order
  645. * The value of the ``!23`` variable merges into ``%bb1``, but there is no PHI
  646. node
  647. As mentioned above, the ``llvm.dbg.value`` intrinsics essentially form an
  648. imperative program embedded in the IR, with each intrinsic defining a variable
  649. location. This *could* be converted to an SSA form by mem2reg, in the same way
  650. that it uses use-def chains to identify control flow merges and insert phi
  651. nodes for IR Values. However, because debug variable locations are defined for
  652. every machine instruction, in effect every IR instruction uses every variable
  653. location, which would lead to a large number of debugging intrinsics being
  654. generated.
  655. Examining the example above, variable ``!30`` is assigned ``%input`` on both
  656. conditional paths through the function, while ``!23`` is assigned differing
  657. constant values on either path. Where control flow merges in ``%bb1`` we would
  658. want ``!30`` to keep its location (``%input``), but ``!23`` to become undefined
  659. as we cannot determine at runtime what value it should have in %bb1 without
  660. inserting a PHI node. mem2reg does not insert the PHI node to avoid changing
  661. codegen when debugging is enabled, and does not insert the other dbg.values
  662. to avoid adding very large numbers of intrinsics.
  663. Instead, LiveDebugValues determines variable locations when control
  664. flow merges. A dataflow analysis is used to propagate locations between blocks:
  665. when control flow merges, if a variable has the same location in all
  666. predecessors then that location is propagated into the successor. If the
  667. predecessor locations disagree, the location becomes undefined.
  668. Once LiveDebugValues has run, every block should have all valid variable
  669. locations described by DBG_VALUE instructions within the block. Very little
  670. effort is then required by supporting classes (such as
  671. DbgEntityHistoryCalculator) to build a map of each instruction to every
  672. valid variable location, without the need to consider control flow. From
  673. the example above, it is otherwise difficult to determine that the location
  674. of variable ``!30`` should flow "up" into block ``%bb1``, but that the location
  675. of variable ``!23`` should not flow "down" into the ``%exit`` block.
  676. .. _ccxx_frontend:
  677. C/C++ front-end specific debug information
  678. ==========================================
  679. The C and C++ front-ends represent information about the program in a
  680. format that is effectively identical to `DWARF <http://www.dwarfstd.org/>`_
  681. in terms of information content. This allows code generators to
  682. trivially support native debuggers by generating standard dwarf
  683. information, and contains enough information for non-dwarf targets to
  684. translate it as needed.
  685. This section describes the forms used to represent C and C++ programs. Other
  686. languages could pattern themselves after this (which itself is tuned to
  687. representing programs in the same way that DWARF does), or they could choose
  688. to provide completely different forms if they don't fit into the DWARF model.
  689. As support for debugging information gets added to the various LLVM
  690. source-language front-ends, the information used should be documented here.
  691. The following sections provide examples of a few C/C++ constructs and
  692. the debug information that would best describe those constructs. The
  693. canonical references are the ``DINode`` classes defined in
  694. ``include/llvm/IR/DebugInfoMetadata.h`` and the implementations of the
  695. helper functions in ``lib/IR/DIBuilder.cpp``.
  696. C/C++ source file information
  697. -----------------------------
  698. ``llvm::Instruction`` provides easy access to metadata attached with an
  699. instruction. One can extract line number information encoded in LLVM IR using
  700. ``Instruction::getDebugLoc()`` and ``DILocation::getLine()``.
  701. .. code-block:: c++
  702. if (DILocation *Loc = I->getDebugLoc()) { // Here I is an LLVM instruction
  703. unsigned Line = Loc->getLine();
  704. StringRef File = Loc->getFilename();
  705. StringRef Dir = Loc->getDirectory();
  706. bool ImplicitCode = Loc->isImplicitCode();
  707. }
  708. When the flag ImplicitCode is true then it means that the Instruction has been
  709. added by the front-end but doesn't correspond to source code written by the user. For example
  710. .. code-block:: c++
  711. if (MyBoolean) {
  712. MyObject MO;
  713. ...
  714. }
  715. At the end of the scope the MyObject's destructor is called but it isn't written
  716. explicitly. This information is useful to avoid to have counters on brackets when
  717. making code coverage.
  718. C/C++ global variable information
  719. ---------------------------------
  720. Given an integer global variable declared as follows:
  721. .. code-block:: c
  722. _Alignas(8) int MyGlobal = 100;
  723. a C/C++ front-end would generate the following descriptors:
  724. .. code-block:: text
  725. ;;
  726. ;; Define the global itself.
  727. ;;
  728. @MyGlobal = global i32 100, align 8, !dbg !0
  729. ;;
  730. ;; List of debug info of globals
  731. ;;
  732. !llvm.dbg.cu = !{!1}
  733. ;; Some unrelated metadata.
  734. !llvm.module.flags = !{!6, !7}
  735. !llvm.ident = !{!8}
  736. ;; Define the global variable itself
  737. !0 = distinct !DIGlobalVariable(name: "MyGlobal", scope: !1, file: !2, line: 1, type: !5, isLocal: false, isDefinition: true, align: 64)
  738. ;; Define the compile unit.
  739. !1 = distinct !DICompileUnit(language: DW_LANG_C99, file: !2,
  740. producer: "clang version 4.0.0",
  741. isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug,
  742. enums: !3, globals: !4)
  743. ;;
  744. ;; Define the file
  745. ;;
  746. !2 = !DIFile(filename: "/dev/stdin",
  747. directory: "/Users/dexonsmith/data/llvm/debug-info")
  748. ;; An empty array.
  749. !3 = !{}
  750. ;; The Array of Global Variables
  751. !4 = !{!0}
  752. ;;
  753. ;; Define the type
  754. ;;
  755. !5 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
  756. ;; Dwarf version to output.
  757. !6 = !{i32 2, !"Dwarf Version", i32 4}
  758. ;; Debug info schema version.
  759. !7 = !{i32 2, !"Debug Info Version", i32 3}
  760. ;; Compiler identification
  761. !8 = !{!"clang version 4.0.0"}
  762. The align value in DIGlobalVariable description specifies variable alignment in
  763. case it was forced by C11 _Alignas(), C++11 alignas() keywords or compiler
  764. attribute __attribute__((aligned ())). In other case (when this field is missing)
  765. alignment is considered default. This is used when producing DWARF output
  766. for DW_AT_alignment value.
  767. C/C++ function information
  768. --------------------------
  769. Given a function declared as follows:
  770. .. code-block:: c
  771. int main(int argc, char *argv[]) {
  772. return 0;
  773. }
  774. a C/C++ front-end would generate the following descriptors:
  775. .. code-block:: text
  776. ;;
  777. ;; Define the anchor for subprograms.
  778. ;;
  779. !4 = !DISubprogram(name: "main", scope: !1, file: !1, line: 1, type: !5,
  780. isLocal: false, isDefinition: true, scopeLine: 1,
  781. flags: DIFlagPrototyped, isOptimized: false,
  782. variables: !2)
  783. ;;
  784. ;; Define the subprogram itself.
  785. ;;
  786. define i32 @main(i32 %argc, i8** %argv) !dbg !4 {
  787. ...
  788. }
  789. Fortran specific debug information
  790. ==================================
  791. Fortran function information
  792. ----------------------------
  793. There are a few DWARF attributes defined to support client debugging of Fortran programs. LLVM can generate (or omit) the appropriate DWARF attributes for the prefix-specs of ELEMENTAL, PURE, IMPURE, RECURSIVE, and NON_RECURSIVE. This is done by using the spFlags values: DISPFlagElemental, DISPFlagPure, and DISPFlagRecursive.
  794. .. code-block:: fortran
  795. elemental function elem_func(a)
  796. a Fortran front-end would generate the following descriptors:
  797. .. code-block:: text
  798. !11 = distinct !DISubprogram(name: "subroutine2", scope: !1, file: !1,
  799. line: 5, type: !8, scopeLine: 6,
  800. spFlags: DISPFlagDefinition | DISPFlagElemental, unit: !0,
  801. retainedNodes: !2)
  802. and this will materialize an additional DWARF attribute as:
  803. .. code-block:: text
  804. DW_TAG_subprogram [3]
  805. DW_AT_low_pc [DW_FORM_addr] (0x0000000000000010 ".text")
  806. DW_AT_high_pc [DW_FORM_data4] (0x00000001)
  807. ...
  808. DW_AT_elemental [DW_FORM_flag_present] (true)
  809. Debugging information format
  810. ============================
  811. Debugging Information Extension for Objective C Properties
  812. ----------------------------------------------------------
  813. Introduction
  814. ^^^^^^^^^^^^
  815. Objective C provides a simpler way to declare and define accessor methods using
  816. declared properties. The language provides features to declare a property and
  817. to let compiler synthesize accessor methods.
  818. The debugger lets developer inspect Objective C interfaces and their instance
  819. variables and class variables. However, the debugger does not know anything
  820. about the properties defined in Objective C interfaces. The debugger consumes
  821. information generated by compiler in DWARF format. The format does not support
  822. encoding of Objective C properties. This proposal describes DWARF extensions to
  823. encode Objective C properties, which the debugger can use to let developers
  824. inspect Objective C properties.
  825. Proposal
  826. ^^^^^^^^
  827. Objective C properties exist separately from class members. A property can be
  828. defined only by "setter" and "getter" selectors, and be calculated anew on each
  829. access. Or a property can just be a direct access to some declared ivar.
  830. Finally it can have an ivar "automatically synthesized" for it by the compiler,
  831. in which case the property can be referred to in user code directly using the
  832. standard C dereference syntax as well as through the property "dot" syntax, but
  833. there is no entry in the ``@interface`` declaration corresponding to this ivar.
  834. To facilitate debugging, these properties we will add a new DWARF TAG into the
  835. ``DW_TAG_structure_type`` definition for the class to hold the description of a
  836. given property, and a set of DWARF attributes that provide said description.
  837. The property tag will also contain the name and declared type of the property.
  838. If there is a related ivar, there will also be a DWARF property attribute placed
  839. in the ``DW_TAG_member`` DIE for that ivar referring back to the property TAG
  840. for that property. And in the case where the compiler synthesizes the ivar
  841. directly, the compiler is expected to generate a ``DW_TAG_member`` for that
  842. ivar (with the ``DW_AT_artificial`` set to 1), whose name will be the name used
  843. to access this ivar directly in code, and with the property attribute pointing
  844. back to the property it is backing.
  845. The following examples will serve as illustration for our discussion:
  846. .. code-block:: objc
  847. @interface I1 {
  848. int n2;
  849. }
  850. @property int p1;
  851. @property int p2;
  852. @end
  853. @implementation I1
  854. @synthesize p1;
  855. @synthesize p2 = n2;
  856. @end
  857. This produces the following DWARF (this is a "pseudo dwarfdump" output):
  858. .. code-block:: none
  859. 0x00000100: TAG_structure_type [7] *
  860. AT_APPLE_runtime_class( 0x10 )
  861. AT_name( "I1" )
  862. AT_decl_file( "Objc_Property.m" )
  863. AT_decl_line( 3 )
  864. 0x00000110 TAG_APPLE_property
  865. AT_name ( "p1" )
  866. AT_type ( {0x00000150} ( int ) )
  867. 0x00000120: TAG_APPLE_property
  868. AT_name ( "p2" )
  869. AT_type ( {0x00000150} ( int ) )
  870. 0x00000130: TAG_member [8]
  871. AT_name( "_p1" )
  872. AT_APPLE_property ( {0x00000110} "p1" )
  873. AT_type( {0x00000150} ( int ) )
  874. AT_artificial ( 0x1 )
  875. 0x00000140: TAG_member [8]
  876. AT_name( "n2" )
  877. AT_APPLE_property ( {0x00000120} "p2" )
  878. AT_type( {0x00000150} ( int ) )
  879. 0x00000150: AT_type( ( int ) )
  880. Note, the current convention is that the name of the ivar for an
  881. auto-synthesized property is the name of the property from which it derives
  882. with an underscore prepended, as is shown in the example. But we actually
  883. don't need to know this convention, since we are given the name of the ivar
  884. directly.
  885. Also, it is common practice in ObjC to have different property declarations in
  886. the @interface and @implementation - e.g. to provide a read-only property in
  887. the interface,and a read-write interface in the implementation. In that case,
  888. the compiler should emit whichever property declaration will be in force in the
  889. current translation unit.
  890. Developers can decorate a property with attributes which are encoded using
  891. ``DW_AT_APPLE_property_attribute``.
  892. .. code-block:: objc
  893. @property (readonly, nonatomic) int pr;
  894. .. code-block:: none
  895. TAG_APPLE_property [8]
  896. AT_name( "pr" )
  897. AT_type ( {0x00000147} (int) )
  898. AT_APPLE_property_attribute (DW_APPLE_PROPERTY_readonly, DW_APPLE_PROPERTY_nonatomic)
  899. The setter and getter method names are attached to the property using
  900. ``DW_AT_APPLE_property_setter`` and ``DW_AT_APPLE_property_getter`` attributes.
  901. .. code-block:: objc
  902. @interface I1
  903. @property (setter=myOwnP3Setter:) int p3;
  904. -(void)myOwnP3Setter:(int)a;
  905. @end
  906. @implementation I1
  907. @synthesize p3;
  908. -(void)myOwnP3Setter:(int)a{ }
  909. @end
  910. The DWARF for this would be:
  911. .. code-block:: none
  912. 0x000003bd: TAG_structure_type [7] *
  913. AT_APPLE_runtime_class( 0x10 )
  914. AT_name( "I1" )
  915. AT_decl_file( "Objc_Property.m" )
  916. AT_decl_line( 3 )
  917. 0x000003cd TAG_APPLE_property
  918. AT_name ( "p3" )
  919. AT_APPLE_property_setter ( "myOwnP3Setter:" )
  920. AT_type( {0x00000147} ( int ) )
  921. 0x000003f3: TAG_member [8]
  922. AT_name( "_p3" )
  923. AT_type ( {0x00000147} ( int ) )
  924. AT_APPLE_property ( {0x000003cd} )
  925. AT_artificial ( 0x1 )
  926. New DWARF Tags
  927. ^^^^^^^^^^^^^^
  928. +-----------------------+--------+
  929. | TAG | Value |
  930. +=======================+========+
  931. | DW_TAG_APPLE_property | 0x4200 |
  932. +-----------------------+--------+
  933. New DWARF Attributes
  934. ^^^^^^^^^^^^^^^^^^^^
  935. +--------------------------------+--------+-----------+
  936. | Attribute | Value | Classes |
  937. +================================+========+===========+
  938. | DW_AT_APPLE_property | 0x3fed | Reference |
  939. +--------------------------------+--------+-----------+
  940. | DW_AT_APPLE_property_getter | 0x3fe9 | String |
  941. +--------------------------------+--------+-----------+
  942. | DW_AT_APPLE_property_setter | 0x3fea | String |
  943. +--------------------------------+--------+-----------+
  944. | DW_AT_APPLE_property_attribute | 0x3feb | Constant |
  945. +--------------------------------+--------+-----------+
  946. New DWARF Constants
  947. ^^^^^^^^^^^^^^^^^^^
  948. +--------------------------------------+-------+
  949. | Name | Value |
  950. +======================================+=======+
  951. | DW_APPLE_PROPERTY_readonly | 0x01 |
  952. +--------------------------------------+-------+
  953. | DW_APPLE_PROPERTY_getter | 0x02 |
  954. +--------------------------------------+-------+
  955. | DW_APPLE_PROPERTY_assign | 0x04 |
  956. +--------------------------------------+-------+
  957. | DW_APPLE_PROPERTY_readwrite | 0x08 |
  958. +--------------------------------------+-------+
  959. | DW_APPLE_PROPERTY_retain | 0x10 |
  960. +--------------------------------------+-------+
  961. | DW_APPLE_PROPERTY_copy | 0x20 |
  962. +--------------------------------------+-------+
  963. | DW_APPLE_PROPERTY_nonatomic | 0x40 |
  964. +--------------------------------------+-------+
  965. | DW_APPLE_PROPERTY_setter | 0x80 |
  966. +--------------------------------------+-------+
  967. | DW_APPLE_PROPERTY_atomic | 0x100 |
  968. +--------------------------------------+-------+
  969. | DW_APPLE_PROPERTY_weak | 0x200 |
  970. +--------------------------------------+-------+
  971. | DW_APPLE_PROPERTY_strong | 0x400 |
  972. +--------------------------------------+-------+
  973. | DW_APPLE_PROPERTY_unsafe_unretained | 0x800 |
  974. +--------------------------------------+-------+
  975. | DW_APPLE_PROPERTY_nullability | 0x1000|
  976. +--------------------------------------+-------+
  977. | DW_APPLE_PROPERTY_null_resettable | 0x2000|
  978. +--------------------------------------+-------+
  979. | DW_APPLE_PROPERTY_class | 0x4000|
  980. +--------------------------------------+-------+
  981. Name Accelerator Tables
  982. -----------------------
  983. Introduction
  984. ^^^^^^^^^^^^
  985. The "``.debug_pubnames``" and "``.debug_pubtypes``" formats are not what a
  986. debugger needs. The "``pub``" in the section name indicates that the entries
  987. in the table are publicly visible names only. This means no static or hidden
  988. functions show up in the "``.debug_pubnames``". No static variables or private
  989. class variables are in the "``.debug_pubtypes``". Many compilers add different
  990. things to these tables, so we can't rely upon the contents between gcc, icc, or
  991. clang.
  992. The typical query given by users tends not to match up with the contents of
  993. these tables. For example, the DWARF spec states that "In the case of the name
  994. of a function member or static data member of a C++ structure, class or union,
  995. the name presented in the "``.debug_pubnames``" section is not the simple name
  996. given by the ``DW_AT_name attribute`` of the referenced debugging information
  997. entry, but rather the fully qualified name of the data or function member."
  998. So the only names in these tables for complex C++ entries is a fully
  999. qualified name. Debugger users tend not to enter their search strings as
  1000. "``a::b::c(int,const Foo&) const``", but rather as "``c``", "``b::c``" , or
  1001. "``a::b::c``". So the name entered in the name table must be demangled in
  1002. order to chop it up appropriately and additional names must be manually entered
  1003. into the table to make it effective as a name lookup table for debuggers to
  1004. use.
  1005. All debuggers currently ignore the "``.debug_pubnames``" table as a result of
  1006. its inconsistent and useless public-only name content making it a waste of
  1007. space in the object file. These tables, when they are written to disk, are not
  1008. sorted in any way, leaving every debugger to do its own parsing and sorting.
  1009. These tables also include an inlined copy of the string values in the table
  1010. itself making the tables much larger than they need to be on disk, especially
  1011. for large C++ programs.
  1012. Can't we just fix the sections by adding all of the names we need to this
  1013. table? No, because that is not what the tables are defined to contain and we
  1014. won't know the difference between the old bad tables and the new good tables.
  1015. At best we could make our own renamed sections that contain all of the data we
  1016. need.
  1017. These tables are also insufficient for what a debugger like LLDB needs. LLDB
  1018. uses clang for its expression parsing where LLDB acts as a PCH. LLDB is then
  1019. often asked to look for type "``foo``" or namespace "``bar``", or list items in
  1020. namespace "``baz``". Namespaces are not included in the pubnames or pubtypes
  1021. tables. Since clang asks a lot of questions when it is parsing an expression,
  1022. we need to be very fast when looking up names, as it happens a lot. Having new
  1023. accelerator tables that are optimized for very quick lookups will benefit this
  1024. type of debugging experience greatly.
  1025. We would like to generate name lookup tables that can be mapped into memory
  1026. from disk, and used as is, with little or no up-front parsing. We would also
  1027. be able to control the exact content of these different tables so they contain
  1028. exactly what we need. The Name Accelerator Tables were designed to fix these
  1029. issues. In order to solve these issues we need to:
  1030. * Have a format that can be mapped into memory from disk and used as is
  1031. * Lookups should be very fast
  1032. * Extensible table format so these tables can be made by many producers
  1033. * Contain all of the names needed for typical lookups out of the box
  1034. * Strict rules for the contents of tables
  1035. Table size is important and the accelerator table format should allow the reuse
  1036. of strings from common string tables so the strings for the names are not
  1037. duplicated. We also want to make sure the table is ready to be used as-is by
  1038. simply mapping the table into memory with minimal header parsing.
  1039. The name lookups need to be fast and optimized for the kinds of lookups that
  1040. debuggers tend to do. Optimally we would like to touch as few parts of the
  1041. mapped table as possible when doing a name lookup and be able to quickly find
  1042. the name entry we are looking for, or discover there are no matches. In the
  1043. case of debuggers we optimized for lookups that fail most of the time.
  1044. Each table that is defined should have strict rules on exactly what is in the
  1045. accelerator tables and documented so clients can rely on the content.
  1046. Hash Tables
  1047. ^^^^^^^^^^^
  1048. Standard Hash Tables
  1049. """"""""""""""""""""
  1050. Typical hash tables have a header, buckets, and each bucket points to the
  1051. bucket contents:
  1052. .. code-block:: none
  1053. .------------.
  1054. | HEADER |
  1055. |------------|
  1056. | BUCKETS |
  1057. |------------|
  1058. | DATA |
  1059. `------------'
  1060. The BUCKETS are an array of offsets to DATA for each hash:
  1061. .. code-block:: none
  1062. .------------.
  1063. | 0x00001000 | BUCKETS[0]
  1064. | 0x00002000 | BUCKETS[1]
  1065. | 0x00002200 | BUCKETS[2]
  1066. | 0x000034f0 | BUCKETS[3]
  1067. | | ...
  1068. | 0xXXXXXXXX | BUCKETS[n_buckets]
  1069. '------------'
  1070. So for ``bucket[3]`` in the example above, we have an offset into the table
  1071. 0x000034f0 which points to a chain of entries for the bucket. Each bucket must
  1072. contain a next pointer, full 32 bit hash value, the string itself, and the data
  1073. for the current string value.
  1074. .. code-block:: none
  1075. .------------.
  1076. 0x000034f0: | 0x00003500 | next pointer
  1077. | 0x12345678 | 32 bit hash
  1078. | "erase" | string value
  1079. | data[n] | HashData for this bucket
  1080. |------------|
  1081. 0x00003500: | 0x00003550 | next pointer
  1082. | 0x29273623 | 32 bit hash
  1083. | "dump" | string value
  1084. | data[n] | HashData for this bucket
  1085. |------------|
  1086. 0x00003550: | 0x00000000 | next pointer
  1087. | 0x82638293 | 32 bit hash
  1088. | "main" | string value
  1089. | data[n] | HashData for this bucket
  1090. `------------'
  1091. The problem with this layout for debuggers is that we need to optimize for the
  1092. negative lookup case where the symbol we're searching for is not present. So
  1093. if we were to lookup "``printf``" in the table above, we would make a 32-bit
  1094. hash for "``printf``", it might match ``bucket[3]``. We would need to go to
  1095. the offset 0x000034f0 and start looking to see if our 32 bit hash matches. To
  1096. do so, we need to read the next pointer, then read the hash, compare it, and
  1097. skip to the next bucket. Each time we are skipping many bytes in memory and
  1098. touching new pages just to do the compare on the full 32 bit hash. All of
  1099. these accesses then tell us that we didn't have a match.
  1100. Name Hash Tables
  1101. """"""""""""""""
  1102. To solve the issues mentioned above we have structured the hash tables a bit
  1103. differently: a header, buckets, an array of all unique 32 bit hash values,
  1104. followed by an array of hash value data offsets, one for each hash value, then
  1105. the data for all hash values:
  1106. .. code-block:: none
  1107. .-------------.
  1108. | HEADER |
  1109. |-------------|
  1110. | BUCKETS |
  1111. |-------------|
  1112. | HASHES |
  1113. |-------------|
  1114. | OFFSETS |
  1115. |-------------|
  1116. | DATA |
  1117. `-------------'
  1118. The ``BUCKETS`` in the name tables are an index into the ``HASHES`` array. By
  1119. making all of the full 32 bit hash values contiguous in memory, we allow
  1120. ourselves to efficiently check for a match while touching as little memory as
  1121. possible. Most often checking the 32 bit hash values is as far as the lookup
  1122. goes. If it does match, it usually is a match with no collisions. So for a
  1123. table with "``n_buckets``" buckets, and "``n_hashes``" unique 32 bit hash
  1124. values, we can clarify the contents of the ``BUCKETS``, ``HASHES`` and
  1125. ``OFFSETS`` as:
  1126. .. code-block:: none
  1127. .-------------------------.
  1128. | HEADER.magic | uint32_t
  1129. | HEADER.version | uint16_t
  1130. | HEADER.hash_function | uint16_t
  1131. | HEADER.bucket_count | uint32_t
  1132. | HEADER.hashes_count | uint32_t
  1133. | HEADER.header_data_len | uint32_t
  1134. | HEADER_DATA | HeaderData
  1135. |-------------------------|
  1136. | BUCKETS | uint32_t[n_buckets] // 32 bit hash indexes
  1137. |-------------------------|
  1138. | HASHES | uint32_t[n_hashes] // 32 bit hash values
  1139. |-------------------------|
  1140. | OFFSETS | uint32_t[n_hashes] // 32 bit offsets to hash value data
  1141. |-------------------------|
  1142. | ALL HASH DATA |
  1143. `-------------------------'
  1144. So taking the exact same data from the standard hash example above we end up
  1145. with:
  1146. .. code-block:: none
  1147. .------------.
  1148. | HEADER |
  1149. |------------|
  1150. | 0 | BUCKETS[0]
  1151. | 2 | BUCKETS[1]
  1152. | 5 | BUCKETS[2]
  1153. | 6 | BUCKETS[3]
  1154. | | ...
  1155. | ... | BUCKETS[n_buckets]
  1156. |------------|
  1157. | 0x........ | HASHES[0]
  1158. | 0x........ | HASHES[1]
  1159. | 0x........ | HASHES[2]
  1160. | 0x........ | HASHES[3]
  1161. | 0x........ | HASHES[4]
  1162. | 0x........ | HASHES[5]
  1163. | 0x12345678 | HASHES[6] hash for BUCKETS[3]
  1164. | 0x29273623 | HASHES[7] hash for BUCKETS[3]
  1165. | 0x82638293 | HASHES[8] hash for BUCKETS[3]
  1166. | 0x........ | HASHES[9]
  1167. | 0x........ | HASHES[10]
  1168. | 0x........ | HASHES[11]
  1169. | 0x........ | HASHES[12]
  1170. | 0x........ | HASHES[13]
  1171. | 0x........ | HASHES[n_hashes]
  1172. |------------|
  1173. | 0x........ | OFFSETS[0]
  1174. | 0x........ | OFFSETS[1]
  1175. | 0x........ | OFFSETS[2]
  1176. | 0x........ | OFFSETS[3]
  1177. | 0x........ | OFFSETS[4]
  1178. | 0x........ | OFFSETS[5]
  1179. | 0x000034f0 | OFFSETS[6] offset for BUCKETS[3]
  1180. | 0x00003500 | OFFSETS[7] offset for BUCKETS[3]
  1181. | 0x00003550 | OFFSETS[8] offset for BUCKETS[3]
  1182. | 0x........ | OFFSETS[9]
  1183. | 0x........ | OFFSETS[10]
  1184. | 0x........ | OFFSETS[11]
  1185. | 0x........ | OFFSETS[12]
  1186. | 0x........ | OFFSETS[13]
  1187. | 0x........ | OFFSETS[n_hashes]
  1188. |------------|
  1189. | |
  1190. | |
  1191. | |
  1192. | |
  1193. | |
  1194. |------------|
  1195. 0x000034f0: | 0x00001203 | .debug_str ("erase")
  1196. | 0x00000004 | A 32 bit array count - number of HashData with name "erase"
  1197. | 0x........ | HashData[0]
  1198. | 0x........ | HashData[1]
  1199. | 0x........ | HashData[2]
  1200. | 0x........ | HashData[3]
  1201. | 0x00000000 | String offset into .debug_str (terminate data for hash)
  1202. |------------|
  1203. 0x00003500: | 0x00001203 | String offset into .debug_str ("collision")
  1204. | 0x00000002 | A 32 bit array count - number of HashData with name "collision"
  1205. | 0x........ | HashData[0]
  1206. | 0x........ | HashData[1]
  1207. | 0x00001203 | String offset into .debug_str ("dump")
  1208. | 0x00000003 | A 32 bit array count - number of HashData with name "dump"
  1209. | 0x........ | HashData[0]
  1210. | 0x........ | HashData[1]
  1211. | 0x........ | HashData[2]
  1212. | 0x00000000 | String offset into .debug_str (terminate data for hash)
  1213. |------------|
  1214. 0x00003550: | 0x00001203 | String offset into .debug_str ("main")
  1215. | 0x00000009 | A 32 bit array count - number of HashData with name "main"
  1216. | 0x........ | HashData[0]
  1217. | 0x........ | HashData[1]
  1218. | 0x........ | HashData[2]
  1219. | 0x........ | HashData[3]
  1220. | 0x........ | HashData[4]
  1221. | 0x........ | HashData[5]
  1222. | 0x........ | HashData[6]
  1223. | 0x........ | HashData[7]
  1224. | 0x........ | HashData[8]
  1225. | 0x00000000 | String offset into .debug_str (terminate data for hash)
  1226. `------------'
  1227. So we still have all of the same data, we just organize it more efficiently for
  1228. debugger lookup. If we repeat the same "``printf``" lookup from above, we
  1229. would hash "``printf``" and find it matches ``BUCKETS[3]`` by taking the 32 bit
  1230. hash value and modulo it by ``n_buckets``. ``BUCKETS[3]`` contains "6" which
  1231. is the index into the ``HASHES`` table. We would then compare any consecutive
  1232. 32 bit hashes values in the ``HASHES`` array as long as the hashes would be in
  1233. ``BUCKETS[3]``. We do this by verifying that each subsequent hash value modulo
  1234. ``n_buckets`` is still 3. In the case of a failed lookup we would access the
  1235. memory for ``BUCKETS[3]``, and then compare a few consecutive 32 bit hashes
  1236. before we know that we have no match. We don't end up marching through
  1237. multiple words of memory and we really keep the number of processor data cache
  1238. lines being accessed as small as possible.
  1239. The string hash that is used for these lookup tables is the Daniel J.
  1240. Bernstein hash which is also used in the ELF ``GNU_HASH`` sections. It is a
  1241. very good hash for all kinds of names in programs with very few hash
  1242. collisions.
  1243. Empty buckets are designated by using an invalid hash index of ``UINT32_MAX``.
  1244. Details
  1245. ^^^^^^^
  1246. These name hash tables are designed to be generic where specializations of the
  1247. table get to define additional data that goes into the header ("``HeaderData``"),
  1248. how the string value is stored ("``KeyType``") and the content of the data for each
  1249. hash value.
  1250. Header Layout
  1251. """""""""""""
  1252. The header has a fixed part, and the specialized part. The exact format of the
  1253. header is:
  1254. .. code-block:: c
  1255. struct Header
  1256. {
  1257. uint32_t magic; // 'HASH' magic value to allow endian detection
  1258. uint16_t version; // Version number
  1259. uint16_t hash_function; // The hash function enumeration that was used
  1260. uint32_t bucket_count; // The number of buckets in this hash table
  1261. uint32_t hashes_count; // The total number of unique hash values and hash data offsets in this table
  1262. uint32_t header_data_len; // The bytes to skip to get to the hash indexes (buckets) for correct alignment
  1263. // Specifically the length of the following HeaderData field - this does not
  1264. // include the size of the preceding fields
  1265. HeaderData header_data; // Implementation specific header data
  1266. };
  1267. The header starts with a 32 bit "``magic``" value which must be ``'HASH'``
  1268. encoded as an ASCII integer. This allows the detection of the start of the
  1269. hash table and also allows the table's byte order to be determined so the table
  1270. can be correctly extracted. The "``magic``" value is followed by a 16 bit
  1271. ``version`` number which allows the table to be revised and modified in the
  1272. future. The current version number is 1. ``hash_function`` is a ``uint16_t``
  1273. enumeration that specifies which hash function was used to produce this table.
  1274. The current values for the hash function enumerations include:
  1275. .. code-block:: c
  1276. enum HashFunctionType
  1277. {
  1278. eHashFunctionDJB = 0u, // Daniel J Bernstein hash function
  1279. };
  1280. ``bucket_count`` is a 32 bit unsigned integer that represents how many buckets
  1281. are in the ``BUCKETS`` array. ``hashes_count`` is the number of unique 32 bit
  1282. hash values that are in the ``HASHES`` array, and is the same number of offsets
  1283. are contained in the ``OFFSETS`` array. ``header_data_len`` specifies the size
  1284. in bytes of the ``HeaderData`` that is filled in by specialized versions of
  1285. this table.
  1286. Fixed Lookup
  1287. """"""""""""
  1288. The header is followed by the buckets, hashes, offsets, and hash value data.
  1289. .. code-block:: c
  1290. struct FixedTable
  1291. {
  1292. uint32_t buckets[Header.bucket_count]; // An array of hash indexes into the "hashes[]" array below
  1293. uint32_t hashes [Header.hashes_count]; // Every unique 32 bit hash for the entire table is in this table
  1294. uint32_t offsets[Header.hashes_count]; // An offset that corresponds to each item in the "hashes[]" array above
  1295. };
  1296. ``buckets`` is an array of 32 bit indexes into the ``hashes`` array. The
  1297. ``hashes`` array contains all of the 32 bit hash values for all names in the
  1298. hash table. Each hash in the ``hashes`` table has an offset in the ``offsets``
  1299. array that points to the data for the hash value.
  1300. This table setup makes it very easy to repurpose these tables to contain
  1301. different data, while keeping the lookup mechanism the same for all tables.
  1302. This layout also makes it possible to save the table to disk and map it in
  1303. later and do very efficient name lookups with little or no parsing.
  1304. DWARF lookup tables can be implemented in a variety of ways and can store a lot
  1305. of information for each name. We want to make the DWARF tables extensible and
  1306. able to store the data efficiently so we have used some of the DWARF features
  1307. that enable efficient data storage to define exactly what kind of data we store
  1308. for each name.
  1309. The ``HeaderData`` contains a definition of the contents of each HashData chunk.
  1310. We might want to store an offset to all of the debug information entries (DIEs)
  1311. for each name. To keep things extensible, we create a list of items, or
  1312. Atoms, that are contained in the data for each name. First comes the type of
  1313. the data in each atom:
  1314. .. code-block:: c
  1315. enum AtomType
  1316. {
  1317. eAtomTypeNULL = 0u,
  1318. eAtomTypeDIEOffset = 1u, // DIE offset, check form for encoding
  1319. eAtomTypeCUOffset = 2u, // DIE offset of the compiler unit header that contains the item in question
  1320. eAtomTypeTag = 3u, // DW_TAG_xxx value, should be encoded as DW_FORM_data1 (if no tags exceed 255) or DW_FORM_data2
  1321. eAtomTypeNameFlags = 4u, // Flags from enum NameFlags
  1322. eAtomTypeTypeFlags = 5u, // Flags from enum TypeFlags
  1323. };
  1324. The enumeration values and their meanings are:
  1325. .. code-block:: none
  1326. eAtomTypeNULL - a termination atom that specifies the end of the atom list
  1327. eAtomTypeDIEOffset - an offset into the .debug_info section for the DWARF DIE for this name
  1328. eAtomTypeCUOffset - an offset into the .debug_info section for the CU that contains the DIE
  1329. eAtomTypeDIETag - The DW_TAG_XXX enumeration value so you don't have to parse the DWARF to see what it is
  1330. eAtomTypeNameFlags - Flags for functions and global variables (isFunction, isInlined, isExternal...)
  1331. eAtomTypeTypeFlags - Flags for types (isCXXClass, isObjCClass, ...)
  1332. Then we allow each atom type to define the atom type and how the data for each
  1333. atom type data is encoded:
  1334. .. code-block:: c
  1335. struct Atom
  1336. {
  1337. uint16_t type; // AtomType enum value
  1338. uint16_t form; // DWARF DW_FORM_XXX defines
  1339. };
  1340. The ``form`` type above is from the DWARF specification and defines the exact
  1341. encoding of the data for the Atom type. See the DWARF specification for the
  1342. ``DW_FORM_`` definitions.
  1343. .. code-block:: c
  1344. struct HeaderData
  1345. {
  1346. uint32_t die_offset_base;
  1347. uint32_t atom_count;
  1348. Atoms atoms[atom_count0];
  1349. };
  1350. ``HeaderData`` defines the base DIE offset that should be added to any atoms
  1351. that are encoded using the ``DW_FORM_ref1``, ``DW_FORM_ref2``,
  1352. ``DW_FORM_ref4``, ``DW_FORM_ref8`` or ``DW_FORM_ref_udata``. It also defines
  1353. what is contained in each ``HashData`` object -- ``Atom.form`` tells us how large
  1354. each field will be in the ``HashData`` and the ``Atom.type`` tells us how this data
  1355. should be interpreted.
  1356. For the current implementations of the "``.apple_names``" (all functions +
  1357. globals), the "``.apple_types``" (names of all types that are defined), and
  1358. the "``.apple_namespaces``" (all namespaces), we currently set the ``Atom``
  1359. array to be:
  1360. .. code-block:: c
  1361. HeaderData.atom_count = 1;
  1362. HeaderData.atoms[0].type = eAtomTypeDIEOffset;
  1363. HeaderData.atoms[0].form = DW_FORM_data4;
  1364. This defines the contents to be the DIE offset (eAtomTypeDIEOffset) that is
  1365. encoded as a 32 bit value (DW_FORM_data4). This allows a single name to have
  1366. multiple matching DIEs in a single file, which could come up with an inlined
  1367. function for instance. Future tables could include more information about the
  1368. DIE such as flags indicating if the DIE is a function, method, block,
  1369. or inlined.
  1370. The KeyType for the DWARF table is a 32 bit string table offset into the
  1371. ".debug_str" table. The ".debug_str" is the string table for the DWARF which
  1372. may already contain copies of all of the strings. This helps make sure, with
  1373. help from the compiler, that we reuse the strings between all of the DWARF
  1374. sections and keeps the hash table size down. Another benefit to having the
  1375. compiler generate all strings as DW_FORM_strp in the debug info, is that
  1376. DWARF parsing can be made much faster.
  1377. After a lookup is made, we get an offset into the hash data. The hash data
  1378. needs to be able to deal with 32 bit hash collisions, so the chunk of data
  1379. at the offset in the hash data consists of a triple:
  1380. .. code-block:: c
  1381. uint32_t str_offset
  1382. uint32_t hash_data_count
  1383. HashData[hash_data_count]
  1384. If "str_offset" is zero, then the bucket contents are done. 99.9% of the
  1385. hash data chunks contain a single item (no 32 bit hash collision):
  1386. .. code-block:: none
  1387. .------------.
  1388. | 0x00001023 | uint32_t KeyType (.debug_str[0x0001023] => "main")
  1389. | 0x00000004 | uint32_t HashData count
  1390. | 0x........ | uint32_t HashData[0] DIE offset
  1391. | 0x........ | uint32_t HashData[1] DIE offset
  1392. | 0x........ | uint32_t HashData[2] DIE offset
  1393. | 0x........ | uint32_t HashData[3] DIE offset
  1394. | 0x00000000 | uint32_t KeyType (end of hash chain)
  1395. `------------'
  1396. If there are collisions, you will have multiple valid string offsets:
  1397. .. code-block:: none
  1398. .------------.
  1399. | 0x00001023 | uint32_t KeyType (.debug_str[0x0001023] => "main")
  1400. | 0x00000004 | uint32_t HashData count
  1401. | 0x........ | uint32_t HashData[0] DIE offset
  1402. | 0x........ | uint32_t HashData[1] DIE offset
  1403. | 0x........ | uint32_t HashData[2] DIE offset
  1404. | 0x........ | uint32_t HashData[3] DIE offset
  1405. | 0x00002023 | uint32_t KeyType (.debug_str[0x0002023] => "print")
  1406. | 0x00000002 | uint32_t HashData count
  1407. | 0x........ | uint32_t HashData[0] DIE offset
  1408. | 0x........ | uint32_t HashData[1] DIE offset
  1409. | 0x00000000 | uint32_t KeyType (end of hash chain)
  1410. `------------'
  1411. Current testing with real world C++ binaries has shown that there is around 1
  1412. 32 bit hash collision per 100,000 name entries.
  1413. Contents
  1414. ^^^^^^^^
  1415. As we said, we want to strictly define exactly what is included in the
  1416. different tables. For DWARF, we have 3 tables: "``.apple_names``",
  1417. "``.apple_types``", and "``.apple_namespaces``".
  1418. "``.apple_names``" sections should contain an entry for each DWARF DIE whose
  1419. ``DW_TAG`` is a ``DW_TAG_label``, ``DW_TAG_inlined_subroutine``, or
  1420. ``DW_TAG_subprogram`` that has address attributes: ``DW_AT_low_pc``,
  1421. ``DW_AT_high_pc``, ``DW_AT_ranges`` or ``DW_AT_entry_pc``. It also contains
  1422. ``DW_TAG_variable`` DIEs that have a ``DW_OP_addr`` in the location (global and
  1423. static variables). All global and static variables should be included,
  1424. including those scoped within functions and classes. For example using the
  1425. following code:
  1426. .. code-block:: c
  1427. static int var = 0;
  1428. void f ()
  1429. {
  1430. static int var = 0;
  1431. }
  1432. Both of the static ``var`` variables would be included in the table. All
  1433. functions should emit both their full names and their basenames. For C or C++,
  1434. the full name is the mangled name (if available) which is usually in the
  1435. ``DW_AT_MIPS_linkage_name`` attribute, and the ``DW_AT_name`` contains the
  1436. function basename. If global or static variables have a mangled name in a
  1437. ``DW_AT_MIPS_linkage_name`` attribute, this should be emitted along with the
  1438. simple name found in the ``DW_AT_name`` attribute.
  1439. "``.apple_types``" sections should contain an entry for each DWARF DIE whose
  1440. tag is one of:
  1441. * DW_TAG_array_type
  1442. * DW_TAG_class_type
  1443. * DW_TAG_enumeration_type
  1444. * DW_TAG_pointer_type
  1445. * DW_TAG_reference_type
  1446. * DW_TAG_string_type
  1447. * DW_TAG_structure_type
  1448. * DW_TAG_subroutine_type
  1449. * DW_TAG_typedef
  1450. * DW_TAG_union_type
  1451. * DW_TAG_ptr_to_member_type
  1452. * DW_TAG_set_type
  1453. * DW_TAG_subrange_type
  1454. * DW_TAG_base_type
  1455. * DW_TAG_const_type
  1456. * DW_TAG_file_type
  1457. * DW_TAG_namelist
  1458. * DW_TAG_packed_type
  1459. * DW_TAG_volatile_type
  1460. * DW_TAG_restrict_type
  1461. * DW_TAG_atomic_type
  1462. * DW_TAG_interface_type
  1463. * DW_TAG_unspecified_type
  1464. * DW_TAG_shared_type
  1465. Only entries with a ``DW_AT_name`` attribute are included, and the entry must
  1466. not be a forward declaration (``DW_AT_declaration`` attribute with a non-zero
  1467. value). For example, using the following code:
  1468. .. code-block:: c
  1469. int main ()
  1470. {
  1471. int *b = 0;
  1472. return *b;
  1473. }
  1474. We get a few type DIEs:
  1475. .. code-block:: none
  1476. 0x00000067: TAG_base_type [5]
  1477. AT_encoding( DW_ATE_signed )
  1478. AT_name( "int" )
  1479. AT_byte_size( 0x04 )
  1480. 0x0000006e: TAG_pointer_type [6]
  1481. AT_type( {0x00000067} ( int ) )
  1482. AT_byte_size( 0x08 )
  1483. The DW_TAG_pointer_type is not included because it does not have a ``DW_AT_name``.
  1484. "``.apple_namespaces``" section should contain all ``DW_TAG_namespace`` DIEs.
  1485. If we run into a namespace that has no name this is an anonymous namespace, and
  1486. the name should be output as "``(anonymous namespace)``" (without the quotes).
  1487. Why? This matches the output of the ``abi::cxa_demangle()`` that is in the
  1488. standard C++ library that demangles mangled names.
  1489. Language Extensions and File Format Changes
  1490. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1491. Objective-C Extensions
  1492. """"""""""""""""""""""
  1493. "``.apple_objc``" section should contain all ``DW_TAG_subprogram`` DIEs for an
  1494. Objective-C class. The name used in the hash table is the name of the
  1495. Objective-C class itself. If the Objective-C class has a category, then an
  1496. entry is made for both the class name without the category, and for the class
  1497. name with the category. So if we have a DIE at offset 0x1234 with a name of
  1498. method "``-[NSString(my_additions) stringWithSpecialString:]``", we would add
  1499. an entry for "``NSString``" that points to DIE 0x1234, and an entry for
  1500. "``NSString(my_additions)``" that points to 0x1234. This allows us to quickly
  1501. track down all Objective-C methods for an Objective-C class when doing
  1502. expressions. It is needed because of the dynamic nature of Objective-C where
  1503. anyone can add methods to a class. The DWARF for Objective-C methods is also
  1504. emitted differently from C++ classes where the methods are not usually
  1505. contained in the class definition, they are scattered about across one or more
  1506. compile units. Categories can also be defined in different shared libraries.
  1507. So we need to be able to quickly find all of the methods and class functions
  1508. given the Objective-C class name, or quickly find all methods and class
  1509. functions for a class + category name. This table does not contain any
  1510. selector names, it just maps Objective-C class names (or class names +
  1511. category) to all of the methods and class functions. The selectors are added
  1512. as function basenames in the "``.debug_names``" section.
  1513. In the "``.apple_names``" section for Objective-C functions, the full name is
  1514. the entire function name with the brackets ("``-[NSString
  1515. stringWithCString:]``") and the basename is the selector only
  1516. ("``stringWithCString:``").
  1517. Mach-O Changes
  1518. """"""""""""""
  1519. The sections names for the apple hash tables are for non-mach-o files. For
  1520. mach-o files, the sections should be contained in the ``__DWARF`` segment with
  1521. names as follows:
  1522. * "``.apple_names``" -> "``__apple_names``"
  1523. * "``.apple_types``" -> "``__apple_types``"
  1524. * "``.apple_namespaces``" -> "``__apple_namespac``" (16 character limit)
  1525. * "``.apple_objc``" -> "``__apple_objc``"
  1526. .. _codeview:
  1527. CodeView Debug Info Format
  1528. ==========================
  1529. LLVM supports emitting CodeView, the Microsoft debug info format, and this
  1530. section describes the design and implementation of that support.
  1531. Format Background
  1532. -----------------
  1533. CodeView as a format is clearly oriented around C++ debugging, and in C++, the
  1534. majority of debug information tends to be type information. Therefore, the
  1535. overriding design constraint of CodeView is the separation of type information
  1536. from other "symbol" information so that type information can be efficiently
  1537. merged across translation units. Both type information and symbol information is
  1538. generally stored as a sequence of records, where each record begins with a
  1539. 16-bit record size and a 16-bit record kind.
  1540. Type information is usually stored in the ``.debug$T`` section of the object
  1541. file. All other debug info, such as line info, string table, symbol info, and
  1542. inlinee info, is stored in one or more ``.debug$S`` sections. There may only be
  1543. one ``.debug$T`` section per object file, since all other debug info refers to
  1544. it. If a PDB (enabled by the ``/Zi`` MSVC option) was used during compilation,
  1545. the ``.debug$T`` section will contain only an ``LF_TYPESERVER2`` record pointing
  1546. to the PDB. When using PDBs, symbol information appears to remain in the object
  1547. file ``.debug$S`` sections.
  1548. Type records are referred to by their index, which is the number of records in
  1549. the stream before a given record plus ``0x1000``. Many common basic types, such
  1550. as the basic integral types and unqualified pointers to them, are represented
  1551. using type indices less than ``0x1000``. Such basic types are built in to
  1552. CodeView consumers and do not require type records.
  1553. Each type record may only contain type indices that are less than its own type
  1554. index. This ensures that the graph of type stream references is acyclic. While
  1555. the source-level type graph may contain cycles through pointer types (consider a
  1556. linked list struct), these cycles are removed from the type stream by always
  1557. referring to the forward declaration record of user-defined record types. Only
  1558. "symbol" records in the ``.debug$S`` streams may refer to complete,
  1559. non-forward-declaration type records.
  1560. Working with CodeView
  1561. ---------------------
  1562. These are instructions for some common tasks for developers working to improve
  1563. LLVM's CodeView support. Most of them revolve around using the CodeView dumper
  1564. embedded in ``llvm-readobj``.
  1565. * Testing MSVC's output::
  1566. $ cl -c -Z7 foo.cpp # Use /Z7 to keep types in the object file
  1567. $ llvm-readobj --codeview foo.obj
  1568. * Getting LLVM IR debug info out of Clang::
  1569. $ clang -g -gcodeview --target=x86_64-windows-msvc foo.cpp -S -emit-llvm
  1570. Use this to generate LLVM IR for LLVM test cases.
  1571. * Generate and dump CodeView from LLVM IR metadata::
  1572. $ llc foo.ll -filetype=obj -o foo.obj
  1573. $ llvm-readobj --codeview foo.obj > foo.txt
  1574. Use this pattern in lit test cases and FileCheck the output of llvm-readobj
  1575. Improving LLVM's CodeView support is a process of finding interesting type
  1576. records, constructing a C++ test case that makes MSVC emit those records,
  1577. dumping the records, understanding them, and then generating equivalent records
  1578. in LLVM's backend.
  1579. Testing Debug Info Preservation in Optimizations
  1580. ================================================
  1581. The following paragraphs are an introduction to the debugify utility
  1582. and examples of how to use it in regression tests to check debug info
  1583. preservation after optimizations.
  1584. The ``debugify`` utility
  1585. ------------------------
  1586. The ``debugify`` synthetic debug info testing utility consists of two
  1587. main parts. The ``debugify`` pass and the ``check-debugify`` one. They are
  1588. meant to be used with ``opt`` for development purposes.
  1589. The first applies synthetic debug information to every instruction of the module,
  1590. while the latter checks that this DI is still available after an optimization
  1591. has occurred, reporting any errors/warnings while doing so.
  1592. The instructions are assigned sequentially increasing line locations,
  1593. and are immediately used by debug value intrinsics when possible.
  1594. For example, here is a module before:
  1595. .. code-block:: llvm
  1596. define void @f(i32* %x) {
  1597. entry:
  1598. %x.addr = alloca i32*, align 8
  1599. store i32* %x, i32** %x.addr, align 8
  1600. %0 = load i32*, i32** %x.addr, align 8
  1601. store i32 10, i32* %0, align 4
  1602. ret void
  1603. }
  1604. and after running ``opt -debugify`` on it we get:
  1605. .. code-block:: text
  1606. define void @f(i32* %x) !dbg !6 {
  1607. entry:
  1608. %x.addr = alloca i32*, align 8, !dbg !12
  1609. call void @llvm.dbg.value(metadata i32** %x.addr, metadata !9, metadata !DIExpression()), !dbg !12
  1610. store i32* %x, i32** %x.addr, align 8, !dbg !13
  1611. %0 = load i32*, i32** %x.addr, align 8, !dbg !14
  1612. call void @llvm.dbg.value(metadata i32* %0, metadata !11, metadata !DIExpression()), !dbg !14
  1613. store i32 10, i32* %0, align 4, !dbg !15
  1614. ret void, !dbg !16
  1615. }
  1616. !llvm.dbg.cu = !{!0}
  1617. !llvm.debugify = !{!3, !4}
  1618. !llvm.module.flags = !{!5}
  1619. !0 = distinct !DICompileUnit(language: DW_LANG_C, file: !1, producer: "debugify", isOptimized: true, runtimeVersion: 0, emissionKind: FullDebug, enums: !2)
  1620. !1 = !DIFile(filename: "debugify-sample.ll", directory: "/")
  1621. !2 = !{}
  1622. !3 = !{i32 5}
  1623. !4 = !{i32 2}
  1624. !5 = !{i32 2, !"Debug Info Version", i32 3}
  1625. !6 = distinct !DISubprogram(name: "f", linkageName: "f", scope: null, file: !1, line: 1, type: !7, isLocal: false, isDefinition: true, scopeLine: 1, isOptimized: true, unit: !0, retainedNodes: !8)
  1626. !7 = !DISubroutineType(types: !2)
  1627. !8 = !{!9, !11}
  1628. !9 = !DILocalVariable(name: "1", scope: !6, file: !1, line: 1, type: !10)
  1629. !10 = !DIBasicType(name: "ty64", size: 64, encoding: DW_ATE_unsigned)
  1630. !11 = !DILocalVariable(name: "2", scope: !6, file: !1, line: 3, type: !10)
  1631. !12 = !DILocation(line: 1, column: 1, scope: !6)
  1632. !13 = !DILocation(line: 2, column: 1, scope: !6)
  1633. !14 = !DILocation(line: 3, column: 1, scope: !6)
  1634. !15 = !DILocation(line: 4, column: 1, scope: !6)
  1635. !16 = !DILocation(line: 5, column: 1, scope: !6)
  1636. The following is an example of the -check-debugify output:
  1637. .. code-block:: none
  1638. $ opt -enable-debugify -loop-vectorize llvm/test/Transforms/LoopVectorize/i8-induction.ll -disable-output
  1639. ERROR: Instruction with empty DebugLoc in function f -- %index = phi i32 [ 0, %vector.ph ], [ %index.next, %vector.body ]
  1640. Errors/warnings can range from instructions with empty debug location to an
  1641. instruction having a type that's incompatible with the source variable it describes,
  1642. all the way to missing lines and missing debug value intrinsics.
  1643. Fixing errors
  1644. ^^^^^^^^^^^^^
  1645. Each of the errors above has a relevant API available to fix it.
  1646. * In the case of missing debug location, ``Instruction::setDebugLoc`` or possibly
  1647. ``IRBuilder::setCurrentDebugLocation`` when using a Builder and the new location
  1648. should be reused.
  1649. * When a debug value has incompatible type ``llvm::replaceAllDbgUsesWith`` can be used.
  1650. After a RAUW call an incompatible type error can occur because RAUW does not handle
  1651. widening and narrowing of variables while ``llvm::replaceAllDbgUsesWith`` does. It is
  1652. also capable of changing the DWARF expression used by the debugger to describe the variable.
  1653. It also prevents use-before-def by salvaging or deleting invalid debug values.
  1654. * When a debug value is missing ``llvm::salvageDebugInfo`` can be used when no replacement
  1655. exists, or ``llvm::replaceAllDbgUsesWith`` when a replacement exists.
  1656. Using ``debugify``
  1657. ------------------
  1658. In order for ``check-debugify`` to work, the DI must be coming from
  1659. ``debugify``. Thus, modules with existing DI will be skipped.
  1660. The most straightforward way to use ``debugify`` is as follows::
  1661. $ opt -debugify -pass-to-test -check-debugify sample.ll
  1662. This will inject synthetic DI to ``sample.ll`` run the ``pass-to-test``
  1663. and then check for missing DI.
  1664. Some other ways to run debugify are avaliable:
  1665. .. code-block:: bash
  1666. # Same as the above example.
  1667. $ opt -enable-debugify -pass-to-test sample.ll
  1668. # Suppresses verbose debugify output.
  1669. $ opt -enable-debugify -debugify-quiet -pass-to-test sample.ll
  1670. # Prepend -debugify before and append -check-debugify -strip after
  1671. # each pass on the pipeline (similar to -verify-each).
  1672. $ opt -debugify-each -O2 sample.ll
  1673. ``debugify`` can also be used to test a backend, e.g:
  1674. .. code-block:: bash
  1675. $ opt -debugify < sample.ll | llc -o -
  1676. ``debugify`` in regression tests
  1677. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1678. The ``-debugify`` pass is especially helpful when it comes to testing that
  1679. a given pass preserves DI while transforming the module. For this to work,
  1680. the ``-debugify`` output must be stable enough to use in regression tests.
  1681. Changes to this pass are not allowed to break existing tests.
  1682. It allows us to test for DI loss in the same tests we check that the
  1683. transformation is actually doing what it should.
  1684. Here is an example from ``test/Transforms/InstCombine/cast-mul-select.ll``:
  1685. .. code-block:: llvm
  1686. ; RUN: opt < %s -debugify -instcombine -S | FileCheck %s --check-prefix=DEBUGINFO
  1687. define i32 @mul(i32 %x, i32 %y) {
  1688. ; DBGINFO-LABEL: @mul(
  1689. ; DBGINFO-NEXT: [[C:%.*]] = mul i32 {{.*}}
  1690. ; DBGINFO-NEXT: call void @llvm.dbg.value(metadata i32 [[C]]
  1691. ; DBGINFO-NEXT: [[D:%.*]] = and i32 {{.*}}
  1692. ; DBGINFO-NEXT: call void @llvm.dbg.value(metadata i32 [[D]]
  1693. %A = trunc i32 %x to i8
  1694. %B = trunc i32 %y to i8
  1695. %C = mul i8 %A, %B
  1696. %D = zext i8 %C to i32
  1697. ret i32 %D
  1698. }
  1699. Here we test that the two ``dbg.value`` instrinsics are preserved and
  1700. are correctly pointing to the ``[[C]]`` and ``[[D]]`` variables.
  1701. .. note::
  1702. Note, that when writing this kind of regression tests, it is important
  1703. to make them as robust as possible. That's why we should try to avoid
  1704. hardcoding line/variable numbers in check lines. If for example you test
  1705. for a ``DILocation`` to have a specific line number, and someone later adds
  1706. an instruction before the one we check the test will fail. In the cases this
  1707. can't be avoided (say, if a test wouldn't be precise enough), moving the
  1708. test to its own file is preferred.