[clang] [LifetimeSafety] Give a lifetime-extended temporary a loan (PR #238776)
Gábor Horváth via cfe-commits
cfe-commits at lists.llvm.org
Thu Nov 5 03:51:04 PST 2026
https://github.com/Xazax-hun updated https://github.com/llvm/llvm-project/pull/238776
>From 4ad4d76867c33640968a21b034cdd19f60e4021b Mon Sep 17 00:00:00 2001
From: Gabor Horvath <gaborh at apple.com>
Date: Wed, 4 Nov 2026 12:36:35 +0000
Subject: [PATCH] [LifetimeSafety] Give a lifetime-extended temporary a loan
A loan was only issued for a temporary destroyed at the end of its
full-expression, so one extended by binding it to a reference had an
empty origin and a view of it could dangle unreported. Issue the loan
unconditionally and expire an automatic temporary together with the
variable that extends it.
Assisted-by: Claude Opus 5.5
---
.../Analyses/LifetimeSafety/FactsGenerator.h | 5 +
.../LifetimeSafety/FactsGenerator.cpp | 31 +++--
.../Sema/LifetimeSafety/lifetime-facts.cpp | 15 +++
clang/test/Sema/LifetimeSafety/safety.cpp | 109 ++++++++++++++++++
.../unittests/Analysis/LifetimeSafetyTest.cpp | 2 +-
5 files changed, 150 insertions(+), 12 deletions(-)
diff --git a/clang/include/clang/Analysis/Analyses/LifetimeSafety/FactsGenerator.h b/clang/include/clang/Analysis/Analyses/LifetimeSafety/FactsGenerator.h
index 009f050710c35f..9e6f70b9e6ffe4 100644
--- a/clang/include/clang/Analysis/Analyses/LifetimeSafety/FactsGenerator.h
+++ b/clang/include/clang/Analysis/Analyses/LifetimeSafety/FactsGenerator.h
@@ -21,6 +21,7 @@
#include "clang/Analysis/Analyses/LifetimeSafety/Origins.h"
#include "clang/Analysis/AnalysisDeclContext.h"
#include "clang/Analysis/CFG.h"
+#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallVector.h"
namespace clang::lifetimes::internal {
@@ -175,6 +176,10 @@ class FactsGenerator : public ConstStmtVisitor<FactsGenerator> {
// appended at the end of CurrentBlockFacts to ensure they appear after
// ExpireFact entries.
llvm::SmallVector<Fact *> EscapesInCurrentBlock;
+ // Lifetime-extended temporaries, keyed by the variable they expire with.
+ llvm::DenseMap<const ValueDecl *,
+ llvm::SmallVector<const MaterializeTemporaryExpr *, 1>>
+ ExtendedTemporaries;
const CFGBlock *CurrentBlock;
bool IsCMode = false;
};
diff --git a/clang/lib/Analysis/LifetimeSafety/FactsGenerator.cpp b/clang/lib/Analysis/LifetimeSafety/FactsGenerator.cpp
index 073c79972f2d3b..4fe5c5a18ae414 100644
--- a/clang/lib/Analysis/LifetimeSafety/FactsGenerator.cpp
+++ b/clang/lib/Analysis/LifetimeSafety/FactsGenerator.cpp
@@ -642,12 +642,16 @@ void FactsGenerator::VisitMaterializeTemporaryExpr(
OriginList *RValMTEList = MTEList->peelOuterOrigin();
flow(RValMTEList, SubExprList, /*Kill=*/true);
OriginID OuterMTEID = MTEList->getOuterOriginID();
- if (MTE->getStorageDuration() == SD_FullExpression) {
- // Issue a loan to MTE for the storage location represented by MTE.
- const Loan *L = createLoan(FactMgr, MTE);
- CurrentBlockFacts.push_back(
- FactMgr.createFact<IssueFact>(L->getID(), OuterMTEID));
- }
+ const Loan *L = createLoan(FactMgr, MTE);
+ CurrentBlockFacts.push_back(
+ FactMgr.createFact<IssueFact>(L->getID(), OuterMTEID));
+ // A temporary extended to static or thread storage duration does not expire
+ // within the function.
+ // Thread termination is not modeled; a thread-local value used after its
+ // thread exits is not diagnosed.
+ if (MTE->getStorageDuration() == SD_Automatic)
+ if (const ValueDecl *ExtendingDecl = MTE->getExtendingDecl())
+ ExtendedTemporaries[ExtendingDecl].push_back(MTE);
}
void FactsGenerator::VisitLambdaExpr(const LambdaExpr *LE) {
@@ -829,6 +833,7 @@ void FactsGenerator::handleLifetimeEnds(const CFGLifetimeEnds &LifetimeEnds) {
const VarDecl *LifetimeEndsVD = LifetimeEnds.getVarDecl();
if (!LifetimeEndsVD)
return;
+ SourceLocation EndLoc = LifetimeEnds.getTriggerStmt()->getEndLoc();
// A cleanup callback or a non-trivial destructor (other than an owner's) run
// at scope exit may read the borrows the variable holds.
QualType Ty = LifetimeEndsVD->getType();
@@ -840,9 +845,9 @@ void FactsGenerator::handleLifetimeEnds(const CFGLifetimeEnds &LifetimeEnds) {
if (HasCleanup || IsDestructorUse)
if (OriginList *List = getOriginsList(*LifetimeEndsVD))
CurrentBlockFacts.push_back(FactMgr.createFact<UseFact>(
- UseSite::scopeExit(
- LifetimeEnds.getTriggerStmt()->getEndLoc(), *LifetimeEndsVD,
- HasCleanup ? UseKind::Cleanup : UseKind::Destructor),
+ UseSite::scopeExit(EndLoc, *LifetimeEndsVD,
+ HasCleanup ? UseKind::Cleanup
+ : UseKind::Destructor),
List));
// Expire the origin when its variable's lifetime ends to ensure liveness
// doesn't persist through loop back-edges.
@@ -855,8 +860,12 @@ void FactsGenerator::handleLifetimeEnds(const CFGLifetimeEnds &LifetimeEnds) {
ExpiredOID = OID;
}
CurrentBlockFacts.push_back(FactMgr.createFact<ExpireFact>(
- AccessPath(LifetimeEndsVD), LifetimeEnds.getTriggerStmt()->getEndLoc(),
- ExpiredOID));
+ AccessPath(LifetimeEndsVD), EndLoc, ExpiredOID));
+ if (auto It = ExtendedTemporaries.find(LifetimeEndsVD);
+ It != ExtendedTemporaries.end())
+ for (const MaterializeTemporaryExpr *MTE : It->second)
+ CurrentBlockFacts.push_back(
+ FactMgr.createFact<ExpireFact>(AccessPath(MTE), EndLoc));
}
void FactsGenerator::handleFullExprCleanup(
diff --git a/clang/test/Sema/LifetimeSafety/lifetime-facts.cpp b/clang/test/Sema/LifetimeSafety/lifetime-facts.cpp
index f3e76374b34c88..302d3d59589379 100644
--- a/clang/test/Sema/LifetimeSafety/lifetime-facts.cpp
+++ b/clang/test/Sema/LifetimeSafety/lifetime-facts.cpp
@@ -294,3 +294,18 @@ void naming_a_variable_is_not_an_access(int *p) {
// CHECK: Use ([[O_DEREF]] (Expr: UnaryOperator, Type : int &))
// CHECK-NOT: Use ({{[0-9]+}} (Expr: DeclRefExpr
}
+
+struct TwoRefs {
+ const int &a;
+ const int &b;
+};
+
+// Every temporary extended by a variable expires with it.
+// CHECK-LABEL: Function: aggregate_extends_two_temporaries
+void aggregate_extends_two_temporaries() {
+ TwoRefs s{1, 2};
+// CHECK: Issue ({{[0-9]+}} (Path: MaterializeTemporaryExpr at [[MTE_A:0x[0-9a-f]+]])
+// CHECK: Issue ({{[0-9]+}} (Path: MaterializeTemporaryExpr at [[MTE_B:0x[0-9a-f]+]])
+// CHECK: Expire (MaterializeTemporaryExpr at [[MTE_A]])
+// CHECK: Expire (MaterializeTemporaryExpr at [[MTE_B]])
+}
diff --git a/clang/test/Sema/LifetimeSafety/safety.cpp b/clang/test/Sema/LifetimeSafety/safety.cpp
index 0f689546941bdc..1dcce2398d172b 100644
--- a/clang/test/Sema/LifetimeSafety/safety.cpp
+++ b/clang/test/Sema/LifetimeSafety/safety.cpp
@@ -2091,6 +2091,115 @@ const std::string& test_return() {
}
} // namespace reference_type_decl_ref_expr
+namespace lifetime_extended_temporary {
+std::string make();
+std::vector<std::string> makeStrings();
+struct Pair { std::string first; int second; };
+Pair makePair();
+
+void escapes_extending_scope() {
+ std::string_view v;
+ {
+ const std::string &r = make(); // expected-warning {{temporary object does not live long enough}}
+ v = r; // expected-note {{result of call to 'operator basic_string_view' aliases the storage of temporary object}}
+ } // expected-note {{temporary object is destroyed here}}
+ use(v); // expected-note {{later used here}}
+}
+
+void escapes_rvalue_ref() {
+ std::string_view v;
+ {
+ std::string &&r = make(); // expected-warning {{temporary object does not live long enough}}
+ v = r; // expected-note {{local variable 'r' aliases the storage of temporary object}}
+ } // expected-note {{temporary object is destroyed here}}
+ use(v); // expected-note {{later used here}}
+}
+
+void escapes_through_conditional(bool c) {
+ std::string live;
+ std::string_view v;
+ {
+ const auto &r =
+ c ? live : static_cast<const std::string &>(make()); // expected-warning {{temporary object does not live long enough}}
+ v = r; // expected-note {{result of call to 'operator basic_string_view' aliases the storage of temporary object}}
+ } // expected-note {{temporary object is destroyed here}}
+ use(v); // expected-note {{later used here}}
+}
+
+void escapes_two_extended_temporaries(bool c) {
+ std::string_view v;
+ {
+ const auto &r = c ? static_cast<const std::string &>(make()) // expected-warning {{temporary object does not live long enough}}
+ : static_cast<const std::string &>(make()); // expected-warning {{temporary object does not live long enough}}
+ v = r; // expected-note 2 {{result of call to 'operator basic_string_view' aliases the storage of temporary object}}
+ } // expected-note 2 {{temporary object is destroyed here}}
+ use(v); // expected-note 2 {{later used here}}
+}
+
+void escapes_across_iterations() {
+ std::string_view v = "init";
+ for (int i = 0; i < 3; ++i) {
+ use(v); // expected-note {{later used here}}
+ const std::string &r = make(); // expected-warning {{temporary object does not live long enough}}
+ v = r; // expected-note {{result of call to 'operator basic_string_view' aliases the storage of temporary object}}
+ } // expected-note {{temporary object is destroyed here}}
+}
+
+void escapes_nested_extension() {
+ std::string_view v;
+ {
+ const Pair &p = Pair{make(), 0}; // expected-warning {{temporary object does not live long enough}}
+ v = p.first; // expected-note {{result of call to 'operator basic_string_view' aliases the storage of temporary object}}
+ } // expected-note {{temporary object is destroyed here}}
+ use(v); // expected-note {{later used here}}
+}
+
+std::string_view returned() {
+ const std::string &r = make(); // expected-warning {{stack memory associated with temporary object is returned}}
+ return r; // expected-note {{result of call to 'operator basic_string_view' aliases the storage of temporary object}} \
+ // expected-note {{returned here}}
+}
+
+std::string_view returned_subobject() {
+ const std::string &r = makePair().first; // expected-warning {{stack memory associated with temporary object is returned}}
+ return r; // expected-note {{result of call to 'operator basic_string_view' aliases the storage of temporary object}} \
+ // expected-note {{returned here}}
+}
+
+const int *returned_scalar() {
+ const int &r = 42; // expected-warning {{stack memory associated with temporary object is returned}}
+ return &r; // expected-note {{returned here}}
+}
+
+void used_within_extending_scope(bool c) {
+ const std::string &r = make();
+ use(r);
+ for (int i = 0; i < 3; ++i) {
+ const std::string &s = c ? make() : make();
+ std::string_view v = s;
+ use(v);
+ }
+ const Pair &p = Pair{make(), 0};
+ std::string_view first = p.first;
+ use(first);
+ const auto &[a, b] = makePair();
+ std::string_view va = a;
+ use(va);
+ for (const std::string &s : makeStrings()) {
+ std::string_view v = s;
+ use(v);
+ }
+}
+
+std::string_view static_extension() {
+ static const std::string &r = make();
+ return r;
+}
+
+thread_local const std::string &tl = make();
+std::string_view thread_local_extension() { return tl; }
+} // namespace lifetime_extended_temporary
+
namespace field_access {
struct S {
diff --git a/clang/unittests/Analysis/LifetimeSafetyTest.cpp b/clang/unittests/Analysis/LifetimeSafetyTest.cpp
index 6d118d9235f574..2c39cd5b52d2fc 100644
--- a/clang/unittests/Analysis/LifetimeSafetyTest.cpp
+++ b/clang/unittests/Analysis/LifetimeSafetyTest.cpp
@@ -1207,7 +1207,7 @@ TEST_F(LifetimeAnalysisTest, LifetimeboundTemplateFunctionReturnVal) {
EXPECT_THAT(Origin("v2"), HasLoansTo({"b"}, "p2"));
EXPECT_THAT(Origin("v3"), HasLoansTo({"v2"}, "p2"));
// View temporary on RHS is lifetime-extended.
- EXPECT_THAT(Origin("v4"), HasLoansTo({}, "p2"));
+ EXPECT_THAT(Origin("v4"), HasLoanToATemporary("p2"));
}
TEST_F(LifetimeAnalysisTest, LifetimeboundConversionOperator) {
More information about the cfe-commits
mailing list