blob: e277ad3419f72a9875a08971e0103eb6bd6067da [file] [log] [blame]
Felix Berger3c8edde2016-03-29 02:42:38 +00001//===--- UnnecessaryValueParamCheck.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 "UnnecessaryValueParamCheck.h"
11
12#include "../utils/DeclRefExprUtils.h"
13#include "../utils/FixItHintUtils.h"
14#include "../utils/Matchers.h"
Felix Berger7f882752016-07-01 20:12:15 +000015#include "../utils/TypeTraits.h"
16#include "clang/Frontend/CompilerInstance.h"
17#include "clang/Lex/Lexer.h"
18#include "clang/Lex/Preprocessor.h"
Felix Berger3c8edde2016-03-29 02:42:38 +000019
20using namespace clang::ast_matchers;
21
22namespace clang {
23namespace tidy {
24namespace performance {
25
26namespace {
27
28std::string paramNameOrIndex(StringRef Name, size_t Index) {
29 return (Name.empty() ? llvm::Twine('#') + llvm::Twine(Index + 1)
30 : llvm::Twine('\'') + Name + llvm::Twine('\''))
31 .str();
32}
33
Felix Berger7f882752016-07-01 20:12:15 +000034template <typename S>
35bool isSubset(const S &SubsetCandidate, const S &SupersetCandidate) {
36 for (const auto &E : SubsetCandidate)
37 if (SupersetCandidate.count(E) == 0)
38 return false;
39 return true;
40}
41
Felix Berger85f9e8b32016-11-10 01:28:22 +000042bool isReferencedOutsideOfCallExpr(const FunctionDecl &Function,
43 ASTContext &Context) {
44 auto Matches = match(declRefExpr(to(functionDecl(equalsNode(&Function))),
45 unless(hasAncestor(callExpr()))),
46 Context);
47 return !Matches.empty();
48}
49
Malcolm Parsonscfa7d372017-01-03 12:10:44 +000050bool hasLoopStmtAncestor(const DeclRefExpr &DeclRef, const Decl &Decl,
Felix Berger519de4b2016-12-16 02:47:56 +000051 ASTContext &Context) {
52 auto Matches =
Malcolm Parsonscfa7d372017-01-03 12:10:44 +000053 match(decl(forEachDescendant(declRefExpr(
Felix Berger519de4b2016-12-16 02:47:56 +000054 equalsNode(&DeclRef),
55 unless(hasAncestor(stmt(anyOf(forStmt(), cxxForRangeStmt(),
Malcolm Parsonscfa7d372017-01-03 12:10:44 +000056 whileStmt(), doStmt()))))))),
57 Decl, Context);
Felix Berger519de4b2016-12-16 02:47:56 +000058 return Matches.empty();
59}
60
Felix Berger603ea2d2017-07-26 00:45:41 +000061bool isExplicitTemplateSpecialization(const FunctionDecl &Function) {
62 if (const auto *SpecializationInfo = Function.getTemplateSpecializationInfo())
63 if (SpecializationInfo->getTemplateSpecializationKind() ==
64 TSK_ExplicitSpecialization)
65 return true;
66 if (const auto *Method = llvm::dyn_cast<CXXMethodDecl>(&Function))
67 if (Method->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
68 Method->getMemberSpecializationInfo()->isExplicitSpecialization())
69 return true;
70 return false;
71}
72
Felix Berger3c8edde2016-03-29 02:42:38 +000073} // namespace
74
Felix Berger7f882752016-07-01 20:12:15 +000075UnnecessaryValueParamCheck::UnnecessaryValueParamCheck(
76 StringRef Name, ClangTidyContext *Context)
77 : ClangTidyCheck(Name, Context),
78 IncludeStyle(utils::IncludeSorter::parseIncludeStyle(
Alexander Kornienkob1c74322017-07-20 12:02:03 +000079 Options.getLocalOrGlobal("IncludeStyle", "llvm"))) {}
Felix Berger7f882752016-07-01 20:12:15 +000080
Felix Berger3c8edde2016-03-29 02:42:38 +000081void UnnecessaryValueParamCheck::registerMatchers(MatchFinder *Finder) {
Ben Hamiltonb4ab4b62018-02-02 15:34:33 +000082 // This check is specific to C++ and doesn't apply to languages like
83 // Objective-C.
84 if (!getLangOpts().CPlusPlus)
85 return;
Felix Berger3c8edde2016-03-29 02:42:38 +000086 const auto ExpensiveValueParamDecl =
Alexander Kornienkob215d472017-05-16 17:28:17 +000087 parmVarDecl(hasType(hasCanonicalType(allOf(
88 unless(referenceType()), matchers::isExpensiveToCopy()))),
Felix Berger3c8edde2016-03-29 02:42:38 +000089 decl().bind("param"));
90 Finder->addMatcher(
Alexander Kornienkob215d472017-05-16 17:28:17 +000091 functionDecl(hasBody(stmt()), isDefinition(), unless(isImplicit()),
Felix Bergere4ab0602016-12-02 14:44:16 +000092 unless(cxxMethodDecl(anyOf(isOverride(), isFinal()))),
Felix Berger3c8edde2016-03-29 02:42:38 +000093 has(typeLoc(forEach(ExpensiveValueParamDecl))),
Alexander Kornienkob215d472017-05-16 17:28:17 +000094 unless(isInstantiated()), decl().bind("functionDecl")),
Felix Berger3c8edde2016-03-29 02:42:38 +000095 this);
96}
97
98void UnnecessaryValueParamCheck::check(const MatchFinder::MatchResult &Result) {
99 const auto *Param = Result.Nodes.getNodeAs<ParmVarDecl>("param");
100 const auto *Function = Result.Nodes.getNodeAs<FunctionDecl>("functionDecl");
101 const size_t Index = std::find(Function->parameters().begin(),
102 Function->parameters().end(), Param) -
103 Function->parameters().begin();
104 bool IsConstQualified =
105 Param->getType().getCanonicalType().isConstQualified();
106
Felix Berger7f882752016-07-01 20:12:15 +0000107 auto AllDeclRefExprs = utils::decl_ref_expr::allDeclRefExprs(
Malcolm Parsonscfa7d372017-01-03 12:10:44 +0000108 *Param, *Function, *Result.Context);
Felix Berger7f882752016-07-01 20:12:15 +0000109 auto ConstDeclRefExprs = utils::decl_ref_expr::constReferenceDeclRefExprs(
Malcolm Parsonscfa7d372017-01-03 12:10:44 +0000110 *Param, *Function, *Result.Context);
111
112 // Do not trigger on non-const value parameters when they are not only used as
113 // const.
Felix Berger7f882752016-07-01 20:12:15 +0000114 if (!isSubset(AllDeclRefExprs, ConstDeclRefExprs))
115 return;
116
117 // If the parameter is non-const, check if it has a move constructor and is
118 // only referenced once to copy-construct another object or whether it has a
119 // move assignment operator and is only referenced once when copy-assigned.
120 // In this case wrap DeclRefExpr with std::move() to avoid the unnecessary
121 // copy.
Malcolm Parsonscfa7d372017-01-03 12:10:44 +0000122 if (!IsConstQualified && AllDeclRefExprs.size() == 1) {
Felix Berger7f882752016-07-01 20:12:15 +0000123 auto CanonicalType = Param->getType().getCanonicalType();
Malcolm Parsonscfa7d372017-01-03 12:10:44 +0000124 const auto &DeclRefExpr = **AllDeclRefExprs.begin();
125
126 if (!hasLoopStmtAncestor(DeclRefExpr, *Function, *Result.Context) &&
Felix Berger7f882752016-07-01 20:12:15 +0000127 ((utils::type_traits::hasNonTrivialMoveConstructor(CanonicalType) &&
128 utils::decl_ref_expr::isCopyConstructorArgument(
Malcolm Parsonscfa7d372017-01-03 12:10:44 +0000129 DeclRefExpr, *Function, *Result.Context)) ||
Felix Berger7f882752016-07-01 20:12:15 +0000130 (utils::type_traits::hasNonTrivialMoveAssignment(CanonicalType) &&
131 utils::decl_ref_expr::isCopyAssignmentArgument(
Malcolm Parsonscfa7d372017-01-03 12:10:44 +0000132 DeclRefExpr, *Function, *Result.Context)))) {
133 handleMoveFix(*Param, DeclRefExpr, *Result.Context);
Felix Berger7f882752016-07-01 20:12:15 +0000134 return;
135 }
136 }
137
Felix Berger3c8edde2016-03-29 02:42:38 +0000138 auto Diag =
139 diag(Param->getLocation(),
140 IsConstQualified ? "the const qualified parameter %0 is "
141 "copied for each invocation; consider "
142 "making it a reference"
143 : "the parameter %0 is copied for each "
144 "invocation but only used as a const reference; "
145 "consider making it a const reference")
146 << paramNameOrIndex(Param->getName(), Index);
Felix Berger85f9e8b32016-11-10 01:28:22 +0000147 // Do not propose fixes when:
148 // 1. the ParmVarDecl is in a macro, since we cannot place them correctly
149 // 2. the function is virtual as it might break overrides
150 // 3. the function is referenced outside of a call expression within the
151 // compilation unit as the signature change could introduce build errors.
Felix Berger603ea2d2017-07-26 00:45:41 +0000152 // 4. the function is an explicit template specialization.
Felix Berger17934da2016-07-05 14:40:44 +0000153 const auto *Method = llvm::dyn_cast<CXXMethodDecl>(Function);
Felix Berger85f9e8b32016-11-10 01:28:22 +0000154 if (Param->getLocStart().isMacroID() || (Method && Method->isVirtual()) ||
Felix Berger603ea2d2017-07-26 00:45:41 +0000155 isReferencedOutsideOfCallExpr(*Function, *Result.Context) ||
156 isExplicitTemplateSpecialization(*Function))
Felix Berger3c8edde2016-03-29 02:42:38 +0000157 return;
158 for (const auto *FunctionDecl = Function; FunctionDecl != nullptr;
159 FunctionDecl = FunctionDecl->getPreviousDecl()) {
160 const auto &CurrentParam = *FunctionDecl->getParamDecl(Index);
Etienne Bergeron2a4c00f2016-05-03 02:54:05 +0000161 Diag << utils::fixit::changeVarDeclToReference(CurrentParam,
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000162 *Result.Context);
Felix Berger7c6d2892016-11-04 20:51:31 +0000163 // The parameter of each declaration needs to be checked individually as to
164 // whether it is const or not as constness can differ between definition and
165 // declaration.
166 if (!CurrentParam.getType().getCanonicalType().isConstQualified())
Etienne Bergeron2a4c00f2016-05-03 02:54:05 +0000167 Diag << utils::fixit::changeVarDeclToConst(CurrentParam);
Felix Berger3c8edde2016-03-29 02:42:38 +0000168 }
169}
170
Felix Berger7f882752016-07-01 20:12:15 +0000171void UnnecessaryValueParamCheck::registerPPCallbacks(
172 CompilerInstance &Compiler) {
173 Inserter.reset(new utils::IncludeInserter(
174 Compiler.getSourceManager(), Compiler.getLangOpts(), IncludeStyle));
175 Compiler.getPreprocessor().addPPCallbacks(Inserter->CreatePPCallbacks());
176}
177
178void UnnecessaryValueParamCheck::storeOptions(
179 ClangTidyOptions::OptionMap &Opts) {
180 Options.store(Opts, "IncludeStyle",
181 utils::IncludeSorter::toString(IncludeStyle));
182}
183
184void UnnecessaryValueParamCheck::handleMoveFix(const ParmVarDecl &Var,
185 const DeclRefExpr &CopyArgument,
186 const ASTContext &Context) {
187 auto Diag = diag(CopyArgument.getLocStart(),
188 "parameter %0 is passed by value and only copied once; "
189 "consider moving it to avoid unnecessary copies")
190 << &Var;
191 // Do not propose fixes in macros since we cannot place them correctly.
192 if (CopyArgument.getLocStart().isMacroID())
193 return;
194 const auto &SM = Context.getSourceManager();
Kirill Bobyrev11cea452016-08-01 12:06:18 +0000195 auto EndLoc = Lexer::getLocForEndOfToken(CopyArgument.getLocation(), 0, SM,
196 Context.getLangOpts());
Felix Berger7f882752016-07-01 20:12:15 +0000197 Diag << FixItHint::CreateInsertion(CopyArgument.getLocStart(), "std::move(")
198 << FixItHint::CreateInsertion(EndLoc, ")");
199 if (auto IncludeFixit = Inserter->CreateIncludeInsertion(
200 SM.getFileID(CopyArgument.getLocStart()), "utility",
201 /*IsAngled=*/true))
202 Diag << *IncludeFixit;
203}
204
Felix Berger3c8edde2016-03-29 02:42:38 +0000205} // namespace performance
206} // namespace tidy
207} // namespace clang