https://github.com/Xazax-hun updated 
https://github.com/llvm/llvm-project/pull/240485

From 307456830c7e6a4aa3a3ad3eaaabfd571eddb88a Mon Sep 17 00:00:00 2001
From: Gabor Horvath <[email protected]>
Date: Mon, 9 Nov 2026 17:57:58 +0000
Subject: [PATCH] [LifetimeSafety] Treat lifetime_capture_by(this) on a
 constructor as lifetimebound

lifetime_capture_by(this) on a constructor parameter means the same as
lifetimebound, but the analysis only honored it with inference enabled.
It also ignored a lifetimebound parameter of a gsl::Pointer constructor
taking several arguments. Handle both, and make lifetime_capture_by
inherited by redeclarations like lifetimebound, so an out-of-line
definition keeps it.

Fixes #227246

Assisted-by: Claude Opus 5.5
---
 .../LifetimeSafety/LifetimeAnnotations.h      |  5 ++
 clang/lib/Analysis/LifetimeSafety/Checker.cpp |  2 +-
 .../LifetimeSafety/FactsGenerator.cpp         | 12 +++-
 .../LifetimeSafety/LifetimeAnnotations.cpp    | 13 +++-
 clang/lib/Analysis/LifetimeSafety/Origins.cpp |  2 +-
 clang/lib/Sema/SemaDecl.cpp                   |  9 +--
 clang/test/AST/attr-lifetime-capture-by.cpp   | 13 ++++
 clang/test/Sema/LifetimeSafety/capture-by.cpp | 19 ++++++
 clang/test/Sema/LifetimeSafety/safety.cpp     | 62 +++++++++++++++++--
 9 files changed, 123 insertions(+), 14 deletions(-)

diff --git 
a/clang/include/clang/Analysis/Analyses/LifetimeSafety/LifetimeAnnotations.h 
b/clang/include/clang/Analysis/Analyses/LifetimeSafety/LifetimeAnnotations.h
index 6f9255311d9496..faca59dab06be0 100644
--- a/clang/include/clang/Analysis/Analyses/LifetimeSafety/LifetimeAnnotations.h
+++ b/clang/include/clang/Analysis/Analyses/LifetimeSafety/LifetimeAnnotations.h
@@ -64,6 +64,11 @@ getImplicitObjectParamLifetimeBoundAttr(const FunctionDecl 
*FD);
 /// method or because it's a normal assignment operator.
 bool implicitObjectParamIsLifetimeBound(const FunctionDecl *FD);
 
+/// Returns true if \p PVD should be considered lifetimebound, either due to an
+/// explicit lifetimebound attribute or because it is a constructor parameter
+/// marked `lifetime_capture_by(this)`, which has the same meaning.
+bool paramIsLifetimeBound(const ParmVarDecl &PVD);
+
 /// Check if a function has a lifetime_capture_by attribute on its declaration
 /// or its function type (which represents the implicit 'this' parameter for
 /// methods). Returns the attribute if found, nullptr otherwise.
diff --git a/clang/lib/Analysis/LifetimeSafety/Checker.cpp 
b/clang/lib/Analysis/LifetimeSafety/Checker.cpp
index 2d2c394e255943..eaa501d63508da 100644
--- a/clang/lib/Analysis/LifetimeSafety/Checker.cpp
+++ b/clang/lib/Analysis/LifetimeSafety/Checker.cpp
@@ -144,7 +144,7 @@ class LifetimeChecker {
       // obscures the lifetime relationship (e.g., shared_ptr from unique_ptr).
       if (IsMoved)
         return;
-      if (PVD->hasAttr<LifetimeBoundAttr>()) {
+      if (paramIsLifetimeBound(*PVD)) {
         // Track that this lifetimebound parameter correctly escapes
         // (via return or via field assignment in a constructor).
         if (isa<ReturnEscapeFact>(OEF) ||
diff --git a/clang/lib/Analysis/LifetimeSafety/FactsGenerator.cpp 
b/clang/lib/Analysis/LifetimeSafety/FactsGenerator.cpp
index 7356c6b5ce134c..d436bea7f64238 100644
--- a/clang/lib/Analysis/LifetimeSafety/FactsGenerator.cpp
+++ b/clang/lib/Analysis/LifetimeSafety/FactsGenerator.cpp
@@ -935,8 +935,12 @@ void FactsGenerator::handleExitBlock() {
 
 void FactsGenerator::handleGSLPointerConstruction(const CXXConstructExpr *CCE) 
{
   assert(isGslPointerType(CCE->getType()));
-  if (CCE->getNumArgs() != 1)
+  // Only lifetimebound parameters propagate for a constructor taking several
+  // arguments; the owner heuristic applies to single-argument construction.
+  if (CCE->getNumArgs() != 1) {
+    handleFunctionCall(CCE, /*IsGslConstruction=*/true);
     return;
+  }
 
   const Expr *Arg = CCE->getArg(0);
   if (isGslPointerType(Arg->getType())) {
@@ -1235,7 +1239,8 @@ void FactsGenerator::handleFunctionCall(const Expr *Call,
   }
   auto shouldTrackPointerImplicitObjectArg = [FD, &Args](unsigned I) -> bool {
     const auto *Method = dyn_cast<CXXMethodDecl>(FD);
-    if (!Method || !Method->isInstance())
+    // A constructor call has no object argument.
+    if (!Method || !Method->isInstance() || isa<CXXConstructorDecl>(Method))
       return false;
     return I == 0 &&
            isGslPointerType(Method->getFunctionObjectParameterType()) &&
@@ -1257,7 +1262,8 @@ void FactsGenerator::handleFunctionCall(const Expr *Call,
         assert(!Args[I]->isGLValue() || ArgList->getLength() >= 2);
         ArgList = readValue(Args[I]);
       }
-      if (isGslOwnerType(Args[I]->getType())) {
+      if (isGslOwnerType(Args[I]->getType()) &&
+          (Args.size() == 1 || ShouldTrackArg)) {
         // The constructed gsl::Pointer borrows from the Owner's storage, not
         // from what the Owner itself borrows, so only the outermost origin is
         // needed.
diff --git a/clang/lib/Analysis/LifetimeSafety/LifetimeAnnotations.cpp 
b/clang/lib/Analysis/LifetimeSafety/LifetimeAnnotations.cpp
index dd00ff4f5ccb61..497ecd837cb571 100644
--- a/clang/lib/Analysis/LifetimeSafety/LifetimeAnnotations.cpp
+++ b/clang/lib/Analysis/LifetimeSafety/LifetimeAnnotations.cpp
@@ -115,6 +115,17 @@ bool implicitObjectParamIsLifetimeBound(const FunctionDecl 
*FD) {
   return isNormalAssignmentOperator(FD);
 }
 
+bool paramIsLifetimeBound(const ParmVarDecl &PVD) {
+  if (PVD.hasAttr<LifetimeBoundAttr>())
+    return true;
+  return isa<CXXConstructorDecl>(PVD.getDeclContext()) &&
+         llvm::any_of(PVD.specific_attrs<LifetimeCaptureByAttr>(),
+                      [](const LifetimeCaptureByAttr *A) {
+                        return llvm::is_contained(A->params(),
+                                                  LifetimeCaptureByAttr::This);
+                      });
+}
+
 const LifetimeCaptureByAttr *
 getCaptureByAttrFromFunctionType(const FunctionDecl *FD) {
   return getImplicitObjectParamAttr<LifetimeCaptureByAttr>(FD);
@@ -163,7 +174,7 @@ getTrackedArgInfo(const FunctionDecl *FD, 
llvm::ArrayRef<const Expr *> Args,
     PVD = FD->getParamDecl(I);
   }
 
-  if (PVD && PVD->hasAttr<clang::LifetimeBoundAttr>())
+  if (PVD && paramIsLifetimeBound(*PVD))
     return LifetimeBoundParamInfo(PVD);
 
   return std::nullopt;
diff --git a/clang/lib/Analysis/LifetimeSafety/Origins.cpp 
b/clang/lib/Analysis/LifetimeSafety/Origins.cpp
index e571e6290bb308..fd712faeb6626e 100644
--- a/clang/lib/Analysis/LifetimeSafety/Origins.cpp
+++ b/clang/lib/Analysis/LifetimeSafety/Origins.cpp
@@ -93,7 +93,7 @@ class LifetimeAnnotatedOriginTypeCollector
     }
 
     for (const auto *Param : FD->parameters()) {
-      if (Param->hasAttr<LifetimeBoundAttr>()) {
+      if (paramIsLifetimeBound(*Param)) {
         CollectedTypes.push_back(RetType);
         return;
       }
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index d4fbf04ee284af..72d32e3a7b1482 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -3517,11 +3517,12 @@ static void mergeParamDeclAttributes(ParmVarDecl 
*newDecl,
       newDecl, oldDecl, [&S](ParmVarDecl *To, const ParmVarDecl *From) {
         unsigned found = 0;
         found += propagateAttribute<InheritableParamAttr>(To, From, S);
-        // Propagate the lifetimebound attribute from parameters to the
-        // most recent declaration. Note that this doesn't include the implicit
-        // 'this' parameter, as the attribute is applied to the function type 
in
-        // that case.
+        // Propagate the lifetimebound and lifetime_capture_by attributes from
+        // parameters to the most recent declaration. Note that this doesn't
+        // include the implicit 'this' parameter, as the attribute is applied 
to
+        // the function type in that case.
         found += propagateAttribute<LifetimeBoundAttr>(To, From, S);
+        found += propagateAttribute<LifetimeCaptureByAttr>(To, From, S);
         return found;
       });
 }
diff --git a/clang/test/AST/attr-lifetime-capture-by.cpp 
b/clang/test/AST/attr-lifetime-capture-by.cpp
index 8770c6c822934f..b930b580ad590b 100644
--- a/clang/test/AST/attr-lifetime-capture-by.cpp
+++ b/clang/test/AST/attr-lifetime-capture-by.cpp
@@ -115,3 +115,16 @@ std::map<View, int> map;
 // CHECK:       CXXMethodDecl {{.*}} operator[] 'int &(const View &)' 
implicit_instantiation
 // CHECK-NEXT:           ParmVarDecl {{.*}} p 'const View &'
 // CHECK-NEXT:               LifetimeCaptureByAttr {{.*}} Implicit
+
+// Verify that the attribute is inherited by a redeclaration, keeping the
+// resolved index even when the parameters are renamed.
+void captured(int &x [[clang::lifetime_capture_by(c)]], int &c);
+void captured(int &y, int &other);
+
+// CHECK:      FunctionDecl {{.*}} captured 'void (int &, int &)'
+// CHECK-NEXT:   ParmVarDecl {{.*}} x 'int &'
+// CHECK-NEXT:     LifetimeCaptureByAttr {{.*}} lifetime_capture_by 1
+// CHECK-NEXT:   ParmVarDecl {{.*}} c 'int &'
+// CHECK:      FunctionDecl {{.*}} prev {{.*}} captured 'void (int &, int &)'
+// CHECK-NEXT:   ParmVarDecl {{.*}} y 'int &'
+// CHECK-NEXT:     LifetimeCaptureByAttr {{.*}} Inherited lifetime_capture_by 1
diff --git a/clang/test/Sema/LifetimeSafety/capture-by.cpp 
b/clang/test/Sema/LifetimeSafety/capture-by.cpp
index ff8ec8544930a0..afb544f94e2bce 100644
--- a/clang/test/Sema/LifetimeSafety/capture-by.cpp
+++ b/clang/test/Sema/LifetimeSafety/capture-by.cpp
@@ -739,6 +739,25 @@ void test() {
   int a;
   T2(1, a); // expected-warning {{object whose reference is captured by}}
 }
+
+// The attribute is inherited by a redeclaration, even with renamed parameters.
+struct T4 {
+  T4(const int& t [[clang::lifetime_capture_by_this]]);
+};
+T4::T4(const int& renamed) {}
+
+void sink(const int& x [[clang::lifetime_capture_by(c)]], std::vector<const 
int*>& c);
+void sink(const int& y, std::vector<const int*>& other);
+
+void redeclared() {
+  T4 t4(1); // expected-warning {{temporary whose address is used}} \
+            // cfg-warning {{temporary object does not live long enough}} 
cfg-note {{destroyed here}}
+  use(t4);  // cfg-note {{later used here}}
+  std::vector<const int*> v;
+  sink(1, v); // expected-warning {{object whose reference is captured by 
'v'}} \
+              // cfg-warning {{temporary object does not live long enough}} 
cfg-note {{destroyed here}}
+  use(v);     // cfg-note {{later used here}}
+}
 } // namespace on_constructor
 
 namespace GH121391 {
diff --git a/clang/test/Sema/LifetimeSafety/safety.cpp 
b/clang/test/Sema/LifetimeSafety/safety.cpp
index a287bfb57ecce9..1b080f5029a777 100644
--- a/clang/test/Sema/LifetimeSafety/safety.cpp
+++ b/clang/test/Sema/LifetimeSafety/safety.cpp
@@ -2983,6 +2983,7 @@ void dangling_from_static_subscript(const Table &table) {
   }                  // expected-note {{local variable 'key' is destroyed 
here}}
   use(*p);           // expected-note {{later used here}}
 }
+#pragma clang diagnostic pop
 } // namespace static_call_operator
 
 namespace track_origins_for_lifetimebound_record_type {
@@ -3341,6 +3342,53 @@ struct PFieldFromTemp {
   PFieldFromTemp() : value(Bar{}) {} // expected-warning {{stack memory 
associated with temporary object escapes to the field 'value' which will 
dangle}}
 };
 
+template <typename T> struct [[gsl::Pointer]] MultiArgPointer {
+  MultiArgPointer();
+  MultiArgPointer(const T &bar [[clang::lifetimebound]], int flags = 0);
+};
+
+void multi_arg_pointer() {
+  MultiArgPointer<int> p, q;
+  {
+    int v;
+    p = MultiArgPointer(v, 1); // expected-warning {{local variable 'v' does 
not live long enough}}
+    q = MultiArgPointer(v);    // expected-warning {{local variable 'v' does 
not live long enough}}
+  }                            // expected-note 2 {{local variable 'v' is 
destroyed here}}
+  use(p, q);                   // expected-note 2 {{later used here}}
+}
+
+// A gsl::Pointer argument is seen through, as for a single argument.
+struct [[gsl::Pointer]] ViewArgPointer {
+  ViewArgPointer(const Pointer<int> &p [[clang::lifetimebound]], int flags);
+};
+
+ViewArgPointer view_arg_through_param(const int &x) {
+  Pointer<int> p(x);
+  return ViewArgPointer(p, 0);
+}
+
+ViewArgPointer view_arg_dangling() {
+  int x;
+  Pointer<int> p(x);           // expected-warning {{stack memory associated 
with local variable 'x' is returned}}
+  return ViewArgPointer(p, 0); // expected-note {{returned here}}
+}
+
+// Without an annotation, an owner argument of a constructor taking several
+// arguments is not assumed to be borrowed.
+struct [[gsl::Pointer]] UnannotatedMultiArgPointer {
+  UnannotatedMultiArgPointer();
+  UnannotatedMultiArgPointer(const MyObj &obj, int flags);
+};
+
+void unannotated_multi_arg_pointer() {
+  UnannotatedMultiArgPointer p;
+  {
+    MyObj obj;
+    p = UnannotatedMultiArgPointer(obj, 1);
+  }
+  use(p);
+}
+
 } // namespace gslpointer_construction_from_lifetimebound
 namespace conditional_operator_control_flow {
 // https://github.com/llvm/llvm-project/issues/183895
@@ -4633,7 +4681,7 @@ struct Helper {
 };
 } // namespace off_by_one_crash
 
-// FIXME(GH227246): Support capture_by_this on constructors without inference 
of lifetimebound.
+// `lifetime_capture_by_this` on a constructor parameter means `lifetimebound`.
 namespace constructor_test {
 struct Item {};
 
@@ -4649,9 +4697,15 @@ void test() {
   Container c;
   {
     Item item;
-    c = Container(item); // tu-warning {{local variable 'item' does not live 
long enough}}
-  }                      // tu-note {{local variable 'item' is destroyed here}}
-  use(c);                // tu-note {{later used here}}
+    c = Container(item); // expected-warning {{local variable 'item' does not 
live long enough}}
+  }                      // expected-note {{local variable 'item' is destroyed 
here}}
+  use(c);                // expected-note {{later used here}}
+}
+
+Container returned() {
+  Item item;
+  return Container(item); // expected-warning {{stack memory associated with 
local variable 'item' is returned}} \
+                          // expected-note {{returned here}}
 }
 } // namespace constructor_test
 

_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to