https://github.com/nickdesaulniers created 
https://github.com/llvm/llvm-project/pull/238919

Previously, C local variables and block-scoped compound literals suppressed
lifetime markers whenever any label had already been seen in the current
lexical scope (`hasLabelBeenSeenInCurrentScope()`). That heuristic was both
overly conservative (suppressing lifetime markers after labels only targeted by
forward jumps, unused labels, or labels confined to inner statement
expressions) and missed forward jumps over compound literals whose
`llvm.lifetime.end` cleanup runs at enclosing block exit.

Extend `VarBypassDetector` to track enclosing `CompoundStmt` block scopes and
C block-scoped `CompoundLiteralExpr`s (including inside variably-modified types,
`switch` conditions, `do-while` conditions, and attributed statements), detect
both forward jumps over compound literals and backward jumps crossing C local
variables or compound literals within their enclosing lexical block, and run
`Bypasses.Init()` from `CodeGenFunction::StartFunction()` so non-`FunctionDecl`
bodies (such as `CapturedDecl`, blocks, and ObjC methods) are analyzed too.
Remove the now-unused `hasLabelBeenSeenInCurrentScope()` helper.

Link: https://github.com/llvm/llvm-project/pull/219045
Assisted-by: Gemini


>From 07ac1ff8705ec1b46bffe8ef4f87024dd00f3edf Mon Sep 17 00:00:00 2001
From: Nick Desaulniers <[email protected]>
Date: Tue, 3 Nov 2026 13:46:20 -0800
Subject: [PATCH] [clang][CodeGen] Detect backward jumps for C lifetime markers

Previously, C local variables and block-scoped compound literals suppressed
lifetime markers whenever any label had already been seen in the current
lexical scope (`hasLabelBeenSeenInCurrentScope()`). That heuristic was both
overly conservative (suppressing lifetime markers after labels only targeted by
forward jumps, unused labels, or labels confined to inner statement
expressions) and missed forward jumps over compound literals whose
`llvm.lifetime.end` cleanup runs at enclosing block exit.

Extend `VarBypassDetector` to track enclosing `CompoundStmt` block scopes and
C block-scoped `CompoundLiteralExpr`s (including inside variably-modified types,
`switch` conditions, `do-while` conditions, and attributed statements), detect
both forward jumps over compound literals and backward jumps crossing C local
variables or compound literals within their enclosing lexical block, and run
`Bypasses.Init()` from `CodeGenFunction::StartFunction()` so non-`FunctionDecl`
bodies (such as `CapturedDecl`, blocks, and ObjC methods) are analyzed too.
Remove the now-unused `hasLabelBeenSeenInCurrentScope()` helper.

Link: https://github.com/llvm/llvm-project/pull/219045
Assisted-by: Gemini
---
 clang/lib/CodeGen/CGDecl.cpp                  |   2 +-
 clang/lib/CodeGen/CGExpr.cpp                  |   9 +-
 clang/lib/CodeGen/CodeGenFunction.cpp         |  27 +-
 clang/lib/CodeGen/CodeGenFunction.h           |   9 -
 clang/lib/CodeGen/VarBypassDetector.cpp       | 232 ++++++++++++++++--
 clang/lib/CodeGen/VarBypassDetector.h         |  54 ++--
 .../test/CodeGen/compound-literal-lifetime.c  | 118 ++++++++-
 clang/test/CodeGen/lifetime2.c                |  66 +++++
 8 files changed, 446 insertions(+), 71 deletions(-)

diff --git a/clang/lib/CodeGen/CGDecl.cpp b/clang/lib/CodeGen/CGDecl.cpp
index b425392ebbe41c..5a107e9e160b1e 100644
--- a/clang/lib/CodeGen/CGDecl.cpp
+++ b/clang/lib/CodeGen/CGDecl.cpp
@@ -1637,7 +1637,7 @@ CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
         // completely in this case is unnecessarily pessimistic, but again, 
this
         // is rare.
         if (!Bypasses.IsBypassed(&D) &&
-            !(!getLangOpts().CPlusPlus && hasLabelBeenSeenInCurrentScope())) {
+            !(!getLangOpts().CPlusPlus && Bypasses.IsBackwardBypassed(&D))) {
           emission.UseLifetimeMarkers =
               EmitLifetimeStart(AllocaAddr.getPointer());
         }
diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index ae5f4e723f5129..1e0817fbbe7018 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -6160,12 +6160,9 @@ LValue CodeGenFunction::EmitCompoundLiteralLValue(const 
CompoundLiteralExpr *E){
   const Expr *InitExpr = E->getInitializer();
   LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl);
 
-  if (!getLangOpts().CPlusPlus) {
-    if (HaveInsertPoint() && !hasLabelBeenSeenInCurrentScope() &&
-        EmitLifetimeStart(DeclPtr.getBasePointer()))
-      pushCleanupAfterFullExpr<CallLifetimeEnd>(NormalEHLifetimeMarker,
-                                                DeclPtr);
-  }
+  if (!getLangOpts().CPlusPlus && HaveInsertPoint() &&
+      !Bypasses.IsBypassed(E) && EmitLifetimeStart(DeclPtr.getBasePointer()))
+    pushCleanupAfterFullExpr<CallLifetimeEnd>(NormalEHLifetimeMarker, DeclPtr);
 
   EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
                    /*Init*/ true);
diff --git a/clang/lib/CodeGen/CodeGenFunction.cpp 
b/clang/lib/CodeGen/CodeGenFunction.cpp
index 33434526d86325..32b543540068c7 100644
--- a/clang/lib/CodeGen/CodeGenFunction.cpp
+++ b/clang/lib/CodeGen/CodeGenFunction.cpp
@@ -759,6 +759,19 @@ void CodeGenFunction::StartFunction(GlobalDecl GD, 
QualType RetTy,
   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
   if (FD && FD->usesSEHTry())
     CurSEHParent = GD;
+  if (const Stmt *Body = D ? D->getBody() : nullptr) {
+    // Coroutines always emit lifetime markers.
+    if (isa<CoroutineBodyStmt>(Body))
+      ShouldEmitLifetimeMarkers = true;
+
+    // Detect jumps that invalidate lifetime markers or bypass auto-var-init.
+    bool NeedsBypassDetection =
+        ShouldEmitLifetimeMarkers ||
+        (CGM.getLangOpts().getTrivialAutoVarInit() !=
+         LangOptions::TrivialAutoVarInitKind::Uninitialized);
+    if (NeedsBypassDetection)
+      Bypasses.Init(CGM, Body);
+  }
   CurFuncDecl = (D ? D->getNonClosureContext() : nullptr);
   FnRetTy = RetTy;
   CurFn = Fn;
@@ -1576,20 +1589,6 @@ void CodeGenFunction::GenerateCode(GlobalDecl GD, 
llvm::Function *Fn,
 
   Stmt *Body = FD->getBody();
 
-  if (Body) {
-    // Coroutines always emit lifetime markers.
-    if (isa<CoroutineBodyStmt>(Body))
-      ShouldEmitLifetimeMarkers = true;
-
-    // Detect jumps that invalidate lifetime markers or bypass auto-var-init.
-    bool NeedsBypassDetection =
-        ShouldEmitLifetimeMarkers ||
-        (CGM.getLangOpts().getTrivialAutoVarInit() !=
-         LangOptions::TrivialAutoVarInitKind::Uninitialized);
-    if (NeedsBypassDetection)
-      Bypasses.Init(CGM, Body);
-  }
-
   // Emit the standard function prologue.
   StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
 
diff --git a/clang/lib/CodeGen/CodeGenFunction.h 
b/clang/lib/CodeGen/CodeGenFunction.h
index 22f72ead623700..c521075a27cef5 100644
--- a/clang/lib/CodeGen/CodeGenFunction.h
+++ b/clang/lib/CodeGen/CodeGenFunction.h
@@ -435,13 +435,6 @@ class CodeGenFunction : public CodeGenTypeCache {
   /// result expression.
   const Expr *RetExpr = nullptr;
 
-  /// Return true if a label was seen in the current scope.
-  bool hasLabelBeenSeenInCurrentScope() const {
-    if (CurLexicalScope)
-      return CurLexicalScope->hasLabels();
-    return !LabelMap.empty();
-  }
-
   /// AllocaInsertPoint - This is an instruction in the entry block before 
which
   /// we prefer to insert allocas.
   llvm::AssertingVH<llvm::Instruction> AllocaInsertPt;
@@ -1168,8 +1161,6 @@ class CodeGenFunction : public CodeGenTypeCache {
         rescopeLabels();
     }
 
-    bool hasLabels() const { return !Labels.empty(); }
-
     void rescopeLabels();
   };
 
diff --git a/clang/lib/CodeGen/VarBypassDetector.cpp 
b/clang/lib/CodeGen/VarBypassDetector.cpp
index 5f3df7f245d3db..717da002549dae 100644
--- a/clang/lib/CodeGen/VarBypassDetector.cpp
+++ b/clang/lib/CodeGen/VarBypassDetector.cpp
@@ -9,9 +9,12 @@
 #include "VarBypassDetector.h"
 
 #include "CodeGenModule.h"
+#include "clang/AST/ASTContext.h"
 #include "clang/AST/Decl.h"
 #include "clang/AST/Expr.h"
 #include "clang/AST/Stmt.h"
+#include "clang/AST/Type.h"
+#include "llvm/ADT/ScopeExit.h"
 
 using namespace clang;
 using namespace CodeGen;
@@ -50,15 +53,59 @@ void VarBypassDetector::Init(CodeGenModule &CGM, const Stmt 
*Body) {
   FromScopes.clear();
   ToScopes.clear();
   Bypasses.clear();
+  BackwardBypassedVars.clear();
+  BypassedCLs.clear();
   BypassedVarsAtSource.clear();
-  Scopes = {{~0U, nullptr}};
+  Scopes = {{~0U, 0, nullptr}};
+  CurEnclosingBlockScope = 0;
   AlwaysBypassed = false;
+  Initialized = true;
   if (!hasJumpStmts(Body))
     return;
   unsigned ParentScope = 0;
   AlwaysBypassed = !BuildScopeInformation(CGM, Body, ParentScope);
   if (!AlwaysBypassed)
-    Detect();
+    Detect(CGM.getLangOpts().CPlusPlus);
+}
+
+bool VarBypassDetector::BuildScopeInformation(CodeGenModule &CGM, QualType Ty,
+                                              unsigned &ParentScope) {
+  while (!Ty.isNull() && Ty->isVariablyModifiedType()) {
+    const Type *T = Ty.getTypePtr();
+    if (isa<TypedefType, DecltypeType, AutoType,
+            DeducedTemplateSpecializationType, PackIndexingType>(T))
+      return true;
+    if (const auto *TOE = dyn_cast<TypeOfExprType>(T))
+      return BuildScopeInformation(CGM, TOE->getUnderlyingExpr(), ParentScope);
+    if (const auto *VAT = dyn_cast<VariableArrayType>(T)) {
+      if (const Expr *Size = VAT->getSizeExpr())
+        if (!BuildScopeInformation(CGM, Size, ParentScope))
+          return false;
+      Ty = VAT->getElementType();
+      continue;
+    }
+    if (const auto *AT = dyn_cast<ArrayType>(T)) {
+      Ty = AT->getElementType();
+      continue;
+    }
+    if (QualType Pointee = T->getPointeeType(); !Pointee.isNull()) {
+      Ty = Pointee;
+      continue;
+    }
+    if (const auto *FT = dyn_cast<FunctionType>(T)) {
+      if (const auto *FPT = dyn_cast<FunctionProtoType>(FT))
+        for (QualType ParamTy : FPT->param_types())
+          if (!BuildScopeInformation(CGM, ParamTy, ParentScope))
+            return false;
+      Ty = FT->getReturnType();
+      continue;
+    }
+    QualType Desugared = Ty.getSingleStepDesugaredType(CGM.getContext());
+    if (Desugared == Ty)
+      break;
+    Ty = Desugared;
+  }
+  return true;
 }
 
 /// Build scope information for a declaration that is part of a DeclStmt.
@@ -66,19 +113,50 @@ void VarBypassDetector::Init(CodeGenModule &CGM, const 
Stmt *Body) {
 /// which vars are being bypassed.
 bool VarBypassDetector::BuildScopeInformation(CodeGenModule &CGM, const Decl 
*D,
                                               unsigned &ParentScope) {
+  if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
+    return BuildScopeInformation(CGM, TD->getUnderlyingType(), ParentScope);
+
   const VarDecl *VD = dyn_cast<VarDecl>(D);
-  if (VD && VD->hasLocalStorage()) {
-    Scopes.push_back({ParentScope, VD});
+  if (!VD)
+    return true;
+
+  if (VD->hasLocalStorage()) {
+    Scopes.push_back({ParentScope, CurEnclosingBlockScope, VD});
     ParentScope = Scopes.size() - 1;
+    if (!BuildScopeInformation(CGM, VD->getType(), ParentScope))
+      return false;
   }
 
-  if (const VarDecl *VD = dyn_cast<VarDecl>(D))
+  if (VD->hasLocalStorage() || CGM.getLangOpts().CPlusPlus)
     if (const Expr *Init = VD->getInit())
       return BuildScopeInformation(CGM, Init, ParentScope);
 
   return true;
 }
 
+/// Returns true if SubStmt is a non-compound child statement of Parent that
+/// introduces its own lexical cleanup scope (e.g. the body or branch of a
+/// loop or conditional statement).
+static bool needsChildCleanupScope(const Stmt *Parent, const Stmt *SubStmt) {
+  if (isa<CompoundStmt>(SubStmt))
+    return false;
+
+  switch (Parent->getStmtClass()) {
+  case Stmt::IfStmtClass: {
+    const auto *IS = cast<IfStmt>(Parent);
+    return SubStmt == IS->getThen() || SubStmt == IS->getElse();
+  }
+  case Stmt::WhileStmtClass:
+    return SubStmt == cast<WhileStmt>(Parent)->getBody();
+  case Stmt::DoStmtClass:
+    return SubStmt == cast<DoStmt>(Parent)->getBody();
+  case Stmt::ForStmtClass:
+    return SubStmt == cast<ForStmt>(Parent)->getBody();
+  default:
+    return false;
+  }
+}
+
 /// Walk through the statements, adding any labels or gotos to
 /// LabelAndGotoScopes and recursively walking the AST as needed.
 /// Returns false if we failed to build scope information and can't tell for
@@ -89,9 +167,13 @@ bool VarBypassDetector::BuildScopeInformation(CodeGenModule 
&CGM, const Stmt *S,
   // propagate out into the enclosing scope. Otherwise we have to worry about
   // block literals, which have the lifetime of their enclosing statement.
   unsigned independentParentScope = origParentScope;
-  unsigned &ParentScope =
-      ((isa<Expr>(S) && !isa<StmtExpr>(S)) ? origParentScope
-                                           : independentParentScope);
+  unsigned &ParentScope = ((isa<Expr, AttributedStmt>(S) && !isa<StmtExpr>(S))
+                               ? origParentScope
+                               : independentParentScope);
+
+  unsigned PrevBlockScope = CurEnclosingBlockScope;
+  llvm::scope_exit RestoreBlock(
+      [&] { CurEnclosingBlockScope = PrevBlockScope; });
 
   unsigned StmtsToSkip = 0u;
 
@@ -99,7 +181,66 @@ bool VarBypassDetector::BuildScopeInformation(CodeGenModule 
&CGM, const Stmt *S,
   case Stmt::IndirectGotoStmtClass:
     return false;
 
+  case Stmt::CompoundStmtClass:
+    Scopes.push_back({ParentScope, ParentScope, nullptr});
+    ParentScope = Scopes.size() - 1;
+    CurEnclosingBlockScope = ParentScope;
+    break;
+
+  case Stmt::CompoundLiteralExprClass: {
+    const auto *CLE = cast<CompoundLiteralExpr>(S);
+    if (!BuildScopeInformation(CGM, CLE->getType(), origParentScope))
+      return false;
+    if (!CGM.getLangOpts().CPlusPlus && !CLE->isFileScope()) {
+      Scopes.push_back({origParentScope, CurEnclosingBlockScope, CLE});
+      origParentScope = Scopes.size() - 1;
+    }
+    break;
+  }
+
+  case Stmt::UnaryExprOrTypeTraitExprClass: {
+    const auto *UETT = cast<UnaryExprOrTypeTraitExpr>(S);
+    if (UETT->isArgumentType())
+      return BuildScopeInformation(CGM, UETT->getArgumentType(),
+                                   origParentScope);
+    if (!UETT->getTypeOfArgument()->isVariablyModifiedType())
+      return true;
+    break;
+  }
+
+  case Stmt::GenericSelectionExprClass: {
+    const auto *GSE = cast<GenericSelectionExpr>(S);
+    if (!GSE->isResultDependent())
+      return BuildScopeInformation(CGM, GSE->getResultExpr(), origParentScope);
+    return true;
+  }
+
+  case Stmt::ChooseExprClass:
+    return BuildScopeInformation(CGM, cast<ChooseExpr>(S)->getChosenSubExpr(),
+                                 origParentScope);
+
+  case Stmt::ForStmtClass:
+    if (!CGM.getLangOpts().C99 && !CGM.getLangOpts().CPlusPlus) {
+      if (const Stmt *Init = cast<ForStmt>(S)->getInit()) {
+        if (!BuildScopeInformation(CGM, Init, origParentScope))
+          return false;
+        ParentScope = origParentScope;
+        ++StmtsToSkip;
+      }
+    }
+    [[fallthrough]];
+
+  case Stmt::IfStmtClass:
+  case Stmt::WhileStmtClass:
+    Scopes.push_back({ParentScope, ParentScope, nullptr});
+    ParentScope = Scopes.size() - 1;
+    CurEnclosingBlockScope = ParentScope;
+    break;
+
   case Stmt::SwitchStmtClass:
+    Scopes.push_back({ParentScope, ParentScope, nullptr});
+    ParentScope = Scopes.size() - 1;
+    CurEnclosingBlockScope = ParentScope;
     if (const Stmt *Init = cast<SwitchStmt>(S)->getInit()) {
       if (!BuildScopeInformation(CGM, Init, ParentScope))
         return false;
@@ -110,6 +251,11 @@ bool 
VarBypassDetector::BuildScopeInformation(CodeGenModule &CGM, const Stmt *S,
         return false;
       ++StmtsToSkip;
     }
+    if (const Expr *Cond = cast<SwitchStmt>(S)->getCond()) {
+      if (!BuildScopeInformation(CGM, Cond, ParentScope))
+        return false;
+      ++StmtsToSkip;
+    }
     [[fallthrough]];
 
   case Stmt::GotoStmtClass:
@@ -131,6 +277,9 @@ bool VarBypassDetector::BuildScopeInformation(CodeGenModule 
&CGM, const Stmt *S,
     break;
 
   default:
+    if (const auto *ECE = dyn_cast<ExplicitCastExpr>(S))
+      if (!BuildScopeInformation(CGM, ECE->getTypeAsWritten(), 
origParentScope))
+        return false;
     break;
   }
 
@@ -142,6 +291,23 @@ bool 
VarBypassDetector::BuildScopeInformation(CodeGenModule &CGM, const Stmt *S,
       continue;
     }
 
+    bool IsDoCond = isa<DoStmt>(S) && SubStmt == cast<DoStmt>(S)->getCond();
+    bool NeedsChildCleanupScope = needsChildCleanupScope(S, SubStmt);
+
+    unsigned SubCleanupScope = ParentScope;
+    unsigned SavedBlockScope = CurEnclosingBlockScope;
+    llvm::scope_exit RestoreChildBlock(
+        [&] { CurEnclosingBlockScope = SavedBlockScope; });
+    if (NeedsChildCleanupScope) {
+      Scopes.push_back({SubCleanupScope, SubCleanupScope, nullptr});
+      SubCleanupScope = Scopes.size() - 1;
+      CurEnclosingBlockScope = SubCleanupScope;
+    }
+
+    unsigned &ChildScope =
+        IsDoCond ? origParentScope
+                 : (NeedsChildCleanupScope ? SubCleanupScope : ParentScope);
+
     // Cases, labels, and defaults aren't "scope parents".  It's also
     // important to handle these iteratively instead of recursively in
     // order to avoid blowing out the stack.
@@ -154,14 +320,14 @@ bool 
VarBypassDetector::BuildScopeInformation(CodeGenModule &CGM, const Stmt *S,
       else
         break;
 
-      ToScopes[SubStmt] = ParentScope;
+      ToScopes[SubStmt] = ChildScope;
       SubStmt = Next;
     }
 
     // Recursively walk the AST.
     bool Result;
     CGM.runWithSufficientStackSpace(S->getEndLoc(), [&] {
-      Result = BuildScopeInformation(CGM, SubStmt, ParentScope);
+      Result = BuildScopeInformation(CGM, SubStmt, ChildScope);
     });
     if (!Result)
       return false;
@@ -174,43 +340,59 @@ bool 
VarBypassDetector::BuildScopeInformation(CodeGenModule &CGM, const Stmt *S,
 }
 
 /// Checks each jump and stores each variable declaration they bypass.
-void VarBypassDetector::Detect() {
+void VarBypassDetector::Detect(bool IsCPlusPlus) {
   for (const auto &S : FromScopes) {
     const Stmt *St = S.first;
-    unsigned from = S.second;
+    unsigned From = S.second;
     if (const GotoStmt *GS = dyn_cast<GotoStmt>(St)) {
       if (const LabelStmt *LS = GS->getLabel()->getStmt())
-        Detect(from, ToScopes[LS], GS);
+        Detect(IsCPlusPlus, From, ToScopes[LS], GS);
     } else if (const SwitchStmt *SS = dyn_cast<SwitchStmt>(St)) {
       // Keyed by the switch, not by each case: the dispatch is the jump
       // source, and that is where the initialization is emitted.
       for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
            SC = SC->getNextSwitchCase()) {
-        Detect(from, ToScopes[SC], SS);
+        Detect(IsCPlusPlus, From, ToScopes[SC], SS);
       }
     } else if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(St)) {
       for (const AddrLabelExpr *L : GAS->labels())
         if (const LabelStmt *LS = L->getLabel()->getStmt())
-          Detect(from, ToScopes[LS], GAS);
+          Detect(IsCPlusPlus, From, ToScopes[LS], GAS);
     } else {
       llvm_unreachable("goto, switch, or asm goto was expected");
     }
   }
 }
 
-/// Checks the jump and stores each variable declaration it bypasses.
-void VarBypassDetector::Detect(unsigned From, unsigned To, const Stmt *Source) 
{
+/// Checks the jump and stores each variable declaration or compound literal it
+/// bypasses.
+void VarBypassDetector::Detect(bool IsCPlusPlus, unsigned From, unsigned To,
+                               const Stmt *Source) {
   while (From != To) {
     if (From < To) {
-      assert(Scopes[To].first < To);
-      const auto &ScopeTo = Scopes[To];
-      To = ScopeTo.first;
-      Bypasses.insert(ScopeTo.second);
-      if (ScopeTo.second)
-        BypassedVarsAtSource[Source].insert(ScopeTo.second);
+      assert(Scopes[To].ParentScope < To &&
+             "Scope tree must be topologically ordered");
+      const ScopeEntry &ScopeTo = Scopes[To];
+      To = ScopeTo.ParentScope;
+      if (const auto *VD = ScopeTo.Item.dyn_cast<const VarDecl *>()) {
+        Bypasses.insert(VD);
+        BypassedVarsAtSource[Source].insert(VD);
+      } else if (const auto *CLE =
+                     ScopeTo.Item.dyn_cast<const CompoundLiteralExpr *>()) {
+        BypassedCLs.insert(CLE);
+      }
     } else {
-      assert(Scopes[From].first < From);
-      From = Scopes[From].first;
+      assert(Scopes[From].ParentScope < From &&
+             "Scope tree must be topologically ordered");
+      const ScopeEntry &ScopeFrom = Scopes[From];
+      if (!IsCPlusPlus && ScopeFrom.EnclosingBlockScope <= To) {
+        if (const auto *VD = ScopeFrom.Item.dyn_cast<const VarDecl *>())
+          BackwardBypassedVars.insert(VD);
+        else if (const auto *CLE =
+                     ScopeFrom.Item.dyn_cast<const CompoundLiteralExpr *>())
+          BypassedCLs.insert(CLE);
+      }
+      From = ScopeFrom.ParentScope;
     }
   }
 }
diff --git a/clang/lib/CodeGen/VarBypassDetector.h 
b/clang/lib/CodeGen/VarBypassDetector.h
index 80e6c483bb9ab6..2f855924c42ee5 100644
--- a/clang/lib/CodeGen/VarBypassDetector.h
+++ b/clang/lib/CodeGen/VarBypassDetector.h
@@ -16,17 +16,15 @@
 
 #include "CodeGenModule.h"
 #include "clang/AST/Decl.h"
+#include "clang/AST/Expr.h"
+#include "clang/AST/Stmt.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/DenseSet.h"
+#include "llvm/ADT/PointerUnion.h"
 #include "llvm/ADT/SetVector.h"
 #include "llvm/ADT/SmallVector.h"
 
 namespace clang {
-
-class Decl;
-class Stmt;
-class VarDecl;
-
 namespace CodeGen {
 
 /// The class detects jumps which bypass local variables declaration:
@@ -39,31 +37,57 @@ namespace CodeGen {
 ///  * Does not detect jumps out of the scope of local variables.
 ///  * Not limited to variables with initializers, JumpScopeChecker is limited.
 class VarBypassDetector {
+  struct ScopeEntry {
+    unsigned ParentScope;
+    // Scope index of the immediately enclosing CompoundStmt block.
+    unsigned EnclosingBlockScope = 0;
+    llvm::PointerUnion<const VarDecl *, const CompoundLiteralExpr *> Item;
+  };
   // Scope information. Contains a parent scope and related variable
-  // declaration.
-  llvm::SmallVector<std::pair<unsigned, const VarDecl *>, 48> Scopes;
+  // declaration or compound literal.
+  llvm::SmallVector<ScopeEntry, 48> Scopes;
   // List of jumps with scopes.
   llvm::SmallVector<std::pair<const Stmt *, unsigned>, 16> FromScopes;
   // Lookup map to find scope for destinations.
   llvm::DenseMap<const Stmt *, unsigned> ToScopes;
-  // Set of variables which were bypassed by some jump.
+  // Set of variables which were bypassed by some forward jump.
   llvm::DenseSet<const VarDecl *> Bypasses;
+  // Set of C local variables crossed by a backward jump within their enclosing
+  // lexical block.
+  llvm::DenseSet<const VarDecl *> BackwardBypassedVars;
+  // Set of C block-scoped compound literals bypassed by a forward jump or
+  // crossed by a backward jump within their enclosing lexical block.
+  llvm::DenseSet<const CompoundLiteralExpr *> BypassedCLs;
   // Map from a bypassing jump (goto/asm goto/switch) to the variable
   // declarations it bypasses. Used to reinitialize those variables at the 
jump.
   llvm::DenseMap<const Stmt *, llvm::SmallSetVector<const VarDecl *, 4>>
       BypassedVarsAtSource;
+  unsigned CurEnclosingBlockScope = 0;
   // If true assume that all variables are being bypassed.
   bool AlwaysBypassed = false;
+  bool Initialized = false;
 
 public:
   void Init(CodeGenModule &CGM, const Stmt *Body);
 
-  /// Returns true if the variable declaration was bypassed by any goto, asm
-  /// goto, or switch statement.
+  /// Returns true if the variable declaration was bypassed by any forward 
goto,
+  /// asm goto, or switch statement.
   bool IsBypassed(const VarDecl *D) const {
     return AlwaysBypassed || Bypasses.contains(D);
   }
 
+  /// Returns true if a backward jump branches from within \p D's live scope to
+  /// an earlier label inside \p D's enclosing lexical block.
+  bool IsBackwardBypassed(const VarDecl *D) const {
+    return !Initialized || AlwaysBypassed || BackwardBypassedVars.contains(D);
+  }
+
+  /// Returns true if \p CLE was bypassed by a forward jump or crossed by a
+  /// backward jump to an earlier label inside \p CLE's enclosing lexical 
block.
+  bool IsBypassed(const CompoundLiteralExpr *CLE) const {
+    return !Initialized || AlwaysBypassed || BypassedCLs.contains(CLE);
+  }
+
   /// Returns true if jump sources cannot be determined (e.g. computed gotos),
   /// so all variables must be treated as bypassed.
   bool isAlwaysBypassed() const { return AlwaysBypassed; }
@@ -79,14 +103,16 @@ class VarBypassDetector {
   }
 
 private:
+  bool BuildScopeInformation(CodeGenModule &CGM, QualType Ty,
+                             unsigned &ParentScope);
   bool BuildScopeInformation(CodeGenModule &CGM, const Decl *D,
                              unsigned &ParentScope);
   bool BuildScopeInformation(CodeGenModule &CGM, const Stmt *S,
                              unsigned &origParentScope);
-  void Detect();
-  void Detect(unsigned From, unsigned To, const Stmt *Source);
+  void Detect(bool IsCPlusPlus);
+  void Detect(bool IsCPlusPlus, unsigned From, unsigned To, const Stmt 
*Source);
 };
-}
-}
+} // namespace CodeGen
+} // namespace clang
 
 #endif
diff --git a/clang/test/CodeGen/compound-literal-lifetime.c 
b/clang/test/CodeGen/compound-literal-lifetime.c
index c61b8189de6125..72109fde138766 100644
--- a/clang/test/CodeGen/compound-literal-lifetime.c
+++ b/clang/test/CodeGen/compound-literal-lifetime.c
@@ -76,8 +76,8 @@ void test_order(void) {
   side_effect3();
 }
 
-// Verify that lifetime markers are not emitted when a label has been seen in 
the
-// current scope, matching VarDecl behavior to avoid miscompilation on 
backward jumps.
+// Verify that tight full-expression lifetime markers are not emitted when a
+// compound literal is crossed by a backward jump in its enclosing block.
 // CHECK-LABEL: define dso_local i32 @test_backward_goto()
 // CHECK-NOT: call void @llvm.lifetime.start
 // CHECK-NOT: call void @llvm.lifetime.end
@@ -91,6 +91,120 @@ int test_backward_goto(void) {
   goto label;
 }
 
+// Verify that a backward jump confined to an earlier statement expression does
+// not suppress lifetime markers for subsequent compound literals in the outer
+// block.
+// CHECK-LABEL: define dso_local void @test_stmt_expr_label(
+// CHECK: call void @llvm.lifetime.start.p0(ptr nonnull %[[CL_SE:.*]])
+// CHECK: call void @bar(ptr noundef nonnull %[[CL_SE]])
+// CHECK: call void @llvm.lifetime.end.p0(ptr nonnull %[[CL_SE]])
+void test_stmt_expr_label(int n) {
+  ({
+    __label__ l;
+  l:
+    if (n--)
+      goto l;
+  });
+  bar(&(struct foo){.x = 1, .y = 2});
+}
+
+// Verify that a label targeted only by a forward jump does not suppress
+// lifetime markers for compound literals after the label.
+// CHECK-LABEL: define dso_local void @test_label_without_backward_goto(
+// CHECK: call void @llvm.lifetime.start.p0(ptr nonnull %[[CL_FWD:.*]])
+// CHECK: call void @bar(ptr noundef nonnull %[[CL_FWD]])
+// CHECK: call void @llvm.lifetime.end.p0(ptr nonnull %[[CL_FWD]])
+void test_label_without_backward_goto(int cond) {
+  if (cond)
+    goto label;
+  side_effect1();
+label:
+  bar(&(struct foo){.x = 1, .y = 2});
+}
+
+// Verify that jumping forward over a compound literal suppresses its
+// block-exit lifetime end marker so it cannot execute without lifetime.start.
+// CHECK-LABEL: define dso_local void @test_forward_goto_bypass(
+// CHECK-NOT: call void @llvm.lifetime.start
+// CHECK-NOT: call void @llvm.lifetime.end
+// CHECK: ret void
+void test_forward_goto_bypass(int cond) {
+  if (cond)
+    goto after;
+  bar(&(struct foo){.x = 1, .y = 2});
+after:
+  side_effect1();
+}
+
+// Verify that a compound literal inside an inner block keeps its tight
+// lifetime markers when a backward goto branches to a label outside that inner
+// block.
+// CHECK-LABEL: define dso_local void @test_inner_block_backward_goto_to_outer(
+// CHECK: call void @llvm.lifetime.start.p0(ptr nonnull %[[CL_IN:.*]])
+// CHECK: call void @bar(ptr noundef nonnull %[[CL_IN]])
+// CHECK: call void @llvm.lifetime.end.p0(ptr nonnull %[[CL_IN]])
+void test_inner_block_backward_goto_to_outer(int cond) {
+outer:
+  {
+    bar(&(struct foo){.x = 1, .y = 2});
+    if (cond--)
+      goto outer;
+  }
+}
+
+int bar_int(struct foo *);
+
+// Verify that a compound literal in a switch condition is evaluated before the
+// switch jump and retains its lifetime markers.
+// CHECK-LABEL: define dso_local void @test_switch_cond_compound_literal(
+// CHECK: call void @llvm.lifetime.start.p0(ptr nonnull %[[CL_SW:.*]])
+// CHECK: call i32 @bar_int(ptr noundef nonnull %[[CL_SW]])
+// CHECK: call void @llvm.lifetime.end.p0(ptr nonnull %[[CL_SW]])
+void test_switch_cond_compound_literal(void) {
+  switch (bar_int(&(struct foo){.x = 1, .y = 2})) {
+  case 0:
+    side_effect1();
+    break;
+  default:
+    break;
+  }
+}
+
+int *id_ptr(int *);
+
+// Verify that an attributed statement does not hide a compound literal in a
+// synthetic scope when crossed by a backward jump.
+// CHECK-LABEL: define dso_local i32 @test_attributed_stmt_backward_goto()
+// CHECK-NOT: call void @llvm.lifetime.start
+// CHECK-NOT: call void @llvm.lifetime.end
+// CHECK: ret i32
+int test_attributed_stmt_backward_goto(void) {
+  int *p = 0;
+label:
+  if (p)
+    return *p;
+  [[clang::nomerge]] p = id_ptr(&(int){10});
+  goto label;
+}
+
+void use_vla(int, char *);
+
+// Verify that a compound literal inside a VLA bound is visited during bypass
+// detection when crossed by a backward jump.
+// CHECK-LABEL: define dso_local i32 @test_vla_bound_backward_goto()
+// CHECK-NOT: call void @llvm.lifetime.start
+// CHECK-NOT: call void @llvm.lifetime.end
+// CHECK: ret i32
+int test_vla_bound_backward_goto(void) {
+  int *p = 0;
+label:
+  if (p)
+    return *p;
+  char vla[*(p = id_ptr(&(int){5}))];
+  use_vla(sizeof(vla), vla);
+  goto label;
+}
+
 int callee(int);
 
 // Verify that conditional compound literals (which wrap CallLifetimeEnd in
diff --git a/clang/test/CodeGen/lifetime2.c b/clang/test/CodeGen/lifetime2.c
index 2f978751838af6..9876746c7114f1 100644
--- a/clang/test/CodeGen/lifetime2.c
+++ b/clang/test/CodeGen/lifetime2.c
@@ -146,3 +146,69 @@ int jump_backward_over_declaration(int a) {
   return -1;
 // O2: call void @llvm.lifetime.end.p0(
 }
+
+// CHECK-LABEL: @stmt_expr_label(
+void stmt_expr_label(int n) {
+  ({
+    __label__ l;
+  l:
+    if (n--)
+      goto l;
+  });
+  // O2: call void @llvm.lifetime.start.p0(
+  char x;
+  bar(&x, 1);
+  // O2: call void @llvm.lifetime.end.p0(
+}
+
+// CHECK-LABEL: @label_without_backward_jump(
+void label_without_backward_jump(int n) {
+  if (n)
+    goto l1;
+  bar(0, 0);
+l1:;
+  // O2: call void @llvm.lifetime.start.p0(
+  char x;
+  bar(&x, 1);
+  // O2: call void @llvm.lifetime.end.p0(
+}
+
+// CHECK-LABEL: @inner_block_backward_goto_to_outer(
+void inner_block_backward_goto_to_outer(int n) {
+l1:
+  if (n <= 0)
+    return;
+  {
+    // O2: call void @llvm.lifetime.start.p0(
+    char x;
+    bar(&x, 1);
+    // O2: call void @llvm.lifetime.end.p0(
+    --n;
+    goto l1;
+  }
+}
+
+// Verify bypass detection runs on non-FunctionDecl bodies (CapturedDecl):
+// `p` before `label1` gets lifetime markers, while `i` crossed by `goto 
label1`
+// does not.
+// CHECK-LABEL: @captured_stmt_backward_goto(
+// O2-LABEL: define internal void @__captured_stmt(
+// O2: %p = alloca ptr
+// O2: %i = alloca i32
+// O2: call void @llvm.lifetime.start.p0(ptr %p)
+// O2: call void @llvm.lifetime.end.p0(ptr %p)
+void captured_stmt_backward_goto(void) {
+  #pragma clang __debug captured
+  {
+    int *p = 0;
+  label1:
+    if (p) {
+      foo2(*p);
+      goto out;
+    }
+    int i = 999;
+    p = &i;
+    goto label1;
+  out:;
+  }
+}

_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to