[clang] [LifetimeSafety] Catch intra-method lifetime_capture_by(this) dangles (PR #204630)

Gábor Horváth via cfe-commits cfe-commits at lists.llvm.org
Thu Oct 22 18:53:19 PDT 2026


================
@@ -858,6 +858,13 @@ void FactsGenerator::handleExitBlock() {
             FactMgr.createFact<GlobalEscapeFact>(O.ID, VD));
       }
     }
+
+  // A borrow captured via [[clang::lifetime_capture_by_this]] flows into the
+  // never-expiring `this` origin, so it is not otherwise live at the captured
+  // local's expiry. Keep `this` live at exit so the dangle is caught.
+  if (auto ThisOrigins = FactMgr.getOriginMgr().getThisOrigins())
+    EscapesInCurrentBlock.push_back(FactMgr.createFact<ThisEscapeFact>(
+        (*ThisOrigins)->getOuterOriginID(), AC.getDecl()->getEndLoc()));
----------------
Xazax-hun wrote:

It should not be added for destructors actually, thanks for the suggested test case. Fixed.

Yes, it needs to be emitted for all methods. Because sometimes we don't know what field would a value be bound to, like:
```
 int* m1() [[lifetimebound]];
 
 void m2() {
   int *p = m1();
 }
```

Here `p` might refer to a field (as per lifetimebound) but in the analysis we only know this is related to the this origin, but not know which particular field. As a result, just like fields, the this origin also needs to be escaped in every method, even if we don't have explicit lifetime_capture_by annotations. 

https://github.com/llvm/llvm-project/pull/204630


More information about the cfe-commits mailing list