diff --git a/clang/lib/StaticAnalyzer/Checkers/DeadStoresChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/DeadStoresChecker.cpp --- a/clang/lib/StaticAnalyzer/Checkers/DeadStoresChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/DeadStoresChecker.cpp @@ -474,6 +474,15 @@ // Driver function to invoke the Dead-Stores checker on a CFG. //===----------------------------------------------------------------------===// +static bool isMemberOperatorCall(const CallExpr *CE) { + if (const auto *OpCE = dyn_cast(CE)) { + const FunctionDecl *DirectCallee = OpCE->getDirectCallee(); + if (const auto *MD = dyn_cast(DirectCallee)) + return MD->isInstance(); + } + return false; +} + namespace { class FindEscaped { public: @@ -482,12 +491,28 @@ void operator()(const Stmt *S) { // Check for '&'. Any VarDecl whose address has been taken we treat as // escaped. - // FIXME: What about references? if (auto *LE = dyn_cast(S)) { findLambdaReferenceCaptures(LE); return; } + if (auto *CE = dyn_cast(S)) { + if (auto *FD = dyn_cast_or_null(CE->getCalleeDecl())) { + CallExpr::const_arg_range args = CE->arguments(); + if (isMemberOperatorCall(CE) && !args.empty()) { + // Implicit 'this' is part of args but not params, skip it. + args = {args.begin() + 1, args.end()}; + } + findReferenceParameters(FD, args); + } + return; + } + + if (auto *CE = dyn_cast(S)) { + findReferenceParameters(CE->getConstructor(), CE->arguments()); + return; + } + const UnaryOperator *U = dyn_cast(S); if (!U) return; @@ -521,6 +546,21 @@ Escaped.insert(cast(VD)); } } + + void findReferenceParameters(const FunctionDecl *FD, + CallExpr::const_arg_range Args) { + for (const auto &[Param, Arg] : llvm::zip(FD->parameters(), Args)) { + if (!Param->getType()->isReferenceType()) + continue; + + auto *DRE = dyn_cast(Arg); + if (!DRE) + continue; + + if (auto *VD = dyn_cast(DRE->getDecl())) + Escaped.insert(VD); + } + } }; } // end anonymous namespace diff --git a/clang/test/Analysis/dead-stores.cpp b/clang/test/Analysis/dead-stores.cpp --- a/clang/test/Analysis/dead-stores.cpp +++ b/clang/test/Analysis/dead-stores.cpp @@ -235,3 +235,46 @@ return i + j; } +//===----------------------------------------------------------------------===// +// Dead store checking involving reference parameters. +//===----------------------------------------------------------------------===// + +struct ReferenceParameter { + int *ptr; + + ReferenceParameter(int &i) : ptr(&i) {} + void function(int &i) { + ptr = &i; + } + + void operator ()(int &i) { + ptr = &i; + } + + int value() { + return *ptr; + } +}; + +void referenceParameters() { + int i = 7; + ReferenceParameter r(i); + i = 8; + if (r.value() == 8) + ; + i = 9; // FIXME this is a false-negative + + int j = 10; + r.function(j); + j = 11; + if (r.value() == 11) + ; + j = 12; // FIXME this is a false-negative + + int k = 13; + r(k); + k = 14; + if (r.value() == 14) + ; + k = 15; // FIXME this is a false-negative +}