We have all used Box<T> before in our Rust code. It’s a glorious type, with great ergonomics
and flexibitility. We can use it to put our values on the heap, but it can do even more
than that!
struct Fields {
@@ -45,16 +45,17 @@ reveals the solution: (severely shortened to only show the relevant parts)noalias
is an LLVM attribute on pointers that allows for various optimizations. If there are two pointers,
and at least one of them is noalias, there are some restrictions around the two. Approximately:- If one of them writes, they must not point to the same value (alias each other)
- If neither of them writes, they can alias just fine.
Therefore, we also apply
noaliasto&mut Tand&T(if it doesn’t contain interior mutability through -UnsafeCell<T>, since they uphold these rules.
This might sound familiar to you if you’re a viewer of Jon Gjengset’s content (which I can highly recommend). Jon has made an entire video about this before, since his crate left-right
+UnsafeCell<T>), since they uphold these rules.
For more info on noalias, see LLVMs LangRef.
This might sound familiar to you if you’re a viewer of Jon Gjengset’s content (which I can highly recommend). Jon has made an entire video about this before, since his crate left-right
was affected by this (https://youtu.be/EY7Wi9fV5bk).
If you’re looking for any hint that using box emits noalias, you have to look no further than the documentation
for std::boxed. Well, the nightly or beta docs, because I only added this section very recently. For years, this behaviour was not really documented, and you had to
belong to the arcane circles of the select few who were aware of it. So lots of code was written thinking that box was “just an
RAII pointer” (a pointer that allocates the value in the constructor, and deallocates it in the destructor on drop) for all
-pointers are concerned.
Stacked Borrows and Miri⌗
TODO: introduce UB by explaining how it allows optimizations like the one above, don’t talk in standardese
Miri is an interpreter for Rust code with the goal of finding undefined behaviour. -Undefined behaviour, UB for short, is behaviour of a program upon which no restrictions are imposed. If UB is executed, -anything can happen, including segmentation faults, silent memory corruption, leakage of private keys or exactly -what you intended to happen. Examples of UB include use-after-free, out of bounds reads or data races.
I cannot recommend Miri highly enough for all unsafe code you’re writing (sadly support for some IO functions -and FFI is still lacking, and it’s still very slow).
So, let’s see whether our code contains UB. It has to, since otherwise the optimizer wouldn’t be allowed to change +pointers are concerned.
Stacked Borrows and Miri⌗
So, LLVM was completely correct in optimizing our code to make the assert fail. But what exactly gave it permission to do so? +Undefined Behaviour (UB for short). Undefined behaviour is at the root of many modern compiler optimizations. But what is undefined behaviour? +UB represents a contract between the program and the compiler. The compiler assumes that UB will not happen, and can therefore optimize based +on these assumptions. Examples of UB also include use-after-free, out of bounds reads or data races. If UB is executed, anything can happen, +including segmentation faults, silent memory corruption, leakage of private keys or exactly what you intended to happen.
Miri is an interpreter for Rust code with the goal of finding undefined behaviour in Rust. I cannot recommend Miri +highly enough for all unsafe code you’re writing (sadly support for some IO functions and FFI is still lacking, and it’s still very slow).
So, let’s see whether our code contains UB. It has to, since otherwise the optimizer wouldn’t be allowed to change
observable behaviour (since the assert doesn’t fail in debug mode). $ cargo miri run…
error: Undefined Behavior: attempting a read access using <3314> at alloc1722[0x0], but that tag does not exist in the borrow stack for this location
--> src/main.rs:2:26
|
@@ -105,22 +106,29 @@ This is fairly inconvenient, but totally acceptable. There are bigger problems t
that want to expose a generic interface over any type. Users like to choose box, and sometimes have to chose box because of
other box-exclusive features it offers. Even worse is string_cache, which is extremely hard to fix.Then last but not least, there’s the opinionated fact that Box<T> shall be implementable entirely in user code. While we are
many missing language features away from this being the case, the noalias case is also magic descended upon box itself, with no
-user code ever having access to it.
There are also several arguments in favour of box being unique and special cased here. To negate the last argument above, it can
+user code ever having access to it.
There are several arguments in favour of box being unique and special cased here. To negate the last argument above, it can
be said that Box<T> is a very special type. It’s just like a T, but on the heap. Using this mental model, it’s very easy to
justify all the box magic and its unique behaviour. But in my opinion, this is not a useful mental model regarding unsafe code,
-and I prefer the mental model of “reference that manages its own lifetime”, which doesn’t imply uniqueness.
noalias, noslow⌗
There is one clear potential benefit from this box behaviour: ✨Optimizations✨. noalias doesn’t exist for fun, it’s something
+and I prefer the mental model of “reference that manages its own lifetime”, which doesn’t imply uniqueness.
But there are also crates on crates.io like aliasable that already
+provide an aliasable version of Box<T>, which is used by the self-referential type helper crate ouroboros.
+So if box stayed unique, people could also just pick up that crate as a dependency and use the aliasable box from there instead of
+having to write their own. Interestingly, this crate also provides a Vec<T>, even though Vec<T> can currently be aliased in practice and
+in the current version of stacked borrows. just fine, although it’s also not clear whether we want to keep it like this, but I
+don’t think this can reasonable be changed.
noalias, noslow⌗
There is one clear potential benefit from this box behaviour: ✨Optimizations✨. noalias doesn’t exist for fun, it’s something
that can bring clear performance wins (for noalias on &mut T, those were measureable). So the only question remains:
How much performance does noalias on Box<T> give us now, and how many potential performance improvements could we get in the
future? For the latter, there is no simple answer. For the former, there is. rustc has no performance improvements
-from being compiled with noalias on Box<T>.
I have not yet benchmarked ecosystem crates without box noalias and don’t have the capacity to do so right now, so I would be very
-grateful if anyone wanted to pick that up and report the results.
There are also crates on crates.io like aliasable that already
-provide an aliasable version of Box<T>, which is used by the self-referential type helper crate ouroboros.
a way forward⌗
Based on all of this, I do have a few solutions. First of all, I think that even if there might be some small performance regressions in ecosystem crates,
-the overall tradeoff goes against the current box behaviour. Unsafe code wants to use box, and it is reasonable to do so. Therefore I propose to completely
-remove all uniqueness from Box<T>, and treat it just like a *const T for the purposes of aliasing. This will make it more
-predictable for unsafe code, and comes at none or only a minor performance cost.
But this performance cost may be real, and especially the future optimization value can’t be certain. The current uniqueness guarantees of box
+from being compiled with noalias on Box<T>.
I have also benchmarked a few crates from the ecosystem with and without noalias on box, and the results
+were inconclusive. (At the time of writing, only regex-syntax, tokio, and syn have been benchmarked.) regex-syntax showed no changes. Tokio showed a few improvements without noalias
+which is very weird, so maybe the benchmarks aren’t really good or something else was going on. And syn tended towards minor regressions without noalias, but the benchmarks had high
+jitter so no real conclusion can be reached from this either, at least in my eyes, but I don’t have a lot of experience with benchmarks. Therefore, I would love for more people
+to benchmark more crates, especially if you have more experience with benchmarks.
a way forward⌗
Based on all of this, I do have a few solutions. First of all, I think that even if there might be some small performance regressions, they are not significant enough
+to justify boxes uniqueness. Unsafe code wants to use box, and it is reasonable to do so. Therefore I propose to completely remove all uniqueness from Box<T>, and treat it
+just like a *const T for the purposes of aliasing. This will make it more predictable for unsafe code, and is a step forward towards less magic from Box<T>.
But the performance cost may be real, and especially the future optimization value can’t be certain. The current uniqueness guarantees of box
are very strong, and still giving code an option to obtain these seems useful. One possibility would be for code to use a
&'static mut T that is unleaked for drop, but the semantics of this are still unclear.
If that is not possible, exposing std::ptr::Unique (with it getting boxes aliasing semantics) could be desirable. For this, all existing usages of Unique
-inside the standard library would have to be removed.
I guess what I am wishing for are some good and flexible raw pointer types. But that’s still in the stars…
For more information about this topic, see https://github.com/rust-lang/unsafe-code-guidelines/issues/326