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