Repository navigation
C front-end: Visual Studio layout of bit-fields - #9580
tautschnig wants to merge 20 commits into
Conversation
Packing needs to be evaluated as part of the definition of a type, while an alignment attribute also applies where the type is used. The position of an attribute also requires care, as GCC accepts some positions while ignoring the attribute there (Clang warns that it ignores them). - A typedef'd type no longer carries the packing of the type it names (which is already reflected in the layout of a packed struct/union), unless the use site requests packing, so that a packed-struct typedef used as a member does not pack the enclosing struct (diffblue#8443). - Alignments are combined (the stricter one applies) when a struct/union declared with an alignment attribute is completed, and when a typedef that carries an alignment is used with another one. - A packed attribute preceding the struct/union keyword of a declaration is dropped, as GCC and Clang ignore it. - Alignments must be positive powers of two (C11 6.2.8p4), which the type checker now verifies. An alignment of zero has no effect (C11 6.7.5p6, and GCC also ignores __attribute__((aligned(0))), with a warning), so the type checker drops it. - As the natural alignment of a scalar was its size, the 12-byte long double of i386 had an alignment of 12, which the new check would reject in the declaration of max_align_t in GCC's and Clang's stddef.h, which uses __attribute__((__aligned__(__alignof__(long double)))) GCC and Clang align this long double to 4, i.e., the largest power of two that divides its size, which is now the natural alignment of a scalar whose size is not a power of two. The new test ansi-c/gcc_attributes16 covers attributes in many positions, including a reduction of diffblue#8443, and gcc_attributes16_align_error covers an invalid alignment. alignas_zero covers an alignment of zero, and long_double_alignment_i386 uses Clang's support for targeting i386 on any host. Fixes: diffblue#8443 Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
A union's size must be a multiple of its alignment, including when the
alignment comes from an explicit aligned() attribute on a packed union.
Previously add_padding(union_typet) discarded any explicit alignment for
packed unions (rounding the size up to a single byte only), so e.g.
union __attribute__((packed)) __attribute__((aligned(16))) u
{ uint8_t c; int32_t i; };
had size 4 instead of 16. The alignment is now computed as the maximum
member alignment (one byte if packed), raised by an explicit aligned()
attribute regardless of packing, matching GCC and Clang.
Adds regression test union_packed_aligned, and checks the size of an
aligned union in gcc_attributes16.
Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
The alignment of a struct/union member depends on whether the enclosing aggregate is packed, which a context-free alignment() could not capture: the same type (e.g. int aligned(2)) must align to 4 inside a non-packed struct (an aligned() attribute can only increase alignment there) but to 2 inside a packed struct (where it is honoured verbatim). alignment() now derives an aggregate's alignment from its members' layout alignments, computed in the aggregate's packing context via a new member_layout_alignment helper: - packed field: the explicit alignment verbatim, otherwise one byte; - non-packed field: max(explicit, natural) -- an aligned() request smaller than the natural alignment is ignored. An explicit alignment on the aggregate itself can only raise the result, while on a non-aggregate (e.g. a typedef) it is still taken verbatim. Padding members no longer contribute to an aggregate's alignment (they previously polluted _Alignof of e.g. a union with an array member). add_padding_gcc uses the same per-member computation for member offsets, and a packed struct is now padded up to the alignment forced by an explicitly-aligned member (it previously skipped end-of-struct padding for any packed struct). add_padding(union_typet) is simplified to rely on the corrected alignment(). This makes sizeof/_Alignof match GCC and Clang for member-level and struct/union-level aligned()/packed combinations. Adds regression test struct_member_alignment. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
An alignment attribute that follows a declarator, as in a struct member int32_t m __attribute__((aligned(8 + 8))); is attached to the declarator's type outside the already type-checked declaration type. typecheck_type only type-checked and folded the alignment of a type that is not already type-checked, so this alignment remained an unevaluated expression. padding then failed to convert it to a number and silently used the natural alignment instead: the member was placed at offset 4 rather than 16. Literal alignments happened to work, as the unevaluated literal converts to a number, and so did members of array type, whose attributes take a different path. Invalid alignments, such as aligned(5 + 0), were accepted silently. Type-check, fold, and validate such alignments as well, sharing the code with the existing alignment handling, and report errors at the location of the alignment expression, as the type may not carry a location. Extend struct_member_alignment by members with constant-expression alignments, and add the negative test gcc_attributes16_align_error_member. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
Anonymous structs and unions are named after their members, and an
existing type symbol of the same name is re-used. As the name did not
include packing or alignment attributes, `struct { int i; } a1;` and
`struct { int i; } __attribute__((packed)) a2;` were conflated, and
whichever was declared first determined the layout of both. Include
packing and explicit alignment of the aggregate and of its members'
types in the name.
Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
The parser used to communicate #pragma pack(n) by attaching both __attribute__((packed)) and __attribute__((aligned(n))) to each member whose type is not a struct or union, and additionally marked the aggregate as packed for pack(1). This conflated the pragma's cap on member alignment with explicit attributes, and was wrong in several ways: - an aligned attribute on the aggregate was capped by the pragma, but GCC, Clang, and Visual Studio do not cap it (and the aggregate-level packed of pack(1) had no such effect either); - packed on the aggregate no longer reduced member alignment to one; - explicit aligned() on members was replaced rather than capped; - members of struct or union type were not capped at all. Record the applicable #pragma pack value with each member declaration instead (ID_C_pragma_pack), and cap each member's layout alignment at that value in padding, for both GCC and Visual Studio layouts. The value that applies differs between compilers when the pragma changes within a definition: GCC uses the value in effect at the closing brace, Clang the value in effect where the definition starts, and Visual Studio the value in effect at each member. The parser determines the value accordingly. Bit-fields are capped as well. Anonymous aggregates are distinguished by the per-member value, and dump-c reproduces the pragma (which, for pack(1), it previously did via the aggregate-level packed attribute). The test goto-instrument/dump-c-pragma-pack checks the layout using pointer differences, which, unlike sizeof, dump-c does not replace by their value, so that compiling the output again checks the layout. dump-c-pragma-pack-anonymous (KNOWNBUG) documents that the inline definition of an anonymous struct member does not reproduce the #pragma pack in effect for that struct. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
`#pragma pack(n)` sets the current maximum alignment, and `#pragma pack()` resets it to the default; neither changes the stack used by `#pragma pack(push[, n])` and `#pragma pack(pop)`. We instead pushed n, and cleared the whole stack, respectively, so that, e.g., a `#pragma pack(pop)` following `#pragma pack(push, 1)` and `#pragma pack(2)` restored a maximum alignment of 1 rather than the value before the push. Furthermore, a `#pragma pack(pop)` without a matching push reset the current value to the default rather than retaining it. This matches the documentation and behaviour of GCC, Clang, and Visual Studio. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
Bit-fields contributed the alignment of their underlying type to the
alignment of the enclosing struct (used for end-of-struct padding) even
when the struct is packed, so that, e.g.,
`struct { int m : 7; } __attribute__((packed))` had size 4 instead of
1. Use the member layout alignment instead, which now also covers
bit-fields:
- in a packed aggregate, bit-fields are densely packed, unless a
#pragma pack(n) is in effect, which then caps their alignment at n
(GCC and Clang agree on this);
- a zero-width bit-field aligns the next member to its underlying type
irrespective of packing, but, like any unnamed bit-field, only affects
the alignment of the aggregate where unnamed bit-fields do (see
unnamed_bit_fields_affect_alignment): on ARM (other than Apple's ABI),
and on Windows.
Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
GCC and Clang distinguish the alignment of a declared entity from that
of its type: an alignment attribute in a declaration applies to the
declared member, object, or typedef, irrespective of its position in
the declaration. For members, such an attribute can only increase the
alignment, also within packed aggregates and for bit-fields (whose
start it then aligns). For objects, it may also reduce the alignment.
In contrast, the alignment of a type (set by a typedef or a
struct/union definition) may be smaller than its natural alignment,
and packing overrides it.
We previously recorded every alignment attribute on whichever type it
was syntactically attached to, and treated all of them as increasing
the alignment of a member. This went wrong in several ways:
- a typedef that reduces the alignment of a type, as in
`typedef int T __attribute__((aligned(2)));`, did not reduce the
alignment of members of type T;
- `__attribute__((aligned(16))) char *p` or
`long __attribute__((aligned(2))) m[2]` aligned the pointee or
element type rather than the member;
- packing did not override the alignment of typedef'd types or of
struct/union definitions used as members, but did override member
attributes;
- a member attribute replaced, rather than combined with, the
alignment of a typedef'd type;
- the alignment of a struct/union definition was copied to every use
of its tag, where it was then taken verbatim, so that
`struct S { long l; } __attribute__((aligned(1)))` reduced the
alignment of members of type `struct S`;
- an attribute on an object could not reduce its alignment (as
reported by __alignof__).
Record alignments requested by declarations separately
(ID_C_declaration_alignment), move them to the outermost level of the
declared entity's type, and turn them into the type's alignment for
typedefs only. __typeof__ does not carry them over, as they are not
part of the type. Struct/union definitions keep their attributes with
the type symbol only. The parser drops packed and aligned attributes
between the keyword and the tag of a declaration without body, as in
`struct __attribute__((aligned(16))) S *p;`, which GCC ignores, so that
they do not become declaration alignments of p. GCC (but not Clang)
applies an attribute that follows the '*' of a pointer declarator to the
pointer type, which the parser now marks accordingly. When combining a
plain `__attribute__((aligned))` with an explicit alignment, retain the
latter, as we do not determine the target's maximum alignment. Encode
declaration alignments in the names of anonymous aggregates.
This promotes ansi-c/struct_member_alignment_typedef from KNOWNBUG to
CORE. The new test cbmc/Bitfields6 is the example of diffblue#7816, where the
alignment attributes of bit-field declarations did not align the start
of the bit-fields.
Fixes diffblue#7816
Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
The parser accepted Visual Studio's __declspec between `struct`/`union`
and the tag, but discarded it, so that, e.g.,
`struct __declspec(align(8)) S { char c; };` had size 1 and alignment
1 instead of 8. Retain the declspec with the type, which already
handles align(n).
Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
Differential testing against MSVC x64 (via Compiler Explorer) showed three differences in Visual Studio mode: - the trailing padding of a struct or union is capped by the #pragma pack in effect at the end of its definition, whereas the alignment of the aggregate is not; - #pragma pack does not reduce an alignment that __declspec(align(n)) requires (also via a typedef), neither for a member nor for the trailing padding; - bit-fields do not affect the alignment of a union (only its size). Record the #pragma pack value at the end of the definition with the aggregate in Visual Studio mode, and lay out members using the common member layout alignment, which now also implements the latter two rules. dump-c reproduces the value at the end of the definition. The new test goto-instrument/dump-c-pragma-pack-msvc covers dump-c in Visual Studio mode. For this, chain.sh passes options selecting a Visual Studio target to goto-cc (except on Windows, where this is the default), and does not compile the output of dump-c again, as this would require Visual Studio's system headers. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
Reading an alignment or #pragma pack value from a type or component -- find the attribute, cast it to an expression, and convert it to a number with a default -- was repeated in padding (twice), type2name, and dump-c, not all of which handled an `aligned` attribute without argument (ID_default). layout_attribute now does this in one place. Also document member_layout_alignment, which implements the layout rules that depend on the context of a component. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
Whether a packed or aligned attribute applies to a struct/union type or
to the declared object, member, or typedef depends on its position, as
GCC and Clang agree:
- between the struct/union keyword and the opening brace, and directly
after the closing brace, it applies to the type being defined;
- in any other position, e.g., preceding the keyword, following a
qualifier, or following the tag of a declaration without body, it
applies to the declared entity.
Attributes in the latter positions of a definition previously ended up
with the type being defined, so that, e.g.,
__attribute__((aligned(16))) struct S { char c; } s;
aligned struct S rather than just s, and
const __attribute__((packed)) struct P { char c; int i; } p;
packed struct P (only a packed attribute preceding the keyword was
dropped). Furthermore, the last of several alignment attributes of a
declaration applied.
The parser now marks the attributes in type positions, which become
attributes of the type (ID_C_alignment, ID_C_packed), while all others
become attributes of the declared entity, recording packing of a
struct/union definition as ID_C_declaration_packed until the type
checker moves it to the tag type. A packed attribute then packs a
member, as GCC and Clang do, and has no effect for an object. With
several alignment attributes of a declaration, the largest one now
applies, as with GCC and Clang. For a type, GCC uses the last one, and
Clang the largest one.
Visual Studio, in contrast, applies __declspec(align(n)) in the other
positions of a definition (e.g., preceding the keyword) to the declared
entity and also to the type being defined, unless a declspec between
the keyword and the opening brace sets the alignment of the type: with
__declspec(align(8)) struct S { char c; };
the size of struct S is 8, as Struct_Padding5 and Union_Padding1 expect
on Windows.
The new test ansi-c/alignment_attribute_positions covers these cases,
gcc_attributes16 now also covers attributes preceding the keyword of a
definition, and declspec_align_struct covers the Visual Studio rules.
Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
The alignment that the declaration of an object or member requests (ID_C_declaration_alignment) is recorded with the type of the declared entity, and thus also travelled into the types of expressions computed from it: with int x __attribute__((aligned(16))), __alignof__(x + 0) was 16, where GCC and Clang give 4. __alignof__ now uses the declaration alignment for objects and members only. GCC and Clang disagree on __alignof__(*&x): GCC folds the dereference of the address of an object to that object, and thus yields 16, whereas Clang considers the operand as written, and yields 4. Furthermore, for a dereferenced pointer GCC uses the largest alignment of the pointee types of the pointer and of any pointers it was converted from, so that __alignof__(*(char *)&x) is 4 with GCC and 1 with Clang. Implement both behaviours depending on the compiler mode. The new test ansi-c/alignof_expression covers these cases, and runs in both GCC and Clang mode. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
GCC ignores packed and aligned attributes between the struct/union
keyword and the tag of a declaration without body, as in
struct __attribute__((aligned(16))) S;
struct S { char c; };
Clang, however, applies them to the type if it is not complete yet, so
that the above S has an alignment of 16 with Clang and of 1 with GCC.
Once the type is complete, Clang ignores them as well (with a warning).
With several such declarations, as well as with a definition that has
attributes of its own, the largest alignment applies, and the type is
packed if any of them requests packing.
The parser now marks these attributes as type attributes, and, in Clang
mode, the type checker records them with the incomplete type symbol,
from where the definition picks them up. In GCC mode they continue to
be ignored.
The new test ansi-c/attributes_declaration_without_body covers these
cases, and runs in both GCC and Clang mode.
Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
Visual Studio accepts declspecs in the declaration of a member, e.g.,
struct M { char c; __declspec(align(16)) int i; };
for which goto-cc reported a syntax error, as the grammar only permits
declspecs where storage classes may occur. Members now also accept
declspecs preceding their type, which, like any other alignment
attribute of the declaration of a member, can only increase its
alignment.
The new test ansi-c/declspec_align_member checks the layouts that MSVC
19 for x64 yields for such members.
Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
Visual Studio does not let __declspec(align(n)) reduce an alignment (it ignores such a declspec, warning C4359 for a struct), and it uses the last of several align declspecs of a declaration (warning C4141). Like for GCC's aligned attribute, goto-cc instead reduced the alignment of objects and typedefs, e.g., __alignof(x) was 2 with __declspec(align(2)) int x; and used the largest of several align declspecs. In Visual Studio mode, the explicit alignment of a type or of an object is now at least its natural alignment, and the last align declspec of a declaration applies. The new test ansi-c/declspec_align_msvc_rules checks the alignments that MSVC 19 for x64 yields. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
With Visual Studio, consecutive bit-fields of types of the same size
share a unit of that size, but a bit-field that does not fit into the
remaining bits of the current unit starts a new one. CBMC kept adding
such bit-fields to the current unit, so that, e.g., in
struct { short x : 12; short y : 6; };
y straddled the two bytes holding x and the next one, and the struct had
size 3 (rounded up to 4) rather than 4 with y at offset 2.
Differential testing against Clang 18's implementation of the Visual
Studio layout for x86-64 and i386 Windows on 1000 randomly generated
structs with bit-fields of all widths: 140 of them differed before this
change, and none after.
The new test cbmc/msvc_bit_field_units checks a selection of such
layouts for 64-bit and 32-bit Windows.
Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
With Visual Studio, the size of a union is at least the size of the
declared type of any of its bit-fields, but the bit-fields do not affect
the alignment of the union. CBMC instead padded the size up to a
multiple of the width of the declared type of any bit-field, so that,
e.g., the size of
union { char c[5]; int x : 3; };
was 8 rather than 5.
The new test cbmc/msvc_union_bit_field_size checks a selection of such
layouts for 64-bit and 32-bit Windows.
Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
Visual Studio ignores a zero-width bit-field unless it follows a
bit-field of non-zero width. Only then does it end the unit of that
bit-field and align the next member (and the struct) to its declared
type, or, in a union, make the size of the union at least the size of
its declared type. CBMC applied these effects to every zero-width
bit-field, so that, e.g., the size of
struct { char a; unsigned : 0; char b; };
was 8 rather than 2.
Differential testing against Clang 18's implementation of the Visual
Studio layout for x86-64 and i386 Windows on 1000 randomly generated
structs and unions with bit-fields of all widths, zero-width and
unnamed bit-fields, and #pragma pack: 108 of them differed before the
changes to bit-field layout in this and the previous two commits, 32
after the previous commit, and none after this one.
The new test cbmc/msvc_zero_width_bit_field checks a selection of such
layouts for 64-bit and 32-bit Windows.
Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
There was a problem hiding this comment.
Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.
An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing. Review the Copilot code review billing settings.
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## develop #9580 +/- ##
===========================================
+ Coverage 81.29% 81.35% +0.06%
===========================================
Files 1725 1725
Lines 191680 192119 +439
Branches 73 74 +1
===========================================
+ Hits 155832 156305 +473
+ Misses 35848 35814 -34 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
|
Please consolidate the tests! We've got too many directories. |
|
Consider some squashing of commits |
Depends-on: #8454
Three fixes to the Visual Studio layout of bit-fields:
struct { short x : 12; short y : 6; },yis now at offset 2.union { char c[5]; int x : 3; }now has size 5 rather than 8.struct { char a; unsigned : 0; char b; }now has size 2 rather than 8.These were found by differential testing against Clang 18's implementation of the Visual Studio layout for x86-64 and i386 Windows. The test compares sizes, alignments, member offsets, and the bytes covered by each bit-field of randomly generated structs and unions. On #8454, 140 of 1000 structs with bit-fields differed, and 108 of 1000 structs and unions that also have zero-width and unnamed bit-fields and
#pragma pack. With this PR, none differ.