[clang] [LifetimeSafety] Detect use of a reference type as a use of underlying origin (PR #184295)
via cfe-commits
cfe-commits at lists.llvm.org
Mon Mar 2 23:48:47 PST 2026
llvmbot wrote:
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-clang
@llvm/pr-subscribers-clang-analysis
Author: Zhijie Wang (aeft)
<details>
<summary>Changes</summary>
Writing through a reference (e.g., `ref = 10`) does not rebind the reference, so it should not kill the liveness of its underlying origin.
Fixes #<!-- -->180187
---
Full diff: https://github.com/llvm/llvm-project/pull/184295.diff
2 Files Affected:
- (modified) clang/lib/Analysis/LifetimeSafety/FactsGenerator.cpp (+2-1)
- (modified) clang/test/Sema/warn-lifetime-safety-invalidations.cpp (+3-5)
``````````diff
diff --git a/clang/lib/Analysis/LifetimeSafety/FactsGenerator.cpp b/clang/lib/Analysis/LifetimeSafety/FactsGenerator.cpp
index f39d677758393..6325e63b2388b 100644
--- a/clang/lib/Analysis/LifetimeSafety/FactsGenerator.cpp
+++ b/clang/lib/Analysis/LifetimeSafety/FactsGenerator.cpp
@@ -347,7 +347,8 @@ void FactsGenerator::handleAssignment(const Expr *LHSExpr,
// assigned.
RHSList = getRValueOrigins(RHSExpr, RHSList);
- if (const auto *DRE_LHS = dyn_cast<DeclRefExpr>(LHSExpr))
+ if (const auto *DRE_LHS = dyn_cast<DeclRefExpr>(LHSExpr);
+ DRE_LHS && !DRE_LHS->getDecl()->getType()->isReferenceType())
markUseAsWrite(DRE_LHS);
// Kill the old loans of the destination origin and flow the new loans
// from the source origin.
diff --git a/clang/test/Sema/warn-lifetime-safety-invalidations.cpp b/clang/test/Sema/warn-lifetime-safety-invalidations.cpp
index 65d676cbe8361..60a6be9f0c2a7 100644
--- a/clang/test/Sema/warn-lifetime-safety-invalidations.cpp
+++ b/clang/test/Sema/warn-lifetime-safety-invalidations.cpp
@@ -259,11 +259,9 @@ namespace ElementReferences {
void ReferenceToVectorElement() {
std::vector<int> v = {1, 2, 3};
- int& ref = v[0];
- v.push_back(4);
- // FIXME: Detect this as a use of 'ref'.
- // https://github.com/llvm/llvm-project/issues/180187
- ref = 10;
+ int& ref = v[0]; // expected-warning {{object whose reference is captured is later invalidated}}
+ v.push_back(4); // expected-note {{invalidated here}}
+ ref = 10; // expected-note {{later used here}}
(void)ref;
}
``````````
</details>
https://github.com/llvm/llvm-project/pull/184295
More information about the cfe-commits
mailing list