Hacker News new | ask | show | jobs
by steveklabnik 1991 days ago
Also UnsafeCell’s purpose in life is to make sure noalias is removed where appropriate.
1 comments

Can you explain that more? Because the requirement I pasted about having unique aliases does come from the UnsafeCell documentation. My understanding is that &mut still needs to be a unique alias even when it comes from an UnsafeCell.
>My understanding is that &mut still needs to be a unique alias even when it comes from an UnsafeCell.

That is correct. steveklabnik was not talking about this.

UnsafeCell needs to prevent optimizations that reorder accesses to the `&mut` derived from its `*mut`. If reordering was allowed it could be possible that you write code that creates two `&mut` (or one `&mut` and one `&`) that appear to have distinct lifetimes (which ought to be well-defined) but are nevertheless reordered by the optimizer to overlap (which is aliasing, and thus UB).

It also needs to disable the assumption that a `&Foo` is immutable if `Foo` is `UnsafeCell` or an aggregate that transitively contains `UnsafeCell`.

This special behavior is why UnsafeCell is a lang item.

Yes, the latter was what I was thinking of:

  use std::cell::UnsafeCell;

  pub fn no_unTsafecell(x: &i32) {
    
  }

  pub fn unsafecell(x: &UnsafeCell<i32>) {
    
  }
gives

  define void @_ZN10playground14no_unTsafecell17hd5b10dbf031749b4E(i32* noalias nocapture readonly align 4 dereferenceable(4) %x) unnamed_addr #0 {

  define void @_ZN10playground10unsafecell17h3318292255a4201bE(i32* nocapture align 4 dereferenceable(4) %x) unnamed_addr #0 {
thanks :)
Does it also help that the code doesn't actually cast the raw pointer to references? It only uses the read and write methods.
No. The write method also internally creates a borrow from the pointer.