xref: /llvm-project/clang/lib/Analysis/ExprMutationAnalyzer.cpp (revision 8fd32b96caf37113dd425cd9d0ff8c839c6a048a)
1 //===---------- ExprMutationAnalyzer.cpp ----------------------------------===//
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 #include "clang/Analysis/Analyses/ExprMutationAnalyzer.h"
9 #include "clang/AST/Expr.h"
10 #include "clang/AST/OperationKinds.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
12 #include "clang/ASTMatchers/ASTMatchers.h"
13 #include "llvm/ADT/STLExtras.h"
14 
15 namespace clang {
16 using namespace ast_matchers;
17 
18 // Check if result of Source expression could be a Target expression.
19 // Checks:
20 //  - Implicit Casts
21 //  - Binary Operators
22 //  - ConditionalOperator
23 //  - BinaryConditionalOperator
24 static bool canExprResolveTo(const Expr *Source, const Expr *Target) {
25 
26   const auto IgnoreDerivedToBase = [](const Expr *E, auto Matcher) {
27     if (Matcher(E))
28       return true;
29     if (const auto *Cast = dyn_cast<ImplicitCastExpr>(E)) {
30       if ((Cast->getCastKind() == CK_DerivedToBase ||
31            Cast->getCastKind() == CK_UncheckedDerivedToBase) &&
32           Matcher(Cast->getSubExpr()))
33         return true;
34     }
35     return false;
36   };
37 
38   const auto EvalCommaExpr = [](const Expr *E, auto Matcher) {
39     const Expr *Result = E;
40     while (const auto *BOComma =
41                dyn_cast_or_null<BinaryOperator>(Result->IgnoreParens())) {
42       if (!BOComma->isCommaOp())
43         break;
44       Result = BOComma->getRHS();
45     }
46 
47     return Result != E && Matcher(Result);
48   };
49 
50   // The 'ConditionalOperatorM' matches on `<anything> ? <expr> : <expr>`.
51   // This matching must be recursive because `<expr>` can be anything resolving
52   // to the `InnerMatcher`, for example another conditional operator.
53   // The edge-case `BaseClass &b = <cond> ? DerivedVar1 : DerivedVar2;`
54   // is handled, too. The implicit cast happens outside of the conditional.
55   // This is matched by `IgnoreDerivedToBase(canResolveToExpr(InnerMatcher))`
56   // below.
57   const auto ConditionalOperatorM = [Target](const Expr *E) {
58     if (const auto *OP = dyn_cast<ConditionalOperator>(E)) {
59       if (const auto *TE = OP->getTrueExpr()->IgnoreParens())
60         if (canExprResolveTo(TE, Target))
61           return true;
62       if (const auto *FE = OP->getFalseExpr()->IgnoreParens())
63         if (canExprResolveTo(FE, Target))
64           return true;
65     }
66     return false;
67   };
68 
69   const auto ElvisOperator = [Target](const Expr *E) {
70     if (const auto *OP = dyn_cast<BinaryConditionalOperator>(E)) {
71       if (const auto *TE = OP->getTrueExpr()->IgnoreParens())
72         if (canExprResolveTo(TE, Target))
73           return true;
74       if (const auto *FE = OP->getFalseExpr()->IgnoreParens())
75         if (canExprResolveTo(FE, Target))
76           return true;
77     }
78     return false;
79   };
80 
81   const Expr *SourceExprP = Source->IgnoreParens();
82   return IgnoreDerivedToBase(SourceExprP,
83                              [&](const Expr *E) {
84                                return E == Target || ConditionalOperatorM(E) ||
85                                       ElvisOperator(E);
86                              }) ||
87          EvalCommaExpr(SourceExprP, [&](const Expr *E) {
88            return IgnoreDerivedToBase(
89                E->IgnoreParens(), [&](const Expr *EE) { return EE == Target; });
90          });
91 }
92 
93 namespace {
94 
95 AST_MATCHER_P(LambdaExpr, hasCaptureInit, const Expr *, E) {
96   return llvm::is_contained(Node.capture_inits(), E);
97 }
98 
99 AST_MATCHER_P(CXXForRangeStmt, hasRangeStmt,
100               ast_matchers::internal::Matcher<DeclStmt>, InnerMatcher) {
101   const DeclStmt *const Range = Node.getRangeStmt();
102   return InnerMatcher.matches(*Range, Finder, Builder);
103 }
104 
105 AST_MATCHER_P(Stmt, canResolveToExpr, const Stmt *, Inner) {
106   auto *Exp = dyn_cast<Expr>(&Node);
107   if (!Exp)
108     return true;
109   auto *Target = dyn_cast<Expr>(Inner);
110   if (!Target)
111     return false;
112   return canExprResolveTo(Exp, Target);
113 }
114 
115 // Similar to 'hasAnyArgument', but does not work because 'InitListExpr' does
116 // not have the 'arguments()' method.
117 AST_MATCHER_P(InitListExpr, hasAnyInit, ast_matchers::internal::Matcher<Expr>,
118               InnerMatcher) {
119   for (const Expr *Arg : Node.inits()) {
120     ast_matchers::internal::BoundNodesTreeBuilder Result(*Builder);
121     if (InnerMatcher.matches(*Arg, Finder, &Result)) {
122       *Builder = std::move(Result);
123       return true;
124     }
125   }
126   return false;
127 }
128 
129 const ast_matchers::internal::VariadicDynCastAllOfMatcher<Stmt, CXXTypeidExpr>
130     cxxTypeidExpr;
131 
132 AST_MATCHER(CXXTypeidExpr, isPotentiallyEvaluated) {
133   return Node.isPotentiallyEvaluated();
134 }
135 
136 AST_MATCHER(CXXMemberCallExpr, isConstCallee) {
137   const Decl *CalleeDecl = Node.getCalleeDecl();
138   const auto *VD = dyn_cast_or_null<ValueDecl>(CalleeDecl);
139   if (!VD)
140     return false;
141   const QualType T = VD->getType().getCanonicalType();
142   const auto *MPT = dyn_cast<MemberPointerType>(T);
143   const auto *FPT = MPT ? cast<FunctionProtoType>(MPT->getPointeeType())
144                         : dyn_cast<FunctionProtoType>(T);
145   if (!FPT)
146     return false;
147   return FPT->isConst();
148 }
149 
150 AST_MATCHER_P(GenericSelectionExpr, hasControllingExpr,
151               ast_matchers::internal::Matcher<Expr>, InnerMatcher) {
152   if (Node.isTypePredicate())
153     return false;
154   return InnerMatcher.matches(*Node.getControllingExpr(), Finder, Builder);
155 }
156 
157 template <typename T>
158 ast_matchers::internal::Matcher<T>
159 findFirst(const ast_matchers::internal::Matcher<T> &Matcher) {
160   return anyOf(Matcher, hasDescendant(Matcher));
161 }
162 
163 const auto nonConstReferenceType = [] {
164   return hasUnqualifiedDesugaredType(
165       referenceType(pointee(unless(isConstQualified()))));
166 };
167 
168 const auto nonConstPointerType = [] {
169   return hasUnqualifiedDesugaredType(
170       pointerType(pointee(unless(isConstQualified()))));
171 };
172 
173 const auto isMoveOnly = [] {
174   return cxxRecordDecl(
175       hasMethod(cxxConstructorDecl(isMoveConstructor(), unless(isDeleted()))),
176       hasMethod(cxxMethodDecl(isMoveAssignmentOperator(), unless(isDeleted()))),
177       unless(anyOf(hasMethod(cxxConstructorDecl(isCopyConstructor(),
178                                                 unless(isDeleted()))),
179                    hasMethod(cxxMethodDecl(isCopyAssignmentOperator(),
180                                            unless(isDeleted()))))));
181 };
182 
183 template <class T> struct NodeID;
184 template <> struct NodeID<Expr> { static constexpr StringRef value = "expr"; };
185 template <> struct NodeID<Decl> { static constexpr StringRef value = "decl"; };
186 constexpr StringRef NodeID<Expr>::value;
187 constexpr StringRef NodeID<Decl>::value;
188 
189 template <class T, class F = const Stmt *(ExprMutationAnalyzer::*)(const T *)>
190 const Stmt *tryEachMatch(ArrayRef<ast_matchers::BoundNodes> Matches,
191                          ExprMutationAnalyzer *Analyzer, F Finder) {
192   const StringRef ID = NodeID<T>::value;
193   for (const auto &Nodes : Matches) {
194     if (const Stmt *S = (Analyzer->*Finder)(Nodes.getNodeAs<T>(ID)))
195       return S;
196   }
197   return nullptr;
198 }
199 
200 } // namespace
201 
202 const Stmt *ExprMutationAnalyzer::findMutation(const Expr *Exp) {
203   return findMutationMemoized(Exp,
204                               {&ExprMutationAnalyzer::findDirectMutation,
205                                &ExprMutationAnalyzer::findMemberMutation,
206                                &ExprMutationAnalyzer::findArrayElementMutation,
207                                &ExprMutationAnalyzer::findCastMutation,
208                                &ExprMutationAnalyzer::findRangeLoopMutation,
209                                &ExprMutationAnalyzer::findReferenceMutation,
210                                &ExprMutationAnalyzer::findFunctionArgMutation},
211                               Results);
212 }
213 
214 const Stmt *ExprMutationAnalyzer::findMutation(const Decl *Dec) {
215   return tryEachDeclRef(Dec, &ExprMutationAnalyzer::findMutation);
216 }
217 
218 const Stmt *ExprMutationAnalyzer::findPointeeMutation(const Expr *Exp) {
219   return findMutationMemoized(Exp, {/*TODO*/}, PointeeResults);
220 }
221 
222 const Stmt *ExprMutationAnalyzer::findPointeeMutation(const Decl *Dec) {
223   return tryEachDeclRef(Dec, &ExprMutationAnalyzer::findPointeeMutation);
224 }
225 
226 const Stmt *ExprMutationAnalyzer::findMutationMemoized(
227     const Expr *Exp, llvm::ArrayRef<MutationFinder> Finders,
228     ResultMap &MemoizedResults) {
229   const auto Memoized = MemoizedResults.find(Exp);
230   if (Memoized != MemoizedResults.end())
231     return Memoized->second;
232 
233   if (isUnevaluated(Exp))
234     return MemoizedResults[Exp] = nullptr;
235 
236   for (const auto &Finder : Finders) {
237     if (const Stmt *S = (this->*Finder)(Exp))
238       return MemoizedResults[Exp] = S;
239   }
240 
241   return MemoizedResults[Exp] = nullptr;
242 }
243 
244 const Stmt *ExprMutationAnalyzer::tryEachDeclRef(const Decl *Dec,
245                                                  MutationFinder Finder) {
246   const auto Refs = match(
247       findAll(
248           declRefExpr(to(
249                           // `Dec` or a binding if `Dec` is a decomposition.
250                           anyOf(equalsNode(Dec),
251                                 bindingDecl(forDecomposition(equalsNode(Dec))))
252                           //
253                           ))
254               .bind(NodeID<Expr>::value)),
255       Stm, Context);
256   for (const auto &RefNodes : Refs) {
257     const auto *E = RefNodes.getNodeAs<Expr>(NodeID<Expr>::value);
258     if ((this->*Finder)(E))
259       return E;
260   }
261   return nullptr;
262 }
263 
264 bool ExprMutationAnalyzer::isUnevaluated(const Stmt *Exp, const Stmt &Stm,
265                                          ASTContext &Context) {
266   return selectFirst<Stmt>(
267              NodeID<Expr>::value,
268              match(
269                  findFirst(
270                      stmt(canResolveToExpr(Exp),
271                           anyOf(
272                               // `Exp` is part of the underlying expression of
273                               // decltype/typeof if it has an ancestor of
274                               // typeLoc.
275                               hasAncestor(typeLoc(unless(
276                                   hasAncestor(unaryExprOrTypeTraitExpr())))),
277                               hasAncestor(expr(anyOf(
278                                   // `UnaryExprOrTypeTraitExpr` is unevaluated
279                                   // unless it's sizeof on VLA.
280                                   unaryExprOrTypeTraitExpr(unless(sizeOfExpr(
281                                       hasArgumentOfType(variableArrayType())))),
282                                   // `CXXTypeidExpr` is unevaluated unless it's
283                                   // applied to an expression of glvalue of
284                                   // polymorphic class type.
285                                   cxxTypeidExpr(
286                                       unless(isPotentiallyEvaluated())),
287                                   // The controlling expression of
288                                   // `GenericSelectionExpr` is unevaluated.
289                                   genericSelectionExpr(hasControllingExpr(
290                                       hasDescendant(equalsNode(Exp)))),
291                                   cxxNoexceptExpr())))))
292                          .bind(NodeID<Expr>::value)),
293                  Stm, Context)) != nullptr;
294 }
295 
296 bool ExprMutationAnalyzer::isUnevaluated(const Expr *Exp) {
297   return isUnevaluated(Exp, Stm, Context);
298 }
299 
300 const Stmt *
301 ExprMutationAnalyzer::findExprMutation(ArrayRef<BoundNodes> Matches) {
302   return tryEachMatch<Expr>(Matches, this, &ExprMutationAnalyzer::findMutation);
303 }
304 
305 const Stmt *
306 ExprMutationAnalyzer::findDeclMutation(ArrayRef<BoundNodes> Matches) {
307   return tryEachMatch<Decl>(Matches, this, &ExprMutationAnalyzer::findMutation);
308 }
309 
310 const Stmt *ExprMutationAnalyzer::findExprPointeeMutation(
311     ArrayRef<ast_matchers::BoundNodes> Matches) {
312   return tryEachMatch<Expr>(Matches, this,
313                             &ExprMutationAnalyzer::findPointeeMutation);
314 }
315 
316 const Stmt *ExprMutationAnalyzer::findDeclPointeeMutation(
317     ArrayRef<ast_matchers::BoundNodes> Matches) {
318   return tryEachMatch<Decl>(Matches, this,
319                             &ExprMutationAnalyzer::findPointeeMutation);
320 }
321 
322 const Stmt *ExprMutationAnalyzer::findDirectMutation(const Expr *Exp) {
323   // LHS of any assignment operators.
324   const auto AsAssignmentLhs =
325       binaryOperator(isAssignmentOperator(), hasLHS(canResolveToExpr(Exp)));
326 
327   // Operand of increment/decrement operators.
328   const auto AsIncDecOperand =
329       unaryOperator(anyOf(hasOperatorName("++"), hasOperatorName("--")),
330                     hasUnaryOperand(canResolveToExpr(Exp)));
331 
332   // Invoking non-const member function.
333   // A member function is assumed to be non-const when it is unresolved.
334   const auto NonConstMethod = cxxMethodDecl(unless(isConst()));
335 
336   const auto AsNonConstThis = expr(anyOf(
337       cxxMemberCallExpr(on(canResolveToExpr(Exp)), unless(isConstCallee())),
338       cxxOperatorCallExpr(callee(NonConstMethod),
339                           hasArgument(0, canResolveToExpr(Exp))),
340       // In case of a templated type, calling overloaded operators is not
341       // resolved and modelled as `binaryOperator` on a dependent type.
342       // Such instances are considered a modification, because they can modify
343       // in different instantiations of the template.
344       binaryOperator(isTypeDependent(),
345                      hasEitherOperand(ignoringImpCasts(canResolveToExpr(Exp)))),
346       // Within class templates and member functions the member expression might
347       // not be resolved. In that case, the `callExpr` is considered to be a
348       // modification.
349       callExpr(callee(expr(anyOf(
350           unresolvedMemberExpr(hasObjectExpression(canResolveToExpr(Exp))),
351           cxxDependentScopeMemberExpr(
352               hasObjectExpression(canResolveToExpr(Exp))))))),
353       // Match on a call to a known method, but the call itself is type
354       // dependent (e.g. `vector<T> v; v.push(T{});` in a templated function).
355       callExpr(allOf(
356           isTypeDependent(),
357           callee(memberExpr(hasDeclaration(NonConstMethod),
358                             hasObjectExpression(canResolveToExpr(Exp))))))));
359 
360   // Taking address of 'Exp'.
361   // We're assuming 'Exp' is mutated as soon as its address is taken, though in
362   // theory we can follow the pointer and see whether it escaped `Stm` or is
363   // dereferenced and then mutated. This is left for future improvements.
364   const auto AsAmpersandOperand =
365       unaryOperator(hasOperatorName("&"),
366                     // A NoOp implicit cast is adding const.
367                     unless(hasParent(implicitCastExpr(hasCastKind(CK_NoOp)))),
368                     hasUnaryOperand(canResolveToExpr(Exp)));
369   const auto AsPointerFromArrayDecay = castExpr(
370       hasCastKind(CK_ArrayToPointerDecay),
371       unless(hasParent(arraySubscriptExpr())), has(canResolveToExpr(Exp)));
372   // Treat calling `operator->()` of move-only classes as taking address.
373   // These are typically smart pointers with unique ownership so we treat
374   // mutation of pointee as mutation of the smart pointer itself.
375   const auto AsOperatorArrowThis = cxxOperatorCallExpr(
376       hasOverloadedOperatorName("->"),
377       callee(
378           cxxMethodDecl(ofClass(isMoveOnly()), returns(nonConstPointerType()))),
379       argumentCountIs(1), hasArgument(0, canResolveToExpr(Exp)));
380 
381   // Used as non-const-ref argument when calling a function.
382   // An argument is assumed to be non-const-ref when the function is unresolved.
383   // Instantiated template functions are not handled here but in
384   // findFunctionArgMutation which has additional smarts for handling forwarding
385   // references.
386   const auto NonConstRefParam = forEachArgumentWithParamType(
387       anyOf(canResolveToExpr(Exp),
388             memberExpr(hasObjectExpression(canResolveToExpr(Exp)))),
389       nonConstReferenceType());
390   const auto NotInstantiated = unless(hasDeclaration(isInstantiated()));
391   const auto TypeDependentCallee =
392       callee(expr(anyOf(unresolvedLookupExpr(), unresolvedMemberExpr(),
393                         cxxDependentScopeMemberExpr(),
394                         hasType(templateTypeParmType()), isTypeDependent())));
395 
396   const auto AsNonConstRefArg = anyOf(
397       callExpr(NonConstRefParam, NotInstantiated),
398       cxxConstructExpr(NonConstRefParam, NotInstantiated),
399       callExpr(TypeDependentCallee, hasAnyArgument(canResolveToExpr(Exp))),
400       cxxUnresolvedConstructExpr(hasAnyArgument(canResolveToExpr(Exp))),
401       // Previous False Positive in the following Code:
402       // `template <typename T> void f() { int i = 42; new Type<T>(i); }`
403       // Where the constructor of `Type` takes its argument as reference.
404       // The AST does not resolve in a `cxxConstructExpr` because it is
405       // type-dependent.
406       parenListExpr(hasDescendant(expr(canResolveToExpr(Exp)))),
407       // If the initializer is for a reference type, there is no cast for
408       // the variable. Values are cast to RValue first.
409       initListExpr(hasAnyInit(expr(canResolveToExpr(Exp)))));
410 
411   // Captured by a lambda by reference.
412   // If we're initializing a capture with 'Exp' directly then we're initializing
413   // a reference capture.
414   // For value captures there will be an ImplicitCastExpr <LValueToRValue>.
415   const auto AsLambdaRefCaptureInit = lambdaExpr(hasCaptureInit(Exp));
416 
417   // Returned as non-const-ref.
418   // If we're returning 'Exp' directly then it's returned as non-const-ref.
419   // For returning by value there will be an ImplicitCastExpr <LValueToRValue>.
420   // For returning by const-ref there will be an ImplicitCastExpr <NoOp> (for
421   // adding const.)
422   const auto AsNonConstRefReturn =
423       returnStmt(hasReturnValue(canResolveToExpr(Exp)));
424 
425   // It is used as a non-const-reference for initalizing a range-for loop.
426   const auto AsNonConstRefRangeInit = cxxForRangeStmt(hasRangeInit(declRefExpr(
427       allOf(canResolveToExpr(Exp), hasType(nonConstReferenceType())))));
428 
429   const auto Matches = match(
430       traverse(
431           TK_AsIs,
432           findFirst(stmt(anyOf(AsAssignmentLhs, AsIncDecOperand, AsNonConstThis,
433                                AsAmpersandOperand, AsPointerFromArrayDecay,
434                                AsOperatorArrowThis, AsNonConstRefArg,
435                                AsLambdaRefCaptureInit, AsNonConstRefReturn,
436                                AsNonConstRefRangeInit))
437                         .bind("stmt"))),
438       Stm, Context);
439   return selectFirst<Stmt>("stmt", Matches);
440 }
441 
442 const Stmt *ExprMutationAnalyzer::findMemberMutation(const Expr *Exp) {
443   // Check whether any member of 'Exp' is mutated.
444   const auto MemberExprs = match(
445       findAll(expr(anyOf(memberExpr(hasObjectExpression(canResolveToExpr(Exp))),
446                          cxxDependentScopeMemberExpr(
447                              hasObjectExpression(canResolveToExpr(Exp))),
448                          binaryOperator(hasOperatorName(".*"),
449                                         hasLHS(equalsNode(Exp)))))
450                   .bind(NodeID<Expr>::value)),
451       Stm, Context);
452   return findExprMutation(MemberExprs);
453 }
454 
455 const Stmt *ExprMutationAnalyzer::findArrayElementMutation(const Expr *Exp) {
456   // Check whether any element of an array is mutated.
457   const auto SubscriptExprs = match(
458       findAll(arraySubscriptExpr(
459                   anyOf(hasBase(canResolveToExpr(Exp)),
460                         hasBase(implicitCastExpr(allOf(
461                             hasCastKind(CK_ArrayToPointerDecay),
462                             hasSourceExpression(canResolveToExpr(Exp)))))))
463                   .bind(NodeID<Expr>::value)),
464       Stm, Context);
465   return findExprMutation(SubscriptExprs);
466 }
467 
468 const Stmt *ExprMutationAnalyzer::findCastMutation(const Expr *Exp) {
469   // If the 'Exp' is explicitly casted to a non-const reference type the
470   // 'Exp' is considered to be modified.
471   const auto ExplicitCast =
472       match(findFirst(stmt(castExpr(hasSourceExpression(canResolveToExpr(Exp)),
473                                     explicitCastExpr(hasDestinationType(
474                                         nonConstReferenceType()))))
475                           .bind("stmt")),
476             Stm, Context);
477 
478   if (const auto *CastStmt = selectFirst<Stmt>("stmt", ExplicitCast))
479     return CastStmt;
480 
481   // If 'Exp' is casted to any non-const reference type, check the castExpr.
482   const auto Casts = match(
483       findAll(expr(castExpr(hasSourceExpression(canResolveToExpr(Exp)),
484                             anyOf(explicitCastExpr(hasDestinationType(
485                                       nonConstReferenceType())),
486                                   implicitCastExpr(hasImplicitDestinationType(
487                                       nonConstReferenceType())))))
488                   .bind(NodeID<Expr>::value)),
489       Stm, Context);
490 
491   if (const Stmt *S = findExprMutation(Casts))
492     return S;
493   // Treat std::{move,forward} as cast.
494   const auto Calls =
495       match(findAll(callExpr(callee(namedDecl(
496                                  hasAnyName("::std::move", "::std::forward"))),
497                              hasArgument(0, canResolveToExpr(Exp)))
498                         .bind("expr")),
499             Stm, Context);
500   return findExprMutation(Calls);
501 }
502 
503 const Stmt *ExprMutationAnalyzer::findRangeLoopMutation(const Expr *Exp) {
504   // Keep the ordering for the specific initialization matches to happen first,
505   // because it is cheaper to match all potential modifications of the loop
506   // variable.
507 
508   // The range variable is a reference to a builtin array. In that case the
509   // array is considered modified if the loop-variable is a non-const reference.
510   const auto DeclStmtToNonRefToArray = declStmt(hasSingleDecl(varDecl(hasType(
511       hasUnqualifiedDesugaredType(referenceType(pointee(arrayType())))))));
512   const auto RefToArrayRefToElements = match(
513       findFirst(stmt(cxxForRangeStmt(
514                          hasLoopVariable(
515                              varDecl(anyOf(hasType(nonConstReferenceType()),
516                                            hasType(nonConstPointerType())))
517                                  .bind(NodeID<Decl>::value)),
518                          hasRangeStmt(DeclStmtToNonRefToArray),
519                          hasRangeInit(canResolveToExpr(Exp))))
520                     .bind("stmt")),
521       Stm, Context);
522 
523   if (const auto *BadRangeInitFromArray =
524           selectFirst<Stmt>("stmt", RefToArrayRefToElements))
525     return BadRangeInitFromArray;
526 
527   // Small helper to match special cases in range-for loops.
528   //
529   // It is possible that containers do not provide a const-overload for their
530   // iterator accessors. If this is the case, the variable is used non-const
531   // no matter what happens in the loop. This requires special detection as it
532   // is then faster to find all mutations of the loop variable.
533   // It aims at a different modification as well.
534   const auto HasAnyNonConstIterator =
535       anyOf(allOf(hasMethod(allOf(hasName("begin"), unless(isConst()))),
536                   unless(hasMethod(allOf(hasName("begin"), isConst())))),
537             allOf(hasMethod(allOf(hasName("end"), unless(isConst()))),
538                   unless(hasMethod(allOf(hasName("end"), isConst())))));
539 
540   const auto DeclStmtToNonConstIteratorContainer = declStmt(
541       hasSingleDecl(varDecl(hasType(hasUnqualifiedDesugaredType(referenceType(
542           pointee(hasDeclaration(cxxRecordDecl(HasAnyNonConstIterator)))))))));
543 
544   const auto RefToContainerBadIterators = match(
545       findFirst(stmt(cxxForRangeStmt(allOf(
546                          hasRangeStmt(DeclStmtToNonConstIteratorContainer),
547                          hasRangeInit(canResolveToExpr(Exp)))))
548                     .bind("stmt")),
549       Stm, Context);
550 
551   if (const auto *BadIteratorsContainer =
552           selectFirst<Stmt>("stmt", RefToContainerBadIterators))
553     return BadIteratorsContainer;
554 
555   // If range for looping over 'Exp' with a non-const reference loop variable,
556   // check all declRefExpr of the loop variable.
557   const auto LoopVars =
558       match(findAll(cxxForRangeStmt(
559                 hasLoopVariable(varDecl(hasType(nonConstReferenceType()))
560                                     .bind(NodeID<Decl>::value)),
561                 hasRangeInit(canResolveToExpr(Exp)))),
562             Stm, Context);
563   return findDeclMutation(LoopVars);
564 }
565 
566 const Stmt *ExprMutationAnalyzer::findReferenceMutation(const Expr *Exp) {
567   // Follow non-const reference returned by `operator*()` of move-only classes.
568   // These are typically smart pointers with unique ownership so we treat
569   // mutation of pointee as mutation of the smart pointer itself.
570   const auto Ref = match(
571       findAll(cxxOperatorCallExpr(
572                   hasOverloadedOperatorName("*"),
573                   callee(cxxMethodDecl(ofClass(isMoveOnly()),
574                                        returns(nonConstReferenceType()))),
575                   argumentCountIs(1), hasArgument(0, canResolveToExpr(Exp)))
576                   .bind(NodeID<Expr>::value)),
577       Stm, Context);
578   if (const Stmt *S = findExprMutation(Ref))
579     return S;
580 
581   // If 'Exp' is bound to a non-const reference, check all declRefExpr to that.
582   const auto Refs = match(
583       stmt(forEachDescendant(
584           varDecl(hasType(nonConstReferenceType()),
585                   hasInitializer(anyOf(
586                       canResolveToExpr(Exp),
587                       memberExpr(hasObjectExpression(canResolveToExpr(Exp))))),
588                   hasParent(declStmt().bind("stmt")),
589                   // Don't follow the reference in range statement, we've
590                   // handled that separately.
591                   unless(hasParent(declStmt(hasParent(cxxForRangeStmt(
592                       hasRangeStmt(equalsBoundNode("stmt"))))))))
593               .bind(NodeID<Decl>::value))),
594       Stm, Context);
595   return findDeclMutation(Refs);
596 }
597 
598 const Stmt *ExprMutationAnalyzer::findFunctionArgMutation(const Expr *Exp) {
599   const auto NonConstRefParam = forEachArgumentWithParam(
600       canResolveToExpr(Exp),
601       parmVarDecl(hasType(nonConstReferenceType())).bind("parm"));
602   const auto IsInstantiated = hasDeclaration(isInstantiated());
603   const auto FuncDecl = hasDeclaration(functionDecl().bind("func"));
604   const auto Matches = match(
605       traverse(
606           TK_AsIs,
607           findAll(
608               expr(anyOf(callExpr(NonConstRefParam, IsInstantiated, FuncDecl,
609                                   unless(callee(namedDecl(hasAnyName(
610                                       "::std::move", "::std::forward"))))),
611                          cxxConstructExpr(NonConstRefParam, IsInstantiated,
612                                           FuncDecl)))
613                   .bind(NodeID<Expr>::value))),
614       Stm, Context);
615   for (const auto &Nodes : Matches) {
616     const auto *Exp = Nodes.getNodeAs<Expr>(NodeID<Expr>::value);
617     const auto *Func = Nodes.getNodeAs<FunctionDecl>("func");
618     if (!Func->getBody() || !Func->getPrimaryTemplate())
619       return Exp;
620 
621     const auto *Parm = Nodes.getNodeAs<ParmVarDecl>("parm");
622     const ArrayRef<ParmVarDecl *> AllParams =
623         Func->getPrimaryTemplate()->getTemplatedDecl()->parameters();
624     QualType ParmType =
625         AllParams[std::min<size_t>(Parm->getFunctionScopeIndex(),
626                                    AllParams.size() - 1)]
627             ->getType();
628     if (const auto *T = ParmType->getAs<PackExpansionType>())
629       ParmType = T->getPattern();
630 
631     // If param type is forwarding reference, follow into the function
632     // definition and see whether the param is mutated inside.
633     if (const auto *RefType = ParmType->getAs<RValueReferenceType>()) {
634       if (!RefType->getPointeeType().getQualifiers() &&
635           RefType->getPointeeType()->getAs<TemplateTypeParmType>()) {
636         std::unique_ptr<FunctionParmMutationAnalyzer> &Analyzer =
637             FuncParmAnalyzer[Func];
638         if (!Analyzer)
639           Analyzer.reset(new FunctionParmMutationAnalyzer(*Func, Context));
640         if (Analyzer->findMutation(Parm))
641           return Exp;
642         continue;
643       }
644     }
645     // Not forwarding reference.
646     return Exp;
647   }
648   return nullptr;
649 }
650 
651 FunctionParmMutationAnalyzer::FunctionParmMutationAnalyzer(
652     const FunctionDecl &Func, ASTContext &Context)
653     : BodyAnalyzer(*Func.getBody(), Context) {
654   if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(&Func)) {
655     // CXXCtorInitializer might also mutate Param but they're not part of
656     // function body, check them eagerly here since they're typically trivial.
657     for (const CXXCtorInitializer *Init : Ctor->inits()) {
658       ExprMutationAnalyzer InitAnalyzer(*Init->getInit(), Context);
659       for (const ParmVarDecl *Parm : Ctor->parameters()) {
660         if (Results.contains(Parm))
661           continue;
662         if (const Stmt *S = InitAnalyzer.findMutation(Parm))
663           Results[Parm] = S;
664       }
665     }
666   }
667 }
668 
669 const Stmt *
670 FunctionParmMutationAnalyzer::findMutation(const ParmVarDecl *Parm) {
671   const auto Memoized = Results.find(Parm);
672   if (Memoized != Results.end())
673     return Memoized->second;
674 
675   if (const Stmt *S = BodyAnalyzer.findMutation(Parm))
676     return Results[Parm] = S;
677 
678   return Results[Parm] = nullptr;
679 }
680 
681 } // namespace clang
682