Skip to content

[Sema] Fix lifetime extension for temporaries in range-based for loops in C++23 #145164

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

mrcvtl
Copy link

@mrcvtl mrcvtl commented Jun 21, 2025

C++23 mandates that temporaries used in range-based for loops are lifetime-extended
to cover the full loop. This patch adds a check for loop variables and compiler-
generated __range bindings to apply the correct extension.

Includes test cases based on examples from CWG900/P2644R1.

Fixes #109793

Copy link

Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this page.

If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using @ followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers.

If you have further questions, they may be answered by the LLVM GitHub User Guide.

You can also ask questions in a comment on this PR, on the LLVM Discord or on the forums.

@frederick-vs-ja

This comment was marked as resolved.

@mrcvtl
Copy link
Author

mrcvtl commented Jun 21, 2025

Could you associate this PR with the issue to fix, if any?

Done!

@mrcvtl
Copy link
Author

mrcvtl commented Jun 22, 2025

A couple of quick notes:

  • This is my first LLVM PR, so if there are any issues with code style or conventions, please let me know!
  • I'm not entirely satisfied with the VD->getName().starts_with("__range") check, but it was the most reliable approach I found. Walking up the AST from the node didn’t seem feasible (likely due to optimizations?) and I noticed that pattern here:
    const auto DepthStr = std::to_string(S->getDepth() / 2);
    SourceLocation RangeLoc = Range->getBeginLoc();
    VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
    Context.getAutoRRefDeductType(),
    std::string("__range") + DepthStr);

@mrcvtl mrcvtl marked this pull request as ready for review June 22, 2025 09:53
@llvmbot llvmbot added clang Clang issues not falling into any other category clang:frontend Language frontend issues, e.g. anything involving "Sema" labels Jun 22, 2025
@llvmbot
Copy link
Member

llvmbot commented Jun 22, 2025

@llvm/pr-subscribers-clang-modules

@llvm/pr-subscribers-clang

Author: Marco Vitale (mrcvtl)

Changes

C++23 mandates that temporaries used in range-based for loops are lifetime-extended
to cover the full loop. This patch adds a check for loop variables and compiler-
generated __range bindings to apply the correct extension.

Includes test cases based on examples from CWG900/P2644R1.

Fixes #109793


Full diff: https://github.com/llvm/llvm-project/pull/145164.diff

2 Files Affected:

  • (modified) clang/lib/Sema/CheckExprLifetime.cpp (+28)
  • (added) clang/test/SemaCXX/range-for-lifetime-cxx23.cpp (+79)
diff --git a/clang/lib/Sema/CheckExprLifetime.cpp b/clang/lib/Sema/CheckExprLifetime.cpp
index 060ba31660556..0434aa0c29c26 100644
--- a/clang/lib/Sema/CheckExprLifetime.cpp
+++ b/clang/lib/Sema/CheckExprLifetime.cpp
@@ -57,6 +57,31 @@ enum LifetimeKind {
 };
 using LifetimeResult =
     llvm::PointerIntPair<const InitializedEntity *, 3, LifetimeKind>;
+
+/// Returns true if the given entity is part of a range-based for loop and
+/// should trigger lifetime extension under C++23 rules.
+///
+/// This handles both explicit range loop variables and internal compiler-
+/// generated variables like `__range1`.
+static bool
+isRangeBasedForLoopVariable(const Sema &SemaRef,
+                            const InitializedEntity *ExtendingEntity) {
+  if (!SemaRef.getLangOpts().CPlusPlus23)
+    return false;
+
+  const Decl *EntityDecl = ExtendingEntity->getDecl();
+  if (!EntityDecl)
+    return false;
+
+  if (const auto *VD = dyn_cast<VarDecl>(EntityDecl)) {
+    if (VD->isCXXForRangeDecl() || VD->getName().starts_with("__range")) {
+      return true;
+    }
+  }
+
+  return false;
+}
+
 } // namespace
 
 /// Determine the declaration which an initialized entity ultimately refers to,
@@ -1341,6 +1366,9 @@ checkExprLifetimeImpl(Sema &SemaRef, const InitializedEntity *InitEntity,
       }
 
       if (IsGslPtrValueFromGslTempOwner && DiagLoc.isValid()) {
+        if (isRangeBasedForLoopVariable(SemaRef, ExtendingEntity))
+          return true;
+
         SemaRef.Diag(DiagLoc, diag::warn_dangling_lifetime_pointer)
             << DiagRange;
         return false;
diff --git a/clang/test/SemaCXX/range-for-lifetime-cxx23.cpp b/clang/test/SemaCXX/range-for-lifetime-cxx23.cpp
new file mode 100644
index 0000000000000..bb6e06ec4517c
--- /dev/null
+++ b/clang/test/SemaCXX/range-for-lifetime-cxx23.cpp
@@ -0,0 +1,79 @@
+// RUN: %clangxx -std=c++23 -fsyntax-only -Xclang -verify %s
+
+#include <string>
+#include <vector>
+#include <map>
+#include <tuple>
+#include <optional>
+#include <variant>
+#include <array>
+#include <span>
+
+static std::vector<std::string> getVector() {
+  return {"first", "second", "third"};
+}
+
+static std::map<std::string, std::vector<int>> getMap() {
+  return {{"key", {1, 2, 3}}};
+}
+
+static std::tuple<std::vector<double>> getTuple() {
+  return std::make_tuple(std::vector<double>{3.14, 2.71});
+}
+
+static std::optional<std::vector<char>> getOptionalColl() {
+  return std::vector<char>{'x', 'y', 'z'};
+}
+
+static std::variant<std::string, int> getVariant() {
+  return std::string("variant");
+}
+
+static const std::array<int, 4>& arrOfConst() {
+  static const std::array<int, 4> arr = {10, 20, 30, 40};
+  return arr;
+}
+
+static void testGetVectorSubscript() {
+  for (auto e : getVector()[0]) {
+    (void)e;
+  }
+}
+
+static void testGetMapSubscript() {
+  for (auto valueElem : getMap()["key"]) {
+    (void)valueElem;
+  }
+}
+
+static void testGetTuple() {
+  for (auto e : std::get<0>(getTuple())) {
+    (void)e;
+  }
+}
+
+static void testOptionalValue() {
+  for (auto e : getOptionalColl().value()) {
+    (void)e;
+  }
+}
+
+static void testVariantGetString() {
+  for (char c : std::get<std::string>(getVariant())) {
+    (void)c;
+  }
+}
+
+static void testSpanLastFromConstArray() {
+  for (auto s : std::span{arrOfConst()}.last(2)) {
+    (void)s;
+  }
+}
+
+static void testSpanFromVectorPtr() {
+  for (auto e : std::span(getVector().data(), 2)) {
+    (void)e;
+  }
+}
+
+// expected-no-diagnostics

Copy link
Contributor

@zwuis zwuis left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for the patch!

Please add a release note in clang/docs/ReleaseNotes.rst so that users can know the improvement.

/// This handles both explicit range loop variables and internal compiler-
/// generated variables like `__range1`.
static bool
isRangeBasedForLoopVariable(const Sema &SemaRef,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This parameter type can be const LangOptions &.

@@ -0,0 +1,79 @@
// RUN: %clangxx -std=c++23 -fsyntax-only -Xclang -verify %s
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use %clang_cc1 for frontend tests.

-Xclang can be removed.

Comment on lines 3 to 10
#include <string>
#include <vector>
#include <map>
#include <tuple>
#include <optional>
#include <variant>
#include <array>
#include <span>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do not include files outside test folders. You can search namespace std to see how other test files handle this case.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can construct some simple fake std dependencies.
Eg.

namespace std {
  typedef decltype(sizeof(int)) size_t;
  template <class E>
  struct initializer_list {
    const E *begin;
    size_t   size;
    initializer_list() : begin(nullptr), size(0) {}
  };

  template <typename E>
  struct list {
    list() {}
    ~list() {}
    E *begin();
    E *end();
    const E *begin() const;
    const E *end() const;
  };

  template <typename E>
  struct vector {
    vector() {}
    vector(std::initializer_list<E>) {}
    ~vector() {}
    E *begin();
    E *end();
    const E *begin() const;
    const E *end() const;
  };
} // namespace std

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have a more simple reproducer:

using size_t = decltype(sizeof(void *));

namespace std {
template <typename T> struct vector {
  T &operator[](size_t I);
};

struct string {
  const char *begin();
  const char *end();
};

} // namespace std

extern "C" int printf(const char *, ...);

std::vector<std::string> getData();

void foo() {
  for (auto c : getData()[0]) {
    printf("%c\n", c);
  }
}

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yup, my initial test was actually very similar (even if I used the stdlib), but I wanted to try out all the scenarios mentioned in the paper that you implemented. Since that doesn’t really make much sense, I’ll stick with this approach, thanks!

@zwuis zwuis requested review from shafik and hokein June 22, 2025 11:45
@yronglin
Copy link
Contributor

A couple of quick notes:

  • This is my first LLVM PR, so if there are any issues with code style or conventions, please let me know!
  • I'm not entirely satisfied with the VD->getName().starts_with("__range") check, but it was the most reliable approach I found. Walking up the AST from the node didn’t seem feasible (likely due to optimizations?) and I noticed that pattern here:
    const auto DepthStr = std::to_string(S->getDepth() / 2);
    SourceLocation RangeLoc = Range->getBeginLoc();
    VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
    Context.getAutoRRefDeductType(),
    std::string("__range") + DepthStr);

Thanks for you fix!
Maybe we can use isInLifetimeExtendingContext() instead of check the __range variable name. We usually get into an LifetimeExtendingContex in Sema. FYI, the initial PR is #76361.

@mrcvtl
Copy link
Author

mrcvtl commented Jun 24, 2025

I’ve taken some time to better understand the code and think through the solution.

I tried using isInLifetimeExtendingContext(), but it still returns false, and I believe I now understand why. In your PR, the flag is set here:

if (getLangOpts().CPlusPlus23) {
auto &LastRecord = Actions.currentEvaluationContext();
LastRecord.InLifetimeExtendingContext = true;
LastRecord.RebuildDefaultArgOrDefaultInit = true;
}

However, the warning is actually triggered starting from this location:

return Actions.ConvertDeclToDeclGroup(TheDecl);

An alternative approach would be to apply your logic and set again the flag in here:

if (ForRangeInfo.ParsedForRangeDecl()) {
ForRangeStmt = Actions.ActOnCXXForRangeStmt(
getCurScope(), ForLoc, CoawaitLoc, FirstPart.get(),
ForRangeInfo.LoopVar.get(), ForRangeInfo.ColonLoc,
ForRangeInfo.RangeExpr.get(), T.getCloseLocation(), Sema::BFRK_Build,
ForRangeInfo.LifetimeExtendTemps);

Maybe we could act on ForRangeInfo.LifetimeExtendTemps.back(), or even directly on Actions.currentEvaluationContext();. If that works, we might be able to rely solely on isInLifetimeExtendingContext() and remove the need for isRangeBasedForLoopVariable altogether.

What do you think? I'm absolutely open to every approach (the cleaner, the better!).

@yronglin
Copy link
Contributor

I’ve taken some time to better understand the code and think through the solution.

I tried using isInLifetimeExtendingContext(), but it still returns false, and I believe I now understand why. In your PR, the flag is set here:

if (getLangOpts().CPlusPlus23) {
auto &LastRecord = Actions.currentEvaluationContext();
LastRecord.InLifetimeExtendingContext = true;
LastRecord.RebuildDefaultArgOrDefaultInit = true;
}

However, the warning is actually triggered starting from this location:

return Actions.ConvertDeclToDeclGroup(TheDecl);

An alternative approach would be to apply your logic and set again the flag in here:

if (ForRangeInfo.ParsedForRangeDecl()) {
ForRangeStmt = Actions.ActOnCXXForRangeStmt(
getCurScope(), ForLoc, CoawaitLoc, FirstPart.get(),
ForRangeInfo.LoopVar.get(), ForRangeInfo.ColonLoc,
ForRangeInfo.RangeExpr.get(), T.getCloseLocation(), Sema::BFRK_Build,
ForRangeInfo.LifetimeExtendTemps);

Maybe we could act on ForRangeInfo.LifetimeExtendTemps.back(), or even directly on Actions.currentEvaluationContext();. If that works, we might be able to rely solely on isInLifetimeExtendingContext() and remove the need for isRangeBasedForLoopVariable altogether.

What do you think? I'm absolutely open to every approach (the cleaner, the better!).

IMO, we have 2 options:

  1. Add a flag variable into ExpressionEvaluationContextRecord. Represent that we are initializing the for-range __range variable.
    Eg.
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 9397546c8fc5..c639a4b4af58 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -6786,6 +6786,9 @@ public:
     /// Whether we should rebuild CXXDefaultArgExpr and CXXDefaultInitExpr.
     bool RebuildDefaultArgOrDefaultInit = false;
 
+    /// Whether we are initializing a C++ for-range implicit variable '__range'.
+    bool InitCXXForRangeVar = false;
+
     // When evaluating immediate functions in the initializer of a default
     // argument or default member initializer, this is the declaration whose
     // default initializer is being evaluated and the location of the call
diff --git a/clang/lib/Sema/CheckExprLifetime.cpp b/clang/lib/Sema/CheckExprLifetime.cpp
index 060ba3166055..150e27f8acf7 100644
--- a/clang/lib/Sema/CheckExprLifetime.cpp
+++ b/clang/lib/Sema/CheckExprLifetime.cpp
@@ -1341,6 +1341,8 @@ checkExprLifetimeImpl(Sema &SemaRef, const InitializedEntity *InitEntity,
       }
 
       if (IsGslPtrValueFromGslTempOwner && DiagLoc.isValid()) {
+        if (SemaRef.currentEvaluationContext().InitCXXForRangeVar)
+          return false;
         SemaRef.Diag(DiagLoc, diag::warn_dangling_lifetime_pointer)
             << DiagRange;
         return false;
diff --git a/clang/lib/Sema/SemaStmt.cpp b/clang/lib/Sema/SemaStmt.cpp
index 923a9e81fbd6..da97d34854ac 100644
--- a/clang/lib/Sema/SemaStmt.cpp
+++ b/clang/lib/Sema/SemaStmt.cpp
@@ -2374,6 +2374,13 @@ static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
       SemaRef.ObjC().inferObjCARCLifetime(Decl))
     Decl->setInvalidDecl();
 
+  // EnterExpressionEvaluationContext ForRangeInitContext(
+  //     SemaRef, Sema::ExpressionEvaluationContext::PotentiallyEvaluated,
+  //     /*LambdaContextDecl=*/nullptr,
+  //     Sema::ExpressionEvaluationContextRecord::EK_Other,
+  //     SemaRef.getLangOpts().CPlusPlus23);
+  if (SemaRef.getLangOpts().CPlusPlus23)
+    SemaRef.currentEvaluationContext().InitCXXForRangeVar = true;
   SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false);
   SemaRef.FinalizeDeclaration(Decl);
   SemaRef.CurContext->addHiddenDecl(Decl);
  1. Introduce a bitfields into clang::VarDecl::NonParmVarDeclBitfields, like CXXForRangeDecl(Eg. CXXForRangeImplicitVar)

CC @cor3ntin

@yronglin yronglin requested a review from cor3ntin June 25, 2025 17:37
Copy link
Collaborator

@shafik shafik left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As a previous comment noted, this needs a release note but I think the summary should also mention that this fixes the warning diagnostic from -Wdangling-gsl. Maybe worth a comment in the test explaining these are verifying we don't trigger a diagnostic from -Wdangling-gsl

@mrcvtl
Copy link
Author

mrcvtl commented Jun 26, 2025

IMO, we have 2 options:

  1. Add a flag variable into ExpressionEvaluationContextRecord. Represent that we are initializing the for-range __range variable.
    Eg.
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 9397546c8fc5..c639a4b4af58 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -6786,6 +6786,9 @@ public:
     /// Whether we should rebuild CXXDefaultArgExpr and CXXDefaultInitExpr.
     bool RebuildDefaultArgOrDefaultInit = false;
 
+    /// Whether we are initializing a C++ for-range implicit variable '__range'.
+    bool InitCXXForRangeVar = false;
+
     // When evaluating immediate functions in the initializer of a default
     // argument or default member initializer, this is the declaration whose
     // default initializer is being evaluated and the location of the call
diff --git a/clang/lib/Sema/CheckExprLifetime.cpp b/clang/lib/Sema/CheckExprLifetime.cpp
index 060ba3166055..150e27f8acf7 100644
--- a/clang/lib/Sema/CheckExprLifetime.cpp
+++ b/clang/lib/Sema/CheckExprLifetime.cpp
@@ -1341,6 +1341,8 @@ checkExprLifetimeImpl(Sema &SemaRef, const InitializedEntity *InitEntity,
       }
 
       if (IsGslPtrValueFromGslTempOwner && DiagLoc.isValid()) {
+        if (SemaRef.currentEvaluationContext().InitCXXForRangeVar)
+          return false;
         SemaRef.Diag(DiagLoc, diag::warn_dangling_lifetime_pointer)
             << DiagRange;
         return false;
diff --git a/clang/lib/Sema/SemaStmt.cpp b/clang/lib/Sema/SemaStmt.cpp
index 923a9e81fbd6..da97d34854ac 100644
--- a/clang/lib/Sema/SemaStmt.cpp
+++ b/clang/lib/Sema/SemaStmt.cpp
@@ -2374,6 +2374,13 @@ static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
       SemaRef.ObjC().inferObjCARCLifetime(Decl))
     Decl->setInvalidDecl();
 
+  // EnterExpressionEvaluationContext ForRangeInitContext(
+  //     SemaRef, Sema::ExpressionEvaluationContext::PotentiallyEvaluated,
+  //     /*LambdaContextDecl=*/nullptr,
+  //     Sema::ExpressionEvaluationContextRecord::EK_Other,
+  //     SemaRef.getLangOpts().CPlusPlus23);
+  if (SemaRef.getLangOpts().CPlusPlus23)
+    SemaRef.currentEvaluationContext().InitCXXForRangeVar = true;
   SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false);
   SemaRef.FinalizeDeclaration(Decl);
   SemaRef.CurContext->addHiddenDecl(Decl);
  1. Introduce a bitfields into clang::VarDecl::NonParmVarDeclBitfields, like CXXForRangeDecl(Eg. CXXForRangeImplicitVar)

CC @cor3ntin

I like option one! Maybe a stupid question, but why can’t we use InLifetimeExtendingContext flag here? It feels like it’s meant to capture the same kind of situation. Is there a subtle difference I’m missing?

I updated (locally) the PR to address the other feedbacks and I will push it to be reviewed when I have the green light to use option 1!

@yronglin
Copy link
Contributor

but why can’t we use InLifetimeExtendingContext flag here?
Is there a subtle difference I’m missing?

This flag will tiger subroutines to collect MaterializedTemporaryExpr and rebuild default init/arg。 All we need to know here is that ExtendingDecl is a C++ __range var in for-range-loop, so I think we should introduce a new flag in VarDecl. We may need to also modify handling of VarDecl in ASTWriter and ASTReader to ensure that the AST serialization is correct. WDYT?

@llvmbot llvmbot added the clang:modules C++20 modules and Clang Header Modules label Jun 28, 2025
@mrcvtl
Copy link
Author

mrcvtl commented Jun 28, 2025

but why can’t we use InLifetimeExtendingContext flag here?
Is there a subtle difference I’m missing?

This flag will tiger subroutines to collect MaterializedTemporaryExpr and rebuild default init/arg。 All we need to know here is that ExtendingDecl is a C++ __range var in for-range-loop, so I think we should introduce a new flag in VarDecl. We may need to also modify handling of VarDecl in ASTWriter and ASTReader to ensure that the AST serialization is correct. WDYT?

Agreed.

My last commit should implement this. Let me know if something is wrong!

Edit: I pushed again because I messed up with the branches, sorry!

…s in C++23

C++23 mandates that temporaries used in range-based for loops are lifetime-extended
to cover the full loop. This patch adds a check for loop variables and compiler-
generated `__range` bindings to apply the correct extension.

Includes test cases based on examples from CWG900/P2644R1.
@mrcvtl
Copy link
Author

mrcvtl commented Jun 28, 2025

Old clang tidy test failing seems flaky, locally it pass correctly. If it continue to fail I can rebase on upstream.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
clang:frontend Language frontend issues, e.g. anything involving "Sema" clang:modules C++20 modules and Clang Header Modules clang Clang issues not falling into any other category
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Unnecessary warning for the fixed range-based for loop in C++23
6 participants