Debian Codegraph @

llvm-project/clang-tools-extra/clang-tidy/cppcoreguidelines/SlicingCheck.cpp

raw
1 //===--- SlicingCheck.cpp - clang-tidy-------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "SlicingCheck.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/AST/RecordLayout.h"
12 #include "clang/ASTMatchers/ASTMatchFinder.h"
13 #include "clang/ASTMatchers/ASTMatchers.h"
14
15 using namespace clang::ast_matchers;
16
17 namespace clang::tidy::cppcoreguidelines {
18
19 void SlicingCheck::registerMatchers(MatchFinder *Finder) {
20 // When we see:
21 // class B : public A { ... };
22 // A a;
23 // B b;
24 // a = b;
25 // The assignment is OK if:
26 // - the assignment operator is defined as taking a B as second parameter,
27 // or
28 // - B does not define any additional members (either variables or
29 // overrides) wrt A.
30 //
31 // The same holds for copy ctor calls. This also captures stuff like:
32 // void f(A a);
33 // f(b);
34
35 // Helpers.
36 const auto OfBaseClass = ofClass(cxxRecordDecl().bind("BaseDecl"));
37 const auto IsDerivedFromBaseDecl =
38 cxxRecordDecl(isDerivedFrom(equalsBoundNode("BaseDecl")))
39 .bind("DerivedDecl");
40 const auto HasTypeDerivedFromBaseDecl =
41 anyOf(hasType(IsDerivedFromBaseDecl),
42 hasType(references(IsDerivedFromBaseDecl)));
43 const auto IsWithinDerivedCtor =
44 hasParent(cxxConstructorDecl(ofClass(equalsBoundNode("DerivedDecl"))));
45
46 // Assignment slicing: "a = b;" and "a = std::move(b);" variants.
47 const auto SlicesObjectInAssignment =
48 callExpr(callee(cxxMethodDecl(anyOf(isCopyAssignmentOperator(),
49 isMoveAssignmentOperator()),
50 OfBaseClass)),
51 hasArgument(1, HasTypeDerivedFromBaseDecl));
52
53 // Construction slicing: "A a{b};" and "f(b);" variants. Note that in case of
54 // slicing the letter will create a temporary and therefore call a ctor.
55 const auto SlicesObjectInCtor = cxxConstructExpr(
56 hasDeclaration(cxxConstructorDecl(
57 anyOf(isCopyConstructor(), isMoveConstructor()), OfBaseClass)),
58 hasArgument(0, HasTypeDerivedFromBaseDecl),
59 // We need to disable matching on the call to the base copy/move
60 // constructor in DerivedDecl's constructors.
61 unless(IsWithinDerivedCtor));
62
63 Finder->addMatcher(traverse(TK_AsIs, expr(anyOf(SlicesObjectInAssignment,
64 SlicesObjectInCtor))
65 .bind("Call")),
66 this);
67 }
68
69 /// Warns on methods overridden in DerivedDecl with respect to BaseDecl.
70 /// FIXME: this warns on all overrides outside of the sliced path in case of
71 /// multiple inheritance.
72 void SlicingCheck::diagnoseSlicedOverriddenMethods(
73 const Expr &Call, const CXXRecordDecl &DerivedDecl,
74 const CXXRecordDecl &BaseDecl) {
75 if (DerivedDecl.getCanonicalDecl() == BaseDecl.getCanonicalDecl())
76 return;
77 for (const auto *Method : DerivedDecl.methods()) {
78 // Virtual destructors are OK. We're ignoring constructors since they are
79 // tagged as overrides.
80 if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method))
81 continue;
82 if (Method->size_overridden_methods() > 0) {
83 diag(Call.getExprLoc(),
84 "slicing object from type %0 to %1 discards override %2")
85 << &DerivedDecl << &BaseDecl << Method;
86 }
87 }
88 // Recursively process bases.
89 for (const auto &Base : DerivedDecl.bases()) {
90 if (const auto *BaseRecordType = Base.getType()->getAs<RecordType>()) {
91 if (const auto *BaseRecord = cast_or_null<CXXRecordDecl>(
92 BaseRecordType->getDecl()->getDefinition()))
93 diagnoseSlicedOverriddenMethods(Call, *BaseRecord, BaseDecl);
94 }
95 }
96 }
97
98 void SlicingCheck::check(const MatchFinder::MatchResult &Result) {
99 const auto *BaseDecl = Result.Nodes.getNodeAs<CXXRecordDecl>("BaseDecl");
100 const auto *DerivedDecl =
101 Result.Nodes.getNodeAs<CXXRecordDecl>("DerivedDecl");
102 const auto *Call = Result.Nodes.getNodeAs<Expr>("Call");
103 assert(BaseDecl != nullptr);
104 assert(DerivedDecl != nullptr);
105 assert(Call != nullptr);
106
107 // Warn when slicing the vtable.
108 // We're looking through all the methods in the derived class and see if they
109 // override some methods in the base class.
110 // It's not enough to just test whether the class is polymorphic because we
111 // would be fine slicing B to A if no method in B (or its bases) overrides
112 // anything in A:
113 // class A { virtual void f(); };
114 // class B : public A {};
115 // because in that case calling A::f is the same as calling B::f.
116 diagnoseSlicedOverriddenMethods(*Call, *DerivedDecl, *BaseDecl);
117
118 // Warn when slicing member variables.
119 const auto &BaseLayout =
120 BaseDecl->getASTContext().getASTRecordLayout(BaseDecl);
121 const auto &DerivedLayout =
122 DerivedDecl->getASTContext().getASTRecordLayout(DerivedDecl);
123 const CharUnits StateSize =
124 DerivedLayout.getDataSize() - BaseLayout.getDataSize();
125 if (StateSize.isPositive()) {
126 diag(Call->getExprLoc(), "slicing object from type %0 to %1 discards "
127 "%2 bytes of state")
128 << DerivedDecl << BaseDecl << static_cast<int>(StateSize.getQuantity());
129 }
130 }
131
132 } // namespace clang::tidy::cppcoreguidelines