Skip to content
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

Layout and behavior of enums with uninhabited fields in some variants #443

Open
RalfJung opened this issue Aug 8, 2023 · 0 comments
Open

Comments

@RalfJung
Copy link
Member

RalfJung commented Aug 8, 2023

This is about enums like the following:

enum E1 { A, B(!) }
enum E2 { A, B(!), C(i32, !) }

The first interesting point is that E1 actually will not get any space assigned for storing a discriminant, it has size 0. The algorithm that assigns discriminants entirely skips B. In Miri we had to make SetDiscriminant throw UB early if the requested variant to set is uninhabited, since otherwise we get ICEs later.

However, E2 has size 8, even though there is only a single valid variant and that variant has size 0. I think we currently always provide storage for all fields of all variants, even if they are uninhabited. This is useful because in theory it lets us compile E2::C(f(), panic!()) into something that does in-place initialization:

let val: E2;
val.C.0 = f();
panic!();
SetDiscriminant(val, C); // this would be UB but we don't get here

(AFAIK we currently don't actually do that, we introduce temporaries instead.)

For structs we have decided that we will always have storage for all fields, and this is unavoidable since safe code can partially initialize a struct. However, safe code cannot partially initialize an enum, so we could soundly decide that E2 has size 0. We have to decide between smaller enums and in-place initialization for arbitrary enums. (We can of course have small enums and then have an analysis that uses in-place initialization where possible -- but in generic MIR, it might not be possible to tell whether the variant we are about to initialize is inhabited.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant