blob: 7e36b374fbaa6ff5c9898b9e3d53d1bc300f10f9 [file] [log] [blame]
Alexander Kornienkob959f4c2015-12-30 10:24:40 +00001//===--- UnnecessaryCopyInitialization.cpp - clang-tidy--------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Alexander Kornienkob959f4c2015-12-30 10:24:40 +00006//
7//===----------------------------------------------------------------------===//
8
9#include "UnnecessaryCopyInitialization.h"
10
Felix Bergeradfdc142016-03-05 21:17:58 +000011#include "../utils/DeclRefExprUtils.h"
12#include "../utils/FixItHintUtils.h"
Alexander Kornienkob959f4c2015-12-30 10:24:40 +000013#include "../utils/Matchers.h"
Adam Baloghabd72e92018-10-12 13:05:21 +000014#include "../utils/OptionsUtils.h"
Alexander Kornienkob959f4c2015-12-30 10:24:40 +000015
16namespace clang {
17namespace tidy {
18namespace performance {
Haojian Wu6ccb1dd2016-03-23 09:33:07 +000019namespace {
20
21void recordFixes(const VarDecl &Var, ASTContext &Context,
22 DiagnosticBuilder &Diagnostic) {
Etienne Bergeron2a4c00f2016-05-03 02:54:05 +000023 Diagnostic << utils::fixit::changeVarDeclToReference(Var, Context);
Haojian Wu6ccb1dd2016-03-23 09:33:07 +000024 if (!Var.getType().isLocalConstQualified())
Etienne Bergeron2a4c00f2016-05-03 02:54:05 +000025 Diagnostic << utils::fixit::changeVarDeclToConst(Var);
Haojian Wu6ccb1dd2016-03-23 09:33:07 +000026}
27
28} // namespace
29
Alexander Kornienkob959f4c2015-12-30 10:24:40 +000030using namespace ::clang::ast_matchers;
Etienne Bergeron2a4c00f2016-05-03 02:54:05 +000031using utils::decl_ref_expr::isOnlyUsedAsConst;
Alexander Kornienkob959f4c2015-12-30 10:24:40 +000032
Adam Baloghabd72e92018-10-12 13:05:21 +000033UnnecessaryCopyInitialization::UnnecessaryCopyInitialization(
34 StringRef Name, ClangTidyContext *Context)
35 : ClangTidyCheck(Name, Context),
36 AllowedTypes(
37 utils::options::parseStringList(Options.get("AllowedTypes", ""))) {}
38
Haojian Wu6ccb1dd2016-03-23 09:33:07 +000039void UnnecessaryCopyInitialization::registerMatchers(MatchFinder *Finder) {
Alexander Kornienkob959f4c2015-12-30 10:24:40 +000040 auto ConstReference = referenceType(pointee(qualType(isConstQualified())));
Haojian Wu6ccb1dd2016-03-23 09:33:07 +000041
Felix Berger98e40192016-05-31 00:25:57 +000042 // Match method call expressions where the `this` argument is only used as
43 // const, this will be checked in `check()` part. This returned const
44 // reference is highly likely to outlive the local const reference of the
45 // variable being declared. The assumption is that the const reference being
46 // returned either points to a global static variable or to a member of the
47 // called object.
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000048 auto ConstRefReturningMethodCall =
49 cxxMemberCallExpr(callee(cxxMethodDecl(returns(ConstReference))),
50 on(declRefExpr(to(varDecl().bind("objectArg")))));
Alexander Kornienkob959f4c2015-12-30 10:24:40 +000051 auto ConstRefReturningFunctionCall =
52 callExpr(callee(functionDecl(returns(ConstReference))),
53 unless(callee(cxxMethodDecl())));
Haojian Wu6ccb1dd2016-03-23 09:33:07 +000054
Adam Baloghabd72e92018-10-12 13:05:21 +000055 auto localVarCopiedFrom = [this](const internal::Matcher<Expr> &CopyCtorArg) {
Haojian Wu6ccb1dd2016-03-23 09:33:07 +000056 return compoundStmt(
57 forEachDescendant(
Felix Berger6d3d7462016-05-13 02:47:56 +000058 declStmt(
59 has(varDecl(hasLocalStorage(),
Adam Baloghabd72e92018-10-12 13:05:21 +000060 hasType(qualType(
Alexander Kornienko976e0c02018-11-25 02:41:01 +000061 hasCanonicalType(
62 matchers::isExpensiveToCopy()),
63 unless(hasDeclaration(namedDecl(
64 matchers::matchesAnyListedName(
65 AllowedTypes)))))),
Haojian Wu06e39a32016-11-08 00:45:34 +000066 unless(isImplicit()),
Felix Berger6d3d7462016-05-13 02:47:56 +000067 hasInitializer(
68 cxxConstructExpr(
69 hasDeclaration(cxxConstructorDecl(
70 isCopyConstructor())),
71 hasArgument(0, CopyCtorArg))
72 .bind("ctorCall")))
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000073 .bind("newVarDecl")))
74 .bind("declStmt")))
Haojian Wu6ccb1dd2016-03-23 09:33:07 +000075 .bind("blockStmt");
76 };
77
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000078 Finder->addMatcher(localVarCopiedFrom(anyOf(ConstRefReturningFunctionCall,
79 ConstRefReturningMethodCall)),
80 this);
Haojian Wu6ccb1dd2016-03-23 09:33:07 +000081
82 Finder->addMatcher(localVarCopiedFrom(declRefExpr(
83 to(varDecl(hasLocalStorage()).bind("oldVarDecl")))),
84 this);
Alexander Kornienkob959f4c2015-12-30 10:24:40 +000085}
86
87void UnnecessaryCopyInitialization::check(
Haojian Wu6ccb1dd2016-03-23 09:33:07 +000088 const MatchFinder::MatchResult &Result) {
89 const auto *NewVar = Result.Nodes.getNodeAs<VarDecl>("newVarDecl");
90 const auto *OldVar = Result.Nodes.getNodeAs<VarDecl>("oldVarDecl");
Felix Berger98e40192016-05-31 00:25:57 +000091 const auto *ObjectArg = Result.Nodes.getNodeAs<VarDecl>("objectArg");
Felix Bergeradfdc142016-03-05 21:17:58 +000092 const auto *BlockStmt = Result.Nodes.getNodeAs<Stmt>("blockStmt");
Haojian Wu6ccb1dd2016-03-23 09:33:07 +000093 const auto *CtorCall = Result.Nodes.getNodeAs<CXXConstructExpr>("ctorCall");
Adam Baloghabd72e92018-10-12 13:05:21 +000094
Felix Berger6d3d7462016-05-13 02:47:56 +000095 // Do not propose fixes if the DeclStmt has multiple VarDecls or in macros
96 // since we cannot place them correctly.
97 bool IssueFix =
98 Result.Nodes.getNodeAs<DeclStmt>("declStmt")->isSingleDecl() &&
99 !NewVar->getLocation().isMacroID();
Haojian Wu6ccb1dd2016-03-23 09:33:07 +0000100
101 // A constructor that looks like T(const T& t, bool arg = false) counts as a
102 // copy only when it is called with default arguments for the arguments after
103 // the first.
104 for (unsigned int i = 1; i < CtorCall->getNumArgs(); ++i)
105 if (!CtorCall->getArg(i)->isDefaultArgument())
106 return;
107
108 if (OldVar == nullptr) {
Felix Berger98e40192016-05-31 00:25:57 +0000109 handleCopyFromMethodReturn(*NewVar, *BlockStmt, IssueFix, ObjectArg,
110 *Result.Context);
Haojian Wu6ccb1dd2016-03-23 09:33:07 +0000111 } else {
Felix Berger6d3d7462016-05-13 02:47:56 +0000112 handleCopyFromLocalVar(*NewVar, *OldVar, *BlockStmt, IssueFix,
113 *Result.Context);
Haojian Wu6ccb1dd2016-03-23 09:33:07 +0000114 }
115}
116
117void UnnecessaryCopyInitialization::handleCopyFromMethodReturn(
Felix Berger6d3d7462016-05-13 02:47:56 +0000118 const VarDecl &Var, const Stmt &BlockStmt, bool IssueFix,
Felix Berger98e40192016-05-31 00:25:57 +0000119 const VarDecl *ObjectArg, ASTContext &Context) {
Haojian Wu6ccb1dd2016-03-23 09:33:07 +0000120 bool IsConstQualified = Var.getType().isConstQualified();
121 if (!IsConstQualified && !isOnlyUsedAsConst(Var, BlockStmt, Context))
Felix Bergeradfdc142016-03-05 21:17:58 +0000122 return;
Felix Berger98e40192016-05-31 00:25:57 +0000123 if (ObjectArg != nullptr &&
124 !isOnlyUsedAsConst(*ObjectArg, BlockStmt, Context))
125 return;
Haojian Wu6ccb1dd2016-03-23 09:33:07 +0000126
127 auto Diagnostic =
128 diag(Var.getLocation(),
129 IsConstQualified ? "the const qualified variable %0 is "
Felix Bergeradfdc142016-03-05 21:17:58 +0000130 "copy-constructed from a const reference; "
131 "consider making it a const reference"
Haojian Wu6ccb1dd2016-03-23 09:33:07 +0000132 : "the variable %0 is copy-constructed from a "
Felix Bergeradfdc142016-03-05 21:17:58 +0000133 "const reference but is only used as const "
134 "reference; consider making it a const reference")
Haojian Wu6ccb1dd2016-03-23 09:33:07 +0000135 << &Var;
Felix Berger6d3d7462016-05-13 02:47:56 +0000136 if (IssueFix)
137 recordFixes(Var, Context, Diagnostic);
Haojian Wu6ccb1dd2016-03-23 09:33:07 +0000138}
139
140void UnnecessaryCopyInitialization::handleCopyFromLocalVar(
141 const VarDecl &NewVar, const VarDecl &OldVar, const Stmt &BlockStmt,
Felix Berger6d3d7462016-05-13 02:47:56 +0000142 bool IssueFix, ASTContext &Context) {
Haojian Wu6ccb1dd2016-03-23 09:33:07 +0000143 if (!isOnlyUsedAsConst(NewVar, BlockStmt, Context) ||
144 !isOnlyUsedAsConst(OldVar, BlockStmt, Context))
Felix Bergeradfdc142016-03-05 21:17:58 +0000145 return;
Haojian Wu6ccb1dd2016-03-23 09:33:07 +0000146
147 auto Diagnostic = diag(NewVar.getLocation(),
148 "local copy %0 of the variable %1 is never modified; "
149 "consider avoiding the copy")
150 << &NewVar << &OldVar;
Felix Berger6d3d7462016-05-13 02:47:56 +0000151 if (IssueFix)
152 recordFixes(NewVar, Context, Diagnostic);
Alexander Kornienkob959f4c2015-12-30 10:24:40 +0000153}
154
Adam Baloghabd72e92018-10-12 13:05:21 +0000155void UnnecessaryCopyInitialization::storeOptions(
156 ClangTidyOptions::OptionMap &Opts) {
157 Options.store(Opts, "AllowedTypes",
158 utils::options::serializeStringList(AllowedTypes));
159}
160
Alexander Kornienkob959f4c2015-12-30 10:24:40 +0000161} // namespace performance
162} // namespace tidy
163} // namespace clang