llvm-symbolizer: don't always run demangler on global object names
[oota-llvm.git] / docs / SourceLevelDebugging.rst
1 ================================
2 Source Level Debugging with LLVM
3 ================================
4
5 .. contents::
6    :local:
7
8 Introduction
9 ============
10
11 This document is the central repository for all information pertaining to debug
12 information in LLVM.  It describes the :ref:`actual format that the LLVM debug
13 information takes <format>`, which is useful for those interested in creating
14 front-ends or dealing directly with the information.  Further, this document
15 provides specific examples of what debug information for C/C++ looks like.
16
17 Philosophy behind LLVM debugging information
18 --------------------------------------------
19
20 The idea of the LLVM debugging information is to capture how the important
21 pieces of the source-language's Abstract Syntax Tree map onto LLVM code.
22 Several design aspects have shaped the solution that appears here.  The
23 important ones are:
24
25 * Debugging information should have very little impact on the rest of the
26   compiler.  No transformations, analyses, or code generators should need to
27   be modified because of debugging information.
28
29 * LLVM optimizations should interact in :ref:`well-defined and easily described
30   ways <intro_debugopt>` with the debugging information.
31
32 * Because LLVM is designed to support arbitrary programming languages,
33   LLVM-to-LLVM tools should not need to know anything about the semantics of
34   the source-level-language.
35
36 * Source-level languages are often **widely** different from one another.
37   LLVM should not put any restrictions of the flavor of the source-language,
38   and the debugging information should work with any language.
39
40 * With code generator support, it should be possible to use an LLVM compiler
41   to compile a program to native machine code and standard debugging
42   formats.  This allows compatibility with traditional machine-code level
43   debuggers, like GDB or DBX.
44
45 The approach used by the LLVM implementation is to use a small set of
46 :ref:`intrinsic functions <format_common_intrinsics>` to define a mapping
47 between LLVM program objects and the source-level objects.  The description of
48 the source-level program is maintained in LLVM metadata in an
49 :ref:`implementation-defined format <ccxx_frontend>` (the C/C++ front-end
50 currently uses working draft 7 of the `DWARF 3 standard
51 <http://www.eagercon.com/dwarf/dwarf3std.htm>`_).
52
53 When a program is being debugged, a debugger interacts with the user and turns
54 the stored debug information into source-language specific information.  As
55 such, a debugger must be aware of the source-language, and is thus tied to a
56 specific language or family of languages.
57
58 Debug information consumers
59 ---------------------------
60
61 The role of debug information is to provide meta information normally stripped
62 away during the compilation process.  This meta information provides an LLVM
63 user a relationship between generated code and the original program source
64 code.
65
66 Currently, debug information is consumed by DwarfDebug to produce dwarf
67 information used by the gdb debugger.  Other targets could use the same
68 information to produce stabs or other debug forms.
69
70 It would also be reasonable to use debug information to feed profiling tools
71 for analysis of generated code, or, tools for reconstructing the original
72 source from generated code.
73
74 TODO - expound a bit more.
75
76 .. _intro_debugopt:
77
78 Debugging optimized code
79 ------------------------
80
81 An extremely high priority of LLVM debugging information is to make it interact
82 well with optimizations and analysis.  In particular, the LLVM debug
83 information provides the following guarantees:
84
85 * LLVM debug information **always provides information to accurately read
86   the source-level state of the program**, regardless of which LLVM
87   optimizations have been run, and without any modification to the
88   optimizations themselves.  However, some optimizations may impact the
89   ability to modify the current state of the program with a debugger, such
90   as setting program variables, or calling functions that have been
91   deleted.
92
93 * As desired, LLVM optimizations can be upgraded to be aware of the LLVM
94   debugging information, allowing them to update the debugging information
95   as they perform aggressive optimizations.  This means that, with effort,
96   the LLVM optimizers could optimize debug code just as well as non-debug
97   code.
98
99 * LLVM debug information does not prevent optimizations from
100   happening (for example inlining, basic block reordering/merging/cleanup,
101   tail duplication, etc).
102
103 * LLVM debug information is automatically optimized along with the rest of
104   the program, using existing facilities.  For example, duplicate
105   information is automatically merged by the linker, and unused information
106   is automatically removed.
107
108 Basically, the debug information allows you to compile a program with
109 "``-O0 -g``" and get full debug information, allowing you to arbitrarily modify
110 the program as it executes from a debugger.  Compiling a program with
111 "``-O3 -g``" gives you full debug information that is always available and
112 accurate for reading (e.g., you get accurate stack traces despite tail call
113 elimination and inlining), but you might lose the ability to modify the program
114 and call functions where were optimized out of the program, or inlined away
115 completely.
116
117 :ref:`LLVM test suite <test-suite-quickstart>` provides a framework to test
118 optimizer's handling of debugging information.  It can be run like this:
119
120 .. code-block:: bash
121
122   % cd llvm/projects/test-suite/MultiSource/Benchmarks  # or some other level
123   % make TEST=dbgopt
124
125 This will test impact of debugging information on optimization passes.  If
126 debugging information influences optimization passes then it will be reported
127 as a failure.  See :doc:`TestingGuide` for more information on LLVM test
128 infrastructure and how to run various tests.
129
130 .. _format:
131
132 Debugging information format
133 ============================
134
135 LLVM debugging information has been carefully designed to make it possible for
136 the optimizer to optimize the program and debugging information without
137 necessarily having to know anything about debugging information.  In
138 particular, the use of metadata avoids duplicated debugging information from
139 the beginning, and the global dead code elimination pass automatically deletes
140 debugging information for a function if it decides to delete the function.
141
142 To do this, most of the debugging information (descriptors for types,
143 variables, functions, source files, etc) is inserted by the language front-end
144 in the form of LLVM metadata.
145
146 Debug information is designed to be agnostic about the target debugger and
147 debugging information representation (e.g. DWARF/Stabs/etc).  It uses a generic
148 pass to decode the information that represents variables, types, functions,
149 namespaces, etc: this allows for arbitrary source-language semantics and
150 type-systems to be used, as long as there is a module written for the target
151 debugger to interpret the information.
152
153 To provide basic functionality, the LLVM debugger does have to make some
154 assumptions about the source-level language being debugged, though it keeps
155 these to a minimum.  The only common features that the LLVM debugger assumes
156 exist are :ref:`source files <format_files>`, and :ref:`program objects
157 <format_global_variables>`.  These abstract objects are used by a debugger to
158 form stack traces, show information about local variables, etc.
159
160 This section of the documentation first describes the representation aspects
161 common to any source-language.  :ref:`ccxx_frontend` describes the data layout
162 conventions used by the C and C++ front-ends.
163
164 Debug information descriptors
165 -----------------------------
166
167 In consideration of the complexity and volume of debug information, LLVM
168 provides a specification for well formed debug descriptors.
169
170 Consumers of LLVM debug information expect the descriptors for program objects
171 to start in a canonical format, but the descriptors can include additional
172 information appended at the end that is source-language specific.  All debugging
173 information objects start with a tag to indicate what type of object it is.
174 The source-language is allowed to define its own objects, by using unreserved
175 tag numbers.  We recommend using with tags in the range 0x1000 through 0x2000
176 (there is a defined ``enum DW_TAG_user_base = 0x1000``.)
177
178 The fields of debug descriptors used internally by LLVM are restricted to only
179 the simple data types ``i32``, ``i1``, ``float``, ``double``, ``mdstring`` and
180 ``mdnode``.
181
182 .. code-block:: llvm
183
184   !1 = metadata !{
185     i32,   ;; A tag
186     ...
187   }
188
189 <a name="LLVMDebugVersion">The first field of a descriptor is always an
190 ``i32`` containing a tag value identifying the content of the descriptor.
191 The remaining fields are specific to the descriptor.  The values of tags are
192 loosely bound to the tag values of DWARF information entries.  However, that
193 does not restrict the use of the information supplied to DWARF targets.
194
195 The details of the various descriptors follow.
196
197 Compile unit descriptors
198 ^^^^^^^^^^^^^^^^^^^^^^^^
199
200 .. code-block:: llvm
201
202   !0 = metadata !{
203     i32,       ;; Tag = 17 (DW_TAG_compile_unit)
204     metadata,  ;; Source directory (including trailing slash) & file pair
205     i32,       ;; DWARF language identifier (ex. DW_LANG_C89)
206     metadata   ;; Producer (ex. "4.0.1 LLVM (LLVM research group)")
207     i1,        ;; True if this is optimized.
208     metadata,  ;; Flags
209     i32        ;; Runtime version
210     metadata   ;; List of enums types
211     metadata   ;; List of retained types
212     metadata   ;; List of subprograms
213     metadata   ;; List of global variables
214     metadata   ;; List of imported entities
215     metadata   ;; Split debug filename
216   }
217
218 These descriptors contain a source language ID for the file (we use the DWARF
219 3.0 ID numbers, such as ``DW_LANG_C89``, ``DW_LANG_C_plus_plus``,
220 ``DW_LANG_Cobol74``, etc), a reference to a metadata node containing a pair of
221 strings for the source file name and the working directory, as well as an
222 identifier string for the compiler that produced it.
223
224 Compile unit descriptors provide the root context for objects declared in a
225 specific compilation unit.  File descriptors are defined using this context.
226 These descriptors are collected by a named metadata ``!llvm.dbg.cu``.  They
227 keep track of subprograms, global variables, type information, and imported
228 entities (declarations and namespaces).
229
230 .. _format_files:
231
232 File descriptors
233 ^^^^^^^^^^^^^^^^
234
235 .. code-block:: llvm
236
237   !0 = metadata !{
238     i32,       ;; Tag = 41 (DW_TAG_file_type)
239     metadata,  ;; Source directory (including trailing slash) & file pair
240   }
241
242 These descriptors contain information for a file.  Global variables and top
243 level functions would be defined using this context.  File descriptors also
244 provide context for source line correspondence.
245
246 Each input file is encoded as a separate file descriptor in LLVM debugging
247 information output.
248
249 .. _format_global_variables:
250
251 Global variable descriptors
252 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
253
254 .. code-block:: llvm
255
256   !1 = metadata !{
257     i32,      ;; Tag = 52 (DW_TAG_variable)
258     i32,      ;; Unused field.
259     metadata, ;; Reference to context descriptor
260     metadata, ;; Name
261     metadata, ;; Display name (fully qualified C++ name)
262     metadata, ;; MIPS linkage name (for C++)
263     metadata, ;; Reference to file where defined
264     i32,      ;; Line number where defined
265     metadata, ;; Reference to type descriptor
266     i1,       ;; True if the global is local to compile unit (static)
267     i1,       ;; True if the global is defined in the compile unit (not extern)
268     {}*,      ;; Reference to the global variable
269     metadata, ;; The static member declaration, if any
270   }
271
272 These descriptors provide debug information about globals variables.  They
273 provide details such as name, type and where the variable is defined.  All
274 global variables are collected inside the named metadata ``!llvm.dbg.cu``.
275
276 .. _format_subprograms:
277
278 Subprogram descriptors
279 ^^^^^^^^^^^^^^^^^^^^^^
280
281 .. code-block:: llvm
282
283   !2 = metadata !{
284     i32,      ;; Tag = 46 (DW_TAG_subprogram)
285     metadata, ;; Source directory (including trailing slash) & file pair
286     metadata, ;; Reference to context descriptor
287     metadata, ;; Name
288     metadata, ;; Display name (fully qualified C++ name)
289     metadata, ;; MIPS linkage name (for C++)
290     i32,      ;; Line number where defined
291     metadata, ;; Reference to type descriptor
292     i1,       ;; True if the global is local to compile unit (static)
293     i1,       ;; True if the global is defined in the compile unit (not extern)
294     i32,      ;; Virtuality, e.g. dwarf::DW_VIRTUALITY__virtual
295     i32,      ;; Index into a virtual function
296     metadata, ;; indicates which base type contains the vtable pointer for the
297               ;; derived class
298     i32,      ;; Flags - Artifical, Private, Protected, Explicit, Prototyped.
299     i1,       ;; isOptimized
300     Function * , ;; Pointer to LLVM function
301     metadata, ;; Lists function template parameters
302     metadata, ;; Function declaration descriptor
303     metadata, ;; List of function variables
304     i32       ;; Line number where the scope of the subprogram begins
305   }
306
307 These descriptors provide debug information about functions, methods and
308 subprograms.  They provide details such as name, return types and the source
309 location where the subprogram is defined.
310
311 Block descriptors
312 ^^^^^^^^^^^^^^^^^
313
314 .. code-block:: llvm
315
316   !3 = metadata !{
317     i32,     ;; Tag = 11 (DW_TAG_lexical_block)
318     metadata,;; Source directory (including trailing slash) & file pair
319     metadata,;; Reference to context descriptor
320     i32,     ;; Line number
321     i32,     ;; Column number
322     i32      ;; Unique ID to identify blocks from a template function
323   }
324
325 This descriptor provides debug information about nested blocks within a
326 subprogram.  The line number and column numbers are used to dinstinguish two
327 lexical blocks at same depth.
328
329 .. code-block:: llvm
330
331   !3 = metadata !{
332     i32,     ;; Tag = 11 (DW_TAG_lexical_block)
333     metadata,;; Source directory (including trailing slash) & file pair
334     metadata ;; Reference to the scope we're annotating with a file change
335   }
336
337 This descriptor provides a wrapper around a lexical scope to handle file
338 changes in the middle of a lexical block.
339
340 .. _format_basic_type:
341
342 Basic type descriptors
343 ^^^^^^^^^^^^^^^^^^^^^^
344
345 .. code-block:: llvm
346
347   !4 = metadata !{
348     i32,      ;; Tag = 36 (DW_TAG_base_type)
349     metadata, ;; Source directory (including trailing slash) & file pair (may be null)
350     metadata, ;; Reference to context
351     metadata, ;; Name (may be "" for anonymous types)
352     i32,      ;; Line number where defined (may be 0)
353     i64,      ;; Size in bits
354     i64,      ;; Alignment in bits
355     i64,      ;; Offset in bits
356     i32,      ;; Flags
357     i32       ;; DWARF type encoding
358   }
359
360 These descriptors define primitive types used in the code.  Example ``int``,
361 ``bool`` and ``float``.  The context provides the scope of the type, which is
362 usually the top level.  Since basic types are not usually user defined the
363 context and line number can be left as NULL and 0.  The size, alignment and
364 offset are expressed in bits and can be 64 bit values.  The alignment is used
365 to round the offset when embedded in a :ref:`composite type
366 <format_composite_type>` (example to keep float doubles on 64 bit boundaries).
367 The offset is the bit offset if embedded in a :ref:`composite type
368 <format_composite_type>`.
369
370 The type encoding provides the details of the type.  The values are typically
371 one of the following:
372
373 .. code-block:: llvm
374
375   DW_ATE_address       = 1
376   DW_ATE_boolean       = 2
377   DW_ATE_float         = 4
378   DW_ATE_signed        = 5
379   DW_ATE_signed_char   = 6
380   DW_ATE_unsigned      = 7
381   DW_ATE_unsigned_char = 8
382
383 .. _format_derived_type:
384
385 Derived type descriptors
386 ^^^^^^^^^^^^^^^^^^^^^^^^
387
388 .. code-block:: llvm
389
390   !5 = metadata !{
391     i32,      ;; Tag (see below)
392     metadata, ;; Source directory (including trailing slash) & file pair (may be null)
393     metadata, ;; Reference to context
394     metadata, ;; Name (may be "" for anonymous types)
395     i32,      ;; Line number where defined (may be 0)
396     i64,      ;; Size in bits
397     i64,      ;; Alignment in bits
398     i64,      ;; Offset in bits
399     i32,      ;; Flags to encode attributes, e.g. private
400     metadata, ;; Reference to type derived from
401     metadata, ;; (optional) Name of the Objective C property associated with
402               ;; Objective-C an ivar, or the type of which this
403               ;; pointer-to-member is pointing to members of.
404     metadata, ;; (optional) Name of the Objective C property getter selector.
405     metadata, ;; (optional) Name of the Objective C property setter selector.
406     i32       ;; (optional) Objective C property attributes.
407   }
408
409 These descriptors are used to define types derived from other types.  The value
410 of the tag varies depending on the meaning.  The following are possible tag
411 values:
412
413 .. code-block:: llvm
414
415   DW_TAG_formal_parameter   = 5
416   DW_TAG_member             = 13
417   DW_TAG_pointer_type       = 15
418   DW_TAG_reference_type     = 16
419   DW_TAG_typedef            = 22
420   DW_TAG_ptr_to_member_type = 31
421   DW_TAG_const_type         = 38
422   DW_TAG_volatile_type      = 53
423   DW_TAG_restrict_type      = 55
424
425 ``DW_TAG_member`` is used to define a member of a :ref:`composite type
426 <format_composite_type>` or :ref:`subprogram <format_subprograms>`.  The type
427 of the member is the :ref:`derived type <format_derived_type>`.
428 ``DW_TAG_formal_parameter`` is used to define a member which is a formal
429 argument of a subprogram.
430
431 ``DW_TAG_typedef`` is used to provide a name for the derived type.
432
433 ``DW_TAG_pointer_type``, ``DW_TAG_reference_type``, ``DW_TAG_const_type``,
434 ``DW_TAG_volatile_type`` and ``DW_TAG_restrict_type`` are used to qualify the
435 :ref:`derived type <format_derived_type>`.
436
437 :ref:`Derived type <format_derived_type>` location can be determined from the
438 context and line number.  The size, alignment and offset are expressed in bits
439 and can be 64 bit values.  The alignment is used to round the offset when
440 embedded in a :ref:`composite type <format_composite_type>`  (example to keep
441 float doubles on 64 bit boundaries.) The offset is the bit offset if embedded
442 in a :ref:`composite type <format_composite_type>`.
443
444 Note that the ``void *`` type is expressed as a type derived from NULL.
445
446 .. _format_composite_type:
447
448 Composite type descriptors
449 ^^^^^^^^^^^^^^^^^^^^^^^^^^
450
451 .. code-block:: llvm
452
453   !6 = metadata !{
454     i32,      ;; Tag (see below)
455     metadata, ;; Source directory (including trailing slash) & file pair (may be null)
456     metadata, ;; Reference to context
457     metadata, ;; Name (may be "" for anonymous types)
458     i32,      ;; Line number where defined (may be 0)
459     i64,      ;; Size in bits
460     i64,      ;; Alignment in bits
461     i64,      ;; Offset in bits
462     i32,      ;; Flags
463     metadata, ;; Reference to type derived from
464     metadata, ;; Reference to array of member descriptors
465     i32,      ;; Runtime languages
466     metadata, ;; Base type containing the vtable pointer for this type
467     metadata, ;; Template parameters
468     metadata  ;; A unique identifier for type uniquing purpose (may be null)
469   }
470
471 These descriptors are used to define types that are composed of 0 or more
472 elements.  The value of the tag varies depending on the meaning.  The following
473 are possible tag values:
474
475 .. code-block:: llvm
476
477   DW_TAG_array_type       = 1
478   DW_TAG_enumeration_type = 4
479   DW_TAG_structure_type   = 19
480   DW_TAG_union_type       = 23
481   DW_TAG_subroutine_type  = 21
482   DW_TAG_inheritance      = 28
483
484 The vector flag indicates that an array type is a native packed vector.
485
486 The members of array types (tag = ``DW_TAG_array_type``) are
487 :ref:`subrange descriptors <format_subrange>`, each
488 representing the range of subscripts at that level of indexing.
489
490 The members of enumeration types (tag = ``DW_TAG_enumeration_type``) are
491 :ref:`enumerator descriptors <format_enumerator>`, each representing the
492 definition of enumeration value for the set.  All enumeration type descriptors
493 are collected inside the named metadata ``!llvm.dbg.cu``.
494
495 The members of structure (tag = ``DW_TAG_structure_type``) or union (tag =
496 ``DW_TAG_union_type``) types are any one of the :ref:`basic
497 <format_basic_type>`, :ref:`derived <format_derived_type>` or :ref:`composite
498 <format_composite_type>` type descriptors, each representing a field member of
499 the structure or union.
500
501 For C++ classes (tag = ``DW_TAG_structure_type``), member descriptors provide
502 information about base classes, static members and member functions.  If a
503 member is a :ref:`derived type descriptor <format_derived_type>` and has a tag
504 of ``DW_TAG_inheritance``, then the type represents a base class.  If the member
505 of is a :ref:`global variable descriptor <format_global_variables>` then it
506 represents a static member.  And, if the member is a :ref:`subprogram
507 descriptor <format_subprograms>` then it represents a member function.  For
508 static members and member functions, ``getName()`` returns the members link or
509 the C++ mangled name.  ``getDisplayName()`` the simplied version of the name.
510
511 The first member of subroutine (tag = ``DW_TAG_subroutine_type``) type elements
512 is the return type for the subroutine.  The remaining elements are the formal
513 arguments to the subroutine.
514
515 :ref:`Composite type <format_composite_type>` location can be determined from
516 the context and line number.  The size, alignment and offset are expressed in
517 bits and can be 64 bit values.  The alignment is used to round the offset when
518 embedded in a :ref:`composite type <format_composite_type>` (as an example, to
519 keep float doubles on 64 bit boundaries).  The offset is the bit offset if
520 embedded in a :ref:`composite type <format_composite_type>`.
521
522 .. _format_subrange:
523
524 Subrange descriptors
525 ^^^^^^^^^^^^^^^^^^^^
526
527 .. code-block:: llvm
528
529   !42 = metadata !{
530     i32,    ;; Tag = 33 (DW_TAG_subrange_type)
531     i64,    ;; Low value
532     i64     ;; High value
533   }
534
535 These descriptors are used to define ranges of array subscripts for an array
536 :ref:`composite type <format_composite_type>`.  The low value defines the lower
537 bounds typically zero for C/C++.  The high value is the upper bounds.  Values
538 are 64 bit.  ``High - Low + 1`` is the size of the array.  If ``Low > High``
539 the array bounds are not included in generated debugging information.
540
541 .. _format_enumerator:
542
543 Enumerator descriptors
544 ^^^^^^^^^^^^^^^^^^^^^^
545
546 .. code-block:: llvm
547
548   !6 = metadata !{
549     i32,      ;; Tag = 40 (DW_TAG_enumerator)
550     metadata, ;; Name
551     i64       ;; Value
552   }
553
554 These descriptors are used to define members of an enumeration :ref:`composite
555 type <format_composite_type>`, it associates the name to the value.
556
557 Local variables
558 ^^^^^^^^^^^^^^^
559
560 .. code-block:: llvm
561
562   !7 = metadata !{
563     i32,      ;; Tag (see below)
564     metadata, ;; Context
565     metadata, ;; Name
566     metadata, ;; Reference to file where defined
567     i32,      ;; 24 bit - Line number where defined
568               ;; 8 bit - Argument number. 1 indicates 1st argument.
569     metadata, ;; Type descriptor
570     i32,      ;; flags
571     metadata  ;; (optional) Reference to inline location
572   }
573
574 These descriptors are used to define variables local to a sub program.  The
575 value of the tag depends on the usage of the variable:
576
577 .. code-block:: llvm
578
579   DW_TAG_auto_variable   = 256
580   DW_TAG_arg_variable    = 257
581
582 An auto variable is any variable declared in the body of the function.  An
583 argument variable is any variable that appears as a formal argument to the
584 function.
585
586 The context is either the subprogram or block where the variable is defined.
587 Name the source variable name.  Context and line indicate where the variable
588 was defined.  Type descriptor defines the declared type of the variable.
589
590 .. _format_common_intrinsics:
591
592 Debugger intrinsic functions
593 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
594
595 LLVM uses several intrinsic functions (name prefixed with "``llvm.dbg``") to
596 provide debug information at various points in generated code.
597
598 ``llvm.dbg.declare``
599 ^^^^^^^^^^^^^^^^^^^^
600
601 .. code-block:: llvm
602
603   void %llvm.dbg.declare(metadata, metadata)
604
605 This intrinsic provides information about a local element (e.g., variable).
606 The first argument is metadata holding the alloca for the variable.  The second
607 argument is metadata containing a description of the variable.
608
609 ``llvm.dbg.value``
610 ^^^^^^^^^^^^^^^^^^
611
612 .. code-block:: llvm
613
614   void %llvm.dbg.value(metadata, i64, metadata)
615
616 This intrinsic provides information when a user source variable is set to a new
617 value.  The first argument is the new value (wrapped as metadata).  The second
618 argument is the offset in the user source variable where the new value is
619 written.  The third argument is metadata containing a description of the user
620 source variable.
621
622 Object lifetimes and scoping
623 ============================
624
625 In many languages, the local variables in functions can have their lifetimes or
626 scopes limited to a subset of a function.  In the C family of languages, for
627 example, variables are only live (readable and writable) within the source
628 block that they are defined in.  In functional languages, values are only
629 readable after they have been defined.  Though this is a very obvious concept,
630 it is non-trivial to model in LLVM, because it has no notion of scoping in this
631 sense, and does not want to be tied to a language's scoping rules.
632
633 In order to handle this, the LLVM debug format uses the metadata attached to
634 llvm instructions to encode line number and scoping information.  Consider the
635 following C fragment, for example:
636
637 .. code-block:: c
638
639   1.  void foo() {
640   2.    int X = 21;
641   3.    int Y = 22;
642   4.    {
643   5.      int Z = 23;
644   6.      Z = X;
645   7.    }
646   8.    X = Y;
647   9.  }
648
649 Compiled to LLVM, this function would be represented like this:
650
651 .. code-block:: llvm
652
653   define void @_Z3foov() #0 {
654   entry:
655     %X = alloca i32, align 4                        ; [#uses=3 type=i32*]
656     %Y = alloca i32, align 4                        ; [#uses=2 type=i32*]
657     %Z = alloca i32, align 4                        ; [#uses=2 type=i32*]
658     call void @llvm.dbg.declare(metadata !{i32* %X}, metadata !8), !dbg !10
659       ; [debug line = 2:7] [debug variable = X]
660     store i32 21, i32* %X, align 4, !dbg !11        ; [debug line = 2:13]
661     call void @llvm.dbg.declare(metadata !{i32* %Y}, metadata !12), !dbg !13
662       ; [debug line = 3:7] [debug variable = Y]
663     store i32 22, i32* %Y, align 4, !dbg !14        ; [debug line = 3:13]
664     call void @llvm.dbg.declare(metadata !{i32* %Z}, metadata !15), !dbg !17
665       ; [debug line = 5:9] [debug variable = Z]
666     store i32 23, i32* %Z, align 4, !dbg !18        ; [debug line = 5:15]
667     %0 = load i32* %X, align 4, !dbg !19            ; [#uses=1 type=i32] \
668       [debug line = 6:5]
669     store i32 %0, i32* %Z, align 4, !dbg !19        ; [debug line = 6:5]
670     %1 = load i32* %Y, align 4, !dbg !20            ; [#uses=1 type=i32] \
671       [debug line = 8:3]
672     store i32 %1, i32* %X, align 4, !dbg !20        ; [debug line = 8:3]
673     ret void, !dbg !21                              ; [debug line = 9:1]
674   }
675
676   ; [#uses=3]
677   ; Function Attrs: nounwind readnone
678   declare void @llvm.dbg.declare(metadata, metadata) #1
679
680   attributes #0 = { optsize zeroext "less-precise-fpmad"="false"
681     "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf"="true"
682     "no-infs-fp-math"="false" "no-nans-fp-math"="false" "unsafe-fp-math"="false"
683     "use-soft-float"="false" }
684   attributes #1 = { nounwind readnone }
685
686   !llvm.dbg.cu = !{!0}
687   
688   !0 = metadata !{i32 786449, metadata !1, i32 12,
689                   metadata !"clang version 3.4 ", i1 false, metadata !"", i32 0,
690                   metadata !2, metadata !2, metadata !3, metadata !2,
691                   metadata !2, metadata !""} ; [ DW_TAG_compile_unit ] \
692                     [/private/tmp/foo.c] \
693                     [DW_LANG_C]
694   !1 = metadata !{metadata !"foo.c", metadata !"/private/tmp"}
695   !2 = metadata !{i32 0}
696   !3 = metadata !{metadata !4}
697   !4 = metadata !{i32 786478, metadata !1, metadata !5, metadata !"foo",
698                   metadata !"foo", metadata !"_Z3foov", i32 1, metadata !6,
699                   i1 false, i1 true, i32 0, i32 0, null, i32 256, i1 false,
700                   void ()* @_Z3foov, null, null, metadata !2, i32 1}
701                   ; [ DW_TAG_subprogram ] [line 1] [def] [foo]
702   !5 = metadata !{i32 786473, metadata !1} ; [ DW_TAG_file_type ] \
703                     [/private/tmp/foo.c]
704   !6 = metadata !{i32 786453, i32 0, i32 0, metadata !"", i32 0, i64 0, i64 0,
705                   i64 0, i32 0, null, metadata !7, i32 0, i32 0}
706                   ; [ DW_TAG_subroutine_type ] \
707                     [line 0, size 0, align 0, offset 0] [from ]
708   !7 = metadata !{null}
709   !8 = metadata !{i32 786688, metadata !4, metadata !"X", metadata !5, i32 2, \
710                   metadata !9, i32 0, i32 0} ; [ DW_TAG_auto_variable ] [X] \
711                     [line 2]
712   !9 = metadata !{i32 786468, null, null, metadata !"int", i32 0, i64 32, \
713                   i64 32, i64 0, i32 0, i32 5} ; [ DW_TAG_base_type ] [int] \
714                     [line 0, size 32, align 32, offset 0, enc DW_ATE_signed]
715   !10 = metadata !{i32 2, i32 7, metadata !4, null}
716   !11 = metadata !{i32 2, i32 13, metadata !4, null}
717   !12 = metadata !{i32 786688, metadata !4, metadata !"Y", metadata !5, i32 3, \
718                    metadata !9, i32 0, i32 0} ; [ DW_TAG_auto_variable ] [Y] \
719                      [line 3]
720   !13 = metadata !{i32 3, i32 7, metadata !4, null}
721   !14 = metadata !{i32 3, i32 13, metadata !4, null}
722   !15 = metadata !{i32 786688, metadata !16, metadata !"Z", metadata !5, i32 5, \
723                    metadata !9, i32 0, i32 0} ; [ DW_TAG_auto_variable ] [Z] \
724                      [line 5]
725   !16 = metadata !{i32 786443, metadata !1, metadata !4, i32 4, i32 3, i32 0}
726                    ; [ DW_TAG_lexical_block ] [/private/tmp/foo.c]
727   !17 = metadata !{i32 5, i32 9, metadata !16, null}
728   !18 = metadata !{i32 5, i32 15, metadata !16, null}
729   !19 = metadata !{i32 6, i32 5, metadata !16, null}
730   !20 = metadata !{i32 8, i32 3, metadata !4, null}
731   !21 = metadata !{i32 9, i32 1, metadata !4, null}
732
733 This example illustrates a few important details about LLVM debugging
734 information.  In particular, it shows how the ``llvm.dbg.declare`` intrinsic and
735 location information, which are attached to an instruction, are applied
736 together to allow a debugger to analyze the relationship between statements,
737 variable definitions, and the code used to implement the function.
738
739 .. code-block:: llvm
740
741   call void @llvm.dbg.declare(metadata !{i32* %X}, metadata !8), !dbg !10
742     ; [debug line = 2:7] [debug variable = X]
743
744 The first intrinsic ``%llvm.dbg.declare`` encodes debugging information for the
745 variable ``X``.  The metadata ``!dbg !10`` attached to the intrinsic provides
746 scope information for the variable ``X``.
747
748 .. code-block:: llvm
749
750   !10 = metadata !{i32 2, i32 7, metadata !4, null}
751   !4 = metadata !{i32 786478, metadata !1, metadata !5, metadata !"foo",
752                   metadata !"foo", metadata !"_Z3foov", i32 1, metadata !6,
753                   i1 false, i1 true, i32 0, i32 0, null, i32 256, i1 false,
754                   void ()* @_Z3foov, null, null, metadata !2, i32 1}
755                   ; [ DW_TAG_subprogram ] [line 1] [def] [foo]
756
757 Here ``!10`` is metadata providing location information.  It has four fields:
758 line number, column number, scope, and original scope.  The original scope
759 represents inline location if this instruction is inlined inside a caller, and
760 is null otherwise.  In this example, scope is encoded by ``!4``, a
761 :ref:`subprogram descriptor <format_subprograms>`.  This way the location
762 information attached to the intrinsics indicates that the variable ``X`` is
763 declared at line number 2 at a function level scope in function ``foo``.
764
765 Now lets take another example.
766
767 .. code-block:: llvm
768
769   call void @llvm.dbg.declare(metadata !{i32* %Z}, metadata !15), !dbg !17
770     ; [debug line = 5:9] [debug variable = Z]
771
772 The third intrinsic ``%llvm.dbg.declare`` encodes debugging information for
773 variable ``Z``.  The metadata ``!dbg !17`` attached to the intrinsic provides
774 scope information for the variable ``Z``.
775
776 .. code-block:: llvm
777
778   !16 = metadata !{i32 786443, metadata !1, metadata !4, i32 4, i32 3, i32 0}
779                    ; [ DW_TAG_lexical_block ] [/private/tmp/foo.c]
780   !17 = metadata !{i32 5, i32 9, metadata !16, null}
781
782 Here ``!15`` indicates that ``Z`` is declared at line number 5 and
783 column number 9 inside of lexical scope ``!16``.  The lexical scope itself
784 resides inside of subprogram ``!4`` described above.
785
786 The scope information attached with each instruction provides a straightforward
787 way to find instructions covered by a scope.
788
789 .. _ccxx_frontend:
790
791 C/C++ front-end specific debug information
792 ==========================================
793
794 The C and C++ front-ends represent information about the program in a format
795 that is effectively identical to `DWARF 3.0
796 <http://www.eagercon.com/dwarf/dwarf3std.htm>`_ in terms of information
797 content.  This allows code generators to trivially support native debuggers by
798 generating standard dwarf information, and contains enough information for
799 non-dwarf targets to translate it as needed.
800
801 This section describes the forms used to represent C and C++ programs.  Other
802 languages could pattern themselves after this (which itself is tuned to
803 representing programs in the same way that DWARF 3 does), or they could choose
804 to provide completely different forms if they don't fit into the DWARF model.
805 As support for debugging information gets added to the various LLVM
806 source-language front-ends, the information used should be documented here.
807
808 The following sections provide examples of various C/C++ constructs and the
809 debug information that would best describe those constructs.
810
811 C/C++ source file information
812 -----------------------------
813
814 Given the source files ``MySource.cpp`` and ``MyHeader.h`` located in the
815 directory ``/Users/mine/sources``, the following code:
816
817 .. code-block:: c
818
819   #include "MyHeader.h"
820
821   int main(int argc, char *argv[]) {
822     return 0;
823   }
824
825 a C/C++ front-end would generate the following descriptors:
826
827 .. code-block:: llvm
828
829   ...
830   ;;
831   ;; Define the compile unit for the main source file "/Users/mine/sources/MySource.cpp".
832   ;;
833   !0 = metadata !{
834     i32 786449,   ;; Tag
835     metadata !1,  ;; File/directory name
836     i32 4,        ;; Language Id
837     metadata !"clang version 3.4 ",
838     i1 false,     ;; Optimized compile unit
839     metadata !"", ;; Compiler flags
840     i32 0,        ;; Runtime version
841     metadata !2,  ;; Enumeration types
842     metadata !2,  ;; Retained types
843     metadata !3,  ;; Subprograms
844     metadata !2,  ;; Global variables
845     metadata !2,  ;; Imported entities (declarations and namespaces)
846     metadata !""  ;; Split debug filename
847   }
848
849   ;;
850   ;; Define the file for the file "/Users/mine/sources/MySource.cpp".
851   ;;
852   !1 = metadata !{
853     metadata !"MySource.cpp",
854     metadata !"/Users/mine/sources"
855   }
856   !5 = metadata !{
857     i32 786473, ;; Tag
858     metadata !1
859   }
860
861   ;;
862   ;; Define the file for the file "/Users/mine/sources/Myheader.h"
863   ;;
864   !14 = metadata !{
865     i32 786473, ;; Tag
866     metadata !15
867   }
868   !15 = metadata !{
869     metadata !"./MyHeader.h",
870     metadata !"/Users/mine/sources",
871   }
872
873   ...
874
875 ``llvm::Instruction`` provides easy access to metadata attached with an
876 instruction.  One can extract line number information encoded in LLVM IR using
877 ``Instruction::getMetadata()`` and ``DILocation::getLineNumber()``.
878
879 .. code-block:: c++
880
881   if (MDNode *N = I->getMetadata("dbg")) {  // Here I is an LLVM instruction
882     DILocation Loc(N);                      // DILocation is in DebugInfo.h
883     unsigned Line = Loc.getLineNumber();
884     StringRef File = Loc.getFilename();
885     StringRef Dir = Loc.getDirectory();
886   }
887
888 C/C++ global variable information
889 ---------------------------------
890
891 Given an integer global variable declared as follows:
892
893 .. code-block:: c
894
895   int MyGlobal = 100;
896
897 a C/C++ front-end would generate the following descriptors:
898
899 .. code-block:: llvm
900
901   ;;
902   ;; Define the global itself.
903   ;;
904   %MyGlobal = global int 100
905   ...
906   ;;
907   ;; List of debug info of globals
908   ;;
909   !llvm.dbg.cu = !{!0}
910
911   ;; Define the compile unit.
912   !0 = metadata !{
913     i32 786449,                       ;; Tag
914     i32 0,                            ;; Context
915     i32 4,                            ;; Language
916     metadata !"foo.cpp",              ;; File
917     metadata !"/Volumes/Data/tmp",    ;; Directory
918     metadata !"clang version 3.1 ",   ;; Producer
919     i1 true,                          ;; Deprecated field
920     i1 false,                         ;; "isOptimized"?
921     metadata !"",                     ;; Flags
922     i32 0,                            ;; Runtime Version
923     metadata !1,                      ;; Enum Types
924     metadata !1,                      ;; Retained Types
925     metadata !1,                      ;; Subprograms
926     metadata !3,                      ;; Global Variables
927     metadata !1,                      ;; Imported entities
928     "",                               ;; Split debug filename
929   } ; [ DW_TAG_compile_unit ]
930
931   ;; The Array of Global Variables
932   !3 = metadata !{
933     metadata !4
934   }
935
936   ;;
937   ;; Define the global variable itself.
938   ;;
939   !4 = metadata !{
940     i32 786484,                        ;; Tag
941     i32 0,                             ;; Unused
942     null,                              ;; Unused
943     metadata !"MyGlobal",              ;; Name
944     metadata !"MyGlobal",              ;; Display Name
945     metadata !"",                      ;; Linkage Name
946     metadata !6,                       ;; File
947     i32 1,                             ;; Line
948     metadata !7,                       ;; Type
949     i32 0,                             ;; IsLocalToUnit
950     i32 1,                             ;; IsDefinition
951     i32* @MyGlobal,                    ;; LLVM-IR Value
952     null                               ;; Static member declaration
953   } ; [ DW_TAG_variable ]
954
955   ;;
956   ;; Define the file
957   ;;
958   !5 = metadata !{
959     metadata !"foo.cpp",               ;; File
960     metadata !"/Volumes/Data/tmp",     ;; Directory
961   }
962   !6 = metadata !{
963     i32 786473,                        ;; Tag
964     metadata !5                        ;; Unused
965   } ; [ DW_TAG_file_type ]
966
967   ;;
968   ;; Define the type
969   ;;
970   !7 = metadata !{
971     i32 786468,                         ;; Tag
972     null,                               ;; Unused
973     null,                               ;; Unused
974     metadata !"int",                    ;; Name
975     i32 0,                              ;; Line
976     i64 32,                             ;; Size in Bits
977     i64 32,                             ;; Align in Bits
978     i64 0,                              ;; Offset
979     i32 0,                              ;; Flags
980     i32 5                               ;; Encoding
981   } ; [ DW_TAG_base_type ]
982
983 C/C++ function information
984 --------------------------
985
986 Given a function declared as follows:
987
988 .. code-block:: c
989
990   int main(int argc, char *argv[]) {
991     return 0;
992   }
993
994 a C/C++ front-end would generate the following descriptors:
995
996 .. code-block:: llvm
997
998   ;;
999   ;; Define the anchor for subprograms.
1000   ;;
1001   !6 = metadata !{
1002     i32 786484,        ;; Tag
1003     metadata !1,       ;; File
1004     metadata !1,       ;; Context
1005     metadata !"main",  ;; Name
1006     metadata !"main",  ;; Display name
1007     metadata !"main",  ;; Linkage name
1008     i32 1,             ;; Line number
1009     metadata !4,       ;; Type
1010     i1 false,          ;; Is local
1011     i1 true,           ;; Is definition
1012     i32 0,             ;; Virtuality attribute, e.g. pure virtual function
1013     i32 0,             ;; Index into virtual table for C++ methods
1014     i32 0,             ;; Type that holds virtual table.
1015     i32 0,             ;; Flags
1016     i1 false,          ;; True if this function is optimized
1017     Function *,        ;; Pointer to llvm::Function
1018     null,              ;; Function template parameters
1019     null,              ;; List of function variables (emitted when optimizing)
1020     1                  ;; Line number of the opening '{' of the function
1021   }
1022   ;;
1023   ;; Define the subprogram itself.
1024   ;;
1025   define i32 @main(i32 %argc, i8** %argv) {
1026   ...
1027   }
1028
1029 C/C++ basic types
1030 -----------------
1031
1032 The following are the basic type descriptors for C/C++ core types:
1033
1034 bool
1035 ^^^^
1036
1037 .. code-block:: llvm
1038
1039   !2 = metadata !{
1040     i32 786468,        ;; Tag
1041     null,              ;; File
1042     null,              ;; Context
1043     metadata !"bool",  ;; Name
1044     i32 0,             ;; Line number
1045     i64 8,             ;; Size in Bits
1046     i64 8,             ;; Align in Bits
1047     i64 0,             ;; Offset in Bits
1048     i32 0,             ;; Flags
1049     i32 2              ;; Encoding
1050   }
1051
1052 char
1053 ^^^^
1054
1055 .. code-block:: llvm
1056
1057   !2 = metadata !{
1058     i32 786468,        ;; Tag
1059     null,              ;; File
1060     null,              ;; Context
1061     metadata !"char",  ;; Name
1062     i32 0,             ;; Line number
1063     i64 8,             ;; Size in Bits
1064     i64 8,             ;; Align in Bits
1065     i64 0,             ;; Offset in Bits
1066     i32 0,             ;; Flags
1067     i32 6              ;; Encoding
1068   }
1069
1070 unsigned char
1071 ^^^^^^^^^^^^^
1072
1073 .. code-block:: llvm
1074
1075   !2 = metadata !{
1076     i32 786468,        ;; Tag
1077     null,              ;; File
1078     null,              ;; Context
1079     metadata !"unsigned char",
1080     i32 0,             ;; Line number
1081     i64 8,             ;; Size in Bits
1082     i64 8,             ;; Align in Bits
1083     i64 0,             ;; Offset in Bits
1084     i32 0,             ;; Flags
1085     i32 8              ;; Encoding
1086   }
1087
1088 short
1089 ^^^^^
1090
1091 .. code-block:: llvm
1092
1093   !2 = metadata !{
1094     i32 786468,        ;; Tag
1095     null,              ;; File
1096     null,              ;; Context
1097     metadata !"short int",
1098     i32 0,             ;; Line number
1099     i64 16,            ;; Size in Bits
1100     i64 16,            ;; Align in Bits
1101     i64 0,             ;; Offset in Bits
1102     i32 0,             ;; Flags
1103     i32 5              ;; Encoding
1104   }
1105
1106 unsigned short
1107 ^^^^^^^^^^^^^^
1108
1109 .. code-block:: llvm
1110
1111   !2 = metadata !{
1112     i32 786468,        ;; Tag
1113     null,              ;; File
1114     null,              ;; Context
1115     metadata !"short unsigned int",
1116     i32 0,             ;; Line number
1117     i64 16,            ;; Size in Bits
1118     i64 16,            ;; Align in Bits
1119     i64 0,             ;; Offset in Bits
1120     i32 0,             ;; Flags
1121     i32 7              ;; Encoding
1122   }
1123
1124 int
1125 ^^^
1126
1127 .. code-block:: llvm
1128
1129   !2 = metadata !{
1130     i32 786468,        ;; Tag
1131     null,              ;; File
1132     null,              ;; Context
1133     metadata !"int",   ;; Name
1134     i32 0,             ;; Line number
1135     i64 32,            ;; Size in Bits
1136     i64 32,            ;; Align in Bits
1137     i64 0,             ;; Offset in Bits
1138     i32 0,             ;; Flags
1139     i32 5              ;; Encoding
1140   }
1141
1142 unsigned int
1143 ^^^^^^^^^^^^
1144
1145 .. code-block:: llvm
1146
1147   !2 = metadata !{
1148     i32 786468,        ;; Tag
1149     null,              ;; File
1150     null,              ;; Context
1151     metadata !"unsigned int",
1152     i32 0,             ;; Line number
1153     i64 32,            ;; Size in Bits
1154     i64 32,            ;; Align in Bits
1155     i64 0,             ;; Offset in Bits
1156     i32 0,             ;; Flags
1157     i32 7              ;; Encoding
1158   }
1159
1160 long long
1161 ^^^^^^^^^
1162
1163 .. code-block:: llvm
1164
1165   !2 = metadata !{
1166     i32 786468,        ;; Tag
1167     null,              ;; File
1168     null,              ;; Context
1169     metadata !"long long int",
1170     i32 0,             ;; Line number
1171     i64 64,            ;; Size in Bits
1172     i64 64,            ;; Align in Bits
1173     i64 0,             ;; Offset in Bits
1174     i32 0,             ;; Flags
1175     i32 5              ;; Encoding
1176   }
1177
1178 unsigned long long
1179 ^^^^^^^^^^^^^^^^^^
1180
1181 .. code-block:: llvm
1182
1183   !2 = metadata !{
1184     i32 786468,        ;; Tag
1185     null,              ;; File
1186     null,              ;; Context
1187     metadata !"long long unsigned int",
1188     i32 0,             ;; Line number
1189     i64 64,            ;; Size in Bits
1190     i64 64,            ;; Align in Bits
1191     i64 0,             ;; Offset in Bits
1192     i32 0,             ;; Flags
1193     i32 7              ;; Encoding
1194   }
1195
1196 float
1197 ^^^^^
1198
1199 .. code-block:: llvm
1200
1201   !2 = metadata !{
1202     i32 786468,        ;; Tag
1203     null,              ;; File
1204     null,              ;; Context
1205     metadata !"float",
1206     i32 0,             ;; Line number
1207     i64 32,            ;; Size in Bits
1208     i64 32,            ;; Align in Bits
1209     i64 0,             ;; Offset in Bits
1210     i32 0,             ;; Flags
1211     i32 4              ;; Encoding
1212   }
1213
1214 double
1215 ^^^^^^
1216
1217 .. code-block:: llvm
1218
1219   !2 = metadata !{
1220     i32 786468,        ;; Tag
1221     null,              ;; File
1222     null,              ;; Context
1223     metadata !"double",;; Name
1224     i32 0,             ;; Line number
1225     i64 64,            ;; Size in Bits
1226     i64 64,            ;; Align in Bits
1227     i64 0,             ;; Offset in Bits
1228     i32 0,             ;; Flags
1229     i32 4              ;; Encoding
1230   }
1231
1232 C/C++ derived types
1233 -------------------
1234
1235 Given the following as an example of C/C++ derived type:
1236
1237 .. code-block:: c
1238
1239   typedef const int *IntPtr;
1240
1241 a C/C++ front-end would generate the following descriptors:
1242
1243 .. code-block:: llvm
1244
1245   ;;
1246   ;; Define the typedef "IntPtr".
1247   ;;
1248   !2 = metadata !{
1249     i32 786454,          ;; Tag
1250     metadata !3,         ;; File
1251     metadata !1,         ;; Context
1252     metadata !"IntPtr",  ;; Name
1253     i32 0,               ;; Line number
1254     i64 0,               ;; Size in bits
1255     i64 0,               ;; Align in bits
1256     i64 0,               ;; Offset in bits
1257     i32 0,               ;; Flags
1258     metadata !4          ;; Derived From type
1259   }
1260   ;;
1261   ;; Define the pointer type.
1262   ;;
1263   !4 = metadata !{
1264     i32 786447,          ;; Tag
1265     null,                ;; File
1266     null,                ;; Context
1267     metadata !"",        ;; Name
1268     i32 0,               ;; Line number
1269     i64 64,              ;; Size in bits
1270     i64 64,              ;; Align in bits
1271     i64 0,               ;; Offset in bits
1272     i32 0,               ;; Flags
1273     metadata !5          ;; Derived From type
1274   }
1275   ;;
1276   ;; Define the const type.
1277   ;;
1278   !5 = metadata !{
1279     i32 786470,          ;; Tag
1280     null,                ;; File
1281     null,                ;; Context
1282     metadata !"",        ;; Name
1283     i32 0,               ;; Line number
1284     i64 0,               ;; Size in bits
1285     i64 0,               ;; Align in bits
1286     i64 0,               ;; Offset in bits
1287     i32 0,               ;; Flags
1288     metadata !6          ;; Derived From type
1289   }
1290   ;;
1291   ;; Define the int type.
1292   ;;
1293   !6 = metadata !{
1294     i32 786468,          ;; Tag
1295     null,                ;; File
1296     null,                ;; Context
1297     metadata !"int",     ;; Name
1298     i32 0,               ;; Line number
1299     i64 32,              ;; Size in bits
1300     i64 32,              ;; Align in bits
1301     i64 0,               ;; Offset in bits
1302     i32 0,               ;; Flags
1303     i32 5                ;; Encoding
1304   }
1305
1306 C/C++ struct/union types
1307 ------------------------
1308
1309 Given the following as an example of C/C++ struct type:
1310
1311 .. code-block:: c
1312
1313   struct Color {
1314     unsigned Red;
1315     unsigned Green;
1316     unsigned Blue;
1317   };
1318
1319 a C/C++ front-end would generate the following descriptors:
1320
1321 .. code-block:: llvm
1322
1323   ;;
1324   ;; Define basic type for unsigned int.
1325   ;;
1326   !5 = metadata !{
1327     i32 786468,        ;; Tag
1328     null,              ;; File
1329     null,              ;; Context
1330     metadata !"unsigned int",
1331     i32 0,             ;; Line number
1332     i64 32,            ;; Size in Bits
1333     i64 32,            ;; Align in Bits
1334     i64 0,             ;; Offset in Bits
1335     i32 0,             ;; Flags
1336     i32 7              ;; Encoding
1337   }
1338   ;;
1339   ;; Define composite type for struct Color.
1340   ;;
1341   !2 = metadata !{
1342     i32 786451,        ;; Tag
1343     metadata !1,       ;; Compile unit
1344     null,              ;; Context
1345     metadata !"Color", ;; Name
1346     i32 1,             ;; Line number
1347     i64 96,            ;; Size in bits
1348     i64 32,            ;; Align in bits
1349     i64 0,             ;; Offset in bits
1350     i32 0,             ;; Flags
1351     null,              ;; Derived From
1352     metadata !3,       ;; Elements
1353     i32 0,             ;; Runtime Language
1354     null,              ;; Base type containing the vtable pointer for this type
1355     null               ;; Template parameters
1356   }
1357
1358   ;;
1359   ;; Define the Red field.
1360   ;;
1361   !4 = metadata !{
1362     i32 786445,        ;; Tag
1363     metadata !1,       ;; File
1364     metadata !1,       ;; Context
1365     metadata !"Red",   ;; Name
1366     i32 2,             ;; Line number
1367     i64 32,            ;; Size in bits
1368     i64 32,            ;; Align in bits
1369     i64 0,             ;; Offset in bits
1370     i32 0,             ;; Flags
1371     metadata !5        ;; Derived From type
1372   }
1373
1374   ;;
1375   ;; Define the Green field.
1376   ;;
1377   !6 = metadata !{
1378     i32 786445,        ;; Tag
1379     metadata !1,       ;; File
1380     metadata !1,       ;; Context
1381     metadata !"Green", ;; Name
1382     i32 3,             ;; Line number
1383     i64 32,            ;; Size in bits
1384     i64 32,            ;; Align in bits
1385     i64 32,             ;; Offset in bits
1386     i32 0,             ;; Flags
1387     metadata !5        ;; Derived From type
1388   }
1389
1390   ;;
1391   ;; Define the Blue field.
1392   ;;
1393   !7 = metadata !{
1394     i32 786445,        ;; Tag
1395     metadata !1,       ;; File
1396     metadata !1,       ;; Context
1397     metadata !"Blue",  ;; Name
1398     i32 4,             ;; Line number
1399     i64 32,            ;; Size in bits
1400     i64 32,            ;; Align in bits
1401     i64 64,             ;; Offset in bits
1402     i32 0,             ;; Flags
1403     metadata !5        ;; Derived From type
1404   }
1405
1406   ;;
1407   ;; Define the array of fields used by the composite type Color.
1408   ;;
1409   !3 = metadata !{metadata !4, metadata !6, metadata !7}
1410
1411 C/C++ enumeration types
1412 -----------------------
1413
1414 Given the following as an example of C/C++ enumeration type:
1415
1416 .. code-block:: c
1417
1418   enum Trees {
1419     Spruce = 100,
1420     Oak = 200,
1421     Maple = 300
1422   };
1423
1424 a C/C++ front-end would generate the following descriptors:
1425
1426 .. code-block:: llvm
1427
1428   ;;
1429   ;; Define composite type for enum Trees
1430   ;;
1431   !2 = metadata !{
1432     i32 786436,        ;; Tag
1433     metadata !1,       ;; File
1434     metadata !1,       ;; Context
1435     metadata !"Trees", ;; Name
1436     i32 1,             ;; Line number
1437     i64 32,            ;; Size in bits
1438     i64 32,            ;; Align in bits
1439     i64 0,             ;; Offset in bits
1440     i32 0,             ;; Flags
1441     null,              ;; Derived From type
1442     metadata !3,       ;; Elements
1443     i32 0              ;; Runtime language
1444   }
1445
1446   ;;
1447   ;; Define the array of enumerators used by composite type Trees.
1448   ;;
1449   !3 = metadata !{metadata !4, metadata !5, metadata !6}
1450
1451   ;;
1452   ;; Define Spruce enumerator.
1453   ;;
1454   !4 = metadata !{i32 786472, metadata !"Spruce", i64 100}
1455
1456   ;;
1457   ;; Define Oak enumerator.
1458   ;;
1459   !5 = metadata !{i32 786472, metadata !"Oak", i64 200}
1460
1461   ;;
1462   ;; Define Maple enumerator.
1463   ;;
1464   !6 = metadata !{i32 786472, metadata !"Maple", i64 300}
1465
1466 Debugging information format
1467 ============================
1468
1469 Debugging Information Extension for Objective C Properties
1470 ----------------------------------------------------------
1471
1472 Introduction
1473 ^^^^^^^^^^^^
1474
1475 Objective C provides a simpler way to declare and define accessor methods using
1476 declared properties.  The language provides features to declare a property and
1477 to let compiler synthesize accessor methods.
1478
1479 The debugger lets developer inspect Objective C interfaces and their instance
1480 variables and class variables.  However, the debugger does not know anything
1481 about the properties defined in Objective C interfaces.  The debugger consumes
1482 information generated by compiler in DWARF format.  The format does not support
1483 encoding of Objective C properties.  This proposal describes DWARF extensions to
1484 encode Objective C properties, which the debugger can use to let developers
1485 inspect Objective C properties.
1486
1487 Proposal
1488 ^^^^^^^^
1489
1490 Objective C properties exist separately from class members.  A property can be
1491 defined only by "setter" and "getter" selectors, and be calculated anew on each
1492 access.  Or a property can just be a direct access to some declared ivar.
1493 Finally it can have an ivar "automatically synthesized" for it by the compiler,
1494 in which case the property can be referred to in user code directly using the
1495 standard C dereference syntax as well as through the property "dot" syntax, but
1496 there is no entry in the ``@interface`` declaration corresponding to this ivar.
1497
1498 To facilitate debugging, these properties we will add a new DWARF TAG into the
1499 ``DW_TAG_structure_type`` definition for the class to hold the description of a
1500 given property, and a set of DWARF attributes that provide said description.
1501 The property tag will also contain the name and declared type of the property.
1502
1503 If there is a related ivar, there will also be a DWARF property attribute placed
1504 in the ``DW_TAG_member`` DIE for that ivar referring back to the property TAG
1505 for that property.  And in the case where the compiler synthesizes the ivar
1506 directly, the compiler is expected to generate a ``DW_TAG_member`` for that
1507 ivar (with the ``DW_AT_artificial`` set to 1), whose name will be the name used
1508 to access this ivar directly in code, and with the property attribute pointing
1509 back to the property it is backing.
1510
1511 The following examples will serve as illustration for our discussion:
1512
1513 .. code-block:: objc
1514
1515   @interface I1 {
1516     int n2;
1517   }
1518
1519   @property int p1;
1520   @property int p2;
1521   @end
1522
1523   @implementation I1
1524   @synthesize p1;
1525   @synthesize p2 = n2;
1526   @end
1527
1528 This produces the following DWARF (this is a "pseudo dwarfdump" output):
1529
1530 .. code-block:: none
1531
1532   0x00000100:  TAG_structure_type [7] *
1533                  AT_APPLE_runtime_class( 0x10 )
1534                  AT_name( "I1" )
1535                  AT_decl_file( "Objc_Property.m" )
1536                  AT_decl_line( 3 )
1537
1538   0x00000110    TAG_APPLE_property
1539                   AT_name ( "p1" )
1540                   AT_type ( {0x00000150} ( int ) )
1541
1542   0x00000120:   TAG_APPLE_property
1543                   AT_name ( "p2" )
1544                   AT_type ( {0x00000150} ( int ) )
1545
1546   0x00000130:   TAG_member [8]
1547                   AT_name( "_p1" )
1548                   AT_APPLE_property ( {0x00000110} "p1" )
1549                   AT_type( {0x00000150} ( int ) )
1550                   AT_artificial ( 0x1 )
1551
1552   0x00000140:    TAG_member [8]
1553                    AT_name( "n2" )
1554                    AT_APPLE_property ( {0x00000120} "p2" )
1555                    AT_type( {0x00000150} ( int ) )
1556
1557   0x00000150:  AT_type( ( int ) )
1558
1559 Note, the current convention is that the name of the ivar for an
1560 auto-synthesized property is the name of the property from which it derives
1561 with an underscore prepended, as is shown in the example.  But we actually
1562 don't need to know this convention, since we are given the name of the ivar
1563 directly.
1564
1565 Also, it is common practice in ObjC to have different property declarations in
1566 the @interface and @implementation - e.g. to provide a read-only property in
1567 the interface,and a read-write interface in the implementation.  In that case,
1568 the compiler should emit whichever property declaration will be in force in the
1569 current translation unit.
1570
1571 Developers can decorate a property with attributes which are encoded using
1572 ``DW_AT_APPLE_property_attribute``.
1573
1574 .. code-block:: objc
1575
1576   @property (readonly, nonatomic) int pr;
1577
1578 .. code-block:: none
1579
1580   TAG_APPLE_property [8]
1581     AT_name( "pr" )
1582     AT_type ( {0x00000147} (int) )
1583     AT_APPLE_property_attribute (DW_APPLE_PROPERTY_readonly, DW_APPLE_PROPERTY_nonatomic)
1584
1585 The setter and getter method names are attached to the property using
1586 ``DW_AT_APPLE_property_setter`` and ``DW_AT_APPLE_property_getter`` attributes.
1587
1588 .. code-block:: objc
1589
1590   @interface I1
1591   @property (setter=myOwnP3Setter:) int p3;
1592   -(void)myOwnP3Setter:(int)a;
1593   @end
1594
1595   @implementation I1
1596   @synthesize p3;
1597   -(void)myOwnP3Setter:(int)a{ }
1598   @end
1599
1600 The DWARF for this would be:
1601
1602 .. code-block:: none
1603
1604   0x000003bd: TAG_structure_type [7] *
1605                 AT_APPLE_runtime_class( 0x10 )
1606                 AT_name( "I1" )
1607                 AT_decl_file( "Objc_Property.m" )
1608                 AT_decl_line( 3 )
1609
1610   0x000003cd      TAG_APPLE_property
1611                     AT_name ( "p3" )
1612                     AT_APPLE_property_setter ( "myOwnP3Setter:" )
1613                     AT_type( {0x00000147} ( int ) )
1614
1615   0x000003f3:     TAG_member [8]
1616                     AT_name( "_p3" )
1617                     AT_type ( {0x00000147} ( int ) )
1618                     AT_APPLE_property ( {0x000003cd} )
1619                     AT_artificial ( 0x1 )
1620
1621 New DWARF Tags
1622 ^^^^^^^^^^^^^^
1623
1624 +-----------------------+--------+
1625 | TAG                   | Value  |
1626 +=======================+========+
1627 | DW_TAG_APPLE_property | 0x4200 |
1628 +-----------------------+--------+
1629
1630 New DWARF Attributes
1631 ^^^^^^^^^^^^^^^^^^^^
1632
1633 +--------------------------------+--------+-----------+
1634 | Attribute                      | Value  | Classes   |
1635 +================================+========+===========+
1636 | DW_AT_APPLE_property           | 0x3fed | Reference |
1637 +--------------------------------+--------+-----------+
1638 | DW_AT_APPLE_property_getter    | 0x3fe9 | String    |
1639 +--------------------------------+--------+-----------+
1640 | DW_AT_APPLE_property_setter    | 0x3fea | String    |
1641 +--------------------------------+--------+-----------+
1642 | DW_AT_APPLE_property_attribute | 0x3feb | Constant  |
1643 +--------------------------------+--------+-----------+
1644
1645 New DWARF Constants
1646 ^^^^^^^^^^^^^^^^^^^
1647
1648 +--------------------------------+-------+
1649 | Name                           | Value |
1650 +================================+=======+
1651 | DW_AT_APPLE_PROPERTY_readonly  | 0x1   |
1652 +--------------------------------+-------+
1653 | DW_AT_APPLE_PROPERTY_readwrite | 0x2   |
1654 +--------------------------------+-------+
1655 | DW_AT_APPLE_PROPERTY_assign    | 0x4   |
1656 +--------------------------------+-------+
1657 | DW_AT_APPLE_PROPERTY_retain    | 0x8   |
1658 +--------------------------------+-------+
1659 | DW_AT_APPLE_PROPERTY_copy      | 0x10  |
1660 +--------------------------------+-------+
1661 | DW_AT_APPLE_PROPERTY_nonatomic | 0x20  |
1662 +--------------------------------+-------+
1663
1664 Name Accelerator Tables
1665 -----------------------
1666
1667 Introduction
1668 ^^^^^^^^^^^^
1669
1670 The "``.debug_pubnames``" and "``.debug_pubtypes``" formats are not what a
1671 debugger needs.  The "``pub``" in the section name indicates that the entries
1672 in the table are publicly visible names only.  This means no static or hidden
1673 functions show up in the "``.debug_pubnames``".  No static variables or private
1674 class variables are in the "``.debug_pubtypes``".  Many compilers add different
1675 things to these tables, so we can't rely upon the contents between gcc, icc, or
1676 clang.
1677
1678 The typical query given by users tends not to match up with the contents of
1679 these tables.  For example, the DWARF spec states that "In the case of the name
1680 of a function member or static data member of a C++ structure, class or union,
1681 the name presented in the "``.debug_pubnames``" section is not the simple name
1682 given by the ``DW_AT_name attribute`` of the referenced debugging information
1683 entry, but rather the fully qualified name of the data or function member."
1684 So the only names in these tables for complex C++ entries is a fully
1685 qualified name.  Debugger users tend not to enter their search strings as
1686 "``a::b::c(int,const Foo&) const``", but rather as "``c``", "``b::c``" , or
1687 "``a::b::c``".  So the name entered in the name table must be demangled in
1688 order to chop it up appropriately and additional names must be manually entered
1689 into the table to make it effective as a name lookup table for debuggers to
1690 se.
1691
1692 All debuggers currently ignore the "``.debug_pubnames``" table as a result of
1693 its inconsistent and useless public-only name content making it a waste of
1694 space in the object file.  These tables, when they are written to disk, are not
1695 sorted in any way, leaving every debugger to do its own parsing and sorting.
1696 These tables also include an inlined copy of the string values in the table
1697 itself making the tables much larger than they need to be on disk, especially
1698 for large C++ programs.
1699
1700 Can't we just fix the sections by adding all of the names we need to this
1701 table? No, because that is not what the tables are defined to contain and we
1702 won't know the difference between the old bad tables and the new good tables.
1703 At best we could make our own renamed sections that contain all of the data we
1704 need.
1705
1706 These tables are also insufficient for what a debugger like LLDB needs.  LLDB
1707 uses clang for its expression parsing where LLDB acts as a PCH.  LLDB is then
1708 often asked to look for type "``foo``" or namespace "``bar``", or list items in
1709 namespace "``baz``".  Namespaces are not included in the pubnames or pubtypes
1710 tables.  Since clang asks a lot of questions when it is parsing an expression,
1711 we need to be very fast when looking up names, as it happens a lot.  Having new
1712 accelerator tables that are optimized for very quick lookups will benefit this
1713 type of debugging experience greatly.
1714
1715 We would like to generate name lookup tables that can be mapped into memory
1716 from disk, and used as is, with little or no up-front parsing.  We would also
1717 be able to control the exact content of these different tables so they contain
1718 exactly what we need.  The Name Accelerator Tables were designed to fix these
1719 issues.  In order to solve these issues we need to:
1720
1721 * Have a format that can be mapped into memory from disk and used as is
1722 * Lookups should be very fast
1723 * Extensible table format so these tables can be made by many producers
1724 * Contain all of the names needed for typical lookups out of the box
1725 * Strict rules for the contents of tables
1726
1727 Table size is important and the accelerator table format should allow the reuse
1728 of strings from common string tables so the strings for the names are not
1729 duplicated.  We also want to make sure the table is ready to be used as-is by
1730 simply mapping the table into memory with minimal header parsing.
1731
1732 The name lookups need to be fast and optimized for the kinds of lookups that
1733 debuggers tend to do.  Optimally we would like to touch as few parts of the
1734 mapped table as possible when doing a name lookup and be able to quickly find
1735 the name entry we are looking for, or discover there are no matches.  In the
1736 case of debuggers we optimized for lookups that fail most of the time.
1737
1738 Each table that is defined should have strict rules on exactly what is in the
1739 accelerator tables and documented so clients can rely on the content.
1740
1741 Hash Tables
1742 ^^^^^^^^^^^
1743
1744 Standard Hash Tables
1745 """"""""""""""""""""
1746
1747 Typical hash tables have a header, buckets, and each bucket points to the
1748 bucket contents:
1749
1750 .. code-block:: none
1751
1752   .------------.
1753   |  HEADER    |
1754   |------------|
1755   |  BUCKETS   |
1756   |------------|
1757   |  DATA      |
1758   `------------'
1759
1760 The BUCKETS are an array of offsets to DATA for each hash:
1761
1762 .. code-block:: none
1763
1764   .------------.
1765   | 0x00001000 | BUCKETS[0]
1766   | 0x00002000 | BUCKETS[1]
1767   | 0x00002200 | BUCKETS[2]
1768   | 0x000034f0 | BUCKETS[3]
1769   |            | ...
1770   | 0xXXXXXXXX | BUCKETS[n_buckets]
1771   '------------'
1772
1773 So for ``bucket[3]`` in the example above, we have an offset into the table
1774 0x000034f0 which points to a chain of entries for the bucket.  Each bucket must
1775 contain a next pointer, full 32 bit hash value, the string itself, and the data
1776 for the current string value.
1777
1778 .. code-block:: none
1779
1780               .------------.
1781   0x000034f0: | 0x00003500 | next pointer
1782               | 0x12345678 | 32 bit hash
1783               | "erase"    | string value
1784               | data[n]    | HashData for this bucket
1785               |------------|
1786   0x00003500: | 0x00003550 | next pointer
1787               | 0x29273623 | 32 bit hash
1788               | "dump"     | string value
1789               | data[n]    | HashData for this bucket
1790               |------------|
1791   0x00003550: | 0x00000000 | next pointer
1792               | 0x82638293 | 32 bit hash
1793               | "main"     | string value
1794               | data[n]    | HashData for this bucket
1795               `------------'
1796
1797 The problem with this layout for debuggers is that we need to optimize for the
1798 negative lookup case where the symbol we're searching for is not present.  So
1799 if we were to lookup "``printf``" in the table above, we would make a 32 hash
1800 for "``printf``", it might match ``bucket[3]``.  We would need to go to the
1801 offset 0x000034f0 and start looking to see if our 32 bit hash matches.  To do
1802 so, we need to read the next pointer, then read the hash, compare it, and skip
1803 to the next bucket.  Each time we are skipping many bytes in memory and
1804 touching new cache pages just to do the compare on the full 32 bit hash.  All
1805 of these accesses then tell us that we didn't have a match.
1806
1807 Name Hash Tables
1808 """"""""""""""""
1809
1810 To solve the issues mentioned above we have structured the hash tables a bit
1811 differently: a header, buckets, an array of all unique 32 bit hash values,
1812 followed by an array of hash value data offsets, one for each hash value, then
1813 the data for all hash values:
1814
1815 .. code-block:: none
1816
1817   .-------------.
1818   |  HEADER     |
1819   |-------------|
1820   |  BUCKETS    |
1821   |-------------|
1822   |  HASHES     |
1823   |-------------|
1824   |  OFFSETS    |
1825   |-------------|
1826   |  DATA       |
1827   `-------------'
1828
1829 The ``BUCKETS`` in the name tables are an index into the ``HASHES`` array.  By
1830 making all of the full 32 bit hash values contiguous in memory, we allow
1831 ourselves to efficiently check for a match while touching as little memory as
1832 possible.  Most often checking the 32 bit hash values is as far as the lookup
1833 goes.  If it does match, it usually is a match with no collisions.  So for a
1834 table with "``n_buckets``" buckets, and "``n_hashes``" unique 32 bit hash
1835 values, we can clarify the contents of the ``BUCKETS``, ``HASHES`` and
1836 ``OFFSETS`` as:
1837
1838 .. code-block:: none
1839
1840   .-------------------------.
1841   |  HEADER.magic           | uint32_t
1842   |  HEADER.version         | uint16_t
1843   |  HEADER.hash_function   | uint16_t
1844   |  HEADER.bucket_count    | uint32_t
1845   |  HEADER.hashes_count    | uint32_t
1846   |  HEADER.header_data_len | uint32_t
1847   |  HEADER_DATA            | HeaderData
1848   |-------------------------|
1849   |  BUCKETS                | uint32_t[n_buckets] // 32 bit hash indexes
1850   |-------------------------|
1851   |  HASHES                 | uint32_t[n_hashes] // 32 bit hash values
1852   |-------------------------|
1853   |  OFFSETS                | uint32_t[n_hashes] // 32 bit offsets to hash value data
1854   |-------------------------|
1855   |  ALL HASH DATA          |
1856   `-------------------------'
1857
1858 So taking the exact same data from the standard hash example above we end up
1859 with:
1860
1861 .. code-block:: none
1862
1863               .------------.
1864               | HEADER     |
1865               |------------|
1866               |          0 | BUCKETS[0]
1867               |          2 | BUCKETS[1]
1868               |          5 | BUCKETS[2]
1869               |          6 | BUCKETS[3]
1870               |            | ...
1871               |        ... | BUCKETS[n_buckets]
1872               |------------|
1873               | 0x........ | HASHES[0]
1874               | 0x........ | HASHES[1]
1875               | 0x........ | HASHES[2]
1876               | 0x........ | HASHES[3]
1877               | 0x........ | HASHES[4]
1878               | 0x........ | HASHES[5]
1879               | 0x12345678 | HASHES[6]    hash for BUCKETS[3]
1880               | 0x29273623 | HASHES[7]    hash for BUCKETS[3]
1881               | 0x82638293 | HASHES[8]    hash for BUCKETS[3]
1882               | 0x........ | HASHES[9]
1883               | 0x........ | HASHES[10]
1884               | 0x........ | HASHES[11]
1885               | 0x........ | HASHES[12]
1886               | 0x........ | HASHES[13]
1887               | 0x........ | HASHES[n_hashes]
1888               |------------|
1889               | 0x........ | OFFSETS[0]
1890               | 0x........ | OFFSETS[1]
1891               | 0x........ | OFFSETS[2]
1892               | 0x........ | OFFSETS[3]
1893               | 0x........ | OFFSETS[4]
1894               | 0x........ | OFFSETS[5]
1895               | 0x000034f0 | OFFSETS[6]   offset for BUCKETS[3]
1896               | 0x00003500 | OFFSETS[7]   offset for BUCKETS[3]
1897               | 0x00003550 | OFFSETS[8]   offset for BUCKETS[3]
1898               | 0x........ | OFFSETS[9]
1899               | 0x........ | OFFSETS[10]
1900               | 0x........ | OFFSETS[11]
1901               | 0x........ | OFFSETS[12]
1902               | 0x........ | OFFSETS[13]
1903               | 0x........ | OFFSETS[n_hashes]
1904               |------------|
1905               |            |
1906               |            |
1907               |            |
1908               |            |
1909               |            |
1910               |------------|
1911   0x000034f0: | 0x00001203 | .debug_str ("erase")
1912               | 0x00000004 | A 32 bit array count - number of HashData with name "erase"
1913               | 0x........ | HashData[0]
1914               | 0x........ | HashData[1]
1915               | 0x........ | HashData[2]
1916               | 0x........ | HashData[3]
1917               | 0x00000000 | String offset into .debug_str (terminate data for hash)
1918               |------------|
1919   0x00003500: | 0x00001203 | String offset into .debug_str ("collision")
1920               | 0x00000002 | A 32 bit array count - number of HashData with name "collision"
1921               | 0x........ | HashData[0]
1922               | 0x........ | HashData[1]
1923               | 0x00001203 | String offset into .debug_str ("dump")
1924               | 0x00000003 | A 32 bit array count - number of HashData with name "dump"
1925               | 0x........ | HashData[0]
1926               | 0x........ | HashData[1]
1927               | 0x........ | HashData[2]
1928               | 0x00000000 | String offset into .debug_str (terminate data for hash)
1929               |------------|
1930   0x00003550: | 0x00001203 | String offset into .debug_str ("main")
1931               | 0x00000009 | A 32 bit array count - number of HashData with name "main"
1932               | 0x........ | HashData[0]
1933               | 0x........ | HashData[1]
1934               | 0x........ | HashData[2]
1935               | 0x........ | HashData[3]
1936               | 0x........ | HashData[4]
1937               | 0x........ | HashData[5]
1938               | 0x........ | HashData[6]
1939               | 0x........ | HashData[7]
1940               | 0x........ | HashData[8]
1941               | 0x00000000 | String offset into .debug_str (terminate data for hash)
1942               `------------'
1943
1944 So we still have all of the same data, we just organize it more efficiently for
1945 debugger lookup.  If we repeat the same "``printf``" lookup from above, we
1946 would hash "``printf``" and find it matches ``BUCKETS[3]`` by taking the 32 bit
1947 hash value and modulo it by ``n_buckets``.  ``BUCKETS[3]`` contains "6" which
1948 is the index into the ``HASHES`` table.  We would then compare any consecutive
1949 32 bit hashes values in the ``HASHES`` array as long as the hashes would be in
1950 ``BUCKETS[3]``.  We do this by verifying that each subsequent hash value modulo
1951 ``n_buckets`` is still 3.  In the case of a failed lookup we would access the
1952 memory for ``BUCKETS[3]``, and then compare a few consecutive 32 bit hashes
1953 before we know that we have no match.  We don't end up marching through
1954 multiple words of memory and we really keep the number of processor data cache
1955 lines being accessed as small as possible.
1956
1957 The string hash that is used for these lookup tables is the Daniel J.
1958 Bernstein hash which is also used in the ELF ``GNU_HASH`` sections.  It is a
1959 very good hash for all kinds of names in programs with very few hash
1960 collisions.
1961
1962 Empty buckets are designated by using an invalid hash index of ``UINT32_MAX``.
1963
1964 Details
1965 ^^^^^^^
1966
1967 These name hash tables are designed to be generic where specializations of the
1968 table get to define additional data that goes into the header ("``HeaderData``"),
1969 how the string value is stored ("``KeyType``") and the content of the data for each
1970 hash value.
1971
1972 Header Layout
1973 """""""""""""
1974
1975 The header has a fixed part, and the specialized part.  The exact format of the
1976 header is:
1977
1978 .. code-block:: c
1979
1980   struct Header
1981   {
1982     uint32_t   magic;           // 'HASH' magic value to allow endian detection
1983     uint16_t   version;         // Version number
1984     uint16_t   hash_function;   // The hash function enumeration that was used
1985     uint32_t   bucket_count;    // The number of buckets in this hash table
1986     uint32_t   hashes_count;    // The total number of unique hash values and hash data offsets in this table
1987     uint32_t   header_data_len; // The bytes to skip to get to the hash indexes (buckets) for correct alignment
1988                                 // Specifically the length of the following HeaderData field - this does not
1989                                 // include the size of the preceding fields
1990     HeaderData header_data;     // Implementation specific header data
1991   };
1992
1993 The header starts with a 32 bit "``magic``" value which must be ``'HASH'``
1994 encoded as an ASCII integer.  This allows the detection of the start of the
1995 hash table and also allows the table's byte order to be determined so the table
1996 can be correctly extracted.  The "``magic``" value is followed by a 16 bit
1997 ``version`` number which allows the table to be revised and modified in the
1998 future.  The current version number is 1. ``hash_function`` is a ``uint16_t``
1999 enumeration that specifies which hash function was used to produce this table.
2000 The current values for the hash function enumerations include:
2001
2002 .. code-block:: c
2003
2004   enum HashFunctionType
2005   {
2006     eHashFunctionDJB = 0u, // Daniel J Bernstein hash function
2007   };
2008
2009 ``bucket_count`` is a 32 bit unsigned integer that represents how many buckets
2010 are in the ``BUCKETS`` array.  ``hashes_count`` is the number of unique 32 bit
2011 hash values that are in the ``HASHES`` array, and is the same number of offsets
2012 are contained in the ``OFFSETS`` array.  ``header_data_len`` specifies the size
2013 in bytes of the ``HeaderData`` that is filled in by specialized versions of
2014 this table.
2015
2016 Fixed Lookup
2017 """"""""""""
2018
2019 The header is followed by the buckets, hashes, offsets, and hash value data.
2020
2021 .. code-block:: c
2022
2023   struct FixedTable
2024   {
2025     uint32_t buckets[Header.bucket_count];  // An array of hash indexes into the "hashes[]" array below
2026     uint32_t hashes [Header.hashes_count];  // Every unique 32 bit hash for the entire table is in this table
2027     uint32_t offsets[Header.hashes_count];  // An offset that corresponds to each item in the "hashes[]" array above
2028   };
2029
2030 ``buckets`` is an array of 32 bit indexes into the ``hashes`` array.  The
2031 ``hashes`` array contains all of the 32 bit hash values for all names in the
2032 hash table.  Each hash in the ``hashes`` table has an offset in the ``offsets``
2033 array that points to the data for the hash value.
2034
2035 This table setup makes it very easy to repurpose these tables to contain
2036 different data, while keeping the lookup mechanism the same for all tables.
2037 This layout also makes it possible to save the table to disk and map it in
2038 later and do very efficient name lookups with little or no parsing.
2039
2040 DWARF lookup tables can be implemented in a variety of ways and can store a lot
2041 of information for each name.  We want to make the DWARF tables extensible and
2042 able to store the data efficiently so we have used some of the DWARF features
2043 that enable efficient data storage to define exactly what kind of data we store
2044 for each name.
2045
2046 The ``HeaderData`` contains a definition of the contents of each HashData chunk.
2047 We might want to store an offset to all of the debug information entries (DIEs)
2048 for each name.  To keep things extensible, we create a list of items, or
2049 Atoms, that are contained in the data for each name.  First comes the type of
2050 the data in each atom:
2051
2052 .. code-block:: c
2053
2054   enum AtomType
2055   {
2056     eAtomTypeNULL       = 0u,
2057     eAtomTypeDIEOffset  = 1u,   // DIE offset, check form for encoding
2058     eAtomTypeCUOffset   = 2u,   // DIE offset of the compiler unit header that contains the item in question
2059     eAtomTypeTag        = 3u,   // DW_TAG_xxx value, should be encoded as DW_FORM_data1 (if no tags exceed 255) or DW_FORM_data2
2060     eAtomTypeNameFlags  = 4u,   // Flags from enum NameFlags
2061     eAtomTypeTypeFlags  = 5u,   // Flags from enum TypeFlags
2062   };
2063
2064 The enumeration values and their meanings are:
2065
2066 .. code-block:: none
2067
2068   eAtomTypeNULL       - a termination atom that specifies the end of the atom list
2069   eAtomTypeDIEOffset  - an offset into the .debug_info section for the DWARF DIE for this name
2070   eAtomTypeCUOffset   - an offset into the .debug_info section for the CU that contains the DIE
2071   eAtomTypeDIETag     - The DW_TAG_XXX enumeration value so you don't have to parse the DWARF to see what it is
2072   eAtomTypeNameFlags  - Flags for functions and global variables (isFunction, isInlined, isExternal...)
2073   eAtomTypeTypeFlags  - Flags for types (isCXXClass, isObjCClass, ...)
2074
2075 Then we allow each atom type to define the atom type and how the data for each
2076 atom type data is encoded:
2077
2078 .. code-block:: c
2079
2080   struct Atom
2081   {
2082     uint16_t type;  // AtomType enum value
2083     uint16_t form;  // DWARF DW_FORM_XXX defines
2084   };
2085
2086 The ``form`` type above is from the DWARF specification and defines the exact
2087 encoding of the data for the Atom type.  See the DWARF specification for the
2088 ``DW_FORM_`` definitions.
2089
2090 .. code-block:: c
2091
2092   struct HeaderData
2093   {
2094     uint32_t die_offset_base;
2095     uint32_t atom_count;
2096     Atoms    atoms[atom_count0];
2097   };
2098
2099 ``HeaderData`` defines the base DIE offset that should be added to any atoms
2100 that are encoded using the ``DW_FORM_ref1``, ``DW_FORM_ref2``,
2101 ``DW_FORM_ref4``, ``DW_FORM_ref8`` or ``DW_FORM_ref_udata``.  It also defines
2102 what is contained in each ``HashData`` object -- ``Atom.form`` tells us how large
2103 each field will be in the ``HashData`` and the ``Atom.type`` tells us how this data
2104 should be interpreted.
2105
2106 For the current implementations of the "``.apple_names``" (all functions +
2107 globals), the "``.apple_types``" (names of all types that are defined), and
2108 the "``.apple_namespaces``" (all namespaces), we currently set the ``Atom``
2109 array to be:
2110
2111 .. code-block:: c
2112
2113   HeaderData.atom_count = 1;
2114   HeaderData.atoms[0].type = eAtomTypeDIEOffset;
2115   HeaderData.atoms[0].form = DW_FORM_data4;
2116
2117 This defines the contents to be the DIE offset (eAtomTypeDIEOffset) that is
2118 encoded as a 32 bit value (DW_FORM_data4).  This allows a single name to have
2119 multiple matching DIEs in a single file, which could come up with an inlined
2120 function for instance.  Future tables could include more information about the
2121 DIE such as flags indicating if the DIE is a function, method, block,
2122 or inlined.
2123
2124 The KeyType for the DWARF table is a 32 bit string table offset into the
2125 ".debug_str" table.  The ".debug_str" is the string table for the DWARF which
2126 may already contain copies of all of the strings.  This helps make sure, with
2127 help from the compiler, that we reuse the strings between all of the DWARF
2128 sections and keeps the hash table size down.  Another benefit to having the
2129 compiler generate all strings as DW_FORM_strp in the debug info, is that
2130 DWARF parsing can be made much faster.
2131
2132 After a lookup is made, we get an offset into the hash data.  The hash data
2133 needs to be able to deal with 32 bit hash collisions, so the chunk of data
2134 at the offset in the hash data consists of a triple:
2135
2136 .. code-block:: c
2137
2138   uint32_t str_offset
2139   uint32_t hash_data_count
2140   HashData[hash_data_count]
2141
2142 If "str_offset" is zero, then the bucket contents are done. 99.9% of the
2143 hash data chunks contain a single item (no 32 bit hash collision):
2144
2145 .. code-block:: none
2146
2147   .------------.
2148   | 0x00001023 | uint32_t KeyType (.debug_str[0x0001023] => "main")
2149   | 0x00000004 | uint32_t HashData count
2150   | 0x........ | uint32_t HashData[0] DIE offset
2151   | 0x........ | uint32_t HashData[1] DIE offset
2152   | 0x........ | uint32_t HashData[2] DIE offset
2153   | 0x........ | uint32_t HashData[3] DIE offset
2154   | 0x00000000 | uint32_t KeyType (end of hash chain)
2155   `------------'
2156
2157 If there are collisions, you will have multiple valid string offsets:
2158
2159 .. code-block:: none
2160
2161   .------------.
2162   | 0x00001023 | uint32_t KeyType (.debug_str[0x0001023] => "main")
2163   | 0x00000004 | uint32_t HashData count
2164   | 0x........ | uint32_t HashData[0] DIE offset
2165   | 0x........ | uint32_t HashData[1] DIE offset
2166   | 0x........ | uint32_t HashData[2] DIE offset
2167   | 0x........ | uint32_t HashData[3] DIE offset
2168   | 0x00002023 | uint32_t KeyType (.debug_str[0x0002023] => "print")
2169   | 0x00000002 | uint32_t HashData count
2170   | 0x........ | uint32_t HashData[0] DIE offset
2171   | 0x........ | uint32_t HashData[1] DIE offset
2172   | 0x00000000 | uint32_t KeyType (end of hash chain)
2173   `------------'
2174
2175 Current testing with real world C++ binaries has shown that there is around 1
2176 32 bit hash collision per 100,000 name entries.
2177
2178 Contents
2179 ^^^^^^^^
2180
2181 As we said, we want to strictly define exactly what is included in the
2182 different tables.  For DWARF, we have 3 tables: "``.apple_names``",
2183 "``.apple_types``", and "``.apple_namespaces``".
2184
2185 "``.apple_names``" sections should contain an entry for each DWARF DIE whose
2186 ``DW_TAG`` is a ``DW_TAG_label``, ``DW_TAG_inlined_subroutine``, or
2187 ``DW_TAG_subprogram`` that has address attributes: ``DW_AT_low_pc``,
2188 ``DW_AT_high_pc``, ``DW_AT_ranges`` or ``DW_AT_entry_pc``.  It also contains
2189 ``DW_TAG_variable`` DIEs that have a ``DW_OP_addr`` in the location (global and
2190 static variables).  All global and static variables should be included,
2191 including those scoped within functions and classes.  For example using the
2192 following code:
2193
2194 .. code-block:: c
2195
2196   static int var = 0;
2197
2198   void f ()
2199   {
2200     static int var = 0;
2201   }
2202
2203 Both of the static ``var`` variables would be included in the table.  All
2204 functions should emit both their full names and their basenames.  For C or C++,
2205 the full name is the mangled name (if available) which is usually in the
2206 ``DW_AT_MIPS_linkage_name`` attribute, and the ``DW_AT_name`` contains the
2207 function basename.  If global or static variables have a mangled name in a
2208 ``DW_AT_MIPS_linkage_name`` attribute, this should be emitted along with the
2209 simple name found in the ``DW_AT_name`` attribute.
2210
2211 "``.apple_types``" sections should contain an entry for each DWARF DIE whose
2212 tag is one of:
2213
2214 * DW_TAG_array_type
2215 * DW_TAG_class_type
2216 * DW_TAG_enumeration_type
2217 * DW_TAG_pointer_type
2218 * DW_TAG_reference_type
2219 * DW_TAG_string_type
2220 * DW_TAG_structure_type
2221 * DW_TAG_subroutine_type
2222 * DW_TAG_typedef
2223 * DW_TAG_union_type
2224 * DW_TAG_ptr_to_member_type
2225 * DW_TAG_set_type
2226 * DW_TAG_subrange_type
2227 * DW_TAG_base_type
2228 * DW_TAG_const_type
2229 * DW_TAG_constant
2230 * DW_TAG_file_type
2231 * DW_TAG_namelist
2232 * DW_TAG_packed_type
2233 * DW_TAG_volatile_type
2234 * DW_TAG_restrict_type
2235 * DW_TAG_interface_type
2236 * DW_TAG_unspecified_type
2237 * DW_TAG_shared_type
2238
2239 Only entries with a ``DW_AT_name`` attribute are included, and the entry must
2240 not be a forward declaration (``DW_AT_declaration`` attribute with a non-zero
2241 value).  For example, using the following code:
2242
2243 .. code-block:: c
2244
2245   int main ()
2246   {
2247     int *b = 0;
2248     return *b;
2249   }
2250
2251 We get a few type DIEs:
2252
2253 .. code-block:: none
2254
2255   0x00000067:     TAG_base_type [5]
2256                   AT_encoding( DW_ATE_signed )
2257                   AT_name( "int" )
2258                   AT_byte_size( 0x04 )
2259
2260   0x0000006e:     TAG_pointer_type [6]
2261                   AT_type( {0x00000067} ( int ) )
2262                   AT_byte_size( 0x08 )
2263
2264 The DW_TAG_pointer_type is not included because it does not have a ``DW_AT_name``.
2265
2266 "``.apple_namespaces``" section should contain all ``DW_TAG_namespace`` DIEs.
2267 If we run into a namespace that has no name this is an anonymous namespace, and
2268 the name should be output as "``(anonymous namespace)``" (without the quotes).
2269 Why?  This matches the output of the ``abi::cxa_demangle()`` that is in the
2270 standard C++ library that demangles mangled names.
2271
2272
2273 Language Extensions and File Format Changes
2274 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2275
2276 Objective-C Extensions
2277 """"""""""""""""""""""
2278
2279 "``.apple_objc``" section should contain all ``DW_TAG_subprogram`` DIEs for an
2280 Objective-C class.  The name used in the hash table is the name of the
2281 Objective-C class itself.  If the Objective-C class has a category, then an
2282 entry is made for both the class name without the category, and for the class
2283 name with the category.  So if we have a DIE at offset 0x1234 with a name of
2284 method "``-[NSString(my_additions) stringWithSpecialString:]``", we would add
2285 an entry for "``NSString``" that points to DIE 0x1234, and an entry for
2286 "``NSString(my_additions)``" that points to 0x1234.  This allows us to quickly
2287 track down all Objective-C methods for an Objective-C class when doing
2288 expressions.  It is needed because of the dynamic nature of Objective-C where
2289 anyone can add methods to a class.  The DWARF for Objective-C methods is also
2290 emitted differently from C++ classes where the methods are not usually
2291 contained in the class definition, they are scattered about across one or more
2292 compile units.  Categories can also be defined in different shared libraries.
2293 So we need to be able to quickly find all of the methods and class functions
2294 given the Objective-C class name, or quickly find all methods and class
2295 functions for a class + category name.  This table does not contain any
2296 selector names, it just maps Objective-C class names (or class names +
2297 category) to all of the methods and class functions.  The selectors are added
2298 as function basenames in the "``.debug_names``" section.
2299
2300 In the "``.apple_names``" section for Objective-C functions, the full name is
2301 the entire function name with the brackets ("``-[NSString
2302 stringWithCString:]``") and the basename is the selector only
2303 ("``stringWithCString:``").
2304
2305 Mach-O Changes
2306 """"""""""""""
2307
2308 The sections names for the apple hash tables are for non mach-o files.  For
2309 mach-o files, the sections should be contained in the ``__DWARF`` segment with
2310 names as follows:
2311
2312 * "``.apple_names``" -> "``__apple_names``"
2313 * "``.apple_types``" -> "``__apple_types``"
2314 * "``.apple_namespaces``" -> "``__apple_namespac``" (16 character limit)
2315 * "``.apple_objc``" -> "``__apple_objc``"
2316