xref: /freebsd/contrib/llvm-project/clang/lib/Analysis/ExprMutationAnalyzer.cpp (revision e8d8bef961a50d4dc22501cde4fb9fb0be1b2532)
10b57cec5SDimitry Andric //===---------- ExprMutationAnalyzer.cpp ----------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric #include "clang/Analysis/Analyses/ExprMutationAnalyzer.h"
9*e8d8bef9SDimitry Andric #include "clang/AST/Expr.h"
10*e8d8bef9SDimitry Andric #include "clang/AST/OperationKinds.h"
110b57cec5SDimitry Andric #include "clang/ASTMatchers/ASTMatchFinder.h"
12*e8d8bef9SDimitry Andric #include "clang/ASTMatchers/ASTMatchers.h"
130b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
140b57cec5SDimitry Andric 
150b57cec5SDimitry Andric namespace clang {
160b57cec5SDimitry Andric using namespace ast_matchers;
170b57cec5SDimitry Andric 
180b57cec5SDimitry Andric namespace {
190b57cec5SDimitry Andric 
200b57cec5SDimitry Andric AST_MATCHER_P(LambdaExpr, hasCaptureInit, const Expr *, E) {
210b57cec5SDimitry Andric   return llvm::is_contained(Node.capture_inits(), E);
220b57cec5SDimitry Andric }
230b57cec5SDimitry Andric 
240b57cec5SDimitry Andric AST_MATCHER_P(CXXForRangeStmt, hasRangeStmt,
250b57cec5SDimitry Andric               ast_matchers::internal::Matcher<DeclStmt>, InnerMatcher) {
260b57cec5SDimitry Andric   const DeclStmt *const Range = Node.getRangeStmt();
270b57cec5SDimitry Andric   return InnerMatcher.matches(*Range, Finder, Builder);
280b57cec5SDimitry Andric }
290b57cec5SDimitry Andric 
30*e8d8bef9SDimitry Andric AST_MATCHER_P(Expr, maybeEvalCommaExpr, ast_matchers::internal::Matcher<Expr>,
31*e8d8bef9SDimitry Andric               InnerMatcher) {
320b57cec5SDimitry Andric   const Expr *Result = &Node;
330b57cec5SDimitry Andric   while (const auto *BOComma =
340b57cec5SDimitry Andric              dyn_cast_or_null<BinaryOperator>(Result->IgnoreParens())) {
350b57cec5SDimitry Andric     if (!BOComma->isCommaOp())
360b57cec5SDimitry Andric       break;
370b57cec5SDimitry Andric     Result = BOComma->getRHS();
380b57cec5SDimitry Andric   }
390b57cec5SDimitry Andric   return InnerMatcher.matches(*Result, Finder, Builder);
400b57cec5SDimitry Andric }
410b57cec5SDimitry Andric 
42*e8d8bef9SDimitry Andric AST_MATCHER_P(Expr, canResolveToExpr, ast_matchers::internal::Matcher<Expr>,
43*e8d8bef9SDimitry Andric               InnerMatcher) {
44*e8d8bef9SDimitry Andric   auto DerivedToBase = [](const ast_matchers::internal::Matcher<Expr> &Inner) {
45*e8d8bef9SDimitry Andric     return implicitCastExpr(anyOf(hasCastKind(CK_DerivedToBase),
46*e8d8bef9SDimitry Andric                                   hasCastKind(CK_UncheckedDerivedToBase)),
47*e8d8bef9SDimitry Andric                             hasSourceExpression(Inner));
48*e8d8bef9SDimitry Andric   };
49*e8d8bef9SDimitry Andric   auto IgnoreDerivedToBase =
50*e8d8bef9SDimitry Andric       [&DerivedToBase](const ast_matchers::internal::Matcher<Expr> &Inner) {
51*e8d8bef9SDimitry Andric         return ignoringParens(expr(anyOf(Inner, DerivedToBase(Inner))));
52*e8d8bef9SDimitry Andric       };
53*e8d8bef9SDimitry Andric 
54*e8d8bef9SDimitry Andric   // The 'ConditionalOperator' matches on `<anything> ? <expr> : <expr>`.
55*e8d8bef9SDimitry Andric   // This matching must be recursive because `<expr>` can be anything resolving
56*e8d8bef9SDimitry Andric   // to the `InnerMatcher`, for example another conditional operator.
57*e8d8bef9SDimitry Andric   // The edge-case `BaseClass &b = <cond> ? DerivedVar1 : DerivedVar2;`
58*e8d8bef9SDimitry Andric   // is handled, too. The implicit cast happens outside of the conditional.
59*e8d8bef9SDimitry Andric   // This is matched by `IgnoreDerivedToBase(canResolveToExpr(InnerMatcher))`
60*e8d8bef9SDimitry Andric   // below.
61*e8d8bef9SDimitry Andric   auto const ConditionalOperator = conditionalOperator(anyOf(
62*e8d8bef9SDimitry Andric       hasTrueExpression(ignoringParens(canResolveToExpr(InnerMatcher))),
63*e8d8bef9SDimitry Andric       hasFalseExpression(ignoringParens(canResolveToExpr(InnerMatcher)))));
64*e8d8bef9SDimitry Andric   auto const ElvisOperator = binaryConditionalOperator(anyOf(
65*e8d8bef9SDimitry Andric       hasTrueExpression(ignoringParens(canResolveToExpr(InnerMatcher))),
66*e8d8bef9SDimitry Andric       hasFalseExpression(ignoringParens(canResolveToExpr(InnerMatcher)))));
67*e8d8bef9SDimitry Andric 
68*e8d8bef9SDimitry Andric   auto const ComplexMatcher = ignoringParens(
69*e8d8bef9SDimitry Andric       expr(anyOf(IgnoreDerivedToBase(InnerMatcher),
70*e8d8bef9SDimitry Andric                  maybeEvalCommaExpr(IgnoreDerivedToBase(InnerMatcher)),
71*e8d8bef9SDimitry Andric                  IgnoreDerivedToBase(ConditionalOperator),
72*e8d8bef9SDimitry Andric                  IgnoreDerivedToBase(ElvisOperator))));
73*e8d8bef9SDimitry Andric 
74*e8d8bef9SDimitry Andric   return ComplexMatcher.matches(Node, Finder, Builder);
75*e8d8bef9SDimitry Andric }
76*e8d8bef9SDimitry Andric 
77*e8d8bef9SDimitry Andric // Similar to 'hasAnyArgument', but does not work because 'InitListExpr' does
78*e8d8bef9SDimitry Andric // not have the 'arguments()' method.
79*e8d8bef9SDimitry Andric AST_MATCHER_P(InitListExpr, hasAnyInit, ast_matchers::internal::Matcher<Expr>,
80*e8d8bef9SDimitry Andric               InnerMatcher) {
81*e8d8bef9SDimitry Andric   for (const Expr *Arg : Node.inits()) {
82*e8d8bef9SDimitry Andric     ast_matchers::internal::BoundNodesTreeBuilder Result(*Builder);
83*e8d8bef9SDimitry Andric     if (InnerMatcher.matches(*Arg, Finder, &Result)) {
84*e8d8bef9SDimitry Andric       *Builder = std::move(Result);
85*e8d8bef9SDimitry Andric       return true;
86*e8d8bef9SDimitry Andric     }
87*e8d8bef9SDimitry Andric   }
88*e8d8bef9SDimitry Andric   return false;
89*e8d8bef9SDimitry Andric }
90*e8d8bef9SDimitry Andric 
910b57cec5SDimitry Andric const ast_matchers::internal::VariadicDynCastAllOfMatcher<Stmt, CXXTypeidExpr>
920b57cec5SDimitry Andric     cxxTypeidExpr;
930b57cec5SDimitry Andric 
940b57cec5SDimitry Andric AST_MATCHER(CXXTypeidExpr, isPotentiallyEvaluated) {
950b57cec5SDimitry Andric   return Node.isPotentiallyEvaluated();
960b57cec5SDimitry Andric }
970b57cec5SDimitry Andric 
980b57cec5SDimitry Andric AST_MATCHER_P(GenericSelectionExpr, hasControllingExpr,
990b57cec5SDimitry Andric               ast_matchers::internal::Matcher<Expr>, InnerMatcher) {
1000b57cec5SDimitry Andric   return InnerMatcher.matches(*Node.getControllingExpr(), Finder, Builder);
1010b57cec5SDimitry Andric }
1020b57cec5SDimitry Andric 
1030b57cec5SDimitry Andric const auto nonConstReferenceType = [] {
1040b57cec5SDimitry Andric   return hasUnqualifiedDesugaredType(
1050b57cec5SDimitry Andric       referenceType(pointee(unless(isConstQualified()))));
1060b57cec5SDimitry Andric };
1070b57cec5SDimitry Andric 
1080b57cec5SDimitry Andric const auto nonConstPointerType = [] {
1090b57cec5SDimitry Andric   return hasUnqualifiedDesugaredType(
1100b57cec5SDimitry Andric       pointerType(pointee(unless(isConstQualified()))));
1110b57cec5SDimitry Andric };
1120b57cec5SDimitry Andric 
1130b57cec5SDimitry Andric const auto isMoveOnly = [] {
1140b57cec5SDimitry Andric   return cxxRecordDecl(
1150b57cec5SDimitry Andric       hasMethod(cxxConstructorDecl(isMoveConstructor(), unless(isDeleted()))),
1160b57cec5SDimitry Andric       hasMethod(cxxMethodDecl(isMoveAssignmentOperator(), unless(isDeleted()))),
1170b57cec5SDimitry Andric       unless(anyOf(hasMethod(cxxConstructorDecl(isCopyConstructor(),
1180b57cec5SDimitry Andric                                                 unless(isDeleted()))),
1190b57cec5SDimitry Andric                    hasMethod(cxxMethodDecl(isCopyAssignmentOperator(),
1200b57cec5SDimitry Andric                                            unless(isDeleted()))))));
1210b57cec5SDimitry Andric };
1220b57cec5SDimitry Andric 
1230b57cec5SDimitry Andric template <class T> struct NodeID;
1245ffd83dbSDimitry Andric template <> struct NodeID<Expr> { static constexpr StringRef value = "expr"; };
1255ffd83dbSDimitry Andric template <> struct NodeID<Decl> { static constexpr StringRef value = "decl"; };
1265ffd83dbSDimitry Andric constexpr StringRef NodeID<Expr>::value;
1275ffd83dbSDimitry Andric constexpr StringRef NodeID<Decl>::value;
1280b57cec5SDimitry Andric 
1290b57cec5SDimitry Andric template <class T, class F = const Stmt *(ExprMutationAnalyzer::*)(const T *)>
1300b57cec5SDimitry Andric const Stmt *tryEachMatch(ArrayRef<ast_matchers::BoundNodes> Matches,
1310b57cec5SDimitry Andric                          ExprMutationAnalyzer *Analyzer, F Finder) {
1320b57cec5SDimitry Andric   const StringRef ID = NodeID<T>::value;
1330b57cec5SDimitry Andric   for (const auto &Nodes : Matches) {
1340b57cec5SDimitry Andric     if (const Stmt *S = (Analyzer->*Finder)(Nodes.getNodeAs<T>(ID)))
1350b57cec5SDimitry Andric       return S;
1360b57cec5SDimitry Andric   }
1370b57cec5SDimitry Andric   return nullptr;
1380b57cec5SDimitry Andric }
1390b57cec5SDimitry Andric 
1400b57cec5SDimitry Andric } // namespace
1410b57cec5SDimitry Andric 
1420b57cec5SDimitry Andric const Stmt *ExprMutationAnalyzer::findMutation(const Expr *Exp) {
1430b57cec5SDimitry Andric   return findMutationMemoized(Exp,
1440b57cec5SDimitry Andric                               {&ExprMutationAnalyzer::findDirectMutation,
1450b57cec5SDimitry Andric                                &ExprMutationAnalyzer::findMemberMutation,
1460b57cec5SDimitry Andric                                &ExprMutationAnalyzer::findArrayElementMutation,
1470b57cec5SDimitry Andric                                &ExprMutationAnalyzer::findCastMutation,
1480b57cec5SDimitry Andric                                &ExprMutationAnalyzer::findRangeLoopMutation,
1490b57cec5SDimitry Andric                                &ExprMutationAnalyzer::findReferenceMutation,
1500b57cec5SDimitry Andric                                &ExprMutationAnalyzer::findFunctionArgMutation},
1510b57cec5SDimitry Andric                               Results);
1520b57cec5SDimitry Andric }
1530b57cec5SDimitry Andric 
1540b57cec5SDimitry Andric const Stmt *ExprMutationAnalyzer::findMutation(const Decl *Dec) {
1550b57cec5SDimitry Andric   return tryEachDeclRef(Dec, &ExprMutationAnalyzer::findMutation);
1560b57cec5SDimitry Andric }
1570b57cec5SDimitry Andric 
1580b57cec5SDimitry Andric const Stmt *ExprMutationAnalyzer::findPointeeMutation(const Expr *Exp) {
1590b57cec5SDimitry Andric   return findMutationMemoized(Exp, {/*TODO*/}, PointeeResults);
1600b57cec5SDimitry Andric }
1610b57cec5SDimitry Andric 
1620b57cec5SDimitry Andric const Stmt *ExprMutationAnalyzer::findPointeeMutation(const Decl *Dec) {
1630b57cec5SDimitry Andric   return tryEachDeclRef(Dec, &ExprMutationAnalyzer::findPointeeMutation);
1640b57cec5SDimitry Andric }
1650b57cec5SDimitry Andric 
1660b57cec5SDimitry Andric const Stmt *ExprMutationAnalyzer::findMutationMemoized(
1670b57cec5SDimitry Andric     const Expr *Exp, llvm::ArrayRef<MutationFinder> Finders,
1680b57cec5SDimitry Andric     ResultMap &MemoizedResults) {
1690b57cec5SDimitry Andric   const auto Memoized = MemoizedResults.find(Exp);
1700b57cec5SDimitry Andric   if (Memoized != MemoizedResults.end())
1710b57cec5SDimitry Andric     return Memoized->second;
1720b57cec5SDimitry Andric 
1730b57cec5SDimitry Andric   if (isUnevaluated(Exp))
1740b57cec5SDimitry Andric     return MemoizedResults[Exp] = nullptr;
1750b57cec5SDimitry Andric 
1760b57cec5SDimitry Andric   for (const auto &Finder : Finders) {
1770b57cec5SDimitry Andric     if (const Stmt *S = (this->*Finder)(Exp))
1780b57cec5SDimitry Andric       return MemoizedResults[Exp] = S;
1790b57cec5SDimitry Andric   }
1800b57cec5SDimitry Andric 
1810b57cec5SDimitry Andric   return MemoizedResults[Exp] = nullptr;
1820b57cec5SDimitry Andric }
1830b57cec5SDimitry Andric 
1840b57cec5SDimitry Andric const Stmt *ExprMutationAnalyzer::tryEachDeclRef(const Decl *Dec,
1850b57cec5SDimitry Andric                                                  MutationFinder Finder) {
1860b57cec5SDimitry Andric   const auto Refs =
1870b57cec5SDimitry Andric       match(findAll(declRefExpr(to(equalsNode(Dec))).bind(NodeID<Expr>::value)),
1880b57cec5SDimitry Andric             Stm, Context);
1890b57cec5SDimitry Andric   for (const auto &RefNodes : Refs) {
1900b57cec5SDimitry Andric     const auto *E = RefNodes.getNodeAs<Expr>(NodeID<Expr>::value);
1910b57cec5SDimitry Andric     if ((this->*Finder)(E))
1920b57cec5SDimitry Andric       return E;
1930b57cec5SDimitry Andric   }
1940b57cec5SDimitry Andric   return nullptr;
1950b57cec5SDimitry Andric }
1960b57cec5SDimitry Andric 
1970b57cec5SDimitry Andric bool ExprMutationAnalyzer::isUnevaluated(const Expr *Exp) {
1980b57cec5SDimitry Andric   return selectFirst<Expr>(
1990b57cec5SDimitry Andric              NodeID<Expr>::value,
2000b57cec5SDimitry Andric              match(
2010b57cec5SDimitry Andric                  findAll(
202*e8d8bef9SDimitry Andric                      expr(canResolveToExpr(equalsNode(Exp)),
2030b57cec5SDimitry Andric                           anyOf(
2040b57cec5SDimitry Andric                               // `Exp` is part of the underlying expression of
2050b57cec5SDimitry Andric                               // decltype/typeof if it has an ancestor of
2060b57cec5SDimitry Andric                               // typeLoc.
2070b57cec5SDimitry Andric                               hasAncestor(typeLoc(unless(
2080b57cec5SDimitry Andric                                   hasAncestor(unaryExprOrTypeTraitExpr())))),
2090b57cec5SDimitry Andric                               hasAncestor(expr(anyOf(
2100b57cec5SDimitry Andric                                   // `UnaryExprOrTypeTraitExpr` is unevaluated
2110b57cec5SDimitry Andric                                   // unless it's sizeof on VLA.
2120b57cec5SDimitry Andric                                   unaryExprOrTypeTraitExpr(unless(sizeOfExpr(
2130b57cec5SDimitry Andric                                       hasArgumentOfType(variableArrayType())))),
2140b57cec5SDimitry Andric                                   // `CXXTypeidExpr` is unevaluated unless it's
2150b57cec5SDimitry Andric                                   // applied to an expression of glvalue of
2160b57cec5SDimitry Andric                                   // polymorphic class type.
2170b57cec5SDimitry Andric                                   cxxTypeidExpr(
2180b57cec5SDimitry Andric                                       unless(isPotentiallyEvaluated())),
2190b57cec5SDimitry Andric                                   // The controlling expression of
2200b57cec5SDimitry Andric                                   // `GenericSelectionExpr` is unevaluated.
2210b57cec5SDimitry Andric                                   genericSelectionExpr(hasControllingExpr(
2220b57cec5SDimitry Andric                                       hasDescendant(equalsNode(Exp)))),
2230b57cec5SDimitry Andric                                   cxxNoexceptExpr())))))
2240b57cec5SDimitry Andric                          .bind(NodeID<Expr>::value)),
2250b57cec5SDimitry Andric                  Stm, Context)) != nullptr;
2260b57cec5SDimitry Andric }
2270b57cec5SDimitry Andric 
2280b57cec5SDimitry Andric const Stmt *
2290b57cec5SDimitry Andric ExprMutationAnalyzer::findExprMutation(ArrayRef<BoundNodes> Matches) {
2300b57cec5SDimitry Andric   return tryEachMatch<Expr>(Matches, this, &ExprMutationAnalyzer::findMutation);
2310b57cec5SDimitry Andric }
2320b57cec5SDimitry Andric 
2330b57cec5SDimitry Andric const Stmt *
2340b57cec5SDimitry Andric ExprMutationAnalyzer::findDeclMutation(ArrayRef<BoundNodes> Matches) {
2350b57cec5SDimitry Andric   return tryEachMatch<Decl>(Matches, this, &ExprMutationAnalyzer::findMutation);
2360b57cec5SDimitry Andric }
2370b57cec5SDimitry Andric 
2380b57cec5SDimitry Andric const Stmt *ExprMutationAnalyzer::findExprPointeeMutation(
2390b57cec5SDimitry Andric     ArrayRef<ast_matchers::BoundNodes> Matches) {
2400b57cec5SDimitry Andric   return tryEachMatch<Expr>(Matches, this,
2410b57cec5SDimitry Andric                             &ExprMutationAnalyzer::findPointeeMutation);
2420b57cec5SDimitry Andric }
2430b57cec5SDimitry Andric 
2440b57cec5SDimitry Andric const Stmt *ExprMutationAnalyzer::findDeclPointeeMutation(
2450b57cec5SDimitry Andric     ArrayRef<ast_matchers::BoundNodes> Matches) {
2460b57cec5SDimitry Andric   return tryEachMatch<Decl>(Matches, this,
2470b57cec5SDimitry Andric                             &ExprMutationAnalyzer::findPointeeMutation);
2480b57cec5SDimitry Andric }
2490b57cec5SDimitry Andric 
2500b57cec5SDimitry Andric const Stmt *ExprMutationAnalyzer::findDirectMutation(const Expr *Exp) {
2510b57cec5SDimitry Andric   // LHS of any assignment operators.
2525ffd83dbSDimitry Andric   const auto AsAssignmentLhs = binaryOperator(
253*e8d8bef9SDimitry Andric       isAssignmentOperator(), hasLHS(canResolveToExpr(equalsNode(Exp))));
2540b57cec5SDimitry Andric 
2550b57cec5SDimitry Andric   // Operand of increment/decrement operators.
2560b57cec5SDimitry Andric   const auto AsIncDecOperand =
2570b57cec5SDimitry Andric       unaryOperator(anyOf(hasOperatorName("++"), hasOperatorName("--")),
258*e8d8bef9SDimitry Andric                     hasUnaryOperand(canResolveToExpr(equalsNode(Exp))));
2590b57cec5SDimitry Andric 
2600b57cec5SDimitry Andric   // Invoking non-const member function.
2610b57cec5SDimitry Andric   // A member function is assumed to be non-const when it is unresolved.
2620b57cec5SDimitry Andric   const auto NonConstMethod = cxxMethodDecl(unless(isConst()));
263*e8d8bef9SDimitry Andric 
264*e8d8bef9SDimitry Andric   const auto AsNonConstThis = expr(anyOf(
265*e8d8bef9SDimitry Andric       cxxMemberCallExpr(callee(NonConstMethod),
266*e8d8bef9SDimitry Andric                         on(canResolveToExpr(equalsNode(Exp)))),
2670b57cec5SDimitry Andric       cxxOperatorCallExpr(callee(NonConstMethod),
268*e8d8bef9SDimitry Andric                           hasArgument(0, canResolveToExpr(equalsNode(Exp)))),
269*e8d8bef9SDimitry Andric       // In case of a templated type, calling overloaded operators is not
270*e8d8bef9SDimitry Andric       // resolved and modelled as `binaryOperator` on a dependent type.
271*e8d8bef9SDimitry Andric       // Such instances are considered a modification, because they can modify
272*e8d8bef9SDimitry Andric       // in different instantiations of the template.
273*e8d8bef9SDimitry Andric       binaryOperator(hasEitherOperand(
274*e8d8bef9SDimitry Andric           allOf(ignoringImpCasts(canResolveToExpr(equalsNode(Exp))),
275*e8d8bef9SDimitry Andric                 isTypeDependent()))),
276*e8d8bef9SDimitry Andric       // Within class templates and member functions the member expression might
277*e8d8bef9SDimitry Andric       // not be resolved. In that case, the `callExpr` is considered to be a
278*e8d8bef9SDimitry Andric       // modification.
279*e8d8bef9SDimitry Andric       callExpr(
280*e8d8bef9SDimitry Andric           callee(expr(anyOf(unresolvedMemberExpr(hasObjectExpression(
281*e8d8bef9SDimitry Andric                                 canResolveToExpr(equalsNode(Exp)))),
282*e8d8bef9SDimitry Andric                             cxxDependentScopeMemberExpr(hasObjectExpression(
283*e8d8bef9SDimitry Andric                                 canResolveToExpr(equalsNode(Exp)))))))),
284*e8d8bef9SDimitry Andric       // Match on a call to a known method, but the call itself is type
285*e8d8bef9SDimitry Andric       // dependent (e.g. `vector<T> v; v.push(T{});` in a templated function).
286*e8d8bef9SDimitry Andric       callExpr(allOf(isTypeDependent(),
287*e8d8bef9SDimitry Andric                      callee(memberExpr(hasDeclaration(NonConstMethod),
288*e8d8bef9SDimitry Andric                                        hasObjectExpression(canResolveToExpr(
289*e8d8bef9SDimitry Andric                                            equalsNode(Exp)))))))));
2900b57cec5SDimitry Andric 
2910b57cec5SDimitry Andric   // Taking address of 'Exp'.
2920b57cec5SDimitry Andric   // We're assuming 'Exp' is mutated as soon as its address is taken, though in
2930b57cec5SDimitry Andric   // theory we can follow the pointer and see whether it escaped `Stm` or is
2940b57cec5SDimitry Andric   // dereferenced and then mutated. This is left for future improvements.
2950b57cec5SDimitry Andric   const auto AsAmpersandOperand =
2960b57cec5SDimitry Andric       unaryOperator(hasOperatorName("&"),
2970b57cec5SDimitry Andric                     // A NoOp implicit cast is adding const.
2980b57cec5SDimitry Andric                     unless(hasParent(implicitCastExpr(hasCastKind(CK_NoOp)))),
299*e8d8bef9SDimitry Andric                     hasUnaryOperand(canResolveToExpr(equalsNode(Exp))));
3000b57cec5SDimitry Andric   const auto AsPointerFromArrayDecay =
3010b57cec5SDimitry Andric       castExpr(hasCastKind(CK_ArrayToPointerDecay),
3020b57cec5SDimitry Andric                unless(hasParent(arraySubscriptExpr())),
303*e8d8bef9SDimitry Andric                has(canResolveToExpr(equalsNode(Exp))));
3040b57cec5SDimitry Andric   // Treat calling `operator->()` of move-only classes as taking address.
3050b57cec5SDimitry Andric   // These are typically smart pointers with unique ownership so we treat
3060b57cec5SDimitry Andric   // mutation of pointee as mutation of the smart pointer itself.
307*e8d8bef9SDimitry Andric   const auto AsOperatorArrowThis = cxxOperatorCallExpr(
308*e8d8bef9SDimitry Andric       hasOverloadedOperatorName("->"),
309*e8d8bef9SDimitry Andric       callee(
310*e8d8bef9SDimitry Andric           cxxMethodDecl(ofClass(isMoveOnly()), returns(nonConstPointerType()))),
311*e8d8bef9SDimitry Andric       argumentCountIs(1), hasArgument(0, canResolveToExpr(equalsNode(Exp))));
3120b57cec5SDimitry Andric 
3130b57cec5SDimitry Andric   // Used as non-const-ref argument when calling a function.
3140b57cec5SDimitry Andric   // An argument is assumed to be non-const-ref when the function is unresolved.
3150b57cec5SDimitry Andric   // Instantiated template functions are not handled here but in
3160b57cec5SDimitry Andric   // findFunctionArgMutation which has additional smarts for handling forwarding
3170b57cec5SDimitry Andric   // references.
318*e8d8bef9SDimitry Andric   const auto NonConstRefParam = forEachArgumentWithParamType(
319*e8d8bef9SDimitry Andric       anyOf(canResolveToExpr(equalsNode(Exp)),
320*e8d8bef9SDimitry Andric             memberExpr(hasObjectExpression(canResolveToExpr(equalsNode(Exp))))),
321*e8d8bef9SDimitry Andric       nonConstReferenceType());
3220b57cec5SDimitry Andric   const auto NotInstantiated = unless(hasDeclaration(isInstantiated()));
323*e8d8bef9SDimitry Andric   const auto TypeDependentCallee =
324*e8d8bef9SDimitry Andric       callee(expr(anyOf(unresolvedLookupExpr(), unresolvedMemberExpr(),
325*e8d8bef9SDimitry Andric                         cxxDependentScopeMemberExpr(),
326*e8d8bef9SDimitry Andric                         hasType(templateTypeParmType()), isTypeDependent())));
327*e8d8bef9SDimitry Andric 
3280b57cec5SDimitry Andric   const auto AsNonConstRefArg = anyOf(
3290b57cec5SDimitry Andric       callExpr(NonConstRefParam, NotInstantiated),
3300b57cec5SDimitry Andric       cxxConstructExpr(NonConstRefParam, NotInstantiated),
331*e8d8bef9SDimitry Andric       callExpr(TypeDependentCallee,
332*e8d8bef9SDimitry Andric                hasAnyArgument(canResolveToExpr(equalsNode(Exp)))),
333*e8d8bef9SDimitry Andric       cxxUnresolvedConstructExpr(
334*e8d8bef9SDimitry Andric           hasAnyArgument(canResolveToExpr(equalsNode(Exp)))),
335*e8d8bef9SDimitry Andric       // Previous False Positive in the following Code:
336*e8d8bef9SDimitry Andric       // `template <typename T> void f() { int i = 42; new Type<T>(i); }`
337*e8d8bef9SDimitry Andric       // Where the constructor of `Type` takes its argument as reference.
338*e8d8bef9SDimitry Andric       // The AST does not resolve in a `cxxConstructExpr` because it is
339*e8d8bef9SDimitry Andric       // type-dependent.
340*e8d8bef9SDimitry Andric       parenListExpr(hasDescendant(expr(canResolveToExpr(equalsNode(Exp))))),
341*e8d8bef9SDimitry Andric       // If the initializer is for a reference type, there is no cast for
342*e8d8bef9SDimitry Andric       // the variable. Values are cast to RValue first.
343*e8d8bef9SDimitry Andric       initListExpr(hasAnyInit(expr(canResolveToExpr(equalsNode(Exp))))));
3440b57cec5SDimitry Andric 
3450b57cec5SDimitry Andric   // Captured by a lambda by reference.
3460b57cec5SDimitry Andric   // If we're initializing a capture with 'Exp' directly then we're initializing
3470b57cec5SDimitry Andric   // a reference capture.
3480b57cec5SDimitry Andric   // For value captures there will be an ImplicitCastExpr <LValueToRValue>.
3490b57cec5SDimitry Andric   const auto AsLambdaRefCaptureInit = lambdaExpr(hasCaptureInit(Exp));
3500b57cec5SDimitry Andric 
3510b57cec5SDimitry Andric   // Returned as non-const-ref.
3520b57cec5SDimitry Andric   // If we're returning 'Exp' directly then it's returned as non-const-ref.
3530b57cec5SDimitry Andric   // For returning by value there will be an ImplicitCastExpr <LValueToRValue>.
3540b57cec5SDimitry Andric   // For returning by const-ref there will be an ImplicitCastExpr <NoOp> (for
3550b57cec5SDimitry Andric   // adding const.)
356*e8d8bef9SDimitry Andric   const auto AsNonConstRefReturn =
357*e8d8bef9SDimitry Andric       returnStmt(hasReturnValue(canResolveToExpr(equalsNode(Exp))));
358*e8d8bef9SDimitry Andric 
359*e8d8bef9SDimitry Andric   // It is used as a non-const-reference for initalizing a range-for loop.
360*e8d8bef9SDimitry Andric   const auto AsNonConstRefRangeInit = cxxForRangeStmt(
361*e8d8bef9SDimitry Andric       hasRangeInit(declRefExpr(allOf(canResolveToExpr(equalsNode(Exp)),
362*e8d8bef9SDimitry Andric                                      hasType(nonConstReferenceType())))));
3630b57cec5SDimitry Andric 
3645ffd83dbSDimitry Andric   const auto Matches = match(
365*e8d8bef9SDimitry Andric       traverse(TK_AsIs,
366*e8d8bef9SDimitry Andric                findAll(stmt(anyOf(AsAssignmentLhs, AsIncDecOperand,
367*e8d8bef9SDimitry Andric                                   AsNonConstThis, AsAmpersandOperand,
368*e8d8bef9SDimitry Andric                                   AsPointerFromArrayDecay, AsOperatorArrowThis,
369*e8d8bef9SDimitry Andric                                   AsNonConstRefArg, AsLambdaRefCaptureInit,
370*e8d8bef9SDimitry Andric                                   AsNonConstRefReturn, AsNonConstRefRangeInit))
3715ffd83dbSDimitry Andric                            .bind("stmt"))),
3720b57cec5SDimitry Andric       Stm, Context);
3730b57cec5SDimitry Andric   return selectFirst<Stmt>("stmt", Matches);
3740b57cec5SDimitry Andric }
3750b57cec5SDimitry Andric 
3760b57cec5SDimitry Andric const Stmt *ExprMutationAnalyzer::findMemberMutation(const Expr *Exp) {
3770b57cec5SDimitry Andric   // Check whether any member of 'Exp' is mutated.
3780b57cec5SDimitry Andric   const auto MemberExprs =
379*e8d8bef9SDimitry Andric       match(findAll(expr(anyOf(memberExpr(hasObjectExpression(
380*e8d8bef9SDimitry Andric                                    canResolveToExpr(equalsNode(Exp)))),
381*e8d8bef9SDimitry Andric                                cxxDependentScopeMemberExpr(hasObjectExpression(
382*e8d8bef9SDimitry Andric                                    canResolveToExpr(equalsNode(Exp))))))
3830b57cec5SDimitry Andric                         .bind(NodeID<Expr>::value)),
3840b57cec5SDimitry Andric             Stm, Context);
3850b57cec5SDimitry Andric   return findExprMutation(MemberExprs);
3860b57cec5SDimitry Andric }
3870b57cec5SDimitry Andric 
3880b57cec5SDimitry Andric const Stmt *ExprMutationAnalyzer::findArrayElementMutation(const Expr *Exp) {
3890b57cec5SDimitry Andric   // Check whether any element of an array is mutated.
390*e8d8bef9SDimitry Andric   const auto SubscriptExprs =
391*e8d8bef9SDimitry Andric       match(findAll(arraySubscriptExpr(
392*e8d8bef9SDimitry Andric                         anyOf(hasBase(canResolveToExpr(equalsNode(Exp))),
393*e8d8bef9SDimitry Andric                               hasBase(implicitCastExpr(
394*e8d8bef9SDimitry Andric                                   allOf(hasCastKind(CK_ArrayToPointerDecay),
395*e8d8bef9SDimitry Andric                                         hasSourceExpression(canResolveToExpr(
396*e8d8bef9SDimitry Andric                                             equalsNode(Exp))))))))
3970b57cec5SDimitry Andric                         .bind(NodeID<Expr>::value)),
3980b57cec5SDimitry Andric             Stm, Context);
3990b57cec5SDimitry Andric   return findExprMutation(SubscriptExprs);
4000b57cec5SDimitry Andric }
4010b57cec5SDimitry Andric 
4020b57cec5SDimitry Andric const Stmt *ExprMutationAnalyzer::findCastMutation(const Expr *Exp) {
403*e8d8bef9SDimitry Andric   // If the 'Exp' is explicitly casted to a non-const reference type the
404*e8d8bef9SDimitry Andric   // 'Exp' is considered to be modified.
405*e8d8bef9SDimitry Andric   const auto ExplicitCast = match(
406*e8d8bef9SDimitry Andric       findAll(
407*e8d8bef9SDimitry Andric           stmt(castExpr(hasSourceExpression(canResolveToExpr(equalsNode(Exp))),
408*e8d8bef9SDimitry Andric                         explicitCastExpr(
409*e8d8bef9SDimitry Andric                             hasDestinationType(nonConstReferenceType()))))
410*e8d8bef9SDimitry Andric               .bind("stmt")),
411*e8d8bef9SDimitry Andric       Stm, Context);
412*e8d8bef9SDimitry Andric 
413*e8d8bef9SDimitry Andric   if (const auto *CastStmt = selectFirst<Stmt>("stmt", ExplicitCast))
414*e8d8bef9SDimitry Andric     return CastStmt;
415*e8d8bef9SDimitry Andric 
4160b57cec5SDimitry Andric   // If 'Exp' is casted to any non-const reference type, check the castExpr.
417*e8d8bef9SDimitry Andric   const auto Casts = match(
418*e8d8bef9SDimitry Andric       findAll(
419*e8d8bef9SDimitry Andric           expr(castExpr(hasSourceExpression(canResolveToExpr(equalsNode(Exp))),
420*e8d8bef9SDimitry Andric                         anyOf(explicitCastExpr(
421*e8d8bef9SDimitry Andric                                   hasDestinationType(nonConstReferenceType())),
4220b57cec5SDimitry Andric                               implicitCastExpr(hasImplicitDestinationType(
423*e8d8bef9SDimitry Andric                                   nonConstReferenceType())))))
4240b57cec5SDimitry Andric               .bind(NodeID<Expr>::value)),
4250b57cec5SDimitry Andric       Stm, Context);
426*e8d8bef9SDimitry Andric 
4270b57cec5SDimitry Andric   if (const Stmt *S = findExprMutation(Casts))
4280b57cec5SDimitry Andric     return S;
4290b57cec5SDimitry Andric   // Treat std::{move,forward} as cast.
4300b57cec5SDimitry Andric   const auto Calls =
4310b57cec5SDimitry Andric       match(findAll(callExpr(callee(namedDecl(
4320b57cec5SDimitry Andric                                  hasAnyName("::std::move", "::std::forward"))),
433*e8d8bef9SDimitry Andric                              hasArgument(0, canResolveToExpr(equalsNode(Exp))))
4340b57cec5SDimitry Andric                         .bind("expr")),
4350b57cec5SDimitry Andric             Stm, Context);
4360b57cec5SDimitry Andric   return findExprMutation(Calls);
4370b57cec5SDimitry Andric }
4380b57cec5SDimitry Andric 
4390b57cec5SDimitry Andric const Stmt *ExprMutationAnalyzer::findRangeLoopMutation(const Expr *Exp) {
440*e8d8bef9SDimitry Andric   // Keep the ordering for the specific initialization matches to happen first,
441*e8d8bef9SDimitry Andric   // because it is cheaper to match all potential modifications of the loop
442*e8d8bef9SDimitry Andric   // variable.
443*e8d8bef9SDimitry Andric 
444*e8d8bef9SDimitry Andric   // The range variable is a reference to a builtin array. In that case the
445*e8d8bef9SDimitry Andric   // array is considered modified if the loop-variable is a non-const reference.
446*e8d8bef9SDimitry Andric   const auto DeclStmtToNonRefToArray = declStmt(hasSingleDecl(varDecl(hasType(
447*e8d8bef9SDimitry Andric       hasUnqualifiedDesugaredType(referenceType(pointee(arrayType())))))));
448*e8d8bef9SDimitry Andric   const auto RefToArrayRefToElements = match(
449*e8d8bef9SDimitry Andric       findAll(stmt(cxxForRangeStmt(
450*e8d8bef9SDimitry Andric                        hasLoopVariable(varDecl(hasType(nonConstReferenceType()))
451*e8d8bef9SDimitry Andric                                            .bind(NodeID<Decl>::value)),
452*e8d8bef9SDimitry Andric                        hasRangeStmt(DeclStmtToNonRefToArray),
453*e8d8bef9SDimitry Andric                        hasRangeInit(canResolveToExpr(equalsNode(Exp)))))
454*e8d8bef9SDimitry Andric                   .bind("stmt")),
455*e8d8bef9SDimitry Andric       Stm, Context);
456*e8d8bef9SDimitry Andric 
457*e8d8bef9SDimitry Andric   if (const auto *BadRangeInitFromArray =
458*e8d8bef9SDimitry Andric           selectFirst<Stmt>("stmt", RefToArrayRefToElements))
459*e8d8bef9SDimitry Andric     return BadRangeInitFromArray;
460*e8d8bef9SDimitry Andric 
461*e8d8bef9SDimitry Andric   // Small helper to match special cases in range-for loops.
462*e8d8bef9SDimitry Andric   //
463*e8d8bef9SDimitry Andric   // It is possible that containers do not provide a const-overload for their
464*e8d8bef9SDimitry Andric   // iterator accessors. If this is the case, the variable is used non-const
465*e8d8bef9SDimitry Andric   // no matter what happens in the loop. This requires special detection as it
466*e8d8bef9SDimitry Andric   // is then faster to find all mutations of the loop variable.
467*e8d8bef9SDimitry Andric   // It aims at a different modification as well.
468*e8d8bef9SDimitry Andric   const auto HasAnyNonConstIterator =
469*e8d8bef9SDimitry Andric       anyOf(allOf(hasMethod(allOf(hasName("begin"), unless(isConst()))),
470*e8d8bef9SDimitry Andric                   unless(hasMethod(allOf(hasName("begin"), isConst())))),
471*e8d8bef9SDimitry Andric             allOf(hasMethod(allOf(hasName("end"), unless(isConst()))),
472*e8d8bef9SDimitry Andric                   unless(hasMethod(allOf(hasName("end"), isConst())))));
473*e8d8bef9SDimitry Andric 
474*e8d8bef9SDimitry Andric   const auto DeclStmtToNonConstIteratorContainer = declStmt(
475*e8d8bef9SDimitry Andric       hasSingleDecl(varDecl(hasType(hasUnqualifiedDesugaredType(referenceType(
476*e8d8bef9SDimitry Andric           pointee(hasDeclaration(cxxRecordDecl(HasAnyNonConstIterator)))))))));
477*e8d8bef9SDimitry Andric 
478*e8d8bef9SDimitry Andric   const auto RefToContainerBadIterators =
479*e8d8bef9SDimitry Andric       match(findAll(stmt(cxxForRangeStmt(allOf(
480*e8d8bef9SDimitry Andric                              hasRangeStmt(DeclStmtToNonConstIteratorContainer),
481*e8d8bef9SDimitry Andric                              hasRangeInit(canResolveToExpr(equalsNode(Exp))))))
482*e8d8bef9SDimitry Andric                         .bind("stmt")),
483*e8d8bef9SDimitry Andric             Stm, Context);
484*e8d8bef9SDimitry Andric 
485*e8d8bef9SDimitry Andric   if (const auto *BadIteratorsContainer =
486*e8d8bef9SDimitry Andric           selectFirst<Stmt>("stmt", RefToContainerBadIterators))
487*e8d8bef9SDimitry Andric     return BadIteratorsContainer;
488*e8d8bef9SDimitry Andric 
4890b57cec5SDimitry Andric   // If range for looping over 'Exp' with a non-const reference loop variable,
4900b57cec5SDimitry Andric   // check all declRefExpr of the loop variable.
4910b57cec5SDimitry Andric   const auto LoopVars =
4920b57cec5SDimitry Andric       match(findAll(cxxForRangeStmt(
4930b57cec5SDimitry Andric                 hasLoopVariable(varDecl(hasType(nonConstReferenceType()))
4940b57cec5SDimitry Andric                                     .bind(NodeID<Decl>::value)),
495*e8d8bef9SDimitry Andric                 hasRangeInit(canResolveToExpr(equalsNode(Exp))))),
4960b57cec5SDimitry Andric             Stm, Context);
4970b57cec5SDimitry Andric   return findDeclMutation(LoopVars);
4980b57cec5SDimitry Andric }
4990b57cec5SDimitry Andric 
5000b57cec5SDimitry Andric const Stmt *ExprMutationAnalyzer::findReferenceMutation(const Expr *Exp) {
5010b57cec5SDimitry Andric   // Follow non-const reference returned by `operator*()` of move-only classes.
5020b57cec5SDimitry Andric   // These are typically smart pointers with unique ownership so we treat
5030b57cec5SDimitry Andric   // mutation of pointee as mutation of the smart pointer itself.
5040b57cec5SDimitry Andric   const auto Ref =
5050b57cec5SDimitry Andric       match(findAll(cxxOperatorCallExpr(
5060b57cec5SDimitry Andric                         hasOverloadedOperatorName("*"),
5070b57cec5SDimitry Andric                         callee(cxxMethodDecl(ofClass(isMoveOnly()),
5080b57cec5SDimitry Andric                                              returns(nonConstReferenceType()))),
509*e8d8bef9SDimitry Andric                         argumentCountIs(1),
510*e8d8bef9SDimitry Andric                         hasArgument(0, canResolveToExpr(equalsNode(Exp))))
5110b57cec5SDimitry Andric                         .bind(NodeID<Expr>::value)),
5120b57cec5SDimitry Andric             Stm, Context);
5130b57cec5SDimitry Andric   if (const Stmt *S = findExprMutation(Ref))
5140b57cec5SDimitry Andric     return S;
5150b57cec5SDimitry Andric 
5160b57cec5SDimitry Andric   // If 'Exp' is bound to a non-const reference, check all declRefExpr to that.
5170b57cec5SDimitry Andric   const auto Refs = match(
5180b57cec5SDimitry Andric       stmt(forEachDescendant(
5190b57cec5SDimitry Andric           varDecl(
5200b57cec5SDimitry Andric               hasType(nonConstReferenceType()),
521*e8d8bef9SDimitry Andric               hasInitializer(anyOf(canResolveToExpr(equalsNode(Exp)),
522*e8d8bef9SDimitry Andric                                    memberExpr(hasObjectExpression(
523*e8d8bef9SDimitry Andric                                        canResolveToExpr(equalsNode(Exp)))))),
5240b57cec5SDimitry Andric               hasParent(declStmt().bind("stmt")),
525*e8d8bef9SDimitry Andric               // Don't follow the reference in range statement, we've
526*e8d8bef9SDimitry Andric               // handled that separately.
5270b57cec5SDimitry Andric               unless(hasParent(declStmt(hasParent(
5280b57cec5SDimitry Andric                   cxxForRangeStmt(hasRangeStmt(equalsBoundNode("stmt"))))))))
5290b57cec5SDimitry Andric               .bind(NodeID<Decl>::value))),
5300b57cec5SDimitry Andric       Stm, Context);
5310b57cec5SDimitry Andric   return findDeclMutation(Refs);
5320b57cec5SDimitry Andric }
5330b57cec5SDimitry Andric 
5340b57cec5SDimitry Andric const Stmt *ExprMutationAnalyzer::findFunctionArgMutation(const Expr *Exp) {
5350b57cec5SDimitry Andric   const auto NonConstRefParam = forEachArgumentWithParam(
536*e8d8bef9SDimitry Andric       canResolveToExpr(equalsNode(Exp)),
5370b57cec5SDimitry Andric       parmVarDecl(hasType(nonConstReferenceType())).bind("parm"));
5380b57cec5SDimitry Andric   const auto IsInstantiated = hasDeclaration(isInstantiated());
5390b57cec5SDimitry Andric   const auto FuncDecl = hasDeclaration(functionDecl().bind("func"));
5400b57cec5SDimitry Andric   const auto Matches = match(
5415ffd83dbSDimitry Andric       traverse(
542*e8d8bef9SDimitry Andric           TK_AsIs,
5435ffd83dbSDimitry Andric           findAll(
5445ffd83dbSDimitry Andric               expr(anyOf(callExpr(NonConstRefParam, IsInstantiated, FuncDecl,
5450b57cec5SDimitry Andric                                   unless(callee(namedDecl(hasAnyName(
5460b57cec5SDimitry Andric                                       "::std::move", "::std::forward"))))),
5470b57cec5SDimitry Andric                          cxxConstructExpr(NonConstRefParam, IsInstantiated,
5480b57cec5SDimitry Andric                                           FuncDecl)))
5495ffd83dbSDimitry Andric                   .bind(NodeID<Expr>::value))),
5500b57cec5SDimitry Andric       Stm, Context);
5510b57cec5SDimitry Andric   for (const auto &Nodes : Matches) {
5520b57cec5SDimitry Andric     const auto *Exp = Nodes.getNodeAs<Expr>(NodeID<Expr>::value);
5530b57cec5SDimitry Andric     const auto *Func = Nodes.getNodeAs<FunctionDecl>("func");
5540b57cec5SDimitry Andric     if (!Func->getBody() || !Func->getPrimaryTemplate())
5550b57cec5SDimitry Andric       return Exp;
5560b57cec5SDimitry Andric 
5570b57cec5SDimitry Andric     const auto *Parm = Nodes.getNodeAs<ParmVarDecl>("parm");
5580b57cec5SDimitry Andric     const ArrayRef<ParmVarDecl *> AllParams =
5590b57cec5SDimitry Andric         Func->getPrimaryTemplate()->getTemplatedDecl()->parameters();
5600b57cec5SDimitry Andric     QualType ParmType =
5610b57cec5SDimitry Andric         AllParams[std::min<size_t>(Parm->getFunctionScopeIndex(),
5620b57cec5SDimitry Andric                                    AllParams.size() - 1)]
5630b57cec5SDimitry Andric             ->getType();
5640b57cec5SDimitry Andric     if (const auto *T = ParmType->getAs<PackExpansionType>())
5650b57cec5SDimitry Andric       ParmType = T->getPattern();
5660b57cec5SDimitry Andric 
5670b57cec5SDimitry Andric     // If param type is forwarding reference, follow into the function
5680b57cec5SDimitry Andric     // definition and see whether the param is mutated inside.
5690b57cec5SDimitry Andric     if (const auto *RefType = ParmType->getAs<RValueReferenceType>()) {
5700b57cec5SDimitry Andric       if (!RefType->getPointeeType().getQualifiers() &&
5710b57cec5SDimitry Andric           RefType->getPointeeType()->getAs<TemplateTypeParmType>()) {
5720b57cec5SDimitry Andric         std::unique_ptr<FunctionParmMutationAnalyzer> &Analyzer =
5730b57cec5SDimitry Andric             FuncParmAnalyzer[Func];
5740b57cec5SDimitry Andric         if (!Analyzer)
5750b57cec5SDimitry Andric           Analyzer.reset(new FunctionParmMutationAnalyzer(*Func, Context));
5760b57cec5SDimitry Andric         if (Analyzer->findMutation(Parm))
5770b57cec5SDimitry Andric           return Exp;
5780b57cec5SDimitry Andric         continue;
5790b57cec5SDimitry Andric       }
5800b57cec5SDimitry Andric     }
5810b57cec5SDimitry Andric     // Not forwarding reference.
5820b57cec5SDimitry Andric     return Exp;
5830b57cec5SDimitry Andric   }
5840b57cec5SDimitry Andric   return nullptr;
5850b57cec5SDimitry Andric }
5860b57cec5SDimitry Andric 
5870b57cec5SDimitry Andric FunctionParmMutationAnalyzer::FunctionParmMutationAnalyzer(
5880b57cec5SDimitry Andric     const FunctionDecl &Func, ASTContext &Context)
5890b57cec5SDimitry Andric     : BodyAnalyzer(*Func.getBody(), Context) {
5900b57cec5SDimitry Andric   if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(&Func)) {
5910b57cec5SDimitry Andric     // CXXCtorInitializer might also mutate Param but they're not part of
5920b57cec5SDimitry Andric     // function body, check them eagerly here since they're typically trivial.
5930b57cec5SDimitry Andric     for (const CXXCtorInitializer *Init : Ctor->inits()) {
5940b57cec5SDimitry Andric       ExprMutationAnalyzer InitAnalyzer(*Init->getInit(), Context);
5950b57cec5SDimitry Andric       for (const ParmVarDecl *Parm : Ctor->parameters()) {
5960b57cec5SDimitry Andric         if (Results.find(Parm) != Results.end())
5970b57cec5SDimitry Andric           continue;
5980b57cec5SDimitry Andric         if (const Stmt *S = InitAnalyzer.findMutation(Parm))
5990b57cec5SDimitry Andric           Results[Parm] = S;
6000b57cec5SDimitry Andric       }
6010b57cec5SDimitry Andric     }
6020b57cec5SDimitry Andric   }
6030b57cec5SDimitry Andric }
6040b57cec5SDimitry Andric 
6050b57cec5SDimitry Andric const Stmt *
6060b57cec5SDimitry Andric FunctionParmMutationAnalyzer::findMutation(const ParmVarDecl *Parm) {
6070b57cec5SDimitry Andric   const auto Memoized = Results.find(Parm);
6080b57cec5SDimitry Andric   if (Memoized != Results.end())
6090b57cec5SDimitry Andric     return Memoized->second;
6100b57cec5SDimitry Andric 
6110b57cec5SDimitry Andric   if (const Stmt *S = BodyAnalyzer.findMutation(Parm))
6120b57cec5SDimitry Andric     return Results[Parm] = S;
6130b57cec5SDimitry Andric 
6140b57cec5SDimitry Andric   return Results[Parm] = nullptr;
6150b57cec5SDimitry Andric }
6160b57cec5SDimitry Andric 
6170b57cec5SDimitry Andric } // namespace clang
618