[clang] [Clang] Implement P2718R0 "Lifetime extension in range-based for loops" (PR #76361)

via cfe-commits cfe-commits at lists.llvm.org
Wed Jan 17 23:53:41 PST 2024


================
@@ -2312,12 +2312,31 @@ Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
     bool IsForRangeLoop = false;
     if (TryConsumeToken(tok::colon, FRI->ColonLoc)) {
       IsForRangeLoop = true;
+      EnterExpressionEvaluationContext ForRangeInitContext(
+          Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated,
+          /*LambdaContextDecl=*/nullptr,
+          Sema::ExpressionEvaluationContextRecord::EK_Other,
+          getLangOpts().CPlusPlus23);
+
+      // P2718R0 - Lifetime extension in range-based for loops.
+      if (getLangOpts().CPlusPlus23) {
+        auto &LastRecord = Actions.ExprEvalContexts.back();
+        LastRecord.IsInLifetimeExtendingContext = true;
+
+        // Materialize non-`cv void` prvalue temporaries in discarded
+        // expressions. These materialized temporaries may be lifetime-extented.
+        LastRecord.MaterializePRValueInDiscardedExpression = true;
+      }
+
       if (getLangOpts().OpenMP)
         Actions.startOpenMPCXXRangeFor();
       if (Tok.is(tok::l_brace))
         FRI->RangeExpr = ParseBraceInitializer();
       else
         FRI->RangeExpr = ParseExpression();
+      if (getLangOpts().CPlusPlus23)
----------------
cor3ntin wrote:

`ForRangeLifetimeExtendTemps` is going to be filled by `ParseExpression`/ I wonder if we should do that unconditionally though.
and replace the if with `assert(getLangOpts().CPlusPlus23 || Actions.ExprEvalContexts.back().ForRangeLifetimeExtendTemps.empty())`

https://github.com/llvm/llvm-project/pull/76361


More information about the cfe-commits mailing list