1 //===--- MoveForwardingReferenceCheck.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 "MoveForwardingReferenceCheck.h"
10 #include "clang/Lex/Lexer.h"
11 #include "llvm/Support/raw_ostream.h"
12 
13 #include <algorithm>
14 
15 using namespace clang::ast_matchers;
16 
17 namespace clang {
18 namespace tidy {
19 namespace bugprone {
20 
replaceMoveWithForward(const UnresolvedLookupExpr * Callee,const ParmVarDecl * ParmVar,const TemplateTypeParmDecl * TypeParmDecl,DiagnosticBuilder & Diag,const ASTContext & Context)21 static void replaceMoveWithForward(const UnresolvedLookupExpr *Callee,
22                                    const ParmVarDecl *ParmVar,
23                                    const TemplateTypeParmDecl *TypeParmDecl,
24                                    DiagnosticBuilder &Diag,
25                                    const ASTContext &Context) {
26   const SourceManager &SM = Context.getSourceManager();
27   const LangOptions &LangOpts = Context.getLangOpts();
28 
29   CharSourceRange CallRange =
30       Lexer::makeFileCharRange(CharSourceRange::getTokenRange(
31                                    Callee->getBeginLoc(), Callee->getEndLoc()),
32                                SM, LangOpts);
33 
34   if (CallRange.isValid()) {
35     const std::string TypeName =
36         (TypeParmDecl->getIdentifier() && !TypeParmDecl->isImplicit())
37             ? TypeParmDecl->getName().str()
38             : (llvm::Twine("decltype(") + ParmVar->getName() + ")").str();
39 
40     const std::string ForwardName =
41         (llvm::Twine("forward<") + TypeName + ">").str();
42 
43     // Create a replacement only if we see a "standard" way of calling
44     // std::move(). This will hopefully prevent erroneous replacements if the
45     // code does unusual things (e.g. create an alias for std::move() in
46     // another namespace).
47     NestedNameSpecifier *NNS = Callee->getQualifier();
48     if (!NNS) {
49       // Called as "move" (i.e. presumably the code had a "using std::move;").
50       // We still conservatively put a "std::" in front of the forward because
51       // we don't know whether the code also had a "using std::forward;".
52       Diag << FixItHint::CreateReplacement(CallRange, "std::" + ForwardName);
53     } else if (const NamespaceDecl *Namespace = NNS->getAsNamespace()) {
54       if (Namespace->getName() == "std") {
55         if (!NNS->getPrefix()) {
56           // Called as "std::move".
57           Diag << FixItHint::CreateReplacement(CallRange,
58                                                "std::" + ForwardName);
59         } else if (NNS->getPrefix()->getKind() == NestedNameSpecifier::Global) {
60           // Called as "::std::move".
61           Diag << FixItHint::CreateReplacement(CallRange,
62                                                "::std::" + ForwardName);
63         }
64       }
65     }
66   }
67 }
68 
registerMatchers(MatchFinder * Finder)69 void MoveForwardingReferenceCheck::registerMatchers(MatchFinder *Finder) {
70   // Matches a ParmVarDecl for a forwarding reference, i.e. a non-const rvalue
71   // reference of a function template parameter type.
72   auto ForwardingReferenceParmMatcher =
73       parmVarDecl(
74           hasType(qualType(rValueReferenceType(),
75                            references(templateTypeParmType(hasDeclaration(
76                                templateTypeParmDecl().bind("type-parm-decl")))),
77                            unless(references(qualType(isConstQualified()))))))
78           .bind("parm-var");
79 
80   Finder->addMatcher(
81       callExpr(callee(unresolvedLookupExpr(
82                           hasAnyDeclaration(namedDecl(
83                               hasUnderlyingDecl(hasName("::std::move")))))
84                           .bind("lookup")),
85                argumentCountIs(1),
86                hasArgument(0, ignoringParenImpCasts(declRefExpr(
87                                   to(ForwardingReferenceParmMatcher)))))
88           .bind("call-move"),
89       this);
90 }
91 
check(const MatchFinder::MatchResult & Result)92 void MoveForwardingReferenceCheck::check(
93     const MatchFinder::MatchResult &Result) {
94   const auto *CallMove = Result.Nodes.getNodeAs<CallExpr>("call-move");
95   const auto *UnresolvedLookup =
96       Result.Nodes.getNodeAs<UnresolvedLookupExpr>("lookup");
97   const auto *ParmVar = Result.Nodes.getNodeAs<ParmVarDecl>("parm-var");
98   const auto *TypeParmDecl =
99       Result.Nodes.getNodeAs<TemplateTypeParmDecl>("type-parm-decl");
100 
101   // Get the FunctionDecl and FunctionTemplateDecl containing the function
102   // parameter.
103   const auto *FuncForParam = dyn_cast<FunctionDecl>(ParmVar->getDeclContext());
104   if (!FuncForParam)
105     return;
106   const FunctionTemplateDecl *FuncTemplate =
107       FuncForParam->getDescribedFunctionTemplate();
108   if (!FuncTemplate)
109     return;
110 
111   // Check that the template type parameter belongs to the same function
112   // template as the function parameter of that type. (This implies that type
113   // deduction will happen on the type.)
114   const TemplateParameterList *Params = FuncTemplate->getTemplateParameters();
115   if (!std::count(Params->begin(), Params->end(), TypeParmDecl))
116     return;
117 
118   auto Diag = diag(CallMove->getExprLoc(),
119                    "forwarding reference passed to std::move(), which may "
120                    "unexpectedly cause lvalues to be moved; use "
121                    "std::forward() instead");
122 
123   replaceMoveWithForward(UnresolvedLookup, ParmVar, TypeParmDecl, Diag,
124                          *Result.Context);
125 }
126 
127 } // namespace bugprone
128 } // namespace tidy
129 } // namespace clang
130