-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
ability to set alignment on struct fields #1512
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Here we can see a use case for specifying the alignment of struct fields: https://github.com/facebook/folly/blob/master/folly/ProducerConsumerQueue.h (search for 'alignas'). They specify the alignment to be the minimum offset between two objects to avoid false sharing. |
Note this workaround that is now in master branch, and also described in #1845 (comment): Lines 2698 to 2707 in 459045a
I think we have to solve the underlying issue before this issue can be resolved. |
One more thing that should be done with this issue, is to make packed structs divide based on ABI size, not store size. So for this example: const std = @import("std");
const assert = std.debug.assert;
comptime {
assert(@sizeOf(u24) == 4);
}
const P = packed struct {
a: u24,
b: u8,
}; Currently the struct is generated as %P = type <{ i24, i8 }> This is problematic because based on Instead Zig should generate the struct like this: %P = type <{ i32 }> and then do the normal bit shifting and masking that happens for bit fields. This will enable packed structs to work effectively when specifying alignment. Otherwise, aligned u24 fields of packed structs would incorrectly be missing a padding byte. |
After implementing this, audit |
@nrdmn notes that this is required for certain UEFI structures.
|
I'm in the middle of fixing the bugs regarding struct alignment (#2174). Once that's done, the main blocker to this will be updating the grammar, parser, zig fmt, etc. Anyone want to take a crack at that? The syntax/parser updating work can be merged even if the analysis/codegen isn't done yet. Here's the current syntax proposal: struct {
x: i32 align(expression),
} |
Just like global variables and local variables support alignment, struct fields should support alignment.
The alignment of a struct should be the alignment of its most aligned member. As Zig iterates over the fields of a struct, it knows the current alignment at that position. When a field requires more alignment, padding bytes are inserted until the desired alignment is achieved. Zig currently does this incorrectly - See #1248
Related is reordering fields for better performance and memory usage (see #168)
You should also be able to set the alignment of fields in packed structs. This does 2 things:
A packed struct in an array should give a compile error if its size is not byte-aligned, or if its size is not aligned to its own alignment.
The text was updated successfully, but these errors were encountered: