[clang] [Sema] Diagnose taking the address of a #pragma pack member (PR #219096)

Aaron Puchert via cfe-commits cfe-commits at lists.llvm.org
Thu Sep 10 14:49:34 PDT 2026


================
@@ -16983,6 +16983,26 @@ void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
   }
 }
 
+/// If packing reduces \p FD below the alignment required by its type, return
+/// the alignment it is reduced to. __attribute__((packed)) reduces every
+/// field; #pragma pack(N) only reduces fields that require more than N.
+static std::optional<CharUnits> getPackedFieldAlignment(const ASTContext &Ctx,
+                                                        const FieldDecl *FD) {
+  const RecordDecl *RD = FD->getParent();
+  bool IsPacked = FD->hasAttr<PackedAttr>() || RD->hasAttr<PackedAttr>();
+  const auto *MFAA = RD->getAttr<MaxFieldAlignmentAttr>();
+  if (!IsPacked && !MFAA)
+    return std::nullopt;
+
+  CharUnits TypeAlignment = Ctx.getTypeAlignInChars(FD->getType());
+  if (!IsPacked &&
+      Ctx.toCharUnitsFromBits(MFAA->getAlignment()) >= TypeAlignment)
+    return std::nullopt;
----------------
aaronpuchert wrote:

I wonder if we shouldn't leave this to the caller to figure out and just return the minimum alignment here.

The first loop just wants to exit early in case no relevant attributes are present. Then we check the field alignment against the type alignment, and the second loop tries to find which attribute weakened it.

Conceptually I find it clearer to just return what the attributes say in this function, and then compare with the type alignment separately.

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


More information about the cfe-commits mailing list