[clang] [LifetimeSafety] Preserve extending references on content invalidation (PR #240003)

Andrew Au via cfe-commits cfe-commits at lists.llvm.org
Sat Nov 7 09:54:00 PST 2026


https://github.com/cshung created https://github.com/llvm/llvm-project/pull/240003

Follow-up to #238776.

Content invalidation currently diagnoses the reference extending a temporary's lifetime as dangling, even when the referenced object remains alive:

```cpp
static std::vector<int> &&v = std::vector<int>{1, 2};
v.clear();
use(v); // Incorrect invalidation warning.
```

`clear()` destroys the vector's elements, not the vector itself.

This change exempts the extending declaration's reference origin from recognized STL content invalidation. Temporary loan issuance remains unchanged, preserving diagnostics for invalidated iterators and interior borrows. Destruction and deallocation are not exempt.

The exemption uses declaration identity rather than referent-type equality: nested owners can have the same type while referring to distinct objects. General owner-borrow versus content-borrow tracking remains outside this change's scope.

Regression coverage includes automatic, static, and thread-local extending references; invalidated iterators; nested container and same-type owner references; and explicit destruction.

**Validation**
- All 25 lifetime-safety regression tests passed.
- All 87 lifetime-analysis unit tests passed.
- Formatting and whitespace checks passed.

I'm new to LLVM and found this while reviewing #238776. I questioned the additional static/thread-local temporary loans and used GitHub Copilot to explore restricting their issuance. That investigation showed why the loans are needed for iterator diagnostics, but also exposed false-positive warnings on valid uses of the extending reference.

**AI assistance:** Implementation, tests, and this description were prepared with GitHub Copilot.


>From 393917dcd35efc567995171e787475f30b782330 Mon Sep 17 00:00:00 2001
From: cshung <3410332+cshung at users.noreply.github.com>
Date: Sat, 7 Nov 2026 16:38:54 +0000
Subject: [PATCH] [LifetimeSafety] Preserve extending references on content
 invalidation

After #238776, clearing a lifetime-extended vector temporary can diagnose
its extending reference as dangling even though the vector itself is
still alive. Keep the temporary loans needed to diagnose invalidated
iterators and other interior borrows.

For recognized STL content mutations, exempt only the reference origin
whose declaration extends the loan's temporary lifetime. Do not exempt
other origins or actual destruction and deallocation.

Add regression coverage for automatic, static, and thread-local
references, invalidated iterators, nested container and same-type owner
references, and explicit destruction. Leave existing arbitrary-alias
false positives unchanged.

Assisted-by: GitHub Copilot
Co-authored-by: Copilot <223556219+Copilot at users.noreply.github.com>
Signed-off-by: cshung <3410332+cshung at users.noreply.github.com>
---
 clang/lib/Analysis/LifetimeSafety/Checker.cpp | 15 +++++
 .../Sema/LifetimeSafety/invalidations.cpp     | 62 +++++++++++++++++++
 2 files changed, 77 insertions(+)

diff --git a/clang/lib/Analysis/LifetimeSafety/Checker.cpp b/clang/lib/Analysis/LifetimeSafety/Checker.cpp
index 2d2c394e255943..7bf6d85d5a3b54 100644
--- a/clang/lib/Analysis/LifetimeSafety/Checker.cpp
+++ b/clang/lib/Analysis/LifetimeSafety/Checker.cpp
@@ -251,6 +251,9 @@ class LifetimeChecker {
   /// an invalidated container's path (e.g., `v.*` extends `v`).
   void checkInvalidation(const InvalidateOriginFact *IOF) {
     OriginID InvalidatedOrigin = IOF->getInvalidatedOrigin();
+    FunctionCallInfo CallInfo(IOF->getInvalidationExpr());
+    const auto *MD = dyn_cast_or_null<CXXMethodDecl>(CallInfo.FD);
+    const bool InvalidatesContents = MD && isInvalidationMethod(*MD);
     /// Get loans directly pointing to the invalidated container
     LoanSet DirectlyInvalidatedLoans =
         LoanPropagation.getLoans(InvalidatedOrigin, IOF);
@@ -266,9 +269,21 @@ class LifetimeChecker {
     LiveOriginSet Origins = LiveOrigins.getLiveOriginsAt(IOF);
     for (const LivenessMap &Live : {Origins.Persistent, Origins.BlockLocal})
       for (auto &[OID, LiveInfo] : Live) {
+        const Origin &O = FactMgr.getOriginMgr().getOrigin(OID);
         LoanSet HeldLoans = LoanPropagation.getLoans(OID, IOF);
         for (LoanID LiveLoanID : HeldLoans)
           if (IsInvalidated(FactMgr.getLoanMgr().getLoan(LiveLoanID))) {
+            // The extending reference still refers to the temporary after its
+            // contents change. Inner borrows and destruction are not exempt.
+            if (InvalidatesContents && O.getDecl() && O.Ty &&
+                O.Ty->isReferenceType()) {
+              const auto *MTE = FactMgr.getLoanMgr()
+                                    .getLoan(LiveLoanID)
+                                    ->getAccessPath()
+                                    .getAsMaterializeTemporaryExpr();
+              if (MTE && MTE->getExtendingDecl() == O.getDecl())
+                continue;
+            }
             bool CurDomination = causingFactDominatesExpiry(LiveInfo.Kind);
             bool LastDomination =
                 FinalWarningsMap.lookup(LiveLoanID).CausingFactDominatesExpiry;
diff --git a/clang/test/Sema/LifetimeSafety/invalidations.cpp b/clang/test/Sema/LifetimeSafety/invalidations.cpp
index bdeb309d89973e..89a5e8631203ad 100644
--- a/clang/test/Sema/LifetimeSafety/invalidations.cpp
+++ b/clang/test/Sema/LifetimeSafety/invalidations.cpp
@@ -904,6 +904,68 @@ void function_captured_ref_invalidated() {
 
 } // namespace callable_wrappers
 
+namespace lifetime_extended_temporary {
+
+// clear() destroys the elements, not the vector the reference refers to.
+void clear_preserves_automatic_reference() {
+  std::vector<int> &&v = std::vector<int>{1, 2};
+  v.clear();
+  use(v);
+}
+
+void clear_preserves_static_reference() {
+  static std::vector<int> &&v = std::vector<int>{1, 2};
+  v.clear();
+  use(v);
+}
+
+void clear_preserves_thread_local_reference() {
+  thread_local std::vector<int> &&v = std::vector<int>{1, 2};
+  v.clear();
+  use(v);
+}
+
+void clear_invalidates_static_iterator() {
+  static std::vector<int> &&v = std::vector<int>{1, 2}; // expected-warning {{temporary object is later invalidated}}
+  auto it = v.begin(); // expected-note {{result of call to 'begin' aliases the storage of temporary object}}
+  v.clear();          // expected-note {{temporary object is invalidated here}}
+  use(*it);           // expected-note {{later used here}}
+}
+
+void clear_invalidates_thread_local_iterator() {
+  thread_local std::vector<int> &&v = std::vector<int>{1, 2}; // expected-warning {{temporary object is later invalidated}}
+  auto it = v.begin(); // expected-note {{result of call to 'begin' aliases the storage of temporary object}}
+  v.clear();          // expected-note {{temporary object is invalidated here}}
+  use(*it);           // expected-note {{later used here}}
+}
+
+void clear_invalidates_nested_container_reference() {
+  std::vector<std::vector<int>> v{{1}, {2}};
+  std::vector<int> &r = v[0]; // expected-warning {{local variable 'v' is later invalidated}} \
+                             // expected-note {{result of call to 'operator[]' aliases the storage of local variable 'v' because the implicit object parameter is inferred as lifetimebound}}
+  v.clear();                 // expected-note {{local variable 'v' is invalidated here}}
+  use(r);                    // expected-note {{later used here}}
+}
+
+struct Node {
+  std::unique_ptr<Node> next;
+};
+
+void reset_invalidates_nested_owner_reference() {
+  static std::unique_ptr<Node> &&p = std::unique_ptr<Node>(new Node); // expected-warning {{temporary object is later invalidated}}
+  std::unique_ptr<Node> &r = p->next; // expected-note {{result of call to 'operator->' aliases the storage of temporary object}}
+  p.reset();                        // expected-note {{temporary object is invalidated here}}
+  use(r);                           // expected-note {{later used here}}
+}
+
+void destruction_invalidates_static_reference() {
+  static std::vector<int> &&v = std::vector<int>{1, 2}; // expected-warning {{temporary object is later invalidated}}
+  std::destroy_at(&v); // expected-note {{temporary object is invalidated here}}
+  use(v);             // expected-note {{later used here}}
+}
+
+} // namespace lifetime_extended_temporary
+
 // FIXME: does not report a double free
 namespace explicit_destructor {
 



More information about the cfe-commits mailing list