1 //===--- UnnecessaryCopyInitialization.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 "UnnecessaryCopyInitialization.h"
10
11 #include "../utils/DeclRefExprUtils.h"
12 #include "../utils/FixItHintUtils.h"
13 #include "../utils/Matchers.h"
14 #include "../utils/OptionsUtils.h"
15 #include "clang/Basic/Diagnostic.h"
16
17 namespace clang {
18 namespace tidy {
19 namespace performance {
20 namespace {
21
recordFixes(const VarDecl & Var,ASTContext & Context,DiagnosticBuilder & Diagnostic)22 void recordFixes(const VarDecl &Var, ASTContext &Context,
23 DiagnosticBuilder &Diagnostic) {
24 Diagnostic << utils::fixit::changeVarDeclToReference(Var, Context);
25 if (!Var.getType().isLocalConstQualified()) {
26 if (llvm::Optional<FixItHint> Fix = utils::fixit::addQualifierToVarDecl(
27 Var, Context, DeclSpec::TQ::TQ_const))
28 Diagnostic << *Fix;
29 }
30 }
31
32 } // namespace
33
34 using namespace ::clang::ast_matchers;
35 using utils::decl_ref_expr::isOnlyUsedAsConst;
36
UnnecessaryCopyInitialization(StringRef Name,ClangTidyContext * Context)37 UnnecessaryCopyInitialization::UnnecessaryCopyInitialization(
38 StringRef Name, ClangTidyContext *Context)
39 : ClangTidyCheck(Name, Context),
40 AllowedTypes(
41 utils::options::parseStringList(Options.get("AllowedTypes", ""))) {}
42
registerMatchers(MatchFinder * Finder)43 void UnnecessaryCopyInitialization::registerMatchers(MatchFinder *Finder) {
44 auto ConstReference = referenceType(pointee(qualType(isConstQualified())));
45
46 // Match method call expressions where the `this` argument is only used as
47 // const, this will be checked in `check()` part. This returned const
48 // reference is highly likely to outlive the local const reference of the
49 // variable being declared. The assumption is that the const reference being
50 // returned either points to a global static variable or to a member of the
51 // called object.
52 auto ConstRefReturningMethodCall =
53 cxxMemberCallExpr(callee(cxxMethodDecl(returns(ConstReference))),
54 on(declRefExpr(to(varDecl().bind("objectArg")))));
55 auto ConstRefReturningFunctionCall =
56 callExpr(callee(functionDecl(returns(ConstReference))),
57 unless(callee(cxxMethodDecl())))
58 .bind("initFunctionCall");
59
60 auto localVarCopiedFrom = [this](const internal::Matcher<Expr> &CopyCtorArg) {
61 return compoundStmt(
62 forEachDescendant(
63 declStmt(
64 has(varDecl(hasLocalStorage(),
65 hasType(qualType(
66 hasCanonicalType(allOf(
67 matchers::isExpensiveToCopy(),
68 unless(hasDeclaration(namedDecl(
69 hasName("::std::function")))))),
70 unless(hasDeclaration(namedDecl(
71 matchers::matchesAnyListedName(
72 AllowedTypes)))))),
73 unless(isImplicit()),
74 hasInitializer(traverse(
75 ast_type_traits::TK_AsIs,
76 cxxConstructExpr(
77 hasDeclaration(cxxConstructorDecl(
78 isCopyConstructor())),
79 hasArgument(0, CopyCtorArg))
80 .bind("ctorCall"))))
81 .bind("newVarDecl")))
82 .bind("declStmt")))
83 .bind("blockStmt");
84 };
85
86 Finder->addMatcher(localVarCopiedFrom(anyOf(ConstRefReturningFunctionCall,
87 ConstRefReturningMethodCall)),
88 this);
89
90 Finder->addMatcher(localVarCopiedFrom(declRefExpr(
91 to(varDecl(hasLocalStorage()).bind("oldVarDecl")))),
92 this);
93 }
94
check(const MatchFinder::MatchResult & Result)95 void UnnecessaryCopyInitialization::check(
96 const MatchFinder::MatchResult &Result) {
97 const auto *NewVar = Result.Nodes.getNodeAs<VarDecl>("newVarDecl");
98 const auto *OldVar = Result.Nodes.getNodeAs<VarDecl>("oldVarDecl");
99 const auto *ObjectArg = Result.Nodes.getNodeAs<VarDecl>("objectArg");
100 const auto *BlockStmt = Result.Nodes.getNodeAs<Stmt>("blockStmt");
101 const auto *CtorCall = Result.Nodes.getNodeAs<CXXConstructExpr>("ctorCall");
102 const auto *InitFunctionCall =
103 Result.Nodes.getNodeAs<CallExpr>("initFunctionCall");
104
105 TraversalKindScope RAII(*Result.Context, ast_type_traits::TK_AsIs);
106
107 // Do not propose fixes if the DeclStmt has multiple VarDecls or in macros
108 // since we cannot place them correctly.
109 bool IssueFix =
110 Result.Nodes.getNodeAs<DeclStmt>("declStmt")->isSingleDecl() &&
111 !NewVar->getLocation().isMacroID();
112
113 // A constructor that looks like T(const T& t, bool arg = false) counts as a
114 // copy only when it is called with default arguments for the arguments after
115 // the first.
116 for (unsigned int i = 1; i < CtorCall->getNumArgs(); ++i)
117 if (!CtorCall->getArg(i)->isDefaultArgument())
118 return;
119
120 if (OldVar == nullptr) {
121 // Only allow initialization of a const reference from a free function if it
122 // has no arguments. Otherwise it could return an alias to one of its
123 // arguments and the arguments need to be checked for const use as well.
124 if (InitFunctionCall != nullptr && InitFunctionCall->getNumArgs() > 0)
125 return;
126 handleCopyFromMethodReturn(*NewVar, *BlockStmt, IssueFix, ObjectArg,
127 *Result.Context);
128 } else {
129 handleCopyFromLocalVar(*NewVar, *OldVar, *BlockStmt, IssueFix,
130 *Result.Context);
131 }
132 }
133
handleCopyFromMethodReturn(const VarDecl & Var,const Stmt & BlockStmt,bool IssueFix,const VarDecl * ObjectArg,ASTContext & Context)134 void UnnecessaryCopyInitialization::handleCopyFromMethodReturn(
135 const VarDecl &Var, const Stmt &BlockStmt, bool IssueFix,
136 const VarDecl *ObjectArg, ASTContext &Context) {
137 bool IsConstQualified = Var.getType().isConstQualified();
138 if (!IsConstQualified && !isOnlyUsedAsConst(Var, BlockStmt, Context))
139 return;
140 if (ObjectArg != nullptr &&
141 !isOnlyUsedAsConst(*ObjectArg, BlockStmt, Context))
142 return;
143
144 auto Diagnostic =
145 diag(Var.getLocation(),
146 IsConstQualified ? "the const qualified variable %0 is "
147 "copy-constructed from a const reference; "
148 "consider making it a const reference"
149 : "the variable %0 is copy-constructed from a "
150 "const reference but is only used as const "
151 "reference; consider making it a const reference")
152 << &Var;
153 if (IssueFix)
154 recordFixes(Var, Context, Diagnostic);
155 }
156
handleCopyFromLocalVar(const VarDecl & NewVar,const VarDecl & OldVar,const Stmt & BlockStmt,bool IssueFix,ASTContext & Context)157 void UnnecessaryCopyInitialization::handleCopyFromLocalVar(
158 const VarDecl &NewVar, const VarDecl &OldVar, const Stmt &BlockStmt,
159 bool IssueFix, ASTContext &Context) {
160 if (!isOnlyUsedAsConst(NewVar, BlockStmt, Context) ||
161 !isOnlyUsedAsConst(OldVar, BlockStmt, Context))
162 return;
163
164 auto Diagnostic = diag(NewVar.getLocation(),
165 "local copy %0 of the variable %1 is never modified; "
166 "consider avoiding the copy")
167 << &NewVar << &OldVar;
168 if (IssueFix)
169 recordFixes(NewVar, Context, Diagnostic);
170 }
171
storeOptions(ClangTidyOptions::OptionMap & Opts)172 void UnnecessaryCopyInitialization::storeOptions(
173 ClangTidyOptions::OptionMap &Opts) {
174 Options.store(Opts, "AllowedTypes",
175 utils::options::serializeStringList(AllowedTypes));
176 }
177
178 } // namespace performance
179 } // namespace tidy
180 } // namespace clang
181