[clang] [clang] Don't fold reads of modifiable file-scope compound literals (PR #241126)

Prajwal KP via cfe-commits cfe-commits at lists.llvm.org
Mon Nov 23 20:23:36 PST 2026


https://github.com/Prajwal-kp-18 updated https://github.com/llvm/llvm-project/pull/241126

>From ac2f4296ea31cfa4d9129da8b48ee01673f545fc Mon Sep 17 00:00:00 2001
From: Prajwal <prajwal.kp.1817 at gmail.com>
Date: Tue, 10 Nov 2026 13:03:05 +0530
Subject: [PATCH 1/4] [clang] Don't fold reads of modifiable file-scope
 compound literals

A compound literal at file scope is an unnamed object with static storage
duration. Unless its type is const-qualified it can be modified at
runtime, but the constant evaluator returned its initial value for any
read, for example through a const pointer:

  static struct S *const p = &(struct S){255};
  int f(void) { p->x = 252; return p->x; } // returned 255

Reject reads of such compound literals, except for the GNU extension
where the compound literal is immediately read by an lvalue-to-rvalue
conversion, possibly through '.' member access or __real/__imag, as in
'int x = (int){1};' or 'int y = (struct S){1}.a;'. That is not a read of
the object, so its value is used directly.

The bytecode interpreter still folds these reads, so the new checks only
run against the current evaluator for now.

Fixes #54014
---
 clang/lib/AST/ExprConstant.cpp        | 66 +++++++++++++++++++++------
 clang/test/CodeGen/compound-literal.c | 28 +++++++++++-
 clang/test/Sema/compound-literal.c    | 11 ++++-
 clang/test/Sema/constexpr.c           |  4 ++
 4 files changed, 94 insertions(+), 15 deletions(-)

diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 647bb9c45f871a..2a67cc96118c4b 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -4712,10 +4712,12 @@ static bool AreElementsOfSameArray(QualType ObjType,
   return CommonLength >= A.Entries.size() - IsArray;
 }
 
-/// Find the complete object to which an LValue refers.
-static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
-                                         AccessKinds AK, const LValue &LVal,
-                                         QualType LValType) {
+/// Find the complete object to which an LValue refers. \p DirectlyReadCLE is a
+/// compound literal that may be read; see getDirectlyReadCompoundLiteral.
+static CompleteObject
+findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK,
+                   const LValue &LVal, QualType LValType,
+                   const CompoundLiteralExpr *DirectlyReadCLE = nullptr) {
   if (LVal.InvalidBase) {
     Info.FFDiag(E);
     return CompleteObject();
@@ -4995,6 +4997,18 @@ static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
           return CompleteObject();
         }
 
+        // A compound literal with static storage duration is an unnamed object
+        // (C11 6.5.2.5) that can be modified unless it is const-qualified, so
+        // its value is not known, except in the GNU extension
+        // 'int x = (int){1};'; see getDirectlyReadCompoundLiteral.
+        if (!CLE->getType().isConstant(Info.Ctx) && CLE != DirectlyReadCLE) {
+          if (!IsAccess)
+            return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
+          Info.FFDiag(E);
+          Info.Note(CLE->getExprLoc(), diag::note_declared_at);
+          return CompleteObject();
+        }
+
         BaseVal = &CLE->getStaticValue();
       } else {
         if (!IsAccess)
@@ -5047,10 +5061,12 @@ static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
 /// \param WantObjectRepresentation - If true, we're looking for the object
 ///               representation rather than the value, and in particular,
 ///               there is no requirement that the result be fully initialized.
-static bool
-handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
-                               const LValue &LVal, APValue &RVal,
-                               bool WantObjectRepresentation = false) {
+/// \param DirectlyReadCLE - The compound literal read directly by this
+///               conversion, if any; see getDirectlyReadCompoundLiteral.
+static bool handleLValueToRValueConversion(
+    EvalInfo &Info, const Expr *Conv, QualType Type, const LValue &LVal,
+    APValue &RVal, bool WantObjectRepresentation = false,
+    const CompoundLiteralExpr *DirectlyReadCLE = nullptr) {
   if (LVal.Designator.Invalid)
     return false;
 
@@ -5086,7 +5102,8 @@ handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
     }
   }
 
-  CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
+  CompleteObject Obj =
+      findCompleteObject(Info, Conv, AK, LVal, Type, DirectlyReadCLE);
   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
 }
 
@@ -8751,6 +8768,25 @@ static bool diagnoseBPFPreserveAIEnumerator(EvalInfo &Info,
   return true;
 }
 
+/// GNU extension: a compound literal that is immediately read by an
+/// lvalue-to-rvalue conversion, possibly through '.' member access or
+/// __real/__imag, as in 'int x = (int){1};' or 'int y = (struct S){1}.a;', is
+/// not a read of the compound literal object; the value of its initializer is
+/// used directly. Returns that compound literal, if E is such an operand.
+static const CompoundLiteralExpr *
+getDirectlyReadCompoundLiteral(const Expr *E) {
+  while (true) {
+    E = E->IgnoreParens();
+    if (const auto *ME = dyn_cast<MemberExpr>(E); ME && !ME->isArrow())
+      E = ME->getBase();
+    else if (const auto *UO = dyn_cast<UnaryOperator>(E);
+             UO && (UO->getOpcode() == UO_Real || UO->getOpcode() == UO_Imag))
+      E = UO->getSubExpr();
+    else
+      return dyn_cast<CompoundLiteralExpr>(E);
+  }
+}
+
 template <class Derived>
 class ExprEvaluatorBase
   : public ConstStmtVisitor<Derived, bool> {
@@ -9376,8 +9412,10 @@ class ExprEvaluatorBase
         return false;
       APValue RVal;
       // Note, we use the subexpression's type in order to retain cv-qualifiers.
-      if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
-                                          LVal, RVal))
+      if (!handleLValueToRValueConversion(
+              Info, E, E->getSubExpr()->getType(), LVal, RVal,
+              /*WantObjectRepresentation=*/false,
+              getDirectlyReadCompoundLiteral(E->getSubExpr())))
         return false;
       return DerivedSuccess(RVal, E);
     }
@@ -10610,8 +10648,10 @@ bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
 
     APValue RVal;
     // Note, we use the subexpression's type in order to retain cv-qualifiers.
-    if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
-                                        LVal, RVal))
+    if (!handleLValueToRValueConversion(
+            Info, E, E->getSubExpr()->getType(), LVal, RVal,
+            /*WantObjectRepresentation=*/false,
+            getDirectlyReadCompoundLiteral(SubExpr)))
       return InvalidBaseOK &&
              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
     return Success(RVal, E);
diff --git a/clang/test/CodeGen/compound-literal.c b/clang/test/CodeGen/compound-literal.c
index 5fe9594c0f954f..785ce8beae235e 100644
--- a/clang/test/CodeGen/compound-literal.c
+++ b/clang/test/CodeGen/compound-literal.c
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -triple x86_64-apple-darwin -emit-llvm %s -o - | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-apple-darwin -emit-llvm %s -o - | FileCheck %s --check-prefixes=CHECK,REF
 // RUN: %clang_cc1 -triple x86_64-apple-darwin -fexperimental-new-constant-interpreter -emit-llvm %s -o - | FileCheck %s
 
 // Capture the type and name so matching later is cleaner.
@@ -94,3 +94,29 @@ int compound_array_fn(void) {
   int compound_array[] = (int[]){1,2,3,4,5,6,7,8};
   return compound_array[0];
 }
+
+// GH54014: a file-scope compound literal is a modifiable object even when it
+// is only reachable through a const pointer, so reads of it must load from
+// memory instead of being folded to its initial value.
+// FIXME: The bytecode interpreter still folds these reads.
+struct GH54014 { int counter; };
+static struct GH54014 *const GH54014_ptr = &(struct GH54014){255};
+void GH54014_g(void);
+
+// REF-LABEL: define{{.*}} i32 @GH54014_write_then_read()
+// REF:      store i32 252, ptr [[CL:@.compoundliteral[.0-9]*]]
+// REF-NEXT: [[V:%.*]] = load i32, ptr [[CL]]
+// REF-NEXT: ret i32 [[V]]
+int GH54014_write_then_read(void) {
+  GH54014_ptr->counter = 252;
+  return GH54014_ptr->counter;
+}
+
+// REF-LABEL: define{{.*}} i32 @GH54014_read_after_call()
+// REF:      call void @GH54014_g()
+// REF-NEXT: [[V:%.*]] = load i32, ptr @.compoundliteral{{[.0-9]*}}
+// REF-NEXT: ret i32 [[V]]
+int GH54014_read_after_call(void) {
+  GH54014_g();
+  return GH54014_ptr->counter;
+}
diff --git a/clang/test/Sema/compound-literal.c b/clang/test/Sema/compound-literal.c
index 1026e5ece11b49..ecb3c985623fb1 100644
--- a/clang/test/Sema/compound-literal.c
+++ b/clang/test/Sema/compound-literal.c
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -fsyntax-only -verify -fblocks -pedantic %s
+// RUN: %clang_cc1 -fsyntax-only -verify=expected,ref -fblocks -pedantic %s
 // RUN: %clang_cc1 -fsyntax-only -verify -fblocks -pedantic %s -fexperimental-new-constant-interpreter
 // REQUIRES: LP64
 
@@ -54,3 +54,12 @@ void vla(int n) {
   (void)(int[size]){1,2,3}; // expected-error {{compound literal cannot be of variable-length array type}}
   (void)(int[size]){1,2,3,4,5}; // expected-error {{compound literal cannot be of variable-length array type}}
 }
+
+// GH54014: a non-const file-scope compound literal may be modified at runtime,
+// so its value can't be read through a pointer in a constant initializer.
+// FIXME: The bytecode interpreter still folds this read.
+static int *const GH54014_p = &(int){255};
+static int GH54014_x = *GH54014_p; // ref-error {{initializer element is not a compile-time constant}}
+// A const-qualified compound literal can't change, so this is still folded.
+static const int *const GH54014_q = &(const int){3};
+static int GH54014_y = *GH54014_q;
diff --git a/clang/test/Sema/constexpr.c b/clang/test/Sema/constexpr.c
index aedaba2cb921a7..5654ade47ac5b9 100644
--- a/clang/test/Sema/constexpr.c
+++ b/clang/test/Sema/constexpr.c
@@ -43,6 +43,10 @@ constexpr signed auto Long = 1L; // expected-error {{illegal storage class on fi
 // expected-error at -1 {{cannot combine with previous 'constexpr' declaration specifier}}
 _Static_assert(_Generic(Ulong, long : 1));
 _Static_assert(_Generic(CompoundLiteral, int : 1));
+// GH54014: a compound literal that is directly converted to an rvalue isn't a
+// read of the (modifiable) compound literal object, unless it is volatile.
+constexpr int *CompoundLiteralPtr = (int *){nullptr};
+constexpr int CompoundLiteralVolatile = (volatile int){1}; // expected-error {{constexpr variable 'CompoundLiteralVolatile' must be initialized by a constant expression}}
 _Static_assert(_Generic(DoubleCast, double : 1));
 _Static_assert(_Generic(String, char* : 1));
 

>From 76be28fc611d8811fcd5828021780c82cd0f768b Mon Sep 17 00:00:00 2001
From: Prajwal <prajwal.kp.1817 at gmail.com>
Date: Thu, 19 Nov 2026 11:43:49 +0530
Subject: [PATCH 2/4] [clang] Remove the array-specific compound literal check

The check for reads of non-const compound literals with static storage
duration covers it. A non-const array compound literal that is read as a
non-array type is never the operand of a direct lvalue-to-rvalue
conversion, so it is already rejected with the same diagnostics.
---
 clang/lib/AST/ExprConstant.cpp | 21 ---------------------
 1 file changed, 21 deletions(-)

diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 2a67cc96118c4b..8901eddf9b0c55 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -4976,27 +4976,6 @@ findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK,
         assert(BaseVal && "got reference to unevaluated temporary");
       } else if (const CompoundLiteralExpr *CLE =
                      dyn_cast_or_null<CompoundLiteralExpr>(Base)) {
-        // According to GCC info page:
-        //
-        // 6.28 Compound Literals
-        //
-        // As an optimization, G++ sometimes gives array compound literals
-        // longer lifetimes: when the array either appears outside a function or
-        // has a const-qualified type. If foo and its initializer had elements
-        // of type char *const rather than char *, or if foo were a global
-        // variable, the array would have static storage duration. But it is
-        // probably safest just to avoid the use of array compound literals in
-        // C++ code.
-        //
-        // Obey that rule by checking constness for converted array types.
-        if (QualType CLETy = CLE->getType(); CLETy->isArrayType() &&
-                                             !LValType->isArrayType() &&
-                                             !CLETy.isConstant(Info.Ctx)) {
-          Info.FFDiag(E);
-          Info.Note(CLE->getExprLoc(), diag::note_declared_at);
-          return CompleteObject();
-        }
-
         // A compound literal with static storage duration is an unnamed object
         // (C11 6.5.2.5) that can be modified unless it is const-qualified, so
         // its value is not known, except in the GNU extension

>From be4424c89e0ddadb6c645867e898c703a463b7ce Mon Sep 17 00:00:00 2001
From: Prajwal <prajwal.kp.1817 at gmail.com>
Date: Thu, 19 Nov 2026 11:43:56 +0530
Subject: [PATCH 3/4] [clang][bytecode] Don't fold reads of modifiable
 file-scope compound literals

Apply the same rule as the current evaluator. CheckLoad and
CheckFinalLoad now reject reads of non-const compound literals with
static storage duration, which replaces the array-only check in
CheckLoad.

A compound literal that is directly read by an lvalue-to-rvalue
conversion is evaluated into a local instead of its global, so its value
is used directly. getDirectlyReadCompoundLiteral is declared in
ExprConstShared.h so both evaluators use the same pattern.

The tests now expect the same results from both evaluators.
---
 clang/lib/AST/ByteCode/Compiler.cpp   |  7 +++-
 clang/lib/AST/ByteCode/Compiler.h     |  3 ++
 clang/lib/AST/ByteCode/Interp.cpp     | 48 +++++++++++----------------
 clang/lib/AST/ExprConstShared.h       |  3 ++
 clang/lib/AST/ExprConstant.cpp        | 37 ++++++++++-----------
 clang/test/CodeGen/compound-literal.c | 19 +++++------
 clang/test/Sema/compound-literal.c    |  5 ++-
 7 files changed, 61 insertions(+), 61 deletions(-)

diff --git a/clang/lib/AST/ByteCode/Compiler.cpp b/clang/lib/AST/ByteCode/Compiler.cpp
index 5044656e3afff1..aeda32f5c4ff68 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -457,6 +457,9 @@ bool Compiler<Emitter>::VisitCastExpr(const CastExpr *E) {
     if (!Ctx.getLangOpts().HLSL && E->getType()->isConstantMatrixType())
       return false;
 
+    llvm::SaveAndRestore DirectRead(DirectlyReadCLE,
+                                    getDirectlyReadCompoundLiteral(SubExpr));
+
     if (ToLValue && E->getType()->isPointerType()) {
       assert(!DiscardResult);
       if (!this->visit(SubExpr))
@@ -3710,7 +3713,9 @@ bool Compiler<Emitter>::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
   }
 
   OptPrimType T = classify(E->getType());
-  if (E->isFileScope()) {
+  // A compound literal that is directly read doesn't need the global object;
+  // see getDirectlyReadCompoundLiteral.
+  if (E->isFileScope() && E != DirectlyReadCLE) {
     // Avoid creating a variable if this is a primitive RValue anyway.
     if (T && !E->isLValue())
       return this->delegate(Init);
diff --git a/clang/lib/AST/ByteCode/Compiler.h b/clang/lib/AST/ByteCode/Compiler.h
index 72fbef7c8b2920..4180ef6b5661e6 100644
--- a/clang/lib/AST/ByteCode/Compiler.h
+++ b/clang/lib/AST/ByteCode/Compiler.h
@@ -486,6 +486,9 @@ class Compiler final : public ConstStmtVisitor<Compiler<Emitter>, bool>,
   /// DefaultInit- or DefaultArgExpr, needed for SourceLocExpr.
   const Expr *SourceLocDefaultExpr = nullptr;
 
+  /// Compound literal read by the current lvalue-to-rvalue conversion.
+  const CompoundLiteralExpr *DirectlyReadCLE = nullptr;
+
   /// Flag indicating if return value is to be discarded.
   bool DiscardResult = false;
 
diff --git a/clang/lib/AST/ByteCode/Interp.cpp b/clang/lib/AST/ByteCode/Interp.cpp
index 0377dbe6c130fc..c81d69cd1fe8ec 100644
--- a/clang/lib/AST/ByteCode/Interp.cpp
+++ b/clang/lib/AST/ByteCode/Interp.cpp
@@ -930,6 +930,22 @@ bool CheckLocalLoad(InterpState &S, CodePtr OpPC, const Block *B) {
   return true;
 }
 
+/// A compound literal with static storage duration can be modified unless it
+/// is const-qualified, so its value is not known.
+static bool CheckCompoundLiteral(InterpState &S, CodePtr OpPC, const Block *B) {
+  const auto *CLE =
+      dyn_cast_if_present<CompoundLiteralExpr>(B->getDescriptor()->asExpr());
+  if (!CLE || !CLE->hasStaticStorage() ||
+      CLE->getType().isConstant(S.getASTContext()))
+    return true;
+
+  S.FFDiag(S.Current->getLocation(OpPC),
+           diag::note_invalid_subexpr_in_const_expr)
+      << S.Current->getRange(OpPC);
+  S.Note(CLE->getExprLoc(), diag::note_declared_at);
+  return false;
+}
+
 bool CheckLoad(InterpState &S, CodePtr OpPC, PtrView Ptr, AccessKinds AK) {
   if (Ptr.isZero()) {
     SourceInfo Loc = S.Current->getSource(OpPC);
@@ -980,34 +996,8 @@ bool CheckLoad(InterpState &S, CodePtr OpPC, PtrView Ptr, AccessKinds AK) {
     return false;
   if (!CheckVolatile(S, OpPC, Ptr, AK))
     return false;
-
-  if (!Ptr.isArrayRoot()) {
-    // According to GCC info page:
-    //
-    // 6.28 Compound Literals
-    //
-    // As an optimization, G++ sometimes gives array compound literals
-    // longer lifetimes: when the array either appears outside a function or
-    // has a const-qualified type. If foo and its initializer had elements
-    // of type char *const rather than char *, or if foo were a global
-    // variable, the array would have static storage duration. But it is
-    // probably safest just to avoid the use of array compound literals in
-    // C++ code.
-    //
-    // Obey that rule by checking constness for converted array types.
-    const Descriptor *Desc = Ptr.getFieldDesc();
-    if (const auto *CLE =
-            dyn_cast_if_present<CompoundLiteralExpr>(Desc->asExpr())) {
-      if (QualType CLETy = CLE->getType();
-          CLETy->isArrayType() && !CLETy.isConstant(S.getASTContext())) {
-        S.FFDiag(S.Current->getLocation(OpPC),
-                 diag::note_invalid_subexpr_in_const_expr)
-            << S.Current->getRange(OpPC);
-        S.Note(CLE->getExprLoc(), diag::note_declared_at);
-        return false;
-      }
-    }
-  }
+  if (!CheckCompoundLiteral(S, OpPC, Ptr.block()))
+    return false;
   return true;
 }
 
@@ -1075,6 +1065,8 @@ bool CheckFinalLoad(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
       return false;
     if (!CheckMutable(S, OpPC, Ptr.view()))
       return false;
+    if (!CheckCompoundLiteral(S, OpPC, Ptr.block()))
+      return false;
   }
   return true;
 }
diff --git a/clang/lib/AST/ExprConstShared.h b/clang/lib/AST/ExprConstShared.h
index a306af5bcf61db..5dc0beb44a8c06 100644
--- a/clang/lib/AST/ExprConstShared.h
+++ b/clang/lib/AST/ExprConstShared.h
@@ -31,6 +31,7 @@ class ASTContext;
 class CharUnits;
 class Expr;
 class CallExpr;
+class CompoundLiteralExpr;
 class CXXRecordDecl;
 class FunctionDecl;
 
@@ -118,6 +119,8 @@ EvalScalarMinMaxFp(const llvm::APFloat &A, const llvm::APFloat &B,
 
 const Expr *ignorePointerCastsAndParens(const Expr *E);
 
+const CompoundLiteralExpr *getDirectlyReadCompoundLiteral(const Expr *E);
+
 bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
 bool isReadByLvalueToRvalueConversion(QualType T);
 /// Determines whether the given kind of constant expression is only ever
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 8901eddf9b0c55..fc888e6b81632d 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -4712,6 +4712,24 @@ static bool AreElementsOfSameArray(QualType ObjType,
   return CommonLength >= A.Entries.size() - IsArray;
 }
 
+/// GNU extension: a compound literal that is immediately read by an
+/// lvalue-to-rvalue conversion, possibly through '.' member access or
+/// __real/__imag, as in 'int x = (int){1};' or 'int y = (struct S){1}.a;', is
+/// not a read of the compound literal object; the value of its initializer is
+/// used directly. Returns that compound literal, if E is such an operand.
+const CompoundLiteralExpr *getDirectlyReadCompoundLiteral(const Expr *E) {
+  while (true) {
+    E = E->IgnoreParens();
+    if (const auto *ME = dyn_cast<MemberExpr>(E); ME && !ME->isArrow())
+      E = ME->getBase();
+    else if (const auto *UO = dyn_cast<UnaryOperator>(E);
+             UO && (UO->getOpcode() == UO_Real || UO->getOpcode() == UO_Imag))
+      E = UO->getSubExpr();
+    else
+      return dyn_cast<CompoundLiteralExpr>(E);
+  }
+}
+
 /// Find the complete object to which an LValue refers. \p DirectlyReadCLE is a
 /// compound literal that may be read; see getDirectlyReadCompoundLiteral.
 static CompleteObject
@@ -8747,25 +8765,6 @@ static bool diagnoseBPFPreserveAIEnumerator(EvalInfo &Info,
   return true;
 }
 
-/// GNU extension: a compound literal that is immediately read by an
-/// lvalue-to-rvalue conversion, possibly through '.' member access or
-/// __real/__imag, as in 'int x = (int){1};' or 'int y = (struct S){1}.a;', is
-/// not a read of the compound literal object; the value of its initializer is
-/// used directly. Returns that compound literal, if E is such an operand.
-static const CompoundLiteralExpr *
-getDirectlyReadCompoundLiteral(const Expr *E) {
-  while (true) {
-    E = E->IgnoreParens();
-    if (const auto *ME = dyn_cast<MemberExpr>(E); ME && !ME->isArrow())
-      E = ME->getBase();
-    else if (const auto *UO = dyn_cast<UnaryOperator>(E);
-             UO && (UO->getOpcode() == UO_Real || UO->getOpcode() == UO_Imag))
-      E = UO->getSubExpr();
-    else
-      return dyn_cast<CompoundLiteralExpr>(E);
-  }
-}
-
 template <class Derived>
 class ExprEvaluatorBase
   : public ConstStmtVisitor<Derived, bool> {
diff --git a/clang/test/CodeGen/compound-literal.c b/clang/test/CodeGen/compound-literal.c
index 785ce8beae235e..14e68ff73a538c 100644
--- a/clang/test/CodeGen/compound-literal.c
+++ b/clang/test/CodeGen/compound-literal.c
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -triple x86_64-apple-darwin -emit-llvm %s -o - | FileCheck %s --check-prefixes=CHECK,REF
+// RUN: %clang_cc1 -triple x86_64-apple-darwin -emit-llvm %s -o - | FileCheck %s
 // RUN: %clang_cc1 -triple x86_64-apple-darwin -fexperimental-new-constant-interpreter -emit-llvm %s -o - | FileCheck %s
 
 // Capture the type and name so matching later is cleaner.
@@ -98,24 +98,23 @@ int compound_array_fn(void) {
 // GH54014: a file-scope compound literal is a modifiable object even when it
 // is only reachable through a const pointer, so reads of it must load from
 // memory instead of being folded to its initial value.
-// FIXME: The bytecode interpreter still folds these reads.
 struct GH54014 { int counter; };
 static struct GH54014 *const GH54014_ptr = &(struct GH54014){255};
 void GH54014_g(void);
 
-// REF-LABEL: define{{.*}} i32 @GH54014_write_then_read()
-// REF:      store i32 252, ptr [[CL:@.compoundliteral[.0-9]*]]
-// REF-NEXT: [[V:%.*]] = load i32, ptr [[CL]]
-// REF-NEXT: ret i32 [[V]]
+// CHECK-LABEL: define{{.*}} i32 @GH54014_write_then_read()
+// CHECK:      store i32 252, ptr [[CL:@.compoundliteral[.0-9]*]]
+// CHECK-NEXT: [[V:%.*]] = load i32, ptr [[CL]]
+// CHECK-NEXT: ret i32 [[V]]
 int GH54014_write_then_read(void) {
   GH54014_ptr->counter = 252;
   return GH54014_ptr->counter;
 }
 
-// REF-LABEL: define{{.*}} i32 @GH54014_read_after_call()
-// REF:      call void @GH54014_g()
-// REF-NEXT: [[V:%.*]] = load i32, ptr @.compoundliteral{{[.0-9]*}}
-// REF-NEXT: ret i32 [[V]]
+// CHECK-LABEL: define{{.*}} i32 @GH54014_read_after_call()
+// CHECK:      call void @GH54014_g()
+// CHECK-NEXT: [[V:%.*]] = load i32, ptr @.compoundliteral{{[.0-9]*}}
+// CHECK-NEXT: ret i32 [[V]]
 int GH54014_read_after_call(void) {
   GH54014_g();
   return GH54014_ptr->counter;
diff --git a/clang/test/Sema/compound-literal.c b/clang/test/Sema/compound-literal.c
index ecb3c985623fb1..f638e175cfc0b6 100644
--- a/clang/test/Sema/compound-literal.c
+++ b/clang/test/Sema/compound-literal.c
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -fsyntax-only -verify=expected,ref -fblocks -pedantic %s
+// RUN: %clang_cc1 -fsyntax-only -verify -fblocks -pedantic %s
 // RUN: %clang_cc1 -fsyntax-only -verify -fblocks -pedantic %s -fexperimental-new-constant-interpreter
 // REQUIRES: LP64
 
@@ -57,9 +57,8 @@ void vla(int n) {
 
 // GH54014: a non-const file-scope compound literal may be modified at runtime,
 // so its value can't be read through a pointer in a constant initializer.
-// FIXME: The bytecode interpreter still folds this read.
 static int *const GH54014_p = &(int){255};
-static int GH54014_x = *GH54014_p; // ref-error {{initializer element is not a compile-time constant}}
+static int GH54014_x = *GH54014_p; // expected-error {{initializer element is not a compile-time constant}}
 // A const-qualified compound literal can't change, so this is still folded.
 static const int *const GH54014_q = &(const int){3};
 static int GH54014_y = *GH54014_q;

>From 8e0d958ff7462099fe0a3d614fd21d524da1b858 Mon Sep 17 00:00:00 2001
From: Prajwal <prajwal.kp.1817 at gmail.com>
Date: Tue, 24 Nov 2026 09:52:54 +0530
Subject: [PATCH 4/4] [clang][bytecode] Count the extra note in
 CheckCompoundLiteral

Use the frame's source info for the diagnostic and pass ExtraNotes = 1 for
the note_declared_at note that follows it.
---
 clang/lib/AST/ByteCode/Interp.cpp | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/clang/lib/AST/ByteCode/Interp.cpp b/clang/lib/AST/ByteCode/Interp.cpp
index c81d69cd1fe8ec..f2f07004928131 100644
--- a/clang/lib/AST/ByteCode/Interp.cpp
+++ b/clang/lib/AST/ByteCode/Interp.cpp
@@ -939,8 +939,8 @@ static bool CheckCompoundLiteral(InterpState &S, CodePtr OpPC, const Block *B) {
       CLE->getType().isConstant(S.getASTContext()))
     return true;
 
-  S.FFDiag(S.Current->getLocation(OpPC),
-           diag::note_invalid_subexpr_in_const_expr)
+  S.FFDiag(S.Current->getSource(OpPC), diag::note_invalid_subexpr_in_const_expr,
+           1)
       << S.Current->getRange(OpPC);
   S.Note(CLE->getExprLoc(), diag::note_declared_at);
   return false;



More information about the cfe-commits mailing list