[clang] [LifetimeSafety] Add warning for member functions returning field origins (PR #229784)
Utkarsh Saxena via cfe-commits
cfe-commits at lists.llvm.org
Wed Oct 14 02:50:33 PDT 2026
================
@@ -700,3 +700,94 @@ S foo() {
return S(create_up());
}
} // namespace GH193747
+
+namespace field_origin_escape {
+
+class Context {
+public:
+ // This method should be annotated with lifetimebound.
+ std::string_view method() const { // expected-warning {{implicit this in intra-TU function should be marked [[clang::lifetimebound]]}}
+ return method_; // expected-note {{param returned here}}
+ }
+
+private:
+ std::string method_ = "42";
+};
+
+class ContextAnnotated {
+public:
+ std::string_view method() const [[clang::lifetimebound]] {
+ return method_;
+ }
+
+private:
+ std::string method_ = "42";
+};
+
+class ContextWrapper {
+public:
+ explicit ContextWrapper(Context &inner, // expected-warning {{parameter in intra-TU constructor should be marked [[clang::lifetimebound]]}}
+ ContextAnnotated &annot) // expected-warning {{parameter in intra-TU constructor should be marked [[clang::lifetimebound]]}}
+ : inner_(inner), annot_(annot) {}
+
+ Context &inner() const { // expected-warning {{return value depends on the lifetime of the object referenced by field 'inner_', which cannot be expressed with [[clang::lifetimebound]]}}
+ return inner_; // expected-note {{returned here}}
+ }
+
+ // This method should NOT be annotated with lifetimebound.
+ std::string_view method() const { // expected-warning {{return value depends on the lifetime of the object referenced by field 'inner_', which cannot be expressed with [[clang::lifetimebound]]}}
+ return inner_.method(); // expected-note {{returned here}}
+ }
+
+ std::string_view annot_method() const { // expected-warning {{return value depends on the lifetime of the object referenced by field 'annot_', which cannot be expressed with [[clang::lifetimebound]]}}
+ return annot_.method(); // expected-note {{returned here}}
+ }
+
+private:
+ Context &inner_; // expected-note {{escapes to this field}}
+ ContextAnnotated &annot_; // expected-note {{escapes to this field}}
+};
+
+struct FieldTypes {
+ int val_;
+ int *ptr_;
+ int &ref_;
+ std::string str_;
----------------
usx95 wrote:
Added.
https://github.com/llvm/llvm-project/pull/229784
More information about the cfe-commits
mailing list