clang 22.0.0git
ExprMutationAnalyzer.cpp
Go to the documentation of this file.
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//===----------------------------------------------------------------------===//
9#include "clang/AST/Expr.h"
11#include "clang/AST/Stmt.h"
15#include "llvm/ADT/STLExtras.h"
16
17namespace clang {
18using namespace ast_matchers;
19
20// Check if result of Source expression could be a Target expression.
21// Checks:
22// - Implicit Casts
23// - Binary Operators
24// - ConditionalOperator
25// - BinaryConditionalOperator
26static bool canExprResolveTo(const Expr *Source, const Expr *Target) {
27 const auto IgnoreDerivedToBase = [](const Expr *E, auto Matcher) {
28 if (Matcher(E))
29 return true;
30 if (const auto *Cast = dyn_cast<ImplicitCastExpr>(E)) {
31 if ((Cast->getCastKind() == CK_DerivedToBase ||
32 Cast->getCastKind() == CK_UncheckedDerivedToBase) &&
33 Matcher(Cast->getSubExpr()))
34 return true;
35 }
36 return false;
37 };
38
39 const auto EvalCommaExpr = [](const Expr *E, auto Matcher) {
40 const Expr *Result = E;
41 while (const auto *BOComma =
42 dyn_cast_or_null<BinaryOperator>(Result->IgnoreParens())) {
43 if (!BOComma->isCommaOp())
44 break;
45 Result = BOComma->getRHS();
46 }
47
48 return Result != E && Matcher(Result);
49 };
50
51 // The 'ConditionalOperatorM' matches on `<anything> ? <expr> : <expr>`.
52 // This matching must be recursive because `<expr>` can be anything resolving
53 // to the `InnerMatcher`, for example another conditional operator.
54 // The edge-case `BaseClass &b = <cond> ? DerivedVar1 : DerivedVar2;`
55 // is handled, too. The implicit cast happens outside of the conditional.
56 // This is matched by `IgnoreDerivedToBase(canResolveToExpr(InnerMatcher))`
57 // below.
58 const auto ConditionalOperatorM = [Target](const Expr *E) {
59 if (const auto *CO = dyn_cast<AbstractConditionalOperator>(E)) {
60 const auto *TE = CO->getTrueExpr()->IgnoreParens();
61 if (TE && canExprResolveTo(TE, Target))
62 return true;
63 const auto *FE = CO->getFalseExpr()->IgnoreParens();
64 if (FE && canExprResolveTo(FE, Target))
65 return true;
66 }
67 return false;
68 };
69
70 const Expr *SourceExprP = Source->IgnoreParens();
71 return IgnoreDerivedToBase(SourceExprP,
72 [&](const Expr *E) {
73 return E == Target || ConditionalOperatorM(E);
74 }) ||
75 EvalCommaExpr(SourceExprP, [&](const Expr *E) {
76 return IgnoreDerivedToBase(
77 E->IgnoreParens(), [&](const Expr *EE) { return EE == Target; });
78 });
79}
80
81namespace {
82
83// `ArraySubscriptExpr` can switch base and idx, e.g. `a[4]` is the same as
84// `4[a]`. When type is dependent, we conservatively assume both sides are base.
85AST_MATCHER_P(ArraySubscriptExpr, hasBaseConservative,
86 ast_matchers::internal::Matcher<Expr>, InnerMatcher) {
87 if (Node.isTypeDependent()) {
88 return InnerMatcher.matches(*Node.getLHS(), Finder, Builder) ||
89 InnerMatcher.matches(*Node.getRHS(), Finder, Builder);
90 }
91 return InnerMatcher.matches(*Node.getBase(), Finder, Builder);
92}
93
94AST_MATCHER(Type, isDependentType) { return Node.isDependentType(); }
95
96AST_MATCHER_P(LambdaExpr, hasCaptureInit, const Expr *, E) {
97 return llvm::is_contained(Node.capture_inits(), E);
98}
99
100AST_MATCHER_P(CXXForRangeStmt, hasRangeStmt,
101 ast_matchers::internal::Matcher<DeclStmt>, InnerMatcher) {
102 const DeclStmt *const Range = Node.getRangeStmt();
103 return InnerMatcher.matches(*Range, Finder, Builder);
104}
105
106AST_MATCHER_P(Stmt, canResolveToExpr, const Stmt *, Inner) {
107 auto *Exp = dyn_cast<Expr>(&Node);
108 if (!Exp)
109 return true;
110 auto *Target = dyn_cast<Expr>(Inner);
111 if (!Target)
112 return false;
113 return canExprResolveTo(Exp, Target);
114}
115
116// use class member to store data can reduce stack usage to avoid stack overflow
117// when recursive call.
118class ExprPointeeResolve {
119 const Expr *T;
120
121 bool resolveExpr(const Expr *E) {
122 if (E == nullptr)
123 return false;
124 if (E == T)
125 return true;
126
127 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
128 if (BO->isAdditiveOp())
129 return (resolveExpr(BO->getLHS()) || resolveExpr(BO->getRHS()));
130 if (BO->isCommaOp())
131 return resolveExpr(BO->getRHS());
132 return false;
133 }
134
135 if (const auto *PE = dyn_cast<ParenExpr>(E))
136 return resolveExpr(PE->getSubExpr());
137
138 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
139 if (UO->getOpcode() == UO_AddrOf)
140 return resolveExpr(UO->getSubExpr());
141 }
142
143 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
144 // only implicit cast needs to be treated as resolvable.
145 // explicit cast will be checked in `findPointeeToNonConst`
146 const CastKind kind = ICE->getCastKind();
147 if (kind == CK_LValueToRValue || kind == CK_DerivedToBase ||
148 kind == CK_UncheckedDerivedToBase ||
149 (kind == CK_NoOp && (ICE->getType() == ICE->getSubExpr()->getType())))
150 return resolveExpr(ICE->getSubExpr());
151 return false;
152 }
153
154 if (const auto *ACE = dyn_cast<AbstractConditionalOperator>(E))
155 return resolve(ACE->getTrueExpr()) || resolve(ACE->getFalseExpr());
156
157 return false;
158 }
159
160public:
161 ExprPointeeResolve(const Expr *T) : T(T) {}
162 bool resolve(const Expr *S) { return resolveExpr(S); }
163};
164
165AST_MATCHER_P(Stmt, canResolveToExprPointee, const Stmt *, T) {
166 auto *Exp = dyn_cast<Expr>(&Node);
167 if (!Exp)
168 return true;
169 auto *Target = dyn_cast<Expr>(T);
170 if (!Target)
171 return false;
172 return ExprPointeeResolve{Target}.resolve(Exp);
173}
174
175// Similar to 'hasAnyArgument', but does not work because 'InitListExpr' does
176// not have the 'arguments()' method.
177AST_MATCHER_P(InitListExpr, hasAnyInit, ast_matchers::internal::Matcher<Expr>,
178 InnerMatcher) {
179 for (const Expr *Arg : Node.inits()) {
180 if (Arg == nullptr)
181 continue;
182 ast_matchers::internal::BoundNodesTreeBuilder Result(*Builder);
183 if (InnerMatcher.matches(*Arg, Finder, &Result)) {
184 *Builder = std::move(Result);
185 return true;
186 }
187 }
188 return false;
189}
190
191const ast_matchers::internal::VariadicDynCastAllOfMatcher<Stmt, CXXTypeidExpr>
192 cxxTypeidExpr;
193
194AST_MATCHER(CXXTypeidExpr, isPotentiallyEvaluated) {
195 return Node.isPotentiallyEvaluated();
196}
197
198AST_MATCHER(CXXMemberCallExpr, isConstCallee) {
199 const Decl *CalleeDecl = Node.getCalleeDecl();
200 const auto *VD = dyn_cast_or_null<ValueDecl>(CalleeDecl);
201 if (!VD)
202 return false;
203 const QualType T = VD->getType().getCanonicalType();
204 const auto *MPT = dyn_cast<MemberPointerType>(T);
205 const auto *FPT = MPT ? cast<FunctionProtoType>(MPT->getPointeeType())
206 : dyn_cast<FunctionProtoType>(T);
207 if (!FPT)
208 return false;
209 return FPT->isConst();
210}
211
212AST_MATCHER_P(GenericSelectionExpr, hasControllingExpr,
213 ast_matchers::internal::Matcher<Expr>, InnerMatcher) {
214 if (Node.isTypePredicate())
215 return false;
216 return InnerMatcher.matches(*Node.getControllingExpr(), Finder, Builder);
217}
218
219template <typename T>
220ast_matchers::internal::Matcher<T>
221findFirst(const ast_matchers::internal::Matcher<T> &Matcher) {
222 return anyOf(Matcher, hasDescendant(Matcher));
223}
224
225const auto nonConstReferenceType = [] {
226 return hasUnqualifiedDesugaredType(
227 referenceType(pointee(unless(isConstQualified()))));
228};
229
230const auto nonConstPointerType = [] {
231 return hasUnqualifiedDesugaredType(
232 pointerType(pointee(unless(isConstQualified()))));
233};
234
235const auto isMoveOnly = [] {
236 return cxxRecordDecl(
237 hasMethod(cxxConstructorDecl(isMoveConstructor(), unless(isDeleted()))),
238 hasMethod(cxxMethodDecl(isMoveAssignmentOperator(), unless(isDeleted()))),
239 unless(anyOf(hasMethod(cxxConstructorDecl(isCopyConstructor(),
240 unless(isDeleted()))),
241 hasMethod(cxxMethodDecl(isCopyAssignmentOperator(),
242 unless(isDeleted()))))));
243};
244
245template <class T> struct NodeID;
246template <> struct NodeID<Expr> {
247 static constexpr StringRef value = "expr";
248};
249template <> struct NodeID<Decl> {
250 static constexpr StringRef value = "decl";
251};
252
253template <class T,
254 class F = const Stmt *(ExprMutationAnalyzer::Analyzer::*)(const T *)>
255const Stmt *tryEachMatch(ArrayRef<ast_matchers::BoundNodes> Matches,
256 ExprMutationAnalyzer::Analyzer *Analyzer, F Finder) {
257 const StringRef ID = NodeID<T>::value;
258 for (const auto &Nodes : Matches) {
259 if (const Stmt *S = (Analyzer->*Finder)(Nodes.getNodeAs<T>(ID)))
260 return S;
261 }
262 return nullptr;
263}
264
265} // namespace
266
268 return findMutationMemoized(
269 Exp,
270 {&ExprMutationAnalyzer::Analyzer::findDirectMutation,
271 &ExprMutationAnalyzer::Analyzer::findMemberMutation,
272 &ExprMutationAnalyzer::Analyzer::findArrayElementMutation,
273 &ExprMutationAnalyzer::Analyzer::findCastMutation,
274 &ExprMutationAnalyzer::Analyzer::findRangeLoopMutation,
275 &ExprMutationAnalyzer::Analyzer::findReferenceMutation,
276 &ExprMutationAnalyzer::Analyzer::findFunctionArgMutation},
277 Memorized.Results);
278}
279
283
284const Stmt *
286 return findMutationMemoized(
287 Exp,
288 {
289 &ExprMutationAnalyzer::Analyzer::findPointeeValueMutation,
290 &ExprMutationAnalyzer::Analyzer::findPointeeMemberMutation,
291 &ExprMutationAnalyzer::Analyzer::findPointeeToNonConst,
292 },
293 Memorized.PointeeResults);
294}
295
296const Stmt *
301
302const Stmt *ExprMutationAnalyzer::Analyzer::findMutationMemoized(
303 const Expr *Exp, llvm::ArrayRef<MutationFinder> Finders,
304 Memoized::ResultMap &MemoizedResults) {
305 // Assume Exp is not mutated before analyzing Exp.
306 auto [Memoized, Inserted] = MemoizedResults.try_emplace(Exp);
307 if (!Inserted)
308 return Memoized->second;
309
310 if (ExprMutationAnalyzer::isUnevaluated(Exp, Context))
311 return nullptr;
312
313 for (const auto &Finder : Finders) {
314 if (const Stmt *S = (this->*Finder)(Exp))
315 return MemoizedResults[Exp] = S;
316 }
317
318 return nullptr;
319}
320
321const Stmt *
322ExprMutationAnalyzer::Analyzer::tryEachDeclRef(const Decl *Dec,
323 MutationFinder Finder) {
324 const auto Refs = match(
325 findAll(
326 declRefExpr(to(
327 // `Dec` or a binding if `Dec` is a decomposition.
328 anyOf(equalsNode(Dec),
329 bindingDecl(forDecomposition(equalsNode(Dec))))
330 //
331 ))
332 .bind(NodeID<Expr>::value)),
333 Stm, Context);
334 for (const auto &RefNodes : Refs) {
335 const auto *E = RefNodes.getNodeAs<Expr>(NodeID<Expr>::value);
336 if ((this->*Finder)(E))
337 return E;
338 }
339 return nullptr;
340}
341
343 return !match(stmt(anyOf(
344 // `Exp` is part of the underlying expression of
345 // decltype/typeof if it has an ancestor of
346 // typeLoc.
350 // `UnaryExprOrTypeTraitExpr` is unevaluated
351 // unless it's sizeof on VLA.
353 hasArgumentOfType(variableArrayType())))),
354 // `CXXTypeidExpr` is unevaluated unless it's
355 // applied to an expression of glvalue of
356 // polymorphic class type.
357 cxxTypeidExpr(unless(isPotentiallyEvaluated())),
358 // The controlling expression of
359 // `GenericSelectionExpr` is unevaluated.
361 hasControllingExpr(hasDescendant(equalsNode(Stm)))),
362 cxxNoexceptExpr()))))),
363 *Stm, Context)
364 .empty();
365}
366
367const Stmt *
368ExprMutationAnalyzer::Analyzer::findExprMutation(ArrayRef<BoundNodes> Matches) {
369 return tryEachMatch<Expr>(Matches, this,
371}
372
373const Stmt *
374ExprMutationAnalyzer::Analyzer::findDeclMutation(ArrayRef<BoundNodes> Matches) {
375 return tryEachMatch<Decl>(Matches, this,
377}
378
379const Stmt *ExprMutationAnalyzer::Analyzer::findExprPointeeMutation(
380 ArrayRef<ast_matchers::BoundNodes> Matches) {
381 return tryEachMatch<Expr>(
383}
384
385const Stmt *ExprMutationAnalyzer::Analyzer::findDeclPointeeMutation(
386 ArrayRef<ast_matchers::BoundNodes> Matches) {
387 return tryEachMatch<Decl>(
389}
390
391const Stmt *
392ExprMutationAnalyzer::Analyzer::findDirectMutation(const Expr *Exp) {
393 // LHS of any assignment operators.
394 const auto AsAssignmentLhs =
395 binaryOperator(isAssignmentOperator(), hasLHS(canResolveToExpr(Exp)));
396
397 // Operand of increment/decrement operators.
398 const auto AsIncDecOperand =
399 unaryOperator(anyOf(hasOperatorName("++"), hasOperatorName("--")),
400 hasUnaryOperand(canResolveToExpr(Exp)));
401
402 // Invoking non-const member function.
403 // A member function is assumed to be non-const when it is unresolved.
404 const auto NonConstMethod = cxxMethodDecl(unless(isConst()));
405
406 const auto AsNonConstThis = expr(anyOf(
407 cxxMemberCallExpr(on(canResolveToExpr(Exp)), unless(isConstCallee())),
408 cxxOperatorCallExpr(callee(NonConstMethod),
409 hasArgument(0, canResolveToExpr(Exp))),
410 // In case of a templated type, calling overloaded operators is not
411 // resolved and modelled as `binaryOperator` on a dependent type.
412 // Such instances are considered a modification, because they can modify
413 // in different instantiations of the template.
414 binaryOperator(isTypeDependent(),
415 hasEitherOperand(ignoringImpCasts(canResolveToExpr(Exp)))),
416 // A fold expression may contain `Exp` as it's initializer.
417 // We don't know if the operator modifies `Exp` because the
418 // operator is type dependent due to the parameter pack.
419 cxxFoldExpr(hasFoldInit(ignoringImpCasts(canResolveToExpr(Exp)))),
420 // Within class templates and member functions the member expression might
421 // not be resolved. In that case, the `callExpr` is considered to be a
422 // modification.
423 callExpr(callee(expr(anyOf(
424 unresolvedMemberExpr(hasObjectExpression(canResolveToExpr(Exp))),
426 hasObjectExpression(canResolveToExpr(Exp))))))),
427 // Match on a call to a known method, but the call itself is type
428 // dependent (e.g. `vector<T> v; v.push(T{});` in a templated function).
430 isTypeDependent(),
431 callee(memberExpr(hasDeclaration(NonConstMethod),
432 hasObjectExpression(canResolveToExpr(Exp))))))));
433
434 // Taking address of 'Exp'.
435 // We're assuming 'Exp' is mutated as soon as its address is taken, though in
436 // theory we can follow the pointer and see whether it escaped `Stm` or is
437 // dereferenced and then mutated. This is left for future improvements.
438 const auto AsAmpersandOperand =
439 unaryOperator(hasOperatorName("&"),
440 // A NoOp implicit cast is adding const.
441 unless(hasParent(implicitCastExpr(hasCastKind(CK_NoOp)))),
442 hasUnaryOperand(canResolveToExpr(Exp)));
443 const auto AsPointerFromArrayDecay = castExpr(
444 hasCastKind(CK_ArrayToPointerDecay),
445 unless(hasParent(arraySubscriptExpr())), has(canResolveToExpr(Exp)));
446 // Treat calling `operator->()` of move-only classes as taking address.
447 // These are typically smart pointers with unique ownership so we treat
448 // mutation of pointee as mutation of the smart pointer itself.
449 const auto AsOperatorArrowThis = cxxOperatorCallExpr(
451 callee(
452 cxxMethodDecl(ofClass(isMoveOnly()), returns(nonConstPointerType()))),
453 argumentCountIs(1), hasArgument(0, canResolveToExpr(Exp)));
454
455 // Used as non-const-ref argument when calling a function.
456 // An argument is assumed to be non-const-ref when the function is unresolved.
457 // Instantiated template functions are not handled here but in
458 // findFunctionArgMutation which has additional smarts for handling forwarding
459 // references.
460 const auto NonConstRefParam = forEachArgumentWithParamType(
461 anyOf(canResolveToExpr(Exp),
463 hasObjectExpression(ignoringImpCasts(canResolveToExpr(Exp))))),
464 nonConstReferenceType());
465 const auto NotInstantiated = unless(hasDeclaration(isInstantiated()));
466
467 const auto AsNonConstRefArg =
468 anyOf(callExpr(NonConstRefParam, NotInstantiated),
469 cxxConstructExpr(NonConstRefParam, NotInstantiated),
470 // If the call is type-dependent, we can't properly process any
471 // argument because required type conversions and implicit casts
472 // will be inserted only after specialization.
473 callExpr(isTypeDependent(), hasAnyArgument(canResolveToExpr(Exp))),
474 cxxUnresolvedConstructExpr(hasAnyArgument(canResolveToExpr(Exp))),
475 // Previous False Positive in the following Code:
476 // `template <typename T> void f() { int i = 42; new Type<T>(i); }`
477 // Where the constructor of `Type` takes its argument as reference.
478 // The AST does not resolve in a `cxxConstructExpr` because it is
479 // type-dependent.
480 parenListExpr(hasDescendant(expr(canResolveToExpr(Exp)))),
481 // If the initializer is for a reference type, there is no cast for
482 // the variable. Values are cast to RValue first.
483 initListExpr(hasAnyInit(expr(canResolveToExpr(Exp)))));
484
485 // Captured by a lambda by reference.
486 // If we're initializing a capture with 'Exp' directly then we're initializing
487 // a reference capture.
488 // For value captures there will be an ImplicitCastExpr <LValueToRValue>.
489 const auto AsLambdaRefCaptureInit = lambdaExpr(hasCaptureInit(Exp));
490
491 // Returned as non-const-ref.
492 // If we're returning 'Exp' directly then it's returned as non-const-ref.
493 // For returning by value there will be an ImplicitCastExpr <LValueToRValue>.
494 // For returning by const-ref there will be an ImplicitCastExpr <NoOp> (for
495 // adding const.)
496 const auto AsNonConstRefReturn =
497 returnStmt(hasReturnValue(canResolveToExpr(Exp)));
498
499 // It is used as a non-const-reference for initializing a range-for loop.
500 const auto AsNonConstRefRangeInit = cxxForRangeStmt(hasRangeInit(declRefExpr(
501 allOf(canResolveToExpr(Exp), hasType(nonConstReferenceType())))));
502
503 const auto Matches = match(
504 traverse(
505 TK_AsIs,
506 findFirst(stmt(anyOf(AsAssignmentLhs, AsIncDecOperand, AsNonConstThis,
507 AsAmpersandOperand, AsPointerFromArrayDecay,
508 AsOperatorArrowThis, AsNonConstRefArg,
509 AsLambdaRefCaptureInit, AsNonConstRefReturn,
510 AsNonConstRefRangeInit))
511 .bind("stmt"))),
512 Stm, Context);
513 return selectFirst<Stmt>("stmt", Matches);
514}
515
516const Stmt *
517ExprMutationAnalyzer::Analyzer::findMemberMutation(const Expr *Exp) {
518 // Check whether any member of 'Exp' is mutated.
519 const auto MemberExprs = match(
520 findAll(expr(anyOf(memberExpr(hasObjectExpression(canResolveToExpr(Exp))),
522 hasObjectExpression(canResolveToExpr(Exp))),
523 binaryOperator(hasOperatorName(".*"),
524 hasLHS(equalsNode(Exp)))))
525 .bind(NodeID<Expr>::value)),
526 Stm, Context);
527 return findExprMutation(MemberExprs);
528}
529
530const Stmt *
531ExprMutationAnalyzer::Analyzer::findArrayElementMutation(const Expr *Exp) {
532 // Check whether any element of an array is mutated.
533 const auto SubscriptExprs = match(
535 anyOf(hasBaseConservative(canResolveToExpr(Exp)),
536 hasBaseConservative(implicitCastExpr(allOf(
537 hasCastKind(CK_ArrayToPointerDecay),
538 hasSourceExpression(canResolveToExpr(Exp)))))))
539 .bind(NodeID<Expr>::value)),
540 Stm, Context);
541 return findExprMutation(SubscriptExprs);
542}
543
544const Stmt *ExprMutationAnalyzer::Analyzer::findCastMutation(const Expr *Exp) {
545 // If the 'Exp' is explicitly casted to a non-const reference type the
546 // 'Exp' is considered to be modified.
547 const auto ExplicitCast =
548 match(findFirst(stmt(castExpr(hasSourceExpression(canResolveToExpr(Exp)),
549 explicitCastExpr(hasDestinationType(
550 nonConstReferenceType()))))
551 .bind("stmt")),
552 Stm, Context);
553
554 if (const auto *CastStmt = selectFirst<Stmt>("stmt", ExplicitCast))
555 return CastStmt;
556
557 // If 'Exp' is casted to any non-const reference type, check the castExpr.
558 const auto Casts = match(
559 findAll(expr(castExpr(hasSourceExpression(canResolveToExpr(Exp)),
560 anyOf(explicitCastExpr(hasDestinationType(
561 nonConstReferenceType())),
562 implicitCastExpr(hasImplicitDestinationType(
563 nonConstReferenceType())))))
564 .bind(NodeID<Expr>::value)),
565 Stm, Context);
566
567 if (const Stmt *S = findExprMutation(Casts))
568 return S;
569 // Treat std::{move,forward} as cast.
570 const auto Calls =
572 hasAnyName("::std::move", "::std::forward"))),
573 hasArgument(0, canResolveToExpr(Exp)))
574 .bind("expr")),
575 Stm, Context);
576 return findExprMutation(Calls);
577}
578
579const Stmt *
580ExprMutationAnalyzer::Analyzer::findRangeLoopMutation(const Expr *Exp) {
581 // Keep the ordering for the specific initialization matches to happen first,
582 // because it is cheaper to match all potential modifications of the loop
583 // variable.
584
585 // The range variable is a reference to a builtin array. In that case the
586 // array is considered modified if the loop-variable is a non-const reference.
587 const auto DeclStmtToNonRefToArray = declStmt(hasSingleDecl(varDecl(hasType(
588 hasUnqualifiedDesugaredType(referenceType(pointee(arrayType())))))));
589 const auto RefToArrayRefToElements = match(
590 findFirst(stmt(cxxForRangeStmt(
591 hasLoopVariable(
592 varDecl(anyOf(hasType(nonConstReferenceType()),
593 hasType(nonConstPointerType())))
594 .bind(NodeID<Decl>::value)),
595 hasRangeStmt(DeclStmtToNonRefToArray),
596 hasRangeInit(canResolveToExpr(Exp))))
597 .bind("stmt")),
598 Stm, Context);
599
600 if (const auto *BadRangeInitFromArray =
601 selectFirst<Stmt>("stmt", RefToArrayRefToElements))
602 return BadRangeInitFromArray;
603
604 // Small helper to match special cases in range-for loops.
605 //
606 // It is possible that containers do not provide a const-overload for their
607 // iterator accessors. If this is the case, the variable is used non-const
608 // no matter what happens in the loop. This requires special detection as it
609 // is then faster to find all mutations of the loop variable.
610 // It aims at a different modification as well.
611 const auto HasAnyNonConstIterator =
612 anyOf(allOf(hasMethod(allOf(hasName("begin"), unless(isConst()))),
613 unless(hasMethod(allOf(hasName("begin"), isConst())))),
614 allOf(hasMethod(allOf(hasName("end"), unless(isConst()))),
615 unless(hasMethod(allOf(hasName("end"), isConst())))));
616
617 const auto DeclStmtToNonConstIteratorContainer = declStmt(
618 hasSingleDecl(varDecl(hasType(hasUnqualifiedDesugaredType(referenceType(
619 pointee(hasDeclaration(cxxRecordDecl(HasAnyNonConstIterator)))))))));
620
621 const auto RefToContainerBadIterators = match(
622 findFirst(stmt(cxxForRangeStmt(allOf(
623 hasRangeStmt(DeclStmtToNonConstIteratorContainer),
624 hasRangeInit(canResolveToExpr(Exp)))))
625 .bind("stmt")),
626 Stm, Context);
627
628 if (const auto *BadIteratorsContainer =
629 selectFirst<Stmt>("stmt", RefToContainerBadIterators))
630 return BadIteratorsContainer;
631
632 // If range for looping over 'Exp' with a non-const reference loop variable,
633 // check all declRefExpr of the loop variable.
634 const auto LoopVars =
636 hasLoopVariable(varDecl(hasType(nonConstReferenceType()))
637 .bind(NodeID<Decl>::value)),
638 hasRangeInit(canResolveToExpr(Exp)))),
639 Stm, Context);
640 return findDeclMutation(LoopVars);
641}
642
643const Stmt *
644ExprMutationAnalyzer::Analyzer::findReferenceMutation(const Expr *Exp) {
645 // Follow non-const reference returned by `operator*()` of move-only classes.
646 // These are typically smart pointers with unique ownership so we treat
647 // mutation of pointee as mutation of the smart pointer itself.
648 const auto Ref = match(
651 callee(cxxMethodDecl(ofClass(isMoveOnly()),
652 returns(nonConstReferenceType()))),
653 argumentCountIs(1), hasArgument(0, canResolveToExpr(Exp)))
654 .bind(NodeID<Expr>::value)),
655 Stm, Context);
656 if (const Stmt *S = findExprMutation(Ref))
657 return S;
658
659 // If 'Exp' is bound to a non-const reference, check all declRefExpr to that.
660 const auto Refs = match(
662 varDecl(hasType(nonConstReferenceType()),
663 hasInitializer(anyOf(
664 canResolveToExpr(Exp),
665 memberExpr(hasObjectExpression(canResolveToExpr(Exp))))),
666 hasParent(declStmt().bind("stmt")),
667 // Don't follow the reference in range statement, we've
668 // handled that separately.
670 hasRangeStmt(equalsBoundNode("stmt"))))))))
671 .bind(NodeID<Decl>::value))),
672 Stm, Context);
673 return findDeclMutation(Refs);
674}
675
676const Stmt *
677ExprMutationAnalyzer::Analyzer::findFunctionArgMutation(const Expr *Exp) {
678 const auto NonConstRefParam = forEachArgumentWithParam(
679 canResolveToExpr(Exp),
680 parmVarDecl(hasType(nonConstReferenceType())).bind("parm"));
681 const auto IsInstantiated = hasDeclaration(isInstantiated());
682 const auto FuncDecl = hasDeclaration(functionDecl().bind("func"));
683 const auto Matches = match(
684 traverse(
685 TK_AsIs,
686 findAll(
687 expr(anyOf(callExpr(NonConstRefParam, IsInstantiated, FuncDecl,
689 "::std::move", "::std::forward"))))),
690 cxxConstructExpr(NonConstRefParam, IsInstantiated,
691 FuncDecl)))
692 .bind(NodeID<Expr>::value))),
693 Stm, Context);
694 for (const auto &Nodes : Matches) {
695 const auto *Exp = Nodes.getNodeAs<Expr>(NodeID<Expr>::value);
696 const auto *Func = Nodes.getNodeAs<FunctionDecl>("func");
697 if (!Func->getBody() || !Func->getPrimaryTemplate())
698 return Exp;
699
700 const auto *Parm = Nodes.getNodeAs<ParmVarDecl>("parm");
701 const ArrayRef<ParmVarDecl *> AllParams =
702 Func->getPrimaryTemplate()->getTemplatedDecl()->parameters();
703 QualType ParmType =
704 AllParams[std::min<size_t>(Parm->getFunctionScopeIndex(),
705 AllParams.size() - 1)]
706 ->getType();
707 if (const auto *T = ParmType->getAs<PackExpansionType>())
708 ParmType = T->getPattern();
709
710 // If param type is forwarding reference, follow into the function
711 // definition and see whether the param is mutated inside.
712 if (const auto *RefType = ParmType->getAs<RValueReferenceType>()) {
713 if (!RefType->getPointeeType().getQualifiers() &&
715 RefType->getPointeeType().getCanonicalType())) {
718 *Func, Context, Memorized);
719 if (Analyzer->findMutation(Parm))
720 return Exp;
721 continue;
722 }
723 }
724 // Not forwarding reference.
725 return Exp;
726 }
727 return nullptr;
728}
729
730const Stmt *
731ExprMutationAnalyzer::Analyzer::findPointeeValueMutation(const Expr *Exp) {
732 const auto Matches = match(
734 expr(anyOf(
735 // deref by *
736 unaryOperator(hasOperatorName("*"),
737 hasUnaryOperand(canResolveToExprPointee(Exp))),
738 // deref by []
740 hasBaseConservative(canResolveToExprPointee(Exp)))))
741 .bind(NodeID<Expr>::value))),
742 Stm, Context);
743 return findExprMutation(Matches);
744}
745
746const Stmt *
747ExprMutationAnalyzer::Analyzer::findPointeeMemberMutation(const Expr *Exp) {
748 const Stmt *MemberCallExpr = selectFirst<Stmt>(
750 cxxMemberCallExpr(on(canResolveToExprPointee(Exp)),
751 unless(isConstCallee()))
752 .bind("stmt"))),
753 Stm, Context));
754 if (MemberCallExpr)
755 return MemberCallExpr;
756 const auto Matches = match(
759 hasObjectExpression(canResolveToExprPointee(Exp))),
760 binaryOperator(hasOperatorName("->*"),
761 hasLHS(canResolveToExprPointee(Exp)))))
762 .bind(NodeID<Expr>::value))),
763 Stm, Context);
764 return findExprMutation(Matches);
765}
766
767const Stmt *
768ExprMutationAnalyzer::Analyzer::findPointeeToNonConst(const Expr *Exp) {
769 const auto NonConstPointerOrNonConstRefOrDependentType = type(
770 anyOf(nonConstPointerType(), nonConstReferenceType(), isDependentType()));
771
772 // assign
773 const auto InitToNonConst =
774 varDecl(hasType(NonConstPointerOrNonConstRefOrDependentType),
775 hasInitializer(expr(canResolveToExprPointee(Exp)).bind("stmt")));
776 const auto AssignToNonConst = binaryOperation(
777 hasOperatorName("="),
778 hasLHS(expr(hasType(NonConstPointerOrNonConstRefOrDependentType))),
779 hasRHS(canResolveToExprPointee(Exp)));
780 // arguments like
781 const auto ArgOfInstantiationDependent = allOf(
782 hasAnyArgument(canResolveToExprPointee(Exp)), isInstantiationDependent());
783 const auto ArgOfNonConstParameter =
784 forEachArgumentWithParamType(canResolveToExprPointee(Exp),
785 NonConstPointerOrNonConstRefOrDependentType);
786 const auto CallLikeMatcher =
787 anyOf(ArgOfNonConstParameter, ArgOfInstantiationDependent);
788 const auto PassAsNonConstArg =
789 expr(anyOf(cxxUnresolvedConstructExpr(ArgOfInstantiationDependent),
790 cxxConstructExpr(CallLikeMatcher), callExpr(CallLikeMatcher),
791 parenListExpr(has(canResolveToExprPointee(Exp))),
792 initListExpr(hasAnyInit(canResolveToExprPointee(Exp)))));
793 // cast
794 const auto CastToNonConst = explicitCastExpr(
795 hasSourceExpression(canResolveToExprPointee(Exp)),
796 hasDestinationType(NonConstPointerOrNonConstRefOrDependentType));
797
798 // capture
799 // FIXME: false positive if the pointee does not change in lambda
800 const auto CaptureNoConst = lambdaExpr(hasCaptureInit(Exp));
801
802 const auto ReturnNoConst =
803 returnStmt(hasReturnValue(canResolveToExprPointee(Exp)));
804
805 const auto Matches = match(
807 stmt(anyOf(AssignToNonConst, PassAsNonConstArg,
808 CastToNonConst, CaptureNoConst, ReturnNoConst))
809 .bind("stmt")),
810 forEachDescendant(InitToNonConst))),
811 Stm, Context);
812 return selectFirst<Stmt>("stmt", Matches);
813}
814
815FunctionParmMutationAnalyzer::FunctionParmMutationAnalyzer(
816 const FunctionDecl &Func, ASTContext &Context,
817 ExprMutationAnalyzer::Memoized &Memorized)
818 : BodyAnalyzer(*Func.getBody(), Context, Memorized) {
819 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(&Func)) {
820 // CXXCtorInitializer might also mutate Param but they're not part of
821 // function body, check them eagerly here since they're typically trivial.
822 for (const CXXCtorInitializer *Init : Ctor->inits()) {
823 ExprMutationAnalyzer::Analyzer InitAnalyzer(*Init->getInit(), Context,
824 Memorized);
825 for (const ParmVarDecl *Parm : Ctor->parameters()) {
826 if (Results.contains(Parm))
827 continue;
828 if (const Stmt *S = InitAnalyzer.findMutation(Parm))
829 Results[Parm] = S;
830 }
831 }
832 }
833}
834
835const Stmt *
837 auto [Place, Inserted] = Results.try_emplace(Parm);
838 if (!Inserted)
839 return Place->second;
840
841 // To handle call A -> call B -> call A. Assume parameters of A is not mutated
842 // before analyzing parameters of A. Then when analyzing the second "call A",
843 // FunctionParmMutationAnalyzer can use this memoized value to avoid infinite
844 // recursion.
845 return Place->second = BodyAnalyzer.findMutation(Parm);
846}
847
848} // namespace clang
#define AST_MATCHER(Type, DefineMatcher)
AST_MATCHER(Type, DefineMatcher) { ... } defines a zero parameter function named DefineMatcher() that...
#define AST_MATCHER_P(Type, DefineMatcher, ParamType, Param)
AST_MATCHER_P(Type, DefineMatcher, ParamType, Param) { ... } defines a single-parameter function name...
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:220
CXXForRangeStmt - This represents C++0x [stmt.ranged]'s ranged for statement, represented as 'for (ra...
Definition StmtCXX.h:135
Represents a call to a member function that may be written either with member call syntax (e....
Definition ExprCXX.h:179
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
Definition ExprCXX.h:848
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1610
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
static bool isUnevaluated(const Stmt *Stm, ASTContext &Context)
check whether stmt is unevaluated.
This represents one expression.
Definition Expr.h:112
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3082
static FunctionParmMutationAnalyzer * getFunctionParmMutationAnalyzer(const FunctionDecl &Func, ASTContext &Context, ExprMutationAnalyzer::Memoized &Memorized)
const Stmt * findMutation(const ParmVarDecl *Parm)
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5254
bool isConst() const
Definition TypeBase.h:4812
Represents a C11 generic selection.
Definition Expr.h:6112
Describes an C or C++ initializer list.
Definition Expr.h:5233
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition ExprCXX.h:1968
Represents a parameter to a function.
Definition Decl.h:1790
A (possibly-)qualified type.
Definition TypeBase.h:937
Stmt - This represents one statement.
Definition Stmt.h:85
The base class of the type hierarchy.
Definition TypeBase.h:1833
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9091
const internal::VariadicDynCastAllOfMatcher< Decl, VarDecl > varDecl
Matches variable declarations.
const internal::VariadicDynCastAllOfMatcher< Stmt, DeclRefExpr > declRefExpr
Matches expressions that refer to declarations.
const internal::VariadicOperatorMatcherFunc< 1, 1 > unless
Matches if the provided matcher does not match.
const internal::VariadicDynCastAllOfMatcher< Stmt, ImplicitCastExpr > implicitCastExpr
Matches the implicit cast nodes of Clang's AST.
const internal::ArgumentAdaptingMatcherFunc< internal::HasDescendantMatcher > hasDescendant
Matches AST nodes that have descendant AST nodes that match the provided matcher.
const internal::VariadicDynCastAllOfMatcher< Stmt, CXXDependentScopeMemberExpr > cxxDependentScopeMemberExpr
Matches member expressions where the actual member referenced could not be resolved because the base ...
const internal::VariadicDynCastAllOfMatcher< Decl, BindingDecl > bindingDecl
Matches binding declarations Example matches foo and bar (matcher = bindingDecl()
const internal::VariadicDynCastAllOfMatcher< Decl, ParmVarDecl > parmVarDecl
Matches parameter variable declarations.
const AstTypeMatcher< VariableArrayType > variableArrayType
const internal::VariadicDynCastAllOfMatcher< Stmt, GenericSelectionExpr > genericSelectionExpr
Matches C11 _Generic expression.
const internal::VariadicDynCastAllOfMatcher< Stmt, ReturnStmt > returnStmt
Matches return statements.
internal::Matcher< NamedDecl > hasName(StringRef Name)
Matches NamedDecl nodes that have the specified name.
const internal::VariadicDynCastAllOfMatcher< Stmt, CallExpr > callExpr
Matches call expressions.
const internal::VariadicDynCastAllOfMatcher< Stmt, LambdaExpr > lambdaExpr
Matches lambda expressions.
const internal::VariadicDynCastAllOfMatcher< Stmt, UnaryExprOrTypeTraitExpr > unaryExprOrTypeTraitExpr
Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL)
const internal::ArgumentAdaptingMatcherFunc< internal::ForEachDescendantMatcher > forEachDescendant
Matches AST nodes that have descendant AST nodes that match the provided matcher.
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
const internal::VariadicDynCastAllOfMatcher< Decl, NamedDecl > namedDecl
Matches a declaration of anything that could have a name.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicAllOfMatcher< TypeLoc > typeLoc
Matches TypeLocs in the clang AST.
const internal::VariadicDynCastAllOfMatcher< Stmt, ParenListExpr > parenListExpr
Matches paren list expressions.
const AstTypeMatcher< ArrayType > arrayType
const internal::VariadicDynCastAllOfMatcher< Stmt, UnaryOperator > unaryOperator
Matches unary operator expressions.
const internal::VariadicFunction< internal::Matcher< NamedDecl >, StringRef, internal::hasAnyNameFunc > hasAnyName
Matches NamedDecl nodes that have any of the specified names.
const internal::MapAnyOfMatcher< BinaryOperator, CXXOperatorCallExpr, CXXRewrittenBinaryOperator > binaryOperation
Matches nodes which can be used with binary operators.
const internal::VariadicDynCastAllOfMatcher< Stmt, ArraySubscriptExpr > arraySubscriptExpr
Matches array subscript expressions.
const internal::VariadicDynCastAllOfMatcher< Stmt, CXXForRangeStmt > cxxForRangeStmt
Matches range-based for statements.
const internal::VariadicDynCastAllOfMatcher< Stmt, CXXMemberCallExpr > cxxMemberCallExpr
Matches member call expressions.
const internal::VariadicDynCastAllOfMatcher< Decl, CXXConstructorDecl > cxxConstructorDecl
Matches C++ constructor declarations.
internal::BindableMatcher< Stmt > sizeOfExpr(const internal::Matcher< UnaryExprOrTypeTraitExpr > &InnerMatcher)
Same as unaryExprOrTypeTraitExpr, but only matching sizeof.
const internal::VariadicDynCastAllOfMatcher< Stmt, InitListExpr > initListExpr
Matches init list expressions.
const internal::VariadicDynCastAllOfMatcher< Stmt, CXXNoexceptExpr > cxxNoexceptExpr
Matches noexcept expressions.
const NodeT * selectFirst(StringRef BoundTo, const SmallVectorImpl< BoundNodes > &Results)
Returns the first result of type NodeT bound to BoundTo.
const internal::VariadicDynCastAllOfMatcher< Stmt, BinaryOperator > binaryOperator
Matches binary operator expressions.
const internal::ArgumentAdaptingMatcherFunc< internal::HasMatcher > has
Matches AST nodes that have child AST nodes that match the provided matcher.
const internal::VariadicDynCastAllOfMatcher< Stmt, ExplicitCastExpr > explicitCastExpr
Matches explicit cast expressions.
const internal::VariadicDynCastAllOfMatcher< Stmt, CXXConstructExpr > cxxConstructExpr
Matches constructor call expressions (including implicit ones).
const internal::VariadicDynCastAllOfMatcher< Stmt, CXXOperatorCallExpr > cxxOperatorCallExpr
Matches overloaded operator calls.
const AstTypeMatcher< PointerType > pointerType
internal::PolymorphicMatcher< internal::HasOverloadedOperatorNameMatcher, AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl), std::vector< std::string > > hasOverloadedOperatorName(StringRef Name)
Matches overloaded operator names.
const internal::VariadicOperatorMatcherFunc< 2, std::numeric_limits< unsigned >::max()> allOf
Matches if all given matchers match.
const internal::VariadicDynCastAllOfMatcher< Decl, FunctionDecl > functionDecl
Matches function declarations.
const internal::VariadicDynCastAllOfMatcher< Stmt, UnresolvedMemberExpr > unresolvedMemberExpr
Matches unresolved member expressions.
const internal::VariadicDynCastAllOfMatcher< Stmt, MemberExpr > memberExpr
Matches member expressions.
const internal::VariadicDynCastAllOfMatcher< Decl, CXXRecordDecl > cxxRecordDecl
Matches C++ class declarations.
internal::Matcher< T > traverse(TraversalKind TK, const internal::Matcher< T > &InnerMatcher)
Causes all nested matchers to be matched with the specified traversal kind.
const internal::VariadicDynCastAllOfMatcher< Stmt, CXXUnresolvedConstructExpr > cxxUnresolvedConstructExpr
Matches unresolved constructor call expressions.
internal::Matcher< T > findAll(const internal::Matcher< T > &Matcher)
Matches if the node or any descendant matches.
internal::PolymorphicMatcher< internal::HasDeclarationMatcher, void(internal::HasDeclarationSupportedTypes), internal::Matcher< Decl > > hasDeclaration(const internal::Matcher< Decl > &InnerMatcher)
Matches a node if the declaration associated with that node matches the given matcher.
const internal::VariadicDynCastAllOfMatcher< Stmt, DeclStmt > declStmt
Matches declaration statements.
const internal::VariadicAllOfMatcher< Stmt > stmt
Matches statements.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
const internal::VariadicDynCastAllOfMatcher< Stmt, CXXFoldExpr > cxxFoldExpr
Matches C++17 fold expressions.
const internal::VariadicOperatorMatcherFunc< 2, std::numeric_limits< unsigned >::max()> anyOf
Matches if any of the given matchers matches.
const internal::VariadicDynCastAllOfMatcher< Decl, CXXMethodDecl > cxxMethodDecl
Matches method declarations.
const internal::VariadicDynCastAllOfMatcher< Stmt, CastExpr > castExpr
Matches any cast nodes of Clang's AST.
const internal::ArgumentAdaptingMatcherFunc< internal::HasAncestorMatcher, internal::TypeList< Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr >, internal::TypeList< Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr > > hasAncestor
Matches AST nodes that have an ancestor that matches the provided matcher.
const internal::ArgumentAdaptingMatcherFunc< internal::HasParentMatcher, internal::TypeList< Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr >, internal::TypeList< Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr > > hasParent
Matches AST nodes that have a parent that matches the provided matcher.
const AstTypeMatcher< ReferenceType > referenceType
unsigned kind
All of the diagnostics that can be emitted by the frontend.
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ TK_AsIs
Will traverse all child nodes.
@ Result
The result type of a method or function.
Definition TypeBase.h:905
const FunctionProtoType * T
CastKind
CastKind - The kind of operation required for a conversion.
static bool canExprResolveTo(const Expr *Source, const Expr *Target)
U cast(CodeGen::Address addr)
Definition Address.h:327
const Stmt * findPointeeMutation(const Expr *Exp)
const Stmt * findMutation(const Expr *Exp)
llvm::DenseMap< const Expr *, const Stmt * > ResultMap