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

439 lines
16 KiB
C++

//===--- AddUsing.cpp --------------------------------------------*- C++-*-===//
//
// 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 "AST.h"
#include "Config.h"
#include "SourceCode.h"
#include "refactor/Tweak.h"
#include "support/Logger.h"
#include "clang/AST/Decl.h"
#include "clang/AST/Expr.h"
#include "clang/AST/NestedNameSpecifier.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/AST/Type.h"
#include "clang/AST/TypeLoc.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Tooling/Core/Replacement.h"
#include "clang/Tooling/Syntax/Tokens.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/FormatVariadic.h"
#include "llvm/Support/raw_ostream.h"
#include <string>
#include <tuple>
#include <utility>
namespace clang {
namespace clangd {
namespace {
// Tweak for removing full namespace qualifier under cursor on DeclRefExpr and
// types and adding "using" statement instead.
//
// Only qualifiers that refer exclusively to namespaces (no record types) are
// supported. There is some guessing of appropriate place to insert the using
// declaration. If we find any existing usings, we insert it there. If not, we
// insert right after the inner-most relevant namespace declaration. If there is
// none, or there is, but it was declared via macro, we insert above the first
// top level decl.
//
// Currently this only removes qualifier from under the cursor. In the future,
// we should improve this to remove qualifier from all occurrences of this
// symbol.
class AddUsing : public Tweak {
public:
const char *id() const override;
bool prepare(const Selection &Inputs) override;
Expected<Effect> apply(const Selection &Inputs) override;
std::string title() const override;
llvm::StringLiteral kind() const override {
return CodeAction::REFACTOR_KIND;
}
private:
// All of the following are set by prepare().
// The qualifier to remove.
NestedNameSpecifierLoc QualifierToRemove;
// Qualified name to use when spelling the using declaration. This might be
// different than SpelledQualifier in presence of error correction.
std::string QualifierToSpell;
// The name and qualifier as spelled in the code.
llvm::StringRef SpelledQualifier;
llvm::StringRef SpelledName;
// If valid, the insertion point for "using" statement must come after this.
// This is relevant when the type is defined in the main file, to make sure
// the type/function is already defined at the point where "using" is added.
SourceLocation MustInsertAfterLoc;
};
REGISTER_TWEAK(AddUsing)
std::string AddUsing::title() const {
return std::string(llvm::formatv(
"Add using-declaration for {0} and remove qualifier", SpelledName));
}
// Locates all "using" statements relevant to SelectionDeclContext.
class UsingFinder : public RecursiveASTVisitor<UsingFinder> {
public:
UsingFinder(std::vector<const UsingDecl *> &Results,
const DeclContext *SelectionDeclContext, const SourceManager &SM)
: Results(Results), SelectionDeclContext(SelectionDeclContext), SM(SM) {}
bool VisitUsingDecl(UsingDecl *D) {
auto Loc = D->getUsingLoc();
if (SM.getFileID(Loc) != SM.getMainFileID()) {
return true;
}
if (D->getDeclContext()->Encloses(SelectionDeclContext)) {
Results.push_back(D);
}
return true;
}
bool TraverseDecl(Decl *Node) {
if (!Node)
return true;
// There is no need to go deeper into nodes that do not enclose selection,
// since "using" there will not affect selection, nor would it make a good
// insertion point.
if (!Node->getDeclContext() ||
Node->getDeclContext()->Encloses(SelectionDeclContext)) {
return RecursiveASTVisitor<UsingFinder>::TraverseDecl(Node);
}
return true;
}
private:
std::vector<const UsingDecl *> &Results;
const DeclContext *SelectionDeclContext;
const SourceManager &SM;
};
struct InsertionPointData {
// Location to insert the "using" statement. If invalid then the statement
// should not be inserted at all (it already exists).
SourceLocation Loc;
// Extra suffix to place after the "using" statement. Depending on what the
// insertion point is anchored to, we may need one or more \n to ensure
// proper formatting.
std::string Suffix;
// Whether using should be fully qualified, even if what the user typed was
// not. This is based on our detection of the local style.
bool AlwaysFullyQualify = false;
};
// Finds the best place to insert the "using" statement. Returns invalid
// SourceLocation if the "using" statement already exists.
//
// The insertion point might be a little awkward if the decl we're anchoring to
// has a comment in an unfortunate place (e.g. directly above function or using
// decl, or immediately following "namespace {". We should add some helpers for
// dealing with that and use them in other code modifications as well.
llvm::Expected<InsertionPointData>
findInsertionPoint(const Tweak::Selection &Inputs,
const NestedNameSpecifierLoc &QualifierToRemove,
const llvm::StringRef Name,
const SourceLocation MustInsertAfterLoc) {
auto &SM = Inputs.AST->getSourceManager();
// Search for all using decls that affect this point in file. We need this for
// two reasons: to skip adding "using" if one already exists and to find best
// place to add it, if it doesn't exist.
SourceLocation LastUsingLoc;
std::vector<const UsingDecl *> Usings;
UsingFinder(Usings, &Inputs.ASTSelection.commonAncestor()->getDeclContext(),
SM)
.TraverseAST(Inputs.AST->getASTContext());
auto IsValidPoint = [&](const SourceLocation Loc) {
return MustInsertAfterLoc.isInvalid() ||
SM.isBeforeInTranslationUnit(MustInsertAfterLoc, Loc);
};
bool AlwaysFullyQualify = true;
for (auto &U : Usings) {
// Only "upgrade" to fully qualified is all relevant using decls are fully
// qualified. Otherwise trust what the user typed.
if (!U->getQualifier().isFullyQualified())
AlwaysFullyQualify = false;
if (SM.isBeforeInTranslationUnit(Inputs.Cursor, U->getUsingLoc()))
// "Usings" is sorted, so we're done.
break;
if (NestedNameSpecifier Qualifier = U->getQualifier();
Qualifier.getKind() == NestedNameSpecifier::Kind::Namespace) {
const auto *Namespace =
U->getQualifier().getAsNamespaceAndPrefix().Namespace;
if (Namespace->getCanonicalDecl() ==
QualifierToRemove.getNestedNameSpecifier()
.getAsNamespaceAndPrefix()
.Namespace->getCanonicalDecl() &&
U->getName() == Name) {
return InsertionPointData();
}
}
// Insertion point will be before last UsingDecl that affects cursor
// position. For most cases this should stick with the local convention of
// add using inside or outside namespace.
LastUsingLoc = U->getUsingLoc();
}
if (LastUsingLoc.isValid() && IsValidPoint(LastUsingLoc)) {
InsertionPointData Out;
Out.Loc = LastUsingLoc;
Out.AlwaysFullyQualify = AlwaysFullyQualify;
return Out;
}
// No relevant "using" statements. Try the nearest namespace level.
const DeclContext *ParentDeclCtx =
&Inputs.ASTSelection.commonAncestor()->getDeclContext();
while (ParentDeclCtx && !ParentDeclCtx->isFileContext()) {
ParentDeclCtx = ParentDeclCtx->getLexicalParent();
}
if (auto *ND = llvm::dyn_cast_or_null<NamespaceDecl>(ParentDeclCtx)) {
auto Toks = Inputs.AST->getTokens().expandedTokens(ND->getSourceRange());
const auto *Tok = llvm::find_if(Toks, [](const syntax::Token &Tok) {
return Tok.kind() == tok::l_brace;
});
if (Tok == Toks.end() || Tok->endLocation().isInvalid()) {
return error("Namespace with no {{");
}
if (!Tok->endLocation().isMacroID() && IsValidPoint(Tok->endLocation())) {
InsertionPointData Out;
Out.Loc = Tok->endLocation();
Out.Suffix = "\n";
return Out;
}
}
// No using, no namespace, no idea where to insert. Try above the first
// top level decl after MustInsertAfterLoc.
auto TLDs = Inputs.AST->getLocalTopLevelDecls();
for (const auto &TLD : TLDs) {
if (!IsValidPoint(TLD->getBeginLoc()))
continue;
InsertionPointData Out;
Out.Loc = SM.getExpansionLoc(TLD->getBeginLoc());
Out.Suffix = "\n\n";
return Out;
}
return error("Cannot find place to insert \"using\"");
}
bool isNamespaceForbidden(const Tweak::Selection &Inputs,
NestedNameSpecifier Namespace) {
const auto *NS =
dyn_cast<NamespaceDecl>(Namespace.getAsNamespaceAndPrefix().Namespace);
if (!NS)
return true;
std::string NamespaceStr = printNamespaceScope(*NS);
for (StringRef Banned : Config::current().Style.FullyQualifiedNamespaces) {
StringRef PrefixMatch = NamespaceStr;
if (PrefixMatch.consume_front(Banned) && PrefixMatch.consume_front("::"))
return true;
}
return false;
}
std::string getNNSLAsString(NestedNameSpecifierLoc NNSL,
const PrintingPolicy &Policy) {
std::string Out;
llvm::raw_string_ostream OutStream(Out);
NNSL.getNestedNameSpecifier().print(OutStream, Policy);
return OutStream.str();
}
bool AddUsing::prepare(const Selection &Inputs) {
auto &SM = Inputs.AST->getSourceManager();
const auto &TB = Inputs.AST->getTokens();
// Do not suggest "using" in header files. That way madness lies.
if (isHeaderFile(SM.getFileEntryRefForID(SM.getMainFileID())->getName(),
Inputs.AST->getLangOpts()))
return false;
auto *Node = Inputs.ASTSelection.commonAncestor();
if (Node == nullptr)
return false;
// If we're looking at a type or NestedNameSpecifier, walk up the tree until
// we find the "main" node we care about, which would be ElaboratedTypeLoc or
// DeclRefExpr.
for (; Node->Parent; Node = Node->Parent) {
if (Node->ASTNode.get<NestedNameSpecifierLoc>()) {
continue;
}
if (auto *T = Node->ASTNode.get<TypeLoc>()) {
// Find the outermost TypeLoc.
if (Node->Parent->ASTNode.get<NestedNameSpecifierLoc>())
continue;
if (isa<TagType, TemplateSpecializationType, TypedefType, UsingType,
UnresolvedUsingType>(T->getTypePtr()))
break;
// Find the outermost TypeLoc.
if (Node->Parent->ASTNode.get<TypeLoc>())
continue;
}
break;
}
if (Node == nullptr)
return false;
// Closed range for the fully qualified name as spelled in source code.
SourceRange SpelledNameRange;
if (auto *D = Node->ASTNode.get<DeclRefExpr>()) {
if (D->getDecl()->getIdentifier()) {
QualifierToRemove = D->getQualifierLoc();
// Use the name range rather than expr, as the latter can contain template
// arguments in the range.
SpelledNameRange = D->getSourceRange();
// Remove the template arguments from the name, as they shouldn't be
// spelled in the using declaration.
if (auto AngleLoc = D->getLAngleLoc(); AngleLoc.isValid())
SpelledNameRange.setEnd(AngleLoc.getLocWithOffset(-1));
MustInsertAfterLoc = D->getDecl()->getBeginLoc();
}
} else if (auto *T = Node->ASTNode.get<TypeLoc>()) {
switch (T->getTypeLocClass()) {
case TypeLoc::TemplateSpecialization: {
auto TL = T->castAs<TemplateSpecializationTypeLoc>();
QualifierToRemove = TL.getQualifierLoc();
if (!QualifierToRemove)
break;
SpelledNameRange = TL.getTemplateNameLoc();
if (auto *TD = TL.getTypePtr()->getTemplateName().getAsTemplateDecl(
/*IgnoreDeduced=*/true))
MustInsertAfterLoc = TD->getBeginLoc();
break;
}
case TypeLoc::Enum:
case TypeLoc::Record:
case TypeLoc::InjectedClassName: {
auto TL = T->castAs<TagTypeLoc>();
QualifierToRemove = TL.getQualifierLoc();
if (!QualifierToRemove)
break;
SpelledNameRange = TL.getNameLoc();
MustInsertAfterLoc = TL.getOriginalDecl()->getBeginLoc();
break;
}
case TypeLoc::Typedef: {
auto TL = T->castAs<TypedefTypeLoc>();
QualifierToRemove = TL.getQualifierLoc();
if (!QualifierToRemove)
break;
SpelledNameRange = TL.getNameLoc();
MustInsertAfterLoc = TL.getDecl()->getBeginLoc();
break;
}
case TypeLoc::UnresolvedUsing: {
auto TL = T->castAs<UnresolvedUsingTypeLoc>();
QualifierToRemove = TL.getQualifierLoc();
if (!QualifierToRemove)
break;
SpelledNameRange = TL.getNameLoc();
MustInsertAfterLoc = TL.getDecl()->getBeginLoc();
break;
}
case TypeLoc::Using: {
auto TL = T->castAs<UsingTypeLoc>();
QualifierToRemove = TL.getQualifierLoc();
if (!QualifierToRemove)
break;
SpelledNameRange = TL.getNameLoc();
MustInsertAfterLoc = TL.getDecl()->getBeginLoc();
break;
}
default:
break;
}
if (QualifierToRemove)
SpelledNameRange.setBegin(QualifierToRemove.getBeginLoc());
}
if (!QualifierToRemove ||
// FIXME: This only supports removing qualifiers that are made up of just
// namespace names. If qualifier contains a type, we could take the
// longest namespace prefix and remove that.
QualifierToRemove.getNestedNameSpecifier().getKind() !=
NestedNameSpecifier::Kind::Namespace ||
// Respect user config.
isNamespaceForbidden(Inputs, QualifierToRemove.getNestedNameSpecifier()))
return false;
// Macros are difficult. We only want to offer code action when what's spelled
// under the cursor is a namespace qualifier. If it's a macro that expands to
// a qualifier, user would not know what code action will actually change.
// On the other hand, if the qualifier is part of the macro argument, we
// should still support that.
if (SM.isMacroBodyExpansion(QualifierToRemove.getBeginLoc()) ||
!SM.isWrittenInSameFile(QualifierToRemove.getBeginLoc(),
QualifierToRemove.getEndLoc())) {
return false;
}
auto SpelledTokens =
TB.spelledForExpanded(TB.expandedTokens(SpelledNameRange));
if (!SpelledTokens)
return false;
auto SpelledRange =
syntax::Token::range(SM, SpelledTokens->front(), SpelledTokens->back());
// We only drop qualifiers that're namespaces, so this is safe.
std::tie(SpelledQualifier, SpelledName) =
splitQualifiedName(SpelledRange.text(SM));
QualifierToSpell = getNNSLAsString(
QualifierToRemove, Inputs.AST->getASTContext().getPrintingPolicy());
if (!llvm::StringRef(QualifierToSpell).ends_with(SpelledQualifier) ||
SpelledName.empty())
return false; // What's spelled doesn't match the qualifier.
return true;
}
Expected<Tweak::Effect> AddUsing::apply(const Selection &Inputs) {
auto &SM = Inputs.AST->getSourceManager();
tooling::Replacements R;
if (auto Err = R.add(tooling::Replacement(
SM, SM.getSpellingLoc(QualifierToRemove.getBeginLoc()),
SpelledQualifier.size(), ""))) {
return std::move(Err);
}
auto InsertionPoint = findInsertionPoint(Inputs, QualifierToRemove,
SpelledName, MustInsertAfterLoc);
if (!InsertionPoint) {
return InsertionPoint.takeError();
}
if (InsertionPoint->Loc.isValid()) {
// Add the using statement at appropriate location.
std::string UsingText;
llvm::raw_string_ostream UsingTextStream(UsingText);
UsingTextStream << "using ";
if (InsertionPoint->AlwaysFullyQualify &&
!QualifierToRemove.getNestedNameSpecifier().isFullyQualified())
UsingTextStream << "::";
UsingTextStream << QualifierToSpell << SpelledName << ";"
<< InsertionPoint->Suffix;
assert(SM.getFileID(InsertionPoint->Loc) == SM.getMainFileID());
if (auto Err = R.add(tooling::Replacement(SM, InsertionPoint->Loc, 0,
UsingTextStream.str()))) {
return std::move(Err);
}
}
return Effect::mainFileEdit(Inputs.AST->getASTContext().getSourceManager(),
std::move(R));
}
} // namespace
} // namespace clangd
} // namespace clang