clang-tools  4.0.0
UnnecessaryValueParamCheck.cpp
Go to the documentation of this file.
1 //===--- 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 
11 
12 #include "../utils/DeclRefExprUtils.h"
13 #include "../utils/FixItHintUtils.h"
14 #include "../utils/Matchers.h"
15 #include "../utils/TypeTraits.h"
16 #include "clang/Frontend/CompilerInstance.h"
17 #include "clang/Lex/Lexer.h"
18 #include "clang/Lex/Preprocessor.h"
19 
20 using namespace clang::ast_matchers;
21 
22 namespace clang {
23 namespace tidy {
24 namespace performance {
25 
26 namespace {
27 
28 std::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 
34 template <typename S>
35 bool 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 
42 bool 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 
50 bool hasLoopStmtAncestor(const DeclRefExpr &DeclRef, const Decl &Decl,
51  ASTContext &Context) {
52  auto Matches =
53  match(decl(forEachDescendant(declRefExpr(
54  equalsNode(&DeclRef),
55  unless(hasAncestor(stmt(anyOf(forStmt(), cxxForRangeStmt(),
56  whileStmt(), doStmt()))))))),
57  Decl, Context);
58  return Matches.empty();
59 }
60 
61 } // namespace
62 
63 UnnecessaryValueParamCheck::UnnecessaryValueParamCheck(
64  StringRef Name, ClangTidyContext *Context)
65  : ClangTidyCheck(Name, Context),
66  IncludeStyle(utils::IncludeSorter::parseIncludeStyle(
67  Options.get("IncludeStyle", "llvm"))) {}
68 
70  const auto ExpensiveValueParamDecl =
71  parmVarDecl(hasType(hasCanonicalType(allOf(matchers::isExpensiveToCopy(),
72  unless(referenceType())))),
73  decl().bind("param"));
74  Finder->addMatcher(
75  functionDecl(hasBody(stmt()), isDefinition(),
76  unless(cxxMethodDecl(anyOf(isOverride(), isFinal()))),
77  unless(isInstantiated()),
78  has(typeLoc(forEach(ExpensiveValueParamDecl))),
79  decl().bind("functionDecl")),
80  this);
81 }
82 
83 void UnnecessaryValueParamCheck::check(const MatchFinder::MatchResult &Result) {
84  const auto *Param = Result.Nodes.getNodeAs<ParmVarDecl>("param");
85  const auto *Function = Result.Nodes.getNodeAs<FunctionDecl>("functionDecl");
86  const size_t Index = std::find(Function->parameters().begin(),
87  Function->parameters().end(), Param) -
88  Function->parameters().begin();
89  bool IsConstQualified =
90  Param->getType().getCanonicalType().isConstQualified();
91 
92  auto AllDeclRefExprs = utils::decl_ref_expr::allDeclRefExprs(
93  *Param, *Function, *Result.Context);
94  auto ConstDeclRefExprs = utils::decl_ref_expr::constReferenceDeclRefExprs(
95  *Param, *Function, *Result.Context);
96 
97  // Do not trigger on non-const value parameters when they are not only used as
98  // const.
99  if (!isSubset(AllDeclRefExprs, ConstDeclRefExprs))
100  return;
101 
102  // If the parameter is non-const, check if it has a move constructor and is
103  // only referenced once to copy-construct another object or whether it has a
104  // move assignment operator and is only referenced once when copy-assigned.
105  // In this case wrap DeclRefExpr with std::move() to avoid the unnecessary
106  // copy.
107  if (!IsConstQualified && AllDeclRefExprs.size() == 1) {
108  auto CanonicalType = Param->getType().getCanonicalType();
109  const auto &DeclRefExpr = **AllDeclRefExprs.begin();
110 
111  if (!hasLoopStmtAncestor(DeclRefExpr, *Function, *Result.Context) &&
114  DeclRefExpr, *Function, *Result.Context)) ||
117  DeclRefExpr, *Function, *Result.Context)))) {
118  handleMoveFix(*Param, DeclRefExpr, *Result.Context);
119  return;
120  }
121  }
122 
123  auto Diag =
124  diag(Param->getLocation(),
125  IsConstQualified ? "the const qualified parameter %0 is "
126  "copied for each invocation; consider "
127  "making it a reference"
128  : "the parameter %0 is copied for each "
129  "invocation but only used as a const reference; "
130  "consider making it a const reference")
131  << paramNameOrIndex(Param->getName(), Index);
132  // Do not propose fixes when:
133  // 1. the ParmVarDecl is in a macro, since we cannot place them correctly
134  // 2. the function is virtual as it might break overrides
135  // 3. the function is referenced outside of a call expression within the
136  // compilation unit as the signature change could introduce build errors.
137  const auto *Method = llvm::dyn_cast<CXXMethodDecl>(Function);
138  if (Param->getLocStart().isMacroID() || (Method && Method->isVirtual()) ||
139  isReferencedOutsideOfCallExpr(*Function, *Result.Context))
140  return;
141  for (const auto *FunctionDecl = Function; FunctionDecl != nullptr;
142  FunctionDecl = FunctionDecl->getPreviousDecl()) {
143  const auto &CurrentParam = *FunctionDecl->getParamDecl(Index);
144  Diag << utils::fixit::changeVarDeclToReference(CurrentParam,
145  *Result.Context);
146  // The parameter of each declaration needs to be checked individually as to
147  // whether it is const or not as constness can differ between definition and
148  // declaration.
149  if (!CurrentParam.getType().getCanonicalType().isConstQualified())
150  Diag << utils::fixit::changeVarDeclToConst(CurrentParam);
151  }
152 }
153 
155  CompilerInstance &Compiler) {
156  Inserter.reset(new utils::IncludeInserter(
157  Compiler.getSourceManager(), Compiler.getLangOpts(), IncludeStyle));
158  Compiler.getPreprocessor().addPPCallbacks(Inserter->CreatePPCallbacks());
159 }
160 
163  Options.store(Opts, "IncludeStyle",
164  utils::IncludeSorter::toString(IncludeStyle));
165 }
166 
167 void UnnecessaryValueParamCheck::handleMoveFix(const ParmVarDecl &Var,
168  const DeclRefExpr &CopyArgument,
169  const ASTContext &Context) {
170  auto Diag = diag(CopyArgument.getLocStart(),
171  "parameter %0 is passed by value and only copied once; "
172  "consider moving it to avoid unnecessary copies")
173  << &Var;
174  // Do not propose fixes in macros since we cannot place them correctly.
175  if (CopyArgument.getLocStart().isMacroID())
176  return;
177  const auto &SM = Context.getSourceManager();
178  auto EndLoc = Lexer::getLocForEndOfToken(CopyArgument.getLocation(), 0, SM,
179  Context.getLangOpts());
180  Diag << FixItHint::CreateInsertion(CopyArgument.getLocStart(), "std::move(")
181  << FixItHint::CreateInsertion(EndLoc, ")");
182  if (auto IncludeFixit = Inserter->CreateIncludeInsertion(
183  SM.getFileID(CopyArgument.getLocStart()), "utility",
184  /*IsAngled=*/true))
185  Diag << *IncludeFixit;
186 }
187 
188 } // namespace performance
189 } // namespace tidy
190 } // namespace clang
const std::string Name
Definition: USRFinder.cpp:164
SmallPtrSet< const DeclRefExpr *, 16 > allDeclRefExprs(const VarDecl &VarDecl, const Stmt &Stmt, ASTContext &Context)
Returns set of all DeclRefExprs to VarDecl within Stmt.
std::unique_ptr< ast_matchers::MatchFinder > Finder
Definition: ClangTidy.cpp:262
bool isCopyConstructorArgument(const DeclRefExpr &DeclRef, const Decl &Decl, ASTContext &Context)
Returns true if DeclRefExpr is the argument of a copy-constructor call expression within Decl...
static StringRef toString(IncludeStyle Style)
Converts IncludeStyle to string representation.
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
Base class for all clang-tidy checks.
Definition: ClangTidy.h:127
bool hasNonTrivialMoveConstructor(QualType Type)
Returns true if Type has a non-trivial move constructor.
Definition: TypeTraits.cpp:134
SourceManager & SM
llvm::Optional< bool > isExpensiveToCopy(QualType Type, const ASTContext &Context)
Returns true if Type is expensive to copy.
Definition: TypeTraits.cpp:42
SmallPtrSet< const DeclRefExpr *, 16 > constReferenceDeclRefExprs(const VarDecl &VarDecl, const Stmt &Stmt, ASTContext &Context)
Returns set of all DeclRefExprs to VarDecl within Stmt where VarDecl is guaranteed to be accessed in ...
void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName, StringRef Value) const
Stores an option with the check-local name LocalName with string value Value to Options.
Definition: ClangTidy.cpp:436
std::map< std::string, std::string > OptionMap
void registerPPCallbacks(CompilerInstance &Compiler) override
Override this to register PPCallbacks with Compiler.
Produces fixes to insert specified includes to source files, if not yet present.
ClangTidyContext & Context
Definition: ClangTidy.cpp:87
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
bool isCopyAssignmentArgument(const DeclRefExpr &DeclRef, const Decl &Decl, ASTContext &Context)
Returns true if DeclRefExpr is the argument of a copy-assignment operator CallExpr within Decl...
const DeclRefExpr * DeclRef
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
Definition: ClangTidy.cpp:403
bool hasNonTrivialMoveAssignment(QualType Type)
Return true if Type has a non-trivial move assignment operator.
Definition: TypeTraits.cpp:140
FixItHint changeVarDeclToConst(const VarDecl &Var)
Creates fix to make VarDecl const qualified.
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
const NamedDecl * Result
Definition: USRFinder.cpp:162
FixItHint changeVarDeclToReference(const VarDecl &Var, ASTContext &Context)
Creates fix to make VarDecl a reference by adding &.