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:
-
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.
-
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 callingexpressionrepeatedly with the same result type doesn’t keep allocating permanent memory. -
Clang ASTs are self-contained, so we need to actually copy this data. For example, the
intType object in a Clang AST can’t be theintType 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:
SymbolFilePDBandSymbolFileNativePDBstill 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:
TypeSystemClikeconsults theClangModulesDeclVendorfor 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).
-
Create the new type representation classes. This is a self-contained subsystem: there is no
TypeSystemsubclass yet, nothing else in LLDB references it, and it is fully covered by gtest. -
Create
TypeSystemClike. TheTypeSystemimplementation with most queries answered. This is still unreachable at runtime and will be tested with gtest. -
Create the DWARF parser and the setting.
DWARFASTParserCppand thesymbols.enable-typesystem-cppproperty (default false during development) to allow using this in LLDB.[At this stage we support commands like
frame var x(for simple types)] -
Create the expression-parser skeleton.
ClangASTGenerator,ClangTypeConverterandCppExpressionDeclMap. 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)] -
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]
-
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).