Author: Gábor Horváth Date: 2026-11-10T15:47:20Z New Revision: e1eeaaae8f11ec193414f20842c28c74e1240bbc
URL: https://github.com/llvm/llvm-project/commit/e1eeaaae8f11ec193414f20842c28c74e1240bbc DIFF: https://github.com/llvm/llvm-project/commit/e1eeaaae8f11ec193414f20842c28c74e1240bbc.diff LOG: [LifetimeSafety] Map arguments to an explicit object parameter correctly (#240411) For a C++23 explicit object member function the object argument binds to `self`, getParamDecl(0), but getTrackedArgInfo mapped argument I to getParamDecl(I - 1) as for an implicit object. A lifetimebound parameter after `self` was ignored, lifetimebound on `self` was attributed to the next argument, and a by-value `self` of a gsl::Pointer hit an assertion. Add hasObjectArg, hasImplicitObjectArg and getParamForArg, and use them wherever call arguments are mapped to parameters. Assisted-by: Claude Opus 5.5 Co-authored-by: Gabor Horvath <[email protected]> Added: clang/test/Sema/LifetimeSafety/explicit-object-param.cpp Modified: clang/include/clang/Analysis/Analyses/LifetimeSafety/LifetimeAnnotations.h clang/lib/Analysis/LifetimeSafety/FactsGenerator.cpp clang/lib/Analysis/LifetimeSafety/LifetimeAnnotations.cpp Removed: clang/test/Sema/LifetimeSafety/explicit-object-param-no-crash.cpp ################################################################################ diff --git a/clang/include/clang/Analysis/Analyses/LifetimeSafety/LifetimeAnnotations.h b/clang/include/clang/Analysis/Analyses/LifetimeSafety/LifetimeAnnotations.h index 6f9255311d9496..200c69dafa9699 100644 --- a/clang/include/clang/Analysis/Analyses/LifetimeSafety/LifetimeAnnotations.h +++ b/clang/include/clang/Analysis/Analyses/LifetimeSafety/LifetimeAnnotations.h @@ -81,6 +81,20 @@ struct FunctionCallInfo { explicit FunctionCallInfo(const Expr *Call); }; +/// Returns true if argument 0 of a call to \p FD (as listed by +/// FunctionCallInfo) is the object argument, bound either to the implicit +/// object parameter or to an explicit object parameter. Constructors have no +/// object argument. +bool hasObjectArg(const FunctionDecl &FD); + +/// Returns true if argument 0 of a call to \p FD is the implicit object +/// argument. An explicit object parameter is an ordinary parameter. +bool hasImplicitObjectArg(const FunctionDecl &FD); + +/// Returns the parameter that argument \p I of a call to \p FD binds to, or +/// null for the implicit object argument and for variadic arguments. +const ParmVarDecl *getParamForArg(const FunctionDecl &FD, unsigned I); + /// Returns the parameter corresponding to argument I when the argument should /// be tracked for lifetime safety. std::optional<LifetimeBoundParamInfo> diff --git a/clang/lib/Analysis/LifetimeSafety/FactsGenerator.cpp b/clang/lib/Analysis/LifetimeSafety/FactsGenerator.cpp index 7356c6b5ce134c..fd2709edd88bb0 100644 --- a/clang/lib/Analysis/LifetimeSafety/FactsGenerator.cpp +++ b/clang/lib/Analysis/LifetimeSafety/FactsGenerator.cpp @@ -965,30 +965,23 @@ void FactsGenerator::handleGSLPointerConstruction(const CXXConstructExpr *CCE) { void FactsGenerator::handleMovedArgsInCall(const FunctionDecl *FD, ArrayRef<const Expr *> Args) { - unsigned ImplicitObjectArgOffset = 0; - // Constructors are excluded because Args has no object argument for them, - // even though isImplicitObjectMemberFunction() is true. + // std::unique_ptr::release() transfers ownership. + // Treat it as a move to prevent false-positive warnings when the unique_ptr + // destructor runs after ownership has been transferred. if (const auto *MD = dyn_cast<CXXMethodDecl>(FD); - MD && !isa<CXXConstructorDecl>(FD) && - MD->isImplicitObjectMemberFunction()) { - ImplicitObjectArgOffset = 1; - // std::unique_ptr::release() transfers ownership. - // Treat it as a move to prevent false-positive warnings when the unique_ptr - // destructor runs after ownership has been transferred. - if (isUniquePtrRelease(*MD)) { - const Expr *UniquePtrExpr = Args[0]; - OriginList *MovedOrigins = getOriginsList(*UniquePtrExpr); - if (MovedOrigins) - CurrentBlockFacts.push_back(FactMgr.createFact<MovedOriginFact>( - UniquePtrExpr, MovedOrigins->getOuterOriginID())); - } + MD && hasImplicitObjectArg(*FD) && isUniquePtrRelease(*MD)) { + const Expr *UniquePtrExpr = Args[0]; + OriginList *MovedOrigins = getOriginsList(*UniquePtrExpr); + if (MovedOrigins) + CurrentBlockFacts.push_back(FactMgr.createFact<MovedOriginFact>( + UniquePtrExpr, MovedOrigins->getOuterOriginID())); } - // Skip implicit 'this' arg as it cannot be moved. - for (unsigned I = ImplicitObjectArgOffset; - I < Args.size() && I < FD->getNumParams() + ImplicitObjectArgOffset; - ++I) { - const ParmVarDecl *PVD = FD->getParamDecl(I - ImplicitObjectArgOffset); + for (unsigned I = 0; I < Args.size(); ++I) { + // Null for the implicit 'this' arg, which cannot be moved. + const ParmVarDecl *PVD = getParamForArg(*FD, I); + if (!PVD) + continue; // In principle, explicit object parameters can be moved, but skip marking // them as moved for consistency with implicit 'this'. if (PVD->isExplicitObjectParameter()) @@ -1085,31 +1078,13 @@ void FactsGenerator::handleLifetimeCaptureBy(const FunctionDecl *FD, // FIXME: Add support for capture_by on constructors. if (isa<CXXConstructorDecl>(FD)) return; - const auto *Method = dyn_cast<CXXMethodDecl>(FD); - bool HasImplicitObjectArg = Method && - Method->isImplicitObjectMemberFunction() && - !isa<CXXConstructorDecl>(FD); auto getArgCaptureByAttr = - [FD, HasImplicitObjectArg]( - unsigned I) -> std::pair<const LifetimeCaptureByAttr *, QualType> { - if (HasImplicitObjectArg) { - if (I == 0) { - auto *MethodDecl = cast<CXXMethodDecl>(FD); - QualType ParamType = MethodDecl->getFunctionObjectParameterType(); - return {getCaptureByAttrFromFunctionType(FD), ParamType}; - } - if (I > 0 && I - 1 < FD->getNumParams()) { - const ParmVarDecl *PVD = FD->getParamDecl(I - 1); - return {PVD ? PVD->getAttr<LifetimeCaptureByAttr>() : nullptr, - PVD->getType()}; - } - } else { - if (I < FD->getNumParams()) { - const ParmVarDecl *PVD = FD->getParamDecl(I); - return {PVD ? PVD->getAttr<LifetimeCaptureByAttr>() : nullptr, - PVD->getType()}; - } - } + [FD](unsigned I) -> std::pair<const LifetimeCaptureByAttr *, QualType> { + if (I == 0 && hasImplicitObjectArg(*FD)) + return {getCaptureByAttrFromFunctionType(FD), + cast<CXXMethodDecl>(FD)->getFunctionObjectParameterType()}; + if (const ParmVarDecl *PVD = getParamForArg(*FD, I)) + return {PVD->getAttr<LifetimeCaptureByAttr>(), PVD->getType()}; return {nullptr, QualType()}; }; for (unsigned I = 0; I < Args.size(); ++I) { @@ -1234,11 +1209,14 @@ void FactsGenerator::handleFunctionCall(const Expr *Call, return; } auto shouldTrackPointerImplicitObjectArg = [FD, &Args](unsigned I) -> bool { - const auto *Method = dyn_cast<CXXMethodDecl>(FD); - if (!Method || !Method->isInstance()) + if (I != 0 || !hasObjectArg(*FD)) + return false; + // A by-value explicit object parameter takes a prvalue copy, which is + // handled as an ordinary argument below. + if (!hasImplicitObjectArg(*FD) && !Args[0]->isGLValue()) return false; - return I == 0 && - isGslPointerType(Method->getFunctionObjectParameterType()) && + const auto *Method = cast<CXXMethodDecl>(FD); + return isGslPointerType(Method->getFunctionObjectParameterType()) && shouldTrackImplicitObjectArg(*Args[0], Method, /*RunningUnderLifetimeSafety=*/true); }; diff --git a/clang/lib/Analysis/LifetimeSafety/LifetimeAnnotations.cpp b/clang/lib/Analysis/LifetimeSafety/LifetimeAnnotations.cpp index dd00ff4f5ccb61..310e55931fc448 100644 --- a/clang/lib/Analysis/LifetimeSafety/LifetimeAnnotations.cpp +++ b/clang/lib/Analysis/LifetimeSafety/LifetimeAnnotations.cpp @@ -132,6 +132,25 @@ FunctionCallInfo::FunctionCallInfo(const Expr *Call) { FD = dyn_cast_or_null<FunctionDecl>(AC->getDecl()); } +bool hasObjectArg(const FunctionDecl &FD) { + const auto *MD = dyn_cast<CXXMethodDecl>(&FD); + return MD && MD->isInstance() && !isa<CXXConstructorDecl>(MD); +} + +bool hasImplicitObjectArg(const FunctionDecl &FD) { + return hasObjectArg(FD) && + cast<CXXMethodDecl>(FD).isImplicitObjectMemberFunction(); +} + +const ParmVarDecl *getParamForArg(const FunctionDecl &FD, unsigned I) { + if (hasImplicitObjectArg(FD)) { + if (I == 0) + return nullptr; + --I; + } + return I < FD.getNumParams() ? FD.getParamDecl(I) : nullptr; +} + std::optional<LifetimeBoundParamInfo> getTrackedArgInfo(const FunctionDecl *FD, llvm::ArrayRef<const Expr *> Args, unsigned I) { @@ -139,31 +158,28 @@ getTrackedArgInfo(const FunctionDecl *FD, llvm::ArrayRef<const Expr *> Args, if (!FD || I >= Args.size()) return std::nullopt; - const ParmVarDecl *PVD = nullptr; - - if (const auto *Method = dyn_cast<CXXMethodDecl>(FD); - Method && Method->isInstance() && !isa<CXXConstructorDecl>(FD)) { - if (I == 0) { - // For the 'this' argument, the attribute is on the method itself. - if (implicitObjectParamIsLifetimeBound(Method) || - shouldTrackImplicitObjectArg(*Args[0], Method, - /*RunningUnderLifetimeSafety=*/true)) - return LifetimeBoundParamInfo(Method); - return std::nullopt; - } - if ((I - 1) < Method->getNumParams()) - // For explicit arguments, find the corresponding parameter declaration. - PVD = Method->getParamDecl(I - 1); - } else if (I == 0 && shouldTrackFirstArgument(FD)) { - return LifetimeBoundParamInfo(FD->getParamDecl(I)); - } else if (I == 1 && shouldTrackSecondArgument(FD)) { - return LifetimeBoundParamInfo(FD->getParamDecl(I)); - } else if (I < FD->getNumParams()) { - // For free functions or static methods. - PVD = FD->getParamDecl(I); + if (I == 0 && hasObjectArg(*FD)) { + const auto *Method = cast<CXXMethodDecl>(FD); + bool TrackObject = + implicitObjectParamIsLifetimeBound(Method) || + shouldTrackImplicitObjectArg(*Args[0], Method, + /*RunningUnderLifetimeSafety=*/true); + if (hasImplicitObjectArg(*FD)) + return TrackObject ? std::optional(LifetimeBoundParamInfo(Method)) + : std::nullopt; + // An explicit object parameter is reported as the parameter it is. + if (TrackObject) + return LifetimeBoundParamInfo(Method->getParamDecl(0)); + } + if (!hasImplicitObjectArg(*FD)) { + if (I == 0 && shouldTrackFirstArgument(FD)) + return LifetimeBoundParamInfo(FD->getParamDecl(I)); + if (I == 1 && shouldTrackSecondArgument(FD)) + return LifetimeBoundParamInfo(FD->getParamDecl(I)); } - if (PVD && PVD->hasAttr<clang::LifetimeBoundAttr>()) + if (const ParmVarDecl *PVD = getParamForArg(*FD, I); + PVD && PVD->hasAttr<clang::LifetimeBoundAttr>()) return LifetimeBoundParamInfo(PVD); return std::nullopt; diff --git a/clang/test/Sema/LifetimeSafety/explicit-object-param-no-crash.cpp b/clang/test/Sema/LifetimeSafety/explicit-object-param-no-crash.cpp deleted file mode 100644 index 31c07d9d7f1028..00000000000000 --- a/clang/test/Sema/LifetimeSafety/explicit-object-param-no-crash.cpp +++ /dev/null @@ -1,106 +0,0 @@ -// RUN: %clang_cc1 %s -std=c++23 -verify -fsyntax-only -Wlifetime-safety -Wlifetime-safety-lifetimebound-violation - -#include "Inputs/lifetime-analysis.h" - -// Explicit object member functions must not be treated as having an implicit -// object argument. -struct Foo { - template <typename T> - int get(this Foo &&self, T) { - return self.field; - } - - int field; -}; - -struct Base {}; -struct Derived : Base { - int base(this Base &&, int); -}; - -template <typename T> -struct Crtp { - template <typename Self> - int deduced(this Self &&self, T) { - return self.field; - } -}; - -struct Widget : Crtp<int> { - int field; -}; - -struct NoMove { - NoMove() = default; - NoMove(NoMove &&) = delete; - NoMove(const NoMove &) = delete; - - int get(this NoMove &&self, int) { - return self.field; - } - - int field; -}; - -template <typename T> -struct SharedPtr { - SharedPtr() = default; - SharedPtr(SharedPtr &&o) : p(o.p) { o.p = nullptr; } - SharedPtr(const SharedPtr &) = default; - - int get(this SharedPtr &&self, int) { - return self.p->field; - } - - T *p = nullptr; -}; - -void call() { - Foo().get(0); - Derived().base(0); - Widget().deduced(0); - NoMove().get(0); - SharedPtr<NoMove>().get(0); -} - -struct Holder { - int field; - const int *borrow() [[clang::lifetimebound]] { return &field; } - void consume(this Holder &&self) {} -}; - -const int *object_arg_is_not_moved(Holder &&h [[clang::lifetimebound]]) { - static_cast<Holder &&>(h).consume(); - return h.borrow(); -} - -const int *t1(Holder h) { - const int *ptr = h.borrow(); // expected-warning {{stack memory associated with parameter 'h' is returned}} \ - // expected-note {{result of call to 'borrow' aliases the storage of parameter 'h' because the implicit object parameter is marked as lifetimebound}} - static_cast<Holder &&>(h).consume(); - return ptr; // expected-note {{returned here}} -} - -const int *t2(Holder h) { - const int *ptr = h.borrow(); // expected-warning {{stack memory associated with parameter 'h' is returned}} \ - // expected-note {{result of call to 'borrow' aliases the storage of parameter 'h' because the implicit object parameter is marked as lifetimebound}} - std::move(h).consume(); - return ptr; // expected-note {{returned here}} -} - -struct Set { - void insert(this Set &self, const int &x [[clang::lifetime_capture_by(self)]], - const int &hint); -}; - -int global; - -void capture_by_explicit_object() { - Set s; - { - int local = 0; - s.insert(local, global); // expected-warning {{local variable 'local' does not live long enough}} - s.insert(global, local); - } // expected-note {{destroyed here}} - use(s); // expected-note {{later used here}} -} diff --git a/clang/test/Sema/LifetimeSafety/explicit-object-param.cpp b/clang/test/Sema/LifetimeSafety/explicit-object-param.cpp new file mode 100644 index 00000000000000..d708dae3447709 --- /dev/null +++ b/clang/test/Sema/LifetimeSafety/explicit-object-param.cpp @@ -0,0 +1,259 @@ +// RUN: %clang_cc1 %s -std=c++23 -verify -fsyntax-only -Wlifetime-safety -Wlifetime-safety-lifetimebound-violation -Wno-dangling + +#include "Inputs/lifetime-analysis.h" + +// Explicit object member functions must not be treated as having an implicit +// object argument. +struct Foo { + template <typename T> + int get(this Foo &&self, T) { + return self.field; + } + + int field; +}; + +struct Base {}; +struct Derived : Base { + int base(this Base &&, int); +}; + +template <typename T> +struct Crtp { + template <typename Self> + int deduced(this Self &&self, T) { + return self.field; + } +}; + +struct Widget : Crtp<int> { + int field; +}; + +struct NoMove { + NoMove() = default; + NoMove(NoMove &&) = delete; + NoMove(const NoMove &) = delete; + + int get(this NoMove &&self, int) { + return self.field; + } + + int field; +}; + +template <typename T> +struct SharedPtr { + SharedPtr() = default; + SharedPtr(SharedPtr &&o) : p(o.p) { o.p = nullptr; } + SharedPtr(const SharedPtr &) = default; + + int get(this SharedPtr &&self, int) { + return self.p->field; + } + + T *p = nullptr; +}; + +void call() { + Foo().get(0); + Derived().base(0); + Widget().deduced(0); + NoMove().get(0); + SharedPtr<NoMove>().get(0); +} + +struct Holder { + int field; + const int *borrow() [[clang::lifetimebound]] { return &field; } + void consume(this Holder &&self) {} +}; + +const int *object_arg_is_not_moved(Holder &&h [[clang::lifetimebound]]) { + static_cast<Holder &&>(h).consume(); + return h.borrow(); +} + +const int *t1(Holder h) { + const int *ptr = h.borrow(); // expected-warning {{stack memory associated with parameter 'h' is returned}} \ + // expected-note {{result of call to 'borrow' aliases the storage of parameter 'h' because the implicit object parameter is marked as lifetimebound}} + static_cast<Holder &&>(h).consume(); + return ptr; // expected-note {{returned here}} +} + +const int *t2(Holder h) { + const int *ptr = h.borrow(); // expected-warning {{stack memory associated with parameter 'h' is returned}} \ + // expected-note {{result of call to 'borrow' aliases the storage of parameter 'h' because the implicit object parameter is marked as lifetimebound}} + std::move(h).consume(); + return ptr; // expected-note {{returned here}} +} + +struct Set { + void insert(this Set &self, const int &x [[clang::lifetime_capture_by(self)]], + const int &hint); +}; + +int global; + +void capture_by_explicit_object() { + Set s; + { + int local = 0; + s.insert(local, global); // expected-warning {{local variable 'local' does not live long enough}} + s.insert(global, local); + } // expected-note {{destroyed here}} + use(s); // expected-note {{later used here}} +} + +struct Lookup { + const int &operator[](this const Lookup &self, + const int &key [[clang::lifetimebound]]); + const int &get(this const Lookup &self, + const int &key [[clang::lifetimebound]]); + const int &self_bound(this const Lookup &self [[clang::lifetimebound]], + const int &key); +}; + +const int &lifetimebound_after_explicit_object_subscript(const Lookup &l) { + int key = 1; + return l[key]; // expected-warning {{stack memory associated with local variable 'key' is returned}} \ + // expected-note {{returned here}} +} + +const int &lifetimebound_after_explicit_object_call(const Lookup &l) { + int key = 1; + return l.get(key); // expected-warning {{stack memory associated with local variable 'key' is returned}} \ + // expected-note {{returned here}} +} + +const int &lifetimebound_explicit_object(const Lookup &l) { + int key = 1; + return l.self_bound(key); +} + +const int &dangling_explicit_object() { + Lookup l; + return l.self_bound(1); // expected-warning {{stack memory associated with local variable 'l' is returned}} \ + // expected-note {{returned here}} +} + +const int &lifetimebound_after_xvalue_explicit_object(Lookup &l) { + int key = 1; + return std::move(l).get(key); // expected-warning {{stack memory associated with local variable 'key' is returned}} \ + // expected-note {{returned here}} +} + +const int &lifetimebound_after_prvalue_explicit_object() { + int key = 1; + return Lookup{}.get(key); // expected-warning {{stack memory associated with local variable 'key' is returned}} \ + // expected-note {{returned here}} +} + +const int &dangling_xvalue_explicit_object() { + Lookup l; + return std::move(l).self_bound(1); // expected-warning {{stack memory associated with local variable 'l' is returned}} \ + // expected-note {{result of call to 'move<Lookup &>' aliases the storage of local variable 'l'}} \ + // expected-note {{returned here}} +} + +const int &dangling_prvalue_explicit_object() { + return Lookup{}.self_bound(1); // expected-warning {{stack memory associated with temporary object is returned}} \ + // expected-note {{returned here}} +} + +const int &xvalue_explicit_object_param(Lookup &l) { + return std::move(l).self_bound(1); +} + +struct Deduced { + template <typename Self> + const int &get(this Self &&self [[clang::lifetimebound]]); + const int &get_auto(this auto &&self [[clang::lifetimebound]]); +}; + +const int &dangling_deduced_explicit_object() { + Deduced d; + return d.get(); // expected-warning {{stack memory associated with local variable 'd' is returned}} \ + // expected-note {{returned here}} +} + +const int &dangling_abbreviated_explicit_object() { + Deduced d; + return d.get_auto(); // expected-warning {{stack memory associated with local variable 'd' is returned}} \ + // expected-note {{returned here}} +} + +const int &dangling_prvalue_deduced_explicit_object() { + return Deduced{}.get(); // expected-warning {{stack memory associated with temporary object is returned}} \ + // expected-note {{returned here}} +} + +const int &deduced_explicit_object_param(const Deduced &d) { return d.get(); } + +// The object-argument heuristics apply to an explicit object parameter too. +struct [[gsl::Owner]] Buffer {}; +struct [[gsl::Pointer]] BufferView { + BufferView(const Buffer &b [[clang::lifetimebound]]); + int *get(this const BufferView &self); + int &operator*(this const BufferView &self); +}; +struct [[gsl::Pointer]] ValueView { + ValueView(const Buffer &b [[clang::lifetimebound]]); + int *get(this ValueView self); +}; +struct [[gsl::Pointer]] TextView { + const char *p; +}; +struct [[gsl::Owner]] Text { + operator TextView(this const Text &self); +}; +struct Assignable { + Assignable &operator=(this Assignable &self, const Assignable &other); +}; + +int *get_through_explicit_object() { + Buffer b; + BufferView w(b); // expected-warning {{stack memory associated with local variable 'b' is returned}} + return w.get(); // expected-note {{returned here}} +} + +int *deref_through_explicit_object() { + Buffer b; + BufferView w(b); // expected-warning {{stack memory associated with local variable 'b' is returned}} + return &*w; // expected-note {{result of call to 'operator*' aliases the storage of local variable 'b'}} \ + // expected-note {{returned here}} +} + +int *get_through_by_value_explicit_object() { + Buffer b; + ValueView w(b); // expected-warning {{stack memory associated with local variable 'b' is returned}} + return w.get(); // expected-note {{returned here}} +} + +TextView convert_through_explicit_object() { + Text t; + return t; // expected-warning {{stack memory associated with local variable 't' is returned}} \ + // expected-note {{returned here}} +} + +Assignable &assign_through_explicit_object() { + Assignable a; + return a = Assignable(); // expected-warning {{stack memory associated with local variable 'a' is returned}} \ + // expected-note {{returned here}} +} + +int *get_through_explicit_object_ok(const Buffer &b) { + BufferView w(b); + return w.get(); +} + +struct Sink { + void take(this Sink &self, std::string &&s); +}; + +std::string_view moved_after_explicit_object(Sink &sink) { + std::string s; + std::string_view v = s; // expected-warning {{stack memory associated with local variable 's' may be returned later}} + sink.take(std::move(s)); // expected-note {{potentially moved here}} + return v; // expected-note {{returned here}} +} _______________________________________________ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
