[RFC] A Faster, More Reliable Type System for C-languages

In the beginning, it was decided that LLDB would be built upon Clang. While this had some benefits, LLDB’s reliance on Clang has also caused a lot of trouble for both users and developers. This RFC is concerned with one of the biggest pain points, which is our internal type system representation for C/C++/Objective-C programs, also known as TypeSystemClang. This class is responsible for modeling the program we reconstruct from debug info, and also provides the type information for other parts of LLDB (e.g., the expression evaluator or ValueObjects). This RFC is about replacing TypeSystemClang with a new TypeSystem that does not depend on Clang to make LLDB less fragile and more efficient. Note that this does not mean we remove the Clang expression evaluator.

Before we can talk about our solution, let me quickly describe how the current system works and what its problems are. In a nutshell, TypeSystemClang internally uses a Clang AST (that is, the AST nodes usually created by Clang’s parser) to represent any type in the debugged program. Let’s say you compile the following C program with Clang:

struct S { int a; int b; };

After parsing, Clang will internally represent this struct with a CXXRecordDecl S and two FieldDecls a and b (plus some other related data structures). When you debug the program with LLDB, TypeSystemClang (and its DWARF parser) will translate the debug information back into a Clang AST. This reconstructed Clang AST is supposed to be mostly identical to the one created by Clang’s parser during compilation.

The rest of LLDB relies on these created Clang AST nodes to answer most type-related queries coming from other parts of LLDB. I tried to create a very simplified overview of this scheme in the diagram below. For example, if you inspect a variable my_var of type S, LLDB will refer to the properties of the created CXXRecordDecl to tell you how many members it has. Similarly, we inspect the FieldDecls when we need to tell users what types those members have and to figure out how to format their underlying memory.

A more complicated scenario is expression evaluation. Here we parse a user’s expression such as (&my_var) + 8 and then have to provide Clang AST nodes that are needed to explain to Clang the type of my_var. We use the ASTImporter to copy the needed Clang AST nodes into a temporary expression AST. We then JIT and execute the code to calculate the result.

To actually display the result, we again copy the type with the ASTImporter to the scratch AST, which is our long-term type storage for each process. We need to do this for three reasons:

  1. The ValueObject for the expression result can be inspected in follow-up queries by the user, so we need to keep the type around to answer those queries.

  2. We want to get rid of the large expression AST to recover its used memory. We need to preserve the type as just explained, so we save the required type information in some long-term storage (which is the scratch type system). Note that we don’t move the whole Clang AST to the scratch AST, but only the type information of the expression result (Foo * in the diagram below). Additionally, we merge equivalent types in the scratch AST so that calling expression repeatedly with the same result type doesn’t keep allocating permanent memory.

  3. Clang ASTs are self-contained, so we need to actually copy this data. For example, the int Type object in a Clang AST can’t be the int Type object from a different AST. This prevents us from simply making a pointer to the type in the original AST.

                                           +--------------------+
              (lldb) frame var my_var      | Debugger Interface |    (lldb) expr (&my_var) + 8
                            |              +--------------------+             |
                            |                                                 |
                            |                                                 |
                            |                                                 |
                            +--------+                                        +------------------------+
                                     |                                                                 |
                                     |                                                                 |
                                     |                                                                 |
                                     |                                                                 |
      +-------+  Translation   +-----v-----+  ASTImporter   +----------------------+   ASTImporter  +--v-----------+
      | DWARF | =============> | Clang AST | =============> | Clang Expression AST | =============> | Scratch AST  |
      +-------+                +-----------+                +----------------------+                +--------------+

    DW_TAG_structure_type      struct Foo {                   struct Foo {                            struct Foo {
      DW_AT_cc_convention        int member;                    int member;                             int member;
      DW_AT_name "Foo"         };                             };                                      };
      DW_AT_byte_size 0x04                                                                            Foo * 
      DW_AT_decl_file "foo.c"                                 Foo my_var;                              ^
      DW_AT_decl_line 1                                                                                |
                                                              Foo *__lldb_expr() {                  /* This is a new PointerType */
      DW_TAG_member                                             return &my_var + 8;                 /* that only exists here.    */
        DW_AT_name   "member"                                 }
        DW_AT_type   "int"                                    (Very simplified code)
        DW_AT_decl_file  "foo.c"
        DW_AT_decl_line  2

The Bad And The Ugly

While modeling everything as Clang AST nodes seems like a neat design, it has become clear over time that it causes more problems than it solves. LLDB currently suffers from various performance and reliability issues that can often be traced back to our reliance on the Clang AST. In general, these issues can be attributed to two root causes.

1. The Clang AST is not designed to handle LLDB’s use cases

Clang ASTs are usually created from source code (or equivalent, like a module) and describe one translation unit. In LLDB’s case, nearly all types are created from DWARF, which is neither an exact representation of the source code nor limited to one translation unit. For this reason, we have various workarounds in place to fill the gaps with synthetic declarations that make the result look like an AST that Clang’s frontend would produce.

For example, because DWARF only describes template instantiations and not the templates themselves, we infer synthetic template classes to connect our instantiations to a forward-declared template. However, because we might need to represent several translation units in one AST, we could have two templates with the same name but different template args. Connecting a template instantiation to a template with different parameters creates a malformed AST, so we need another workaround. The current approach is to use a heuristic that decides when we can reuse an existing class template. If this heuristic is too strict, we waste time and memory recreating redundant class templates. However, if the heuristic is too lax, we might reuse an incompatible template and crash (or worse, produce wrong output). The point of this example is to illustrate how the current system requires various workarounds to support even simple debugging workflows.

The biggest workaround we have in LLDB is relying on the ASTImporter. As described above, we use it to copy types across LLDB. The only reason we need to copy types in the first place is that Clang ASTs are self-contained and can’t contain types/decls from a different ASTContext. Note that we aren’t solving any lifetime issues either, as the scratch AST has a shorter lifetime than the DWARF AST we copy from.

The problem with using the ASTImporter is the incredible complexity of the copying process. The ASTImporter itself is already a large piece of code. To add to that, we use its lazy copying mode, which is even more complicated and not very well tested as it’s only used by LLDB. And to make things even worse, we give the ASTImporter the nearly impossible task of merging everything in the weird Clang ASTs we build into something coherent.

The result is that the ASTImporter code has been a constant source of problems. These issues range from the ASTImporter itself crashing to the type merging logic creating incoherent types that cause failures later on. We already landed countless workarounds to fix these issues, and despite that, we still have a huge backlog of unsolved crashes in this system that require even more workarounds.

2. The Clang AST is not very efficient for our use case

Setting aside whether the system works and if we can make it work reliably, the other question is whether it is efficient. One observation I made when benchmarking LLDB is that we can spend a lot of time just copying types with the ASTImporter. To repeat the point from above, this operation is a workaround, and any time we spend moving types between the expression AST and the scratch AST is wasted. It is very strange that we spend a lot of CPU time in a system that doesn’t actually do anything that is of value to the user.

The current system is also inefficient in terms of memory. While using the Clang AST might sound like we benefit from all its memory-saving tricks, we don’t actually benefit from most of them. For one, we mostly just annotate the Clang AST with additional information that overwrites whatever Clang is storing. For example, we overwrite its record layouts and we overwrite the mangled names of functions for the functions we create. We essentially create a Clang AST just to roll our own solution that we have to awkwardly tack on. The record layout overwrite mechanism is, for example, based on a single big DenseMap that works around the fact that we can’t add LLDB-specific fields to Clang’s RecordDecls.

Many other things in Clang are optimized for space, but that doesn’t help us as we don’t need them at all in LLDB. For example, here are a few unused allocations/chunks that occur whenever we create a struct representation:

  • We create a clang::RecordType (32B), an extra allocation used purely as an indirection from the type to the decl. We only use this as it differentiates between Decls and Types (but LLDB doesn’t).
  • We store the “friend” class list (8B), which is always empty and unused in LLDB.
  • We store source locations (8B per record + 8B per field), which are empty in LLDB.
  • We store redeclaration chains (16B), which are also empty in LLDB.
  • And so on…

All of this memory sits unused in LLDB’s heap, and is only touched by the code that initializes it and by the ASTImporter, which duplicates it into even more unused memory on the heap.

A New Design: TypeSystemClike

The description above should make it clear that we need a type system that actually works for LLDB’s use case, which brings us to this RFC. Our plan can be summarized as follows: we stop using the Clang AST unless we need it, and we make a new, simple type system that is designed to work with LLDB’s core debugging workflow.

Our idea is to create a new TypeSystem called TypeSystemClike that models C/C++/Objective-C types directly, in a small IR designed for what a debugger asks of a type. It creates no Clang AST and never calls into TypeSystemClang or the ASTImporter. The DWARF/PDB/etc. parser fills it in; frame var, data formatters, ValueObjects and the SB API read from it.

The IR lives in Plugins/TypeSystem/Clike/Type*.h and is a simple class hierarchy. Our Type classes are designed to be compact, with the base class just having a vtable pointer. Types are owned by a per-module Context, and most type logic is in the subclasses. Aside from that, there isn’t really much else noteworthy about it.

When an expression is evaluated, we still need a Clang AST, because the expression parser remains Clang-based. But instead of importing declarations out of a long-lived Clang AST with the ASTImporter, a new ClangASTGenerator synthesizes Clang declarations directly from the IR, on demand, into the expression’s own ASTContext. The expression AST is thrown away as before. The inverse mapping (ClangTypeConverter) maps the expression’s result type back onto an IR type, which is how the result becomes a long-lived ValueObject. Note that “mapping back” is in most cases just a single map lookup.

The key difference is that there is no long-lived Clang AST and no copying of Clang AST nodes. The scratch type system is a ScratchTypeSystemClike holding IR nodes, so the result of an expression can simply reference the module’s IR node (or, for a type the parser invented, a node created in the scratch context) instead of being copied into a scratch AST. To make this future-proof for potential LLDB design spaces, our IR doesn’t use plain type pointers but a cpp_typesystem::TypeRef which is designed to safely reference nodes in another Context.

                                           +--------------------+
              (lldb) frame var my_var      | Debugger Interface |    (lldb) expr (&my_var) + 8
                            |              +--------------------+             |
                            |                                                 |
                            |                                                 |
                            |                                                 |
                            +--------+                                        +------------------------+
                                     |                                                                 |
                                     |                                                                 |
                                     |                                                                 |
                                     |                                                                 |
      +-------+  Translation   +-----v-----+  Translation   +----------------------+   Map Back     +--v-----------+
      | DWARF | =============> | Custom IR | =============> | Clang Expression AST | =============> | Scratch Area |
      +-------+                +-----------+                +----------------------+                +--------------+
                                             ClangASTGenerator                      ClangTypeConverter

    DW_TAG_structure_type      StructType("Foo",              struct Foo {                            TypeReference foo;
      DW_AT_cc_convention        {Field("m", int_)}             int member;                     .......(points to "Foo")
      DW_AT_name "Foo"         };                             };                                .
      DW_AT_byte_size 0x04                   ^                                                  .     PointerType(foo);
      DW_AT_decl_file "foo.c"                .                Foo my_var;                       .       (generated on demand)
      DW_AT_decl_line 1                      .                                                  .
                                             .                Foo *__lldb_expr() {              .
      DW_TAG_member                          .                  return &my_var + 8;             .
        DW_AT_name   "member"                .                }                                 .
        DW_AT_type   "int"                   .                (Simplified code)                 .
        DW_AT_decl_file  "foo.c"             .                (Same as current system)          .
        DW_AT_decl_line  2                   .                                                  .
                                             ....................................................
                                                     (TypeRef pointing to "Foo")

Prototype

We have a mostly working prototype implementing our proposal where TypeSystemClang and TypeSystemClike live side-by-side in the same LLDB. LLDB uses the new TypeSystemClike by default, but this can always be turned off via symbols.enable-typesystem-cpp.

Nearly all of LLDB’s tests are passing with this prototype. The remaining failing tests belong to one of the following categories:

  • Persistent decls: There are some non-trivial persistent type declarations used in tests that aren’t supported in their current form in the new system. The plans for persistent types are discussed in the “Feature Parity” section below.
  • PDB: SymbolFilePDB and SymbolFileNativePDB still use the old system. I plan to at least port the NativePDB version to the new system, with the old one being a bit more tricky. As above, see the “Feature Parity” section below.
  • Clang AST tests: Those tests dump the Clang AST and inspect it. They simply fail as there is no AST to inspect. I plan to rewrite/update those tests to instead inspect user-facing functionality.
  • Clang modules: TypeSystemClike consults the ClangModulesDeclVendor for functions and ObjC interfaces, but there are a few edge cases (inline functions, for example) that I’m not yet sure how to solve in a way that doesn’t just fall back to the ASTImporter. Note that this is a macOS-only feature and set of tests.

Performance

The current prototype is mostly focused on getting feature parity while leaving performance optimizations for later. Still, there are some performance benefits with the new design (e.g., the lack of copying) that make it worth benchmarking. I set up two short benchmarks that compare our prototype versus the baseline TypeSystemClang in two setups. The benchmarked commands are frame var and expression, which are the main users of the type system logic.

The first scenario is debugging a real Clang invocation where I stop in clang::Sema::ActOnEndOfTranslationUnit. The reason I stop in this method is that Sema is one of the most complex classes in Clang, and I print out the Preprocessor member. With TypeSystemClike, frame var/expression is about twice as fast (wait time drops from 2.2s to 1.1s, and 0.5s to 0.25s for expr and frame var respectively).

I also made an artificial pathological example where the whole program is just one function, but it contains about 50k struct types. The structs are all referencing each other’s types, and one big outer struct is what I’m trying to print with LLDB. I also bumped the maximum number of children to be displayed to 400 so LLDB actually has to print out a substantial amount of types. In this use case, frame var takes 13% less time (3s → 2.65s) with TypeSystemClike. The expression command needs 90% less time to complete (33s → 2.8s).

The memory consumption is harder to measure, as in the case of Clang most heap memory is taken up by objects like Symbol, and only a small amount is occupied by the Sema type, so there is little to no change in the memory footprint. In our pathological case, the prototype had a 60% smaller peak memory (RSS) than the baseline. Most of the memory reduction can be attributed to the lack of copies, which roughly halves the allocated memory.

For the future, the new design also opens up many new opportunities for improving LLDB’s performance. For example, we could now try parallelizing type reconstruction and also make using types on multiple threads possible in a safe way. Another option is freeing unused types in a module and reloading them on demand.

Feature Parity

Our current plan is to support all features that are also supported in TypeSystemClang. However, there are two exceptions to this.

The first one is the PDB parsing support using the DIA SDK, which is provided as an external library. Given that this parser is supposed to be replaced by our native PDB parser, the current plan is to not migrate it to TypeSystemClike. However, I don’t expect the migration itself to be a lot of work, so if this is considered essential we could migrate this too. Ideally, we would remove SymbolFilePDB before/alongside TypeSystemClang.

The second exception concerns the more fringe uses of persistent types. If you weren’t aware, LLDB allows declaring new “persistent” types in the expression parser via a $ prefix in the name. For example, this is possible right now:

   1    #include <cstdio>
   2
   3    int buffer[] = {1, 4, 42, 45};
   4
   5    int main() {
   6      void *x = (void*)buffer;
-> 7      printf("%p", x);
   8    }
(lldb) expr struct $Buffer { float x; int a; int b; int c; }
(lldb) expr *($Buffer*)x
($Buffer) $0 = (x = 1.40129846E-45, a = 4, b = 42, c = 45)

For the most part, this feature is preserved and uses like the one above work as before. However, there are some ways to use this feature that would force us to go back to copying and merging Clang AST nodes, which is why this support is limited to some common use cases.

The main change is that declaring persistent types that are more than simple structs now requires using a top-level expression. For example:

(lldb) expression --top-level -- struct $MyClass { $MyClass() { call(); } int x = 4; };

The reason for this is that those declarations are now textually represented in LLDB, and they are inserted where needed as a prefix to expressions that reference one of the used types. This also means that top-level expressions are no longer represented via the SB API’s type system. I don’t expect this change to have a large impact on the user base, given that persistent types have few users.

Testing

Our plan for testing TypeSystemClike is to rely on gtest unit tests at the start, and then use a test variant for existing Python/API tests. The idea is that we run relevant Python tests with TypeSystemClike enabled and disabled and make sure they pass in both modes. This test variant is opt-in, and only tests with the respective decorator will run in both modes. Given the number of affected tests, at some point it would make sense to allow tests based on directory structure. In other words, we would enable the variant for all tests in lang/cpp without requiring a decorator on each individual test.

One concern with using test variants is that it becomes easy to accidentally balloon the runtime of our test suite. Partially motivated by this, I spent the last few months landing various performance improvements to our test infrastructure. Ideally, these two effects should balance each other out and the net growth of our test runtime should be close to zero.

Migration plan

Assuming there are no objections, our plan for replacing the old TypeSystemClang consists of three phases.

1. Developing the prototype in tree

We plan to develop TypeSystemClike incrementally, off by default, behind symbols.enable-typesystem-cpp. Nothing about the default TypeSystemClang behavior changes during this phase, so there is no risk for existing users. We test both type systems in CI during this phase. The phase ends when TypeSystemClike is at feature parity.

2. Switching the default type system to TypeSystemClike

We flip the default of symbols.enable-typesystem-cpp to true, keeping the setting so that anyone hitting a regression can switch back while we fix it. Both configurations stay tested in CI for the duration.

3. Removing the old TypeSystemClang

Once the default has been TypeSystemClike for a full release cycle without significant fallback, remove TypeSystemClang, ClangASTImporter, and all other now-unused classes. This also removes the need to run tests twice.

Development Plan

The plan is that we develop a clean version of this system upstream in a series of small, reviewable PRs. The prototype mainly serves as a way to evaluate changes proposed in reviews, and to give an overview of how the final system could look.

Below is a rough development outline. (Note that one bullet point does not equal one PR. Many of the features below are too large for one patch).

  1. Create the new type representation classes. This is a self-contained subsystem: there is no TypeSystem subclass yet, nothing else in LLDB references it, and it is fully covered by gtest.

  2. Create TypeSystemClike. The TypeSystem implementation with most queries answered. This is still unreachable at runtime and will be tested with gtest.

  3. Create the DWARF parser and the setting. DWARFASTParserCpp and the symbols.enable-typesystem-cpp property (default false during development) to allow using this in LLDB.

    [At this stage we support commands like frame var x (for simple types)]

  4. Create the expression-parser skeleton. ClangASTGenerator, ClangTypeConverter and CppExpressionDeclMap. As a prerequisite, we’ll abstract various functionality from the expression parser via an interface, so we keep the new and old implementation separate.

    [At this stage we support commands like expr x (for simple types)]

  5. Fill in C++ support. Templates, virtual/multiple inheritance, member pointers, operators, static members, namespaces and using-directives, _Complex, __ptrauth, VLAs, etc. This is the bulk of the commit count and this should get most of the tests passing.

    [We plan to reach this stage in time for LLVM/LLDB 24]

  6. Fill in Objective-C. ObjCInterfaceType, ObjC method modeling and message sends, runtime ivar completion, ObjCDeclVendor, dynamic type resolution.

FAQ

Q: Does this mean LLDB no longer uses Clang?

A: No! The expression evaluator is still Clang, and this proposal does not change that. What changes is that the storage format for types read out of debug info is no longer the Clang AST. Clang declarations are synthesized on demand, into the expression’s own throwaway ASTContext, and discarded with it.

Q: Why not just make the Clang AST cheaper / fix TypeSystemClang in place?

A: Most of what LLDB pays for in the Clang AST is not removable without hurting Clang (source locations, redecl chains), as Clang actually needs them all the time. And the reliability problems come from having to produce a well-formed translation unit out of debug info that doesn’t describe one. That constraint is what forces the workarounds for synthetic templates, dummy definitions, asm labels, merging heuristics, and the ASTImporter copying.

Q: What happens to the ASTImporter?

A: LLDB stops using it. Types are no longer copied between ASTs, because there is only one (short-lived) AST at a time. clang::ASTImporter itself is, of course, unaffected, and only LLDB’s dependency on it goes away.

Q: Doesn’t this just mean we have to maintain our own type system?

A: In theory, yes. In practice, this reduces our maintenance burden. The prototype’s IR is smaller and considerably easier to reason about than the machinery it replaces. It also allows us to actually implement logic outside a giant TypeSystem class (the prototype’s fully functional TypeSystemClike is about 2k LoC, while TypeSystemClang is 8k). Even when including the new IR and related code, the new type system would be less code and would rely on far fewer workarounds.

Q: Does this impact the existing debugging support for Rust/D/Dylan/…?

A: TypeSystemClang has support for these languages and I expect TypeSystemClike to have at least the same level of support. Given that we are no longer limited by what we can express in Clang AST nodes, adding dedicated types for those languages is now also feasible (and encouraged).

16 Likes

I am pretty excited by this proposal. In my opinion it removes many of LLDB inefficiencies that stem from converting to Clang AST types too early, while preserving LLDB’s greatest strength: having a real compiler as the expression evaluator. In the Swift plugin we landed (after a thorough redesign) on a similar split between a “frame variable” typesystem that does not depend on the compiler and using the compiler for expression evaluation and it worked out very well.

3 Likes

This seems like a good direction.

I think you downplay the importance of persistent types. We don’t tend to do much reverse engineering while working on lldb, but anybody that does that type of research will have lots of types that they know about but don’t have debug information for, and being able to make them appear in the debugger both for expressions and CreateValueObjectFromMemory is very convenient.

I worry a little bit that making some persistent declarations interpreted at compile time would lead to subtle bugs where the type refers to a known struct when defined, but then when interpreted, that struct name refers to a different layout. Also --top-level means “evaluated completely in the current CU context”, which is not what you are doing here. If you are really just supporting an “auto-insertion in the expr-prefix” it might be better to fail such an expression definition, and tell the user they have to put it in the expr-prefix instead. That way, they will know what they are doing.

I was wondering how this would work in an expression that names a variable of the persistent type, but I guess you’d just always include all these persistent definitions in the expr-prefix of all the expressions you evaluate?

Also, though the ClangModulesDeclVendor is currently used primarily on Darwin platforms, it is a pretty heavily used feature. It provides the most efficient way to get access to preprocessor macros, and for toolkits that rely on #defines it’s a very handy feature. And there’s no real reason why this is Darwin specific, except that the structure of the tools on macOS made it fairly easy to implement. On other systems you probably have to tell the debugger a lot more about how the compiler and libraries are set up to make this work.

Howdy! I’m a bit late to the party, but i did want to chime in as someone who mostly interacts with LLDB from Rust

A while back when writing a prototype TypeSystemRust, I suggested something along the lines of a TypeSystemLLVM and DWARFASTParserLLVM/PdbAstBuilderLLVM that are less C-centric and more usable, generally, by anyone who uses LLVM

(full quote for posterity)

It might be a different story if there was a TypeSystemLLVM and a default DWARFASTParserLLVM that more or less just exposed the raw DWARF data in a default “sane” way. Maybe by assuming the data was generated via LLVM’s DIBuilder API, and that if you have the DW_TAG_struct node, it probably represents a struct. At that point, it’s on the compiler devs to make sure they’re generating sane debug info, which is easy because they already are. There wouldn’t be anything to gain or lose by implementing your own DWARF parser - a huge time-save for implementers - and the LLVMType objects given out could then be interpreted uniquely by the TypeSystem and/or Language plugin.

The corrolary being that DWARF and especially PDB already view programs with C-tinted lenses. Generating debug info in those formats (so far as i’ve seen) more or less requires you to model your types in a C-compatible way. I’m sure that’s not strictly true, but it’s sortof moot since most commonly and semi-commonly used languages are descendants of C to some degree anyway.

TypeSystemCLike seems like it’ll move more in that direction, which is awesome. I havent looked closely at the code, so i wont comment too much on the type representation beyond “i really really hope we stop ignoring debug info that isnt directly useful to C” i.e. if i deliberately provide a name to LLVM’s DIBuilder when creating a primitive, and that name exists in the DWARF data, it’d be nice if LLDB didnt rename it C-style (especially in template args which results in name collisions :melting_face:).

One thing that annoyed me while writing TypeSystemRust was that there’s no way to prefer 1 type system over another if both report that they can handle a given language. Since the plan is for CLike to exist behind a toggle switch anyway, it might be beneficial to generalize that and allow users to specify which typesystem they want for any given language.

Love the initiative, thanks for pushing it forward @Teemperor!

I did want to point out that there’s the TypeSystemFortran project actively landing. How do you forsee other in-tree language plugins being handled? Is each responsible for it’s own DWARF->IR translation?

Related comment: [lldb][Fortran] Added DWARFASTParser for Fortran by Iasonaskrpr · Pull Request #218024 · llvm/llvm-project · GitHub

(sounds like @Walnut356’s comment above touches on the same)

Right, and those use cases should all still be supported. Users can still declare a struct $MyLayout and then cast memory to it and inspect it via the SB API etc. The only change is that if they want to have persistent executable code, they need to use a top-level expression. Once they create an actual value with that type, then we currently just extract the relevant information we need for the SBType API out of the newly declared decl and store it in the new type representation.

That’s mostly how it already works. We patch up normal variables, but generally speaking LLDB always AST nodes around and recompile them. For example, that’s how the current ToT TypeSystemClang works (and always worked like that):

(lldb) expr --top-level -- int count() { static int res = 0; return ++res; } int $first = count(); int $second = count();
(lldb) expr $first
(int) $0 = 1
(lldb) expr $second
(int) $1 = 2
(lldb) expr count() // prints 1 as we just copy `count` and its static variable in here.
(int) $2 = 1
(lldb) expr count() // same as above
(int) $3 = 1

In general the new system preserves the jank of the old system as closely as possible, but the lines between features and bugs are so blurry that we might have to settle on some small functional differences.

If the tokenised user expression contains a persistent function name, then we insert only that function into the expression prefix. If it’s a persistent variable we discover them during parsing create the Clang AST node on demand (which is identical to the current system).

TypeSystemCLike seems like it’ll move more in that direction, which is awesome. I havent looked closely at the code, so i wont comment too much on the type representation beyond “i really really hope we stop ignoring debug info that isnt directly useful to C” i.e. if i deliberately provide a name to LLVM’s DIBuilder when creating a primitive, and that name exists in the DWARF data, it’d be nice if LLDB didnt rename it C-style (especially in template args which results in name collisions :melting_face:).

That’s probably beyond the scope of this RFC, but ideally the new TypeSystem would handle other languages explicitly instead of just interpreting the DWARF as if it were a C program. The new code should be modular enough that adding more explicit Rust support is straightforward.

One thing that annoyed me while writing TypeSystemRust was that there’s no way to prefer 1 type system over another if both report that they can handle a given language. Since the plan is for CLike to exist behind a toggle switch anyway, it might be beneficial to generalize that and allow users to specify which typesystem they want for any given language.

I assume this refers to TypeSystemClang’s ‘support’ for Rust (by just enabling itself when the language type is Rust), which then conflicts with a downstream TypeSystemRust? If yes, then we should just fix the registration API so we can rank TypeSystems by how ‘natively’ they support a certain language. I can make a PR for that as that seems in general like a good thing to have.

Regarding the Fortran TypeSystem: I think we should just go ahead with the Fortran TypeSystem. I don’t think it’s worth blocking the Fortran effort on this, and we can always unify any shared code later on.

That’s probably beyond the scope of this RFC, but ideally the new TypeSystem would handle other languages explicitly instead of just interpreting the DWARF as if it were a C program.

To clarify, my point is that languages that currently rely on TypeSystemClang already pretend to be C in a ton of ways (for better and worse). Since you’re redoing the entire in-memory type representation from scratch anyway, it seems like removing some of the fast-path “we’re definitely working with C” assumptions would be easier right now, rather than later. Doing so mostly comes down to “trust the DWARF data that is already there” rather than adding in hard-coded values.

If I’m not mistaken, the bug I brought up would only require each primitive have a name field that’s used when the type system needs a type name. From what I understand, this regression happened because LLDB added a shortcut (in v21 or 22) to use prebuilt primitive nodes (based on the tag and size) rather than reading the full dwarf entry for the primitive like it used to (or maybe it still reads the name, but uses the prebuilt node when asked for its name? I can’t remember which). I imagine this would also be useful for other languages that pretend to be C but have different primitive names like Zig and C3.

So long as this class doesn’t normalize all primitives found in the dwarf to “known” primitives, and it isn’t the sole source of truth when primitives are queried for e.g. their name, it should be fine.

To extend that example, if non-“known” primitives are allowed, but this assumption remains, it would stop lldb.is_numeric_type from working for non-C languages. SBType.GetBasicType has, in the past, semantically meant GetNumericKind rather than GetCPrimitiveKind. Back when LLDB used to properly read Rust’s u16 as u16, GetBasicType would return lldb.eBasicTypeUnsignedShort, which we can then match against. The eBasicType can be trivially derived from the signedness and size available in the DWARF data. Since we’ve been pretending to be C for a long time, we’re already sortof used to adhering to C semantics in some ways so that the LLDB public interface is baseline useful.

At least IMO, handling the general case seems easier in the long run, rather than also needing a BuiltinTypeRust and BuiltinTypeZig and BuiltinTypeC3 that are all 99% identical.

Yeah, that sounds like a bug. The debug information should always have the priority. However, it’s not as easy as just letting the debug information overwrite type semantics.

The reason there is a hardcoded list at all is that there is a GetBasicTypeFromAST API (and SB API) that maps the LLDB enum to the respective types. So, the hardcoded type logic is needed to support this API.

Anyway, given that we are no longer tied by Clang semantics, it’s easy to add a custom-sized Builtin type for anything we can’t match. However, that would also mean the SBType API wouldn’t work as expected with Rust for types that don’t fit to a known builtin. In general, the whole API that maps to/from BasicType will behave weirdly for types that don’t match a builtin.

I feel like the right way is that we have a custom Builtin for the ones we can’t match, and for the ones we can match to something sensible (like u16 to lldb.eBasicTypeUnsignedShort), we should just add explicit support for them to the new TypeSystem. In other words, we can add a u16/32/… type to the type listing.

I agree, I think the custom types should be for cases where the deviation is large enough (e.g., Objective-C interfaces are a good example).

I don’t think there is any objection to the general direction of this RFC, and the raised concerns are best addressed in PR review where we can figure out the implementation details.

I made a tracking issue on the LLVM bug tracker that I’ll link each PR with. This should hopefully make it easy to follow the development process. If there aren’t any objections then I’ll start merging relevant PRs Monday 28th September.

Would this bring better support for generated DWARF interpretation? (It’s possible the WIP systems for C and Fotran already improve on this?)

The generated Debuginfo in my case reads a length field using an expression. LLDB seems to ignore expressions attached to types. GDB on the other hand handled this well.

In addition, by default, LLDB will format 8bit integer values as Characters, regardless of them having the Char type from Dwarf or not.

The DWARF parser is presumably dropping length records that have expressions? The client of the DWARF parser, Clang AST’s or the new CLike type system just ask “what is the field length”; they aren’t involved in how it’s arrived at. So this isn’t something that the RFC addresses.

If you can contribute an example we can compile that produces such debug information, please file an Issue with the example and someone who works on the DWARF parser can take a look.

As for the default printing for int8_t and uint8_t, etc., those are just defaults in the “format” part of the Data Formatters system. The Data Formatters are not part of the type system, but rather act on Values produced BY the type system using a map of typename matches to format options.

See:

https://lldb.llvm.org/use/variable.html

For more details. If that’s not how you want to see them, just put, for instance:

type format add -f d uint8_t

in your .lldbinit. If you feel more strongly about this, start an RFC with your suggested changes to the default format maps and we can discuss it.

But anyway, this issue is also orthogonal to the changes proposed in this RFC.