Coverage Report

Created: 2021-09-21 08:58

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