[clang] 3de25f5 - [LifetimeSafety] Warn on incorrectly placed `[[clang::lifetimebound]]` attributes (#196144)
via cfe-commits
cfe-commits at lists.llvm.org
Sun May 10 06:37:20 PDT 2026
Author: NeKon69
Date: 2026-05-10T19:07:15+05:30
New Revision: 3de25f551c1df8a70131758b482dca4f4575343f
URL: https://github.com/llvm/llvm-project/commit/3de25f551c1df8a70131758b482dca4f4575343f
DIFF: https://github.com/llvm/llvm-project/commit/3de25f551c1df8a70131758b482dca4f4575343f.diff
LOG: [LifetimeSafety] Warn on incorrectly placed `[[clang::lifetimebound]]` attributes (#196144)
Adds new warning that is emitted when parameter is marked as
`[[clang::lifetimebound]]` but is not returned in one way or another
(tracked via `OriginEscapeFact`).
Closes #182935
Added:
clang/test/Sema/warn-lifetime-safety-lifetimebound.cpp
Modified:
clang/docs/LifetimeSafety.rst
clang/include/clang/Analysis/Analyses/LifetimeSafety/LifetimeSafety.h
clang/include/clang/Basic/DiagnosticGroups.td
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Analysis/LifetimeSafety/Checker.cpp
clang/lib/Sema/SemaLifetimeSafety.h
Removed:
################################################################################
diff --git a/clang/docs/LifetimeSafety.rst b/clang/docs/LifetimeSafety.rst
index c71816dd75a82..db166db0637ca 100644
--- a/clang/docs/LifetimeSafety.rst
+++ b/clang/docs/LifetimeSafety.rst
@@ -467,6 +467,7 @@ enables only the high-confidence subset of these checks.
* ``-Wlifetime-safety-validations``: Enables checks that validate existing lifetime annotations.
* ``-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]]``.
Limitations
===========
diff --git a/clang/include/clang/Analysis/Analyses/LifetimeSafety/LifetimeSafety.h b/clang/include/clang/Analysis/Analyses/LifetimeSafety/LifetimeSafety.h
index d20ac87a7c8d9..7ccf30ba14987 100644
--- a/clang/include/clang/Analysis/Analyses/LifetimeSafety/LifetimeSafety.h
+++ b/clang/include/clang/Analysis/Analyses/LifetimeSafety/LifetimeSafety.h
@@ -108,6 +108,10 @@ class LifetimeSafetySemaHelper {
virtual void reportNoescapeViolation(const ParmVarDecl *ParmWithNoescape,
const VarDecl *EscapeGlobal) {}
+ // Reports misuse of [[clang::lifetimebound]] when parameter doesn't escape
+ // through return.
+ virtual void reportLifetimeboundViolation(const ParmVarDecl *VD) {}
+
// Suggests lifetime bound annotations for implicit this.
virtual void suggestLifetimeboundToImplicitThis(SuggestionScope Scope,
const CXXMethodDecl *MD,
diff --git a/clang/include/clang/Basic/DiagnosticGroups.td b/clang/include/clang/Basic/DiagnosticGroups.td
index 2b3055d6d6bdd..03d423db9d21a 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -624,6 +624,13 @@ Warning to detect invalidation of references.
}];
}
+def LifetimeSafetyLifetimeboundViolation : DiagGroup<"lifetime-safety-lifetimebound-violation"> {
+ code Documentation = [{
+Detects parameters marked as [[clang::lifetimebound]] for which the analysis could not verify that the return value can be lifetime bound to the parameter.
+This warning may produce false-positives diagnostics when it cannot fully model the code.
+ }];
+}
+
def LifetimeSafetyPermissive : DiagGroup<"lifetime-safety-permissive",
[LifetimeSafetyUseAfterScope,
LifetimeSafetyReturnStackAddr,
@@ -666,10 +673,11 @@ Detects misuse of [[clang::noescape]] annotation where the parameter escapes (fo
}
def LifetimeSafetyValidations : DiagGroup<"lifetime-safety-validations",
- [LifetimeSafetyNoescape]> {
+ [LifetimeSafetyNoescape,
+ LifetimeSafetyLifetimeboundViolation]> {
code Documentation = [{
Verify function implementations adhere to the annotated lifetime contracts through lifetime safety
-like verifying [[clang::noescape]] and [[clang::lifetimebound]] (upcoming).
+like verifying [[clang::noescape]] and [[clang::lifetimebound]].
}];
}
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index c638c23f24bb5..879812f3de0d3 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -11007,6 +11007,11 @@ def warn_lifetime_safety_dangling_global_moved
InGroup<LifetimeSafetyDanglingGlobalMoved>,
DefaultIgnore;
+def warn_lifetime_safety_param_lifetimebound_violation
+ : Warning<"could not verify that the return value can be lifetime bound to %select{an unnamed parameter|'%1'}0">,
+ InGroup<LifetimeSafetyLifetimeboundViolation>,
+ DefaultIgnore;
+
def note_lifetime_safety_used_here : Note<"later used here">;
def note_lifetime_safety_invalidated_here : Note<"invalidated here">;
def note_lifetime_safety_destroyed_here : Note<"destroyed here">;
diff --git a/clang/lib/Analysis/LifetimeSafety/Checker.cpp b/clang/lib/Analysis/LifetimeSafety/Checker.cpp
index 4ae90cf751ec3..fc77ed3097602 100644
--- a/clang/lib/Analysis/LifetimeSafety/Checker.cpp
+++ b/clang/lib/Analysis/LifetimeSafety/Checker.cpp
@@ -60,6 +60,7 @@ class LifetimeChecker {
llvm::DenseMap<LoanID, PendingWarning> FinalWarningsMap;
llvm::DenseMap<AnnotationTarget, EscapingTarget> AnnotationWarningsMap;
llvm::DenseMap<const ParmVarDecl *, EscapingTarget> NoescapeWarningsMap;
+ llvm::DenseSet<const ParmVarDecl *> VerifiedLiftimeboundEscapes;
const LoanPropagationAnalysis &LoanPropagation;
const MovedLoansAnalysis &MovedLoans;
const LiveOriginsAnalysis &LiveOrigins;
@@ -101,6 +102,7 @@ class LifetimeChecker {
issuePendingWarnings();
suggestAnnotations();
reportNoescapeViolations();
+ reportLifetimeboundViolations();
// Annotation inference is currently guarded by a frontend flag. In the
// future, this might be replaced by a design that
diff erentiates between
// explicit and inferred findings with separate warning groups.
@@ -129,9 +131,12 @@ class LifetimeChecker {
// obscures the lifetime relationship (e.g., shared_ptr from unique_ptr).
if (IsMoved)
return;
- // Otherwise, suggest lifetimebound for parameter escaping through return
- // or a field in constructor.
- if (!PVD->hasAttr<LifetimeBoundAttr>()) {
+ if (PVD->hasAttr<LifetimeBoundAttr>()) {
+ // Track that this lifetimebound parameter correctly escapes.
+ 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);
@@ -358,6 +363,22 @@ class LifetimeChecker {
}
}
+ void reportLifetimeboundViolations() {
+ if (!isa<FunctionDecl>(FD))
+ return;
+ for (const ParmVarDecl *PVD : cast<FunctionDecl>(FD)->parameters()) {
+ if (!PVD->hasAttr<LifetimeBoundAttr>())
+ continue;
+ bool isImplicit = PVD->getAttr<LifetimeBoundAttr>()->isImplicit();
+ bool Escapes = VerifiedLiftimeboundEscapes.contains(PVD);
+ assert((!isImplicit || Escapes || isInStlNamespace(FD)) &&
+ "Implicit lifetimebound parameters "
+ "should escape through return");
+ if (!isImplicit && !Escapes)
+ SemaHelper->reportLifetimeboundViolation(PVD);
+ }
+ }
+
void inferAnnotations() {
for (auto [Target, EscapeTarget] : AnnotationWarningsMap) {
if (const auto *MD = Target.dyn_cast<const CXXMethodDecl *>()) {
diff --git a/clang/lib/Sema/SemaLifetimeSafety.h b/clang/lib/Sema/SemaLifetimeSafety.h
index 92e7b5cf14ae5..5b1cf41445399 100644
--- a/clang/lib/Sema/SemaLifetimeSafety.h
+++ b/clang/lib/Sema/SemaLifetimeSafety.h
@@ -24,18 +24,24 @@ namespace clang::lifetimes {
inline bool IsLifetimeSafetyDiagnosticEnabled(Sema &S, const Decl *D) {
DiagnosticsEngine &Diags = S.getDiagnostics();
- return !Diags.isIgnored(diag::warn_lifetime_safety_use_after_scope,
- D->getBeginLoc()) ||
- !Diags.isIgnored(diag::warn_lifetime_safety_use_after_scope_moved,
- D->getBeginLoc()) ||
- !Diags.isIgnored(diag::warn_lifetime_safety_return_stack_addr,
- D->getBeginLoc()) ||
- !Diags.isIgnored(diag::warn_lifetime_safety_return_stack_addr_moved,
- D->getBeginLoc()) ||
- !Diags.isIgnored(diag::warn_lifetime_safety_invalidation,
- D->getBeginLoc()) ||
- !Diags.isIgnored(diag::warn_lifetime_safety_noescape_escapes,
- D->getBeginLoc());
+ constexpr unsigned DiagIDs[] = {
+ diag::warn_lifetime_safety_use_after_scope,
+ diag::warn_lifetime_safety_use_after_scope_moved,
+ diag::warn_lifetime_safety_use_after_free,
+ diag::warn_lifetime_safety_return_stack_addr,
+ diag::warn_lifetime_safety_return_stack_addr_moved,
+ diag::warn_lifetime_safety_invalidation,
+ diag::warn_lifetime_safety_dangling_field,
+ diag::warn_lifetime_safety_dangling_field_moved,
+ diag::warn_lifetime_safety_dangling_global,
+ diag::warn_lifetime_safety_dangling_global_moved,
+ diag::warn_lifetime_safety_noescape_escapes,
+ diag::warn_lifetime_safety_param_lifetimebound_violation,
+ };
+ for (unsigned DiagID : DiagIDs)
+ if (!Diags.isIgnored(DiagID, D->getBeginLoc()))
+ return true;
+ return false;
}
class LifetimeSafetySemaHelperImpl : public LifetimeSafetySemaHelper {
@@ -172,6 +178,15 @@ class LifetimeSafetySemaHelperImpl : public LifetimeSafetySemaHelper {
<< EscapeField->getSourceRange();
}
+ void reportLifetimeboundViolation(
+ const ParmVarDecl *ParmWithLifetimebound) override {
+ StringRef ParamName = ParmWithLifetimebound->getName();
+ bool HasName = ParamName.size() > 0;
+ S.Diag(ParmWithLifetimebound->getLocation(),
+ diag::warn_lifetime_safety_param_lifetimebound_violation)
+ << HasName << ParamName << ParmWithLifetimebound->getSourceRange();
+ }
+
void suggestLifetimeboundToImplicitThis(SuggestionScope Scope,
const CXXMethodDecl *MD,
const Expr *EscapeExpr) override {
diff --git a/clang/test/Sema/warn-lifetime-safety-lifetimebound.cpp b/clang/test/Sema/warn-lifetime-safety-lifetimebound.cpp
new file mode 100644
index 0000000000000..941a3bb8ce1e3
--- /dev/null
+++ b/clang/test/Sema/warn-lifetime-safety-lifetimebound.cpp
@@ -0,0 +1,89 @@
+// RUN: %clang_cc1 -fsyntax-only -Wlifetime-safety-lifetimebound-violation -verify %s
+
+#include "Inputs/lifetime-analysis.h"
+
+struct [[gsl::Owner]] MyObj {
+ int id;
+ ~MyObj() {} // Non-trivial destructor
+};
+
+struct [[gsl::Pointer()]] View {
+ View(const MyObj &); // Borrows from MyObj
+ View();
+ void use() const;
+};
+
+bool cond();
+
+View not_lb(const MyObj &obj);
+
+View lb(const MyObj &obj [[clang::lifetimebound]]);
+
+View return_through_unannotated_passthrough(
+ const MyObj &obj [[clang::lifetimebound]]) { // expected-warning {{could not verify that the return value can be lifetime bound to 'obj'}}
+ return not_lb(obj);
+}
+
+View return_through_lifetimebound_passthrough(
+ const MyObj &obj [[clang::lifetimebound]]) {
+ return lb(obj);
+}
+
+View lose_lb(const MyObj &obj [[clang::lifetimebound]]) { // expected-warning {{could not verify that the return value can be lifetime bound to 'obj'}}
+ return not_lb(obj);
+}
+
+View return_through_alias(const MyObj &obj [[clang::lifetimebound]]) {
+ const MyObj &alias = obj;
+ return alias;
+}
+
+View return_alias_through_unannotated_passthrough(
+ const MyObj &obj [[clang::lifetimebound]]) { // expected-warning {{could not verify that the return value can be lifetime bound to 'obj'}}
+ const MyObj &alias = obj;
+ return not_lb(alias);
+}
+
+View not_lb_view(View v);
+
+View lb_view(View v [[clang::lifetimebound]]);
+
+
+View return_through_two_lifetimebound_calls(
+ const MyObj &obj [[clang::lifetimebound]]) {
+ return lb_view(lb(obj));
+}
+
+View return_through_nested_broken_chain(
+ const MyObj &obj [[clang::lifetimebound]]) { // expected-warning {{could not verify that the return value can be lifetime bound to 'obj'}}
+ return not_lb_view(lb_view(View(obj)));
+}
+
+View return_constructed_view_through_unannotated_forwarder(
+ const MyObj &obj [[clang::lifetimebound]]) { // expected-warning {{could not verify that the return value can be lifetime bound to 'obj'}}
+ return not_lb_view(View(obj));
+}
+
+View return_constructed_view_through_lifetimebound_forwarder(
+ const MyObj &obj [[clang::lifetimebound]]) {
+ return lb_view(View(obj));
+}
+
+View verify_each_annotated_param_independently(
+ const MyObj &a [[clang::lifetimebound]],
+ const MyObj &b [[clang::lifetimebound]], // expected-warning {{could not verify that the return value can be lifetime bound to 'b'}}
+ const MyObj &c [[clang::lifetimebound]]) { // expected-warning {{could not verify that the return value can be lifetime bound to 'c'}}
+ return cond() ? a : not_lb(b);
+}
+
+View unnamed_lifetimebound_param(
+ [[clang::lifetimebound]] const MyObj &) { // expected-warning {{could not verify that the return value can be lifetime bound to an unnamed parameter}}
+ return View();
+}
+
+// FIXME: Should warn on declaration, not definiton
+View annotated_decl_but_not_def_not_returned(const MyObj &obj [[clang::lifetimebound]]);
+
+View annotated_decl_but_not_def_not_returned(const MyObj &obj) { // expected-warning {{could not verify that the return value can be lifetime bound to 'obj'}}
+ return not_lb(obj);
+}
More information about the cfe-commits
mailing list