[clang] [LifetimeSafety] Propagate origins through BaseToDerived casts (PR #231896)
via cfe-commits
cfe-commits at lists.llvm.org
Wed Oct 14 07:51:30 PDT 2026
================
@@ -0,0 +1,71 @@
+// RUN: %clang_cc1 -fsyntax-only -Wlifetime-safety -Wno-dangling -verify %s
+
+struct Base {};
+struct Derived : Base {};
+Derived *DowncastReturnsStackAddress() {
+ Derived d;
+ Base *b = &d;
+ // expected-warning at -1 {{stack memory associated with local variable 'd' is returned}}
+ return static_cast<Derived *>(b); // expected-note {{returned here}}
+}
+
+// A downcast that does not outlive the pointee is fine.
+void use(Derived *);
+void DowncastWithinScopeIsOk() {
+ Derived d;
+ Base *b = &d;
+ use(static_cast<Derived *>(b)); // ok
+}
+
+struct RefBase {};
+struct RefDerived : RefBase {};
+RefDerived *DowncastReferenceReturnsStackAddress() {
+ RefDerived d;
+ RefBase &b = d;
+ // expected-warning at -1 {{stack memory associated with local variable 'd' is returned}}
+ RefDerived &r = static_cast<RefDerived &>(b);
+ return &r; // expected-note {{returned here}}
+}
+
+void use(Derived &);
+void DowncastReferenceWithinScopeIsOk() {
+ Derived d;
+ Base &b = d;
+ use(static_cast<Derived &>(b)); // ok
+}
+
+// ****************************************************************************
+// Different origin shapes for BaseToDerived and DerivedToBase casts.
+// ****************************************************************************
----------------
NeKon69 wrote:
I don't think we usually write such comments? Especially with stars and everything. This probably doesn't matter that much though.
https://github.com/llvm/llvm-project/pull/231896
More information about the cfe-commits
mailing list