[clang] [Clang][LifetimeSafety] Support [[clang::coro_lifetimebound]] (PR #247660)
via cfe-commits
cfe-commits at lists.llvm.org
Wed Dec 2 10:06:00 PST 2026
https://github.com/etiennep-chromium updated https://github.com/llvm/llvm-project/pull/247660
>From da11d750173b939395a34aa87e79e6b6d1eb1b23 Mon Sep 17 00:00:00 2001
From: Etienne Pierre-doray <etiennep at chromium.org>
Date: Tue, 1 Dec 2026 14:14:43 +0000
Subject: [PATCH 1/2] [Clang][LifetimeSafety] Support
[[clang::coro_lifetimebound]]
Extend Clang's CFG-based lifetime safety analysis (-Wlifetime-safety) to
recognize coroutine return types annotated with
[[clang::coro_return_type, clang::coro_lifetimebound]], sharing the core
predicate with Sema's statement-local CheckExprLifetime handling:
- Add isCoroLifetimeBoundType() and isCoroLifetimeBoundCall()
(respecting [[clang::coro_disable_lifetimebound]]) in
LifetimeAnnotations, and reuse isCoroLifetimeBoundCall() from
CheckExprLifetime to avoid drift between the two analyses.
- Track coroutine parameters and implicit/explicit object arguments in
getTrackedArgInfo(), excluding promise get_return_object() and
captureless lambdas. Unlike Sema's syntactic LambdaExpr check, this
checks the closure record's capture_size() == 0 so named captureless
lambdas are also exempted (their operator() never reads *this).
- Treat [[clang::coro_return_type, clang::coro_lifetimebound]] types as
origin-bearing in OriginManager::hasOrigins() and propagate origins
across their copy/move constructors, assignments, rvalue-ref calls,
and lifetime_capture_by parameters in FactsGenerator. Coroutine return
types are kept distinct from isPointerLikeType()/isGslPointerType() so
they do not trigger GSL pointer inference (e.g. return-type tracking
or implicit object tracking on unrelated methods).
- Suppress redundant [[clang::lifetimebound]] annotation suggestions in
Checker when the function is already covered by coro_lifetimebound.
This enables -Wlifetime-safety to diagnose inner-scope and loop-local
escapes into stored coroutine handles and containers without manual
[[clang::lifetimebound]] annotations on every coroutine parameter.
---
clang/docs/ReleaseNotes.md | 5 +
.../LifetimeSafety/LifetimeAnnotations.h | 9 +
clang/lib/Analysis/LifetimeSafety/Checker.cpp | 17 +-
.../LifetimeSafety/FactsGenerator.cpp | 30 +-
.../LifetimeSafety/LifetimeAnnotations.cpp | 25 +-
clang/lib/Analysis/LifetimeSafety/Origins.cpp | 3 +-
clang/lib/Sema/CheckExprLifetime.cpp | 7 +-
.../LifetimeSafety/coro-lifetimebound.cpp | 431 ++++++++++++++++++
8 files changed, 499 insertions(+), 28 deletions(-)
create mode 100644 clang/test/Sema/LifetimeSafety/coro-lifetimebound.cpp
diff --git a/clang/docs/ReleaseNotes.md b/clang/docs/ReleaseNotes.md
index c221b0d7f0fa08..29603d3b6e2f4c 100644
--- a/clang/docs/ReleaseNotes.md
+++ b/clang/docs/ReleaseNotes.md
@@ -744,6 +744,11 @@ documentation](CIR/index.md) for more information regarding ClangIR's status and
- Lifetime safety analysis is now enabled for C by default. The `-fexperimental-lifetime-safety-c`
flag is renamed to `-flifetime-safety-c`. Use `-fno-lifetime-safety-c` to disable it.
+- Lifetime safety analysis (`-Wlifetime-safety`) now tracks coroutine return
+ types annotated with `[[clang::coro_return_type, clang::coro_lifetimebound]]`,
+ diagnosing dangling references, views, and object arguments that outlive
+ their scope across stored coroutine handles and containers.
+
- Improved `-Wassign-enum` performance by caching enum enumerator values. (#GH176454)
- Fixed a false negative in `-Warray-bounds` where the warning was suppressed
diff --git a/clang/include/clang/Analysis/Analyses/LifetimeSafety/LifetimeAnnotations.h b/clang/include/clang/Analysis/Analyses/LifetimeSafety/LifetimeAnnotations.h
index f0b1dd0ad94e51..cc089f2318076b 100644
--- a/clang/include/clang/Analysis/Analyses/LifetimeSafety/LifetimeAnnotations.h
+++ b/clang/include/clang/Analysis/Analyses/LifetimeSafety/LifetimeAnnotations.h
@@ -139,6 +139,15 @@ bool isGslPointerType(QualType QT);
bool isGslOwnerType(QualType QT);
bool isGslOwnerType(const CXXRecordDecl *RD);
+// Tells whether the type is a coroutine return type annotated with both
+// [[clang::coro_return_type]] and [[clang::coro_lifetimebound]].
+bool isCoroLifetimeBoundType(QualType QT);
+
+// Returns true if calls to \p FD return a [[clang::coro_return_type,
+// clang::coro_lifetimebound]] type and \p FD is not annotated with
+// [[clang::coro_disable_lifetimebound]].
+bool isCoroLifetimeBoundCall(const FunctionDecl *FD);
+
// Tells whether the given constructor belongs to an Owner type and the
// parameter is of pointer type. This is useful to disable inference on owning
// pointers being captured by owners.
diff --git a/clang/lib/Analysis/LifetimeSafety/Checker.cpp b/clang/lib/Analysis/LifetimeSafety/Checker.cpp
index 59e382a8aef234..fcde741b1b4c02 100644
--- a/clang/lib/Analysis/LifetimeSafety/Checker.cpp
+++ b/clang/lib/Analysis/LifetimeSafety/Checker.cpp
@@ -174,11 +174,13 @@ class LifetimeChecker {
VerifiedLiftimeboundEscapes.insert(PVD);
} else {
// Otherwise, suggest lifetimebound for parameter escaping through
- // return or a field in constructor.
- if (auto *ReturnEsc = dyn_cast<ReturnEscapeFact>(OEF))
- AnnotationWarningsMap.try_emplace(PVD, ReturnEsc->getReturnExpr());
- else if (auto *FieldEsc = dyn_cast<FieldEscapeFact>(OEF);
- FieldEsc && isa<CXXConstructorDecl>(FD)) {
+ // return or a field in constructor (unless already covered by
+ // coro_lifetimebound).
+ if (auto *ReturnEsc = dyn_cast<ReturnEscapeFact>(OEF)) {
+ if (!isCoroLifetimeBoundCall(dyn_cast<FunctionDecl>(FD)))
+ AnnotationWarningsMap.try_emplace(PVD, ReturnEsc->getReturnExpr());
+ } else if (auto *FieldEsc = dyn_cast<FieldEscapeFact>(OEF);
+ FieldEsc && isa<CXXConstructorDecl>(FD)) {
// Disable inference for pointers being captured by an owner type,
// as owners typically consume these pointers rather than borrow them.
if (!isOwnerPtrCtor(dyn_cast<CXXConstructorDecl>(FD), PVD))
@@ -192,7 +194,7 @@ class LifetimeChecker {
if (auto *ReturnEsc = dyn_cast<ReturnEscapeFact>(OEF)) {
if (implicitObjectParamIsLifetimeBound(MD))
VerifiedLiftimeboundEscapes.insert(MD);
- else
+ else if (!isCoroLifetimeBoundCall(MD))
AnnotationWarningsMap.try_emplace(MD, ReturnEsc->getReturnExpr());
}
};
@@ -203,7 +205,8 @@ class LifetimeChecker {
return;
// Lifetimebound marks the field as owned by *this (e.g., Vector::data()).
const auto *MD = dyn_cast<CXXMethodDecl>(FD);
- if (MD && implicitObjectParamIsLifetimeBound(MD))
+ if (MD && (implicitObjectParamIsLifetimeBound(MD) ||
+ isCoroLifetimeBoundCall(MD)))
return;
if (auto *ReturnEsc = dyn_cast<ReturnEscapeFact>(OEF)) {
// Ignore field loans in inner origins, e.g., returning a reference to
diff --git a/clang/lib/Analysis/LifetimeSafety/FactsGenerator.cpp b/clang/lib/Analysis/LifetimeSafety/FactsGenerator.cpp
index 7fc7c933f72186..30eed27daec677 100644
--- a/clang/lib/Analysis/LifetimeSafety/FactsGenerator.cpp
+++ b/clang/lib/Analysis/LifetimeSafety/FactsGenerator.cpp
@@ -221,12 +221,13 @@ void FactsGenerator::VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
handleGSLPointerConstruction(CCE);
return;
}
- // For defaulted (implicit or `= default`) copy/move constructors, propagate
- // origins directly. User-defined copy/move constructors are not handled here
- // as they have opaque semantics.
+ // For defaulted (implicit or `= default`) copy/move constructors, or
+ // copy/move constructors of coro_lifetimebound handles, propagate origins
+ // directly. Other user-defined copy/move constructors have opaque semantics.
if (CCE->getConstructor()->isCopyOrMoveConstructor() &&
- CCE->getConstructor()->isDefaulted() && CCE->getNumArgs() == 1 &&
- hasOrigins(CCE->getType())) {
+ (CCE->getConstructor()->isDefaulted() ||
+ isCoroLifetimeBoundType(CCE->getType())) &&
+ CCE->getNumArgs() == 1 && hasOrigins(CCE->getType())) {
const Expr *Arg = CCE->getArg(0);
if (OriginList *ArgList = readValue(Arg)) {
flow(getOriginsList(*CCE), ArgList, /*Kill=*/true);
@@ -618,9 +619,10 @@ bool FactsGenerator::handleAssignmentOperatorCall(const CallExpr *CE,
QualType LHSTy = LHSExpr->getType();
if (!hasOrigins(LHSTy))
return false;
- // Pointer-like types: assignment inherently propagates origins.
+ // Pointer-like and coro_lifetimebound types: assignment inherently
+ // propagates origins.
if (LHSTy->isPointerOrReferenceType() || isGslPointerType(LHSTy) ||
- isGslOwnerType(LHSTy)) {
+ isGslOwnerType(LHSTy) || isCoroLifetimeBoundType(LHSTy)) {
handleAssignment(CE, LHSExpr, RHSExpr);
return true;
}
@@ -1033,9 +1035,11 @@ void FactsGenerator::handleMovedArgsInCall(const FunctionDecl *FD,
continue;
// Skip lifetime annotated r-value reference parameters. Lifetime annotation
// indicates that the parameter is borrowed (not consumed), so it should not
- // be marked as moved even though it's an r-value reference.
+ // be marked as moved even though it's an r-value reference. Similarly, a
+ // coro_lifetimebound call captures an r-value reference into the coroutine
+ // frame rather than consuming the object immediately at the call site.
if (PVD->hasAttr<LifetimeBoundAttr>() ||
- PVD->hasAttr<LifetimeCaptureByAttr>())
+ PVD->hasAttr<LifetimeCaptureByAttr>() || isCoroLifetimeBoundCall(FD))
continue;
const Expr *Arg = Args[I];
OriginList *MovedOrigins = getOriginsList(*Arg);
@@ -1143,11 +1147,13 @@ void FactsGenerator::handleLifetimeCaptureBy(const FunctionDecl *FD,
OriginList *CapturedOriginList = getOriginsList(*Args[I]);
if (!CapturedOriginList)
continue;
- // For references to pointer-like types, peel the outer origin (the pointer
- // object itself) so that we capture the underlying data (the inner origin).
+ // For references to pointer-like or coro_lifetimebound types, peel the
+ // outer origin (the pointer/handle object itself) so that we capture the
+ // underlying data (the inner origin).
if (!ParamType.isNull() &&
(ParamType->isReferenceType() &&
- isPointerLikeType(ParamType->getPointeeType())) &&
+ (isPointerLikeType(ParamType->getPointeeType()) ||
+ isCoroLifetimeBoundType(ParamType->getPointeeType()))) &&
CapturedOriginList->getLength() > 1)
CapturedOriginList = CapturedOriginList->peelOuterOrigin();
for (int CapturingArgIdx : Attr->params()) {
diff --git a/clang/lib/Analysis/LifetimeSafety/LifetimeAnnotations.cpp b/clang/lib/Analysis/LifetimeSafety/LifetimeAnnotations.cpp
index 2807a624159047..7d1816e38abf77 100644
--- a/clang/lib/Analysis/LifetimeSafety/LifetimeAnnotations.cpp
+++ b/clang/lib/Analysis/LifetimeSafety/LifetimeAnnotations.cpp
@@ -162,6 +162,12 @@ const ParmVarDecl *getParamForArg(const FunctionDecl &FD, unsigned I) {
return I < FD.getNumParams() ? FD.getParamDecl(I) : nullptr;
}
+static bool canBeGetReturnObject(const FunctionDecl *FD) {
+ return isa<CXXMethodDecl>(FD) && FD->param_empty() &&
+ FD->getDeclName().isIdentifier() &&
+ FD->getName() == "get_return_object";
+}
+
std::optional<LifetimeBoundParamInfo>
getTrackedArgInfo(const FunctionDecl *FD, llvm::ArrayRef<const Expr *> Args,
unsigned I) {
@@ -169,10 +175,14 @@ getTrackedArgInfo(const FunctionDecl *FD, llvm::ArrayRef<const Expr *> Args,
if (!FD || I >= Args.size())
return std::nullopt;
+ bool IsCoroCall = isCoroLifetimeBoundCall(FD);
if (I == 0 && hasObjectArg(*FD)) {
const auto *Method = cast<CXXMethodDecl>(FD);
+ bool IsCoroObjArg = IsCoroCall && !canBeGetReturnObject(Method) &&
+ !(Method->getParent()->isLambda() &&
+ Method->getParent()->capture_size() == 0);
bool TrackObject =
- implicitObjectParamIsLifetimeBound(Method) ||
+ implicitObjectParamIsLifetimeBound(Method) || IsCoroObjArg ||
shouldTrackImplicitObjectArg(*Args[0], Method,
/*RunningUnderLifetimeSafety=*/true);
if (hasImplicitObjectArg(*FD))
@@ -190,7 +200,7 @@ getTrackedArgInfo(const FunctionDecl *FD, llvm::ArrayRef<const Expr *> Args,
}
if (const ParmVarDecl *PVD = getParamForArg(*FD, I);
- PVD && paramIsLifetimeBound(*PVD))
+ PVD && (paramIsLifetimeBound(*PVD) || IsCoroCall))
return LifetimeBoundParamInfo(PVD);
return std::nullopt;
@@ -423,6 +433,17 @@ bool isGslOwnerType(const CXXRecordDecl *RD) {
return isRecordWithAttr<OwnerAttr>(RD);
}
+bool isCoroLifetimeBoundType(QualType QT) {
+ return isRecordWithAttr<CoroLifetimeBoundAttr>(QT) &&
+ isRecordWithAttr<CoroReturnTypeAttr>(QT);
+}
+
+bool isCoroLifetimeBoundCall(const FunctionDecl *FD) {
+ FD = getDeclWithMergedLifetimeBoundAttrs(FD);
+ return FD && !FD->hasAttr<CoroDisableLifetimeBoundAttr>() &&
+ isCoroLifetimeBoundType(FD->getReturnType());
+}
+
bool isOwnerPtrCtor(const CXXConstructorDecl *Ctor, const ParmVarDecl *PVD) {
return Ctor && PVD->getType()->isPointerType() &&
isGslOwnerType(Ctor->getParent());
diff --git a/clang/lib/Analysis/LifetimeSafety/Origins.cpp b/clang/lib/Analysis/LifetimeSafety/Origins.cpp
index d5a55d4d3d0d35..25512ed91e2e58 100644
--- a/clang/lib/Analysis/LifetimeSafety/Origins.cpp
+++ b/clang/lib/Analysis/LifetimeSafety/Origins.cpp
@@ -137,7 +137,8 @@ class LifetimeAnnotatedOriginTypeCollector
} // namespace
bool OriginManager::hasOrigins(QualType QT, bool IntrinsicOnly) const {
- if (QT->isPointerOrReferenceType() || isGslPointerType(QT))
+ if (QT->isPointerOrReferenceType() || isGslPointerType(QT) ||
+ isCoroLifetimeBoundType(QT))
return true;
if (!IntrinsicOnly &&
LifetimeAnnotatedOriginTypes.contains(QT.getCanonicalType().getTypePtr()))
diff --git a/clang/lib/Sema/CheckExprLifetime.cpp b/clang/lib/Sema/CheckExprLifetime.cpp
index fafee76ec18c30..22d1f52c96a40f 100644
--- a/clang/lib/Sema/CheckExprLifetime.cpp
+++ b/clang/lib/Sema/CheckExprLifetime.cpp
@@ -460,12 +460,7 @@ static void visitFunctionCallArguments(IndirectLocalPath &Path, Expr *Call,
Path.pop_back();
};
- bool CheckCoroCall = false;
- if (const auto *RD = Callee->getReturnType()->getAsRecordDecl()) {
- CheckCoroCall = RD->hasAttr<CoroLifetimeBoundAttr>() &&
- RD->hasAttr<CoroReturnTypeAttr>() &&
- !Callee->hasAttr<CoroDisableLifetimeBoundAttr>();
- }
+ bool CheckCoroCall = lifetimes::isCoroLifetimeBoundCall(Callee);
if (ObjectArg) {
bool CheckCoroObjArg = CheckCoroCall;
diff --git a/clang/test/Sema/LifetimeSafety/coro-lifetimebound.cpp b/clang/test/Sema/LifetimeSafety/coro-lifetimebound.cpp
new file mode 100644
index 00000000000000..9bb38c0027d473
--- /dev/null
+++ b/clang/test/Sema/LifetimeSafety/coro-lifetimebound.cpp
@@ -0,0 +1,431 @@
+// RUN: %clang_cc1 -std=c++23 -fsyntax-only -Wno-dangling -Wlifetime-safety -Wlifetime-safety-lifetimebound-violation -Wlifetime-safety-suggestions -verify=expected,suggest %s
+// RUN: %clang_cc1 -std=c++23 -fsyntax-only -Wno-dangling -Wlifetime-safety-permissive -verify=expected %s
+
+#include "Inputs/lifetime-analysis.h"
+
+namespace std {
+template <class Ret, typename... T>
+struct coroutine_traits {
+ using promise_type = typename Ret::promise_type;
+};
+
+template <class Promise = void>
+struct coroutine_handle {
+ static coroutine_handle from_address(void *) noexcept;
+ static coroutine_handle from_promise(Promise &promise);
+ constexpr void *address() const noexcept;
+};
+
+template <>
+struct coroutine_handle<void> {
+ template <class PromiseType>
+ coroutine_handle(coroutine_handle<PromiseType>) noexcept;
+ static coroutine_handle from_address(void *);
+ constexpr void *address() const noexcept;
+};
+
+struct suspend_always {
+ bool await_ready() noexcept { return false; }
+ void await_suspend(coroutine_handle<>) noexcept {}
+ void await_resume() noexcept {}
+};
+} // namespace std
+
+// Coroutine return type without [[gsl::Pointer]], with user-defined move
+// constructor and move assignment (matching real coroutine handle types).
+template <typename T>
+struct [[clang::coro_return_type, clang::coro_lifetimebound]] Co {
+ struct promise_type {
+ Co<T> get_return_object() { return {}; }
+ std::suspend_always initial_suspend() noexcept;
+ std::suspend_always final_suspend() noexcept;
+ void unhandled_exception();
+ void return_value(const T &t);
+
+ template <typename U>
+ auto await_transform(const Co<U> &) {
+ struct awaitable {
+ bool await_ready() noexcept { return false; }
+ void await_suspend(std::coroutine_handle<>) noexcept {}
+ U await_resume() noexcept { return {}; }
+ };
+ return awaitable{};
+ }
+ };
+
+ Co() = default;
+ Co(const Co &other) {}
+ Co(Co &&other) noexcept {}
+ Co &operator=(const Co &other) { return *this; }
+ Co &operator=(Co &&other) noexcept { return *this; }
+ ~Co() {}
+};
+
+// Coroutine return type also marked [[gsl::Pointer]] for STL container
+// capture-by inference (e.g. std::vector::push_back).
+template <typename T>
+struct [[clang::coro_return_type, clang::coro_lifetimebound, gsl::Pointer]]
+Step {
+ struct promise_type {
+ Step<T> get_return_object() { return {}; }
+ std::suspend_always initial_suspend() noexcept;
+ std::suspend_always final_suspend() noexcept;
+ void unhandled_exception();
+ void return_value(const T &t);
+ };
+ Step() = default;
+ Step(Step &&other) noexcept {}
+ Step &operator=(Step &&other) noexcept { return *this; }
+};
+
+Co<int> ref_coro(const int &b) { co_return b; }
+Co<int> ptr_coro(const int *p) { co_return *p; }
+Co<int> rref_coro(int &&r) { co_return r; }
+Co<int> view_coro(std::string_view sv) { co_return sv.size(); }
+Co<int> val_int_coro(int v) { co_return v; }
+Co<int> val_str_coro(std::string s) { co_return 0; }
+Step<int> step_ref_coro(const int &b) { co_return b; }
+Step<int> step_val_coro(std::string s) { co_return 0; }
+
+void consume(Co<int> &);
+void consume(std::vector<Step<int>> &);
+
+// =============================================================================
+// 1. Reference, pointer, rvalue-ref, and view parameters across scopes
+// =============================================================================
+void inner_scope_ref_escapes() {
+ Co<int> saved;
+ {
+ int local = 1;
+ saved = ref_coro(local); // expected-warning {{local variable 'local' does not live long enough}} \
+ // expected-note {{result of call to 'ref_coro' aliases the storage of local variable 'local' because parameter 'b' is inferred as lifetimebound}}
+ } // expected-note {{destroyed here}}
+ consume(saved); // expected-note {{later used here}}
+}
+
+void inner_scope_ptr_escapes() {
+ Co<int> saved;
+ {
+ int local = 1;
+ saved = ptr_coro(&local); // expected-warning {{local variable 'local' does not live long enough}} \
+ // expected-note {{result of call to 'ptr_coro' aliases the storage of local variable 'local' because parameter 'p' is inferred as lifetimebound}}
+ } // expected-note {{destroyed here}}
+ consume(saved); // expected-note {{later used here}}
+}
+
+void inner_scope_rref_escapes() {
+ Co<int> saved;
+ {
+ int local = 1;
+ saved = rref_coro(std::move(local)); // expected-warning {{local variable 'local' does not live long enough}} \
+ // expected-note {{result of call to 'move<int &>' aliases the storage of local variable 'local' because parameter 't' is inferred as lifetimebound}} \
+ // expected-note {{result of call to 'rref_coro' aliases the storage of local variable 'local' because parameter 'r' is inferred as lifetimebound}}
+ } // expected-note {{destroyed here}}
+ consume(saved); // expected-note {{later used here}}
+}
+
+void inner_scope_view_escapes() {
+ Co<int> saved;
+ {
+ std::string local;
+ saved = view_coro(local); // expected-warning {{local variable 'local' does not live long enough}} \
+ // expected-note {{result of call to 'view_coro' aliases the storage of local variable 'local' because parameter 'sv' is inferred as lifetimebound}}
+ } // expected-note {{destroyed here}}
+ consume(saved); // expected-note {{later used here}}
+}
+
+void temporary_arg_used_later() {
+ auto c = ref_coro(1); // expected-warning {{temporary object does not live long enough}} \
+ // expected-note {{destroyed here}} \
+ // expected-note {{result of call to 'ref_coro' aliases the storage of temporary object because parameter 'b' is inferred as lifetimebound}}
+ consume(c); // expected-note {{later used here}}
+}
+
+void move_propagates_loan() {
+ Co<int> outer;
+ {
+ int local = 1;
+ Co<int> inner = ref_coro(local); // expected-warning {{local variable 'local' does not live long enough}} \
+ // expected-note {{result of call to 'ref_coro' aliases the storage of local variable 'local' because parameter 'b' is inferred as lifetimebound}}
+ outer = std::move(inner); // expected-note {{result of call to 'move<Co<int> &>' aliases the storage of local variable 'local'}}
+ } // expected-note {{destroyed here}}
+ consume(outer); // expected-note {{later used here}}
+}
+
+// =============================================================================
+// 2. Safe by-value owning parameters and same-statement co_await
+// =============================================================================
+void by_value_params_safe() {
+ Co<int> saved1, saved2;
+ {
+ int local_i = 1;
+ std::string local_s;
+ saved1 = val_int_coro(local_i);
+ saved2 = val_str_coro(local_s);
+ }
+ consume(saved1);
+ consume(saved2);
+}
+
+Co<int> same_statement_co_await_safe(const int ¶m) {
+ int a = 1;
+ int r1 = co_await ref_coro(1);
+ int r2 = co_await ref_coro(a);
+ int r3 = co_await [a](const int &y) -> Co<int> { co_return a + y; }(1);
+ co_return r1 + r2 + r3 + param;
+}
+
+Co<int> stored_temporary_awaited_later() {
+ auto c = ref_coro(1); // expected-warning {{temporary object does not live long enough}} \
+ // expected-note {{destroyed here}} \
+ // expected-note {{result of call to 'ref_coro' aliases the storage of temporary object because parameter 'b' is inferred as lifetimebound}}
+ co_return co_await c; // expected-note {{later used here}}
+}
+
+// =============================================================================
+// 3. Return stack address through wrapper functions
+// =============================================================================
+[[clang::coro_wrapper]] Co<int> return_param_ref(int b) {
+ return ref_coro(b); // expected-warning {{stack memory associated with parameter 'b' is returned}} \
+ // expected-note {{result of call to 'ref_coro' aliases the storage of parameter 'b' because parameter 'b' is inferred as lifetimebound}} \
+ // expected-note {{returned here}}
+}
+
+[[clang::coro_wrapper]] Co<int> safe_forwarding(const int &b) {
+ return ref_coro(b);
+}
+
+[[clang::coro_wrapper]] Co<int> return_via_wrapper(int b) {
+ return safe_forwarding(b); // expected-warning {{stack memory associated with parameter 'b' is returned}} \
+ // expected-note {{result of call to 'safe_forwarding' aliases the storage of parameter 'b' because parameter 'b' is inferred as lifetimebound}} \
+ // expected-note {{returned here}}
+}
+
+[[clang::coro_wrapper]] Co<int> return_by_value_safe(int b) {
+ return val_int_coro(b);
+}
+
+// =============================================================================
+// 4. Member coroutines (implicit and explicit 'this') and lambdas
+// =============================================================================
+struct Owner {
+ int x = 0;
+ Co<int> member(const int &a) { co_return x + a; }
+ Co<int> explicit_this(this Owner &self, const int &a) {
+ co_return self.x + a;
+ }
+};
+
+void member_receiver_escapes(const int &a) {
+ Co<int> saved;
+ {
+ Owner o;
+ saved = o.member(a); // expected-warning {{local variable 'o' does not live long enough}} \
+ // expected-note {{result of call to 'member' aliases the storage of local variable 'o' because the implicit object parameter is inferred as lifetimebound}}
+ } // expected-note {{destroyed here}}
+ consume(saved); // expected-note {{later used here}}
+}
+
+void member_temp_receiver(const int &a) {
+ auto c = Owner{}.member(a); // expected-warning {{temporary object does not live long enough}} \
+ // expected-note {{destroyed here}} \
+ // expected-note {{result of call to 'member' aliases the storage of temporary object because the implicit object parameter is inferred as lifetimebound}}
+ consume(c); // expected-note {{later used here}}
+}
+
+void explicit_this_receiver_escapes(const int &a) {
+ Co<int> saved;
+ {
+ Owner o;
+ saved = o.explicit_this(a); // expected-warning {{local variable 'o' does not live long enough}} \
+ // expected-note {{result of call to 'explicit_this' aliases the storage of local variable 'o' because parameter 'self' is inferred as lifetimebound}}
+ } // expected-note {{destroyed here}}
+ consume(saved); // expected-note {{later used here}}
+}
+
+void lambda_captures() {
+ int a = 1;
+ // Capturing temporary lambda dies at semicolon.
+ auto bad_lam = [a]() -> Co<int> { co_return a; }(); // expected-warning {{temporary object does not live long enough}} \
+ // expected-note {{destroyed here}} \
+ // expected-note {{result of call to 'operator()' aliases the storage of temporary object because the implicit object parameter is inferred as lifetimebound}}
+ consume(bad_lam); // expected-note {{later used here}}
+
+ // Captureless temporary lambda does not bind 'this'.
+ auto ok_lam = []() -> Co<int> { co_return 1; }();
+ consume(ok_lam);
+
+ // Named captureless lambda does not bind 'this' even when it goes out of
+ // scope before the returned coroutine handle is consumed.
+ Co<int> from_named_captureless;
+ {
+ auto named_ok = []() -> Co<int> { co_return 1; };
+ from_named_captureless = named_ok();
+ }
+ consume(from_named_captureless);
+
+ // Named capturing lambda escaping its scope warns.
+ Co<int> from_named_capturing;
+ {
+ auto named_bad = [a]() -> Co<int> { co_return a; };
+ from_named_capturing = named_bad(); // expected-warning {{local variable 'named_bad' does not live long enough}} \
+ // expected-note {{result of call to 'operator()' aliases the storage of local variable 'named_bad' because the implicit object parameter is inferred as lifetimebound}}
+ } // expected-note {{destroyed here}}
+ consume(from_named_capturing); // expected-note {{later used here}}
+
+ // Captureless lambda with a dangling reference parameter still warns.
+ auto bad_param = [](const int &y) -> Co<int> { co_return y; }(1); // expected-warning {{temporary object does not live long enough}} \
+ // expected-note {{destroyed here}} \
+ // expected-note {{result of call to 'operator()' aliases the storage of temporary object because parameter 'y' is inferred as lifetimebound}}
+ consume(bad_param); // expected-note {{later used here}}
+}
+
+// =============================================================================
+// 4b. Default arguments, handle copy assignment, chaining by value, templates
+// =============================================================================
+Co<int> default_arg_coro(const int &x = 1) { co_return x; }
+
+void default_arg_temp() {
+ auto c = default_arg_coro(); // expected-warning {{temporary object does not live long enough}} \
+ // expected-note {{destroyed here}} \
+ // expected-note {{result of call to 'default_arg_coro' aliases the storage of temporary object because parameter 'x' is inferred as lifetimebound}}
+ consume(c); // expected-note {{later used here}}
+}
+
+void copy_assign_handle() {
+ Co<int> saved;
+ {
+ int local = 1;
+ auto c = ref_coro(local); // expected-warning {{local variable 'local' does not live long enough}} \
+ // expected-note {{result of call to 'ref_coro' aliases the storage of local variable 'local' because parameter 'b' is inferred as lifetimebound}}
+ saved = c; // expected-note {{local variable 'c' aliases the storage of local variable 'local'}}
+ } // expected-note {{destroyed here}}
+ consume(saved); // expected-note {{later used here}}
+}
+
+Co<int> chain_by_value(Co<int> inner) { co_return co_await inner; }
+
+void chain_by_value_escapes() {
+ Co<int> outer;
+ {
+ int local = 1;
+ outer = chain_by_value(ref_coro(local)); // expected-warning {{local variable 'local' does not live long enough}} \
+ // expected-note {{result of call to 'ref_coro' aliases the storage of local variable 'local' because parameter 'b' is inferred as lifetimebound}} \
+ // expected-note {{result of call to 'chain_by_value' aliases the storage of local variable 'local' because parameter 'inner' is inferred as lifetimebound}}
+ } // expected-note {{destroyed here}}
+ consume(outer); // expected-note {{later used here}}
+}
+
+template <typename T>
+Co<int> template_coro(const T &x) {
+ co_return 0;
+}
+
+void template_coro_escapes() {
+ Co<int> saved;
+ {
+ std::string local;
+ saved = template_coro(local); // expected-warning {{local variable 'local' does not live long enough}} \
+ // expected-note {{result of call to 'template_coro<std::basic_string<char>>' aliases the storage of local variable 'local' because parameter 'x' is inferred as lifetimebound}}
+ } // expected-note {{destroyed here}}
+ consume(saved); // expected-note {{later used here}}
+}
+
+// =============================================================================
+// 5. Containers (STL vector + custom lifetime_capture_by_this)
+// =============================================================================
+void loop_local_into_vector() {
+ std::vector<Step<int>> steps;
+ for (int i = 0; i < 3; ++i) {
+ int local = i;
+ steps.push_back(step_ref_coro(local)); // expected-warning {{local variable 'local' does not live long enough}} \
+ // expected-note {{result of call to 'step_ref_coro' aliases the storage of local variable 'local' because parameter 'b' is inferred as lifetimebound}} \
+ // expected-note {{later used here}}
+ } // expected-note {{destroyed here}}
+ consume(steps);
+}
+
+void loop_by_value_into_vector_safe() {
+ std::vector<Step<int>> steps;
+ for (int i = 0; i < 3; ++i) {
+ std::string local;
+ steps.push_back(step_val_coro(local));
+ }
+ consume(steps);
+}
+
+struct CoGroup {
+ void Add(Co<int> &&c [[clang::lifetime_capture_by_this]]);
+};
+void consume(CoGroup &);
+
+void custom_container_capture(const int &outer) {
+ CoGroup g_safe;
+ g_safe.Add(ref_coro(outer));
+ consume(g_safe);
+
+ CoGroup g_bad;
+ {
+ int local = 1;
+ g_bad.Add(ref_coro(local)); // expected-warning {{local variable 'local' does not live long enough}} \
+ // expected-note {{result of call to 'ref_coro' aliases the storage of local variable 'local' because parameter 'b' is inferred as lifetimebound}}
+ } // expected-note {{destroyed here}}
+ consume(g_bad); // expected-note {{later used here}}
+}
+
+// =============================================================================
+// 6. Opt-out [[clang::coro_disable_lifetimebound]] and missing coro_return_type
+// =============================================================================
+[[clang::coro_wrapper, clang::coro_disable_lifetimebound]]
+Co<int> disabled_wrapper(const int &x) {
+ return val_int_coro(x);
+}
+
+// A coro_disable_lifetimebound wrapper that actually returns a reference-bound
+// coroutine still receives a [[clang::lifetimebound]] suggestion.
+[[clang::coro_wrapper, clang::coro_disable_lifetimebound]]
+Co<int> disabled_forwarding_wrapper(const int &x) { // suggest-warning {{parameter in intra-TU function should be marked [[clang::lifetimebound]]}}
+ return ref_coro(x); // suggest-note {{param returned here}}
+}
+
+struct DisabledOwner {
+ [[clang::coro_wrapper, clang::coro_disable_lifetimebound]]
+ Co<int> member(const int &x) {
+ return val_int_coro(x);
+ }
+};
+
+void disable_lifetimebound_safe() {
+ Co<int> saved1, saved2;
+ {
+ int local = 1;
+ DisabledOwner o;
+ saved1 = disabled_wrapper(local);
+ saved2 = o.member(local);
+ }
+ consume(saved1);
+ consume(saved2);
+}
+
+template <typename T>
+struct [[clang::coro_lifetimebound]] CoNoCRT {
+ struct promise_type {
+ CoNoCRT<T> get_return_object() { return {}; }
+ std::suspend_always initial_suspend() noexcept;
+ std::suspend_always final_suspend() noexcept;
+ void unhandled_exception();
+ void return_value(const T &t);
+ };
+};
+
+CoNoCRT<int> no_crt_coro(const int &x) { co_return x; }
+void consume(CoNoCRT<int> &);
+
+void no_coro_return_type_no_warning() {
+ CoNoCRT<int> saved;
+ {
+ int local = 1;
+ saved = no_crt_coro(local);
+ }
+ consume(saved);
+}
>From 3c7fd593b18554571d173d42c174c47530ec80e7 Mon Sep 17 00:00:00 2001
From: Etienne Pierre-doray <etiennep at chromium.org>
Date: Wed, 2 Dec 2026 17:22:41 +0000
Subject: [PATCH 2/2] [Clang][LifetimeSafety] Simplify coro-lifetimebound.cpp
test
Share a single declaration-only promise type across the coroutine return
types, trim the std coroutine stubs, make Co awaitable directly instead of
via await_transform, use the shared use() helper, shorten expected notes to
their distinguishing part, and merge closely related cases. No change in
coverage.
---
.../LifetimeSafety/coro-lifetimebound.cpp | 459 ++++++++----------
1 file changed, 191 insertions(+), 268 deletions(-)
diff --git a/clang/test/Sema/LifetimeSafety/coro-lifetimebound.cpp b/clang/test/Sema/LifetimeSafety/coro-lifetimebound.cpp
index 9bb38c0027d473..8cc5cb488d1750 100644
--- a/clang/test/Sema/LifetimeSafety/coro-lifetimebound.cpp
+++ b/clang/test/Sema/LifetimeSafety/coro-lifetimebound.cpp
@@ -4,428 +4,351 @@
#include "Inputs/lifetime-analysis.h"
namespace std {
-template <class Ret, typename... T>
-struct coroutine_traits {
+template <class Ret, class... Args> struct coroutine_traits {
using promise_type = typename Ret::promise_type;
};
-
-template <class Promise = void>
-struct coroutine_handle {
+template <class Promise = void> struct coroutine_handle {
static coroutine_handle from_address(void *) noexcept;
- static coroutine_handle from_promise(Promise &promise);
- constexpr void *address() const noexcept;
};
-
-template <>
-struct coroutine_handle<void> {
- template <class PromiseType>
- coroutine_handle(coroutine_handle<PromiseType>) noexcept;
+template <> struct coroutine_handle<void> {
+ template <class P> coroutine_handle(coroutine_handle<P>) noexcept;
static coroutine_handle from_address(void *);
- constexpr void *address() const noexcept;
};
-
struct suspend_always {
- bool await_ready() noexcept { return false; }
- void await_suspend(coroutine_handle<>) noexcept {}
- void await_resume() noexcept {}
+ bool await_ready() noexcept;
+ void await_suspend(coroutine_handle<>) noexcept;
+ void await_resume() noexcept;
};
} // namespace std
-// Coroutine return type without [[gsl::Pointer]], with user-defined move
-// constructor and move assignment (matching real coroutine handle types).
+template <class R> struct Promise {
+ R get_return_object();
+ std::suspend_always initial_suspend() noexcept;
+ std::suspend_always final_suspend() noexcept;
+ void unhandled_exception();
+ void return_value(int);
+};
+
+// Not a [[gsl::Pointer]]. User-provided copy/move members and destructor, like
+// real coroutine handle types, so origins must be propagated through them
+// explicitly.
template <typename T>
struct [[clang::coro_return_type, clang::coro_lifetimebound]] Co {
- struct promise_type {
- Co<T> get_return_object() { return {}; }
- std::suspend_always initial_suspend() noexcept;
- std::suspend_always final_suspend() noexcept;
- void unhandled_exception();
- void return_value(const T &t);
-
- template <typename U>
- auto await_transform(const Co<U> &) {
- struct awaitable {
- bool await_ready() noexcept { return false; }
- void await_suspend(std::coroutine_handle<>) noexcept {}
- U await_resume() noexcept { return {}; }
- };
- return awaitable{};
- }
- };
-
+ using promise_type = Promise<Co>;
Co() = default;
- Co(const Co &other) {}
- Co(Co &&other) noexcept {}
- Co &operator=(const Co &other) { return *this; }
- Co &operator=(Co &&other) noexcept { return *this; }
+ Co(const Co &) {}
+ Co(Co &&) noexcept {}
+ Co &operator=(const Co &) { return *this; }
+ Co &operator=(Co &&) noexcept { return *this; }
~Co() {}
+ bool await_ready() noexcept;
+ void await_suspend(std::coroutine_handle<>) noexcept;
+ T await_resume() noexcept;
};
-// Coroutine return type also marked [[gsl::Pointer]] for STL container
-// capture-by inference (e.g. std::vector::push_back).
-template <typename T>
-struct [[clang::coro_return_type, clang::coro_lifetimebound, gsl::Pointer]]
-Step {
- struct promise_type {
- Step<T> get_return_object() { return {}; }
- std::suspend_always initial_suspend() noexcept;
- std::suspend_always final_suspend() noexcept;
- void unhandled_exception();
- void return_value(const T &t);
- };
- Step() = default;
- Step(Step &&other) noexcept {}
- Step &operator=(Step &&other) noexcept { return *this; }
+// Also a [[gsl::Pointer]], so std::vector<Step>::push_back infers
+// [[clang::lifetime_capture_by(this)]].
+struct [[clang::coro_return_type, clang::coro_lifetimebound, gsl::Pointer]] Step {
+ using promise_type = Promise<Step>;
+};
+
+// coro_lifetimebound without coro_return_type has no effect.
+struct [[clang::coro_lifetimebound]] CoNoCRT {
+ using promise_type = Promise<CoNoCRT>;
};
Co<int> ref_coro(const int &b) { co_return b; }
Co<int> ptr_coro(const int *p) { co_return *p; }
Co<int> rref_coro(int &&r) { co_return r; }
-Co<int> view_coro(std::string_view sv) { co_return sv.size(); }
-Co<int> val_int_coro(int v) { co_return v; }
-Co<int> val_str_coro(std::string s) { co_return 0; }
-Step<int> step_ref_coro(const int &b) { co_return b; }
-Step<int> step_val_coro(std::string s) { co_return 0; }
-
-void consume(Co<int> &);
-void consume(std::vector<Step<int>> &);
+Co<int> view_coro(std::string_view sv) { co_return 0; }
+Co<int> val_coro(int i, std::string s) { co_return i; }
+Step step_ref_coro(const int &b) { co_return b; }
+Step step_val_coro(std::string s) { co_return 0; }
+CoNoCRT no_crt_coro(const int &x) { co_return x; }
// =============================================================================
-// 1. Reference, pointer, rvalue-ref, and view parameters across scopes
+// Reference, pointer, rvalue-ref and view parameters escaping their scope
// =============================================================================
-void inner_scope_ref_escapes() {
+void ref_escapes() {
Co<int> saved;
{
int local = 1;
saved = ref_coro(local); // expected-warning {{local variable 'local' does not live long enough}} \
- // expected-note {{result of call to 'ref_coro' aliases the storage of local variable 'local' because parameter 'b' is inferred as lifetimebound}}
+ // expected-note {{parameter 'b' is inferred as lifetimebound}}
} // expected-note {{destroyed here}}
- consume(saved); // expected-note {{later used here}}
+ use(saved); // expected-note {{later used here}}
}
-void inner_scope_ptr_escapes() {
+void ptr_escapes() {
Co<int> saved;
{
int local = 1;
saved = ptr_coro(&local); // expected-warning {{local variable 'local' does not live long enough}} \
- // expected-note {{result of call to 'ptr_coro' aliases the storage of local variable 'local' because parameter 'p' is inferred as lifetimebound}}
+ // expected-note {{parameter 'p' is inferred as lifetimebound}}
} // expected-note {{destroyed here}}
- consume(saved); // expected-note {{later used here}}
+ use(saved); // expected-note {{later used here}}
}
-void inner_scope_rref_escapes() {
+void rref_escapes() {
Co<int> saved;
{
int local = 1;
saved = rref_coro(std::move(local)); // expected-warning {{local variable 'local' does not live long enough}} \
- // expected-note {{result of call to 'move<int &>' aliases the storage of local variable 'local' because parameter 't' is inferred as lifetimebound}} \
- // expected-note {{result of call to 'rref_coro' aliases the storage of local variable 'local' because parameter 'r' is inferred as lifetimebound}}
+ // expected-note {{parameter 't' is inferred as lifetimebound}} \
+ // expected-note {{parameter 'r' is inferred as lifetimebound}}
} // expected-note {{destroyed here}}
- consume(saved); // expected-note {{later used here}}
+ use(saved); // expected-note {{later used here}}
}
-void inner_scope_view_escapes() {
+void view_escapes() {
Co<int> saved;
{
std::string local;
saved = view_coro(local); // expected-warning {{local variable 'local' does not live long enough}} \
- // expected-note {{result of call to 'view_coro' aliases the storage of local variable 'local' because parameter 'sv' is inferred as lifetimebound}}
+ // expected-note {{parameter 'sv' is inferred as lifetimebound}}
} // expected-note {{destroyed here}}
- consume(saved); // expected-note {{later used here}}
+ use(saved); // expected-note {{later used here}}
}
-void temporary_arg_used_later() {
+void temporary_arg() {
auto c = ref_coro(1); // expected-warning {{temporary object does not live long enough}} \
// expected-note {{destroyed here}} \
- // expected-note {{result of call to 'ref_coro' aliases the storage of temporary object because parameter 'b' is inferred as lifetimebound}}
- consume(c); // expected-note {{later used here}}
+ // expected-note {{parameter 'b' is inferred as lifetimebound}}
+ use(c); // expected-note {{later used here}}
}
-void move_propagates_loan() {
+Co<int> default_arg_coro(const int &x = 1) { co_return x; }
+void default_arg_temporary() {
+ auto c = default_arg_coro(); // expected-warning {{temporary object does not live long enough}} \
+ // expected-note {{destroyed here}} \
+ // expected-note {{parameter 'x' is inferred as lifetimebound}}
+ use(c); // expected-note {{later used here}}
+}
+
+template <typename T> Co<int> template_coro(const T &x) { co_return 0; }
+void template_escapes() {
+ Co<int> saved;
+ {
+ std::string local;
+ saved = template_coro(local); // expected-warning {{local variable 'local' does not live long enough}} \
+ // expected-note {{parameter 'x' is inferred as lifetimebound}}
+ } // expected-note {{destroyed here}}
+ use(saved); // expected-note {{later used here}}
+}
+
+// =============================================================================
+// Loans propagate through copies, moves and by-value handle parameters
+// =============================================================================
+void move_propagates() {
Co<int> outer;
{
int local = 1;
Co<int> inner = ref_coro(local); // expected-warning {{local variable 'local' does not live long enough}} \
- // expected-note {{result of call to 'ref_coro' aliases the storage of local variable 'local' because parameter 'b' is inferred as lifetimebound}}
+ // expected-note {{parameter 'b' is inferred as lifetimebound}}
outer = std::move(inner); // expected-note {{result of call to 'move<Co<int> &>' aliases the storage of local variable 'local'}}
} // expected-note {{destroyed here}}
- consume(outer); // expected-note {{later used here}}
+ use(outer); // expected-note {{later used here}}
+}
+
+void copy_propagates() {
+ Co<int> saved;
+ {
+ int local = 1;
+ auto c = ref_coro(local); // expected-warning {{local variable 'local' does not live long enough}} \
+ // expected-note {{parameter 'b' is inferred as lifetimebound}}
+ saved = c; // expected-note {{local variable 'c' aliases the storage of local variable 'local'}}
+ } // expected-note {{destroyed here}}
+ use(saved); // expected-note {{later used here}}
+}
+
+Co<int> chain(Co<int> inner) { co_return co_await inner; }
+void chain_by_value_propagates() {
+ Co<int> outer;
+ {
+ int local = 1;
+ outer = chain(ref_coro(local)); // expected-warning {{local variable 'local' does not live long enough}} \
+ // expected-note {{parameter 'b' is inferred as lifetimebound}} \
+ // expected-note {{parameter 'inner' is inferred as lifetimebound}}
+ } // expected-note {{destroyed here}}
+ use(outer); // expected-note {{later used here}}
}
// =============================================================================
-// 2. Safe by-value owning parameters and same-statement co_await
+// No warning: by-value parameters and same-statement co_await
// =============================================================================
void by_value_params_safe() {
- Co<int> saved1, saved2;
+ Co<int> saved;
{
- int local_i = 1;
- std::string local_s;
- saved1 = val_int_coro(local_i);
- saved2 = val_str_coro(local_s);
+ int i = 1;
+ std::string s;
+ saved = val_coro(i, s);
}
- consume(saved1);
- consume(saved2);
+ use(saved);
}
-Co<int> same_statement_co_await_safe(const int ¶m) {
+Co<int> same_statement_co_await_safe() {
int a = 1;
int r1 = co_await ref_coro(1);
int r2 = co_await ref_coro(a);
int r3 = co_await [a](const int &y) -> Co<int> { co_return a + y; }(1);
- co_return r1 + r2 + r3 + param;
+ co_return r1 + r2 + r3;
}
-Co<int> stored_temporary_awaited_later() {
+Co<int> temporary_awaited_later() {
auto c = ref_coro(1); // expected-warning {{temporary object does not live long enough}} \
// expected-note {{destroyed here}} \
- // expected-note {{result of call to 'ref_coro' aliases the storage of temporary object because parameter 'b' is inferred as lifetimebound}}
+ // expected-note {{parameter 'b' is inferred as lifetimebound}}
co_return co_await c; // expected-note {{later used here}}
}
// =============================================================================
-// 3. Return stack address through wrapper functions
+// coro_wrapper functions returning a handle to their own stack
// =============================================================================
[[clang::coro_wrapper]] Co<int> return_param_ref(int b) {
return ref_coro(b); // expected-warning {{stack memory associated with parameter 'b' is returned}} \
- // expected-note {{result of call to 'ref_coro' aliases the storage of parameter 'b' because parameter 'b' is inferred as lifetimebound}} \
+ // expected-note {{parameter 'b' is inferred as lifetimebound}} \
// expected-note {{returned here}}
}
-[[clang::coro_wrapper]] Co<int> safe_forwarding(const int &b) {
- return ref_coro(b);
-}
+// No [[clang::lifetimebound]] suggestion: coro_lifetimebound already covers 'b'.
+[[clang::coro_wrapper]] Co<int> forwarding(const int &b) { return ref_coro(b); }
[[clang::coro_wrapper]] Co<int> return_via_wrapper(int b) {
- return safe_forwarding(b); // expected-warning {{stack memory associated with parameter 'b' is returned}} \
- // expected-note {{result of call to 'safe_forwarding' aliases the storage of parameter 'b' because parameter 'b' is inferred as lifetimebound}} \
- // expected-note {{returned here}}
+ return forwarding(b); // expected-warning {{stack memory associated with parameter 'b' is returned}} \
+ // expected-note {{result of call to 'forwarding' aliases the storage of parameter 'b'}} \
+ // expected-note {{returned here}}
}
[[clang::coro_wrapper]] Co<int> return_by_value_safe(int b) {
- return val_int_coro(b);
+ return val_coro(b, "");
}
// =============================================================================
-// 4. Member coroutines (implicit and explicit 'this') and lambdas
+// Object arguments: implicit and explicit 'this', lambdas
// =============================================================================
struct Owner {
int x = 0;
Co<int> member(const int &a) { co_return x + a; }
- Co<int> explicit_this(this Owner &self, const int &a) {
- co_return self.x + a;
- }
+ Co<int> explicit_this(this Owner &self, const int &a) { co_return self.x + a; }
+ [[clang::coro_wrapper, clang::coro_disable_lifetimebound]]
+ Co<int> disabled_member(const int &a) { return val_coro(a, ""); }
};
-void member_receiver_escapes(const int &a) {
+void member_escapes(const int &a) {
Co<int> saved;
{
Owner o;
saved = o.member(a); // expected-warning {{local variable 'o' does not live long enough}} \
- // expected-note {{result of call to 'member' aliases the storage of local variable 'o' because the implicit object parameter is inferred as lifetimebound}}
+ // expected-note {{the implicit object parameter is inferred as lifetimebound}}
} // expected-note {{destroyed here}}
- consume(saved); // expected-note {{later used here}}
+ use(saved); // expected-note {{later used here}}
}
-void member_temp_receiver(const int &a) {
+void member_temporary_receiver(const int &a) {
auto c = Owner{}.member(a); // expected-warning {{temporary object does not live long enough}} \
// expected-note {{destroyed here}} \
- // expected-note {{result of call to 'member' aliases the storage of temporary object because the implicit object parameter is inferred as lifetimebound}}
- consume(c); // expected-note {{later used here}}
+ // expected-note {{the implicit object parameter is inferred as lifetimebound}}
+ use(c); // expected-note {{later used here}}
}
-void explicit_this_receiver_escapes(const int &a) {
+void explicit_this_escapes(const int &a) {
Co<int> saved;
{
Owner o;
saved = o.explicit_this(a); // expected-warning {{local variable 'o' does not live long enough}} \
- // expected-note {{result of call to 'explicit_this' aliases the storage of local variable 'o' because parameter 'self' is inferred as lifetimebound}}
+ // expected-note {{parameter 'self' is inferred as lifetimebound}}
} // expected-note {{destroyed here}}
- consume(saved); // expected-note {{later used here}}
+ use(saved); // expected-note {{later used here}}
}
-void lambda_captures() {
+void lambdas() {
int a = 1;
- // Capturing temporary lambda dies at semicolon.
- auto bad_lam = [a]() -> Co<int> { co_return a; }(); // expected-warning {{temporary object does not live long enough}} \
- // expected-note {{destroyed here}} \
- // expected-note {{result of call to 'operator()' aliases the storage of temporary object because the implicit object parameter is inferred as lifetimebound}}
- consume(bad_lam); // expected-note {{later used here}}
-
- // Captureless temporary lambda does not bind 'this'.
- auto ok_lam = []() -> Co<int> { co_return 1; }();
- consume(ok_lam);
-
- // Named captureless lambda does not bind 'this' even when it goes out of
- // scope before the returned coroutine handle is consumed.
- Co<int> from_named_captureless;
+ // A capturing temporary lambda dies at the end of the full-expression.
+ auto c1 = [a]() -> Co<int> { co_return a; }(); // expected-warning {{temporary object does not live long enough}} \
+ // expected-note {{destroyed here}} \
+ // expected-note {{the implicit object parameter is inferred as lifetimebound}}
+ use(c1); // expected-note {{later used here}}
+
+ // A captureless lambda never binds 'this', temporary or named.
+ auto c2 = []() -> Co<int> { co_return 1; }();
+ Co<int> c3;
{
- auto named_ok = []() -> Co<int> { co_return 1; };
- from_named_captureless = named_ok();
+ auto named = []() -> Co<int> { co_return 1; };
+ c3 = named();
}
- consume(from_named_captureless);
+ use(c2, c3);
- // Named capturing lambda escaping its scope warns.
- Co<int> from_named_capturing;
+ // A named capturing lambda escaping its scope warns.
+ Co<int> c4;
{
- auto named_bad = [a]() -> Co<int> { co_return a; };
- from_named_capturing = named_bad(); // expected-warning {{local variable 'named_bad' does not live long enough}} \
- // expected-note {{result of call to 'operator()' aliases the storage of local variable 'named_bad' because the implicit object parameter is inferred as lifetimebound}}
- } // expected-note {{destroyed here}}
- consume(from_named_capturing); // expected-note {{later used here}}
-
- // Captureless lambda with a dangling reference parameter still warns.
- auto bad_param = [](const int &y) -> Co<int> { co_return y; }(1); // expected-warning {{temporary object does not live long enough}} \
- // expected-note {{destroyed here}} \
- // expected-note {{result of call to 'operator()' aliases the storage of temporary object because parameter 'y' is inferred as lifetimebound}}
- consume(bad_param); // expected-note {{later used here}}
+ auto named = [a]() -> Co<int> { co_return a; };
+ c4 = named(); // expected-warning {{local variable 'named' does not live long enough}} \
+ // expected-note {{the implicit object parameter is inferred as lifetimebound}}
+ } // expected-note {{destroyed here}}
+ use(c4); // expected-note {{later used here}}
+
+ // Captureless lambdas still track their reference parameters.
+ auto c5 = [](const int &y) -> Co<int> { co_return y; }(1); // expected-warning {{temporary object does not live long enough}} \
+ // expected-note {{destroyed here}} \
+ // expected-note {{parameter 'y' is inferred as lifetimebound}}
+ use(c5); // expected-note {{later used here}}
}
// =============================================================================
-// 4b. Default arguments, handle copy assignment, chaining by value, templates
+// Containers: std::vector (inferred capture_by) and explicit capture_by(this)
// =============================================================================
-Co<int> default_arg_coro(const int &x = 1) { co_return x; }
-
-void default_arg_temp() {
- auto c = default_arg_coro(); // expected-warning {{temporary object does not live long enough}} \
- // expected-note {{destroyed here}} \
- // expected-note {{result of call to 'default_arg_coro' aliases the storage of temporary object because parameter 'x' is inferred as lifetimebound}}
- consume(c); // expected-note {{later used here}}
-}
-
-void copy_assign_handle() {
- Co<int> saved;
- {
- int local = 1;
- auto c = ref_coro(local); // expected-warning {{local variable 'local' does not live long enough}} \
- // expected-note {{result of call to 'ref_coro' aliases the storage of local variable 'local' because parameter 'b' is inferred as lifetimebound}}
- saved = c; // expected-note {{local variable 'c' aliases the storage of local variable 'local'}}
- } // expected-note {{destroyed here}}
- consume(saved); // expected-note {{later used here}}
-}
-
-Co<int> chain_by_value(Co<int> inner) { co_return co_await inner; }
-
-void chain_by_value_escapes() {
- Co<int> outer;
- {
- int local = 1;
- outer = chain_by_value(ref_coro(local)); // expected-warning {{local variable 'local' does not live long enough}} \
- // expected-note {{result of call to 'ref_coro' aliases the storage of local variable 'local' because parameter 'b' is inferred as lifetimebound}} \
- // expected-note {{result of call to 'chain_by_value' aliases the storage of local variable 'local' because parameter 'inner' is inferred as lifetimebound}}
- } // expected-note {{destroyed here}}
- consume(outer); // expected-note {{later used here}}
-}
-
-template <typename T>
-Co<int> template_coro(const T &x) {
- co_return 0;
-}
-
-void template_coro_escapes() {
- Co<int> saved;
- {
- std::string local;
- saved = template_coro(local); // expected-warning {{local variable 'local' does not live long enough}} \
- // expected-note {{result of call to 'template_coro<std::basic_string<char>>' aliases the storage of local variable 'local' because parameter 'x' is inferred as lifetimebound}}
- } // expected-note {{destroyed here}}
- consume(saved); // expected-note {{later used here}}
-}
-
-// =============================================================================
-// 5. Containers (STL vector + custom lifetime_capture_by_this)
-// =============================================================================
-void loop_local_into_vector() {
- std::vector<Step<int>> steps;
+void loop_into_vector() {
+ std::vector<Step> steps;
for (int i = 0; i < 3; ++i) {
int local = i;
+ std::string by_value;
steps.push_back(step_ref_coro(local)); // expected-warning {{local variable 'local' does not live long enough}} \
- // expected-note {{result of call to 'step_ref_coro' aliases the storage of local variable 'local' because parameter 'b' is inferred as lifetimebound}} \
+ // expected-note {{parameter 'b' is inferred as lifetimebound}} \
// expected-note {{later used here}}
+ steps.push_back(step_val_coro(by_value));
} // expected-note {{destroyed here}}
- consume(steps);
-}
-
-void loop_by_value_into_vector_safe() {
- std::vector<Step<int>> steps;
- for (int i = 0; i < 3; ++i) {
- std::string local;
- steps.push_back(step_val_coro(local));
- }
- consume(steps);
+ use(steps);
}
struct CoGroup {
void Add(Co<int> &&c [[clang::lifetime_capture_by_this]]);
};
-void consume(CoGroup &);
-void custom_container_capture(const int &outer) {
- CoGroup g_safe;
- g_safe.Add(ref_coro(outer));
- consume(g_safe);
+void custom_container(const int &outer) {
+ CoGroup ok;
+ ok.Add(ref_coro(outer));
+ use(ok);
- CoGroup g_bad;
+ CoGroup bad;
{
int local = 1;
- g_bad.Add(ref_coro(local)); // expected-warning {{local variable 'local' does not live long enough}} \
- // expected-note {{result of call to 'ref_coro' aliases the storage of local variable 'local' because parameter 'b' is inferred as lifetimebound}}
- } // expected-note {{destroyed here}}
- consume(g_bad); // expected-note {{later used here}}
+ bad.Add(ref_coro(local)); // expected-warning {{local variable 'local' does not live long enough}} \
+ // expected-note {{parameter 'b' is inferred as lifetimebound}}
+ } // expected-note {{destroyed here}}
+ use(bad); // expected-note {{later used here}}
}
// =============================================================================
-// 6. Opt-out [[clang::coro_disable_lifetimebound]] and missing coro_return_type
+// Opt-outs: coro_disable_lifetimebound and missing coro_return_type
// =============================================================================
[[clang::coro_wrapper, clang::coro_disable_lifetimebound]]
-Co<int> disabled_wrapper(const int &x) {
- return val_int_coro(x);
-}
+Co<int> disabled(const int &x) { return val_coro(x, ""); }
-// A coro_disable_lifetimebound wrapper that actually returns a reference-bound
-// coroutine still receives a [[clang::lifetimebound]] suggestion.
+// Opting out also re-enables the [[clang::lifetimebound]] suggestion.
[[clang::coro_wrapper, clang::coro_disable_lifetimebound]]
-Co<int> disabled_forwarding_wrapper(const int &x) { // suggest-warning {{parameter in intra-TU function should be marked [[clang::lifetimebound]]}}
- return ref_coro(x); // suggest-note {{param returned here}}
-}
-
-struct DisabledOwner {
- [[clang::coro_wrapper, clang::coro_disable_lifetimebound]]
- Co<int> member(const int &x) {
- return val_int_coro(x);
- }
-};
-
-void disable_lifetimebound_safe() {
- Co<int> saved1, saved2;
- {
- int local = 1;
- DisabledOwner o;
- saved1 = disabled_wrapper(local);
- saved2 = o.member(local);
- }
- consume(saved1);
- consume(saved2);
+Co<int> disabled_forwarding(const int &x) { // suggest-warning {{parameter in intra-TU function should be marked [[clang::lifetimebound]]}}
+ return ref_coro(x); // suggest-note {{param returned here}}
}
-template <typename T>
-struct [[clang::coro_lifetimebound]] CoNoCRT {
- struct promise_type {
- CoNoCRT<T> get_return_object() { return {}; }
- std::suspend_always initial_suspend() noexcept;
- std::suspend_always final_suspend() noexcept;
- void unhandled_exception();
- void return_value(const T &t);
- };
-};
-
-CoNoCRT<int> no_crt_coro(const int &x) { co_return x; }
-void consume(CoNoCRT<int> &);
-
-void no_coro_return_type_no_warning() {
- CoNoCRT<int> saved;
+void opt_outs_safe() {
+ Co<int> c1, c2;
+ CoNoCRT c3;
{
int local = 1;
- saved = no_crt_coro(local);
+ Owner o;
+ c1 = disabled(local);
+ c2 = o.disabled_member(local);
+ c3 = no_crt_coro(local);
}
- consume(saved);
+ use(c1, c2, c3);
}
More information about the cfe-commits
mailing list