Store static initializers in metadata instead of the MIR of statics. by oli-obk · Pull Request #116564 · rust-lang/rust

@rustbot rustbot added S-waiting-on-review

Status: Awaiting review from the assignee but also interested parties.

T-compiler

Relevant to the compiler team, which will review and decide on the PR/issue.

labels

Oct 9, 2023

bors added a commit to rust-lang-ci/rust that referenced this pull request

Oct 9, 2023
…, r=<try>

Store static initializers in metadata instead of the MIR of statics.

This means that adding generic statics would be even more difficult, as we can't evaluate statics from other crates anymore, but the subtle issues I have encountered make me think that having this be an explicit problem is better. Said issues are:

### Nested allocations of static items get duplicated

which leads to issues for statics like

```rust
static mut FOO: &mut u32 = &mut 42;
static mut BAR = unsafe { FOO };
```

getting different allocations, instead of referring to the same one. This is also true for non-static mut, but promotion makes `static FOO: &u32 = &42;` annoying to demo.

### The main allocation of a static gets duplicated across crates

```rust
// crate a

static mut FOO: Option<u32> = Some(42);

// crate b

static mut BAR: &mut u32 = unsafe {
    match &mut a::FOO {
        Some(x) => x,
        None => panic!(),
    }
};
```

## Why is this being done?

In order to ensure all crates see the same nested allocations (which is the last issue that needs fixing before we can stabilize [`const_mut_refs`](rust-lang#57349)), I am working on creating anonymous (from the Rust side, to LLVM it's like a regular static item) static items for the nested allocations in a static. If we evaluate the static item in a downstream crate again, we will end up duplicating its nested allocations (and in some cases, like the `match` case, even duplicate the main allocation).

RalfJung

@bors bors added S-waiting-on-review

Status: Awaiting review from the assignee but also interested parties.

and removed S-waiting-on-bors

Status: Waiting on bors to run and complete tests. Bors will change the label on completion.

labels

Feb 14, 2024

@amanjeev @oli-obk

@oli-obk

@oli-obk

@oli-obk

@oli-obk

…n of a static.

Instead we re-use the static's alloc id within the interpreter for its initializer to refer to the `Allocation` that only exists within the interpreter.

@bors bors added S-waiting-on-bors

Status: Waiting on bors to run and complete tests. Bors will change the label on completion.

and removed S-waiting-on-review

Status: Awaiting review from the assignee but also interested parties.

labels

Feb 15, 2024

@oli-obk oli-obk deleted the evaluated_static_in_metadata branch

February 15, 2024 12:37

@bors bors mentioned this pull request

Feb 15, 2024