[clang] [clang] Make -fpack-struct pack every struct, as GCC does (PR #247469)

Brad Smith via cfe-commits cfe-commits at lists.llvm.org
Mon Nov 30 23:46:09 PST 2026


https://github.com/brad0 updated https://github.com/llvm/llvm-project/pull/247469

>From abb1605f4ee798f4e3e131b0f615d67385abc58b Mon Sep 17 00:00:00 2001
From: Brad Smith <brad at comstyle.com>
Date: Mon, 30 Nov 2026 01:02:54 -0500
Subject: [PATCH] [clang] Make -fpack-struct pack every struct, as GCC does

GCC's -fpack-struct without a value packs every struct, union and
class, as if declared with __attribute__((packed)), and makes #pragma
pack have no effect. -fpack-struct=N only limits the alignment of each
field, like #pragma pack(N). Clang's driver turned -fpack-struct into
-fpack-struct=1, so the two did not match. A field with an aligned
attribute kept its alignment with GCC but not with Clang, and on SPARC64
GCC passed the floating-point fields of every struct in integer
registers but Clang did not.

Pass -fpack-struct to cc1 and add an implicit packed attribute to every
record definition and closure type, as GCC does. Ignore #pragma pack
with a warning, as GCC does.

Co-Authored-By: Claude Opus 5.5 <noreply at anthropic.com>
---
 clang/docs/ReleaseNotes.md                    |  5 +++
 .../clang/Basic/DiagnosticSemaKinds.td        |  3 ++
 clang/include/clang/Basic/LangOptions.def     |  2 +
 clang/include/clang/Options/Options.td        |  5 ++-
 clang/lib/Driver/ToolChains/Clang.cpp         |  9 ++--
 clang/lib/Sema/SemaAttr.cpp                   | 10 +++++
 clang/lib/Sema/SemaLambda.cpp                 |  3 ++
 .../CodeGen/Sparc/sparcv9-packed-union-abi.c  |  8 ++--
 clang/test/Driver/fpack-struct.c              | 24 ++++++++---
 clang/test/Sema/fpack-struct.c                | 41 ++++++++++++++++++-
 clang/test/SemaCXX/fpack-struct.cpp           | 41 +++++++++++++++++++
 11 files changed, 134 insertions(+), 17 deletions(-)
 create mode 100644 clang/test/SemaCXX/fpack-struct.cpp

diff --git a/clang/docs/ReleaseNotes.md b/clang/docs/ReleaseNotes.md
index c221b0d7f0fa08..4e29673eb1f6be 100644
--- a/clang/docs/ReleaseNotes.md
+++ b/clang/docs/ReleaseNotes.md
@@ -499,6 +499,11 @@ documentation](CIR/index.md) for more information regarding ClangIR's status and
 - `-fdevirtualize-speculatively` can now also be used to enable speculative
   devirtualization when using LTO.
 
+- `-fpack-struct` without a value now packs every struct, union and class,
+  as if declared with `__attribute__((packed))`, and `#pragma pack` has no
+  effect, matching GCC. It was previously the same as `-fpack-struct=1`, which
+  only limits the alignment of each field.
+
 ### Removed Compiler Flags
 
 ### Attribute Changes in Clang
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index d2c1128d92c253..1ab0fc0bd92e9c 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -1225,6 +1225,9 @@ def warn_pragma_pack_invalid_alignment : Warning<
   InGroup<IgnoredPragmas>;
 def err_pragma_pack_invalid_alignment : Error<
   warn_pragma_pack_invalid_alignment.Summary>;
+def warn_pragma_pack_fpack_struct : Warning<
+  "#pragma pack has no effect with -fpack-struct; ignored">,
+  InGroup<IgnoredPragmas>;
 def warn_pragma_pack_non_default_at_include : Warning<
   "non-default #pragma pack value changes the alignment of struct or union "
   "members in the included file">, InGroup<PragmaPackSuspiciousInclude>,
diff --git a/clang/include/clang/Basic/LangOptions.def b/clang/include/clang/Basic/LangOptions.def
index 1fef2c5d881c77..b11473b4aaafa5 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -174,6 +174,8 @@ LANGOPT(ModulesLocalVisibility, 1, 0, Compatible, "local submodule visibility")
 LANGOPT(Static            , 1, 0, Compatible, "__STATIC__ predefined macro (as opposed to __DYNAMIC__)")
 VALUE_LANGOPT(PackStruct  , 32, 0, NotCompatible,
               "default struct packing maximum alignment")
+LANGOPT(PackAllStructs, 1, 0, NotCompatible,
+        "pack all structs, unions and classes")
 VALUE_LANGOPT(MaxTypeAlign  , 32, 0, NotCompatible,
               "default maximum alignment for types")
 VALUE_LANGOPT(AlignDouble            , 1, 0, NotCompatible, "Controls if doubles should be aligned to 8 bytes (x86 only)")
diff --git a/clang/include/clang/Options/Options.td b/clang/include/clang/Options/Options.td
index 9ff712eaa0e7fd..42c05a6d6c7847 100644
--- a/clang/include/clang/Options/Options.td
+++ b/clang/include/clang/Options/Options.td
@@ -4476,7 +4476,10 @@ def force__flat__namespace : Flag<["-"], "force_flat_namespace">;
 def force__load : Separate<["-"], "force_load">;
 def force_addr : Joined<["-"], "fforce-addr">, Group<clang_ignored_f_Group>;
 def foutput_class_dir_EQ : Joined<["-"], "foutput-class-dir=">, Group<f_Group>;
-def fpack_struct : Flag<["-"], "fpack-struct">, Group<f_Group>;
+def fpack_struct : Flag<["-"], "fpack-struct">, Group<f_Group>,
+  Visibility<[ClangOption, CC1Option]>,
+  HelpText<"Pack all structure members together without holes">,
+  MarshallingInfoFlag<LangOpts<"PackAllStructs">>;
 def fno_pack_struct : Flag<["-"], "fno-pack-struct">, Group<f_Group>;
 def fpack_struct_EQ : Joined<["-"], "fpack-struct=">, Group<f_Group>,
   Visibility<[ClangOption, CC1Option]>,
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp b/clang/lib/Driver/ToolChains/Clang.cpp
index 3721d01b56657c..0b4ef7de731634 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -8083,13 +8083,12 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA,
 
   // Honor -fpack-struct= and -fpack-struct, if given. Note that
   // -fno-pack-struct doesn't apply to -fpack-struct=.
-  if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
+  if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ))
     CmdArgs.push_back(
         Args.MakeArgString("-fpack-struct=" + Twine(A->getValue())));
-  } else if (Args.hasFlag(options::OPT_fpack_struct,
-                          options::OPT_fno_pack_struct, false)) {
-    CmdArgs.push_back("-fpack-struct=1");
-  }
+  if (Args.hasFlag(options::OPT_fpack_struct, options::OPT_fno_pack_struct,
+                   false))
+    CmdArgs.push_back("-fpack-struct");
 
   // Handle -fmax-type-align=N and -fno-type-align
   bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
diff --git a/clang/lib/Sema/SemaAttr.cpp b/clang/lib/Sema/SemaAttr.cpp
index e5253e2a311747..9a6193fa80ecab 100644
--- a/clang/lib/Sema/SemaAttr.cpp
+++ b/clang/lib/Sema/SemaAttr.cpp
@@ -52,6 +52,10 @@ Sema::PragmaStackSentinelRAII::~PragmaStackSentinelRAII() {
 }
 
 void Sema::AddAlignmentAttributesForRecord(RecordDecl *RD) {
+  // -fpack-struct packs every struct, union and class, as GCC does.
+  if (getLangOpts().PackAllStructs && !RD->hasAttr<PackedAttr>())
+    RD->addAttr(PackedAttr::CreateImplicit(Context));
+
   AlignPackInfo InfoVal = AlignPackStack.CurrentValue;
   AlignPackInfo::Mode M = InfoVal.getAlignMode();
   bool IsPackSet = InfoVal.IsPackSet();
@@ -480,6 +484,12 @@ void Sema::ActOnPragmaClangSection(SourceLocation PragmaLoc,
 
 void Sema::ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
                            StringRef SlotLabel, Expr *Alignment) {
+  // As in GCC, #pragma pack is ignored with -fpack-struct.
+  if (getLangOpts().PackAllStructs) {
+    Diag(PragmaLoc, diag::warn_pragma_pack_fpack_struct);
+    return;
+  }
+
   bool IsXLPragma = getLangOpts().XLPragmaPack;
   // XL pragma pack does not support identifier syntax.
   if (IsXLPragma && !SlotLabel.empty()) {
diff --git a/clang/lib/Sema/SemaLambda.cpp b/clang/lib/Sema/SemaLambda.cpp
index 08526b7ec22b83..7c648108eacef7 100644
--- a/clang/lib/Sema/SemaLambda.cpp
+++ b/clang/lib/Sema/SemaLambda.cpp
@@ -253,6 +253,9 @@ Sema::createLambdaClosureType(SourceRange IntroducerRange, TypeSourceInfo *Info,
   CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(
       Context, DC, Info, IntroducerRange.getBegin(), LambdaDependencyKind,
       IsGenericLambda, CaptureDefault);
+  // -fpack-struct packs closure types too, as GCC does.
+  if (getLangOpts().PackAllStructs)
+    Class->addAttr(PackedAttr::CreateImplicit(Context));
   DC->addDecl(Class);
 
   return Class;
diff --git a/clang/test/CodeGen/Sparc/sparcv9-packed-union-abi.c b/clang/test/CodeGen/Sparc/sparcv9-packed-union-abi.c
index dd3223475f5119..7addb3854fe5fb 100644
--- a/clang/test/CodeGen/Sparc/sparcv9-packed-union-abi.c
+++ b/clang/test/CodeGen/Sparc/sparcv9-packed-union-abi.c
@@ -4,6 +4,8 @@
 // RUN:   -fclang-abi-compat=23 | FileCheck %s --check-prefix=COMPAT
 // RUN: %clang_cc1 -triple sparcv9-unknown-unknown -emit-llvm %s -o - \
 // RUN:   -fpack-struct=1 | FileCheck %s --check-prefix=PACK-STRUCT
+// RUN: %clang_cc1 -triple sparcv9-unknown-unknown -emit-llvm %s -o - \
+// RUN:   -fpack-struct | FileCheck %s --check-prefix=PACK-ALL
 
 // GCC never passes or returns a union, or a struct with a packed field, in
 // floating-point registers on SPARC64. A struct declared packed has all of its
@@ -200,15 +202,15 @@ struct pragma_packed {
 struct pragma_packed pragma_packed(struct pragma_packed x) { return x; }
 
 // As in GCC, -fpack-struct=1 does not make the fields packed, so f stays in a
-// floating-point register. FIXME: GCC's -fpack-struct without =N does make
-// every struct packed, so GCC passes this struct in integer registers. The
-// driver turns -fpack-struct into -fpack-struct=1, so Clang does not match.
+// floating-point register. -fpack-struct without =N makes every struct packed,
+// so the struct is passed in integer registers.
 struct pack_struct {
   float f;
   int i;
 };
 
 // PACK-STRUCT-LABEL: define{{.*}} inreg %struct.pack_struct @pack_struct(float inreg %x.coerce0, i32 inreg %x.coerce1)
+// PACK-ALL-LABEL: define{{.*}} i64 @pack_struct(i64 %x.coerce)
 struct pack_struct pack_struct(struct pack_struct x) { return x; }
 
 // A misaligned double is passed in integer registers, like any misaligned
diff --git a/clang/test/Driver/fpack-struct.c b/clang/test/Driver/fpack-struct.c
index da98ae948b7b2d..57332d9fcb6375 100644
--- a/clang/test/Driver/fpack-struct.c
+++ b/clang/test/Driver/fpack-struct.c
@@ -1,10 +1,22 @@
-// RUN: %clang -fpack-struct -### %s 2> %t
-// RUN: FileCheck < %t %s
-// RUN: %clang -fpack-struct=8 -### %s 2> %t
-// RUN: FileCheck < %t %s --check-prefix=CHECK-EQ
+// RUN: %clang -fpack-struct -### %s 2>&1 | FileCheck %s
+// RUN: %clang -fpack-struct=8 -### %s 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=CHECK-EQ
+// RUN: %clang -fpack-struct -fno-pack-struct -### %s 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=CHECK-NONE
+// RUN: %clang -fpack-struct=8 -fpack-struct -### %s 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=CHECK-BOTH
 
 // CHECK: "-cc1"
-// CHECK: "-fpack-struct=1"
+// CHECK-SAME: "-fpack-struct"
+// CHECK-NOT: "-fpack-struct=
 
 // CHECK-EQ: "-cc1"
-// CHECK-EQ: "-fpack-struct=8"
+// CHECK-EQ-SAME: "-fpack-struct=8"
+// CHECK-EQ-NOT: "-fpack-struct"
+
+// CHECK-NONE: "-cc1"
+// CHECK-NONE-NOT: "-fpack-struct
+
+// CHECK-BOTH: "-cc1"
+// CHECK-BOTH-SAME: "-fpack-struct=8"
+// CHECK-BOTH-SAME: "-fpack-struct"
diff --git a/clang/test/Sema/fpack-struct.c b/clang/test/Sema/fpack-struct.c
index 63766e9c9dbd87..e38d4cc9d2b829 100644
--- a/clang/test/Sema/fpack-struct.c
+++ b/clang/test/Sema/fpack-struct.c
@@ -1,5 +1,11 @@
-// RUN: %clang_cc1 -DEXPECTED_STRUCT_SIZE=5 -fpack-struct=1 %s
-// RUN: %clang_cc1 -DEXPECTED_STRUCT_SIZE=6 -fpack-struct=2 %s
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fpack-struct=1 \
+// RUN:   -DEXPECTED_STRUCT_SIZE=5 -DEXPECTED_ALIGNED_OFFSET=1 -verify=max %s
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fpack-struct=2 \
+// RUN:   -DEXPECTED_STRUCT_SIZE=6 -DEXPECTED_ALIGNED_OFFSET=2 -verify=max %s
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fpack-struct -DPACK_ALL \
+// RUN:   -DEXPECTED_STRUCT_SIZE=5 -DEXPECTED_ALIGNED_OFFSET=4 -verify=all %s
+
+// max-no-diagnostics
 
 struct s0 {
        int x;
@@ -7,3 +13,34 @@ struct s0 {
 };
 
 int t0[sizeof(struct s0) == EXPECTED_STRUCT_SIZE ?: -1];
+
+// -fpack-struct=N limits the alignment of every field, even an aligned one.
+// -fpack-struct packs every struct and union, as if declared with
+// __attribute__((packed)), so an aligned field keeps its alignment. Both are
+// what GCC does.
+struct aligned_field {
+  char c;
+  int i __attribute__((aligned(4)));
+};
+
+_Static_assert(__builtin_offsetof(struct aligned_field, i) ==
+                   EXPECTED_ALIGNED_OFFSET, "");
+
+#ifdef PACK_ALL
+union u {
+  char c;
+  int i;
+};
+
+_Static_assert(_Alignof(union u) == 1, "");
+
+// As in GCC, #pragma pack has no effect with -fpack-struct.
+#pragma pack(push, 2) // all-warning {{#pragma pack has no effect with -fpack-struct; ignored}}
+struct pragma_pack {
+  char c;
+  int i;
+};
+#pragma pack(pop) // all-warning {{#pragma pack has no effect with -fpack-struct; ignored}}
+
+_Static_assert(sizeof(struct pragma_pack) == 5, "");
+#endif
diff --git a/clang/test/SemaCXX/fpack-struct.cpp b/clang/test/SemaCXX/fpack-struct.cpp
new file mode 100644
index 00000000000000..6ef28c91ca1193
--- /dev/null
+++ b/clang/test/SemaCXX/fpack-struct.cpp
@@ -0,0 +1,41 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -std=c++17 -fsyntax-only \
+// RUN:   -fpack-struct -verify %s
+// expected-no-diagnostics
+
+// -fpack-struct packs every class, as if declared with
+// __attribute__((packed)), as GCC does.
+struct s {
+  char c;
+  int i;
+};
+
+static_assert(sizeof(s) == 5, "");
+
+template <typename T> struct tmpl {
+  char c;
+  T t;
+};
+
+static_assert(sizeof(tmpl<int>) == 5, "");
+
+// So are closure types.
+void f() {
+  char c = 0;
+  int i = 0;
+  auto l = [c, i] { return c + i; };
+  static_assert(sizeof(l) == 5, "");
+}
+
+// A packed class does not pack a field of a non-POD class type, unless that
+// class is packed too. With -fpack-struct, it is.
+struct non_pod {
+  non_pod();
+  int i;
+};
+
+struct has_non_pod {
+  char c;
+  non_pod n;
+};
+
+static_assert(sizeof(has_non_pod) == 5, "");



More information about the cfe-commits mailing list