-
Notifications
You must be signed in to change notification settings - Fork 1.6k
RFC: Add an attribute for raising the alignment of various items #3806
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
base: master
Are you sure you want to change the base?
Conversation
75d8fc6
to
f6f7686
Compare
f6f7686
to
3a4f5ac
Compare
800e69d
to
eca25f7
Compare
eca25f7
to
4badbc9
Compare
The `align` attribute is a new inert, built-in attribute that can be applied to | ||
ADT fields, `static` items, function items, and local variable declarations. The | ||
attribute accepts a single required parameter, which must be a power-of-2 | ||
integer literal from 1 up to 2<sup>29</sup>. (This is the same as | ||
`#[repr(align(…))]`.) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The 2^29 limit is way too high. The consistency with #[repr(align(..))]
is a good default but alignments larger than a page or two have never worked properly in local variables (rust-lang/rust#70143) and in statics (rust-lang/rust#70022, rust-lang/rust#70144). While there are some use cases for larger alignments on types (if they're heap allocated) and an error on putting such a type in a local or static is ugly, for this new attribute we could just avoid the problem from the start.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
For a struct field, both GCC and clang supported _Alignas(N)
for N ≤ 228 (268435456).
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The bug with local variables (rust-lang/rust#70143) seems to have been fixed everywhere except Windows, and just waiting on someone to fix it there as well in LLVM. (And even on Windows where the issue is not fixed, the only effect is to break the stack overflow protection, bringing it down to the same level as many Tier 2 targets.)
So the only remaining issue is with statics, where it looks like a target-specific max alignment might be necessary. Once implemented, that solution can be used to address align
as well.
Overall, I don't think any of this is sufficient motivation to impose a stricter maximum on #[align]
.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Note that fixing the soundness issue for locals just means that putting a local with huge alignment in a stack frame is very likely to trigger the stack overflow check and abort the program. There is no use case for such massively over-aligned locals or statics, which is why those soundness issues been mostly theoretical problems and why the only progress toward fixing them over many years has been side effects of unrelated improvements (inline stack checks).
The only reason why the repr(align(..))
limit is so enormous is because it’s plausibly useful for heap allocations. Adding a second , lower limit for types put in statics and locals nowadays is somewhat tricky to design and drive to consensus (e.g., there’s theoretical backwards compatibility concerns) and not a priority for anyone, so who knows when it’ll happen. For #[align]
we have the benefit of hindsight and could just mostly side-step the whole mess. I don’t see this as “needlessly restricting the new feature” but rather as “not pointlessly expanding upon an existing soundness issue for no reason”.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There is no use case for such massively over-aligned locals or statics
one use case I can think of is having a massive array that is faster because it's properly aligned so the OS can use huge pages (on x86_64, those require alignment static
s or heap-allocated/mmap
-ed memory.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
To use huge pages for static data, you'd want to align the ELF segment containing the relevant sections (or equivalent in other formats), so the right tool there is a linker script or similar platform-specific mechanism. Over-aligning individual static
s is a bad alternative:
- It risks wasting a lot more (physical!) memory than expected if you end up with multiple
static
s in the program doing it and there's not enough other data to fill the padding required between them or they go in different sections. - If the linker/loader ignores the requested section alignment then that leads to UB if you used Rust-level
#[align(N)]
/#[repr(align(N))]
and the code was optimized under that assumption. - While aligning statics appears easier and more portable than linker scripts, the reality is that platform/toolchain support for this is spotty anyway, so you really ought to carefully consider when and where to apply this trick.
In any case, I'm sure I'm technically wrong to claim that nobody could ever come up with a use case for massively over-aligned statics. But there's a reason why Linux and glibc have only started supporting it at all in the last few years, and other environments like musl-based Linux and Windows apparently doesn't support it at all (see discussion in aforementioned issues).
text/3806-align-attr.md
Outdated
In Rust, a type’s size is always a multiple of its alignment. However, there are | ||
other languages that can interoperate with Rust, where this is not the case | ||
(WGSL, for example). It’s important for Rust to be able to represent such | ||
structures. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It's not clear to me how this would work while keeping Rust's "size is multiple of align" rule intact. I guess if it's about individual fields in a larger aggregate that maintains the rule in total? I don't know anything about WGSL so an example would be appreciated.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
That’s exactly it. The WSGL example was taken from this comment on Internals: https://internals.rust-lang.org/t/pre-rfc-align-attribute/21004/20
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Adding a worked example would indeed help readers of the RFC on this point.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Here is a concrete example of implementing Rust-WGSL compatibility using the #[align]
attribute defined in this RFC. These structs have the same layout, and together demonstrate both inserting required padding (between foo
and bar
), and allowing a following field to be placed where a wrapper type would demand padding (baz
immediately after bar
):
// WGSL
struct Example { // size = 32, alignment = 16
foo: vec3<f32>, // offset = 0, size = 12
bar: vec3<f32>, // offset = 16, size = 12
baz: f32, // offset = 28, size = 4
}
// Rust
#[repr(linear)] // as defined in this RFC; repr(C) in current Rust
#[derive(Debug, Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
pub(crate) struct Example {
#[align(16)]
foo: [f32; 3],
// #[align] below causes 4 bytes of padding to be inserted here to satisfy it.
#[align(16)]
bar: [f32; 3],
baz: f32, // If we used a wrapper for bar, this field would be at offset 32, wrongly
}
It is often possible to order structure fields to fill gaps so that no inter-field padding is needed — such as if the fields in this example were declared in the order {foo, baz, bar}
— and this is preferable when possible to avoid wasted memory, but the advantage of using #[align]
in this scenario is that when used systematically, it can imitate WGSL's layout and thus will be correct even if the field ordering is not optimal.
(Please feel free to use any of the above text in the RFC.)
We discussed this in the lang call today. We were feeling generally favorable about this, but all need to read it more closely. |
Also, justify prohibition on fn params.
text/3806-align-attr.md
Outdated
1. What should the syntax be for applying the `align` attribute to `ref`/`ref | ||
mut` bindings? | ||
|
||
- Option A: the attribute goes inside the `ref`/`ref mut`. | ||
|
||
```rust | ||
fn foo(x: &u8) { | ||
let ref #[align(4)] _a = *x; | ||
} | ||
``` | ||
|
||
- Option B: the attribute goes outside the `ref`/`ref mut`. | ||
|
||
```rust | ||
fn foo(x: &u8) { | ||
let #[align(4)] ref _a = *x; | ||
} | ||
``` |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Whatever we do, I'd expect it to be the same as for mut
. So it's probably not worth deferring this question, as we need to handle it there.
As for where to put it, it seems like a bit of a coin toss. Anyone have a good argument for which way it should go?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I’m comfortable deferring it because I see no use-case for it, and I don’t want to hold up the RFC on something with no use case.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sure, but still, I repeat my question, as we need to answer it for mut
in any case, about whether there are good arguments for on which side of mut
the attribute should appear.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The mut
case does have actual use-cases, so I think we should handle the issue in the context of that, not this RFC.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Oh, wait, I think there may be a misunderstanding here. By “the same as for mut
”, are you referring to combining mut
with ref
/ref mut
?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
No. This RFC specifies this is allowed (quoting from an example in the RFC):
let (a, #[align(4)] b, #[align(2)] mut c) = (4u8, 2u8, 1u8);
My question is whether there are good arguments about whether we should prefer that, or should instead prefer:
let (a, #[align(4)] b, mut #[align(2)] c) = (4u8, 2u8, 1u8);
The RFC should discuss any reasons we might want to prefer one over the other.
Separately, and secondarily, my feeling is that if we chose
let #[align(..)] mut a = ..;
then we would also choose:
let #[align(..)] ref a = ..;
And if we instead chose
let mut #[align(..)] a = ..;
then we would choose:
let ref #[align(..)] a = ..;
So my feeling is that in settling the question of how to syntactically combine #[align(..)]
and mut
, we are de facto settling the question of how to combine #[align(..)]
with any other binding mode token.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don’t agree that we would necessarily want to make the same choice in both cases. I actually think it depends on how mut
and ref
/ref mut
should be combined.
If the combination looks like
let ref (mut x) = …;
let ref mut (mut x) = …;
Then we should also do
let ref (#[align(…)] x) = …;
let ref mut (#[align(…)] x) = …;
But if it looks like
let mut ref x = …;
let mut ref mut x = …;
Then we should do
let #[align(…)] ref x = …;
let #[align(…)] ref mut x = …;
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
In that event, and in your model, that would still leave us deciding between:
let ref (mut #[align(..)] x) = ..; // 1
// vs
let ref (#[align(..)] mut x) = ..; // 2
And between:
let #[align(..)] mut ref x = ..; // 3
// vs
let mut #[align(..)] ref x = ..; // 4
I would estimate that we'd comfortably favor 1, 3 over 2, 4.
There are also, of course, these possibilities:
let #[align(..)] ref (mut x) = ..; // 5
let mut ref #[align(..)] x = ..; // 6
If in this RFC we pick #[align(..) mut x
, that would rule out for me option 1 if we later did ref (mut x)
(and I wouldn't pick option 2 anyway). If we pick mut #[align(..)] x
, that would rule out for me option 3 if we later did mut ref x
(and I wouldn't pick option 4 anyway).
That is, even in this future possibility, I'm going to want to keep all of the binding mode tokens either to the left or to the right of the attribute.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I’ll elaborate in the RFC, but my preference is for 2 or 3.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I’ve added a section on this to the RFC.
Having now had the chance to review this RFC thoroughly, I say that it's well written. Thanks to @Jules-Bertholet for that. It seems well motivated to me. As mentioned above, I'd like for the document to speak more about the analysis of why one or another behavior is proper for If those things can perhaps be done, and the analysis with respect to |
This RFC proposes |
Then I'd appreciate if the RFC could discuss the reasons why we might want to make a different choice between these. It would surprise me a lot if we did, but I gather you must have a good argument in mind for this. |
cc @Nadrieril |
e366c50
to
96350ee
Compare
text/3806-align-attr.md
Outdated
desirable, for optimal performance, to pack them into as few cache lines as | ||
possible. One way of doing this is to force the alignment of the value to be at | ||
least the size of the cache line, or perhaps the greatest common denominator of | ||
the value and cache line sizes. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I am very confused by this paragraph, and don't understand what it tries to say. By raising the alignment, the items will be further apart from each other (since each one must be properly aligned), and therefore it will take more cache lines, not fewer?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The idea is that you don't want a field to span across 2 cache lines if it could fit into just one. An easy way to achieve that is to make the field start at the start of a new cache line.
Aligning a field also means that a reference to it is aligned, which can improve performance in certain cases.
edit: i agree the text should explain this in more detail
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I’ve reworded this paragraph.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Right, so you want to avoid false sharing, that makes sense.
The new text helps, thanks. The section title still says "Packing values into fewer cache lines" though, which doesn't seem to match the text.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It's not about false sharing -- if that was a problem, trailing padding until the next cache line boundary would be a plus. It's about possibly bringing fewer cache lines into the cache for common access patterns. This is a minor micro-optimization at best.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It's about possibly bringing fewer cache lines into the cache for common access patterns.
This is exactly it.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
"Packing values into fewer cache lines"
As it pertains to the header, the ambiguity is the difference between packing the collection of all values into (maybe) fewer cache lines, or packing the bits of each value into (maybe) fewer cache lines.
The word "packing" tends to imply arranging many individual discrete things to fit in less space, and so is perhaps a misleading word for this when combined with "values".
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I updated the paragraph again to clarify further.
text/3806-align-attr.md
Outdated
static LOOKUP_TABLE: CacheAligned<SomeLargeType> = CacheAligned(SomeLargeType { | ||
data: todo!(), | ||
}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The example is confusing since SomeLargeType
is declared as an array but then later we pretend it is a struct. I don't understand what this is trying to say.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fixed, sorry. The contents of the type are immaterial, only the size matters
In my view, this RFC is well motivated and has a lot of correct details. Thanks to @Jules-Bertholet for writing this up. I think we should do it with one adjustment. Proposal: Accept this RFC as written, modulo that: As far as this RFC goes, we allow IdentifierPattern -> OuterAttribute* `ref`? `mut`? IDENTIFIER ( `@` PatternNoTopAlt )? Semantically, for the moment, we would disallow attributes other than If maybe we want to hold back on allowing The current text contains an argument about how this question should be tied in with a potential decision we might later make about syntax for reference bindings where the binding itself is mutable, but I don't buy it. We might or might not ever do that, and even if we did, it wouldn't change my own feeling that all the tokens that control the binding mode should appear together in the grammar. I find the grammar above just too compelling. In terms of whether @rfcbot fcp merge |
Team member @traviscross has proposed to merge this. The next step is review by the rest of the tagged team members: No concerns currently listed. Once a majority of reviewers approve (and at most 2 approvals are outstanding), this will enter its final comment period. If you spot a major issue that hasn't been raised at any point in this process, please speak up! cc @rust-lang/lang-advisors: FCP proposed for lang, please feel free to register concerns. |
Strongly disagree. I’ve updated the RFC |
Thanks, yes, that's right. Adjusted the proposal. |
Port C
alignas
to Rust.Rendered