[clang] [LifetimeSafety] Verify lifetime_capture_by(X) against the body (PR #207346)
via cfe-commits
cfe-commits at lists.llvm.org
Sat Nov 14 07:58:30 PST 2026
================
@@ -207,6 +224,54 @@ class LifetimeChecker {
}
}
+ /// Records \p PVD if it escapes through \p OEF into an entity that its
+ /// written [[clang::lifetime_capture_by]] attributes do not name. Inferred
+ /// attributes are not verified.
+ void checkCaptureBy(const ParmVarDecl &PVD, const OriginEscapesFact &OEF) {
+ CapturingEntity Entity;
+ const ValueDecl *CapturedBy = nullptr;
+ if (const auto *FieldEsc = dyn_cast<FieldEscapeFact>(&OEF)) {
+ Entity = CapturingEntity::This;
+ CapturedBy = FieldEsc->getFieldDecl();
+ } else if (isa<ThisEscapeFact>(OEF)) {
+ Entity = CapturingEntity::This;
+ } else if (const auto *GlobalEsc = dyn_cast<GlobalEscapeFact>(&OEF)) {
+ Entity = CapturingEntity::Global;
+ CapturedBy = GlobalEsc->getGlobal();
+ } else {
+ return;
+ }
+ // A lifetimebound constructor parameter is captured by the constructed
+ // object.
+ if (Entity == CapturingEntity::This && isa<CXXConstructorDecl>(FD) &&
+ PVD.hasAttr<LifetimeBoundAttr>())
+ return;
+ // The capturer index 0 names `this` only if there is an implicit object
+ // parameter; otherwise it names the first parameter.
+ const auto *MD = dyn_cast<CXXMethodDecl>(FD);
+ bool HasThis = MD && MD->isImplicitObjectMemberFunction();
+ const LifetimeCaptureByAttr *FirstWritten = nullptr;
+ for (const auto *A : PVD.specific_attrs<LifetimeCaptureByAttr>()) {
+ if (A->isImplicit())
+ continue;
+ if (!FirstWritten)
+ FirstWritten = A;
+ for (int Idx : A->params()) {
+ bool Named = Entity == CapturingEntity::This
+ ? HasThis && Idx == LifetimeCaptureByAttr::This
+ : Idx == LifetimeCaptureByAttr::Global;
----------------
NeKon69 wrote:
Is this the intended solution? I feel like this might be really hard to extend in the future (or at least the logic would be different) if we would want to verify other captures in the future. This feels really focused on `This`/`Global` in my opinion.
https://github.com/llvm/llvm-project/pull/207346
More information about the cfe-commits
mailing list