
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:  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
136 lines
5.5 KiB
C++
136 lines
5.5 KiB
C++
//===--- SlicingCheck.cpp - clang-tidy-------------------------------------===//
|
|
//
|
|
// 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 "SlicingCheck.h"
|
|
#include "clang/AST/ASTContext.h"
|
|
#include "clang/AST/RecordLayout.h"
|
|
#include "clang/ASTMatchers/ASTMatchFinder.h"
|
|
#include "clang/ASTMatchers/ASTMatchers.h"
|
|
|
|
using namespace clang::ast_matchers;
|
|
|
|
namespace clang::tidy::cppcoreguidelines {
|
|
|
|
void SlicingCheck::registerMatchers(MatchFinder *Finder) {
|
|
// When we see:
|
|
// class B : public A { ... };
|
|
// A a;
|
|
// B b;
|
|
// a = b;
|
|
// The assignment is OK if:
|
|
// - the assignment operator is defined as taking a B as second parameter,
|
|
// or
|
|
// - B does not define any additional members (either variables or
|
|
// overrides) wrt A.
|
|
//
|
|
// The same holds for copy ctor calls. This also captures stuff like:
|
|
// void f(A a);
|
|
// f(b);
|
|
|
|
// Helpers.
|
|
const auto OfBaseClass = ofClass(cxxRecordDecl().bind("BaseDecl"));
|
|
const auto IsDerivedFromBaseDecl =
|
|
cxxRecordDecl(isDerivedFrom(equalsBoundNode("BaseDecl")))
|
|
.bind("DerivedDecl");
|
|
const auto HasTypeDerivedFromBaseDecl =
|
|
anyOf(hasType(IsDerivedFromBaseDecl),
|
|
hasType(references(IsDerivedFromBaseDecl)));
|
|
const auto IsCallToBaseClass = hasParent(cxxConstructorDecl(
|
|
ofClass(isSameOrDerivedFrom(equalsBoundNode("DerivedDecl"))),
|
|
hasAnyConstructorInitializer(allOf(
|
|
isBaseInitializer(), withInitializer(equalsBoundNode("Call"))))));
|
|
|
|
// Assignment slicing: "a = b;" and "a = std::move(b);" variants.
|
|
const auto SlicesObjectInAssignment =
|
|
callExpr(expr().bind("Call"),
|
|
callee(cxxMethodDecl(anyOf(isCopyAssignmentOperator(),
|
|
isMoveAssignmentOperator()),
|
|
OfBaseClass)),
|
|
hasArgument(1, HasTypeDerivedFromBaseDecl));
|
|
|
|
// Construction slicing: "A a{b};" and "f(b);" variants. Note that in case of
|
|
// slicing the letter will create a temporary and therefore call a ctor.
|
|
const auto SlicesObjectInCtor = cxxConstructExpr(
|
|
expr().bind("Call"),
|
|
hasDeclaration(cxxConstructorDecl(
|
|
anyOf(isCopyConstructor(), isMoveConstructor()), OfBaseClass)),
|
|
hasArgument(0, HasTypeDerivedFromBaseDecl),
|
|
// We need to disable matching on the call to the base copy/move
|
|
// constructor in DerivedDecl's constructors.
|
|
unless(IsCallToBaseClass));
|
|
|
|
Finder->addMatcher(
|
|
traverse(TK_AsIs, expr(SlicesObjectInAssignment).bind("Call")), this);
|
|
Finder->addMatcher(traverse(TK_AsIs, SlicesObjectInCtor), this);
|
|
}
|
|
|
|
/// Warns on methods overridden in DerivedDecl with respect to BaseDecl.
|
|
/// FIXME: this warns on all overrides outside of the sliced path in case of
|
|
/// multiple inheritance.
|
|
void SlicingCheck::diagnoseSlicedOverriddenMethods(
|
|
const Expr &Call, const CXXRecordDecl &DerivedDecl,
|
|
const CXXRecordDecl &BaseDecl) {
|
|
if (DerivedDecl.getCanonicalDecl() == BaseDecl.getCanonicalDecl())
|
|
return;
|
|
for (const auto *Method : DerivedDecl.methods()) {
|
|
// Virtual destructors are OK. We're ignoring constructors since they are
|
|
// tagged as overrides.
|
|
if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method))
|
|
continue;
|
|
if (Method->size_overridden_methods() > 0) {
|
|
diag(Call.getExprLoc(),
|
|
"slicing object from type %0 to %1 discards override %2")
|
|
<< &DerivedDecl << &BaseDecl << Method;
|
|
}
|
|
}
|
|
// Recursively process bases.
|
|
for (const auto &Base : DerivedDecl.bases()) {
|
|
if (const auto *BaseRecordType = Base.getType()->getAs<RecordType>()) {
|
|
if (const auto *BaseRecord = cast_or_null<CXXRecordDecl>(
|
|
BaseRecordType->getOriginalDecl()->getDefinition()))
|
|
diagnoseSlicedOverriddenMethods(Call, *BaseRecord, BaseDecl);
|
|
}
|
|
}
|
|
}
|
|
|
|
void SlicingCheck::check(const MatchFinder::MatchResult &Result) {
|
|
const auto *BaseDecl = Result.Nodes.getNodeAs<CXXRecordDecl>("BaseDecl");
|
|
const auto *DerivedDecl =
|
|
Result.Nodes.getNodeAs<CXXRecordDecl>("DerivedDecl");
|
|
const auto *Call = Result.Nodes.getNodeAs<Expr>("Call");
|
|
assert(BaseDecl != nullptr);
|
|
assert(DerivedDecl != nullptr);
|
|
assert(Call != nullptr);
|
|
|
|
// Warn when slicing the vtable.
|
|
// We're looking through all the methods in the derived class and see if they
|
|
// override some methods in the base class.
|
|
// It's not enough to just test whether the class is polymorphic because we
|
|
// would be fine slicing B to A if no method in B (or its bases) overrides
|
|
// anything in A:
|
|
// class A { virtual void f(); };
|
|
// class B : public A {};
|
|
// because in that case calling A::f is the same as calling B::f.
|
|
diagnoseSlicedOverriddenMethods(*Call, *DerivedDecl, *BaseDecl);
|
|
|
|
// Warn when slicing member variables.
|
|
const auto &BaseLayout =
|
|
BaseDecl->getASTContext().getASTRecordLayout(BaseDecl);
|
|
const auto &DerivedLayout =
|
|
DerivedDecl->getASTContext().getASTRecordLayout(DerivedDecl);
|
|
const CharUnits StateSize =
|
|
DerivedLayout.getDataSize() - BaseLayout.getDataSize();
|
|
if (StateSize.isPositive()) {
|
|
diag(Call->getExprLoc(), "slicing object from type %0 to %1 discards "
|
|
"%2 bytes of state")
|
|
<< DerivedDecl << BaseDecl << static_cast<int>(StateSize.getQuantity());
|
|
}
|
|
}
|
|
|
|
} // namespace clang::tidy::cppcoreguidelines
|