[clang] 109700d - [LifetimeSafety] Track static data members accessed via MemberExpr (#238398)

via cfe-commits cfe-commits at lists.llvm.org
Wed Nov 4 01:17:16 PST 2026


Author: Gábor Horváth
Date: 2026-11-04T09:17:09Z
New Revision: 109700dedc6bc9fc66ddda09e58657d1debc9271

URL: https://github.com/llvm/llvm-project/commit/109700dedc6bc9fc66ddda09e58657d1debc9271
DIFF: https://github.com/llvm/llvm-project/commit/109700dedc6bc9fc66ddda09e58657d1debc9271.diff

LOG: [LifetimeSafety] Track static data members accessed via MemberExpr (#238398)

Added: 
    

Modified: 
    clang/lib/Analysis/LifetimeSafety/FactsGenerator.cpp
    clang/lib/Analysis/LifetimeSafety/Origins.cpp
    clang/lib/Sema/SemaLifetimeSafety.h
    clang/test/Sema/LifetimeSafety/dangling-global.cpp
    clang/test/Sema/LifetimeSafety/invalidations.cpp

Removed: 
    


################################################################################
diff  --git a/clang/lib/Analysis/LifetimeSafety/FactsGenerator.cpp b/clang/lib/Analysis/LifetimeSafety/FactsGenerator.cpp
index b9af4b0ff39dd..073c79972f2d3 100644
--- a/clang/lib/Analysis/LifetimeSafety/FactsGenerator.cpp
+++ b/clang/lib/Analysis/LifetimeSafety/FactsGenerator.cpp
@@ -87,15 +87,16 @@ void FactsGenerator::flow(OriginList *Dst, OriginList *Src, bool Kill,
   }
 }
 
-/// Creates a loan for the storage path of a given declaration reference.
-/// This function should be called whenever a DeclRefExpr represents a borrow.
-/// \param DRE The declaration reference expression that initiates the borrow.
+/// Creates a loan for the storage path of a given declaration.
+/// This function should be called whenever an expression naming \p VD
+/// represents a borrow.
+/// \param VD The declaration whose storage is borrowed.
+/// \param IssueExpr The expression (DeclRefExpr or MemberExpr) that initiates
+/// the borrow.
 /// \return The new Loan on success, nullptr otherwise.
-static const Loan *createLoan(FactManager &FactMgr, const DeclRefExpr *DRE) {
-  const ValueDecl *VD = DRE->getDecl();
-  AccessPath Path(VD);
-  // The loan is created at the location of the DeclRefExpr.
-  return FactMgr.getLoanMgr().createLoan(Path, DRE);
+static const Loan *createLoan(FactManager &FactMgr, const ValueDecl &VD,
+                              const Expr *IssueExpr) {
+  return FactMgr.getLoanMgr().createLoan(AccessPath(&VD), IssueExpr);
 }
 
 /// Creates a loan for the storage location of a temporary object.
@@ -190,7 +191,7 @@ void FactsGenerator::VisitDeclRefExpr(const DeclRefExpr *DRE) {
   //   - `View v; v` issues loan to v's storage (the view object)
   //   - `int& r = x; r` issues no loan (r has no storage, it's an alias to x)
   if (doesDeclHaveStorage(DRE->getDecl())) {
-    const Loan *L = createLoan(FactMgr, DRE);
+    const Loan *L = createLoan(FactMgr, *DRE->getDecl(), DRE);
     assert(L);
     OriginList *List = getOriginsList(*DRE);
     assert(List &&
@@ -258,6 +259,15 @@ void FactsGenerator::VisitCXXMemberCallExpr(const CXXMemberCallExpr *MCE) {
 
 void FactsGenerator::VisitMemberExpr(const MemberExpr *ME) {
   auto *MD = ME->getMemberDecl();
+  if (const auto *VD = dyn_cast<VarDecl>(MD); VD && doesDeclHaveStorage(VD)) {
+    // A static data member: borrow its storage, as for a DeclRefExpr.
+    const Loan *L = createLoan(FactMgr, *VD, ME);
+    OriginList *List = getOriginsList(*ME);
+    assert(List && "gl-value static member should have an origin list");
+    CurrentBlockFacts.push_back(
+        FactMgr.createFact<IssueFact>(L->getID(), List->getOuterOriginID()));
+    return;
+  }
   if (isa<FieldDecl>(MD) && doesDeclHaveStorage(MD)) {
     assert(ME->isGLValue() && "Field member should be GL value");
     OriginList *Dst = getOriginsList(*ME);
@@ -976,8 +986,10 @@ void FactsGenerator::handleInvalidatingCall(const Expr *Call,
 
   // Heuristics to turn-down false positives. Skip member field expressions for
   // now. This is not a perfect filter and will still surface some false
-  // positives (e.g. `auto& r = s.v`).
-  if (!isa<DeclRefExpr>(Args[0]->IgnoreImpCasts()))
+  // positives (e.g. `auto& r = s.v`). Static data members are not fields.
+  const Expr *Obj = Args[0]->IgnoreImpCasts();
+  if (const auto *ME = dyn_cast<MemberExpr>(Obj);
+      !isa<DeclRefExpr>(Obj) && !(ME && isa<VarDecl>(ME->getMemberDecl())))
     return;
 
   OriginList *ThisList = getOriginsList(*Args[0]);

diff  --git a/clang/lib/Analysis/LifetimeSafety/Origins.cpp b/clang/lib/Analysis/LifetimeSafety/Origins.cpp
index 566e9ffa0eab0..e571e6290bb30 100644
--- a/clang/lib/Analysis/LifetimeSafety/Origins.cpp
+++ b/clang/lib/Analysis/LifetimeSafety/Origins.cpp
@@ -317,10 +317,14 @@ OriginList *OriginManager::getOrCreateList(const Expr *E) {
   const ValueDecl *ReferencedDecl = nullptr;
   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
     ReferencedDecl = DRE->getDecl();
-  else if (auto *ME = dyn_cast<MemberExpr>(E))
+  else if (auto *ME = dyn_cast<MemberExpr>(E)) {
     if (auto *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
         Field && isSubobjectOfThis(ME))
       ReferencedDecl = Field;
+    // A static data member names the same variable regardless of its base.
+    else if (auto *VD = dyn_cast<VarDecl>(ME->getMemberDecl()))
+      ReferencedDecl = VD;
+  }
   if (ReferencedDecl) {
     OriginList *Head = nullptr;
     // For non-reference declarations (e.g., `int* p`), the expression is an
@@ -331,7 +335,8 @@ OriginList *OriginManager::getOrCreateList(const Expr *E) {
     if (doesDeclHaveStorage(ReferencedDecl)) {
       // `this->f` reaches its field through `this` instead of naming it.
       Head = createNode(E, QualType{},
-                        /*NamesDeclStorage=*/isa<DeclRefExpr>(E));
+                        /*NamesDeclStorage=*/isa<DeclRefExpr>(E) ||
+                            isa<VarDecl>(ReferencedDecl));
       // This ensures origin sharing: multiple expressions to the same
       // declaration share the same underlying origins.
       Head->setInnerOriginList(getOrCreateList(ReferencedDecl));

diff  --git a/clang/lib/Sema/SemaLifetimeSafety.h b/clang/lib/Sema/SemaLifetimeSafety.h
index 1b3fed41abd0e..37533f6ce9fb0 100644
--- a/clang/lib/Sema/SemaLifetimeSafety.h
+++ b/clang/lib/Sema/SemaLifetimeSafety.h
@@ -759,6 +759,9 @@ class LifetimeSafetySemaHelperImpl final : public LifetimeSafetySemaHelper {
       return "allocated object";
     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
       return getDiagSubjectDescription(DRE->getDecl());
+    if (const auto *ME = dyn_cast<MemberExpr>(E))
+      if (const auto *VD = dyn_cast<VarDecl>(ME->getMemberDecl()))
+        return getDiagSubjectDescription(VD);
 
     if (const auto *CE = dyn_cast<CallExpr>(E)) {
       const auto *FD = CE->getDirectCallee();

diff  --git a/clang/test/Sema/LifetimeSafety/dangling-global.cpp b/clang/test/Sema/LifetimeSafety/dangling-global.cpp
index 2013f9479a784..931f60b5e94e7 100644
--- a/clang/test/Sema/LifetimeSafety/dangling-global.cpp
+++ b/clang/test/Sema/LifetimeSafety/dangling-global.cpp
@@ -53,6 +53,73 @@ void dangling_static_field() {
   ObjWithStaticField::static_field = &local; // expected-warning {{stack memory associated with local variable 'local' escapes to the static variable 'static_field' which will dangle}}
 }
 
+struct StaticMembers {
+  static int *sp;                // expected-note 5 {{this static storage dangles}}
+  static std::string_view sv;    // expected-note {{this static storage dangles}}
+  static int *&ref;              // expected-note {{this static storage dangles}}
+  template <typename T>
+  static inline T *vt = nullptr; // expected-note {{this static storage dangles}}
+  void via_this();
+};
+
+void StaticMembers::via_this() {
+  int local;
+  this->sp = &local; // expected-warning {{stack memory associated with local variable 'local' escapes to the static variable 'sp' which will dangle}}
+}
+
+void static_member_via_object(StaticMembers &s) {
+  int local;
+  s.sp = &local; // expected-warning {{stack memory associated with local variable 'local' escapes to the static variable 'sp' which will dangle}}
+}
+
+void static_member_via_pointer(StaticMembers *s) {
+  int local;
+  s->sp = &local; // expected-warning {{stack memory associated with local variable 'local' escapes to the static variable 'sp' which will dangle}}
+}
+
+void static_member_view_via_object(StaticMembers &s) {
+  std::string local;
+  s.sv = local; // expected-warning {{stack memory associated with local variable 'local' escapes to the static variable 'sv' which will dangle}}
+}
+
+void static_member_reference_via_object(StaticMembers &s) {
+  int local;
+  s.ref = &local; // expected-warning {{stack memory associated with local variable 'local' escapes to the static variable 'ref' which will dangle}}
+}
+
+void static_member_no_escape(StaticMembers &s) {
+  static int long_lived;
+  s.sp = &long_lived; // no-warning
+}
+
+struct DerivedFromStaticMembers : StaticMembers {};
+
+void static_member_via_derived(DerivedFromStaticMembers &d) {
+  int local;
+  d.sp = &local; // expected-warning {{stack memory associated with local variable 'local' escapes to the static variable 'sp' which will dangle}}
+}
+
+StaticMembers &getStaticMembers();
+
+void static_member_via_call(StaticMembers &s) {
+  int local;
+  getStaticMembers().sp = &local; // expected-warning {{stack memory associated with local variable 'local' escapes to the static variable 'sp' which will dangle}}
+}
+
+void static_member_variable_template(StaticMembers &s) {
+  int local;
+  s.vt<int> = &local; // expected-warning {{stack memory associated with local variable 'local' escapes to the static variable 'vt<int>' which will dangle}}
+}
+
+template <typename T> struct TemplateStaticMember {
+  static inline T *tp = nullptr; // expected-note {{this static storage dangles}}
+  void via_this() {
+    T local;
+    this->tp = &local; // expected-warning {{stack memory associated with local variable 'local' escapes to the static variable 'tp' which will dangle}}
+  }
+};
+template struct TemplateStaticMember<int>; // expected-note {{in instantiation of member function 'TemplateStaticMember<int>::via_this' requested here}}
+
 // A store on some-but-not-all paths must still be caught: the global's origin
 // only spans blocks via the function-exit escape, so it must survive the join.
 void conditional_escape(int c) {

diff  --git a/clang/test/Sema/LifetimeSafety/invalidations.cpp b/clang/test/Sema/LifetimeSafety/invalidations.cpp
index 60f3c18502aea..e8446402954d1 100644
--- a/clang/test/Sema/LifetimeSafety/invalidations.cpp
+++ b/clang/test/Sema/LifetimeSafety/invalidations.cpp
@@ -1050,3 +1050,30 @@ void via_destructor_invalidated() {
   s.push_back('x'); // expected-note {{local variable 's' is invalidated here}}
 }                   // expected-note {{later used by the destructor of 'r' at scope exit}}
 } // namespace implicit_use_after_free
+
+namespace static_member_container {
+struct S {
+  static std::vector<int> v;
+};
+
+void ViaObject(S &s) {
+  auto it = s.v.begin();  // expected-warning {{static variable 'v' is later invalidated}} \
+                          // expected-note {{result of call to 'begin' aliases the storage of static variable 'v'}}
+  s.v.push_back(1);       // expected-note {{static variable 'v' is invalidated here}}
+  use(*it);               // expected-note {{later used here}}
+}
+
+void BorrowQualifiedInvalidateViaObject(S &s) {
+  auto it = S::v.begin(); // expected-warning {{static variable 'v' is later invalidated}} \
+                          // expected-note {{result of call to 'begin' aliases the storage of static variable 'v'}}
+  s.v.push_back(1);       // expected-note {{static variable 'v' is invalidated here}}
+  use(*it);               // expected-note {{later used here}}
+}
+
+void BorrowViaObjectInvalidateQualified(S &s) {
+  auto it = s.v.begin();  // expected-warning {{static variable 'v' is later invalidated}} \
+                          // expected-note {{result of call to 'begin' aliases the storage of static variable 'v'}}
+  S::v.push_back(1);      // expected-note {{static variable 'v' is invalidated here}}
+  use(*it);               // expected-note {{later used here}}
+}
+} // namespace static_member_container


        


More information about the cfe-commits mailing list