clang-tools  10.0.0svn
NewDeleteOverloadsCheck.cpp
Go to the documentation of this file.
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 
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 
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 
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 
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 
96 bool areCorrespondingOverloads(const FunctionDecl *LHS,
97  const FunctionDecl *RHS) {
98  return RHS->getOverloadedOperator() == getCorrespondingOverload(LHS);
99 }
100 
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 
131 void NewDeleteOverloadsCheck::registerMatchers(MatchFinder *Finder) {
132  if (!getLangOpts().CPlusPlus)
133  return;
134 
135  // Match all operator new and operator delete overloads (including the array
136  // forms). Do not match implicit operators, placement operators, or
137  // deleted/private operators.
138  //
139  // Technically, trivially-defined operator delete seems like a reasonable
140  // thing to also skip. e.g., void operator delete(void *) {}
141  // However, I think it's more reasonable to warn in this case as the user
142  // should really be writing that as a deleted function.
143  Finder->addMatcher(
144  functionDecl(unless(anyOf(isImplicit(), isPlacementOverload(),
145  isDeleted(), cxxMethodDecl(isPrivate()))),
146  anyOf(hasOverloadedOperatorName("new"),
147  hasOverloadedOperatorName("new[]"),
148  hasOverloadedOperatorName("delete"),
149  hasOverloadedOperatorName("delete[]")))
150  .bind("func"),
151  this);
152 }
153 
154 void NewDeleteOverloadsCheck::check(const MatchFinder::MatchResult &Result) {
155  // Add any matches we locate to the list of things to be checked at the
156  // end of the translation unit.
157  const auto *FD = Result.Nodes.getNodeAs<FunctionDecl>("func");
158  const CXXRecordDecl *RD = nullptr;
159  if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
160  RD = MD->getParent();
161  Overloads[RD].push_back(FD);
162 }
163 
164 void NewDeleteOverloadsCheck::onEndOfTranslationUnit() {
165  // Walk over the list of declarations we've found to see if there is a
166  // corresponding overload at the same declaration context or within a base
167  // class. If there is not, add the element to the list of declarations to
168  // diagnose.
169  SmallVector<const FunctionDecl *, 4> Diagnose;
170  for (const auto &RP : Overloads) {
171  // We don't care about the CXXRecordDecl key in the map; we use it as a way
172  // to shard the overloads by declaration context to reduce the algorithmic
173  // complexity when searching for corresponding free store functions.
174  for (const auto *Overload : RP.second) {
175  const auto *Match =
176  std::find_if(RP.second.begin(), RP.second.end(),
177  [&Overload](const FunctionDecl *FD) {
178  if (FD == Overload)
179  return false;
180  // If the declaration contexts don't match, we don't
181  // need to check any further.
182  if (FD->getDeclContext() != Overload->getDeclContext())
183  return false;
184 
185  // Since the declaration contexts match, see whether
186  // the current element is the corresponding operator.
187  if (!areCorrespondingOverloads(Overload, FD))
188  return false;
189 
190  return true;
191  });
192 
193  if (Match == RP.second.end()) {
194  // Check to see if there is a corresponding overload in a base class
195  // context. If there isn't, or if the overload is not a class member
196  // function, then we should diagnose.
197  const auto *MD = dyn_cast<CXXMethodDecl>(Overload);
198  if (!MD || !hasCorrespondingOverloadInBaseClass(MD))
199  Diagnose.push_back(Overload);
200  }
201  }
202  }
203 
204  for (const auto *FD : Diagnose)
205  diag(FD->getLocation(), "declaration of %0 has no matching declaration "
206  "of '%1' at the same scope")
207  << FD << getOperatorName(getCorrespondingOverload(FD));
208 }
209 
210 } // namespace misc
211 } // namespace tidy
212 } // namespace clang
Context Ctx
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
static GeneratorRegistry::Add< MDGenerator > MD(MDGenerator::Format, "Generator for MD output.")