Coverage Report

Created: 2020-11-24 06:42

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