1//===--- NewDeleteOverloadsCheck.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 "NewDeleteOverloadsCheck.h"
10#include "clang/AST/ASTContext.h"
11#include "clang/ASTMatchers/ASTMatchFinder.h"
12
13using namespace clang::ast_matchers;
14
15namespace clang::tidy::misc {
16
17namespace {
18
19AST_MATCHER(FunctionDecl, isPlacementOverload) {
20 bool New = false;
21 switch (Node.getOverloadedOperator()) {
22 default:
23 return false;
24 case OO_New:
25 case OO_Array_New:
26 New = true;
27 break;
28 case OO_Delete:
29 case OO_Array_Delete:
30 New = false;
31 break;
32 }
33
34 // Variadic functions are always placement functions.
35 if (Node.isVariadic())
36 return true;
37
38 // Placement new is easy: it always has more than one parameter (the first
39 // parameter is always the size). If it's an overload of delete or delete[]
40 // that has only one parameter, it's never a placement delete.
41 if (New)
42 return Node.getNumParams() > 1;
43 if (Node.getNumParams() == 1)
44 return false;
45
46 // Placement delete is a little more challenging. They always have more than
47 // one parameter with the first parameter being a pointer. However, the
48 // second parameter can be a size_t for sized deallocation, and that is never
49 // a placement delete operator.
50 if (Node.getNumParams() <= 1 || Node.getNumParams() > 2)
51 return true;
52
53 const auto *FPT = Node.getType()->castAs<FunctionProtoType>();
54 ASTContext &Ctx = Node.getASTContext();
55 if (Ctx.getLangOpts().SizedDeallocation &&
56 Ctx.hasSameType(FPT->getParamType(1), Ctx.getSizeType()))
57 return false;
58
59 return true;
60}
61
62OverloadedOperatorKind getCorrespondingOverload(const FunctionDecl *FD) {
63 switch (FD->getOverloadedOperator()) {
64 default:
65 break;
66 case OO_New:
67 return OO_Delete;
68 case OO_Delete:
69 return OO_New;
70 case OO_Array_New:
71 return OO_Array_Delete;
72 case OO_Array_Delete:
73 return OO_Array_New;
74 }
75 llvm_unreachable("Not an overloaded allocation operator");
76}
77
78const char *getOperatorName(OverloadedOperatorKind K) {
79 switch (K) {
80 default:
81 break;
82 case OO_New:
83 return "operator new";
84 case OO_Delete:
85 return "operator delete";
86 case OO_Array_New:
87 return "operator new[]";
88 case OO_Array_Delete:
89 return "operator delete[]";
90 }
91 llvm_unreachable("Not an overloaded allocation operator");
92}
93
94bool areCorrespondingOverloads(const FunctionDecl *LHS,
95 const FunctionDecl *RHS) {
96 return RHS->getOverloadedOperator() == getCorrespondingOverload(FD: LHS);
97}
98
99bool hasCorrespondingOverloadInBaseClass(const CXXMethodDecl *MD,
100 const CXXRecordDecl *RD = nullptr) {
101 if (RD) {
102 // Check the methods in the given class and accessible to derived classes.
103 for (const auto *BMD : RD->methods())
104 if (BMD->isOverloadedOperator() && BMD->getAccess() != AS_private &&
105 areCorrespondingOverloads(MD, BMD))
106 return true;
107 } else {
108 // Get the parent class of the method; we do not need to care about checking
109 // the methods in this class as the caller has already done that by looking
110 // at the declaration contexts.
111 RD = MD->getParent();
112 }
113
114 for (const auto &BS : RD->bases()) {
115 // We can't say much about a dependent base class, but to avoid false
116 // positives assume it can have a corresponding overload.
117 if (BS.getType()->isDependentType())
118 return true;
119 if (const auto *BaseRD = BS.getType()->getAsCXXRecordDecl())
120 if (hasCorrespondingOverloadInBaseClass(MD, RD: BaseRD))
121 return true;
122 }
123
124 return false;
125}
126
127} // anonymous namespace
128
129void NewDeleteOverloadsCheck::registerMatchers(MatchFinder *Finder) {
130 // Match all operator new and operator delete overloads (including the array
131 // forms). Do not match implicit operators, placement operators, or
132 // deleted/private operators.
133 //
134 // Technically, trivially-defined operator delete seems like a reasonable
135 // thing to also skip. e.g., void operator delete(void *) {}
136 // However, I think it's more reasonable to warn in this case as the user
137 // should really be writing that as a deleted function.
138 Finder->addMatcher(
139 NodeMatch: functionDecl(unless(anyOf(isImplicit(), isPlacementOverload(),
140 isDeleted(), cxxMethodDecl(isPrivate()))),
141 anyOf(hasOverloadedOperatorName(Name: "new"),
142 hasOverloadedOperatorName(Name: "new[]"),
143 hasOverloadedOperatorName(Name: "delete"),
144 hasOverloadedOperatorName(Name: "delete[]")))
145 .bind(ID: "func"),
146 Action: this);
147}
148
149void NewDeleteOverloadsCheck::check(const MatchFinder::MatchResult &Result) {
150 // Add any matches we locate to the list of things to be checked at the
151 // end of the translation unit.
152 const auto *FD = Result.Nodes.getNodeAs<FunctionDecl>(ID: "func");
153 const CXXRecordDecl *RD = nullptr;
154 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD))
155 RD = MD->getParent();
156 Overloads[RD].push_back(Elt: FD);
157}
158
159void NewDeleteOverloadsCheck::onEndOfTranslationUnit() {
160 // Walk over the list of declarations we've found to see if there is a
161 // corresponding overload at the same declaration context or within a base
162 // class. If there is not, add the element to the list of declarations to
163 // diagnose.
164 SmallVector<const FunctionDecl *, 4> Diagnose;
165 for (const auto &RP : Overloads) {
166 // We don't care about the CXXRecordDecl key in the map; we use it as a way
167 // to shard the overloads by declaration context to reduce the algorithmic
168 // complexity when searching for corresponding free store functions.
169 for (const auto *Overload : RP.second) {
170 const auto *Match =
171 std::find_if(first: RP.second.begin(), last: RP.second.end(),
172 pred: [&Overload](const FunctionDecl *FD) {
173 if (FD == Overload)
174 return false;
175 // If the declaration contexts don't match, we don't
176 // need to check any further.
177 if (FD->getDeclContext() != Overload->getDeclContext())
178 return false;
179
180 // Since the declaration contexts match, see whether
181 // the current element is the corresponding operator.
182 if (!areCorrespondingOverloads(LHS: Overload, RHS: FD))
183 return false;
184
185 return true;
186 });
187
188 if (Match == RP.second.end()) {
189 // Check to see if there is a corresponding overload in a base class
190 // context. If there isn't, or if the overload is not a class member
191 // function, then we should diagnose.
192 const auto *MD = dyn_cast<CXXMethodDecl>(Val: Overload);
193 if (!MD || !hasCorrespondingOverloadInBaseClass(MD))
194 Diagnose.push_back(Elt: Overload);
195 }
196 }
197 }
198
199 for (const auto *FD : Diagnose)
200 diag(FD->getLocation(), "declaration of %0 has no matching declaration "
201 "of '%1' at the same scope")
202 << FD << getOperatorName(K: getCorrespondingOverload(FD));
203}
204
205} // namespace clang::tidy::misc
206

source code of clang-tools-extra/clang-tidy/misc/NewDeleteOverloadsCheck.cpp