Matheus Izvekov 91cdd35008
[clang] Improve nested name specifier AST representation (#147835)
This is a major change on how we represent nested name qualifications in
the AST.

* The nested name specifier itself and how it's stored is changed. The
prefixes for types are handled within the type hierarchy, which makes
canonicalization for them super cheap, no memory allocation required.
Also translating a type into nested name specifier form becomes a no-op.
An identifier is stored as a DependentNameType. The nested name
specifier gains a lightweight handle class, to be used instead of
passing around pointers, which is similar to what is implemented for
TemplateName. There is still one free bit available, and this handle can
be used within a PointerUnion and PointerIntPair, which should keep
bit-packing aficionados happy.
* The ElaboratedType node is removed, all type nodes in which it could
previously apply to can now store the elaborated keyword and name
qualifier, tail allocating when present.
* TagTypes can now point to the exact declaration found when producing
these, as opposed to the previous situation of there only existing one
TagType per entity. This increases the amount of type sugar retained,
and can have several applications, for example in tracking module
ownership, and other tools which care about source file origins, such as
IWYU. These TagTypes are lazily allocated, in order to limit the
increase in AST size.

This patch offers a great performance benefit.

It greatly improves compilation time for
[stdexec](https://github.com/NVIDIA/stdexec). For one datapoint, for
`test_on2.cpp` in that project, which is the slowest compiling test,
this patch improves `-c` compilation time by about 7.2%, with the
`-fsyntax-only` improvement being at ~12%.

This has great results on compile-time-tracker as well:

![image](https://github.com/user-attachments/assets/700dce98-2cab-4aa8-97d1-b038c0bee831)

This patch also further enables other optimziations in the future, and
will reduce the performance impact of template specialization resugaring
when that lands.

It has some other miscelaneous drive-by fixes.

About the review: Yes the patch is huge, sorry about that. Part of the
reason is that I started by the nested name specifier part, before the
ElaboratedType part, but that had a huge performance downside, as
ElaboratedType is a big performance hog. I didn't have the steam to go
back and change the patch after the fact.

There is also a lot of internal API changes, and it made sense to remove
ElaboratedType in one go, versus removing it from one type at a time, as
that would present much more churn to the users. Also, the nested name
specifier having a different API avoids missing changes related to how
prefixes work now, which could make existing code compile but not work.

How to review: The important changes are all in
`clang/include/clang/AST` and `clang/lib/AST`, with also important
changes in `clang/lib/Sema/TreeTransform.h`.

The rest and bulk of the changes are mostly consequences of the changes
in API.

PS: TagType::getDecl is renamed to `getOriginalDecl` in this patch, just
for easier to rebasing. I plan to rename it back after this lands.

Fixes #136624
Fixes https://github.com/llvm/llvm-project/issues/43179
Fixes https://github.com/llvm/llvm-project/issues/68670
Fixes https://github.com/llvm/llvm-project/issues/92757
2025-08-09 05:06:53 -03:00

233 lines
7.2 KiB
C++

//===-- DumpASTTests.cpp --------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "Annotations.h"
#include "DumpAST.h"
#include "TestTU.h"
#include "clang/AST/ASTTypeTraits.h"
#include "llvm/Support/ScopedPrinter.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace clang {
namespace clangd {
namespace {
using testing::Contains;
using testing::Not;
using testing::SizeIs;
MATCHER_P(withDetail, str, "") { return arg.detail == str; }
TEST(DumpASTTests, BasicInfo) {
std::pair</*Code=*/std::string, /*Expected=*/std::string> Cases[] = {
{R"cpp(
float root(int *x) {
return *x + 1;
}
)cpp",
R"(
declaration: Function - root
type: FunctionProto
type: Builtin - float
declaration: ParmVar - x
type: Pointer
type: Builtin - int
statement: Compound
statement: Return
expression: ImplicitCast - IntegralToFloating
expression: BinaryOperator - +
expression: ImplicitCast - LValueToRValue
expression: UnaryOperator - *
expression: ImplicitCast - LValueToRValue
expression: DeclRef - x
expression: IntegerLiteral - 1
)"},
{R"cpp(
namespace root {
struct S { static const int x = 0; ~S(); };
int y = S::x + root::S().x;
}
)cpp",
R"(
declaration: Namespace - root
declaration: CXXRecord - S
declaration: Var - x
type: Qualified - const
type: Builtin - int
expression: IntegerLiteral - 0
declaration: CXXDestructor
type: Record - S
type: FunctionProto
type: Builtin - void
declaration: CXXConstructor
declaration: CXXConstructor
declaration: Var - y
type: Builtin - int
expression: ExprWithCleanups
expression: BinaryOperator - +
expression: ImplicitCast - LValueToRValue
expression: DeclRef - x
specifier: Type
type: Record - S
expression: ImplicitCast - LValueToRValue
expression: Member - x
expression: CXXBindTemporary
expression: CXXTemporaryObject - S
type: Record - S
specifier: Namespace - root::
)"},
{R"cpp(
namespace root {
struct S { static const int x = 0; };
int y = S::x + root::S().x;
}
)cpp",
R"(
declaration: Namespace - root
declaration: CXXRecord - S
declaration: Var - x
type: Qualified - const
type: Builtin - int
expression: IntegerLiteral - 0
declaration: CXXConstructor
declaration: CXXConstructor
declaration: CXXConstructor
declaration: CXXDestructor
declaration: Var - y
type: Builtin - int
expression: BinaryOperator - +
expression: ImplicitCast - LValueToRValue
expression: DeclRef - x
specifier: Type
type: Record - S
expression: ImplicitCast - LValueToRValue
expression: Member - x
expression: CXXTemporaryObject - S
type: Record - S
specifier: Namespace - root::
)"},
{R"cpp(
namespace root {
template <typename T> int tmpl() {
(void)tmpl<unsigned>();
return T::value;
}
}
)cpp",
R"(
declaration: Namespace - root
declaration: FunctionTemplate - tmpl
declaration: TemplateTypeParm - T
declaration: Function - tmpl
type: FunctionProto
type: Builtin - int
statement: Compound
expression: CStyleCast - ToVoid
type: Builtin - void
expression: Call
expression: ImplicitCast - FunctionToPointerDecay
expression: DeclRef - tmpl
template argument: Type
type: Builtin - unsigned int
statement: Return
expression: DependentScopeDeclRef - value
specifier: Type
type: TemplateTypeParm - T
)"},
{R"cpp(
struct Foo { char operator+(int); };
char root = Foo() + 42;
)cpp",
R"(
declaration: Var - root
type: Builtin - char
expression: ExprWithCleanups
expression: CXXOperatorCall
expression: ImplicitCast - FunctionToPointerDecay
expression: DeclRef - operator+
expression: MaterializeTemporary - lvalue
expression: CXXTemporaryObject - Foo
type: Record - Foo
expression: IntegerLiteral - 42
)"},
{R"cpp(
struct Bar {
int x;
int root() const {
return x;
}
};
)cpp",
R"(
declaration: CXXMethod - root
type: FunctionProto
type: Builtin - int
statement: Compound
statement: Return
expression: ImplicitCast - LValueToRValue
expression: Member - x
expression: CXXThis - const, implicit
)"},
};
for (const auto &Case : Cases) {
ParsedAST AST = TestTU::withCode(Case.first).build();
auto Node = dumpAST(DynTypedNode::create(findUnqualifiedDecl(AST, "root")),
AST.getTokens(), AST.getASTContext());
EXPECT_EQ(llvm::StringRef(Case.second).trim(),
llvm::StringRef(llvm::to_string(Node)).trim());
}
}
TEST(DumpASTTests, Range) {
Annotations Case("$var[[$type[[int]] x]];");
ParsedAST AST = TestTU::withCode(Case.code()).build();
auto Node = dumpAST(DynTypedNode::create(findDecl(AST, "x")), AST.getTokens(),
AST.getASTContext());
EXPECT_EQ(Node.range, Case.range("var"));
ASSERT_THAT(Node.children, SizeIs(1)) << "Expected one child typeloc";
EXPECT_EQ(Node.children.front().range, Case.range("type"));
}
TEST(DumpASTTests, NoRange) {
auto TU = TestTU::withHeaderCode("void funcFromHeader();");
TU.Code = "int varFromSource;";
ParsedAST AST = TU.build();
auto Node = dumpAST(
DynTypedNode::create(*AST.getASTContext().getTranslationUnitDecl()),
AST.getTokens(), AST.getASTContext());
ASSERT_THAT(Node.children, Contains(withDetail("varFromSource")));
ASSERT_THAT(Node.children, Not(Contains(withDetail("funcFromHeader"))));
EXPECT_THAT(Node.arcana, testing::StartsWith("TranslationUnitDecl "));
ASSERT_FALSE(Node.range) << "Expected no range for translation unit";
}
TEST(DumpASTTests, Arcana) {
ParsedAST AST = TestTU::withCode("int x;").build();
auto Node = dumpAST(DynTypedNode::create(findDecl(AST, "x")), AST.getTokens(),
AST.getASTContext());
EXPECT_THAT(Node.arcana, testing::StartsWith("VarDecl "));
EXPECT_THAT(Node.arcana, testing::EndsWith(" 'int'"));
ASSERT_THAT(Node.children, SizeIs(1)) << "Expected one child typeloc";
EXPECT_THAT(Node.children.front().arcana, testing::StartsWith("QualType "));
}
TEST(DumpASTTests, UnbalancedBraces) {
// Test that we don't crash while trying to compute a source range for the
// node whose ending brace is missing, and also that the source range is
// not empty.
Annotations Case("/*error-ok*/ $func[[int main() {]]");
ParsedAST AST = TestTU::withCode(Case.code()).build();
auto Node = dumpAST(DynTypedNode::create(findDecl(AST, "main")),
AST.getTokens(), AST.getASTContext());
ASSERT_EQ(Node.range, Case.range("func"));
}
} // namespace
} // namespace clangd
} // namespace clang