Coverage Report

Created: 2022-07-16 07:03

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