Collapse trailing padding
retep998 opened this issue · 10 comments
Since we don't have to worry about FFI interop for types that are not #[repr(C)]
, this means we can perform certain optimizations with regards to padding. One such optimization is collapsing trailing padding. For example std::mem::size_of::<((u16, u8), u8)>()
returns 6, but ideally it would be 4.
To implement this size optimization would require keeping track of two separate sizes, one being the actual size not including trailing padding, and the other being the array element size or aligned size. For example (u16, u8)
would have an actual size of 3, but an array size of 4.
As an added benefit, this would allow for enums to use that extra space at the end to store the discriminant.
This likely depends on teaching LLVM to support this sort of stuff.
Triage: not aware of any changes.
Should this be closed in favor of the RFC issue: rust-lang/rfcs#1397?
Just for record, std::mem::size_of::<((u16, u8), u8)>()
is still 6 on the current nightly, unaffected by #45225.
Cc @rust-lang/wg-codegen
I'll look at this given I'm having fun in the layout module these days.
Though I don't think it's something where we can just change the layout to be clever and expect everything else to work. What happens if you have a value coming from a [(u16, u8)]
slice and you want to write that value in the first element of the ((u16, u8), u8)
tuple?
I think we should add an attribute for this, something like #[no_trailing_padding]
, then wait until all unsafe code in the ecosystem supports it and stops doing things equivalent to memset(&x, sizeof(X))
(maybe few years) and only then maybe make #[no_trailing_padding]
a default.
To enable code to handle types with "no trailing padding" correctly, we need to introduce a distinction between "size" and "stride" like Swift has. Theoretically possible but a lot of churn and very hard to ensure all code is updated.
And also note the downside noted in rust-lang/rfcs#1397
Closing this in favour of the rfc listed above: rust-lang/rfcs#1397