blob: 6f31057395cce921f99a539aa9a33986f6060890 [file] [log] [blame]
Alexander Kornienkob959f4c2015-12-30 10:24:40 +00001//===--- UnnecessaryCopyInitialization.cpp - clang-tidy--------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "UnnecessaryCopyInitialization.h"
11
Felix Bergeradfdc142016-03-05 21:17:58 +000012#include "../utils/DeclRefExprUtils.h"
13#include "../utils/FixItHintUtils.h"
Alexander Kornienkob959f4c2015-12-30 10:24:40 +000014#include "../utils/Matchers.h"
Adam Baloghabd72e92018-10-12 13:05:21 +000015#include "../utils/OptionsUtils.h"
Alexander Kornienkob959f4c2015-12-30 10:24:40 +000016
17namespace clang {
18namespace tidy {
19namespace performance {
Haojian Wu6ccb1dd2016-03-23 09:33:07 +000020namespace {
21
22void recordFixes(const VarDecl &Var, ASTContext &Context,
23 DiagnosticBuilder &Diagnostic) {
Etienne Bergeron2a4c00f2016-05-03 02:54:05 +000024 Diagnostic << utils::fixit::changeVarDeclToReference(Var, Context);
Haojian Wu6ccb1dd2016-03-23 09:33:07 +000025 if (!Var.getType().isLocalConstQualified())
Etienne Bergeron2a4c00f2016-05-03 02:54:05 +000026 Diagnostic << utils::fixit::changeVarDeclToConst(Var);
Haojian Wu6ccb1dd2016-03-23 09:33:07 +000027}
28
29} // namespace
30
Alexander Kornienkob959f4c2015-12-30 10:24:40 +000031using namespace ::clang::ast_matchers;
Etienne Bergeron2a4c00f2016-05-03 02:54:05 +000032using utils::decl_ref_expr::isOnlyUsedAsConst;
Alexander Kornienkob959f4c2015-12-30 10:24:40 +000033
Adam Baloghabd72e92018-10-12 13:05:21 +000034UnnecessaryCopyInitialization::UnnecessaryCopyInitialization(
35 StringRef Name, ClangTidyContext *Context)
36 : ClangTidyCheck(Name, Context),
37 AllowedTypes(
38 utils::options::parseStringList(Options.get("AllowedTypes", ""))) {}
39
Haojian Wu6ccb1dd2016-03-23 09:33:07 +000040void UnnecessaryCopyInitialization::registerMatchers(MatchFinder *Finder) {
Alexander Kornienkob959f4c2015-12-30 10:24:40 +000041 auto ConstReference = referenceType(pointee(qualType(isConstQualified())));
Haojian Wu6ccb1dd2016-03-23 09:33:07 +000042
Felix Berger98e40192016-05-31 00:25:57 +000043 // Match method call expressions where the `this` argument is only used as
44 // const, this will be checked in `check()` part. This returned const
45 // reference is highly likely to outlive the local const reference of the
46 // variable being declared. The assumption is that the const reference being
47 // returned either points to a global static variable or to a member of the
48 // called object.
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000049 auto ConstRefReturningMethodCall =
50 cxxMemberCallExpr(callee(cxxMethodDecl(returns(ConstReference))),
51 on(declRefExpr(to(varDecl().bind("objectArg")))));
Alexander Kornienkob959f4c2015-12-30 10:24:40 +000052 auto ConstRefReturningFunctionCall =
53 callExpr(callee(functionDecl(returns(ConstReference))),
54 unless(callee(cxxMethodDecl())));
Haojian Wu6ccb1dd2016-03-23 09:33:07 +000055
Adam Baloghabd72e92018-10-12 13:05:21 +000056 auto localVarCopiedFrom = [this](const internal::Matcher<Expr> &CopyCtorArg) {
Haojian Wu6ccb1dd2016-03-23 09:33:07 +000057 return compoundStmt(
58 forEachDescendant(
Felix Berger6d3d7462016-05-13 02:47:56 +000059 declStmt(
60 has(varDecl(hasLocalStorage(),
Adam Baloghabd72e92018-10-12 13:05:21 +000061 hasType(qualType(
Alexander Kornienko976e0c02018-11-25 02:41:01 +000062 hasCanonicalType(
63 matchers::isExpensiveToCopy()),
64 unless(hasDeclaration(namedDecl(
65 matchers::matchesAnyListedName(
66 AllowedTypes)))))),
Haojian Wu06e39a32016-11-08 00:45:34 +000067 unless(isImplicit()),
Felix Berger6d3d7462016-05-13 02:47:56 +000068 hasInitializer(
69 cxxConstructExpr(
70 hasDeclaration(cxxConstructorDecl(
71 isCopyConstructor())),
72 hasArgument(0, CopyCtorArg))
73 .bind("ctorCall")))
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000074 .bind("newVarDecl")))
75 .bind("declStmt")))
Haojian Wu6ccb1dd2016-03-23 09:33:07 +000076 .bind("blockStmt");
77 };
78
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000079 Finder->addMatcher(localVarCopiedFrom(anyOf(ConstRefReturningFunctionCall,
80 ConstRefReturningMethodCall)),
81 this);
Haojian Wu6ccb1dd2016-03-23 09:33:07 +000082
83 Finder->addMatcher(localVarCopiedFrom(declRefExpr(
84 to(varDecl(hasLocalStorage()).bind("oldVarDecl")))),
85 this);
Alexander Kornienkob959f4c2015-12-30 10:24:40 +000086}
87
88void UnnecessaryCopyInitialization::check(
Haojian Wu6ccb1dd2016-03-23 09:33:07 +000089 const MatchFinder::MatchResult &Result) {
90 const auto *NewVar = Result.Nodes.getNodeAs<VarDecl>("newVarDecl");
91 const auto *OldVar = Result.Nodes.getNodeAs<VarDecl>("oldVarDecl");
Felix Berger98e40192016-05-31 00:25:57 +000092 const auto *ObjectArg = Result.Nodes.getNodeAs<VarDecl>("objectArg");
Felix Bergeradfdc142016-03-05 21:17:58 +000093 const auto *BlockStmt = Result.Nodes.getNodeAs<Stmt>("blockStmt");
Haojian Wu6ccb1dd2016-03-23 09:33:07 +000094 const auto *CtorCall = Result.Nodes.getNodeAs<CXXConstructExpr>("ctorCall");
Adam Baloghabd72e92018-10-12 13:05:21 +000095
Felix Berger6d3d7462016-05-13 02:47:56 +000096 // Do not propose fixes if the DeclStmt has multiple VarDecls or in macros
97 // since we cannot place them correctly.
98 bool IssueFix =
99 Result.Nodes.getNodeAs<DeclStmt>("declStmt")->isSingleDecl() &&
100 !NewVar->getLocation().isMacroID();
Haojian Wu6ccb1dd2016-03-23 09:33:07 +0000101
102 // A constructor that looks like T(const T& t, bool arg = false) counts as a
103 // copy only when it is called with default arguments for the arguments after
104 // the first.
105 for (unsigned int i = 1; i < CtorCall->getNumArgs(); ++i)
106 if (!CtorCall->getArg(i)->isDefaultArgument())
107 return;
108
109 if (OldVar == nullptr) {
Felix Berger98e40192016-05-31 00:25:57 +0000110 handleCopyFromMethodReturn(*NewVar, *BlockStmt, IssueFix, ObjectArg,
111 *Result.Context);
Haojian Wu6ccb1dd2016-03-23 09:33:07 +0000112 } else {
Felix Berger6d3d7462016-05-13 02:47:56 +0000113 handleCopyFromLocalVar(*NewVar, *OldVar, *BlockStmt, IssueFix,
114 *Result.Context);
Haojian Wu6ccb1dd2016-03-23 09:33:07 +0000115 }
116}
117
118void UnnecessaryCopyInitialization::handleCopyFromMethodReturn(
Felix Berger6d3d7462016-05-13 02:47:56 +0000119 const VarDecl &Var, const Stmt &BlockStmt, bool IssueFix,
Felix Berger98e40192016-05-31 00:25:57 +0000120 const VarDecl *ObjectArg, ASTContext &Context) {
Haojian Wu6ccb1dd2016-03-23 09:33:07 +0000121 bool IsConstQualified = Var.getType().isConstQualified();
122 if (!IsConstQualified && !isOnlyUsedAsConst(Var, BlockStmt, Context))
Felix Bergeradfdc142016-03-05 21:17:58 +0000123 return;
Felix Berger98e40192016-05-31 00:25:57 +0000124 if (ObjectArg != nullptr &&
125 !isOnlyUsedAsConst(*ObjectArg, BlockStmt, Context))
126 return;
Haojian Wu6ccb1dd2016-03-23 09:33:07 +0000127
128 auto Diagnostic =
129 diag(Var.getLocation(),
130 IsConstQualified ? "the const qualified variable %0 is "
Felix Bergeradfdc142016-03-05 21:17:58 +0000131 "copy-constructed from a const reference; "
132 "consider making it a const reference"
Haojian Wu6ccb1dd2016-03-23 09:33:07 +0000133 : "the variable %0 is copy-constructed from a "
Felix Bergeradfdc142016-03-05 21:17:58 +0000134 "const reference but is only used as const "
135 "reference; consider making it a const reference")
Haojian Wu6ccb1dd2016-03-23 09:33:07 +0000136 << &Var;
Felix Berger6d3d7462016-05-13 02:47:56 +0000137 if (IssueFix)
138 recordFixes(Var, Context, Diagnostic);
Haojian Wu6ccb1dd2016-03-23 09:33:07 +0000139}
140
141void UnnecessaryCopyInitialization::handleCopyFromLocalVar(
142 const VarDecl &NewVar, const VarDecl &OldVar, const Stmt &BlockStmt,
Felix Berger6d3d7462016-05-13 02:47:56 +0000143 bool IssueFix, ASTContext &Context) {
Haojian Wu6ccb1dd2016-03-23 09:33:07 +0000144 if (!isOnlyUsedAsConst(NewVar, BlockStmt, Context) ||
145 !isOnlyUsedAsConst(OldVar, BlockStmt, Context))
Felix Bergeradfdc142016-03-05 21:17:58 +0000146 return;
Haojian Wu6ccb1dd2016-03-23 09:33:07 +0000147
148 auto Diagnostic = diag(NewVar.getLocation(),
149 "local copy %0 of the variable %1 is never modified; "
150 "consider avoiding the copy")
151 << &NewVar << &OldVar;
Felix Berger6d3d7462016-05-13 02:47:56 +0000152 if (IssueFix)
153 recordFixes(NewVar, Context, Diagnostic);
Alexander Kornienkob959f4c2015-12-30 10:24:40 +0000154}
155
Adam Baloghabd72e92018-10-12 13:05:21 +0000156void UnnecessaryCopyInitialization::storeOptions(
157 ClangTidyOptions::OptionMap &Opts) {
158 Options.store(Opts, "AllowedTypes",
159 utils::options::serializeStringList(AllowedTypes));
160}
161
Alexander Kornienkob959f4c2015-12-30 10:24:40 +0000162} // namespace performance
163} // namespace tidy
164} // namespace clang