[clang] [LifetimeSafety] Verify lifetime_capture_by(X) against the body (PR #207346)
Gábor Horváth via cfe-commits
cfe-commits at lists.llvm.org
Mon Nov 16 06:56:20 PST 2026
https://github.com/Xazax-hun updated https://github.com/llvm/llvm-project/pull/207346
>From a0729dce6869bb9c7ccfdda4c5e1ea7b835dbff1 Mon Sep 17 00:00:00 2001
From: Gabor Horvath <gaborh at apple.com>
Date: Fri, 3 Jul 2026 09:20:16 +0100
Subject: [PATCH] [LifetimeSafety] Verify lifetime_capture_by against the body
A parameter that the body captures by the enclosing object or by global
storage must have a lifetime_capture_by attribute naming that entity, or
unknown. Report a violation under -Wlifetime-safety-capture-by-violation.
Captures by other parameters are not verified yet.
Assisted-by: Claude Opus 5.5
---
clang/docs/LifetimeSafety.md | 1 +
clang/docs/ReleaseNotes.md | 17 ++
.../Analyses/LifetimeSafety/LifetimeSafety.h | 16 ++
clang/include/clang/Basic/DiagnosticGroups.td | 13 +-
.../clang/Basic/DiagnosticSemaKinds.td | 6 +
clang/lib/Analysis/LifetimeSafety/Checker.cpp | 92 ++++++++++-
clang/lib/Sema/SemaLifetimeSafety.h | 25 +++
.../LifetimeSafety/capture-by-violation.cpp | 154 ++++++++++++++++++
8 files changed, 320 insertions(+), 4 deletions(-)
create mode 100644 clang/test/Sema/LifetimeSafety/capture-by-violation.cpp
diff --git a/clang/docs/LifetimeSafety.md b/clang/docs/LifetimeSafety.md
index 13f137e28e3367..a6d5fcc50b1a4d 100644
--- a/clang/docs/LifetimeSafety.md
+++ b/clang/docs/LifetimeSafety.md
@@ -519,6 +519,7 @@ enables only the high-confidence subset of these checks.
- `-Wlifetime-safety-noescape`: Warns when a parameter marked with `[[clang::noescape]]` escapes the function.
- `-Wlifetime-safety-lifetimebound-violation`: Warns when the analysis cannot verify that the return value can be lifetime bound to a parameter marked with `[[clang::lifetimebound]]`.
+ - `-Wlifetime-safety-capture-by-violation`: Warns when a parameter with `[[clang::lifetime_capture_by]]` attributes is captured by the enclosing object or by global storage, but none of the attributes names that entity (`lifetime_capture_by_this` or `lifetime_capture_by_global`) or `unknown`. Captures by other parameters are not verified.
- `-Wlifetime-safety-experimental`: Enables experimental checks. These may have known false positives and their behavior may change. They are not enabled by `-Wlifetime-safety-all`.
diff --git a/clang/docs/ReleaseNotes.md b/clang/docs/ReleaseNotes.md
index 6ced5d9b986e51..64bbbce52c5db2 100644
--- a/clang/docs/ReleaseNotes.md
+++ b/clang/docs/ReleaseNotes.md
@@ -611,6 +611,23 @@ documentation](CIR/index.md) for more information regarding ClangIR's status and
^~
```
+- Added `-Wlifetime-safety-capture-by-violation` to detect a parameter that the
+ body captures by the enclosing object or by global storage, while none of its
+ `[[clang::lifetime_capture_by]]` attributes names that entity or `unknown`.
+ For example:
+
+ ```c++
+ struct Cap { const int *p; };
+ struct S {
+ const int *field;
+ // warning: 'x' is captured by this object but is not marked
+ // [[clang::lifetime_capture_by_this]]
+ void store(Cap &c, const int &x [[clang::lifetime_capture_by(c)]]) {
+ field = &x;
+ }
+ };
+ ```
+
- Added `-Wlifetime-safety-dangling-field` to detect dangling field references
when stack memory escapes to class fields. This is part of `-Wlifetime-safety`
and detects cases where local variables or parameters are stored in fields but
diff --git a/clang/include/clang/Analysis/Analyses/LifetimeSafety/LifetimeSafety.h b/clang/include/clang/Analysis/Analyses/LifetimeSafety/LifetimeSafety.h
index 3a0277cf3e48a3..afdca8ef5763ce 100644
--- a/clang/include/clang/Analysis/Analyses/LifetimeSafety/LifetimeSafety.h
+++ b/clang/include/clang/Analysis/Analyses/LifetimeSafety/LifetimeSafety.h
@@ -32,6 +32,10 @@
#include <cstddef>
#include <memory>
+namespace clang {
+class LifetimeCaptureByAttr;
+} // namespace clang
+
namespace clang::lifetimes {
struct LifetimeSafetyOpts {
@@ -49,6 +53,7 @@ struct LifetimeSafetyOpts {
bool CheckFieldOriginEscape = false;
/// Whether to model non-trivial destructors at scope exit as uses.
bool CheckDestructorUses = false;
+ bool CheckCaptureByViolations = false;
};
/// Enum to track functions visible across or within TU.
@@ -57,6 +62,9 @@ enum class WarningScope {
IntraTU // For warnings on functions local to a Translation Unit.
};
+/// An entity a parameter can be captured by, beyond another parameter.
+enum class CapturingEntity { This, Global };
+
/// Abstract interface for operations requiring Sema access.
///
/// This class exists to break a circular dependency: the LifetimeSafety
@@ -156,6 +164,14 @@ class LifetimeSafetySemaHelper {
virtual void
reportLifetimeboundViolation(const CXXMethodDecl *MDWithLifetimebound) {}
+ // Reports a parameter captured by an entity that its
+ // [[clang::lifetime_capture_by]] attributes do not name. \p CapturedBy is
+ // the field or global it is captured by, if known.
+ virtual void reportCaptureByViolation(const ParmVarDecl *PVD,
+ const LifetimeCaptureByAttr *Attr,
+ CapturingEntity Entity,
+ const ValueDecl *CapturedBy) {}
+
// Reports a member function definition that has [[clang::lifetimebound]] on
// the implicit this parameter when the canonical declaration does not.
virtual void reportMisplacedLifetimebound(WarningScope Scope,
diff --git a/clang/include/clang/Basic/DiagnosticGroups.td b/clang/include/clang/Basic/DiagnosticGroups.td
index eb5a1280bf41ef..e83c019da421de 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -718,6 +718,16 @@ Detects misuse of [[clang::noescape]] annotation where the parameter escapes (fo
}];
}
+def LifetimeSafetyCaptureByViolation
+ : DiagGroup<"lifetime-safety-capture-by-violation"> {
+ code Documentation = [{
+Detects a parameter whose '[[clang::lifetime_capture_by]]' attributes name
+neither 'unknown' nor an entity that the function body captures the parameter
+by: the enclosing object (a store into a field of 'this', or a capture by 'this'
+in a call), or global storage. Captures by other parameters are not verified.
+ }];
+}
+
def LifetimeSafetyAnnotationPlacement
: DiagGroup<"lifetime-safety-annotation-placement",
[LifetimeSafetyInapplicableLifetimebound,
@@ -730,7 +740,8 @@ Validates that lifetime annotations are placed on appropriate types and in appro
def LifetimeSafetyAnnotationVerification
: DiagGroup<"lifetime-safety-annotation-verification",
[LifetimeSafetyNoescape,
- LifetimeSafetyLifetimeboundViolation]> {
+ LifetimeSafetyLifetimeboundViolation,
+ LifetimeSafetyCaptureByViolation]> {
code Documentation = [{
Verifies that function implementations adhere to their lifetime annotation contracts through dataflow analysis.
}];
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index c3793aec1f732f..f4c8dd5cb192c0 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -11160,6 +11160,12 @@ def warn_lifetime_safety_lifetimebound_violation
InGroup<LifetimeSafetyLifetimeboundViolation>,
DefaultIgnore;
+def warn_lifetime_safety_capture_by_violation
+ : Warning<"%0 is captured by %select{this object|global storage}1 but is "
+ "not marked [[clang::lifetime_capture_by_%select{this|global}1]]">,
+ InGroup<LifetimeSafetyCaptureByViolation>,
+ DefaultIgnore;
+
def warn_lifetime_safety_intra_tu_misplaced_lifetimebound
: Warning<"'lifetimebound' attribute on this definition is not visible to callers before the definition; add it to the declaration instead">,
InGroup<LifetimeSafetyIntraTUMisplacedLifetimebound>,
diff --git a/clang/lib/Analysis/LifetimeSafety/Checker.cpp b/clang/lib/Analysis/LifetimeSafety/Checker.cpp
index eaa501d63508da..f325bd0a262e58 100644
--- a/clang/lib/Analysis/LifetimeSafety/Checker.cpp
+++ b/clang/lib/Analysis/LifetimeSafety/Checker.cpp
@@ -12,6 +12,7 @@
//===----------------------------------------------------------------------===//
#include "clang/Analysis/Analyses/LifetimeSafety/Checker.h"
+#include "clang/AST/Attr.h"
#include "clang/AST/Decl.h"
#include "clang/AST/Expr.h"
#include "clang/Analysis/Analyses/LifetimeSafety/Facts.h"
@@ -24,8 +25,11 @@
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/SourceManager.h"
#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/MapVector.h"
+#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/TimeProfiler.h"
+#include <optional>
namespace clang::lifetimes::internal {
@@ -61,6 +65,17 @@ class LifetimeChecker {
llvm::DenseMap<AnnotationTarget, EscapingTarget> AnnotationWarningsMap;
llvm::DenseMap<const ParmVarDecl *, EscapingTarget> NoescapeWarningsMap;
llvm::DenseMap<const FieldDecl *, const Expr *> FieldOriginEscapesMap;
+ struct CaptureByViolation {
+ /// The first written [[clang::lifetime_capture_by]] attribute.
+ const LifetimeCaptureByAttr *Attr;
+ /// The field or global it is captured by, if known.
+ const ValueDecl *CapturedBy;
+ };
+ /// Parameters captured by an entity their written
+ /// [[clang::lifetime_capture_by]] attributes do not name.
+ llvm::MapVector<std::pair<const ParmVarDecl *, CapturingEntity>,
+ CaptureByViolation>
+ CaptureByViolations;
llvm::DenseSet<const Decl *> VerifiedLiftimeboundEscapes;
const LoanPropagationAnalysis &LoanPropagation;
const MovedLoansAnalysis &MovedLoans;
@@ -112,6 +127,8 @@ class LifetimeChecker {
reportNoescapeViolations();
if (LSOpts.CheckLifetimeboundViolations)
reportLifetimeboundViolations();
+ if (LSOpts.CheckCaptureByViolations)
+ reportCaptureByViolations();
if (LSOpts.CheckMisplacedLifetimebound)
reportMisplacedLifetimebound();
if (LSOpts.CheckInapplicableLifetimebound)
@@ -124,8 +141,8 @@ class LifetimeChecker {
}
/// Checks if an escaping origin holds a placeholder loan, indicating a
- /// missing [[clang::lifetimebound]] annotation or a violation of
- /// [[clang::noescape]].
+ /// missing [[clang::lifetimebound]] annotation, or a violation of
+ /// [[clang::noescape]] or [[clang::lifetime_capture_by]].
void checkAnnotations(const OriginEscapesFact *OEF) {
OriginID EscapedOID = OEF->getEscapedOriginID();
LoanSet EscapedLoans = LoanPropagation.getLoans(EscapedOID, OEF);
@@ -144,6 +161,8 @@ class LifetimeChecker {
// obscures the lifetime relationship (e.g., shared_ptr from unique_ptr).
if (IsMoved)
return;
+ if (LSOpts.CheckCaptureByViolations)
+ checkCaptureBy(*PVD, *OEF);
if (paramIsLifetimeBound(*PVD)) {
// Track that this lifetimebound parameter correctly escapes
// (via return or via field assignment in a constructor).
@@ -163,7 +182,7 @@ class LifetimeChecker {
AnnotationWarningsMap.try_emplace(PVD, FieldEsc->getFieldDecl());
}
}
- // TODO: Suggest lifetime_capture_by(this) for parameter escaping to a
+ // TODO: Suggest lifetime_capture_by_this for parameter escaping to a
// field!
};
auto CheckImplicitThis = [&](const CXXMethodDecl *MD) {
@@ -207,6 +226,65 @@ class LifetimeChecker {
}
}
+ /// An entity that a parameter is captured by.
+ struct Capturer {
+ CapturingEntity Entity;
+ /// The index that a [[clang::lifetime_capture_by]] attribute uses for it.
+ int Index;
+ /// The field or global, if known.
+ const ValueDecl *CapturedBy;
+ };
+
+ /// 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) {
+ std::optional<Capturer> C = getCapturer(OEF);
+ if (!C)
+ return;
+ // A lifetimebound constructor parameter is captured by the constructed
+ // object.
+ if (C->Entity == CapturingEntity::This && isa<CXXConstructorDecl>(FD) &&
+ PVD.hasAttr<LifetimeBoundAttr>())
+ return;
+ const LifetimeCaptureByAttr *FirstWritten = nullptr;
+ for (const auto *A : PVD.specific_attrs<LifetimeCaptureByAttr>()) {
+ if (A->isImplicit())
+ continue;
+ if (!FirstWritten)
+ FirstWritten = A;
+ // FIXME: The capturers of a lambda's parameters are never resolved, so
+ // they stay invalid and are not verified.
+ if (llvm::any_of(A->params(), [&](int Idx) {
+ return Idx == C->Index || Idx == LifetimeCaptureByAttr::Unknown ||
+ Idx == LifetimeCaptureByAttr::Invalid;
+ }))
+ return;
+ }
+ if (FirstWritten)
+ CaptureByViolations.try_emplace(
+ {&PVD, C->Entity}, CaptureByViolation{FirstWritten, C->CapturedBy});
+ }
+
+ /// Returns the entity that a parameter escaping through \p OEF is captured
+ /// by, if a [[clang::lifetime_capture_by]] attribute can name it.
+ std::optional<Capturer> getCapturer(const OriginEscapesFact &OEF) const {
+ if (isa<FieldEscapeFact, ThisEscapeFact>(OEF)) {
+ // Index 0 names `this` only with an implicit object parameter;
+ // otherwise it names the first parameter.
+ const auto *MD = dyn_cast<CXXMethodDecl>(FD);
+ if (!MD || !MD->isImplicitObjectMemberFunction())
+ return std::nullopt;
+ const auto *FieldEsc = dyn_cast<FieldEscapeFact>(&OEF);
+ return Capturer{CapturingEntity::This, LifetimeCaptureByAttr::This,
+ FieldEsc ? FieldEsc->getFieldDecl() : nullptr};
+ }
+ if (const auto *GlobalEsc = dyn_cast<GlobalEscapeFact>(&OEF))
+ return Capturer{CapturingEntity::Global, LifetimeCaptureByAttr::Global,
+ GlobalEsc->getGlobal()};
+ return std::nullopt;
+ }
+
/// Checks for use-after-free & use-after-return errors when an access path
/// expires (e.g., a variable goes out of scope).
///
@@ -516,6 +594,14 @@ class LifetimeChecker {
}
}
+ void reportCaptureByViolations() {
+ if (!SemaHelper)
+ return;
+ for (const auto &[Key, Violation] : CaptureByViolations)
+ SemaHelper->reportCaptureByViolation(Key.first, Violation.Attr,
+ Key.second, Violation.CapturedBy);
+ }
+
void reportLifetimeboundViolations() {
llvm::TimeTraceScope TimeTrace("ReportLifetimeboundViolations");
if (!isa<FunctionDecl>(FD))
diff --git a/clang/lib/Sema/SemaLifetimeSafety.h b/clang/lib/Sema/SemaLifetimeSafety.h
index 3495fc63e790be..2630fd23898e0b 100644
--- a/clang/lib/Sema/SemaLifetimeSafety.h
+++ b/clang/lib/Sema/SemaLifetimeSafety.h
@@ -58,6 +58,11 @@ inline bool ShouldCheckLifetimeboundViolations(Sema &S, const Decl *D) {
diag::warn_lifetime_safety_lifetimebound_violation, D->getBeginLoc());
}
+inline bool ShouldCheckCaptureByViolations(Sema &S, const Decl *D) {
+ return !S.getDiagnostics().isIgnored(
+ diag::warn_lifetime_safety_capture_by_violation, D->getBeginLoc());
+}
+
inline bool ShouldCheckMisplacedLifetimebound(Sema &S, const Decl *D) {
DiagnosticsEngine &Diags = S.getDiagnostics();
constexpr unsigned DiagIDs[] = {
@@ -130,6 +135,7 @@ inline bool IsLifetimeSafetyEnabled(Sema &S, const Decl *D) {
return ShouldCheckSafety(S, D) || ShouldCheckNoescapeViolations(S, D) ||
ShouldCheckLifetimeboundViolations(S, D) ||
+ ShouldCheckCaptureByViolations(S, D) ||
ShouldCheckMisplacedLifetimebound(S, D) ||
ShouldCheckInapplicableLifetimebound(S, D) ||
ShouldCheckFieldOriginEscape(S, D) ||
@@ -149,6 +155,7 @@ inline LifetimeSafetyOpts GetLifetimeSafetyOpts(Sema &S, const Decl *D) {
ShouldCheckInapplicableLifetimebound(S, D);
LSOpts.CheckFieldOriginEscape = ShouldCheckFieldOriginEscape(S, D);
LSOpts.CheckDestructorUses = ShouldCheckDestructorUses(S, D);
+ LSOpts.CheckCaptureByViolations = ShouldCheckCaptureByViolations(S, D);
return LSOpts;
}
@@ -393,6 +400,24 @@ class LifetimeSafetySemaHelperImpl final : public LifetimeSafetySemaHelper {
<< 2 << "" << Attr->getRange();
}
+ void reportCaptureByViolation(const ParmVarDecl *PVD,
+ const LifetimeCaptureByAttr *Attr,
+ CapturingEntity Entity,
+ const ValueDecl *CapturedBy) override {
+ assert(!Attr->isImplicit() && "only written attributes are verified");
+ S.Diag(Attr->getLocation(), diag::warn_lifetime_safety_capture_by_violation)
+ << PVD << (Entity == CapturingEntity::Global) << Attr->getRange();
+ if (!CapturedBy)
+ return;
+ unsigned NoteID = diag::note_lifetime_safety_escapes_to_global_here;
+ if (isa<FieldDecl>(CapturedBy))
+ NoteID = diag::note_lifetime_safety_escapes_to_field_here;
+ else if (const auto *VD = cast<VarDecl>(CapturedBy);
+ VD->isStaticLocal() || VD->isStaticDataMember())
+ NoteID = diag::note_lifetime_safety_escapes_to_static_storage_here;
+ S.Diag(CapturedBy->getLocation(), NoteID) << CapturedBy->getEndLoc();
+ }
+
void reportMisplacedLifetimebound(WarningScope Scope,
const CXXMethodDecl *FDef,
const CXXMethodDecl *FDecl) override {
diff --git a/clang/test/Sema/LifetimeSafety/capture-by-violation.cpp b/clang/test/Sema/LifetimeSafety/capture-by-violation.cpp
new file mode 100644
index 00000000000000..b63b2b21cac4c6
--- /dev/null
+++ b/clang/test/Sema/LifetimeSafety/capture-by-violation.cpp
@@ -0,0 +1,154 @@
+// RUN: %clang_cc1 -fsyntax-only -Wlifetime-safety-capture-by-violation -verify %s
+// RUN: %clang_cc1 -fsyntax-only -Wlifetime-safety-annotation-verification -verify=expected,verification %s
+
+#include "Inputs/lifetime-analysis.h"
+
+struct Cap { const int *p; };
+const int *global; // expected-note 4 {{escapes to this global storage}}
+void takeString(std::string &&);
+const int &id(const int &v [[clang::lifetimebound]]);
+
+struct S {
+ const int *field; // expected-note 6 {{escapes to this field}} verification-note {{escapes to this field}}
+ std::string_view view; // expected-note {{escapes to this field}}
+ std::vector<std::string_view> views; // expected-note {{escapes to this field}}
+ static const int *static_field; // expected-note {{escapes to this static storage}}
+
+ void captured(const int &x [[clang::lifetime_capture_by_this]]);
+
+ void field_store(Cap &c, const int &x [[clang::lifetime_capture_by(c)]]) { // expected-warning {{'x' is captured by this object but is not marked [[clang::lifetime_capture_by_this]]}}
+ field = &x;
+ }
+
+ void also_into_param(Cap &c, const int &x [[clang::lifetime_capture_by(c)]]) { // expected-warning {{'x' is captured by this object but is not marked [[clang::lifetime_capture_by_this]]}}
+ c.p = &x;
+ field = &x;
+ }
+
+ void into_param(Cap &c, const int &x [[clang::lifetime_capture_by(c)]]) {
+ c.p = &x;
+ }
+
+ void conditional(bool b, Cap &c, const int &x [[clang::lifetime_capture_by(c)]]) { // expected-warning {{'x' is captured by this object but is not marked [[clang::lifetime_capture_by_this]]}}
+ if (b)
+ field = &x;
+ }
+
+ void through_lifetimebound_call(Cap &c, const int &x [[clang::lifetime_capture_by(c)]]) { // expected-warning {{'x' is captured by this object but is not marked [[clang::lifetime_capture_by_this]]}}
+ field = &id(x);
+ }
+
+ // A capture by this object in a call has no field to point at.
+ void call_capturing_this(Cap &c, const int &x [[clang::lifetime_capture_by(c)]]) { // expected-warning {{'x' is captured by this object but is not marked [[clang::lifetime_capture_by_this]]}}
+ captured(x);
+ }
+
+ // `push_back` of a standard container is inferred to capture by `this`.
+ void into_container(Cap &c, std::string_view s [[clang::lifetime_capture_by(c)]]) { // expected-warning {{'s' is captured by this object but is not marked [[clang::lifetime_capture_by_this]]}}
+ views.push_back(s);
+ }
+
+ void captured_by_this(const int &x [[clang::lifetime_capture_by_this]]) {
+ field = &x;
+ }
+
+ void captured_by_param_and_this(
+ Cap &c,
+ const int &x [[clang::lifetime_capture_by(c), clang::lifetime_capture_by_this]]) {
+ field = &x;
+ }
+
+ void deprecated_this(const int &x [[clang::lifetime_capture_by(this)]]) { // expected-warning {{'lifetime_capture_by(this)' is deprecated; use 'lifetime_capture_by_this' instead}}
+ field = &x;
+ }
+
+ void captured_by_unknown(const int &x [[clang::lifetime_capture_by_unknown]]) {
+ field = &x;
+ global = &x;
+ }
+
+ void into_global(const int &x [[clang::lifetime_capture_by_this]]) { // expected-warning {{'x' is captured by global storage but is not marked [[clang::lifetime_capture_by_global]]}}
+ global = &x;
+ }
+
+ void into_static_member(const int &x [[clang::lifetime_capture_by_this]]) { // expected-warning {{'x' is captured by global storage but is not marked [[clang::lifetime_capture_by_global]]}}
+ static_field = &x;
+ }
+
+ void into_this_and_global(Cap &c, const int &x [[clang::lifetime_capture_by(c)]]) { // expected-warning {{'x' is captured by this object but is not marked [[clang::lifetime_capture_by_this]]}} \
+ // expected-warning {{'x' is captured by global storage but is not marked [[clang::lifetime_capture_by_global]]}}
+ field = &x;
+ global = &x;
+ }
+
+ static void static_into_global(Cap &c, const int &x [[clang::lifetime_capture_by(c)]]) { // expected-warning {{'x' is captured by global storage but is not marked [[clang::lifetime_capture_by_global]]}}
+ global = &x;
+ }
+
+ // An unnamed parameter cannot be referred to, so it is not captured.
+ void unnamed(Cap &c, const int & [[clang::lifetime_capture_by(c)]]) {
+ field = nullptr;
+ }
+
+ void view_store(Cap &c, std::string &s [[clang::lifetime_capture_by(c)]]) { // expected-warning {{'s' is captured by this object but is not marked [[clang::lifetime_capture_by_this]]}}
+ view = s;
+ }
+
+ // The ownership of a moved argument is transferred.
+ void moved(Cap &c, std::string &s [[clang::lifetime_capture_by(c)]]) {
+ view = s;
+ takeString(std::move(s));
+ }
+
+ void noescape(Cap &c, const int &x [[clang::noescape, clang::lifetime_capture_by(c)]]) { // verification-warning {{parameter is marked [[clang::noescape]] but escapes}}
+ field = &x;
+ }
+
+ void unannotated(const int &x) {
+ field = &x;
+ }
+
+ void declared_only(Cap &c, const int &x [[clang::lifetime_capture_by(c)]]); // expected-warning {{'x' is captured by this object but is not marked [[clang::lifetime_capture_by_this]]}}
+
+ // FIXME: The capturers of a lambda's parameters are never resolved, so they
+ // are not verified.
+ void lambda() {
+ auto L = [](Cap &c, const int &x [[clang::lifetime_capture_by(c)]]) {
+ global = &x;
+ };
+ }
+};
+
+void S::declared_only(Cap &c, const int &x) {
+ field = &x;
+}
+
+struct T {
+ const int *field; // expected-note {{escapes to this field}}
+ T(Cap &c, const int &x [[clang::lifetime_capture_by(c)]]) { // expected-warning {{'x' is captured by this object but is not marked [[clang::lifetime_capture_by_this]]}}
+ field = &x;
+ }
+ T(const int &x [[clang::lifetime_capture_by_this]]) : field(&x) {}
+ T(Cap &c, const int &x [[clang::lifetime_capture_by(c), clang::lifetimebound]], int)
+ : field(&x) {}
+};
+
+template <typename U> struct TS {
+ const U *field; // expected-note {{escapes to this field}}
+ void store(Cap &c, const U &x [[clang::lifetime_capture_by(c)]]) { // expected-warning {{'x' is captured by this object but is not marked [[clang::lifetime_capture_by_this]]}}
+ field = &x;
+ }
+};
+template struct TS<int>; // expected-note {{in instantiation of member function 'TS<int>::store' requested here}}
+
+void free_into_global(Cap &c, const int &x [[clang::lifetime_capture_by(c)]]) { // expected-warning {{'x' is captured by global storage but is not marked [[clang::lifetime_capture_by_global]]}}
+ global = &x;
+}
+
+void free_captured_by_global(const int &x [[clang::lifetime_capture_by_global]]) {
+ global = &x;
+}
+
+void deprecated_global(const int &x [[clang::lifetime_capture_by(global)]]) { // expected-warning {{'lifetime_capture_by(global)' is deprecated; use 'lifetime_capture_by_global' instead}}
+ global = &x;
+}
More information about the cfe-commits
mailing list