[clang] [Clang] support storage-class specifiers in C23 compound literals (PR #212559)

Oleksandr Tarasiuk via cfe-commits cfe-commits at lists.llvm.org
Sat Nov 7 11:43:46 PST 2026


https://github.com/a-tarasyuk updated https://github.com/llvm/llvm-project/pull/212559

>From 6a8291c3ac626699e004c64f6dcd4b504a7dbfbc Mon Sep 17 00:00:00 2001
From: Oleksandr Tarasiuk <oleksandr.tarasiuk at outlook.com>
Date: Tue, 28 Jul 2026 17:14:33 +0300
Subject: [PATCH 1/7] [Clang] support storage-class specifiers in C23 compound
 literals

---
 clang/docs/ReleaseNotes.md                    |   2 +
 clang/include/clang/AST/Expr.h                |  67 ++-
 clang/include/clang/AST/Stmt.h                |  17 +
 .../include/clang/Basic/DiagnosticASTKinds.td |   5 +
 .../clang/Basic/DiagnosticParseKinds.td       |   4 +
 .../clang/Basic/DiagnosticSemaKinds.td        |  20 +-
 clang/include/clang/Parse/Parser.h            |  12 +-
 clang/include/clang/Sema/DelayedDiagnostic.h  |  15 +-
 clang/include/clang/Sema/Initialization.h     |  24 +-
 clang/include/clang/Sema/Scope.h              |   6 +-
 clang/include/clang/Sema/Sema.h               |  28 +-
 clang/lib/AST/ASTImporter.cpp                 |   6 +-
 clang/lib/AST/ASTStructuralEquivalence.cpp    |   8 +
 clang/lib/AST/ByteCode/Compiler.cpp           |  15 +-
 clang/lib/AST/ByteCode/Interp.cpp             |  40 +-
 clang/lib/AST/ByteCode/State.cpp              |   7 +
 clang/lib/AST/Expr.cpp                        |  10 +-
 clang/lib/AST/ExprConstant.cpp                |  82 ++--
 clang/lib/AST/StmtPrinter.cpp                 |  24 +-
 clang/lib/AST/StmtProfile.cpp                 |   3 +
 clang/lib/CIR/CodeGen/CIRGenConstantEmitter.h |   2 +
 clang/lib/CIR/CodeGen/CIRGenExpr.cpp          |  24 +-
 clang/lib/CIR/CodeGen/CIRGenExprAggregate.cpp |   5 +-
 clang/lib/CIR/CodeGen/CIRGenExprConstant.cpp  |  57 +--
 clang/lib/CodeGen/CGExpr.cpp                  |  26 +-
 clang/lib/CodeGen/CGExprAgg.cpp               |  13 +-
 clang/lib/CodeGen/CGExprConstant.cpp          |   9 +-
 .../Frontend/Rewrite/RewriteModernObjC.cpp    |   9 +-
 clang/lib/Frontend/Rewrite/RewriteObjC.cpp    |   9 +-
 clang/lib/Parse/ParseDecl.cpp                 | 285 +++++++-----
 clang/lib/Parse/ParseExpr.cpp                 |  79 +++-
 clang/lib/Sema/CheckExprLifetime.cpp          |   3 +-
 clang/lib/Sema/DelayedDiagnostic.cpp          |   1 +
 clang/lib/Sema/Scope.cpp                      |  15 +-
 clang/lib/Sema/SemaDecl.cpp                   |  51 ++-
 clang/lib/Sema/SemaDeclAttr.cpp               |  13 +-
 clang/lib/Sema/SemaExpr.cpp                   | 330 +++++++++-----
 clang/lib/Sema/SemaInit.cpp                   |  45 +-
 clang/lib/Sema/SemaOverload.cpp               | 162 ++++---
 clang/lib/Sema/TreeTransform.h                |  18 +-
 clang/lib/Serialization/ASTReaderStmt.cpp     |   3 +
 clang/lib/Serialization/ASTWriterStmt.cpp     |   3 +
 clang/test/AST/ByteCode/c.c                   |   4 +
 clang/test/AST/c23-compound-literal-print.c   |  33 ++
 clang/test/C/C23/n3006.c                      |  10 +-
 clang/test/C/drs/dr3xx.c                      |   1 +
 clang/test/CIR/CodeGen/c23-compound-literal.c |  83 ++++
 clang/test/CodeGen/c23-compound-literal.c     | 306 +++++++++++++
 clang/test/CodeGenObjC/c23-compound-literal.m |  37 ++
 clang/test/Parser/c23-compound-literal.c      |  32 ++
 clang/test/Parser/expressions.c               |  18 +-
 clang/test/Sema/c23-compound-literal.c        | 417 ++++++++++++++++++
 clang/test/Sema/c23-compound-literal.m        |  12 +
 .../test/Sema/constexpr-builtin-stdc-load8.c  |   6 +-
 clang/test/Sema/constexpr-member-access.c     |   2 +-
 clang/test/Sema/constexpr.c                   |  74 +++-
 .../AST/StructuralEquivalenceTest.cpp         |  19 +
 57 files changed, 2101 insertions(+), 510 deletions(-)
 create mode 100644 clang/test/AST/c23-compound-literal-print.c
 create mode 100644 clang/test/CIR/CodeGen/c23-compound-literal.c
 create mode 100644 clang/test/CodeGen/c23-compound-literal.c
 create mode 100644 clang/test/CodeGenObjC/c23-compound-literal.m
 create mode 100644 clang/test/Parser/c23-compound-literal.c
 create mode 100644 clang/test/Sema/c23-compound-literal.c
 create mode 100644 clang/test/Sema/c23-compound-literal.m

diff --git a/clang/docs/ReleaseNotes.md b/clang/docs/ReleaseNotes.md
index a2ad6d06815c7c..d8c6a2d1c4aec4 100644
--- a/clang/docs/ReleaseNotes.md
+++ b/clang/docs/ReleaseNotes.md
@@ -312,6 +312,8 @@ documentation](CIR/index.md) for more information regarding ClangIR's status and
 
 #### C23 Feature Support
 
+- Clang now supports storage-class specifiers in compound literals.
+
 ### Objective-C Language Changes
 
 ### Non-comprehensive list of changes in this release
diff --git a/clang/include/clang/AST/Expr.h b/clang/include/clang/AST/Expr.h
index b28b9a7a27019a..fc7e775d778a0e 100644
--- a/clang/include/clang/AST/Expr.h
+++ b/clang/include/clang/AST/Expr.h
@@ -650,8 +650,7 @@ class Expr : public ValueStmt {
     /// to a string representation).
     SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr;
 
-    /// Location where we spot ptr to int cast or null subobject while
-    /// evaluating constant expression in MS compatibility mode.
+    /// Diagnostics for extensions accepted during constant evaluation.
     SmallVectorImpl<PartialDiagnosticAt> *ExtendedDiag = nullptr;
 
     EvalStatus() = default;
@@ -3669,7 +3668,7 @@ class MemberExpr final
   }
 };
 
-/// CompoundLiteralExpr - [C99 6.5.2.5]
+/// CompoundLiteralExpr - [C99 6.5.2.5, C23 6.5.3.6]
 ///
 class CompoundLiteralExpr : public Expr {
   /// LParenLoc - If non-null, this is the location of the left paren in a
@@ -3687,11 +3686,20 @@ class CompoundLiteralExpr : public Expr {
   mutable APValue *StaticValue = nullptr;
 
 public:
-  CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
-                      QualType T, ExprValueKind VK, Expr *init, bool fileScope)
+  CompoundLiteralExpr(
+      SourceLocation LParenLoc, TypeSourceInfo *TInfo, QualType T,
+      ExprValueKind VK, Expr *Init, bool IsFileScope, StorageClass SC = SC_None,
+      ThreadStorageClassSpecifier TSC = TSCS_unspecified,
+      ConstexprSpecKind ConstexprKind = ConstexprSpecKind::Unspecified)
       : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary),
-        LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) {
+        LParenLoc(LParenLoc), TInfoAndScope(TInfo, IsFileScope), Init(Init) {
     assert(Init && "Init is a nullptr");
+    assert((ConstexprKind == ConstexprSpecKind::Unspecified ||
+            ConstexprKind == ConstexprSpecKind::Constexpr) &&
+           "invalid compound literal constexpr specifier");
+    setStorageClass(SC);
+    setTSCSpec(TSC);
+    setConstexpr(ConstexprKind == ConstexprSpecKind::Constexpr);
     setDependence(computeDependence(this));
   }
 
@@ -3712,11 +3720,52 @@ class CompoundLiteralExpr : public Expr {
   TypeSourceInfo *getTypeSourceInfo() const {
     return TInfoAndScope.getPointer();
   }
-  void setTypeSourceInfo(TypeSourceInfo *tinfo) {
-    TInfoAndScope.setPointer(tinfo);
+
+  void setTypeSourceInfo(TypeSourceInfo *TInfo) {
+    TInfoAndScope.setPointer(TInfo);
+  }
+
+  bool hasStaticStorage() const {
+    return isGLValue() && !hasThreadStorage() &&
+           (isFileScope() || getStorageClass() == SC_Static);
+  }
+
+  bool hasThreadStorage() const { return getTSCSpec() != TSCS_unspecified; }
+
+  bool hasGlobalStorage() const {
+    return hasStaticStorage() || hasThreadStorage();
+  }
+
+  StorageClass getStorageClass() const {
+    return static_cast<StorageClass>(CompoundLiteralExprBits.SClass);
+  }
+
+  void setStorageClass(StorageClass SC) {
+    assert((SC == SC_None || SC == SC_Static || SC == SC_Register) &&
+           "invalid compound literal storage class");
+    CompoundLiteralExprBits.SClass = SC;
+    assert(getStorageClass() == SC && "truncation");
+  }
+
+  ThreadStorageClassSpecifier getTSCSpec() const {
+    return static_cast<ThreadStorageClassSpecifier>(
+        CompoundLiteralExprBits.TSCSpec);
+  }
+
+  void setTSCSpec(ThreadStorageClassSpecifier TSC) {
+    assert((TSC == TSCS_unspecified || TSC == TSCS___thread ||
+            TSC == TSCS_thread_local || TSC == TSCS__Thread_local) &&
+           "invalid compound literal thread storage class");
+    CompoundLiteralExprBits.TSCSpec = TSC;
+    assert(getTSCSpec() == TSC && "truncation");
+  }
+
+  bool isConstexpr() const { return CompoundLiteralExprBits.IsConstexpr; }
+
+  void setConstexpr(bool IsConstexpr) {
+    CompoundLiteralExprBits.IsConstexpr = IsConstexpr;
   }
 
-  bool hasStaticStorage() const { return isFileScope() && isGLValue(); }
   APValue &getOrCreateStaticValue(ASTContext &Ctx) const;
   APValue &getStaticValue() const;
 
diff --git a/clang/include/clang/AST/Stmt.h b/clang/include/clang/AST/Stmt.h
index 3bc56f427d439c..9f42cf023fc2ef 100644
--- a/clang/include/clang/AST/Stmt.h
+++ b/clang/include/clang/AST/Stmt.h
@@ -667,6 +667,22 @@ class alignas(void *) Stmt {
     SourceLocation OpLoc;
   };
 
+  class CompoundLiteralExprBitfields {
+    friend class CompoundLiteralExpr;
+
+    LLVM_PREFERRED_TYPE(ExprBitfields)
+    unsigned : NumExprBits;
+
+    LLVM_PREFERRED_TYPE(StorageClass)
+    unsigned SClass : 3;
+
+    LLVM_PREFERRED_TYPE(ThreadStorageClassSpecifier)
+    unsigned TSCSpec : 2;
+
+    LLVM_PREFERRED_TYPE(bool)
+    unsigned IsConstexpr : 1;
+  };
+
   class InitListExprBitfields {
     friend class ASTStmtReader;
     friend class InitListExpr;
@@ -1365,6 +1381,7 @@ class alignas(void *) Stmt {
     MemberExprBitfields MemberExprBits;
     CastExprBitfields CastExprBits;
     BinaryOperatorBitfields BinaryOperatorBits;
+    CompoundLiteralExprBitfields CompoundLiteralExprBits;
     InitListExprBitfields InitListExprBits;
     ParenListExprBitfields ParenListExprBits;
     GenericSelectionExprBitfields GenericSelectionExprBits;
diff --git a/clang/include/clang/Basic/DiagnosticASTKinds.td b/clang/include/clang/Basic/DiagnosticASTKinds.td
index e9834cca42091b..1a38a2e45c333d 100644
--- a/clang/include/clang/Basic/DiagnosticASTKinds.td
+++ b/clang/include/clang/Basic/DiagnosticASTKinds.td
@@ -9,6 +9,11 @@
 let Component = "AST" in {
 
 // Constant expression diagnostics. These (and their users) belong in Sema.
+def note_constexpr_non_constexpr_compound_literal : Note<
+  "read of a non-constexpr compound literal is not allowed in a constant expression">;
+def ext_constexpr_compound_literal : Extension<
+  "reading a non-constexpr compound literal in a constant expression is a GNU extension">,
+  InGroup<GNUFoldingConstant>;
 def note_expr_divide_by_zero : Note<"division by zero">;
 def note_constexpr_invalid_cast : Note<
   "%enum_select<ConstexprInvalidCastKind>{%Reinterpret{reinterpret_cast}|%Dynamic{dynamic_cast}|"
diff --git a/clang/include/clang/Basic/DiagnosticParseKinds.td b/clang/include/clang/Basic/DiagnosticParseKinds.td
index 2be6ff8344cd6d..197bf4899bd898 100644
--- a/clang/include/clang/Basic/DiagnosticParseKinds.td
+++ b/clang/include/clang/Basic/DiagnosticParseKinds.td
@@ -244,6 +244,10 @@ def warn_c11_compat_keyword : Warning<
 def warn_c23_compat_keyword : Warning<
  "'%0' is incompatible with C standards before C23">,
  InGroup<CPre23Compat>, DefaultIgnore;
+def warn_c23_compat_compound_literal_storage_class : Warning<
+  "compound literal storage-class specifiers are incompatible with C "
+  "standards before C23">,
+  InGroup<CPre23Compat>, DefaultIgnore;
 def warn_c2y_compat_keyword : Warning<
   "'%0' is incompatible with C standards before C2y">,
   InGroup<CPre2yCompat>, DefaultIgnore;
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 56cc9721781063..532b65db653e74 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -2506,7 +2506,8 @@ def err_init_conversion_failed : Error<
   "base class|a constructor delegation|a vector element|a matrix element|a "
   "block element|a block element|a complex element|a lambda capture|a compound"
   " literal initializer|a related result|a parameter of CF audited function|a "
-  "structured binding|a member subobject}0 "
+  "structured binding|a member subobject|a constexpr compound literal "
+  "initializer}0 "
   "%diff{of type $ with an %select{rvalue|lvalue}2 of type $|"
   "with an %select{rvalue|lvalue}2 of incompatible type}1,3"
   "%select{|: different classes%diff{ ($ vs $)|}5,6"
@@ -3201,6 +3202,13 @@ def err_c23_constexpr_init_type_mismatch : Error<
   "constexpr initializer for type %0 is of type %1">;
 def err_c23_constexpr_pointer_not_null : Error<
   "constexpr pointer initializer is not null">;
+def err_register_compound_literal_file_scope : Error<
+  "file scope compound literal specifies 'register'">;
+def err_thread_local_compound_literal_without_static : Error<
+  "compound literal with 'thread_local' storage duration at block scope must "
+  "also specify 'static'">;
+def err_compound_literal_initializer_not_constant : Error<
+  "initializer of compound literal must be a constant expression">;
 
 // C++ Concepts
 def err_concept_decls_may_only_appear_in_global_namespace_scope : Error<
@@ -3789,9 +3797,10 @@ def err_attr_codemodel_arg : Error<"code model '%0' is not supported on this tar
 
 def err_aix_attr_unsupported : Error<"%0 attribute is not yet supported on AIX">;
 
-def err_tls_var_aligned_over_maximum : Error<
-  "alignment (%0) of thread-local variable %1 is greater than the maximum supported "
-  "alignment (%2) for a thread-local variable on this target">;
+def err_tls_aligned_over_maximum : Error<
+  "alignment (%0) of thread-local %select{variable %3|compound literal}1 is "
+  "greater than the maximum supported alignment (%2) for "
+  "%select{a thread-local variable|thread-local storage}1 on this target">;
 
 def err_only_annotate_after_access_spec : Error<
   "access specifier can only have annotation attributes">;
@@ -7982,7 +7991,8 @@ def err_typecheck_sclass_func : Error<"illegal storage class on function">;
 def err_static_block_func : Error<
   "function declared in block scope cannot have 'static' storage class">;
 def err_typecheck_address_of : Error<"address of %select{bit-field"
-  "|vector element|property expression|register variable|matrix element}0 requested">;
+  "|vector element|property expression|register variable|matrix element"
+  "|register compound literal}0 requested">;
 def ext_typecheck_addrof_void : Extension<
   "ISO C forbids taking the address of an expression of type 'void'">;
 def err_unqualified_pointer_member_function : Error<
diff --git a/clang/include/clang/Parse/Parser.h b/clang/include/clang/Parse/Parser.h
index b19f0ed880ddfe..c80594248579e6 100644
--- a/clang/include/clang/Parse/Parser.h
+++ b/clang/include/clang/Parse/Parser.h
@@ -1898,6 +1898,11 @@ class Parser : public CodeCompletionHandler {
   /// DeclaratorContext enumerator values.
   DeclSpecContext
   getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context);
+
+  enum class StorageClassSpecifierContext { Declaration, CompoundLiteral };
+  void ParseStorageClassSpecifier(DeclSpec &DS,
+                                  StorageClassSpecifierContext Context);
+
   void
   ParseDeclarationSpecifiers(DeclSpec &DS, ParsedTemplateInfo &TemplateInfo,
                              AccessSpecifier AS = AS_none,
@@ -4316,7 +4321,8 @@ class Parser : public CodeCompletionHandler {
   /// \endverbatim
   ExprResult ParseCompoundLiteralExpression(ParsedType Ty,
                                             SourceLocation LParenLoc,
-                                            SourceLocation RParenLoc);
+                                            SourceLocation RParenLoc,
+                                            const DeclSpec *DS = nullptr);
 
   /// ParseGenericSelectionExpression - Parse a C11 generic-selection
   /// [C11 6.5.1.1].
@@ -5126,6 +5132,10 @@ class Parser : public CodeCompletionHandler {
     return isTypeIdInParens(isAmbiguous);
   }
 
+  bool isCompoundLiteralStorageClassSpecifier() const;
+  bool isTypeIdInParensWithStorageClassSpecifiers();
+  void ParseCompoundLiteralStorageClassSpecifiers(DeclSpec &DS);
+
   /// Finish parsing a C++ unqualified-id that is a template-id of
   /// some form.
   ///
diff --git a/clang/include/clang/Sema/DelayedDiagnostic.h b/clang/include/clang/Sema/DelayedDiagnostic.h
index 0105089a393f17..914fb2d6bc370b 100644
--- a/clang/include/clang/Sema/DelayedDiagnostic.h
+++ b/clang/include/clang/Sema/DelayedDiagnostic.h
@@ -125,7 +125,12 @@ class AccessedEntity {
 /// the complete parsing of the current declaration.
 class DelayedDiagnostic {
 public:
-  enum DDKind : unsigned char { Availability, Access, ForbiddenType };
+  enum DDKind : unsigned char {
+    Availability,
+    Access,
+    ForbiddenType,
+    ForbiddenStatic
+  };
 
   DDKind Kind;
   bool Triggered;
@@ -167,6 +172,14 @@ class DelayedDiagnostic {
     return DD;
   }
 
+  static DelayedDiagnostic makeForbiddenStatic(SourceLocation Loc) {
+    DelayedDiagnostic DD;
+    DD.Kind = ForbiddenStatic;
+    DD.Triggered = false;
+    DD.Loc = Loc;
+    return DD;
+  }
+
   AccessedEntity &getAccessData() {
     assert(Kind == Access && "Not an access diagnostic.");
     return *reinterpret_cast<AccessedEntity*>(AccessData);
diff --git a/clang/include/clang/Sema/Initialization.h b/clang/include/clang/Sema/Initialization.h
index 2c2df1f03747b3..b338151cded83f 100644
--- a/clang/include/clang/Sema/Initialization.h
+++ b/clang/include/clang/Sema/Initialization.h
@@ -131,6 +131,9 @@ class alignas(8) InitializedEntity {
     /// object initialized via parenthesized aggregate initialization.
     EK_ParenAggInitMember,
 
+    /// The entity initialized by a constexpr compound literal.
+    EK_ConstexprCompoundLiteralInit,
+
     // Note: err_init_conversion_failed in DiagnosticSemaKinds.td uses this
     // enum as an index for its first %select.  When modifying this list,
     // that diagnostic text needs to be updated as well.
@@ -216,8 +219,8 @@ class alignas(8) InitializedEntity {
     /// integer indicating whether the parameter is "consumed".
     llvm::PointerIntPair<ParmVarDecl *, 1> Parameter;
 
-    /// When Kind == EK_Temporary or EK_CompoundLiteralInit, the type
-    /// source information for the temporary.
+    /// When Kind is EK_Temporary, EK_CompoundLiteralInit, or
+    /// EK_ConstexprCompoundLiteralInit, the type source information.
     TypeSourceInfo *TypeInfo;
 
     struct LN LocAndNRVO;
@@ -465,13 +468,21 @@ class alignas(8) InitializedEntity {
   }
 
   /// Create the entity for a compound literal initializer.
-  static InitializedEntity InitializeCompoundLiteralInit(TypeSourceInfo *TSI) {
-    InitializedEntity Result(EK_CompoundLiteralInit, SourceLocation(),
-                             TSI->getType());
+  static InitializedEntity
+  InitializeCompoundLiteralInit(TypeSourceInfo *TSI, QualType Type,
+                                ConstexprSpecKind ConstexprKind) {
+    InitializedEntity Result(ConstexprKind == ConstexprSpecKind::Constexpr
+                                 ? EK_ConstexprCompoundLiteralInit
+                                 : EK_CompoundLiteralInit,
+                             SourceLocation(), Type);
     Result.TypeInfo = TSI;
     return Result;
   }
 
+  bool isConstexprCompoundLiteral() const {
+    return Kind == EK_ConstexprCompoundLiteralInit;
+  }
+
   /// Determine the kind of initialization.
   EntityKind getKind() const { return Kind; }
 
@@ -486,7 +497,8 @@ class alignas(8) InitializedEntity {
   /// Retrieve complete type-source information for the object being
   /// constructed, if known.
   TypeSourceInfo *getTypeSourceInfo() const {
-    if (Kind == EK_Temporary || Kind == EK_CompoundLiteralInit)
+    if (Kind == EK_Temporary || Kind == EK_CompoundLiteralInit ||
+        Kind == EK_ConstexprCompoundLiteralInit)
       return TypeInfo;
 
     return nullptr;
diff --git a/clang/include/clang/Sema/Scope.h b/clang/include/clang/Sema/Scope.h
index 58ca2c0738f3c7..4f69a18fb72a58 100644
--- a/clang/include/clang/Sema/Scope.h
+++ b/clang/include/clang/Sema/Scope.h
@@ -632,8 +632,10 @@ class Scope {
   /// loops where the condition follows the loop body.
   void LeaveLoopBody();
 
-  /// containedInPrototypeScope - Return true if this or a parent scope
-  /// is a FunctionPrototypeScope.
+  /// Return the innermost function prototype scope containing this scope.
+  const Scope *getEnclosingFunctionPrototypeScope() const;
+
+  /// Return true if this or a parent scope is a function prototype scope.
   bool containedInPrototypeScope() const;
 
   void PushUsingDirective(UsingDirectiveDecl *UDir) {
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index ba215e7e18d7ba..141b36a710ce92 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -4133,6 +4133,10 @@ class Sema final : public SemaBase {
                                      ArrayRef<BindingDecl *> Bindings = {});
 
 private:
+  /// Maps a DeclSpec::SCS to a VarDecl::StorageClass. Any error reporting is up
+  /// to the caller; illegal input values are mapped to SC_None.
+  static StorageClass StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS);
+
   // Perform a check on an AsmLabel to verify its consistency and emit
   // diagnostics in case of an error.
   void CheckAsmLabel(Scope *S, Expr *AsmLabelExpr, StorageClass SC,
@@ -4153,6 +4157,8 @@ class Sema final : public SemaBase {
   /// Returns true if the variable declaration is a redeclaration.
   bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
   void CheckVariableDeclarationType(VarDecl *NewVD);
+  bool CheckConstexprType(SourceLocation Loc, QualType T);
+  void DiagnoseStaticInInline(SourceLocation Loc, const FunctionDecl *FD);
   void CheckCompleteVariableDeclaration(VarDecl *VD);
 
   NamedDecl *ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
@@ -7649,13 +7655,23 @@ class Sema final : public SemaBase {
   /// the ParenListExpr into a sequence of comma binary operators.
   ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
 
-  ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
-                                  SourceLocation RParenLoc, Expr *InitExpr);
+private:
+  ExprResult BuildCompoundLiteralExpr(
+      SourceLocation LParenLoc, TypeSourceInfo *TInfo, SourceLocation RParenLoc,
+      Expr *LiteralExpr, StorageClass SC, SourceLocation StorageClassLoc,
+      ThreadStorageClassSpecifier TSC, SourceLocation ThreadStorageClassLoc,
+      ConstexprSpecKind ConstexprKind, SourceLocation ConstexprLoc);
 
-  ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
-                                      TypeSourceInfo *TInfo,
-                                      SourceLocation RParenLoc,
-                                      Expr *LiteralExpr);
+public:
+  ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
+                                  SourceLocation RParenLoc, Expr *InitExpr,
+                                  const DeclSpec *DS = nullptr);
+
+  ExprResult BuildCompoundLiteralExpr(
+      SourceLocation LParenLoc, TypeSourceInfo *TInfo, SourceLocation RParenLoc,
+      Expr *LiteralExpr, StorageClass SC = SC_None,
+      ThreadStorageClassSpecifier TSC = TSCS_unspecified,
+      ConstexprSpecKind ConstexprKind = ConstexprSpecKind::Unspecified);
 
   ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
                            SourceLocation RBraceLoc);
diff --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp
index a9e45c2b8c56b5..167c2e3dfb3e6e 100644
--- a/clang/lib/AST/ASTImporter.cpp
+++ b/clang/lib/AST/ASTImporter.cpp
@@ -8010,8 +8010,10 @@ ExpectedStmt ASTNodeImporter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
     return std::move(Err);
 
   return new (Importer.getToContext()) CompoundLiteralExpr(
-        ToLParenLoc, ToTypeSourceInfo, ToType, E->getValueKind(),
-        ToInitializer, E->isFileScope());
+      ToLParenLoc, ToTypeSourceInfo, ToType, E->getValueKind(), ToInitializer,
+      E->isFileScope(), E->getStorageClass(), E->getTSCSpec(),
+      E->isConstexpr() ? ConstexprSpecKind::Constexpr
+                       : ConstexprSpecKind::Unspecified);
 }
 
 ExpectedStmt ASTNodeImporter::VisitAtomicExpr(AtomicExpr *E) {
diff --git a/clang/lib/AST/ASTStructuralEquivalence.cpp b/clang/lib/AST/ASTStructuralEquivalence.cpp
index cd0b03c5cc356d..f7abbc0077249e 100644
--- a/clang/lib/AST/ASTStructuralEquivalence.cpp
+++ b/clang/lib/AST/ASTStructuralEquivalence.cpp
@@ -211,6 +211,14 @@ class StmtComparer {
     return true; // Semantics only depend on children.
   }
 
+  bool IsStmtEquivalent(const CompoundLiteralExpr *E1,
+                        const CompoundLiteralExpr *E2) {
+    return E1->isFileScope() == E2->isFileScope() &&
+           E1->getStorageClass() == E2->getStorageClass() &&
+           E1->getTSCSpec() == E2->getTSCSpec() &&
+           E1->isConstexpr() == E2->isConstexpr();
+  }
+
   bool IsStmtEquivalent(const CompoundStmt *E1, const CompoundStmt *E2) {
     // Number of children is actually checked by the generic children comparison
     // code, but a CompoundStmt is one of the few statements where the number of
diff --git a/clang/lib/AST/ByteCode/Compiler.cpp b/clang/lib/AST/ByteCode/Compiler.cpp
index 71f761f58aed28..4728b602d9fbe2 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -3701,6 +3701,9 @@ bool Compiler<Emitter>::VisitCXXBindTemporaryExpr(
 template <class Emitter>
 bool Compiler<Emitter>::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
   const Expr *Init = E->getInitializer();
+  if (E->hasThreadStorage())
+    return this->emitInvalid(E);
+
   if (DiscardResult)
     return this->discard(Init);
 
@@ -3710,7 +3713,7 @@ bool Compiler<Emitter>::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
   }
 
   OptPrimType T = classify(E->getType());
-  if (E->isFileScope()) {
+  if (E->hasGlobalStorage()) {
     // Avoid creating a variable if this is a primitive RValue anyway.
     if (T && !E->isLValue())
       return this->delegate(Init);
@@ -3722,9 +3725,9 @@ bool Compiler<Emitter>::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
     if (!this->emitGetPtrGlobal(*GlobalIndex, E))
       return false;
 
-    // Since this is a global variable, we might've already seen,
-    // don't do it again.
-    if (P.isGlobalInitialized(*GlobalIndex))
+    // An ordinary C23 literal may have been folded for static initialization.
+    if (P.isGlobalInitialized(*GlobalIndex) &&
+        (!Ctx.getLangOpts().C23 || E->isConstexpr()))
       return true;
 
     if (T) {
@@ -3744,8 +3747,8 @@ bool Compiler<Emitter>::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
 
   unsigned LocalIndex;
   if (T)
-    LocalIndex = this->allocateLocalPrimitive(Init, *T, /*IsConst=*/false);
-  else if (UnsignedOrNone MaybeIndex = this->allocateLocal(Init))
+    LocalIndex = this->allocateLocalPrimitive(E, *T, /*IsConst=*/false);
+  else if (UnsignedOrNone MaybeIndex = this->allocateLocal(E))
     LocalIndex = *MaybeIndex;
   else
     return false;
diff --git a/clang/lib/AST/ByteCode/Interp.cpp b/clang/lib/AST/ByteCode/Interp.cpp
index 4d3ee95df216c0..8fc3f41d0d64df 100644
--- a/clang/lib/AST/ByteCode/Interp.cpp
+++ b/clang/lib/AST/ByteCode/Interp.cpp
@@ -521,10 +521,30 @@ bool CheckLive(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
   return true;
 }
 
+static bool CheckConstexprObject(InterpState &S, CodePtr OpPC,
+                                 const Descriptor *Desc) {
+  if (!S.getLangOpts().C23 || S.EvalMode != EvaluationMode::ConstantExpression)
+    return true;
+
+  if (const auto *VD = Desc->asVarDecl()) {
+    if (VD != S.EvaluatingDecl && !VD->isConstexpr())
+      return Invalid(S, OpPC);
+  } else if (const auto *CLE =
+                 dyn_cast_if_present<CompoundLiteralExpr>(Desc->asExpr())) {
+    if (!CLE->isConstexpr())
+      S.CCEDiag(S.Current->getSource(OpPC),
+                diag::note_constexpr_non_constexpr_compound_literal);
+  }
+  return true;
+}
+
 bool CheckConstant(InterpState &S, CodePtr OpPC, const Descriptor *Desc,
                    AccessKinds AK) {
   assert(Desc);
 
+  if (!CheckConstexprObject(S, OpPC, Desc))
+    return false;
+
   const auto *D = Desc->asVarDecl();
   if (S.checkingConstantDestruction(D)) {
     // If we're checking for a constant destructor for this variable, we can
@@ -534,13 +554,6 @@ bool CheckConstant(InterpState &S, CodePtr OpPC, const Descriptor *Desc,
   } else if (!D || D == S.EvaluatingDecl || D->isConstexpr())
     return true;
 
-  // If we're evaluating the initializer for a constexpr variable in C23, we may
-  // only read other contexpr variables. Abort here since this one isn't
-  // constexpr.
-  if (const auto *VD = S.EvaluatingDecl;
-      VD && VD->isConstexpr() && S.getLangOpts().C23)
-    return Invalid(S, OpPC);
-
   QualType T = D->getType();
   bool IsConstant = T.isConstant(S.getASTContext());
   if (T->isIntegralOrEnumerationType()) {
@@ -596,10 +609,8 @@ static bool CheckConstant(InterpState &S, CodePtr OpPC, PtrView Ptr,
   if (S.checkingConstantDestruction(Ptr.getDeclDesc()->asVarDecl()))
     return CheckConstant(S, OpPC, Ptr.getDeclDesc(), AK);
 
-  if (!Ptr.block()->isStatic())
-    return true;
-  if (!Ptr.block()->getDeclID())
-    return true;
+  if (!Ptr.block()->isStatic() || !Ptr.block()->getDeclID())
+    return CheckConstexprObject(S, OpPC, Ptr.getDeclDesc());
   return CheckConstant(S, OpPC, Ptr.getDeclDesc(), AK);
 }
 
@@ -902,6 +913,8 @@ bool CheckLocalLoad(InterpState &S, CodePtr OpPC, const Block *B) {
   assert(!B->isExtern());
   const auto &Desc = *reinterpret_cast<const InlineDescriptor *>(B->rawData());
   const Descriptor *BlockDesc = B->getDescriptor();
+  if (!CheckConstexprObject(S, OpPC, BlockDesc))
+    return false;
   if (!Desc.IsInitialized)
     return diagnoseUninitialized(S, OpPC, /*Extern=*/false, B, Desc.LifeState);
   if (!CheckLifetime(S, OpPC, Desc.LifeState, B, AK_Read))
@@ -980,7 +993,7 @@ bool CheckLoad(InterpState &S, CodePtr OpPC, PtrView Ptr, AccessKinds AK) {
   if (isConstexprUnknown(Ptr.block()))
     return false;
 
-  if (!Ptr.isArrayRoot()) {
+  if (Ptr.block()->isStatic() && !Ptr.isArrayRoot()) {
     // According to GCC info page:
     //
     // 6.28 Compound Literals
@@ -3739,7 +3752,8 @@ bool Memcpy(InterpState &S, CodePtr OpPC) {
       Src.inUnion()) {
     if (!CheckLoad(S, OpPC, Src))
       return false;
-  }
+  } else if (!CheckConstexprObject(S, OpPC, Src.getDeclDesc()))
+    return false;
 
   return DoMemcpy(S, OpPC, Src, Dest);
 }
diff --git a/clang/lib/AST/ByteCode/State.cpp b/clang/lib/AST/ByteCode/State.cpp
index 1fc6ea8e6d6a17..bd65bae05fbcc6 100644
--- a/clang/lib/AST/ByteCode/State.cpp
+++ b/clang/lib/AST/ByteCode/State.cpp
@@ -18,6 +18,13 @@ using namespace clang::interp;
 State::~State() {}
 
 bool State::emitRelaxedDiag(SourceLocation Loc, diag::kind DiagId) {
+  // C23 6.6p14 permits additional forms of constant expressions.
+  if (Ctx.getLangOpts().C23 &&
+      DiagId == diag::note_constexpr_non_constexpr_compound_literal) {
+    addExtendedDiag(Loc, diag::ext_constexpr_compound_literal);
+    return true;
+  }
+
   if (!Ctx.getLangOpts().MSVCCompat ||
       (!EvalStatus.ExtendedDiag && !InConstantContext))
     return false;
diff --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index 1ba2ccdf697f9d..3866909111baf1 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -3444,8 +3444,14 @@ bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef,
     // This handles gcc's extension that allows global initializers like
     // "struct x {int x;} x = (struct x) {};".
     // FIXME: This accepts other cases it shouldn't!
-    const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
-    return Exp->isConstantInitializer(Ctx, false, Culprit);
+    const auto *CLE = cast<CompoundLiteralExpr>(this);
+    // A constant initializer cannot access a thread-local lvalue.
+    if (CLE->hasThreadStorage()) {
+      if (Culprit)
+        *Culprit = this;
+      return false;
+    }
+    return CLE->getInitializer()->isConstantInitializer(Ctx, false, Culprit);
   }
   case DesignatedInitUpdateExprClass: {
     const DesignatedInitUpdateExpr *DIUE = cast<DesignatedInitUpdateExpr>(this);
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 57d5bb475d0f9b..3c69a71e9c3533 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -2045,7 +2045,7 @@ bool isGlobalLValue(const ValueDecl *D, const Expr *E) {
     return false;
   case Expr::CompoundLiteralExprClass: {
     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
-    return CLE->isFileScope() && CLE->isLValue();
+    return CLE->hasStaticStorage() && CLE->isLValue();
   }
   case Expr::MaterializeTemporaryExprClass:
     // A materialized temporary might have been lifetime-extended to static
@@ -4743,7 +4743,6 @@ static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
   }
 
   bool IsAccess = isAnyAccess(AK);
-
   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
   // is not a constant expression (even if the object is non-volatile). We also
   // apply this rule to C++98, in order to conform to the expected 'volatile'
@@ -4821,11 +4820,6 @@ static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
     }
 
     bool IsConstant = BaseType.isConstant(Info.Ctx);
-    bool ConstexprVar = false;
-    if (const auto *VD = dyn_cast_if_present<VarDecl>(
-            Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
-      ConstexprVar = VD->isConstexpr();
-
     // Unless we're looking at a local variable or argument in a constexpr call,
     // the variable we're reading must be const (unless we are binding to a
     // reference).
@@ -4845,7 +4839,8 @@ static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
         return CompleteObject();
       } else if (VD->isConstexpr()) {
         // OK, we can read this variable.
-      } else if (Info.getLangOpts().C23 && ConstexprVar) {
+      } else if (Info.getLangOpts().C23 &&
+                 Info.EvalMode == EvaluationMode::ConstantExpression) {
         Info.FFDiag(E);
         return CompleteObject();
       } else if (VD->isCXXForRangeImplicitVar()) {
@@ -4930,6 +4925,15 @@ static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
   else if (AK != clang::AK_Dereference) {
     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
 
+    if (Info.getLangOpts().C23 &&
+        Info.EvalMode == EvaluationMode::ConstantExpression &&
+        (AK == AK_Read || AK == AK_ReadObjectRepresentation)) {
+      if (const auto *CLE = dyn_cast_or_null<CompoundLiteralExpr>(Base);
+          CLE && !CLE->isConstexpr()) {
+        Info.CCEDiag(E, diag::note_constexpr_non_constexpr_compound_literal);
+      }
+    }
+
     if (!Frame) {
       if (const MaterializeTemporaryExpr *MTE =
               dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
@@ -9901,6 +9905,12 @@ bool
 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
          "lvalue compound literal in c++?");
+  // A thread-local lvalue cannot be the result of constant evaluation.
+  if (E->hasThreadStorage()) {
+    Info.FFDiag(E);
+    return false;
+  }
+
   APValue *Lit;
   // If CompountLiteral has static storage, its value can be used outside
   // this expression. So evaluate it once and store it in ASTContext.
@@ -22671,11 +22681,11 @@ static bool doEvaluateInitializer(const ASTContext &Ctx, SemaProxy *SProxy,
          "Expression evaluator can't be called on a dependent expression.");
   assert(VD && "Need a valid VarDecl");
 
-  EvaluationMode EvalMode =
-      (IsConstantInitialization &&
-       (Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23))
-          ? EvaluationMode::ConstantExpression
-          : EvaluationMode::ConstantFold;
+  EvaluationMode EvalMode = (IsConstantInitialization &&
+                             (Ctx.getLangOpts().CPlusPlus ||
+                              (Ctx.getLangOpts().C23 && VD->isConstexpr())))
+                                ? EvaluationMode::ConstantExpression
+                                : EvaluationMode::ConstantFold;
 
   if (Ctx.getLangOpts().EnableNewConstInterp) {
     interp::EvalSettings Settings(EvalMode, EStatus, SProxy);
@@ -23008,6 +23018,21 @@ static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
   return NoDiag();
 }
 
+static bool isConstexprConstant(const Expr *E) {
+  E = E->IgnoreParenImpCasts();
+  while (const auto *ME = dyn_cast<MemberExpr>(E)) {
+    if (ME->isArrow())
+      return false;
+    E = ME->getBase()->IgnoreParenImpCasts();
+  }
+  if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
+    const auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
+    return VD && VD->isConstexpr();
+  }
+  const auto *CLE = dyn_cast<CompoundLiteralExpr>(E);
+  return CLE && CLE->isConstexpr();
+}
+
 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
   if (!E->getType()->isIntegralOrEnumerationType())
@@ -23018,6 +23043,13 @@ static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
 #define STMT(Node, Base) case Expr::Node##Class:
 #define EXPR(Node, Base)
 #include "clang/AST/StmtNodes.inc"
+  case Expr::CompoundLiteralExprClass: {
+    const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
+    if (CLE->isConstexpr())
+      return CheckEvalInICE(E, Ctx);
+    return ICEDiag(IK_NotICE, E->getBeginLoc());
+  }
+
   case Expr::PredefinedExprClass:
   case Expr::FloatingLiteralClass:
   case Expr::ImaginaryLiteralClass:
@@ -23029,7 +23061,6 @@ static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
   case Expr::OMPArrayShapingExprClass:
   case Expr::OMPIteratorExprClass:
   case Expr::CompoundAssignOperatorClass:
-  case Expr::CompoundLiteralExprClass:
   case Expr::ExtVectorElementExprClass:
   case Expr::MatrixElementExprClass:
   case Expr::DesignatedInitExprClass:
@@ -23108,20 +23139,8 @@ static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
     return ICEDiag(IK_NotICE, E->getBeginLoc());
 
   case Expr::MemberExprClass: {
-    if (Ctx.getLangOpts().C23) {
-      const Expr *ME = E->IgnoreParenImpCasts();
-      while (const auto *M = dyn_cast<MemberExpr>(ME)) {
-        if (M->isArrow())
-          return ICEDiag(IK_NotICE, E->getBeginLoc());
-        ME = M->getBase()->IgnoreParenImpCasts();
-      }
-      const auto *DRE = dyn_cast<DeclRefExpr>(ME);
-      if (DRE) {
-        if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
-            VD && VD->isConstexpr())
-          return CheckEvalInICE(E, Ctx);
-      }
-    }
+    if (Ctx.getLangOpts().C23 && isConstexprConstant(E))
+      return CheckEvalInICE(E, Ctx);
     return ICEDiag(IK_NotICE, E->getBeginLoc());
   }
 
@@ -23360,8 +23379,8 @@ static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
   case Expr::ObjCBridgedCastExprClass: {
     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
     if (isa<ExplicitCastExpr>(E)) {
-      if (const FloatingLiteral *FL
-            = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
+      const Expr *Sub = SubExpr->IgnoreParenImpCasts();
+      if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(Sub)) {
         unsigned DestWidth = Ctx.getIntWidth(E->getType());
         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
         APSInt IgnoredVal(DestWidth, !DestSigned);
@@ -23375,6 +23394,9 @@ static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
           return ICEDiag(IK_NotICE, E->getBeginLoc());
         return NoDiag();
       }
+      if (Ctx.getLangOpts().C23 && Sub->getType()->isArithmeticType() &&
+          isConstexprConstant(Sub))
+        return CheckEvalInICE(E, Ctx);
     }
     switch (cast<CastExpr>(E)->getCastKind()) {
     case CK_LValueToRValue:
diff --git a/clang/lib/AST/StmtPrinter.cpp b/clang/lib/AST/StmtPrinter.cpp
index 4f184868659f48..63eb4556d563cf 100644
--- a/clang/lib/AST/StmtPrinter.cpp
+++ b/clang/lib/AST/StmtPrinter.cpp
@@ -1925,7 +1925,29 @@ void StmtPrinter::VisitCStyleCastExpr(CStyleCastExpr *Node) {
 
 void StmtPrinter::VisitCompoundLiteralExpr(CompoundLiteralExpr *Node) {
   OS << '(';
-  Node->getType().print(OS, Policy);
+  if (Node->getStorageClass() == SC_Static)
+    OS << "static ";
+  else if (Node->getStorageClass() == SC_Register)
+    OS << "register ";
+  switch (Node->getTSCSpec()) {
+  case TSCS_thread_local:
+    OS << "thread_local ";
+    break;
+  case TSCS__Thread_local:
+    OS << "_Thread_local ";
+    break;
+  case TSCS___thread:
+    OS << "__thread ";
+    break;
+  case TSCS_unspecified:
+    break;
+  }
+  QualType T = Node->getType();
+  if (Node->isConstexpr()) {
+    T = Node->getTypeSourceInfo()->getType();
+    OS << "constexpr ";
+  }
+  T.print(OS, Policy);
   OS << ')';
   PrintExpr(Node->getInitializer());
 }
diff --git a/clang/lib/AST/StmtProfile.cpp b/clang/lib/AST/StmtProfile.cpp
index b24aaf2b9cc422..99ae2827bd54ef 100644
--- a/clang/lib/AST/StmtProfile.cpp
+++ b/clang/lib/AST/StmtProfile.cpp
@@ -1624,6 +1624,9 @@ void StmtProfiler::VisitMemberExpr(const MemberExpr *S) {
 void StmtProfiler::VisitCompoundLiteralExpr(const CompoundLiteralExpr *S) {
   VisitExpr(S);
   ID.AddBoolean(S->isFileScope());
+  ID.AddInteger(S->getStorageClass());
+  ID.AddInteger(S->getTSCSpec());
+  ID.AddBoolean(S->isConstexpr());
 }
 
 void StmtProfiler::VisitCastExpr(const CastExpr *S) {
diff --git a/clang/lib/CIR/CodeGen/CIRGenConstantEmitter.h b/clang/lib/CIR/CodeGen/CIRGenConstantEmitter.h
index 2591b53704a8d4..7484fe932816cb 100644
--- a/clang/lib/CIR/CodeGen/CIRGenConstantEmitter.h
+++ b/clang/lib/CIR/CodeGen/CIRGenConstantEmitter.h
@@ -69,6 +69,8 @@ class ConstantEmitter {
   mlir::Attribute tryEmitForInitializer(const VarDecl &d);
   mlir::Attribute tryEmitForInitializer(const Expr *e, QualType destType);
 
+  cir::GlobalOp tryEmitGlobalCompoundLiteral(const CompoundLiteralExpr *e);
+
   mlir::Attribute emitForInitializer(const APValue &value, QualType destType);
 
   void finalize(cir::GlobalOp gv);
diff --git a/clang/lib/CIR/CodeGen/CIRGenExpr.cpp b/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
index 2637266cf3feed..144c58fc3563f6 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
@@ -2182,14 +2182,28 @@ CIRGenFunction::getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e) {
 }
 
 LValue CIRGenFunction::emitCompoundLiteralLValue(const CompoundLiteralExpr *e) {
-  if (e->isFileScope()) {
-    cgm.errorNYI(e->getSourceRange(), "emitCompoundLiteralLValue: FileScope");
-    return {};
-  }
-
   if (e->getType()->isVariablyModifiedType())
     emitVariablyModifiedType(e->getType());
 
+  if (e->hasGlobalStorage()) {
+    ConstantEmitter emitter(*this);
+    cir::GlobalOp global = emitter.tryEmitGlobalCompoundLiteral(e);
+    if (!global) {
+      return makeNaturalAlignAddrLValue(
+          getUndefConstant(
+              getLoc(e->getSourceRange()),
+              builder.getPointerTo(convertTypeForMem(e->getType()))),
+          e->getType());
+    }
+
+    mlir::Value addr = builder.createGetGlobal(getLoc(e->getSourceRange()),
+                                               global, e->hasThreadStorage());
+    return makeAddrLValue(
+        Address(addr, global.getSymType(),
+                getContext().getTypeAlignInChars(e->getType())),
+        e->getType(), AlignmentSource::Decl);
+  }
+
   Address declPtr = createMemTemp(e->getType(), getLoc(e->getSourceRange()),
                                   ".compoundliteral");
   const Expr *initExpr = e->getInitializer();
diff --git a/clang/lib/CIR/CodeGen/CIRGenExprAggregate.cpp b/clang/lib/CIR/CodeGen/CIRGenExprAggregate.cpp
index ac186a5b58a38b..cd8651d75b322d 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExprAggregate.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExprAggregate.cpp
@@ -713,9 +713,8 @@ void AggExprEmitter::emitAggLoadOfLValue(const Expr *e) {
 }
 
 void AggExprEmitter::VisitCompoundLiteralExpr(CompoundLiteralExpr *e) {
-  if (dest.isPotentiallyAliased() && e->getType().isPODType(cgf.getContext())) {
-    // For a POD type, just emit a load of the lvalue + a copy, because our
-    // compound literal might alias the destination.
+  if (e->hasGlobalStorage() || (dest.isPotentiallyAliased() &&
+                                e->getType().isPODType(cgf.getContext()))) {
     emitAggLoadOfLValue(e);
     return;
   }
diff --git a/clang/lib/CIR/CodeGen/CIRGenExprConstant.cpp b/clang/lib/CIR/CodeGen/CIRGenExprConstant.cpp
index ad8034bfbae4e3..65fb395c32e09d 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExprConstant.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExprConstant.cpp
@@ -1020,48 +1020,51 @@ ConstantLValue ConstantLValueEmitter::VisitConstantExpr(const ConstantExpr *e) {
   return {};
 }
 
-static cir::GlobalViewAttr
-tryEmitGlobalCompoundLiteral(ConstantEmitter &emitter,
-                             const CompoundLiteralExpr *e) {
-  CIRGenModule &cgm = emitter.cgm;
-  CIRGenBuilderTy &builder = cgm.getBuilder();
+cir::GlobalOp
+ConstantEmitter::tryEmitGlobalCompoundLiteral(const CompoundLiteralExpr *e) {
   CharUnits align = cgm.getASTContext().getTypeAlignInChars(e->getType());
 
-  if (cir::GlobalOp addr = cgm.getAddrOfConstantCompoundLiteralIfEmitted(e))
-    return builder.getGlobalViewAttr(addr);
+  if (cir::GlobalOp global = cgm.getAddrOfConstantCompoundLiteralIfEmitted(e))
+    return global;
 
   assert(!cir::MissingFeatures::addressSpace());
-  mlir::Attribute c =
-      emitter.tryEmitForInitializer(e->getInitializer(), e->getType());
-  if (!c) {
-    assert(!e->isFileScope() &&
-           "file-scope compound literal did not have constant initializer!");
+  mlir::Attribute initializer =
+      tryEmitForInitializer(e->getInitializer(), e->getType());
+  if (!initializer) {
+    assert((!e->hasGlobalStorage() || cgm.getDiags().hasErrorOccurred()) &&
+           "global compound literal did not have constant initializer!");
     return {};
   }
 
-  auto typedInit = mlir::cast<mlir::TypedAttr>(c);
+  auto typedInitializer = mlir::cast<mlir::TypedAttr>(initializer);
   bool isConstant = e->getType().isConstantStorage(cgm.getASTContext(),
                                                    /*ExcludeCtor=*/true,
                                                    /*ExcludeDtor=*/false);
 
   std::string name = cgm.getUniqueGlobalName(".compoundliteral");
   mlir::Location loc = cgm.getLoc(e->getSourceRange());
-  cir::GlobalOp gv =
-      cgm.createGlobalOp(loc, name, typedInit.getType(), isConstant);
-  gv.setLinkage(cir::GlobalLinkageKind::InternalLinkage);
-  gv.setAlignment(align.getAsAlign().value());
-  CIRGenModule::setInitializer(gv, c);
-
-  emitter.finalize(gv);
-  cgm.setAddrOfConstantCompoundLiteral(e, gv);
-  return builder.getGlobalViewAttr(gv);
+  cir::GlobalOp global =
+      cgm.createGlobalOp(loc, name, typedInitializer.getType(), isConstant);
+  global.setLinkage(cir::GlobalLinkageKind::InternalLinkage);
+  global.setAlignment(align.getAsAlign().value());
+  if (e->hasThreadStorage())
+    global.setTlsModel(cgm.getDefaultCIRTLSModel());
+  CIRGenModule::setInitializer(global, initializer);
+
+  finalize(global);
+  cgm.setAddrOfConstantCompoundLiteral(e, global);
+  return global;
 }
 
 ConstantLValue
 ConstantLValueEmitter::VisitCompoundLiteralExpr(const CompoundLiteralExpr *e) {
   ConstantEmitter compoundLiteralEmitter(cgm, emitter.cgf);
   compoundLiteralEmitter.setInConstantContext(emitter.isInConstantContext());
-  return tryEmitGlobalCompoundLiteral(compoundLiteralEmitter, e);
+
+  cir::GlobalOp global = compoundLiteralEmitter.tryEmitGlobalCompoundLiteral(e);
+  if (!global)
+    return {};
+  return cgm.getBuilder().getGlobalViewAttr(global);
 }
 
 ConstantLValue
@@ -1426,9 +1429,9 @@ mlir::TypedAttr ConstantEmitter::tryEmitPrivate(const Expr *e,
                                                 QualType destType) {
   assert(!destType->isVoidType() && "can't emit a void constant");
 
-  if (mlir::Attribute c =
+  if (mlir::Attribute constant =
           ConstExprEmitter(*this).Visit(const_cast<Expr *>(e), destType))
-    return llvm::dyn_cast<mlir::TypedAttr>(c);
+    return llvm::dyn_cast<mlir::TypedAttr>(constant);
 
   Expr::EvalResult result;
 
@@ -1441,8 +1444,8 @@ mlir::TypedAttr ConstantEmitter::tryEmitPrivate(const Expr *e,
         e->EvaluateAsRValue(result, cgm.getASTContext(), inConstantContext);
 
   if (success && !result.hasSideEffects()) {
-    mlir::Attribute c = tryEmitPrivate(result.Val, destType);
-    return llvm::dyn_cast<mlir::TypedAttr>(c);
+    mlir::Attribute constant = tryEmitPrivate(result.Val, destType);
+    return llvm::dyn_cast_if_present<mlir::TypedAttr>(constant);
   }
 
   return nullptr;
diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index 98133ecf1b48fc..9d650b867ab7e8 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -6143,15 +6143,22 @@ CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
                         CGM.getTBAAInfoForSubobject(Base, FieldType));
 }
 
-LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
-  if (E->isFileScope()) {
-    ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
-    return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
-  }
+LValue
+CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E) {
   if (E->getType()->isVariablyModifiedType())
     // make sure to emit the VLA size.
     EmitVariablyModifiedType(E->getType());
 
+  if (E->hasGlobalStorage()) {
+    ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
+    if (E->hasThreadStorage()) {
+      llvm::Value *V = Builder.CreateThreadLocalAddress(GlobalPtr.getPointer());
+      return MakeAddrLValue(
+          Address(V, ConvertTypeForMem(E->getType()), GlobalPtr.getAlignment()),
+          E->getType(), AlignmentSource::Decl);
+    }
+    return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
+  }
   Address DeclPtr = CreateMemTempWithoutCast(E->getType(), ".compoundliteral");
   const Expr *InitExpr = E->getInitializer();
   LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl);
@@ -6163,14 +6170,17 @@ LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
                                                 DeclPtr);
   }
 
-  EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
-                   /*Init*/ true);
+  if (E->getType()->isAtomicType())
+    EmitAtomicInit(const_cast<Expr *>(InitExpr), Result);
+  else
+    EmitInitializationToLValue(InitExpr, Result);
 
   // Block-scope compound literals are destroyed at the end of the enclosing
   // scope in C.
-  if (!getLangOpts().CPlusPlus)
+  if (!getLangOpts().CPlusPlus) {
     if (QualType::DestructionKind DtorKind = E->getType().isDestructedType())
       pushLifetimeExtendedDestroy(DtorKind, DeclPtr, E->getType());
+  }
 
   return Result;
 }
diff --git a/clang/lib/CodeGen/CGExprAgg.cpp b/clang/lib/CodeGen/CGExprAgg.cpp
index 73c6301c5d585b..2a845370ccd75a 100644
--- a/clang/lib/CodeGen/CGExprAgg.cpp
+++ b/clang/lib/CodeGen/CGExprAgg.cpp
@@ -772,14 +772,14 @@ void AggExprEmitter::VisitOpaqueValueExpr(OpaqueValueExpr *e) {
 }
 
 void AggExprEmitter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
-  if (Dest.isPotentiallyAliased()) {
-    // Just emit a load of the lvalue + a copy, because our compound literal
-    // might alias the destination.
+  QualType Ty = E->getType();
+  if (Dest.isPotentiallyAliased() || E->hasGlobalStorage() ||
+      Ty->isAtomicType() || Ty.isVolatileQualified()) {
     EmitAggLoadOfLValue(E);
     return;
   }
 
-  AggValueSlot Slot = EnsureSlot(E->getType());
+  AggValueSlot Slot = EnsureSlot(Ty);
 
   // Block-scope compound literals are destroyed at the end of the enclosing
   // scope in C.
@@ -791,9 +791,8 @@ void AggExprEmitter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
   CGF.EmitAggExpr(E->getInitializer(), Slot);
 
   if (Destruct)
-    if (QualType::DestructionKind DtorKind = E->getType().isDestructedType())
-      CGF.pushLifetimeExtendedDestroy(DtorKind, Slot.getAddress(),
-                                      E->getType());
+    if (QualType::DestructionKind DtorKind = Ty.isDestructedType())
+      CGF.pushLifetimeExtendedDestroy(DtorKind, Slot.getAddress(), Ty);
 }
 
 /// Attempt to look through various unimportant expressions to find a
diff --git a/clang/lib/CodeGen/CGExprConstant.cpp b/clang/lib/CodeGen/CGExprConstant.cpp
index e2ec07bbae711a..3230c346d5d21e 100644
--- a/clang/lib/CodeGen/CGExprConstant.cpp
+++ b/clang/lib/CodeGen/CGExprConstant.cpp
@@ -1092,8 +1092,8 @@ tryEmitGlobalCompoundLiteral(ConstantEmitter &emitter,
   llvm::Constant *C = emitter.tryEmitForInitializer(E->getInitializer(),
                                                     addressSpace, E->getType());
   if (!C) {
-    assert(!E->isFileScope() &&
-           "file-scope compound literal did not have constant initializer!");
+    assert(!E->hasGlobalStorage() &&
+           "global compound literal did not have constant initializer!");
     return ConstantAddress::invalid();
   }
 
@@ -1101,7 +1101,8 @@ tryEmitGlobalCompoundLiteral(ConstantEmitter &emitter,
       CGM.getModule(), C->getType(),
       E->getType().isConstantStorage(CGM.getContext(), true, false),
       llvm::GlobalValue::InternalLinkage, C, ".compoundliteral", nullptr,
-      llvm::GlobalVariable::NotThreadLocal,
+      E->hasThreadStorage() ? CGM.GetDefaultLLVMTLSModel()
+                            : llvm::GlobalVariable::NotThreadLocal,
       CGM.getContext().getTargetAddressSpace(addressSpace));
   emitter.finalize(GV);
   GV->setAlignment(Align.getAsAlign());
@@ -2794,7 +2795,7 @@ void CodeGenModule::setAddrOfConstantCompoundLiteral(
 
 ConstantAddress
 CodeGenModule::GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *E) {
-  assert(E->isFileScope() && "not a file-scope compound literal expr");
+  assert(E->hasGlobalStorage() && "not a global compound literal expression");
   ConstantEmitter emitter(*this);
   return tryEmitGlobalCompoundLiteral(emitter, E);
 }
diff --git a/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp b/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp
index 12442040b13bb4..a5e513d51c4158 100644
--- a/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp
+++ b/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp
@@ -3299,8 +3299,8 @@ Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
       TypeSourceInfo *superTInfo
         = Context->getTrivialTypeSourceInfo(superType);
       SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
-                                                   superType, VK_LValue,
-                                                   ILE, false);
+                                                   superType, VK_LValue, ILE,
+                                                   /*IsFileScope=*/false);
       // struct __rw_objc_super *
       SuperRep = UnaryOperator::Create(
           const_cast<ASTContext &>(*Context), SuperRep, UO_AddrOf,
@@ -3390,8 +3390,9 @@ Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
                                      SourceLocation(), /*isExplicit=*/true);
       TypeSourceInfo *superTInfo
         = Context->getTrivialTypeSourceInfo(superType);
-      SuperRep = new (Context) CompoundLiteralExpr(
-          SourceLocation(), superTInfo, superType, VK_PRValue, ILE, false);
+      SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
+                                                   superType, VK_PRValue, ILE,
+                                                   /*IsFileScope=*/false);
     }
     MsgExprs.push_back(SuperRep);
     break;
diff --git a/clang/lib/Frontend/Rewrite/RewriteObjC.cpp b/clang/lib/Frontend/Rewrite/RewriteObjC.cpp
index 6b8753e29b8fea..0123a4ed96ff5b 100644
--- a/clang/lib/Frontend/Rewrite/RewriteObjC.cpp
+++ b/clang/lib/Frontend/Rewrite/RewriteObjC.cpp
@@ -2727,8 +2727,8 @@ Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
       TypeSourceInfo *superTInfo
         = Context->getTrivialTypeSourceInfo(superType);
       SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
-                                                   superType, VK_LValue,
-                                                   ILE, false);
+                                                   superType, VK_LValue, ILE,
+                                                   /*IsFileScope=*/false);
       // struct objc_super *
       SuperRep = UnaryOperator::Create(
           const_cast<ASTContext &>(*Context), SuperRep, UO_AddrOf,
@@ -2818,8 +2818,9 @@ Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
                                      SourceLocation(), /*isExplicit=*/true);
       TypeSourceInfo *superTInfo
         = Context->getTrivialTypeSourceInfo(superType);
-      SuperRep = new (Context) CompoundLiteralExpr(
-          SourceLocation(), superTInfo, superType, VK_PRValue, ILE, false);
+      SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
+                                                   superType, VK_PRValue, ILE,
+                                                   /*IsFileScope=*/false);
     }
     MsgExprs.push_back(SuperRep);
     break;
diff --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp
index e452c312702491..baa5888036fbbf 100644
--- a/clang/lib/Parse/ParseDecl.cpp
+++ b/clang/lib/Parse/ParseDecl.cpp
@@ -3394,6 +3394,156 @@ Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
   return false;
 }
 
+void Parser::ParseStorageClassSpecifier(DeclSpec &DS,
+                                        StorageClassSpecifierContext Context) {
+  SourceLocation Loc = Tok.getLocation();
+  const char *PrevSpec = nullptr;
+  unsigned DiagID = 0;
+  bool IsInvalid = false;
+  PrintingPolicy Policy = Actions.getPrintingPolicy();
+
+  switch (Tok.getKind()) {
+  case tok::kw_typedef:
+    IsInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
+                                       PrevSpec, DiagID, Policy);
+    break;
+  case tok::kw_extern:
+    if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
+      Diag(Tok, diag::ext_thread_before) << "extern";
+    IsInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
+                                       PrevSpec, DiagID, Policy);
+    break;
+  case tok::kw___private_extern__:
+    IsInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
+                                       Loc, PrevSpec, DiagID, Policy);
+    break;
+  case tok::kw_static:
+    if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
+      Diag(Tok, diag::ext_thread_before) << "static";
+    IsInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
+                                       PrevSpec, DiagID, Policy);
+    break;
+  case tok::kw_auto:
+    if (getLangOpts().CPlusPlus11 || getLangOpts().C23) {
+      auto IsTypedefName = [&](const Token &T) {
+        if (!T.is(tok::identifier))
+          return false;
+        IdentifierInfo *II = T.getIdentifierInfo();
+        if (!II)
+          return false;
+        // Suppress diagnostics; the real parse will emit them later.
+        LookupResult R(Actions, II, T.getLocation(), Sema::LookupOrdinaryName);
+        Actions.LookupName(R, getCurScope(), /*AllowBuiltinCreation=*/false);
+        R.suppressDiagnostics();
+        return R.isSingleResult() && isa<TypeDecl>(R.getFoundDecl());
+      };
+      auto MayBeTypeSpecifier = [&]() {
+        // In pre-C23 C, auto can be used as a storage-class specifier.
+        // C23 removes auto from the storage-class specifiers and repurposes
+        // it for type inference (6.7.10).
+        if (getLangOpts().C23 && DS.hasTypeSpecifier() &&
+            DS.getTypeSpecType() != DeclSpec::TST_auto)
+          return true;
+
+        unsigned I = 1;
+        while (true) {
+          const Token &T = GetLookAheadToken(I);
+          if (isKnownToBeTypeSpecifier(T))
+            return true;
+
+          // C23: a bare identifier that names a typedef is a type
+          // specifier here, so `auto typedefName varName;` should be
+          // parsed with `auto` as the storage-class specifier — not as
+          // type inference. Without this check the parser would consume
+          // `auto` as type-inference and then error on the missing
+          // initializer for what it thinks is `typedefName`.
+          if (getLangOpts().C23 && IsTypedefName(T))
+            return true;
+
+          if (getLangOpts().C23 && isTypeSpecifierQualifier(T))
+            ++I;
+          else
+            return false;
+        }
+      };
+
+      if (MayBeTypeSpecifier()) {
+        IsInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
+                                           PrevSpec, DiagID, Policy);
+        if (!IsInvalid && !getLangOpts().C23)
+          Diag(Tok, diag::ext_auto_storage_class)
+              << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
+      } else
+        IsInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
+                                       DiagID, Policy);
+    } else {
+      IsInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
+                                         PrevSpec, DiagID, Policy);
+    }
+    break;
+  case tok::kw_register:
+    IsInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
+                                       PrevSpec, DiagID, Policy);
+    break;
+  case tok::kw_mutable:
+    IsInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
+                                       PrevSpec, DiagID, Policy);
+    break;
+  case tok::kw___thread:
+    IsInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc,
+                                             PrevSpec, DiagID);
+    break;
+  case tok::kw_thread_local:
+    if (Context == StorageClassSpecifierContext::Declaration &&
+        getLangOpts().C23)
+      Diag(Tok, diag::warn_c23_compat_keyword) << Tok.getName();
+    // We map thread_local to _Thread_local in C23 mode so it retains the C
+    // semantics rather than getting the C++ semantics.
+    // FIXME: diagnostics will show _Thread_local when the user wrote
+    // thread_local in source in C23 mode; we need some general way to
+    // identify which way the user spelled the keyword in source.
+    IsInvalid = DS.SetStorageClassSpecThread(getLangOpts().C23
+                                                 ? DeclSpec::TSCS__Thread_local
+                                                 : DeclSpec::TSCS_thread_local,
+                                             Loc, PrevSpec, DiagID);
+    break;
+  case tok::kw__Thread_local:
+    diagnoseUseOfC11Keyword(Tok);
+    IsInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS__Thread_local, Loc,
+                                             PrevSpec, DiagID);
+    break;
+  case tok::kw_constexpr:
+    if (Context == StorageClassSpecifierContext::Declaration &&
+        getLangOpts().C23)
+      Diag(Tok, diag::warn_c23_compat_keyword) << Tok.getName();
+    IsInvalid = DS.SetConstexprSpec(ConstexprSpecKind::Constexpr, Loc, PrevSpec,
+                                    DiagID);
+    break;
+  default:
+    llvm_unreachable("not a storage class specifier");
+  }
+
+  DS.SetRangeEnd(Loc);
+  if (IsInvalid) {
+    assert(PrevSpec && "Method did not return previous specifier!");
+    assert(DiagID);
+
+    if (DiagID == diag::ext_duplicate_declspec ||
+        DiagID == diag::ext_warn_duplicate_declspec ||
+        DiagID == diag::err_duplicate_declspec)
+      Diag(Loc, DiagID) << PrevSpec
+                        << FixItHint::CreateRemoval(
+                               SourceRange(Loc, DS.getEndLoc()));
+    else if (DiagID == diag::err_opencl_unknown_type_specifier)
+      Diag(Loc, DiagID) << getLangOpts().getOpenCLVersionString() << PrevSpec
+                        << /*IsStorageClass=*/true;
+    else
+      Diag(Loc, DiagID) << PrevSpec;
+  }
+
+  ConsumeToken();
+}
+
 void Parser::ParseDeclarationSpecifiers(
     DeclSpec &DS, ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS,
     DeclSpecContext DSContext, LateParsedAttrList *LateAttrs,
@@ -3419,7 +3569,6 @@ void Parser::ParseDeclarationSpecifiers(
   PrintingPolicy Policy = Actions.getPrintingPolicy();
   while (true) {
     bool isInvalid = false;
-    bool isStorageClass = false;
     const char *PrevSpec = nullptr;
     unsigned DiagID = 0;
 
@@ -4109,128 +4258,24 @@ void Parser::ParseDeclarationSpecifiers(
 
     // storage-class-specifier
     case tok::kw_typedef:
-      isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
-                                         PrevSpec, DiagID, Policy);
-      isStorageClass = true;
-      break;
     case tok::kw_extern:
-      if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
-        Diag(Tok, diag::ext_thread_before) << "extern";
-      isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
-                                         PrevSpec, DiagID, Policy);
-      isStorageClass = true;
-      break;
     case tok::kw___private_extern__:
-      isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
-                                         Loc, PrevSpec, DiagID, Policy);
-      isStorageClass = true;
-      break;
     case tok::kw_static:
-      if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
-        Diag(Tok, diag::ext_thread_before) << "static";
-      isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
-                                         PrevSpec, DiagID, Policy);
-      isStorageClass = true;
-      break;
     case tok::kw_auto:
-      if (getLangOpts().CPlusPlus11 || getLangOpts().C23) {
-        auto IsTypedefName = [&](const Token &T) {
-          if (!T.is(tok::identifier))
-            return false;
-          IdentifierInfo *II = T.getIdentifierInfo();
-          if (!II)
-            return false;
-          // Suppress diagnostics; the real parse will emit them later.
-          LookupResult R(Actions, II, T.getLocation(),
-                         Sema::LookupOrdinaryName);
-          Actions.LookupName(R, getCurScope(),
-                             /*AllowBuiltinCreation=*/false);
-          R.suppressDiagnostics();
-          return R.isSingleResult() && isa<TypeDecl>(R.getFoundDecl());
-        };
-        auto MayBeTypeSpecifier = [&]() {
-          // In pre-C23 C, auto can be used as a storage-class specifier.
-          // C23 removes auto from the storage-class specifiers and repurposes
-          // it for type inference (6.7.10).
-          if (getLangOpts().C23 && DS.hasTypeSpecifier() &&
-              DS.getTypeSpecType() != DeclSpec::TST_auto)
-            return true;
-
-          unsigned I = 1;
-          while (true) {
-            const Token &T = GetLookAheadToken(I);
-            if (isKnownToBeTypeSpecifier(T))
-              return true;
-
-            // C23: a bare identifier that names a typedef is a type
-            // specifier here, so `auto typedefName varName;` should be
-            // parsed with `auto` as the storage-class specifier — not as
-            // type inference. Without this check the parser would consume
-            // `auto` as type-inference and then error on the missing
-            // initializer for what it thinks is `typedefName`.
-            if (getLangOpts().C23 && IsTypedefName(T))
-              return true;
-
-            if (getLangOpts().C23 && isTypeSpecifierQualifier(T))
-              ++I;
-            else
-              return false;
-          }
-        };
-
-        if (MayBeTypeSpecifier()) {
-          isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
-                                             PrevSpec, DiagID, Policy);
-          if (!isInvalid && !getLangOpts().C23)
-            Diag(Tok, diag::ext_auto_storage_class)
-              << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
-        } else
-          isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
-                                         DiagID, Policy);
-      } else
-        isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
-                                           PrevSpec, DiagID, Policy);
-      isStorageClass = true;
-      break;
-    case tok::kw___auto_type:
-      Diag(Tok, diag::ext_auto_type);
-      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto_type, Loc, PrevSpec,
-                                     DiagID, Policy);
-      break;
     case tok::kw_register:
-      isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
-                                         PrevSpec, DiagID, Policy);
-      isStorageClass = true;
-      break;
     case tok::kw_mutable:
-      isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
-                                         PrevSpec, DiagID, Policy);
-      isStorageClass = true;
-      break;
     case tok::kw___thread:
-      isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc,
-                                               PrevSpec, DiagID);
-      isStorageClass = true;
-      break;
     case tok::kw_thread_local:
-      if (getLangOpts().C23)
-        Diag(Tok, diag::warn_c23_compat_keyword) << Tok.getName();
-      // We map thread_local to _Thread_local in C23 mode so it retains the C
-      // semantics rather than getting the C++ semantics.
-      // FIXME: diagnostics will show _Thread_local when the user wrote
-      // thread_local in source in C23 mode; we need some general way to
-      // identify which way the user spelled the keyword in source.
-      isInvalid = DS.SetStorageClassSpecThread(
-          getLangOpts().C23 ? DeclSpec::TSCS__Thread_local
-                            : DeclSpec::TSCS_thread_local,
-          Loc, PrevSpec, DiagID);
-      isStorageClass = true;
-      break;
     case tok::kw__Thread_local:
-      diagnoseUseOfC11Keyword(Tok);
-      isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS__Thread_local,
-                                               Loc, PrevSpec, DiagID);
-      isStorageClass = true;
+    case tok::kw_constexpr:
+      ParseStorageClassSpecifier(DS, StorageClassSpecifierContext::Declaration);
+      AttrsLastTime = false;
+      continue;
+
+    case tok::kw___auto_type:
+      Diag(Tok, diag::ext_auto_type);
+      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto_type, Loc, PrevSpec,
+                                     DiagID, Policy);
       break;
 
     // function-specifier
@@ -4312,13 +4357,7 @@ void Parser::ParseDeclarationSpecifiers(
       isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
       break;
 
-    // constexpr, consteval, constinit specifiers
-    case tok::kw_constexpr:
-      if (getLangOpts().C23)
-        Diag(Tok, diag::warn_c23_compat_keyword) << Tok.getName();
-      isInvalid = DS.SetConstexprSpec(ConstexprSpecKind::Constexpr, Loc,
-                                      PrevSpec, DiagID);
-      break;
+    // consteval and constinit specifiers
     case tok::kw_consteval:
       isInvalid = DS.SetConstexprSpec(ConstexprSpecKind::Consteval, Loc,
                                       PrevSpec, DiagID);
@@ -4764,7 +4803,7 @@ void Parser::ParseDeclarationSpecifiers(
                                  SourceRange(Loc, DS.getEndLoc()));
       else if (DiagID == diag::err_opencl_unknown_type_specifier) {
         Diag(Loc, DiagID) << getLangOpts().getOpenCLVersionString() << PrevSpec
-                          << isStorageClass;
+                          << /*IsStorageClass=*/false;
       } else
         Diag(Loc, DiagID) << PrevSpec;
     }
@@ -8057,6 +8096,8 @@ void Parser::ParseBracketDeclarator(Declarator &D) {
       EnterExpressionEvaluationContext Unevaluated(
           Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
       NumElements = ParseAssignmentExpression();
+      if (NumElements.isUsable())
+        NumElements = Actions.MaybeCreateExprWithCleanups(NumElements);
     }
   } else {
     if (StaticLoc.isValid()) {
diff --git a/clang/lib/Parse/ParseExpr.cpp b/clang/lib/Parse/ParseExpr.cpp
index d42ffc2ccf0a65..d5803bb49af976 100644
--- a/clang/lib/Parse/ParseExpr.cpp
+++ b/clang/lib/Parse/ParseExpr.cpp
@@ -2655,6 +2655,42 @@ bool Parser::tryParseOpenMPArrayShapingCastPart() {
   return !ErrorFound;
 }
 
+bool Parser::isCompoundLiteralStorageClassSpecifier() const {
+  if (!getLangOpts().C23)
+    return false;
+  switch (Tok.getKind()) {
+  case tok::kw_constexpr:
+  case tok::kw_register:
+  case tok::kw_static:
+  case tok::kw___thread:
+  case tok::kw_thread_local:
+  case tok::kw__Thread_local:
+    return true;
+  default:
+    return false;
+  }
+}
+
+bool Parser::isTypeIdInParensWithStorageClassSpecifiers() {
+  if (!isCompoundLiteralStorageClassSpecifier())
+    return false;
+
+  RevertingTentativeParsingAction TPA(*this);
+  do
+    ConsumeToken();
+  while (isCompoundLiteralStorageClassSpecifier());
+  return isTypeIdInParens();
+}
+
+void Parser::ParseCompoundLiteralStorageClassSpecifiers(DeclSpec &DS) {
+  while (isCompoundLiteralStorageClassSpecifier()) {
+    if (DS.getBeginLoc().isInvalid())
+      DS.SetRangeStart(Tok.getLocation());
+    ParseStorageClassSpecifier(DS,
+                               StorageClassSpecifierContext::CompoundLiteral);
+  }
+}
+
 ExprResult
 Parser::ParseParenExpression(ParenParseOption &ExprType, bool StopIfCastExpr,
                              ParenExprKind ParenBehavior,
@@ -2674,7 +2710,7 @@ Parser::ParseParenExpression(ParenParseOption &ExprType, bool StopIfCastExpr,
   PreferredType.enterParenExpr(Tok.getLocation(), OpenLoc);
 
   ExprResult Result(true);
-  bool isAmbiguousTypeId;
+  bool isAmbiguousTypeId = false;
   CastTy = nullptr;
 
   if (Tok.is(tok::code_completion)) {
@@ -2776,7 +2812,8 @@ Parser::ParseParenExpression(ParenParseOption &ExprType, bool StopIfCastExpr,
                                                BridgeKeywordLoc, Ty.get(),
                                                RParenLoc, SubExpr.get());
   } else if (ExprType >= ParenParseOption::CompoundLiteral &&
-             isTypeIdInParens(isAmbiguousTypeId)) {
+             (isTypeIdInParensWithStorageClassSpecifiers() ||
+              isTypeIdInParens(isAmbiguousTypeId))) {
 
     // Otherwise, this is a compound literal expression or cast expression.
 
@@ -2792,7 +2829,10 @@ Parser::ParseParenExpression(ParenParseOption &ExprType, bool StopIfCastExpr,
       return res;
     }
 
-    // Parse the type declarator.
+    DeclSpec CompoundDS(AttrFactory);
+    ParseCompoundLiteralStorageClassSpecifiers(CompoundDS);
+    CompoundDS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
+
     DeclSpec DS(AttrFactory);
     ParseSpecifierQualifierList(DS);
     Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
@@ -2820,12 +2860,32 @@ Parser::ParseParenExpression(ParenParseOption &ExprType, bool StopIfCastExpr,
       RParenLoc = T.getCloseLocation();
       if (ParenBehavior == ParenExprKind::Unknown && Tok.is(tok::l_brace)) {
         ExprType = ParenParseOption::CompoundLiteral;
+
+        if (CompoundDS.getBeginLoc().isValid())
+          Diag(CompoundDS.getBeginLoc(),
+               diag::warn_c23_compat_compound_literal_storage_class);
+
         TypeResult Ty;
         {
           InMessageExpressionRAIIObject InMessage(*this, false);
           Ty = Actions.ActOnTypeName(DeclaratorInfo);
         }
-        return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc);
+        return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc,
+                                              &CompoundDS);
+      }
+
+      if (!DeclaratorInfo.isInvalidType()) {
+        if (CompoundDS.getParsedSpecifiers() &
+            DeclSpec::PQ_StorageClassSpecifier) {
+          SourceLocation Loc = CompoundDS.getStorageClassSpecLoc();
+          if (Loc.isInvalid())
+            Loc = CompoundDS.getThreadStorageClassSpecLoc();
+          Diag(Loc, diag::err_typename_invalid_storageclass);
+        }
+        if (CompoundDS.hasConstexprSpecifier())
+          Diag(CompoundDS.getConstexprSpecLoc(),
+               diag::err_typename_invalid_constexpr)
+              << static_cast<int>(CompoundDS.getConstexprSpecifier());
       }
 
       if (ParenBehavior == ParenExprKind::Unknown && Tok.is(tok::l_paren)) {
@@ -2999,17 +3059,18 @@ Parser::ParseParenExpression(ParenParseOption &ExprType, bool StopIfCastExpr,
   return Result;
 }
 
-ExprResult
-Parser::ParseCompoundLiteralExpression(ParsedType Ty,
-                                       SourceLocation LParenLoc,
-                                       SourceLocation RParenLoc) {
+ExprResult Parser::ParseCompoundLiteralExpression(ParsedType Ty,
+                                                  SourceLocation LParenLoc,
+                                                  SourceLocation RParenLoc,
+                                                  const DeclSpec *DS) {
   assert(Tok.is(tok::l_brace) && "Not a compound literal!");
   if (!getLangOpts().C99)   // Compound literals don't exist in C90.
     Diag(LParenLoc, diag::ext_c99_compound_literal);
   PreferredType.enterTypeCast(Tok.getLocation(), Ty.get());
   ExprResult Result = ParseInitializer();
   if (!Result.isInvalid() && Ty)
-    return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, Result.get());
+    return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, Result.get(),
+                                        DS);
   return Result;
 }
 
diff --git a/clang/lib/Sema/CheckExprLifetime.cpp b/clang/lib/Sema/CheckExprLifetime.cpp
index fafee76ec18c30..80075370756173 100644
--- a/clang/lib/Sema/CheckExprLifetime.cpp
+++ b/clang/lib/Sema/CheckExprLifetime.cpp
@@ -131,6 +131,7 @@ getEntityLifetime(const InitializedEntity *Entity,
 
   case InitializedEntity::EK_Temporary:
   case InitializedEntity::EK_CompoundLiteralInit:
+  case InitializedEntity::EK_ConstexprCompoundLiteralInit:
   case InitializedEntity::EK_RelatedResult:
     // We don't yet know the storage duration of the surrounding temporary.
     // Assume it's got full-expression duration for now, it will patch up our
@@ -658,7 +659,7 @@ static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
 
   case Stmt::CompoundLiteralExprClass: {
     if (auto *CLE = dyn_cast<CompoundLiteralExpr>(Init)) {
-      if (!CLE->isFileScope())
+      if (!CLE->hasGlobalStorage())
         Visit(Path, Local(CLE), RK);
     }
     break;
diff --git a/clang/lib/Sema/DelayedDiagnostic.cpp b/clang/lib/Sema/DelayedDiagnostic.cpp
index cb2721b92090ec..4f94da0e64fbaf 100644
--- a/clang/lib/Sema/DelayedDiagnostic.cpp
+++ b/clang/lib/Sema/DelayedDiagnostic.cpp
@@ -68,6 +68,7 @@ void DelayedDiagnostic::Destroy() {
     break;
 
   case ForbiddenType:
+  case ForbiddenStatic:
     break;
   }
 }
diff --git a/clang/lib/Sema/Scope.cpp b/clang/lib/Sema/Scope.cpp
index fc79b1a056ed9e..1cd7a21893ba43 100644
--- a/clang/lib/Sema/Scope.cpp
+++ b/clang/lib/Sema/Scope.cpp
@@ -103,14 +103,15 @@ void Scope::Init(Scope *parent, unsigned flags) {
   NRVO = std::nullopt;
 }
 
-bool Scope::containedInPrototypeScope() const {
-  const Scope *S = this;
-  while (S) {
+const Scope *Scope::getEnclosingFunctionPrototypeScope() const {
+  for (const Scope *S = this; S; S = S->getParent())
     if (S->isFunctionPrototypeScope())
-      return true;
-    S = S->getParent();
-  }
-  return false;
+      return S;
+  return nullptr;
+}
+
+bool Scope::containedInPrototypeScope() const {
+  return getEnclosingFunctionPrototypeScope() != nullptr;
 }
 
 void Scope::EnterLoopBody(LabelDecl *LD) {
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index f3d38a555a524a..1c7072dc9b01b1 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -5730,11 +5730,7 @@ InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
   return Invalid;
 }
 
-/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
-/// a VarDecl::StorageClass. Any error reporting is up to the caller:
-/// illegal input values are mapped to SC_None.
-static StorageClass
-StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
+StorageClass Sema::StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
          "Parser allowed 'typedef' as storage class VarDecl.");
@@ -7501,7 +7497,7 @@ static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
 /// Given that we are within the definition of the given function,
 /// will that definition behave like C99's 'inline', where the
 /// definition is discarded except for optimization purposes?
-static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
+static bool isFunctionDefinitionDiscarded(Sema &S, const FunctionDecl *FD) {
   // Try to avoid calling GetGVALinkageForFunction.
 
   // All cases of this require the 'inline' keyword.
@@ -7515,6 +7511,14 @@ static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
 }
 
+void Sema::DiagnoseStaticInInline(SourceLocation Loc, const FunctionDecl *FD) {
+  if (!FD || !isFunctionDefinitionDiscarded(*this, FD))
+    return;
+
+  Diag(Loc, diag::warn_static_local_in_extern_inline);
+  MaybeSuggestAddingStaticToDecl(FD);
+}
+
 /// Determine whether a variable is extern "C" prior to attaching
 /// an initializer. We can't just call isExternC() here, because that
 /// will also compute and cache whether the declaration is externally
@@ -8280,14 +8284,9 @@ NamedDecl *Sema::ActOnVariableDeclarator(
   // be marked 'static'.  Also note that it's possible to get these
   // semantics in C++ using __attribute__((gnu_inline)).
   if (SC == SC_Static && S->getFnParent() != nullptr &&
-      !NewVD->getType().isConstQualified()) {
-    FunctionDecl *CurFD = getCurFunctionDecl();
-    if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
-      Diag(D.getDeclSpec().getStorageClassSpecLoc(),
-           diag::warn_static_local_in_extern_inline);
-      MaybeSuggestAddingStaticToDecl(CurFD);
-    }
-  }
+      !NewVD->getType().isConstQualified())
+    DiagnoseStaticInInline(D.getDeclSpec().getStorageClassSpecLoc(),
+                           getCurFunctionDecl());
 
   if (D.getDeclSpec().isModulePrivateSpecified()) {
     if (IsVariableTemplateSpecialization)
@@ -8994,32 +8993,31 @@ static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
   return false;
 }
 
-static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,
-                                     QualType T) {
-  QualType CanonT = SemaRef.Context.getCanonicalType(T);
+bool Sema::CheckConstexprType(SourceLocation Loc, QualType T) {
+  QualType CanonT = Context.getCanonicalType(T);
   // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
   // any of its members, even recursively, shall not have an atomic type, or a
   // variably modified type, or a type that is volatile or restrict qualified.
   if (CanonT->isVariablyModifiedType()) {
-    SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
+    Diag(Loc, diag::err_c23_constexpr_invalid_type) << T;
     return true;
   }
 
   // Arrays are qualified by their element type, so get the base type (this
   // works on non-arrays as well).
-  CanonT = SemaRef.Context.getBaseElementType(CanonT);
+  CanonT = Context.getBaseElementType(CanonT);
 
   if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
       CanonT.isRestrictQualified()) {
-    SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
+    Diag(Loc, diag::err_c23_constexpr_invalid_type) << T;
     return true;
   }
 
   if (CanonT->isRecordType()) {
     const RecordDecl *RD = CanonT->getAsRecordDecl();
     if (!RD->isInvalidDecl() &&
-        llvm::any_of(RD->fields(), [&SemaRef, VarLoc](const FieldDecl *F) {
-          return CheckC23ConstexprVarType(SemaRef, VarLoc, F->getType());
+        llvm::any_of(RD->fields(), [this, Loc](const FieldDecl *F) {
+          return CheckConstexprType(Loc, F->getType());
         }))
       return true;
   }
@@ -9311,7 +9309,7 @@ void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
   }
 
   if (getLangOpts().C23 && NewVD->isConstexpr() &&
-      CheckC23ConstexprVarType(*this, NewVD->getLocation(), T)) {
+      CheckConstexprType(NewVD->getLocation(), T)) {
     NewVD->setInvalidDecl();
     return;
   }
@@ -15531,9 +15529,10 @@ void Sema::CheckThreadLocalForLargeAlignment(VarDecl *VD) {
     if (!VD->hasDependentAlignment()) {
       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
       if (Context.getDeclAlign(VD) > MaxAlignChars) {
-        Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
-            << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
-            << (unsigned)MaxAlignChars.getQuantity();
+        Diag(VD->getLocation(), diag::err_tls_aligned_over_maximum)
+            << (unsigned)Context.getDeclAlign(VD).getQuantity()
+            << /*IsCompoundLiteral=*/false
+            << (unsigned)MaxAlignChars.getQuantity() << VD;
       }
     }
   }
diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index 33b680c4d93d4c..ada1ea03d22d9c 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -4910,8 +4910,9 @@ void Sema::AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
             .getQuantity();
     if (MaxTLSAlign && AlignVal > MaxTLSAlign &&
         VD->getTLSKind() != VarDecl::TLS_None) {
-      Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
-          << (unsigned)AlignVal << VD << MaxTLSAlign;
+      Diag(VD->getLocation(), diag::err_tls_aligned_over_maximum)
+          << (unsigned)AlignVal << /*IsCompoundLiteral=*/false << MaxTLSAlign
+          << VD;
       return;
     }
   }
@@ -9084,6 +9085,14 @@ void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
       case DelayedDiagnostic::ForbiddenType:
         handleDelayedForbiddenType(*this, diag, decl);
         break;
+
+      case DelayedDiagnostic::ForbiddenStatic:
+        if (const FunctionDecl *FD = decl->getAsFunction();
+            FD && FD->isThisDeclarationADefinition()) {
+          diag.Triggered = true;
+          DiagnoseStaticInInline(diag.Loc, FD);
+        }
+        break;
       }
     }
   } while ((pool = pool->getParent()));
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 00dd8acf1f68dd..683e07480a0b53 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -64,6 +64,7 @@
 #include "clang/Sema/SemaProxy.h"
 #include "clang/Sema/SemaPseudoObject.h"
 #include "clang/Sema/Template.h"
+#include "llvm/ADT/PointerUnion.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/IR/DerivedTypes.h"
@@ -125,6 +126,40 @@ static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
   }
 }
 
+static bool checkThreadLocalCompoundLiteral(Sema &S, SourceLocation Loc,
+                                            QualType T) {
+  if (S.getLangOpts().ObjCAutoRefCount && T->isObjCLifetimeType()) {
+    Qualifiers::ObjCLifetime Lifetime = T.getObjCLifetime();
+    if (Lifetime == Qualifiers::OCL_None)
+      Lifetime = T->getObjCARCImplicitLifetime();
+
+    if (Lifetime && Lifetime != Qualifiers::OCL_ExplicitNone) {
+      S.Diag(Loc, diag::err_arc_thread_ownership)
+          << S.Context.getLifetimeQualifiedType(T, Lifetime);
+      return true;
+    }
+  }
+
+  if (T.isDestructedType()) {
+    S.Diag(Loc, diag::err_thread_nontrivial_dtor);
+    return true;
+  }
+
+  unsigned MaxAlign = S.Context.getTargetInfo().getMaxTLSAlign();
+  if (!MaxAlign || T->isDependentType())
+    return false;
+
+  CharUnits MaxAlignChars = S.Context.toCharUnitsFromBits(MaxAlign);
+  CharUnits TypeAlign = S.Context.getTypeAlignInChars(T);
+  if (TypeAlign <= MaxAlignChars)
+    return false;
+
+  S.Diag(Loc, diag::err_tls_aligned_over_maximum)
+      << (unsigned)TypeAlign.getQuantity() << /*IsCompoundLiteral=*/true
+      << (unsigned)MaxAlignChars.getQuantity();
+  return true;
+}
+
 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
   assert(Decl && Decl->isDeleted());
 
@@ -7617,9 +7652,9 @@ ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
 }
 
-ExprResult
-Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
-                           SourceLocation RParenLoc, Expr *InitExpr) {
+ExprResult Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
+                                      SourceLocation RParenLoc, Expr *InitExpr,
+                                      const DeclSpec *DS) {
   assert(Ty && "ActOnCompoundLiteral(): missing type");
   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
 
@@ -7628,13 +7663,83 @@ Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
   if (!TInfo)
     TInfo = Context.getTrivialTypeSourceInfo(literalType);
 
-  return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
-}
-
-ExprResult
-Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
-                               SourceLocation RParenLoc, Expr *LiteralExpr) {
+  StorageClass SC = SC_None;
+  ThreadStorageClassSpecifier TSC = TSCS_unspecified;
+  ConstexprSpecKind ConstexprKind = ConstexprSpecKind::Unspecified;
+  SourceLocation StorageClassLoc;
+  SourceLocation ThreadStorageClassLoc;
+  SourceLocation ConstexprLoc;
+  if (DS) {
+    SC = StorageClassSpecToVarDeclStorageClass(*DS);
+    TSC = DS->getThreadStorageClassSpec();
+    ConstexprKind = DS->getConstexprSpecifier();
+    StorageClassLoc = DS->getStorageClassSpecLoc();
+    ThreadStorageClassLoc = DS->getThreadStorageClassSpecLoc();
+    ConstexprLoc = DS->getConstexprSpecLoc();
+  }
+
+  return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr, SC,
+                                  StorageClassLoc, TSC, ThreadStorageClassLoc,
+                                  ConstexprKind, ConstexprLoc);
+}
+
+ExprResult Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc,
+                                          TypeSourceInfo *TInfo,
+                                          SourceLocation RParenLoc,
+                                          Expr *LiteralExpr, StorageClass SC,
+                                          ThreadStorageClassSpecifier TSC,
+                                          ConstexprSpecKind ConstexprKind) {
+  return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, LiteralExpr, SC,
+                                  LParenLoc, TSC, LParenLoc, ConstexprKind,
+                                  LParenLoc);
+}
+
+ExprResult Sema::BuildCompoundLiteralExpr(
+    SourceLocation LParenLoc, TypeSourceInfo *TInfo, SourceLocation RParenLoc,
+    Expr *LiteralExpr, StorageClass SC, SourceLocation StorageClassLoc,
+    ThreadStorageClassSpecifier TSC, SourceLocation ThreadStorageClassLoc,
+    ConstexprSpecKind ConstexprKind, SourceLocation ConstexprLoc) {
   QualType literalType = TInfo->getType();
+  const Scope *S = getCurScope();
+  const Scope *PrototypeScope = S->getEnclosingFunctionPrototypeScope();
+
+  bool HasStatic = SC == SC_Static;
+  bool HasRegister = SC == SC_Register;
+  bool HasThreadStorage = TSC != TSCS_unspecified;
+  bool HasConstexpr = ConstexprKind == ConstexprSpecKind::Constexpr;
+
+  bool IsFunctionDeclarationScope =
+      PrototypeScope && PrototypeScope->isFunctionDeclarationScope();
+  bool IsFileScope = !CurContext->isFunctionOrMethod() &&
+                     !S->isInCFunctionScope() && !PrototypeScope;
+
+  if (HasConstexpr && literalType->isObjectType())
+    literalType.addConst();
+
+  if (getLangOpts().C23 &&
+      (SC != SC_None || HasThreadStorage || HasConstexpr)) {
+    if (HasRegister && IsFileScope) {
+      Diag(StorageClassLoc, diag::err_register_compound_literal_file_scope);
+      return ExprError();
+    }
+    if (HasThreadStorage && !IsFileScope && !HasStatic) {
+      Diag(ThreadStorageClassLoc,
+           diag::err_thread_local_compound_literal_without_static);
+      return ExprError();
+    }
+    if (HasThreadStorage && !Context.getTargetInfo().isTLSSupported()) {
+      Diag(ThreadStorageClassLoc, diag::err_thread_unsupported);
+      return ExprError();
+    }
+    if (HasConstexpr && CheckConstexprType(ConstexprLoc, literalType))
+      return ExprError();
+  }
+
+  if (getLangOpts().C23 && IsFileScope &&
+      literalType->isVariablyModifiedType()) {
+    Diag(LParenLoc, diag::err_vm_decl_in_file_scope);
+    return ExprError();
+  }
 
   if (literalType->isArrayType()) {
     if (RequireCompleteSizedType(
@@ -7669,32 +7774,49 @@ Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
         return ExprError();
     }
   } else if (!literalType->isDependentType() &&
-             RequireCompleteType(LParenLoc, literalType,
-               diag::err_typecheck_decl_incomplete_type,
-               SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
+             RequireCompleteType(
+                 LParenLoc, literalType,
+                 diag::err_typecheck_decl_incomplete_type,
+                 SourceRange(LParenLoc,
+                             LiteralExpr->getSourceRange().getEnd())))
     return ExprError();
 
-  InitializedEntity Entity
-    = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
-  InitializationKind Kind
-    = InitializationKind::CreateCStyleCast(LParenLoc,
-                                           SourceRange(LParenLoc, RParenLoc),
-                                           /*InitList=*/true);
+  InitializedEntity Entity = InitializedEntity::InitializeCompoundLiteralInit(
+      TInfo, literalType, ConstexprKind);
+  InitializationKind Kind = InitializationKind::CreateCStyleCast(
+      LParenLoc, SourceRange(LParenLoc, RParenLoc),
+      /*InitList=*/true);
   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
-  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
-                                      &literalType);
+  ExprResult Result =
+      InitSeq.Perform(*this, Entity, Kind, LiteralExpr, &literalType);
   if (Result.isInvalid())
     return ExprError();
   LiteralExpr = Result.get();
 
-  // We treat the compound literal as being at file scope if it's not in a
-  // function or method body, or within the function's prototype scope. This
-  // means the following compound literal is not at file scope:
-  //   void func(char *para[(int [1]){ 0 }[0]);
-  const Scope *S = getCurScope();
-  bool IsFileScope = !CurContext->isFunctionOrMethod() &&
-                     !S->isInCFunctionScope() &&
-                     (!S || !S->isFunctionPrototypeScope());
+  if (HasConstexpr && !LiteralExpr->isTypeDependent() &&
+      !LiteralExpr->isValueDependent() && !literalType->isDependentType()) {
+    SmallVector<PartialDiagnosticAt, 4> Notes;
+    SmallVector<PartialDiagnosticAt, 4> Warnings;
+    Expr::EvalResult Eval;
+    Eval.Diag = &Notes;
+    Eval.ExtendedDiag = &Warnings;
+    if (!LiteralExpr->EvaluateAsConstantExpr(Eval, Context) || !Notes.empty()) {
+      SourceLocation DiagLoc = ConstexprLoc;
+      if (Notes.size() == 1 && Notes.front().second.getDiagID() ==
+                                   diag::note_invalid_subexpr_in_const_expr) {
+        DiagLoc = Notes.front().first;
+        Notes.clear();
+      }
+      Diag(DiagLoc, diag::err_compound_literal_initializer_not_constant)
+          << LiteralExpr->getSourceRange();
+      for (const PartialDiagnosticAt &Note : Notes)
+        Diag(Note.first, Note.second);
+      return ExprError();
+    }
+    for (const PartialDiagnosticAt &Warning : Warnings)
+      Diag(Warning.first, Warning.second);
+    LiteralExpr = ConstantExpr::Create(Context, LiteralExpr, Eval.Val);
+  }
 
   // In C, compound literals are l-values for some reason.
   // For GCC compatibility, in C++, file-scope array compound literals with
@@ -7719,10 +7841,17 @@ Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
           ? VK_PRValue
           : VK_LValue;
 
+  bool HasGlobalStorage =
+      IsFileScope || (getLangOpts().C23 && (HasStatic || HasThreadStorage));
+
+  if (HasThreadStorage && checkThreadLocalCompoundLiteral(
+                              *this, ThreadStorageClassLoc, literalType))
+    return ExprError();
+
   // C99 6.5.2.5
   //  "If the compound literal occurs outside the body of a function, the
   //  initializer list shall consist of constant expressions."
-  if (IsFileScope) {
+  if (HasGlobalStorage && !HasConstexpr) {
     // An element with an immediate call or source_location is left for the
     // use site, and for its rebuild too when the rebuilt default arguments
     // could not be given the use-site location.
@@ -7748,6 +7877,10 @@ Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
             << Init->getSourceBitField();
         return nullptr;
       }
+      // Folding for static initialization must not hide non-constexpr reads
+      // when an ordinary C23 compound literal is used in a constant expression.
+      if (getLangOpts().C23)
+        return Init;
       // An immediate invocation already is a ConstantExpr.
       if (isa<ConstantExpr>(Init))
         return Init;
@@ -7767,8 +7900,10 @@ Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
     }
   }
 
-  auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, VK,
-                                              LiteralExpr, IsFileScope);
+  auto *E = new (Context)
+      CompoundLiteralExpr(LParenLoc, TInfo, literalType, VK, LiteralExpr,
+                          IsFileScope, SC, TSC, ConstexprKind);
+
   if (!IsFileScope && literalType.getAddressSpace() != LangAS::opencl_private &&
       literalType.getAddressSpace() != LangAS::Default) {
     // Embedded-C extensions to C99 6.5.2.5:
@@ -7779,22 +7914,35 @@ Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
     return ExprError();
   }
 
-  if (!IsFileScope && !getLangOpts().CPlusPlus) {
+  if (HasStatic && !literalType.isConstQualified()) {
+    if (PrototypeScope) {
+      if (IsFunctionDeclarationScope &&
+          DelayedDiagnostics.shouldDelayDiagnostics())
+        DelayedDiagnostics.add(
+            sema::DelayedDiagnostic::makeForbiddenStatic(StorageClassLoc));
+    } else {
+      DiagnoseStaticInInline(StorageClassLoc, getCurFunctionDecl());
+    }
+  }
+
+  if (!HasGlobalStorage && !getLangOpts().CPlusPlus) {
     // Compound literals that have automatic storage duration are destroyed at
     // the end of the scope in C; in C++, they're just temporaries.
 
-    // Emit diagnostics if it is or contains a C union type that is non-trivial
-    // to destruct.
-    if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
-      checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
-                            NonTrivialCUnionContext::CompoundLiteral,
-                            NTCUK_Destruct);
-
-    // Diagnose jumps that enter or exit the lifetime of the compound literal.
     Cleanup.setExprNeedsCleanups(true);
     ExprCleanupObjects.push_back(E);
-    if (literalType.isDestructedType()) {
-      getCurFunction()->setHasBranchProtectedScope();
+
+    if (!PrototypeScope) {
+      // Emit diagnostics if it is or contains a C union type that is
+      // non-trivial to destruct.
+      if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
+        checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
+                              NonTrivialCUnionContext::CompoundLiteral,
+                              NTCUK_Destruct);
+      // Diagnose jumps that enter or exit the lifetime of the compound
+      // literal.
+      if (literalType.isDestructedType())
+        getCurFunction()->setHasBranchProtectedScope();
     }
   }
 
@@ -10337,8 +10485,9 @@ static void ConstructTransparentUnion(Sema &S, ASTContext &C,
   // Build a compound literal constructing a value of the transparent
   // union type from this initializer list.
   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
-  EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
-                                        VK_PRValue, Initializer, false);
+  EResult = new (C)
+      CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, VK_PRValue,
+                          Initializer, /*IsFileScope=*/false);
 }
 
 AssignConvertType
@@ -15158,78 +15307,54 @@ static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
   }
 }
 
-/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
-/// This routine allows us to typecheck complex/recursive expressions
-/// where the declaration is needed for type checking. We only need to
-/// handle cases when the expression references a function designator
-/// or is an lvalue. Here are some examples:
-///  - &(x) => x
-///  - &*****f => f for f a function designator.
-///  - &s.xx => s
-///  - &s.zz[1].yy -> s, if zz is an array
-///  - *(x + 1) -> x, if x is an array
-///  - &"123"[2] -> 0
-///  - & __real__ x -> x
-///
-/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
-/// members.
-static ValueDecl *getPrimaryDecl(Expr *E) {
+namespace {
+enum {
+  AO_Bit_Field = 0,
+  AO_Vector_Element = 1,
+  AO_Property_Expansion = 2,
+  AO_Register_Variable = 3,
+  AO_Matrix_Element = 4,
+  AO_Register_Compound_Literal = 5,
+  AO_No_Error = 6
+};
+}
+
+using PrimaryObject = llvm::PointerUnion<ValueDecl *, CompoundLiteralExpr *>;
+
+static PrimaryObject getPrimaryObject(Expr *E) {
+  E = E->IgnoreParens();
   switch (E->getStmtClass()) {
   case Stmt::DeclRefExprClass:
     return cast<DeclRefExpr>(E)->getDecl();
+  case Stmt::CompoundLiteralExprClass:
+    return cast<CompoundLiteralExpr>(E);
   case Stmt::MemberExprClass:
-    // If this is an arrow operator, the address is an offset from
-    // the base's value, so the object the base refers to is
-    // irrelevant.
     if (cast<MemberExpr>(E)->isArrow())
-      return nullptr;
-    // Otherwise, the expression refers to a part of the base
-    return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
+      return {};
+    return getPrimaryObject(cast<MemberExpr>(E)->getBase());
   case Stmt::ArraySubscriptExprClass: {
-    // FIXME: This code shouldn't be necessary!  We should catch the implicit
-    // promotion of register arrays earlier.
-    Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
-    if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
-      if (ICE->getSubExpr()->getType()->isArrayType())
-        return getPrimaryDecl(ICE->getSubExpr());
-    }
-    return nullptr;
+    Expr *Base = cast<ArraySubscriptExpr>(E)->getBase()->IgnoreParens();
+    if (auto *ICE = dyn_cast<ImplicitCastExpr>(Base);
+        ICE && ICE->getSubExpr()->getType()->isArrayType())
+      return getPrimaryObject(ICE->getSubExpr());
+    return {};
   }
   case Stmt::UnaryOperatorClass: {
     UnaryOperator *UO = cast<UnaryOperator>(E);
-
-    switch(UO->getOpcode()) {
-    case UO_Real:
-    case UO_Imag:
-    case UO_Extension:
-      return getPrimaryDecl(UO->getSubExpr());
-    default:
-      return nullptr;
-    }
+    if (UO->getOpcode() == UO_Real || UO->getOpcode() == UO_Imag ||
+        UO->getOpcode() == UO_Extension)
+      return getPrimaryObject(UO->getSubExpr());
+    return {};
   }
-  case Stmt::ParenExprClass:
-    return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
   case Stmt::ImplicitCastExprClass:
-    // If the result of an implicit cast is an l-value, we care about
-    // the sub-expression; otherwise, the result here doesn't matter.
-    return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
+    return getPrimaryObject(cast<ImplicitCastExpr>(E)->getSubExpr());
   case Stmt::CXXUuidofExprClass:
     return cast<CXXUuidofExpr>(E)->getGuidDecl();
   default:
-    return nullptr;
+    return {};
   }
 }
 
-namespace {
-enum {
-  AO_Bit_Field = 0,
-  AO_Vector_Element = 1,
-  AO_Property_Expansion = 2,
-  AO_Register_Variable = 3,
-  AO_Matrix_Element = 4,
-  AO_No_Error = 5
-};
-}
 /// Diagnose invalid operand for address of operations.
 ///
 /// \param Type The type of operand which cannot have its address taken.
@@ -15333,7 +15458,8 @@ QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
     // Technically, there should be a check for array subscript
     // expressions here, but the result of one is always an lvalue anyway.
   }
-  ValueDecl *dcl = getPrimaryDecl(op);
+  PrimaryObject Primary = getPrimaryObject(op);
+  ValueDecl *dcl = Primary.dyn_cast<ValueDecl *>();
 
   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
@@ -15484,6 +15610,10 @@ QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
                     NonTypeTemplateParmDecl, BindingDecl, MSGuidDecl,
                     UnnamedGlobalConstantDecl>(dcl))
       llvm_unreachable("Unknown/unexpected decl type");
+  } else if (!getLangOpts().CPlusPlus) {
+    if (auto *CLE = Primary.dyn_cast<CompoundLiteralExpr *>();
+        CLE && CLE->getStorageClass() == SC_Register)
+      AddressOfError = AO_Register_Compound_Literal;
   }
 
   if (AddressOfError != AO_No_Error) {
diff --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index d9134c052fa9df..1db750875db0b5 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -193,18 +193,15 @@ static void updateGNUCompoundLiteralRValue(Expr *E) {
   }
 }
 
-static bool initializingConstexprVariable(const InitializedEntity &Entity) {
-  Decl *D = Entity.getDecl();
-  const InitializedEntity *Parent = &Entity;
-
-  while (Parent) {
-    D = Parent->getDecl();
-    Parent = Parent->getParent();
+static bool initializingConstexprObject(const InitializedEntity &Entity) {
+  for (const InitializedEntity *Parent = &Entity; Parent;
+       Parent = Parent->getParent()) {
+    if (Parent->isConstexprCompoundLiteral())
+      return true;
+    if (const auto *VD = dyn_cast_if_present<VarDecl>(Parent->getDecl());
+        VD && VD->isConstexpr())
+      return true;
   }
-
-  if (const auto *VD = dyn_cast_if_present<VarDecl>(D); VD && VD->isConstexpr())
-    return true;
-
   return false;
 }
 
@@ -1299,6 +1296,7 @@ static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
   case InitializedEntity::EK_New:
   case InitializedEntity::EK_Temporary:
   case InitializedEntity::EK_CompoundLiteralInit:
+  case InitializedEntity::EK_ConstexprCompoundLiteralInit:
     // No warning, braces are part of the syntax of the underlying construct.
     break;
 
@@ -1428,7 +1426,8 @@ void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
     // parts.
     CheckComplexType(Entity, IList, DeclType, Index,
                      StructuredList, StructuredIndex);
-  } else if (DeclType->isScalarType()) {
+  } else if (DeclType->isScalarType() ||
+             (!SemaRef.getLangOpts().CPlusPlus && DeclType->isAtomicType())) {
     CheckScalarType(Entity, IList, DeclType, Index,
                     StructuredList, StructuredIndex);
   } else if (DeclType->isVectorType()) {
@@ -1618,7 +1617,7 @@ void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
       if (!VerifyOnly)
         CheckStringInit(expr, ElemType, arrayType, SemaRef, Entity,
                         SemaRef.getLangOpts().C23 &&
-                            initializingConstexprVariable(Entity));
+                            initializingConstexprObject(Entity));
       if (StructuredList)
         UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
       ++Index;
@@ -2169,7 +2168,7 @@ void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
       if (!VerifyOnly)
         CheckStringInit(
             IList->getInit(Index), DeclType, arrayType, SemaRef, Entity,
-            SemaRef.getLangOpts().C23 && initializingConstexprVariable(Entity));
+            SemaRef.getLangOpts().C23 && initializingConstexprObject(Entity));
       if (StructuredList) {
         UpdateStructuredListElement(StructuredList, StructuredIndex,
                                     IList->getInit(Index));
@@ -3836,6 +3835,7 @@ DeclarationName InitializedEntity::getName() const {
   case EK_BlockElement:
   case EK_LambdaToBlockConversionBlockElement:
   case EK_CompoundLiteralInit:
+  case EK_ConstexprCompoundLiteralInit:
   case EK_RelatedResult:
     return DeclarationName();
   }
@@ -3871,6 +3871,7 @@ ValueDecl *InitializedEntity::getDecl() const {
   case EK_LambdaToBlockConversionBlockElement:
   case EK_LambdaCapture:
   case EK_CompoundLiteralInit:
+  case EK_ConstexprCompoundLiteralInit:
   case EK_RelatedResult:
     return nullptr;
   }
@@ -3895,6 +3896,7 @@ bool InitializedEntity::allowsNRVO() const {
   case EK_New:
   case EK_Temporary:
   case EK_CompoundLiteralInit:
+  case EK_ConstexprCompoundLiteralInit:
   case EK_Base:
   case EK_Delegating:
   case EK_ArrayElement:
@@ -3934,6 +3936,9 @@ unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
   case EK_New: OS << "New"; break;
   case EK_Temporary: OS << "Temporary"; break;
   case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
+  case EK_ConstexprCompoundLiteralInit:
+    OS << "ConstexprCompoundLiteral";
+    break;
   case EK_RelatedResult: OS << "RelatedResult"; break;
   case EK_Base: OS << "Base"; break;
   case EK_Delegating: OS << "Delegating"; break;
@@ -4958,7 +4963,8 @@ static void TryReferenceListInitialization(Sema &S,
     return;
   }
   // Can't reference initialize a compound literal.
-  if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) {
+  if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit ||
+      Entity.getKind() == InitializedEntity::EK_ConstexprCompoundLiteralInit) {
     Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
     return;
   }
@@ -7225,6 +7231,7 @@ static AssignmentAction getAssignmentAction(const InitializedEntity &Entity,
   case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
   case InitializedEntity::EK_LambdaCapture:
   case InitializedEntity::EK_CompoundLiteralInit:
+  case InitializedEntity::EK_ConstexprCompoundLiteralInit:
     return AssignmentAction::Initializing;
   }
 
@@ -7252,6 +7259,7 @@ static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
   case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
   case InitializedEntity::EK_LambdaCapture:
   case InitializedEntity::EK_CompoundLiteralInit:
+  case InitializedEntity::EK_ConstexprCompoundLiteralInit:
   case InitializedEntity::EK_TemplateParameter:
     return false;
 
@@ -7294,6 +7302,7 @@ static bool shouldDestroyEntity(const InitializedEntity &Entity) {
     case InitializedEntity::EK_ArrayElement:
     case InitializedEntity::EK_Exception:
     case InitializedEntity::EK_CompoundLiteralInit:
+    case InitializedEntity::EK_ConstexprCompoundLiteralInit:
     case InitializedEntity::EK_RelatedResult:
       return true;
   }
@@ -7335,6 +7344,7 @@ static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
   case InitializedEntity::EK_BlockElement:
   case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
   case InitializedEntity::EK_CompoundLiteralInit:
+  case InitializedEntity::EK_ConstexprCompoundLiteralInit:
   case InitializedEntity::EK_RelatedResult:
     return Initializer->getBeginLoc();
   }
@@ -7591,6 +7601,7 @@ static bool isExplicitTemporary(const InitializedEntity &Entity,
   switch (Entity.getKind()) {
   case InitializedEntity::EK_Temporary:
   case InitializedEntity::EK_CompoundLiteralInit:
+  case InitializedEntity::EK_ConstexprCompoundLiteralInit:
   case InitializedEntity::EK_RelatedResult:
     break;
   default:
@@ -8609,7 +8620,7 @@ ExprResult InitializationSequence::Perform(Sema &S,
         return ExprError();
       CurInit = CurInitExprRes;
 
-      if (S.getLangOpts().C23 && initializingConstexprVariable(Entity) &&
+      if (S.getLangOpts().C23 && initializingConstexprObject(Entity) &&
           !CurInit.get()->containsErrors()) {
         CheckC23ConstexprInitConversion(S, SourceType, Entity.getType(),
                                         CurInit.get());
@@ -8654,7 +8665,7 @@ ExprResult InitializationSequence::Perform(Sema &S,
       CheckStringInit(CurInit.get(), UpdateType ? *ResultType : Ty,
                       S.Context.getAsArrayType(Ty), S, Entity,
                       S.getLangOpts().C23 &&
-                          initializingConstexprVariable(Entity));
+                          initializingConstexprObject(Entity));
       break;
     }
 
diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index 8219d5568bdfdd..74567d0a48b4ab 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -40,6 +40,7 @@
 #include "clang/Sema/SemaProxy.h"
 #include "clang/Sema/Template.h"
 #include "clang/Sema/TemplateDeduction.h"
+#include "llvm/ADT/APFloat.h"
 #include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/STLForwardCompat.h"
@@ -382,6 +383,91 @@ static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
   return Converted;
 }
 
+static bool isExactFloatingConversion(llvm::APFloat Value,
+                                      const llvm::fltSemantics &Semantics) {
+  bool Ignored;
+  return Value.isNaN() ||
+         Value.convert(Semantics, llvm::APFloat::rmNearestTiesToEven,
+                       &Ignored) == llvm::APFloat::opOK;
+}
+
+static bool isExactFloatingConversion(const llvm::APSInt &Value,
+                                      const llvm::fltSemantics &Semantics) {
+  llvm::APFloat Result(Semantics);
+  Result.convertFromAPInt(Value, Value.isSigned(),
+                          llvm::APFloat::rmNearestTiesToEven);
+  llvm::APSInt ConvertedValue = Value;
+  bool Ignored;
+  llvm::APFloat::opStatus Status = Result.convertToInteger(
+      ConvertedValue, llvm::APFloat::rmTowardZero, &Ignored);
+  return Status != llvm::APFloat::opInvalidOp && Value == ConvertedValue;
+}
+
+static bool isExactFloatingConversion(const APValue &Value,
+                                      const llvm::fltSemantics &Semantics) {
+  if (Value.isInt())
+    return isExactFloatingConversion(Value.getInt(), Semantics);
+  if (Value.isFloat())
+    return isExactFloatingConversion(Value.getFloat(), Semantics);
+  return isExactFloatingConversion(Value.getComplexFloatReal(), Semantics) &&
+         isExactFloatingConversion(Value.getComplexFloatImag(), Semantics);
+}
+
+static NarrowingKind getC23FloatingNarrowingKind(
+    ASTContext &Ctx, const StandardConversionSequence &SCS,
+    const Expr *Converted, APValue &ConstantValue, QualType &ConstantType,
+    bool IgnoreFloatToIntegralConversion) {
+  switch (SCS.Second) {
+  case ICK_Floating_Promotion:
+  case ICK_Floating_Conversion:
+  case ICK_Floating_Integral:
+  case ICK_Complex_Real:
+  case ICK_Complex_Promotion:
+  case ICK_Complex_Conversion:
+    break;
+  default:
+    return NK_Not_Narrowing;
+  }
+
+  QualType FromType = SCS.getToType(0);
+  QualType ToType = SCS.getToType(1);
+  if (FromType->isComplexType() && !ToType->isComplexType())
+    return NK_Type_Narrowing;
+
+  bool FromInteger = FromType->isIntegralOrUnscopedEnumerationType();
+  if (!FromInteger && !FromType->isFloatingType())
+    return NK_Not_Narrowing;
+  if (FromInteger && IgnoreFloatToIntegralConversion)
+    return NK_Not_Narrowing;
+
+  const Expr *Initializer = Converted->IgnoreParenImpCasts();
+  if (Initializer->isValueDependent())
+    return NK_Dependent_Narrowing;
+
+  Expr::EvalResult Result;
+  if (!Initializer->EvaluateAsRValue(Result, Ctx,
+                                     /*isConstantContext=*/true))
+    return NK_Variable_Narrowing;
+  if (FromInteger && !Result.Val.isInt())
+    return NK_Variable_Narrowing;
+
+  ConstantValue = std::move(Result.Val);
+  ConstantType = Initializer->getType();
+  if (ToType->isComplexType())
+    ToType = ToType->castAs<ComplexType>()->getElementType();
+
+  // C23 6.7.2p6: A real signaling NaN initializer must have a type
+  // compatible with the corresponding real type of the object.
+  if (ConstantValue.isFloat() && ConstantValue.getFloat().isSignaling() &&
+      !Ctx.typesAreCompatible(ConstantType.getUnqualifiedType(),
+                              ToType.getUnqualifiedType()))
+    return NK_Constant_Narrowing;
+  return isExactFloatingConversion(ConstantValue,
+                                   Ctx.getFloatTypeSemantics(ToType))
+             ? NK_Not_Narrowing
+             : NK_Constant_Narrowing;
+}
+
 /// Check if this standard conversion sequence represents a narrowing
 /// conversion, according to C++11 [dcl.init.list]p7.
 ///
@@ -413,6 +499,11 @@ NarrowingKind StandardConversionSequence::getNarrowingKind(
   if (const auto *ED = ToType->getAsEnumDecl())
     ToType = ED->getIntegerType();
 
+  if (Ctx.getLangOpts().C23 && ToType->isFloatingType())
+    return getC23FloatingNarrowingKind(Ctx, *this, Converted, ConstantValue,
+                                       ConstantType,
+                                       IgnoreFloatToIntegralConversion);
+
   switch (Second) {
   // 'bool' is an integral type; dispatch to the right place to handle it.
   case ICK_Boolean_Conversion:
@@ -446,19 +537,8 @@ NarrowingKind StandardConversionSequence::getNarrowingKind(
 
       if (std::optional<llvm::APSInt> IntConstantValue =
               Initializer->getIntegerConstantExpr(Ctx)) {
-        // Convert the integer to the floating type.
-        llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
-        Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
-                                llvm::APFloat::rmNearestTiesToEven);
-        // And back.
-        llvm::APSInt ConvertedValue = *IntConstantValue;
-        bool ignored;
-        llvm::APFloat::opStatus Status = Result.convertToInteger(
-            ConvertedValue, llvm::APFloat::rmTowardZero, &ignored);
-        // If the converted-back integer has unspecified value, or if the
-        // resulting value is different, this was a narrowing conversion.
-        if (Status == llvm::APFloat::opInvalidOp ||
-            *IntConstantValue != ConvertedValue) {
+        if (!isExactFloatingConversion(*IntConstantValue,
+                                       Ctx.getFloatTypeSemantics(ToType))) {
           ConstantValue = APValue(*IntConstantValue);
           ConstantType = Initializer->getType();
           return NK_Constant_Narrowing;
@@ -484,14 +564,8 @@ NarrowingKind StandardConversionSequence::getNarrowingKind(
       if (Initializer->isValueDependent())
         return NK_Dependent_Narrowing;
 
-      Expr::EvalResult R;
-      if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(R, Ctx)) ||
-          ((Ctx.getLangOpts().CPlusPlus &&
-            Initializer->isCXX11ConstantExpr(Ctx, ConstantValue,
-                                             AllowRelaxedEval)))) {
-        // Constant!
-        if (Ctx.getLangOpts().C23)
-          ConstantValue = R.Val;
+      if (Initializer->isCXX11ConstantExpr(Ctx, ConstantValue,
+                                           AllowRelaxedEval)) {
         assert(ConstantValue.isFloat());
         llvm::APFloat FloatVal = ConstantValue.getFloat();
         // Convert the source value into the target type.
@@ -500,27 +574,11 @@ NarrowingKind StandardConversionSequence::getNarrowingKind(
         llvm::APFloat::opStatus ConvertStatus =
             Converted.convert(Ctx.getFloatTypeSemantics(ToType),
                               llvm::APFloat::rmNearestTiesToEven, &ignored);
-        Converted.convert(Ctx.getFloatTypeSemantics(FromType),
-                          llvm::APFloat::rmNearestTiesToEven, &ignored);
-        if (Ctx.getLangOpts().C23) {
-          if (FloatVal.isNaN() && Converted.isNaN() &&
-              !FloatVal.isSignaling() && !Converted.isSignaling()) {
-            // Quiet NaNs are considered the same value, regardless of
-            // payloads.
-            return NK_Not_Narrowing;
-          }
-          // For normal values, check exact equality.
-          if (!Converted.bitwiseIsEqual(FloatVal)) {
-            ConstantType = Initializer->getType();
-            return NK_Constant_Narrowing;
-          }
-        } else {
-          // If there was no overflow, the source value is within the range of
-          // values that can be represented.
-          if (ConvertStatus & llvm::APFloat::opOverflow) {
-            ConstantType = Initializer->getType();
-            return NK_Constant_Narrowing;
-          }
+        // If there was no overflow, the source value is within the range of
+        // values that can be represented.
+        if (ConvertStatus & llvm::APFloat::opOverflow) {
+          ConstantType = Initializer->getType();
+          return NK_Constant_Narrowing;
         }
       } else {
         return NK_Variable_Narrowing;
@@ -623,26 +681,6 @@ NarrowingKind StandardConversionSequence::getNarrowingKind(
     if (FromType->isComplexType() && !ToType->isComplexType())
       return NK_Type_Narrowing;
     return NK_Not_Narrowing;
-
-  case ICK_Floating_Promotion:
-    if (Ctx.getLangOpts().C23) {
-      const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
-      Expr::EvalResult R;
-      if (Initializer->EvaluateAsRValue(R, Ctx)) {
-        ConstantValue = R.Val;
-        assert(ConstantValue.isFloat());
-        llvm::APFloat FloatVal = ConstantValue.getFloat();
-        // C23 6.7.3p6 If the initializer has real type and a signaling NaN
-        // value, the unqualified versions of the type of the initializer and
-        // the corresponding real type of the object declared shall be
-        // compatible.
-        if (FloatVal.isNaN() && FloatVal.isSignaling()) {
-          ConstantType = Initializer->getType();
-          return NK_Constant_Narrowing;
-        }
-      }
-    }
-    return NK_Not_Narrowing;
   default:
     // Other kinds of conversions are not narrowings.
     return NK_Not_Narrowing;
diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index b56d00a65187f3..9f9320196a0a32 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -3128,12 +3128,13 @@ class TreeTransform {
   ///
   /// By default, performs semantic analysis to build the new expression.
   /// Subclasses may override this routine to provide different behavior.
-  ExprResult RebuildCompoundLiteralExpr(SourceLocation LParenLoc,
-                                              TypeSourceInfo *TInfo,
-                                              SourceLocation RParenLoc,
-                                              Expr *Init) {
-    return getSema().BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc,
-                                              Init);
+  ExprResult RebuildCompoundLiteralExpr(
+      SourceLocation LParenLoc, TypeSourceInfo *TInfo, SourceLocation RParenLoc,
+      Expr *Init, StorageClass SC = SC_None,
+      ThreadStorageClassSpecifier TSC = TSCS_unspecified,
+      ConstexprSpecKind ConstexprKind = ConstexprSpecKind::Unspecified) {
+    return getSema().BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, Init,
+                                              SC, TSC, ConstexprKind);
   }
 
   /// Build a new extended vector or matrix element access expression.
@@ -14546,7 +14547,10 @@ TreeTransform<Derived>::TransformCompoundLiteralExpr(CompoundLiteralExpr *E) {
 
   return getDerived().RebuildCompoundLiteralExpr(
       E->getLParenLoc(), NewT,
-      /*FIXME:*/ E->getInitializer()->getEndLoc(), Init.get());
+      /*FIXME:*/ E->getInitializer()->getEndLoc(), Init.get(),
+      E->getStorageClass(), E->getTSCSpec(),
+      E->isConstexpr() ? ConstexprSpecKind::Constexpr
+                       : ConstexprSpecKind::Unspecified);
 }
 
 template<typename Derived>
diff --git a/clang/lib/Serialization/ASTReaderStmt.cpp b/clang/lib/Serialization/ASTReaderStmt.cpp
index 26aee27c65e82f..56390298a409c1 100644
--- a/clang/lib/Serialization/ASTReaderStmt.cpp
+++ b/clang/lib/Serialization/ASTReaderStmt.cpp
@@ -1252,6 +1252,9 @@ void ASTStmtReader::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
   E->setTypeSourceInfo(readTypeSourceInfo());
   E->setInitializer(Record.readSubExpr());
   E->setFileScope(Record.readInt());
+  E->setStorageClass(static_cast<StorageClass>(Record.readInt()));
+  E->setTSCSpec(static_cast<ThreadStorageClassSpecifier>(Record.readInt()));
+  E->setConstexpr(Record.readInt());
 }
 
 void ASTStmtReader::VisitExtVectorElementExpr(ExtVectorElementExpr *E) {
diff --git a/clang/lib/Serialization/ASTWriterStmt.cpp b/clang/lib/Serialization/ASTWriterStmt.cpp
index c6e74fd19750a4..541b26b29e0e5b 100644
--- a/clang/lib/Serialization/ASTWriterStmt.cpp
+++ b/clang/lib/Serialization/ASTWriterStmt.cpp
@@ -1258,6 +1258,9 @@ void ASTStmtWriter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
   Record.AddTypeSourceInfo(E->getTypeSourceInfo());
   Record.AddStmt(E->getInitializer());
   Record.push_back(E->isFileScope());
+  Record.push_back(E->getStorageClass());
+  Record.push_back(E->getTSCSpec());
+  Record.push_back(E->isConstexpr());
   Code = serialization::EXPR_COMPOUND_LITERAL;
 }
 
diff --git a/clang/test/AST/ByteCode/c.c b/clang/test/AST/ByteCode/c.c
index 55ef094b97cf5b..314929effd848d 100644
--- a/clang/test/AST/ByteCode/c.c
+++ b/clang/test/AST/ByteCode/c.c
@@ -253,6 +253,10 @@ void unaryops(void) {
   (void)((struct ww {float x;}){3}.x--);
 }
 
+void arrays(void) {
+  _Static_assert(((int[]){1})[0] == 1, ""); // pedantic-warning {{folding it to a constant is a GNU extension}}
+}
+
 /// Elements of a file-scope compound literal carry their evaluated value.
 static long *addr_as_int = (long[]){2, (long)"x"};
 static const char **into_string = (const char *[]){&"abc"[1]};
diff --git a/clang/test/AST/c23-compound-literal-print.c b/clang/test/AST/c23-compound-literal-print.c
new file mode 100644
index 00000000000000..f83313f7966949
--- /dev/null
+++ b/clang/test/AST/c23-compound-literal-print.c
@@ -0,0 +1,33 @@
+// RUN: %clang_cc1 -std=c23 -ast-print %s | FileCheck %s
+// RUN: %clang_cc1 -std=c23 -emit-pch -o %t %s
+// RUN: %clang_cc1 -std=c23 -include-pch %t -ast-print -x c /dev/null | FileCheck %s
+
+// CHECK-LABEL: int test1(void)
+// CHECK: return (constexpr int){1} + (static _Thread_local int){2} + (register int){3} + (constexpr const int){4} + (static __thread int){5};
+int test1(void) {
+  return (constexpr int){1} + (_Thread_local static int){2} + (register int){3} +
+         (constexpr const int){4} + (static __thread int){5};
+}
+
+// CHECK-LABEL: int test2(void)
+// CHECK: return (int[3]){1, 2, 3}[0] + (constexpr int[3]){1, 2, 3}[0];
+int test2(void) {
+  return (int[3]){1, 2, 3}[0] + (constexpr int[3]){1, 2, 3}[0];
+}
+
+typedef const int T;
+
+// CHECK-LABEL: int test3(void)
+// CHECK: return (constexpr T){1} + (constexpr int[]){1}[0] + (constexpr const int[]){1}[0] + (constexpr T[]){1}[0];
+int test3(void) {
+  return (constexpr T){1} + (constexpr int[]){1}[0] +
+         (constexpr const int[]){1}[0] + (constexpr T[]){1}[0];
+}
+
+// CHECK-LABEL: void test4(void)
+// CHECK: typedef typeof (*(int (*)[(static _Thread_local int){1}])0) T1;
+// CHECK: typedef typeof (*(int (*)[(register int){1}])0) T2;
+void test4(void) {
+  typedef typeof(*(int (*)[(static thread_local int){1}])0) T1;
+  typedef typeof(*(int (*)[(register int){1}])0) T2;
+}
diff --git a/clang/test/C/C23/n3006.c b/clang/test/C/C23/n3006.c
index 16352c37524272..8f77f7e3965fc4 100644
--- a/clang/test/C/C23/n3006.c
+++ b/clang/test/C/C23/n3006.c
@@ -47,12 +47,12 @@ void enum_test(void) {
 void constexpr_test(void) {
   constexpr auto ce_struct = (struct S1){ 1, 2 };                   // expected-error {{variable has incomplete type 'struct S1'}} \
                                                                        expected-note {{forward declaration of 'struct S1'}}
-  constexpr auto ce_struct_zero_init = (struct S2 { int x; }){ 0 };
-  constexpr int ce_struct_field = (struct S3 { int y; }){ 0 }.y;
+  constexpr auto ce_struct_zero_init = (constexpr struct S2 { int x; }){ 0 };
+  constexpr int ce_struct_field = (constexpr struct S3 { int y; }){ 0 }.y;
   constexpr auto ce_union = (union U1){ .a = 12 };                  // expected-error {{variable has incomplete type 'union U1'}} \
                                                                        expected-note {{forward declaration of 'union U1'}}
 
-  constexpr auto ce_enum = (enum E1 { BAZ, QUX }){ BAZ };
+  constexpr auto ce_enum = (constexpr enum E1 { BAZ, QUX }){ BAZ };
   constexpr auto ce_empty_enum = (enum E2){ FOO };                  // expected-error {{use of undeclared identifier 'FOO'}}
 }
 
@@ -71,14 +71,14 @@ void redefinition_test(void) {
 
 void declaring_an_underspecified_defied_object_test(void) {
   struct S { int x, y; };
-  constexpr int i = (struct T { int a, b; }){0, 1}.a;
+  constexpr int i = (constexpr struct T { int a, b; }){0, 1}.a;
 
   struct T t = { 1, 2 };
 }
 
 void constexpr_complience_test(void) {
   int x = (struct Foo { int x; }){ 0 }.x;
-  constexpr int y = (struct Bar { int x; }){ 0 }.x;
+  constexpr int y = (constexpr struct Bar { int x; }){ 0 }.x;
 }
 
 void builtin_functions_test(void) {
diff --git a/clang/test/C/drs/dr3xx.c b/clang/test/C/drs/dr3xx.c
index 0f67470b013a5d..e5d85dca78122a 100644
--- a/clang/test/C/drs/dr3xx.c
+++ b/clang/test/C/drs/dr3xx.c
@@ -226,6 +226,7 @@ extern int dr339_v;
 void *dr339 = &(int (*)[dr339_v]){ 0 }; /* c89only-warning {{variable length arrays are a C99 feature}}
                                            c99andup-warning {{variable length array used}}
                                            c89only-warning {{compound literals are a C99-specific feature}}
+                                           c23andup-error {{variably modified type declaration not allowed at file scope}}
                                          */
 
 /* WG14 DR340: yes
diff --git a/clang/test/CIR/CodeGen/c23-compound-literal.c b/clang/test/CIR/CodeGen/c23-compound-literal.c
new file mode 100644
index 00000000000000..ad8d61f0a882db
--- /dev/null
+++ b/clang/test/CIR/CodeGen/c23-compound-literal.c
@@ -0,0 +1,83 @@
+// RUN: %clang_cc1 -std=c23 -triple x86_64-unknown-linux-gnu -fclangir -emit-cir %s -o - | FileCheck %s --check-prefix=CIR
+// RUN: %clang_cc1 -std=c23 -triple x86_64-unknown-linux-gnu -fclangir -emit-llvm %s -o - | FileCheck %s --check-prefix=LLVM
+
+struct S { int a; int b; };
+
+// CIR-DAG: cir.global "private" internal @".compoundliteral" = #cir.int<0> : !s32i align(4)
+// CIR-DAG: cir.global "private" internal tls_model = tls_dyn @".compoundliteral.1" = #cir.int<0> : !s32i align(4)
+// CIR-DAG: cir.global "private" constant internal @".compoundliteral.2" = #cir.int<3> : !s32i align(4)
+// CIR-DAG: cir.global "private" internal @".compoundliteral.3" = #cir.const_record<{#cir.int<4> : !s32i, #cir.int<5> : !s32i}> : !rec_S align(4)
+// CIR-DAG: cir.global "private" internal tls_model = tls_dyn @".compoundliteral.4" = #cir.const_record<{#cir.int<6> : !s32i, #cir.int<7> : !s32i}> : !rec_S align(4)
+// CIR-DAG: cir.global "private" internal @".compoundliteral.5" = #cir.ptr<null> : !cir.ptr<!s32i> align(8)
+
+// LLVM-DAG: @.compoundliteral = internal global i32 0, align 4
+// LLVM-DAG: @.compoundliteral.1 = internal thread_local global i32 0, align 4
+// LLVM-DAG: @.compoundliteral.2 = internal constant i32 3, align 4
+// LLVM-DAG: @.compoundliteral.3 = internal global %struct.S { i32 4, i32 5 }, align 4
+// LLVM-DAG: @.compoundliteral.4 = internal thread_local global %struct.S { i32 6, i32 7 }, align 4
+// LLVM-DAG: @.compoundliteral.5 = internal global ptr null, align 8
+
+// CIR-LABEL: @test1()
+// CIR: %[[ADDR:.*]] = cir.get_global @".compoundliteral" : !cir.ptr<!s32i>
+// CIR-NEXT: %[[VALUE:.*]] = cir.load align(4) %[[ADDR]]
+// CIR-NEXT: %[[INC:.*]] = cir.inc nsw %[[VALUE]]
+// CIR-NEXT: cir.store align(4) %[[INC]], %[[ADDR]]
+// LLVM-LABEL: @test1()
+// LLVM: %[[VALUE:.*]] = load i32, ptr @.compoundliteral, align 4
+// LLVM-NEXT: %[[INC:.*]] = add nsw i32 %[[VALUE]], 1
+// LLVM-NEXT: store i32 %[[INC]], ptr @.compoundliteral, align 4
+int test1(void) {
+  return ++(static int){0};
+}
+
+// CIR-LABEL: @test2()
+// CIR: %[[ADDR:.*]] = cir.get_global thread_local @".compoundliteral.1" : !cir.ptr<!s32i>
+// CIR-NEXT: %[[VALUE:.*]] = cir.load align(4) %[[ADDR]]
+// CIR-NEXT: %[[INC:.*]] = cir.inc nsw %[[VALUE]]
+// CIR-NEXT: cir.store align(4) %[[INC]], %[[ADDR]]
+// LLVM-LABEL: @test2()
+// LLVM: %[[ADDR:.*]] = call{{.*}} ptr @llvm.threadlocal.address.p0(ptr{{.*}} @.compoundliteral.1)
+// LLVM-NEXT: %[[VALUE:.*]] = load i32, ptr %[[ADDR]], align 4
+// LLVM-NEXT: %[[INC:.*]] = add nsw i32 %[[VALUE]], 1
+// LLVM-NEXT: store i32 %[[INC]], ptr %[[ADDR]], align 4
+int test2(void) {
+  return ++(static thread_local int){0};
+}
+
+// CIR-LABEL: @test3()
+// CIR: cir.get_global @".compoundliteral.2" : !cir.ptr<!s32i>
+// LLVM-LABEL: @test3()
+// LLVM: store ptr @.compoundliteral.2, ptr
+const int *test3(void) {
+  return &(static constexpr int){3};
+}
+
+// CIR-LABEL: @test4()
+// CIR: %[[ADDR:.*]] = cir.get_global @".compoundliteral.3" : !cir.ptr<!rec_S>
+// CIR: cir.copy %[[ADDR]] align(4) to
+// LLVM-LABEL: @test4()
+// LLVM: call void @llvm.memcpy{{.*}}(ptr{{.*}}, ptr align 4 @.compoundliteral.3, i64 8, i1 false)
+struct S test4(void) {
+  return (static struct S){4, 5};
+}
+
+// CIR-LABEL: @test5()
+// CIR: %[[ADDR:.*]] = cir.get_global thread_local @".compoundliteral.4" : !cir.ptr<!rec_S>
+// CIR: cir.copy %[[ADDR]] align(4) to
+// LLVM-LABEL: @test5()
+// LLVM: %[[ADDR:.*]] = call{{.*}} ptr @llvm.threadlocal.address.p0(ptr{{.*}} @.compoundliteral.4)
+// LLVM: call void @llvm.memcpy{{.*}}(ptr{{.*}}, ptr align 4 %[[ADDR]], i64 8, i1 false)
+struct S test5(void) {
+  return (static thread_local struct S){6, 7};
+}
+
+// CIR-LABEL: @test6(
+// CIR: cir.inc nsw
+// CIR: cir.get_global @".compoundliteral.5"
+// LLVM-LABEL: @test6(
+// LLVM: add nsw i32 {{.*}}, 1
+// LLVM: load ptr, ptr @.compoundliteral.5, align 8
+int test6(int a) {
+  (void)(static int (*)[a++]){0};
+  return a;
+}
diff --git a/clang/test/CodeGen/c23-compound-literal.c b/clang/test/CodeGen/c23-compound-literal.c
new file mode 100644
index 00000000000000..c705cd170b968c
--- /dev/null
+++ b/clang/test/CodeGen/c23-compound-literal.c
@@ -0,0 +1,306 @@
+// RUN: %clang_cc1 -std=c23 -triple x86_64-unknown-linux-gnu -emit-llvm -o - %s | FileCheck %s
+// RUN: %clang_cc1 -std=c23 -triple x86_64-unknown-linux-gnu -emit-llvm -o - -fexperimental-new-constant-interpreter %s | FileCheck %s
+// RUN: %clang_cc1 -std=c23 -triple x86_64-unknown-linux-gnu -emit-llvm -O1 -disable-llvm-passes -o - %s | FileCheck %s --check-prefix=LIFETIME
+
+struct S { int a; int b; };
+
+// CHECK: @b = {{.*}}global i32 1
+
+// CHECK-LABEL: define dso_local i32 @test1()
+// CHECK: %[[VALUE:.*]] = load i32, ptr @.compoundliteral, align 4
+// CHECK-NEXT: ret i32 %[[VALUE]]
+int test1(void) {
+  return (static int){42};
+}
+
+// CHECK-LABEL: define dso_local i32 @test2()
+// CHECK: %.compoundliteral = alloca i32
+// CHECK: store i32 7, ptr %.compoundliteral
+// CHECK-NEXT: %[[VALUE:.*]] = load i32, ptr %.compoundliteral, align 4
+// CHECK-NEXT: ret i32 %[[VALUE]]
+int test2(void) {
+  return (constexpr int){7};
+}
+
+// CHECK-LABEL: define dso_local ptr @test3()
+// CHECK: ret ptr @.compoundliteral.1
+const int *test3(void) {
+  return &(static constexpr int){15};
+}
+
+// CHECK-LABEL: define dso_local i32 @test4()
+// CHECK: [[ADDR:%.*]] = call align 4 ptr @llvm.threadlocal.address.p0(ptr align 4 @.compoundliteral.2)
+// CHECK-NEXT: %[[VALUE:.*]] = load i32, ptr [[ADDR]], align 4
+// CHECK-NEXT: ret i32 %[[VALUE]]
+int test4(void) {
+  return (thread_local static int){2};
+}
+
+// CHECK-LABEL: define dso_local ptr @test5()
+// CHECK: [[ADDR:%.*]] = call align 4 ptr @llvm.threadlocal.address.p0(ptr align 4 @.compoundliteral.3)
+// CHECK-NEXT: ret ptr [[ADDR]]
+int *test5(void) {
+  return &(thread_local static int){2};
+}
+
+// CHECK-LABEL: define dso_local i32 @test6()
+// CHECK: store ptr @.compoundliteral.4, ptr %a, align 8
+// CHECK-NEXT: %[[BASE:.*]] = load ptr, ptr %a, align 8
+// CHECK-NEXT: %[[MEMBER:.*]] = getelementptr inbounds nuw %struct.S, ptr %[[BASE]], i32 0, i32 0
+// CHECK-NEXT: %[[VALUE:.*]] = load i32, ptr %[[MEMBER]], align 4
+// CHECK-NEXT: ret i32 %[[VALUE]]
+int test6(void) {
+  struct S *a = &(static struct S){1, 2};
+  return a->a;
+}
+
+// CHECK-LABEL: define dso_local i64 @test7()
+// CHECK: call void @llvm.memcpy.p0.p0.i64(ptr align 4 %retval, ptr align 4 @.compoundliteral.5, i64 8, i1 false)
+// CHECK-NEXT: %[[VALUE:.*]] = load i64, ptr %retval, align 4
+// CHECK-NEXT: ret i64 %[[VALUE]]
+struct S test7(void) {
+  return (static struct S){9, 10};
+}
+
+// CHECK-LABEL: define dso_local i64 @test8()
+// CHECK: [[ADDR:%.*]] = call align 4 ptr @llvm.threadlocal.address.p0(ptr align 4 @.compoundliteral.6)
+// CHECK-NEXT: call void @llvm.memcpy.p0.p0.i64(ptr align 4 %retval, ptr align 4 [[ADDR]], i64 8, i1 true)
+// CHECK-NEXT: %[[VALUE:.*]] = load i64, ptr %retval, align 4
+// CHECK-NEXT: ret i64 %[[VALUE]]
+struct S test8(void) {
+  return (thread_local static volatile struct S){11, 12};
+}
+
+// CHECK-LABEL: define dso_local i64 @test9()
+// CHECK: %.compoundliteral = alloca %struct.S
+// CHECK: store i32 13
+// CHECK: store i32 14
+// CHECK: call void @llvm.memcpy.p0.p0.i64(ptr align 4 %retval, ptr align 4 %.compoundliteral, i64 8, i1 true)
+// CHECK-NEXT: %[[VALUE:.*]] = load i64, ptr %retval, align 4
+// CHECK-NEXT: ret i64 %[[VALUE]]
+struct S test9(void) {
+  return (register volatile struct S){13, 14};
+}
+
+// CHECK-LABEL: define dso_local i32 @test10()
+// CHECK: %.compoundliteral = alloca %struct.S
+// CHECK: store i32 3
+// CHECK: store i32 4
+// CHECK: store ptr %.compoundliteral, ptr %a, align 8
+// CHECK-NEXT: %[[BASE:.*]] = load ptr, ptr %a, align 8
+// CHECK-NEXT: %[[MEMBER:.*]] = getelementptr inbounds nuw %struct.S, ptr %[[BASE]], i32 0, i32 0
+// CHECK-NEXT: %[[VALUE:.*]] = load i32, ptr %[[MEMBER]], align 4
+// CHECK-NEXT: ret i32 %[[VALUE]]
+int test10(void) {
+  const struct S *a = &(constexpr struct S){3, 4};
+  return a->a;
+}
+
+// CHECK-LABEL: define dso_local i32 @test11()
+// CHECK: %[[VALUE:.*]] = load i32, ptr @.compoundliteral.7, align 4
+// CHECK-NEXT: ret i32 %[[VALUE]]
+int test11(void) {
+  return (static int[]){5, 6, 7}[0];
+}
+
+// CHECK-LABEL: define dso_local i32 @test12()
+// CHECK: %.compoundliteral = alloca [3 x i32]
+// CHECK: store [3 x i32] [i32 8, i32 9, i32 10], ptr %.compoundliteral
+// CHECK: %[[ELEMENT:.*]] = getelementptr inbounds [3 x i32], ptr %.compoundliteral, i64 0, i64 0
+// CHECK-NEXT: %[[VALUE:.*]] = load i32, ptr %[[ELEMENT]], align 4
+// CHECK-NEXT: ret i32 %[[VALUE]]
+int test12(void) {
+  return (constexpr int[]){8, 9, 10}[0];
+}
+
+// CHECK-LABEL: define dso_local i32 @test13()
+// CHECK: %.compoundliteral = alloca i32
+// CHECK: store i32 99, ptr %.compoundliteral
+// CHECK-NEXT: %[[VALUE:.*]] = load i32, ptr %.compoundliteral, align 4
+// CHECK-NEXT: ret i32 %[[VALUE]]
+int test13(void) {
+  return (register constexpr int){99};
+}
+
+// CHECK-LABEL: define dso_local i32 @test14()
+// CHECK: %a = alloca i32
+// CHECK: store i32 16, ptr %a
+// CHECK-NEXT: %[[VALUE:.*]] = load atomic i32, ptr %a seq_cst, align 4
+// CHECK-NEXT: ret i32 %[[VALUE]]
+int test14(void) {
+  register _Atomic int a = 16;
+  return a;
+}
+
+// CHECK-LABEL: define dso_local i32 @test15()
+// CHECK: %.compoundliteral = alloca i32
+// CHECK: store i32 16, ptr %.compoundliteral
+// CHECK-NEXT: %[[VALUE:.*]] = load atomic i32, ptr %.compoundliteral seq_cst, align 4
+// CHECK-NEXT: ret i32 %[[VALUE]]
+int test15(void) {
+  return (register _Atomic int){16};
+}
+
+// CHECK-LABEL: define dso_local i64 @test16()
+// CHECK: %a = alloca %struct.S, align 8
+// CHECK: store i32 17
+// CHECK: store i32 18
+// CHECK: %[[VALUE:.*]] = load atomic i64, ptr %a seq_cst, align 8
+// CHECK-NEXT: store i64 %[[VALUE]], ptr %retval, align 4
+// CHECK-NEXT: %[[RESULT:.*]] = load i64, ptr %retval, align 4
+// CHECK-NEXT: ret i64 %[[RESULT]]
+struct S test16(void) {
+  register _Atomic(struct S) a = {(struct S){17, 18}};
+  return a;
+}
+
+// CHECK-LABEL: define dso_local i64 @test17()
+// CHECK: %.compoundliteral = alloca %struct.S, align 8
+// CHECK: store i32 17
+// CHECK: store i32 18
+// CHECK: %[[VALUE:.*]] = load atomic i64, ptr %.compoundliteral seq_cst, align 8
+// CHECK-NEXT: store i64 %[[VALUE]], ptr %retval, align 4
+// CHECK-NEXT: %[[RESULT:.*]] = load i64, ptr %retval, align 4
+// CHECK-NEXT: ret i64 %[[RESULT]]
+struct S test17(void) {
+  return (register _Atomic(struct S)){(struct S){17, 18}};
+}
+
+// CHECK-LABEL: define dso_local i32 @test18()
+// CHECK: %.compoundliteral = alloca i32
+// CHECK: store i32 5, ptr %.compoundliteral
+// CHECK-NEXT: %[[VALUE:.*]] = load i32, ptr %.compoundliteral, align 4
+// CHECK-NEXT: ret i32 %[[VALUE]]
+int test18(void) {
+  return (int){5};
+}
+
+// CHECK-LABEL: define dso_local i32 @test19(i32 noundef %a)
+// CHECK: %[[OLD:.*]] = load i32, ptr %a.addr, align 4
+// CHECK-NEXT: %[[INC:.*]] = add nsw i32 %[[OLD]], 1
+// CHECK-NEXT: store i32 %[[INC]], ptr %a.addr, align 4
+// CHECK: load ptr, ptr @.compoundliteral.8, align 8
+// CHECK: %[[RESULT:.*]] = load i32, ptr %a.addr, align 4
+// CHECK-NEXT: ret i32 %[[RESULT]]
+int test19(int a) {
+  (void)(static int (*)[a++]){0};
+  return a;
+}
+
+// CHECK-LABEL: define dso_local i32 @test20(i32 noundef %a)
+// CHECK: %[[OLD:.*]] = load i32, ptr %a.addr, align 4
+// CHECK-NEXT: %[[INC:.*]] = add nsw i32 %[[OLD]], 1
+// CHECK-NEXT: store i32 %[[INC]], ptr %a.addr, align 4
+// CHECK: %[[ADDR:.*]] = call align 8 ptr @llvm.threadlocal.address.p0(ptr align 8 @.compoundliteral.9)
+// CHECK-NEXT: load ptr, ptr %[[ADDR]], align 8
+// CHECK: %[[RESULT:.*]] = load i32, ptr %a.addr, align 4
+// CHECK-NEXT: ret i32 %[[RESULT]]
+int test20(int a) {
+  (void)(thread_local static int (*)[a++]){0};
+  return a;
+}
+
+int test21(void);
+
+// CHECK-LABEL: define dso_local i32 @test22(
+// CHECK: %.compoundliteral = alloca i32
+// CHECK: [[CALL:%call]] = call i32 @test21()
+// CHECK-NEXT: store i32 [[CALL]], ptr %.compoundliteral
+// CHECK-NEXT: %[[BOUND:.*]] = load i32, ptr %.compoundliteral, align 4
+// CHECK-NEXT: zext i32 %[[BOUND]] to i64
+// CHECK: ret i32
+// CHECK-NEXT: }
+int test22(int a[(int){test21()}]) {
+  return a[0];
+}
+
+// CHECK-LABEL: define dso_local i32 @test23(
+// CHECK: %.compoundliteral = alloca i32
+// CHECK: [[CALL:%call]] = call i32 @test21()
+// CHECK-NEXT: store i32 [[CALL]], ptr %.compoundliteral
+// CHECK-NEXT: %[[BOUND:.*]] = load i32, ptr %.compoundliteral, align 4
+// CHECK-NEXT: zext i32 %[[BOUND]] to i64
+// CHECK: ret i32
+// CHECK-NEXT: }
+int test23(int a[(register int){test21()}]) {
+  return a[0];
+}
+
+// CHECK-LABEL: define dso_local i32 @test24(
+// CHECK: %[[BOUND:.*]] = load volatile i32, ptr @.compoundliteral.10, align 4
+// CHECK-NEXT: zext i32 %[[BOUND]] to i64
+// CHECK: ret i32
+// CHECK-NEXT: }
+int test24(int a[(static volatile int){13}]) {
+  return a[0];
+}
+
+// CHECK-LABEL: define dso_local i32 @test25(
+// CHECK: [[ADDR:%.*]] = call align 4 ptr @llvm.threadlocal.address.p0(ptr align 4 @.compoundliteral.11)
+// CHECK-NEXT: %[[BOUND:.*]] = load volatile i32, ptr [[ADDR]], align 4
+// CHECK-NEXT: zext i32 %[[BOUND]] to i64
+// CHECK: ret i32
+// CHECK-NEXT: }
+int test25(int a[(static thread_local volatile int){14}]) {
+  return a[0];
+}
+
+// CHECK-LABEL: define dso_local i32 @test26(
+// CHECK-NOT: call i32 @test21()
+// CHECK-NOT: load volatile i32
+// CHECK: ret i32 0
+int test26(int b(int a[((int){test21()} + (static volatile int){15})])) {
+  return 0;
+}
+
+// CHECK-LABEL: define dso_local i32 @test27(
+// CHECK: %.compoundliteral = alloca i32
+// CHECK: [[CALL:%call]] = call i32 @test21()
+// CHECK-NEXT: store i32 [[CALL]], ptr %.compoundliteral
+// CHECK-NEXT: load i32, ptr %.compoundliteral, align 4
+// CHECK-NEXT: ret i32 0
+int test27(int (*a(void))[((void)(int){test21()}, 1)]) {
+  return 0;
+}
+
+int test28(const int *);
+
+// LIFETIME-LABEL: define dso_local i32 @test29(
+// LIFETIME: call void @llvm.lifetime.start.p0(ptr %.compoundliteral)
+// LIFETIME: call i32 @test28(ptr noundef %.compoundliteral)
+// LIFETIME-NOT: @llvm.lifetime.end
+// LIFETIME: %[[RESULT:.*]] = load i32, ptr %{{.*}}, align 4
+// LIFETIME-NEXT: call void @llvm.lifetime.end.p0(ptr %.compoundliteral)
+// LIFETIME-NEXT: ret i32 %[[RESULT]]
+// CHECK-LABEL: define dso_local i32 @test29(
+// CHECK: %.compoundliteral = alloca i32
+// CHECK: store i32 3, ptr %.compoundliteral
+// CHECK-NEXT: %[[CALL:.*]] = call i32 @test28(ptr noundef %.compoundliteral)
+// CHECK-NEXT: zext i32 %[[CALL]] to i64
+// CHECK: ret i32
+// CHECK-NEXT: }
+int test29(int a[test28(&(constexpr int){3})]) {
+  return a[0];
+}
+
+// CHECK-LABEL: define dso_local i64 @test30()
+// CHECK: %.compoundliteral = alloca %struct.S
+// CHECK: store i32 19
+// CHECK: store i32 20
+// CHECK: call void @llvm.memcpy.p0.p0.i64(ptr align 4 %retval, ptr align 4 %.compoundliteral, i64 8, i1 true)
+// CHECK-NEXT: %[[VALUE:.*]] = load i64, ptr %retval, align 4
+// CHECK-NEXT: ret i64 %[[VALUE]]
+struct S test30(void) {
+  return (volatile struct S){19, 20};
+}
+
+// CHECK-LABEL: define dso_local i32 @test31()
+// CHECK: [[ADDR:%.*]] = call align 4 ptr @llvm.threadlocal.address.p0(ptr align 4 @.compoundliteral
+// CHECK-NEXT: %[[VALUE:.*]] = load i32, ptr [[ADDR]], align 4
+// CHECK-NEXT: ret i32 %[[VALUE]]
+int test31(void) {
+  return (static __thread int){21};
+}
+
+const int a = 1;
+int b = (int){a};
diff --git a/clang/test/CodeGenObjC/c23-compound-literal.m b/clang/test/CodeGenObjC/c23-compound-literal.m
new file mode 100644
index 00000000000000..a69269e84c4a09
--- /dev/null
+++ b/clang/test/CodeGenObjC/c23-compound-literal.m
@@ -0,0 +1,37 @@
+// RUN: %clang_cc1 -std=c23 -triple x86_64-apple-macosx10.15 -emit-llvm -fobjc-arc -disable-llvm-passes -o - %s | FileCheck %s
+
+typedef struct {
+  id a;
+} S;
+int test1(const S *);
+
+// CHECK-LABEL: define i32 @test2(
+// CHECK: %.compoundliteral = alloca %struct.S, align 8
+// CHECK: store ptr null, ptr %{{.*}}, align 8
+// CHECK: %[[CALL:.*]] = call i32 @test1(ptr noundef %.compoundliteral)
+// CHECK-NEXT: zext i32 %[[CALL]] to i64
+// CHECK-NOT: call void @__destructor_8_s0(ptr %.compoundliteral)
+// CHECK: %[[RESULT:.*]] = load i32, ptr %{{.*}}, align 4
+// CHECK-NEXT: call void @__destructor_8_s0(ptr %.compoundliteral)
+// CHECK-NEXT: ret i32 %[[RESULT]]
+// CHECK-NEXT: }
+int test2(int a[test1(&(constexpr S){.a = 0})]) {
+  return a[0];
+}
+
+// CHECK-LABEL: define i32 @test3(
+// CHECK: %.compoundliteral = alloca %struct.S, align 8
+// CHECK: br i1 %{{.*}}, label %[[RETURN0:.*]], label %[[CONTINUE:.*]]
+// CHECK: [[RETURN0]]:
+// CHECK: br label %[[CLEANUP:.*]]
+// CHECK: [[CONTINUE]]:
+// CHECK: br label %[[CLEANUP]]
+// CHECK: [[CLEANUP]]:
+// CHECK-NEXT: call void @__destructor_8_s0(ptr %.compoundliteral)
+// CHECK-NEXT: %[[RESULT:.*]] = load i32, ptr %{{.*}}, align 4
+// CHECK-NEXT: ret i32 %[[RESULT]]
+int test3(int c, int a[test1(&(constexpr S){.a = 0})]) {
+  if (c)
+    return a[0];
+  return a[1];
+}
diff --git a/clang/test/Parser/c23-compound-literal.c b/clang/test/Parser/c23-compound-literal.c
new file mode 100644
index 00000000000000..1967f09c2258bd
--- /dev/null
+++ b/clang/test/Parser/c23-compound-literal.c
@@ -0,0 +1,32 @@
+// RUN: %clang_cc1 -std=c17 -fsyntax-only -verify=c17 %s
+// RUN: %clang_cc1 -x c++ -std=c++23 -fsyntax-only -verify=cxx %s
+
+void test1(void) {
+  (void)(static int){1}; // c17-error {{expected expression}} \
+                         // cxx-error {{type name does not allow storage class to be specified}}
+}
+
+void test2(void) {
+  (void)(register int){1}; // c17-error {{expected expression}} \
+                           // cxx-error {{type name does not allow storage class to be specified}}
+}
+
+void test3(void) {
+  (void)(thread_local int){1}; // c17-error {{use of undeclared identifier 'thread_local'}} \
+                               // cxx-error {{type name does not allow storage class to be specified}}
+}
+
+void test4(void) {
+  (void)(_Thread_local int){1}; // c17-error {{expected expression}} \
+                                // cxx-error {{type name does not allow storage class to be specified}}
+}
+
+void test5(void) {
+  (void)(__thread int){1}; // c17-error {{expected expression}} \
+                           // cxx-error {{type name does not allow storage class to be specified}}
+}
+
+void test6(void) {
+  (void)(constexpr int){1}; // c17-error {{use of undeclared identifier 'constexpr'}} \
+                            // cxx-error {{type name does not allow constexpr specifier to be specified}}
+}
diff --git a/clang/test/Parser/expressions.c b/clang/test/Parser/expressions.c
index 82556c091206fd..2921158dd5f352 100644
--- a/clang/test/Parser/expressions.c
+++ b/clang/test/Parser/expressions.c
@@ -1,4 +1,6 @@
-// RUN: %clang_cc1 -fsyntax-only -verify %s
+// RUN: %clang_cc1 -std=c17 -fsyntax-only -verify=expected,c17 %s
+// RUN: %clang_cc1 -std=c23 -Wpre-c23-compat -fsyntax-only -verify=expected,c23 %s
+// RUN: %clang_cc1 -std=c23 -triple x86_64-apple-darwin10 -fsyntax-only -verify=expected,notls %s
 
 void test1(void) {
   if (sizeof (int){ 1}) {}   // sizeof compound literal
@@ -73,3 +75,17 @@ void test8(void) {
   callee(foobar,   // expected-error {{use of undeclared identifier 'foobar'}}
          fizbin);  // expected-error {{use of undeclared identifier 'fizbin'}}
 }
+
+void test9(void) {
+  (void)(static int){1}; // c17-error {{expected expression}} \
+                         // c23-warning {{compound literal storage-class specifiers are incompatible with C standards before C23}}
+
+  (void)(register int){2}; // c17-error {{expected expression}} \
+                           // c23-warning {{compound literal storage-class specifiers are incompatible with C standards before C23}}
+
+  (void)(constexpr int){3}; // c17-error {{use of undeclared identifier 'constexpr'}} \
+                            // c23-warning {{compound literal storage-class specifiers are incompatible with C standards before C23}}
+
+  (void)(_Thread_local static int){4}; // c17-error {{expected expression}} notls-error {{thread-local storage is not supported for the current target}} \
+                                       // c23-warning {{compound literal storage-class specifiers are incompatible with C standards before C23}}
+}
diff --git a/clang/test/Sema/c23-compound-literal.c b/clang/test/Sema/c23-compound-literal.c
new file mode 100644
index 00000000000000..e3d209900f5ad5
--- /dev/null
+++ b/clang/test/Sema/c23-compound-literal.c
@@ -0,0 +1,417 @@
+// RUN: %clang_cc1 -std=c23 -triple x86_64-unknown-linux-gnu -verify -fsyntax-only %s
+// RUN: %clang_cc1 -std=c23 -triple x86_64-unknown-linux-gnu -verify -fsyntax-only -fexperimental-new-constant-interpreter %s
+// RUN: %clang_cc1 -std=c23 -triple x86_64-unknown-linux-gnu -verify -fsyntax-only -frecovery-ast -frecovery-ast-type %s
+// RUN: %clang_cc1 -std=c23 -triple x86_64-scei-ps4 -verify=expected,ps4 -fsyntax-only %s
+// RUN: %clang_cc1 -std=c23 -triple x86_64-unknown-linux-gnu -Werror=gnu-folding-constant -verify=expected,gnu %s
+// RUN: %clang_cc1 -std=c23 -triple x86_64-unknown-linux-gnu -Werror=gnu-folding-constant -verify=expected,gnu -fexperimental-new-constant-interpreter %s
+
+#define M static
+struct S { int a; char b; };
+int test1(void);
+
+void test2(void) {
+  (void)(constexpr int){1};
+  (void)&(static int){42};
+  (void)(register int){0};
+  (void)(static thread_local int){1};
+  (void)(static __thread int){2};
+  (void)(constexpr struct S){1, 'a'};
+  (void)(static struct S){2, 'b'};
+  (void)(register struct S){3, 'c'};
+}
+
+void test3(void) {
+  (void)(static constexpr int){1};
+  (void)(constexpr static int){2};
+  (void)(static thread_local int){3};
+  (void)(thread_local static int){4};
+  (void)(constexpr register int){5};
+  (void)(constexpr static thread_local int){6}; // expected-error {{cannot combine with previous '_Thread_local' declaration specifier}}
+}
+
+void test4(void) {
+  (void)(static static int){1};             // expected-warning {{duplicate 'static' declaration specifier}}
+  (void)(constexpr constexpr int){2};       // expected-warning {{duplicate 'constexpr' declaration specifier}}
+  (void)(register register int){3};         // expected-warning {{duplicate 'register' declaration specifier}}
+  (void)(thread_local thread_local int){4}; // expected-warning {{duplicate '_Thread_local' declaration specifier}} expected-error {{compound literal with 'thread_local' storage duration at block scope must also specify 'static'}}
+}
+
+void test5(void) {
+  (void)(register static int){1};       // expected-error {{cannot combine with previous 'register' declaration specifier}}
+  (void)(register thread_local int){2}; // expected-error {{cannot combine with previous 'register' declaration specifier}}
+  (void)(register constexpr int){3};
+  (void)(static register int){4};       // expected-error {{cannot combine with previous 'static' declaration specifier}}
+  (void)(register _Atomic int){5};
+}
+
+void test6(void) {
+  (void)&(thread_local int){1}; // expected-error {{compound literal with 'thread_local' storage duration at block scope must also specify 'static'}}
+}
+
+int *a1 = &(register int){42}; // expected-error {{file scope compound literal specifies 'register'}}
+
+void test7(void) {
+  (void)(constexpr volatile int){1}; // expected-error {{constexpr variable cannot have type 'const volatile int'}}
+  (void)(constexpr _Atomic int){1};  // expected-error {{constexpr variable cannot have type 'const _Atomic(int)'}}
+
+  int c;
+  (void)(constexpr int[c]){0}; // expected-error {{constexpr variable cannot have type 'const int[c]'}}
+}
+
+void test8(void) {
+  (void)(constexpr int){test1()};          // expected-error {{initializer of compound literal must be a constant expression}}
+  (void)(static int){test1()};             // expected-error {{initializer element is not a compile-time constant}}
+  (void)(register constexpr int){test1()}; // expected-error {{initializer of compound literal must be a constant expression}}
+  (void)(constexpr int){1 / 0};
+  // expected-error at -1 {{initializer of compound literal must be a constant expression}}
+  // expected-note at -2 {{division by zero}}
+  // expected-warning at -3 {{division by zero is undefined}}
+}
+
+const int a2 = 1;
+const double a3 = 1.0;
+
+void test9(void) {
+  constexpr int a = a2;                  // expected-error {{constexpr variable 'a' must be initialized by a constant expression}}
+  constexpr int b = (int){a2};           // expected-error {{constexpr variable 'b' must be initialized by a constant expression}}
+  constexpr int c = (constexpr int){a2}; // expected-error {{initializer of compound literal must be a constant expression}}
+
+  (void)(constexpr double){a3};          // expected-error {{initializer of compound literal must be a constant expression}}
+
+  const int d = 2;
+  (void)(constexpr int){d};              // expected-error {{initializer of compound literal must be a constant expression}}
+
+  struct S1 {
+    int a;
+  };
+
+  (void)(constexpr int){(constexpr int){1}};
+  (void)(constexpr struct S1){.a = (constexpr int){1}};
+  (void)(constexpr int){(int){1}};        // gnu-error {{reading a non-constexpr compound literal}}
+  (void)(constexpr int){(static int){1}}; // gnu-error {{reading a non-constexpr compound literal}}
+}
+
+void test10(void) {
+  int *a = &(register int){1};                           // expected-error {{address of register compound literal requested}}
+  int *b = (register int[1]){1};
+  struct S2 { int a; };
+  int *c = &(register struct S2){1}.a;                   // expected-error {{address of register compound literal requested}}
+  double *d = &__real__ (register _Complex double){1};   // expected-error {{address of register compound literal requested}}
+  double *e = &__imag__ (register _Complex double){1};   // expected-error {{address of register compound literal requested}}
+  int *f = &_Generic(0, int: (register int){1});         // expected-error {{address of register compound literal requested}}
+  int *g = _Generic(0, int: (register int[1]){1});
+  int *h = &_Generic(0, int: (register struct S2){1}).a; // expected-error {{address of register compound literal requested}}
+  int *i = &__extension__ (register int){1};             // expected-error {{address of register compound literal requested}}
+  int (*j)[1] = &(register int[1]){1};                   // expected-error {{address of register compound literal requested}}
+}
+
+int a5[1];
+struct S3 {
+  int *a;
+};
+struct S4 {
+  int a[1];
+};
+
+int *test11(void) {
+  return &((register struct S3){a5}.a[0]);
+}
+
+int *test12(void) {
+  return &(register struct S4){{1}}.a[0]; // expected-error {{address of register compound literal requested}}
+}
+
+enum { E1 = (constexpr int){42} };
+enum { E2 = (constexpr int){} };
+static int a6[(constexpr int){10}];
+static int a7[(constexpr int){} + 1];
+static const int *a8 = &(constexpr int){5};
+static int a9 = (constexpr int){7};
+static_assert(!(constexpr int){});
+
+struct S5 { int a; };
+enum { E3 = (constexpr struct S5){42}.a };
+enum { E4 = (int)(constexpr double){1.0} };
+
+union U1 {
+  int a;
+  long b;
+};
+enum { E5 = (constexpr union U1){.a = 9}.a };
+enum {
+  E6 = (constexpr union U1){.a = 9}.b
+  // expected-error at -1 {{expression is not an integer constant expression}}
+  // expected-note at -2 {{read of member 'b' of union with active member 'a' is not allowed in a constant expression}}
+};
+
+void test13(void) {
+  static int a = (constexpr int){8};
+  int b[(constexpr int){3}];
+  switch ((constexpr int){1}) {
+  case (constexpr int){1}:
+    break;
+  }
+}
+
+void test14(void) {
+  (constexpr int){1} = 2;             // expected-error {{read-only variable is not assignable}}
+  (constexpr int[1]){1}[0] = 2;       // expected-error {{read-only variable is not assignable}}
+  (constexpr struct S){1, 'a'}.a = 2; // expected-error {{read-only variable is not assignable}}
+}
+
+int *a10 = &(static int){100};
+int *a11 = &(thread_local int){200}; // expected-error {{initializer element is not a compile-time constant}}
+const int *a12 = &(constexpr int){300};
+
+void test15(void) {
+  const int *a = (constexpr int[]){1, 2, 3};
+  int *b = (static int[]){4, 5, 6};
+}
+
+int a13 = (thread_local int){1};              // expected-error {{initializer element is not a compile-time constant}}
+int a14 = (thread_local static int){1};       // expected-error {{initializer element is not a compile-time constant}}
+int a15 = 1 + (thread_local int){1};          // expected-error {{initializer element is not a compile-time constant}}
+int a16 = +(thread_local int){1};             // expected-error {{initializer element is not a compile-time constant}}
+int a17 = (thread_local struct S5){1}.a;      // expected-error {{initializer element is not a compile-time constant}}
+int a18 = *(thread_local int[1]){1};          // expected-error {{initializer element is not a compile-time constant}}
+
+struct S7 {
+  unsigned char a;
+};
+
+void test16(void) {
+  static int a;
+  (void)(constexpr int *){&a};     // expected-error {{constexpr pointer initializer is not null}}
+  (void)(constexpr struct S7){-1}; // expected-error {{constexpr initializer evaluates to -1 which is not exactly representable in type 'unsigned char'}}
+  (void)(constexpr float){0.1};    // expected-error {{constexpr initializer evaluates to}}
+}
+
+int a19[3];
+static int *a20 = a19 + (constexpr int){1};
+static int *a21 = (constexpr int){0}; // expected-warning {{expression which evaluates to zero treated as a null pointer constant of type 'int *'}}
+static int *a22 = (constexpr int *){0};
+
+struct S8 {
+  int *restrict a;
+};
+void test17(void) {
+  (void)(constexpr struct S8){0}; // expected-error {{constexpr variable cannot have type 'int *restrict'}}
+}
+
+void test18(void) {
+  (void)(constexpr char[]){"\xFF"};
+  (void)(constexpr unsigned char[]){"\xFF"}; // expected-error {{constexpr initializer evaluates to -1 which is not exactly representable in type 'const unsigned char'}}
+}
+
+void test19(void) {
+  static const int *a = &(constexpr int){1}; // expected-error {{initializer element is not a compile-time constant}}
+  static const int *b = &(static constexpr int){1};
+}
+
+void test20(int a[sizeof((static int){1})]);
+void test21(int a[sizeof((register int){1})]);
+void test22(int a[sizeof((constexpr int){1})]);
+void test23(int a[sizeof((thread_local static int){1})]);
+int test24(void);
+
+void test25(int a[(constexpr int){test24()}]); // expected-error {{initializer of compound literal must be a constant expression}}
+void test26(int a[(static int){test24()}]);    // expected-error {{initializer element is not a compile-time constant}}
+
+typedef void F1(int a[(int){test24()}]);
+typedef void F2(int a[(thread_local int){1}]); // expected-error {{compound literal with 'thread_local' storage duration at block scope must also specify 'static'}}
+void (*a23)(int a[(register int){test24()}]);
+
+typedef int T __attribute__((address_space(1)));
+void test27(int a[sizeof((T){0})]);  // expected-error {{compound literal in function scope may not be qualified with an address space}}
+int test28(int a[sizeof((T){0})]) {  // expected-error {{compound literal in function scope may not be qualified with an address space}}
+  return a[0];
+}
+
+void test29(void) {
+  (static T){0}; // expected-error {{compound literal in function scope may not be qualified with an address space}}
+}
+
+int test30(
+    typeof(sizeof((register T){0})) a(void)) { // expected-error {{compound literal in function scope may not be qualified with an address space}}
+  return a();
+}
+
+inline int test31(void) { // expected-note {{use 'static' to give inline function 'test31' internal linkage}}
+  return (static int){1}; // expected-warning {{non-constant static local variable in inline function may be different in different files}}
+}
+
+inline int test32(int a[(static int){1}]) { // expected-warning {{non-constant static local variable in inline function may be different in different files}} \
+                                            // expected-note {{use 'static' to give inline function 'test32' internal linkage}}
+  return a[0];
+}
+
+inline int test33(int a[(static int){1}]);
+
+inline int test34(int a[(static const int){1}]) {
+  return a[0];
+}
+
+extern inline int test35(int a[(static int){1}]) {
+  return a[0];
+}
+
+static inline int test36(int a[(static int){1}]) {
+  return a[0];
+}
+
+inline int test37(int b(int a[sizeof((static int){1})])) {
+  return 0;
+}
+
+inline int test38(int (*a(void))[sizeof((static int){1})]) { // expected-warning {{non-constant static local variable in inline function may be different in different files}}
+                                                             // expected-note at -1 {{use 'static' to give inline function 'test38' internal linkage}}
+  return 0;
+}
+
+inline typeof((static int){1}) test39(void) {
+  return 0;
+}
+typeof((register int){1}) test40(void); // expected-error {{file scope compound literal specifies 'register'}}
+
+inline int test41(int a) __attribute__((enable_if((static int){1}, "enabled"))) { // expected-warning {{non-constant static local variable in inline function may be different in different files}} \
+                                                                                  // expected-note {{use 'static' to give inline function 'test41' internal linkage}}
+  return a;
+}
+
+int test42(int a) __attribute__((enable_if(sizeof((register T){0}), "enabled"))) { // expected-error {{compound literal in function scope may not be qualified with an address space}}
+  return a;
+}
+
+int test43(int a) __attribute__((enable_if( sizeof((register T){0}), "enabled"))); // expected-error {{compound literal in function scope may not be qualified with an address space}}
+int test43(int a) {
+  return a;
+}
+
+int a24;
+int a25 = sizeof((thread_local static int (*)[a24]){0}); // expected-error {{variably modified type declaration not allowed at file scope}}
+
+int *test44(void) {
+  return &(static int){1};
+}
+
+int *test45(void) {
+  return &(thread_local static int){1};
+}
+
+int *test46(void) {
+  return &(int){1}; // expected-warning {{address of stack memory associated with compound literal '{1}' returned}}
+}
+
+const int *test47(void) {
+  return &(constexpr int){1}; // expected-warning {{address of stack memory associated with compound literal '{1}' returned}}
+}
+
+inline int test48(void) {              // expected-note {{use 'static' to give inline function 'test48' internal linkage}}
+  return (thread_local static int){1}; // expected-warning {{non-constant static local variable in inline function may be different in different files}}
+}
+
+void test49(void) {
+  (void)(M const int){1};
+  (void)(constexpr unsigned long){2};
+  (void)sizeof (static int){1};
+  (void)sizeof (static thread_local int){1};
+  (void)sizeof (constexpr int){1};
+}
+
+void test50(void) {
+  (void)(const static int){1};   // expected-error {{type name does not allow storage class to be specified}}
+  (void)(const int register){1}; // expected-error {{type name does not allow storage class to be specified}}
+}
+
+void test51(void) {
+  (void)(auto int){1};        // expected-error {{expected expression}}
+  (void)(extern int){2};      // expected-error {{expected expression}}
+  (void)(typedef int){3};     // expected-error {{expected expression}}
+  (void)(__auto_type int){4}; // expected-error {{expected expression}}
+  (void)(auto){1};            // expected-error {{expected expression}}
+}
+
+void test52(void) {
+  (void)(static int constexpr){1};     // expected-error {{type name does not allow constexpr specifier to be specified}}
+  (void)(static int thread_local){1};  // expected-error {{type name does not allow storage class to be specified}}
+  (void)(static int _Thread_local){1}; // expected-error {{type name does not allow storage class to be specified}}
+  (void)(static int __thread){1};      // expected-error {{type name does not allow storage class to be specified}}
+  (void)(int static){1};               // expected-error {{type name does not allow storage class to be specified}}
+}
+
+void test53(void) {
+  (void)(static int)1;              // expected-error {{type name does not allow storage class to be specified}}
+  (void)sizeof(register int);       // expected-error {{type name does not allow storage class to be specified}}
+  (void)_Alignof(thread_local int); // expected-error {{type name does not allow storage class to be specified}}
+  (void)(constexpr int)1;           // expected-error {{type name does not allow constexpr specifier to be specified}}
+}
+
+int a26 = (static)3; // expected-error {{expected expression}}
+
+typedef int A __attribute__((aligned(64)));
+A *test54(void) {
+  return &(thread_local static A){1}; // ps4-error {{alignment (64) of thread-local compound literal is greater than the maximum supported alignment (32) for thread-local storage on this target}}
+}
+
+int *test55(void) {
+  return (static int[]){1, 2};
+}
+
+int test56(int x) {                 // expected-note {{'test56' declared here}}
+  return (constexpr int){test56()}; // expected-error {{too few arguments to function call, single argument 'x' was not specified}}
+}
+
+constexpr int a27 = (constexpr int){1};
+constexpr int a28 = (int){1};                  // gnu-error {{reading a non-constexpr compound literal}}
+constexpr int a29 = (const int){1};            // gnu-error {{reading a non-constexpr compound literal}}
+constexpr int a30 = (static int){1};           // gnu-error {{reading a non-constexpr compound literal}}
+constexpr int a31 = (constexpr struct S5){1}.a;
+constexpr int a32 = (struct S5){1}.a;          // gnu-error {{reading a non-constexpr compound literal}}
+constexpr struct S5 a33 = (constexpr struct S5){1};
+constexpr struct S5 a34 = (struct S5){1};      // gnu-error {{reading a non-constexpr compound literal}}
+constexpr int a35 = (constexpr int){(int){1}}; // gnu-error {{reading a non-constexpr compound literal}}
+constexpr int a36 = (int){a2};                 // expected-error {{constexpr variable 'a36' must be initialized by a constant expression}}
+constexpr int a37 = sizeof((int){1});
+constexpr int a38 = 1 || (int){1};
+int *a39 = &(int){1};
+int a40 = (int){1};
+static_assert(a27 == 1 && a31 == 1 && a33.a == 1);
+
+enum E { E7 = 1 };
+constexpr enum E a41 = (enum E){E7};         // gnu-error {{reading a non-constexpr compound literal}}
+constexpr double a42 = (double){1.0};        // gnu-error {{reading a non-constexpr compound literal}}
+constexpr union U1 a43 = (union U1){.a = 1}; // gnu-error {{reading a non-constexpr compound literal}}
+constexpr enum E a44 = (constexpr enum E){E7};
+constexpr double a45 = (constexpr double){1.0};
+constexpr union U1 a46 = (constexpr union U1){.a = 1};
+constexpr int a47 = (union U1){.a = 1}.a;    // gnu-error {{reading a non-constexpr compound literal}}
+static_assert(a41 == E7 && (int)a42 == 1 && a43.a == 1);
+static_assert(a44 == E7 && (int)a45 == 1 && a46.a == 1 && a47 == 1);
+
+void test57(void) {
+  constexpr int a = (constexpr int){1};
+  constexpr int b = (int){1};             // gnu-error {{reading a non-constexpr compound literal}}
+  constexpr int c = (const int){1};       // gnu-error {{reading a non-constexpr compound literal}}
+  constexpr int d = (static int){1};      // gnu-error {{reading a non-constexpr compound literal}}
+  constexpr int e = (constexpr struct S5){1}.a;
+  constexpr int f = (struct S5){1}.a;     // gnu-error {{reading a non-constexpr compound literal}}
+  constexpr struct S5 g = (constexpr struct S5){1};
+  constexpr struct S5 h = (struct S5){1}; // gnu-error {{reading a non-constexpr compound literal}}
+  constexpr int j = sizeof((int){1});
+  constexpr int k = 1 || (int){1};
+  int *l = &(int){1};
+  int m = (int){1};
+  constexpr enum E n = (enum E){E7};         // gnu-error {{reading a non-constexpr compound literal}}
+  constexpr double o = (double){1.0};        // gnu-error {{reading a non-constexpr compound literal}}
+  constexpr union U1 p = (union U1){.a = 1}; // gnu-error {{reading a non-constexpr compound literal}}
+  constexpr int q = (union U1){.a = 1}.a;    // gnu-error {{reading a non-constexpr compound literal}}
+  static_assert(a == 1 && e == 1 && g.a == 1);
+  static_assert(n == E7 && (int)o == 1 && p.a == 1 && q == 1);
+  static_assert(((int[]){1})[0] == 1);       // gnu-error {{folding it to a constant is a GNU extension}}
+}
+
+void test58(int a) {
+  (void)(constexpr int){(int){a}};   // expected-error {{initializer of compound literal must be a constant expression}}
+  int b = 0;
+  (void)(constexpr int){(int){b++}}; // expected-error {{initializer of compound literal must be a constant expression}}
+}
diff --git a/clang/test/Sema/c23-compound-literal.m b/clang/test/Sema/c23-compound-literal.m
new file mode 100644
index 00000000000000..1ddc5d6f583eb1
--- /dev/null
+++ b/clang/test/Sema/c23-compound-literal.m
@@ -0,0 +1,12 @@
+// RUN: %clang_cc1 -std=c23 -fobjc-arc -verify %s
+
+typedef struct {
+  id a;
+} S;
+
+void test1(void) {
+  (void)(thread_local static __unsafe_unretained id){0};
+  (void)(thread_local static Class){0};
+  (void)(thread_local static id){0}; // expected-error {{thread-local variable has non-trivial ownership: type is '__strong id'}}
+  (void)(thread_local static S){0};  // expected-error {{type of thread-local variable has non-trivial destruction}}
+}
diff --git a/clang/test/Sema/constexpr-builtin-stdc-load8.c b/clang/test/Sema/constexpr-builtin-stdc-load8.c
index 4053735efa9e48..1f43e66dd359ac 100644
--- a/clang/test/Sema/constexpr-builtin-stdc-load8.c
+++ b/clang/test/Sema/constexpr-builtin-stdc-load8.c
@@ -262,9 +262,9 @@ _Static_assert(_Generic(stdc_load8_les32(le8_u), __INT_LEAST32_TYPE__ : 1, defau
 _Static_assert(_Generic(stdc_load8_les64(le8_u), __INT_LEAST64_TYPE__ : 1, default : 0) == 1, "wrong return type");
 
 void test_compound_literal(void) {
-  constexpr __UINT_LEAST16_TYPE__ ok = stdc_load8_leu16((const unsigned char[]){0x34, 0x12});
+  constexpr __UINT_LEAST16_TYPE__ ok = stdc_load8_leu16((constexpr unsigned char[]){0x34, 0x12});
   static_assert(ok == 0x1234, "");
-  constexpr __UINT_LEAST8_TYPE__ aligned_ok = stdc_load8_aligned_leu8((const unsigned char[]){0xAB});
+  constexpr __UINT_LEAST8_TYPE__ aligned_ok = stdc_load8_aligned_leu8((constexpr unsigned char[]){0xAB});
   static_assert(aligned_ok == 0xAB, "");
-  constexpr __UINT_LEAST16_TYPE__ aligned_fail = stdc_load8_aligned_leu16((const unsigned char[]){0x34, 0x12}); // expected-error{{must be initialized by a constant expression}} expected-note{{requires a pointer aligned to 2 bytes, but the given pointer is only aligned to 1 byte}}
+  constexpr __UINT_LEAST16_TYPE__ aligned_fail = stdc_load8_aligned_leu16((constexpr unsigned char[]){0x34, 0x12}); // expected-error{{must be initialized by a constant expression}} expected-note{{requires a pointer aligned to 2 bytes, but the given pointer is only aligned to 1 byte}}
 }
diff --git a/clang/test/Sema/constexpr-member-access.c b/clang/test/Sema/constexpr-member-access.c
index a2cf3cb56f5d53..f14d05e4eeda00 100644
--- a/clang/test/Sema/constexpr-member-access.c
+++ b/clang/test/Sema/constexpr-member-access.c
@@ -28,7 +28,7 @@ struct S2 {
 constexpr struct S2 V1 = {0, 1, 1, 'c', E_B, {3}, 1.0, -1};
 constexpr union U V2 = {5};
 constexpr int V3 = V1.f.a;
-constexpr int V4 = ((struct S2){0, 4, 0, 0, E_A, {6}, 0.0, 0}).f.a;
+constexpr int V4 = ((constexpr struct S2){0, 4, 0, 0, E_A, {6}, 0.0, 0}).f.a;
 
 void gh178349() {
   int a[V1.b] = {};
diff --git a/clang/test/Sema/constexpr.c b/clang/test/Sema/constexpr.c
index 3bb8cffe16ab21..9c5e70e98b3bc4 100644
--- a/clang/test/Sema/constexpr.c
+++ b/clang/test/Sema/constexpr.c
@@ -36,7 +36,7 @@ constexpr static const auto V6 = 1;
 constexpr static const int V7 = 1;
 constexpr static int V8 = 1;
 constexpr auto Ulong = 1L;
-constexpr auto CompoundLiteral = (int){13};
+constexpr auto CompoundLiteral = (constexpr int){13};
 constexpr auto DoubleCast = (double)(1 / 3);
 constexpr auto String = "this is a string"; // expected-error {{constexpr pointer initializer is not null}}
 constexpr signed auto Long = 1L; // expected-error {{illegal storage class on file-scoped variable}}
@@ -473,3 +473,75 @@ static_assert(s2[0].L[2] == 'x');// expected-warning {{folding it to a constant
 
 x y; // expected-error{{unknown type name 'x'}}
 constexpr int *p = (int*){y};
+
+struct S12 { int n; };
+union U4 { int n; double f; };
+const int C1 = 1;
+
+constexpr int C2 = (int){1};                // expected-warning {{reading a non-constexpr compound literal}}
+constexpr struct S12 C3 = (struct S12){1};  // expected-warning {{reading a non-constexpr compound literal}}
+constexpr union U4 C4 = (union U4){.n = 1}; // expected-warning {{reading a non-constexpr compound literal}}
+constexpr int C5 = (int){C1};               // expected-error {{constexpr variable 'C5' must be initialized by a constant expression}}
+static_assert(C2 == 1 && C3.n == 1 && C4.n == 1);
+
+constexpr struct S12 C6 = (struct S12){C1};    // expected-error {{constexpr variable 'C6' must be initialized by a constant expression}}
+constexpr union U4 C7 = (union U4){.n = C1};   // expected-error {{constexpr variable 'C7' must be initialized by a constant expression}}
+constexpr int C8 = (int){(int){C1}};           // expected-error {{constexpr variable 'C8' must be initialized by a constant expression}}
+constexpr int C9 = 1;
+constexpr int C10 = (int){C9};                 // expected-warning {{reading a non-constexpr compound literal}}
+constexpr int C11 = (constexpr int){C9};
+constexpr int C12 = (constexpr int){(int){C1}}; // expected-error {{initializer of compound literal must be a constant expression}}
+static_assert(C10 == 1 && C11 == 1);
+
+void compound_literals(int value) {
+  constexpr int a = (int){1};                // expected-warning {{reading a non-constexpr compound literal}}
+  constexpr struct S12 b = (struct S12){1};  // expected-warning {{reading a non-constexpr compound literal}}
+  constexpr union U4 c = (union U4){.n = 1}; // expected-warning {{reading a non-constexpr compound literal}}
+  constexpr int d = (int){C1};               // expected-error {{constexpr variable 'd' must be initialized by a constant expression}}
+  (void)(constexpr int){(int){1}};           // expected-warning {{reading a non-constexpr compound literal}}
+  (void)(constexpr int){(static int){1}};    // expected-warning {{reading a non-constexpr compound literal}}
+  static_assert(a == 1 && b.n == 1 && c.n == 1);
+
+  const int e = 1;
+  constexpr int f = (int){e};                // expected-error {{constexpr variable 'f' must be initialized by a constant expression}}
+  constexpr struct S12 g = (struct S12){e};  // expected-error {{constexpr variable 'g' must be initialized by a constant expression}}
+  constexpr union U4 h = (union U4){.n = e}; // expected-error {{constexpr variable 'h' must be initialized by a constant expression}}
+  constexpr int i = (int){(int){e}};         // expected-error {{constexpr variable 'i' must be initialized by a constant expression}}
+
+  constexpr int j = (int){1} + e;                           // expected-error {{constexpr variable 'j' must be initialized by a constant expression}}
+  constexpr int k = __builtin_constant_p((int){e}) + e;     // expected-error {{constexpr variable 'k' must be initialized by a constant expression}}
+  constexpr int l = __builtin_constant_p((int){value}) + e; // expected-error {{constexpr variable 'l' must be initialized by a constant expression}}
+  constexpr int m = (int){(int){value}};                    // expected-error {{constexpr variable 'm' must be initialized by a constant expression}}
+}
+
+void complex_initializers(int value) {
+  constexpr _Complex float a = 16777217;                    // expected-error {{not exactly representable}}
+  constexpr _Complex float b = 0.1;                         // expected-error {{not exactly representable}}
+  constexpr _Complex float c = __builtin_complex(0.1, 0.5); // expected-error {{not exactly representable}}
+  constexpr _Complex float d = __builtin_complex(0.5, 0.1); // expected-error {{not exactly representable}}
+  constexpr _Complex float e = __builtin_complex(0.5, 0.25);
+  constexpr _Complex float f = (float)0.1;
+  constexpr _Complex float g = (_Complex float)__builtin_complex(0.1, 0.2);
+  constexpr _Complex double h = e;
+  constexpr _Complex float i = h;
+  constexpr _Complex float j = INF;
+  constexpr _Complex float k = DBL_NAN;
+  constexpr _Complex float l = FLT_SNAN;
+  constexpr _Complex double m = FLT_SNAN;                   // expected-error {{not exactly representable}}
+  constexpr _Complex double n = __builtin_complex(FLT_SNAN, 0.0f);
+
+  (void)(constexpr _Complex float){16777217};               // expected-error {{not exactly representable}}
+  (void)(constexpr _Complex float){__builtin_complex(0.5, 0.25)};
+
+  struct S { _Complex float a; };
+  constexpr struct S o = {0.1};                             // expected-error {{not exactly representable}}
+  constexpr _Complex float p = 0.5 ? 16777217 : 0;          // expected-error {{not exactly representable}}
+  constexpr _Complex float q = 0.5 ? 1 : 0;
+  constexpr float r = 0.5 ? 16777217 : 0;                   // expected-error {{not exactly representable}}
+  constexpr float s = 0.5 ? 1 : 0;
+  constexpr _Complex float t = (long)&complex_initializers; // expected-error {{must be initialized by a constant expression}} \
+                                                            // expected-note {{this conversion is not allowed in a constant expression}}
+
+  constexpr _Complex float u = __builtin_constant_p(value) ? 0 : 16777217; // expected-error {{not exactly representable}}
+  constexpr _Complex float v = __builtin_constant_p(value) ? 0 : 1;
+}
diff --git a/clang/unittests/AST/StructuralEquivalenceTest.cpp b/clang/unittests/AST/StructuralEquivalenceTest.cpp
index a368474f2841a4..d7950d330b4543 100644
--- a/clang/unittests/AST/StructuralEquivalenceTest.cpp
+++ b/clang/unittests/AST/StructuralEquivalenceTest.cpp
@@ -2219,6 +2219,25 @@ TEST_F(StructuralEquivalenceStmtTest, CharacterLiteralDifferentValues) {
   EXPECT_FALSE(testStructuralMatch(t));
 }
 
+TEST_F(StructuralEquivalenceStmtTest, CompoundLiteralExpr) {
+  EXPECT_TRUE(testStructuralMatch(makeWrappedStmts(
+      "(static thread_local int){1}", "(thread_local static int){1}", Lang_C23,
+      compoundLiteralExpr())));
+  EXPECT_FALSE(testStructuralMatch(
+      makeStmts("const int *p = &(constexpr int){1};",
+                "void f(void) { (void)&(constexpr int){1}; }", Lang_C23,
+                compoundLiteralExpr())));
+  EXPECT_FALSE(testStructuralMatch(makeWrappedStmts(
+      "(static constexpr int){1}", "(register constexpr int){1}", Lang_C23,
+      compoundLiteralExpr())));
+  EXPECT_FALSE(testStructuralMatch(
+      makeWrappedStmts("(static int){1}", "(static thread_local int){1}",
+                       Lang_C23, compoundLiteralExpr())));
+  EXPECT_FALSE(testStructuralMatch(
+      makeWrappedStmts("(static const int){1}", "(static constexpr int){1}",
+                       Lang_C23, compoundLiteralExpr())));
+}
+
 TEST_F(StructuralEquivalenceStmtTest, ExpressionTraitExpr) {
   auto t = makeWrappedStmts("__is_lvalue_expr(1)", "__is_lvalue_expr(1)",
                             Lang_CXX03, fallbackExprMatcher());

>From 15af90d52b51fa45209c0ed80b0051c6dcf11918 Mon Sep 17 00:00:00 2001
From: Oleksandr Tarasiuk <oleksandr.tarasiuk at outlook.com>
Date: Fri, 30 Oct 2026 13:12:20 +0200
Subject: [PATCH 2/7] remove redundant compound literal check

---
 clang/lib/AST/ByteCode/Compiler.cpp | 5 -----
 1 file changed, 5 deletions(-)

diff --git a/clang/lib/AST/ByteCode/Compiler.cpp b/clang/lib/AST/ByteCode/Compiler.cpp
index 4728b602d9fbe2..62a599e3f4a1af 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -3725,11 +3725,6 @@ bool Compiler<Emitter>::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
     if (!this->emitGetPtrGlobal(*GlobalIndex, E))
       return false;
 
-    // An ordinary C23 literal may have been folded for static initialization.
-    if (P.isGlobalInitialized(*GlobalIndex) &&
-        (!Ctx.getLangOpts().C23 || E->isConstexpr()))
-      return true;
-
     if (T) {
       if (!this->visit(Init))
         return false;

>From 9a89860c2cb67512fa880486f413dc15798af70a Mon Sep 17 00:00:00 2001
From: Oleksandr Tarasiuk <oleksandr.tarasiuk at outlook.com>
Date: Sat, 31 Oct 2026 15:00:51 +0200
Subject: [PATCH 3/7] reduce overhead of C23 constexpr object checks

---
 clang/lib/AST/ByteCode/EvalEmitter.cpp |  3 +++
 clang/lib/AST/ByteCode/Interp.cpp      | 23 ++++++++++++-----------
 clang/lib/AST/ByteCode/InterpHelpers.h |  8 ++++++++
 clang/test/Sema/c23-compound-literal.c |  3 +++
 4 files changed, 26 insertions(+), 11 deletions(-)

diff --git a/clang/lib/AST/ByteCode/EvalEmitter.cpp b/clang/lib/AST/ByteCode/EvalEmitter.cpp
index a1fce467dcd203..e3fed6c9d1e4e9 100644
--- a/clang/lib/AST/ByteCode/EvalEmitter.cpp
+++ b/clang/lib/AST/ByteCode/EvalEmitter.cpp
@@ -366,6 +366,9 @@ bool EvalEmitter::emitGetLocal(uint32_t I, SourceInfo Info) {
 
   Block *B = getLocal(I);
 
+  if (!CheckC23ConstexprObject(S, CodePtr(), B->getDescriptor()))
+    return false;
+
   if (!CheckLocalLoad(S, CodePtr(), B))
     return false;
 
diff --git a/clang/lib/AST/ByteCode/Interp.cpp b/clang/lib/AST/ByteCode/Interp.cpp
index 8fc3f41d0d64df..73a9e77bbf4c34 100644
--- a/clang/lib/AST/ByteCode/Interp.cpp
+++ b/clang/lib/AST/ByteCode/Interp.cpp
@@ -521,9 +521,9 @@ bool CheckLive(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
   return true;
 }
 
-static bool CheckConstexprObject(InterpState &S, CodePtr OpPC,
-                                 const Descriptor *Desc) {
-  if (!S.getLangOpts().C23 || S.EvalMode != EvaluationMode::ConstantExpression)
+bool CheckConstexprObject(InterpState &S, CodePtr OpPC,
+                          const Descriptor *Desc) {
+  if (S.EvalMode != EvaluationMode::ConstantExpression)
     return true;
 
   if (const auto *VD = Desc->asVarDecl()) {
@@ -542,18 +542,21 @@ bool CheckConstant(InterpState &S, CodePtr OpPC, const Descriptor *Desc,
                    AccessKinds AK) {
   assert(Desc);
 
-  if (!CheckConstexprObject(S, OpPC, Desc))
-    return false;
-
   const auto *D = Desc->asVarDecl();
+  if (!D)
+    return CheckC23ConstexprObject(S, OpPC, Desc);
+
   if (S.checkingConstantDestruction(D)) {
     // If we're checking for a constant destructor for this variable, we can
     // only read from it if it is constant.
     if (D->getType().isConstQualified())
       return true;
-  } else if (!D || D == S.EvaluatingDecl || D->isConstexpr())
+  } else if (D == S.EvaluatingDecl || D->isConstexpr())
     return true;
 
+  if (!CheckC23ConstexprObject(S, OpPC, Desc))
+    return false;
+
   QualType T = D->getType();
   bool IsConstant = T.isConstant(S.getASTContext());
   if (T->isIntegralOrEnumerationType()) {
@@ -610,7 +613,7 @@ static bool CheckConstant(InterpState &S, CodePtr OpPC, PtrView Ptr,
     return CheckConstant(S, OpPC, Ptr.getDeclDesc(), AK);
 
   if (!Ptr.block()->isStatic() || !Ptr.block()->getDeclID())
-    return CheckConstexprObject(S, OpPC, Ptr.getDeclDesc());
+    return CheckC23ConstexprObject(S, OpPC, Ptr.getDeclDesc());
   return CheckConstant(S, OpPC, Ptr.getDeclDesc(), AK);
 }
 
@@ -913,8 +916,6 @@ bool CheckLocalLoad(InterpState &S, CodePtr OpPC, const Block *B) {
   assert(!B->isExtern());
   const auto &Desc = *reinterpret_cast<const InlineDescriptor *>(B->rawData());
   const Descriptor *BlockDesc = B->getDescriptor();
-  if (!CheckConstexprObject(S, OpPC, BlockDesc))
-    return false;
   if (!Desc.IsInitialized)
     return diagnoseUninitialized(S, OpPC, /*Extern=*/false, B, Desc.LifeState);
   if (!CheckLifetime(S, OpPC, Desc.LifeState, B, AK_Read))
@@ -3752,7 +3753,7 @@ bool Memcpy(InterpState &S, CodePtr OpPC) {
       Src.inUnion()) {
     if (!CheckLoad(S, OpPC, Src))
       return false;
-  } else if (!CheckConstexprObject(S, OpPC, Src.getDeclDesc()))
+  } else if (!CheckC23ConstexprObject(S, OpPC, Src.getDeclDesc()))
     return false;
 
   return DoMemcpy(S, OpPC, Src, Dest);
diff --git a/clang/lib/AST/ByteCode/InterpHelpers.h b/clang/lib/AST/ByteCode/InterpHelpers.h
index 8a99406eb1b67a..3e5d5c0202a654 100644
--- a/clang/lib/AST/ByteCode/InterpHelpers.h
+++ b/clang/lib/AST/ByteCode/InterpHelpers.h
@@ -85,6 +85,14 @@ inline bool CheckMutable(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
   return CheckMutable(S, OpPC, Ptr.view(), AK);
 }
 
+bool CheckConstexprObject(InterpState &S, CodePtr OpPC, const Descriptor *Desc);
+
+/// Checks whether an object can be read in a C23 constant expression.
+inline bool CheckC23ConstexprObject(InterpState &S, CodePtr OpPC,
+                                    const Descriptor *Desc) {
+  return !S.getLangOpts().C23 || CheckConstexprObject(S, OpPC, Desc);
+}
+
 /// Checks if a value can be loaded from a block.
 bool CheckLoad(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
                AccessKinds AK = AK_Read);
diff --git a/clang/test/Sema/c23-compound-literal.c b/clang/test/Sema/c23-compound-literal.c
index e3d209900f5ad5..400dda49fd3a00 100644
--- a/clang/test/Sema/c23-compound-literal.c
+++ b/clang/test/Sema/c23-compound-literal.c
@@ -89,6 +89,9 @@ void test9(void) {
   (void)(constexpr struct S1){.a = (constexpr int){1}};
   (void)(constexpr int){(int){1}};        // gnu-error {{reading a non-constexpr compound literal}}
   (void)(constexpr int){(static int){1}}; // gnu-error {{reading a non-constexpr compound literal}}
+
+  (void)(constexpr int){({ const int a = 1; a; })}; // expected-error {{initializer of compound literal must be a constant expression}}
+  (void)(constexpr int){({ constexpr int a = 1; a; })};
 }
 
 void test10(void) {

>From 60d1b91f8f9e8567f82066e409772661fb19c7a9 Mon Sep 17 00:00:00 2001
From: Oleksandr Tarasiuk <oleksandr.tarasiuk at outlook.com>
Date: Sun, 1 Nov 2026 10:33:45 +0200
Subject: [PATCH 4/7] reuse printing policy and split compound literal
 lookahead

---
 clang/include/clang/Parse/Parser.h |  4 +++-
 clang/lib/Parse/ParseDecl.cpp      |  7 ++++---
 clang/lib/Parse/ParseExpr.cpp      | 11 ++++++++---
 3 files changed, 15 insertions(+), 7 deletions(-)

diff --git a/clang/include/clang/Parse/Parser.h b/clang/include/clang/Parse/Parser.h
index c80594248579e6..94a4ccad3175e5 100644
--- a/clang/include/clang/Parse/Parser.h
+++ b/clang/include/clang/Parse/Parser.h
@@ -1901,7 +1901,8 @@ class Parser : public CodeCompletionHandler {
 
   enum class StorageClassSpecifierContext { Declaration, CompoundLiteral };
   void ParseStorageClassSpecifier(DeclSpec &DS,
-                                  StorageClassSpecifierContext Context);
+                                  StorageClassSpecifierContext Context,
+                                  const PrintingPolicy &Policy);
 
   void
   ParseDeclarationSpecifiers(DeclSpec &DS, ParsedTemplateInfo &TemplateInfo,
@@ -5134,6 +5135,7 @@ class Parser : public CodeCompletionHandler {
 
   bool isCompoundLiteralStorageClassSpecifier() const;
   bool isTypeIdInParensWithStorageClassSpecifiers();
+  bool isTypeIdInParensAfterStorageClassSpecifiers();
   void ParseCompoundLiteralStorageClassSpecifiers(DeclSpec &DS);
 
   /// Finish parsing a C++ unqualified-id that is a template-id of
diff --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp
index baa5888036fbbf..2e541712a45afd 100644
--- a/clang/lib/Parse/ParseDecl.cpp
+++ b/clang/lib/Parse/ParseDecl.cpp
@@ -3395,12 +3395,12 @@ Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
 }
 
 void Parser::ParseStorageClassSpecifier(DeclSpec &DS,
-                                        StorageClassSpecifierContext Context) {
+                                        StorageClassSpecifierContext Context,
+                                        const PrintingPolicy &Policy) {
   SourceLocation Loc = Tok.getLocation();
   const char *PrevSpec = nullptr;
   unsigned DiagID = 0;
   bool IsInvalid = false;
-  PrintingPolicy Policy = Actions.getPrintingPolicy();
 
   switch (Tok.getKind()) {
   case tok::kw_typedef:
@@ -4268,7 +4268,8 @@ void Parser::ParseDeclarationSpecifiers(
     case tok::kw_thread_local:
     case tok::kw__Thread_local:
     case tok::kw_constexpr:
-      ParseStorageClassSpecifier(DS, StorageClassSpecifierContext::Declaration);
+      ParseStorageClassSpecifier(DS, StorageClassSpecifierContext::Declaration,
+                                 Policy);
       AttrsLastTime = false;
       continue;
 
diff --git a/clang/lib/Parse/ParseExpr.cpp b/clang/lib/Parse/ParseExpr.cpp
index d5803bb49af976..99d0a716b928db 100644
--- a/clang/lib/Parse/ParseExpr.cpp
+++ b/clang/lib/Parse/ParseExpr.cpp
@@ -2672,9 +2672,13 @@ bool Parser::isCompoundLiteralStorageClassSpecifier() const {
 }
 
 bool Parser::isTypeIdInParensWithStorageClassSpecifiers() {
-  if (!isCompoundLiteralStorageClassSpecifier())
-    return false;
+  return isCompoundLiteralStorageClassSpecifier() &&
+         isTypeIdInParensAfterStorageClassSpecifiers();
+}
 
+bool Parser::isTypeIdInParensAfterStorageClassSpecifiers() {
+  assert(isCompoundLiteralStorageClassSpecifier() &&
+         "expected a compound literal storage-class specifier");
   RevertingTentativeParsingAction TPA(*this);
   do
     ConsumeToken();
@@ -2687,7 +2691,8 @@ void Parser::ParseCompoundLiteralStorageClassSpecifiers(DeclSpec &DS) {
     if (DS.getBeginLoc().isInvalid())
       DS.SetRangeStart(Tok.getLocation());
     ParseStorageClassSpecifier(DS,
-                               StorageClassSpecifierContext::CompoundLiteral);
+                               StorageClassSpecifierContext::CompoundLiteral,
+                               Actions.getPrintingPolicy());
   }
 }
 

>From 10674e756c84cbc2d6c9fb9f617a1d070f882b9a Mon Sep 17 00:00:00 2001
From: Oleksandr Tarasiuk <oleksandr.tarasiuk at outlook.com>
Date: Sun, 1 Nov 2026 21:23:44 +0200
Subject: [PATCH 5/7] defer compound literal DeclSpec construction

---
 clang/include/clang/Parse/Parser.h |  7 +++---
 clang/include/clang/Sema/Sema.h    |  7 +++---
 clang/lib/Parse/ParseExpr.cpp      | 37 ++++++++++++++++--------------
 clang/lib/Sema/SemaExpr.cpp        |  2 +-
 clang/lib/Sema/SemaInit.cpp        |  6 ++---
 5 files changed, 31 insertions(+), 28 deletions(-)

diff --git a/clang/include/clang/Parse/Parser.h b/clang/include/clang/Parse/Parser.h
index 94a4ccad3175e5..16d374797538c5 100644
--- a/clang/include/clang/Parse/Parser.h
+++ b/clang/include/clang/Parse/Parser.h
@@ -4320,10 +4320,9 @@ class Parser : public CodeCompletionHandler {
   ///         '(' type-name ')' '{' initializer-list '}'
   ///         '(' type-name ')' '{' initializer-list ',' '}'
   /// \endverbatim
-  ExprResult ParseCompoundLiteralExpression(ParsedType Ty,
-                                            SourceLocation LParenLoc,
-                                            SourceLocation RParenLoc,
-                                            const DeclSpec *DS = nullptr);
+  ExprResult ParseCompoundLiteralExpression(
+      ParsedType Ty, SourceLocation LParenLoc, SourceLocation RParenLoc,
+      const std::optional<DeclSpec> &DS = std::nullopt);
 
   /// ParseGenericSelectionExpression - Parse a C11 generic-selection
   /// [C11 6.5.1.1].
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 141b36a710ce92..aae6aaa6715c5a 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -7663,9 +7663,10 @@ class Sema final : public SemaBase {
       ConstexprSpecKind ConstexprKind, SourceLocation ConstexprLoc);
 
 public:
-  ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
-                                  SourceLocation RParenLoc, Expr *InitExpr,
-                                  const DeclSpec *DS = nullptr);
+  ExprResult
+  ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
+                       SourceLocation RParenLoc, Expr *InitExpr,
+                       const std::optional<DeclSpec> &DS = std::nullopt);
 
   ExprResult BuildCompoundLiteralExpr(
       SourceLocation LParenLoc, TypeSourceInfo *TInfo, SourceLocation RParenLoc,
diff --git a/clang/lib/Parse/ParseExpr.cpp b/clang/lib/Parse/ParseExpr.cpp
index 99d0a716b928db..c6467ec0a69b53 100644
--- a/clang/lib/Parse/ParseExpr.cpp
+++ b/clang/lib/Parse/ParseExpr.cpp
@@ -2834,9 +2834,12 @@ Parser::ParseParenExpression(ParenParseOption &ExprType, bool StopIfCastExpr,
       return res;
     }
 
-    DeclSpec CompoundDS(AttrFactory);
-    ParseCompoundLiteralStorageClassSpecifiers(CompoundDS);
-    CompoundDS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
+    std::optional<DeclSpec> CompoundDS;
+    if (isCompoundLiteralStorageClassSpecifier()) {
+      DeclSpec &DS = CompoundDS.emplace(AttrFactory);
+      ParseCompoundLiteralStorageClassSpecifiers(DS);
+      DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
+    }
 
     DeclSpec DS(AttrFactory);
     ParseSpecifierQualifierList(DS);
@@ -2866,8 +2869,8 @@ Parser::ParseParenExpression(ParenParseOption &ExprType, bool StopIfCastExpr,
       if (ParenBehavior == ParenExprKind::Unknown && Tok.is(tok::l_brace)) {
         ExprType = ParenParseOption::CompoundLiteral;
 
-        if (CompoundDS.getBeginLoc().isValid())
-          Diag(CompoundDS.getBeginLoc(),
+        if (CompoundDS)
+          Diag(CompoundDS->getBeginLoc(),
                diag::warn_c23_compat_compound_literal_storage_class);
 
         TypeResult Ty;
@@ -2876,21 +2879,21 @@ Parser::ParseParenExpression(ParenParseOption &ExprType, bool StopIfCastExpr,
           Ty = Actions.ActOnTypeName(DeclaratorInfo);
         }
         return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc,
-                                              &CompoundDS);
+                                              CompoundDS);
       }
 
-      if (!DeclaratorInfo.isInvalidType()) {
-        if (CompoundDS.getParsedSpecifiers() &
+      if (CompoundDS && !DeclaratorInfo.isInvalidType()) {
+        if (CompoundDS->getParsedSpecifiers() &
             DeclSpec::PQ_StorageClassSpecifier) {
-          SourceLocation Loc = CompoundDS.getStorageClassSpecLoc();
+          SourceLocation Loc = CompoundDS->getStorageClassSpecLoc();
           if (Loc.isInvalid())
-            Loc = CompoundDS.getThreadStorageClassSpecLoc();
+            Loc = CompoundDS->getThreadStorageClassSpecLoc();
           Diag(Loc, diag::err_typename_invalid_storageclass);
         }
-        if (CompoundDS.hasConstexprSpecifier())
-          Diag(CompoundDS.getConstexprSpecLoc(),
+        if (CompoundDS->hasConstexprSpecifier())
+          Diag(CompoundDS->getConstexprSpecLoc(),
                diag::err_typename_invalid_constexpr)
-              << static_cast<int>(CompoundDS.getConstexprSpecifier());
+              << static_cast<int>(CompoundDS->getConstexprSpecifier());
       }
 
       if (ParenBehavior == ParenExprKind::Unknown && Tok.is(tok::l_paren)) {
@@ -3064,10 +3067,10 @@ Parser::ParseParenExpression(ParenParseOption &ExprType, bool StopIfCastExpr,
   return Result;
 }
 
-ExprResult Parser::ParseCompoundLiteralExpression(ParsedType Ty,
-                                                  SourceLocation LParenLoc,
-                                                  SourceLocation RParenLoc,
-                                                  const DeclSpec *DS) {
+ExprResult
+Parser::ParseCompoundLiteralExpression(ParsedType Ty, SourceLocation LParenLoc,
+                                       SourceLocation RParenLoc,
+                                       const std::optional<DeclSpec> &DS) {
   assert(Tok.is(tok::l_brace) && "Not a compound literal!");
   if (!getLangOpts().C99)   // Compound literals don't exist in C90.
     Diag(LParenLoc, diag::ext_c99_compound_literal);
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 683e07480a0b53..ff65899fe47dab 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -7654,7 +7654,7 @@ ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
 
 ExprResult Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
                                       SourceLocation RParenLoc, Expr *InitExpr,
-                                      const DeclSpec *DS) {
+                                      const std::optional<DeclSpec> &DS) {
   assert(Ty && "ActOnCompoundLiteral(): missing type");
   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
 
diff --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index 1db750875db0b5..3ee015b19b4a76 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -1426,8 +1426,7 @@ void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
     // parts.
     CheckComplexType(Entity, IList, DeclType, Index,
                      StructuredList, StructuredIndex);
-  } else if (DeclType->isScalarType() ||
-             (!SemaRef.getLangOpts().CPlusPlus && DeclType->isAtomicType())) {
+  } else if (DeclType->isScalarType()) {
     CheckScalarType(Entity, IList, DeclType, Index,
                     StructuredList, StructuredIndex);
   } else if (DeclType->isVectorType()) {
@@ -1473,7 +1472,8 @@ void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
       SemaRef.Diag(IList->getBeginLoc(), diag::err_init_objc_class) << DeclType;
     hadError = true;
   } else if (DeclType->isOCLIntelSubgroupAVCType() ||
-             DeclType->isSizelessBuiltinType()) {
+             DeclType->isSizelessBuiltinType() ||
+             (DeclType->isAtomicType() && !SemaRef.getLangOpts().CPlusPlus)) {
     // Checks for scalar type are sufficient for these types too.
     CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
                     StructuredIndex);

>From ad8d15342c25420f665dc5c42a5ca716d518ee0a Mon Sep 17 00:00:00 2001
From: Oleksandr Tarasiuk <oleksandr.tarasiuk at outlook.com>
Date: Sat, 7 Nov 2026 21:34:32 +0200
Subject: [PATCH 6/7] add comments to boolean args

---
 clang/lib/AST/Expr.cpp               | 3 ++-
 clang/lib/CodeGen/CGExprConstant.cpp | 3 ++-
 2 files changed, 4 insertions(+), 2 deletions(-)

diff --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index 3866909111baf1..e339a409a56da5 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -3451,7 +3451,8 @@ bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef,
         *Culprit = this;
       return false;
     }
-    return CLE->getInitializer()->isConstantInitializer(Ctx, false, Culprit);
+    return CLE->getInitializer()->isConstantInitializer(Ctx, /*ForRef=*/false,
+                                                        Culprit);
   }
   case DesignatedInitUpdateExprClass: {
     const DesignatedInitUpdateExpr *DIUE = cast<DesignatedInitUpdateExpr>(this);
diff --git a/clang/lib/CodeGen/CGExprConstant.cpp b/clang/lib/CodeGen/CGExprConstant.cpp
index 3230c346d5d21e..f271bead450455 100644
--- a/clang/lib/CodeGen/CGExprConstant.cpp
+++ b/clang/lib/CodeGen/CGExprConstant.cpp
@@ -1099,7 +1099,8 @@ tryEmitGlobalCompoundLiteral(ConstantEmitter &emitter,
 
   auto GV = new llvm::GlobalVariable(
       CGM.getModule(), C->getType(),
-      E->getType().isConstantStorage(CGM.getContext(), true, false),
+      E->getType().isConstantStorage(CGM.getContext(), /*ExcludeCtor=*/true,
+                                     /*ExcludeDtor=*/false),
       llvm::GlobalValue::InternalLinkage, C, ".compoundliteral", nullptr,
       E->hasThreadStorage() ? CGM.GetDefaultLLVMTLSModel()
                             : llvm::GlobalVariable::NotThreadLocal,

>From 3ed19b47c54e2d074a363b8db9f092937abb9ac4 Mon Sep 17 00:00:00 2001
From: Oleksandr Tarasiuk <oleksandr.tarasiuk at outlook.com>
Date: Sat, 7 Nov 2026 21:42:21 +0200
Subject: [PATCH 7/7] tidy casts and checks

---
 clang/lib/Parse/ParseDecl.cpp | 2 +-
 clang/lib/Sema/SemaExpr.cpp   | 5 +++--
 2 files changed, 4 insertions(+), 3 deletions(-)

diff --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp
index 182447f581672b..4041a80364b2dc 100644
--- a/clang/lib/Parse/ParseDecl.cpp
+++ b/clang/lib/Parse/ParseDecl.cpp
@@ -3435,7 +3435,7 @@ void Parser::ParseStorageClassSpecifier(DeclSpec &DS,
   case tok::kw_auto:
     if (getLangOpts().CPlusPlus11 || getLangOpts().C23) {
       auto IsTypedefName = [&](const Token &T) {
-        if (!T.is(tok::identifier))
+        if (T.isNot(tok::identifier))
           return false;
         IdentifierInfo *II = T.getIdentifierInfo();
         if (!II)
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 5307d1fe2cbb45..6b7727707743b8 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -155,8 +155,9 @@ static bool checkThreadLocalCompoundLiteral(Sema &S, SourceLocation Loc,
     return false;
 
   S.Diag(Loc, diag::err_tls_aligned_over_maximum)
-      << (unsigned)TypeAlign.getQuantity() << /*IsCompoundLiteral=*/true
-      << (unsigned)MaxAlignChars.getQuantity();
+      << static_cast<unsigned>(TypeAlign.getQuantity())
+      << /*IsCompoundLiteral=*/true
+      << static_cast<unsigned>(MaxAlignChars.getQuantity());
   return true;
 }
 



More information about the cfe-commits mailing list