authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2023-08-21 14:27:34-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2023-08-22 13:54:14-07:00
logada0010471163a3accca8976185fbb6bb59c914f
treed5035071ea3cb73677e381c0052e137fded064ac
parent6a5463951f0aa11cbdd5575cc78e85cd2ed10b46

compiler: move unions into InternPool

There are a couple concepts here worth understanding: Key.UnionType - This type is available *before* resolving the union's fields. The enum tag type, number of fields, and field names, field types, and field alignments are not available with this. InternPool.UnionType - This one can be obtained from the above type with `InternPool.loadUnionType` which asserts that the union's enum tag type has been resolved. This one has all the information available. Additionally: * ZIR: Turn an unused bit into `any_aligned_fields` flag to help semantic analysis know whether a union has explicit alignment on any fields (usually not). * Sema: delete `resolveTypeRequiresComptime` which had the same type signature and near-duplicate logic to `typeRequiresComptime`. - Make opaque types not report comptime-only (this was inconsistent between the two implementations of this function). * Implement accepted proposal #12556 which is a breaking change.

27 files changed, 1396 insertions(+), 1358 deletions(-)

lib/std/dwarf/call_frame.zig+7-7
......@@ -69,16 +69,9 @@ pub const Instruction = union(Opcode) {
6969 register: u8,
7070 offset: u64,
7171 },
72 offset_extended: struct {
73 register: u8,
74 offset: u64,
75 },
7672 restore: struct {
7773 register: u8,
7874 },
79 restore_extended: struct {
80 register: u8,
81 },
8275 nop: void,
8376 set_loc: struct {
8477 address: u64,
......@@ -92,6 +85,13 @@ pub const Instruction = union(Opcode) {
9285 advance_loc4: struct {
9386 delta: u32,
9487 },
88 offset_extended: struct {
89 register: u8,
90 offset: u64,
91 },
92 restore_extended: struct {
93 register: u8,
94 },
9595 undefined: struct {
9696 register: u8,
9797 },
lib/std/meta.zig+2-2
......@@ -614,9 +614,9 @@ test "std.meta.FieldEnum" {
614614 const Tagged = union(enum) { a: u8, b: void, c: f32 };
615615 try testing.expectEqual(Tag(Tagged), FieldEnum(Tagged));
616616
617 const Tag2 = enum { b, c, a };
617 const Tag2 = enum { a, b, c };
618618 const Tagged2 = union(Tag2) { a: u8, b: void, c: f32 };
619 try testing.expect(Tag(Tagged2) != FieldEnum(Tagged2));
619 try testing.expect(Tag(Tagged2) == FieldEnum(Tagged2));
620620
621621 const Tag3 = enum(u8) { a, b, c = 7 };
622622 const Tagged3 = union(Tag3) { a: u8, b: void, c: f32 };
src/AstGen.zig+5
......@@ -4696,6 +4696,7 @@ fn unionDeclInner(
46964696
46974697 const bits_per_field = 4;
46984698 const max_field_size = 5;
4699 var any_aligned_fields = false;
46994700 var wip_members = try WipMembers.init(gpa, &astgen.scratch, decl_count, field_count, bits_per_field, max_field_size);
47004701 defer wip_members.deinit();
47014702
......@@ -4733,6 +4734,7 @@ fn unionDeclInner(
47334734 if (have_align) {
47344735 const align_inst = try expr(&block_scope, &block_scope.base, .{ .rl = .{ .ty = .u32_type } }, member.ast.align_expr);
47354736 wip_members.appendToField(@intFromEnum(align_inst));
4737 any_aligned_fields = true;
47364738 }
47374739 if (have_value) {
47384740 if (arg_inst == .none) {
......@@ -4783,6 +4785,7 @@ fn unionDeclInner(
47834785 .fields_len = field_count,
47844786 .decls_len = decl_count,
47854787 .auto_enum_tag = auto_enum_tok != null,
4788 .any_aligned_fields = any_aligned_fields,
47864789 });
47874790
47884791 wip_members.finishBits(bits_per_field);
......@@ -11754,6 +11757,7 @@ const GenZir = struct {
1175411757 decls_len: u32,
1175511758 layout: std.builtin.Type.ContainerLayout,
1175611759 auto_enum_tag: bool,
11760 any_aligned_fields: bool,
1175711761 }) !void {
1175811762 const astgen = gz.astgen;
1175911763 const gpa = astgen.gpa;
......@@ -11790,6 +11794,7 @@ const GenZir = struct {
1179011794 .name_strategy = gz.anon_name_strategy,
1179111795 .layout = args.layout,
1179211796 .auto_enum_tag = args.auto_enum_tag,
11797 .any_aligned_fields = args.any_aligned_fields,
1179311798 }),
1179411799 .operand = payload_index,
1179511800 } },
src/InternPool.zig+385-125
......@@ -46,13 +46,6 @@ allocated_structs: std.SegmentedList(Module.Struct, 0) = .{},
4646/// When a Struct object is freed from `allocated_structs`, it is pushed into this stack.
4747structs_free_list: std.ArrayListUnmanaged(Module.Struct.Index) = .{},
4848
49/// Union objects are stored in this data structure because:
50/// * They contain pointers such as the field maps.
51/// * They need to be mutated after creation.
52allocated_unions: std.SegmentedList(Module.Union, 0) = .{},
53/// When a Union object is freed from `allocated_unions`, it is pushed into this stack.
54unions_free_list: std.ArrayListUnmanaged(Module.Union.Index) = .{},
55
5649/// Some types such as enums, structs, and unions need to store mappings from field names
5750/// to field index, or value to field index. In such cases, they will store the underlying
5851/// field names and values directly, relying on one of these maps, stored separately,
......@@ -241,7 +234,7 @@ pub const Key = union(enum) {
241234 /// declaration. It is used for types that have no `struct` keyword in the
242235 /// source code, and were not created via `@Type`.
243236 anon_struct_type: AnonStructType,
244 union_type: UnionType,
237 union_type: Key.UnionType,
245238 opaque_type: OpaqueType,
246239 enum_type: EnumType,
247240 func_type: FuncType,
......@@ -391,17 +384,72 @@ pub const Key = union(enum) {
391384 }
392385 };
393386
387 /// Serves two purposes:
388 /// * Being the key in the InternPool hash map, which only requires the `decl` field.
389 /// * Provide the other fields that do not require chasing the enum type.
394390 pub const UnionType = struct {
395 index: Module.Union.Index,
396 runtime_tag: RuntimeTag,
391 /// The Decl that corresponds to the union itself.
392 decl: Module.Decl.Index,
393 /// The index of the `Tag.TypeUnion` payload. Ignored by `get`,
394 /// populated by `indexToKey`.
395 extra_index: u32,
396 namespace: Module.Namespace.Index,
397 flags: Tag.TypeUnion.Flags,
398 /// The enum that provides the list of field names and values.
399 enum_tag_ty: Index,
400 zir_index: Zir.Inst.Index,
401
402 /// The returned pointer expires with any addition to the `InternPool`.
403 pub fn flagsPtr(self: @This(), ip: *const InternPool) *Tag.TypeUnion.Flags {
404 const flags_field_index = std.meta.fieldIndex(Tag.TypeUnion, "flags").?;
405 return @ptrCast(&ip.extra.items[self.extra_index + flags_field_index]);
406 }
397407
398 pub const RuntimeTag = enum { none, safety, tagged };
408 pub fn haveFieldTypes(self: @This(), ip: *const InternPool) bool {
409 return self.flagsPtr(ip).status.haveFieldTypes();
410 }
399411
400 pub fn hasTag(self: UnionType) bool {
401 return switch (self.runtime_tag) {
402 .none => false,
403 .tagged, .safety => true,
404 };
412 pub fn hasTag(self: @This(), ip: *const InternPool) bool {
413 return self.flagsPtr(ip).runtime_tag.hasTag();
414 }
415
416 pub fn getLayout(self: @This(), ip: *const InternPool) std.builtin.Type.ContainerLayout {
417 return self.flagsPtr(ip).layout;
418 }
419
420 pub fn haveLayout(self: @This(), ip: *const InternPool) bool {
421 return self.flagsPtr(ip).status.haveLayout();
422 }
423
424 /// Pointer to an enum type which is used for the tag of the union.
425 /// This type is created even for untagged unions, even when the memory
426 /// layout does not store the tag.
427 /// Whether zig chooses this type or the user specifies it, it is stored here.
428 /// This will be set to the null type until status is `have_field_types`.
429 /// This accessor is provided so that the tag type can be mutated, and so that
430 /// when it is mutated, the mutations are observed.
431 /// The returned pointer is invalidated when something is added to the `InternPool`.
432 pub fn tagTypePtr(self: @This(), ip: *const InternPool) *Index {
433 const tag_ty_field_index = std.meta.fieldIndex(Tag.TypeUnion, "tag_ty").?;
434 return @ptrCast(&ip.extra.items[self.extra_index + tag_ty_field_index]);
435 }
436
437 pub fn setFieldTypes(self: @This(), ip: *InternPool, types: []const Index) void {
438 @memcpy((Index.Slice{
439 .start = @intCast(self.extra_index + @typeInfo(Tag.TypeUnion).Struct.fields.len),
440 .len = @intCast(types.len),
441 }).get(ip), types);
442 }
443
444 pub fn setFieldAligns(self: @This(), ip: *InternPool, aligns: []const Alignment) void {
445 if (aligns.len == 0) return;
446 assert(self.flagsPtr(ip).any_aligned_fields);
447 @memcpy((Alignment.Slice{
448 .start = @intCast(
449 self.extra_index + @typeInfo(Tag.TypeUnion).Struct.fields.len + aligns.len,
450 ),
451 .len = @intCast(aligns.len),
452 }).get(ip), aligns);
405453 }
406454 };
407455
......@@ -833,7 +881,6 @@ pub const Key = union(enum) {
833881 => |x| Hash.hash(seed, asBytes(&x)),
834882
835883 .int_type => |x| Hash.hash(seed + @intFromEnum(x.signedness), asBytes(&x.bits)),
836 .union_type => |x| Hash.hash(seed + @intFromEnum(x.runtime_tag), asBytes(&x.index)),
837884
838885 .error_union => |x| switch (x.val) {
839886 .err_name => |y| Hash.hash(seed + 0, asBytes(&x.ty) ++ asBytes(&y)),
......@@ -845,6 +892,7 @@ pub const Key = union(enum) {
845892 inline .opaque_type,
846893 .enum_type,
847894 .variable,
895 .union_type,
848896 => |x| Hash.hash(seed, asBytes(&x.decl)),
849897
850898 .int => |int| {
......@@ -1079,10 +1127,6 @@ pub const Key = union(enum) {
10791127 const b_info = b.struct_type;
10801128 return std.meta.eql(a_info, b_info);
10811129 },
1082 .union_type => |a_info| {
1083 const b_info = b.union_type;
1084 return std.meta.eql(a_info, b_info);
1085 },
10861130 .un => |a_info| {
10871131 const b_info = b.un;
10881132 return std.meta.eql(a_info, b_info);
......@@ -1250,6 +1294,10 @@ pub const Key = union(enum) {
12501294 const b_info = b.enum_type;
12511295 return a_info.decl == b_info.decl;
12521296 },
1297 .union_type => |a_info| {
1298 const b_info = b.union_type;
1299 return a_info.decl == b_info.decl;
1300 },
12531301 .aggregate => |a_info| {
12541302 const b_info = b.aggregate;
12551303 if (a_info.ty != b_info.ty) return false;
......@@ -1385,6 +1433,158 @@ pub const Key = union(enum) {
13851433 }
13861434};
13871435
1436// Unlike `Tag.TypeUnion` which is an encoding, and `Key.UnionType` which is a
1437// minimal hashmap key, this type is a convenience type that contains info
1438// needed by semantic analysis.
1439pub const UnionType = struct {
1440 /// The Decl that corresponds to the union itself.
1441 decl: Module.Decl.Index,
1442 /// Represents the declarations inside this union.
1443 namespace: Module.Namespace.Index,
1444 /// The enum tag type.
1445 enum_tag_ty: Index,
1446 /// The integer tag type of the enum.
1447 int_tag_ty: Index,
1448 /// List of field names in declaration order.
1449 field_names: NullTerminatedString.Slice,
1450 /// List of field types in declaration order.
1451 /// These are `none` until `status` is `have_field_types` or `have_layout`.
1452 field_types: Index.Slice,
1453 /// List of field alignments in declaration order.
1454 /// `none` means the ABI alignment of the type.
1455 /// If this slice has length 0 it means all elements are `none`.
1456 field_aligns: Alignment.Slice,
1457 /// Index of the union_decl ZIR instruction.
1458 zir_index: Zir.Inst.Index,
1459 /// Index into extra array of the `flags` field.
1460 flags_index: u32,
1461 /// Copied from `enum_tag_ty`.
1462 names_map: OptionalMapIndex,
1463
1464 pub const RuntimeTag = enum(u2) {
1465 none,
1466 safety,
1467 tagged,
1468
1469 pub fn hasTag(self: RuntimeTag) bool {
1470 return switch (self) {
1471 .none => false,
1472 .tagged, .safety => true,
1473 };
1474 }
1475 };
1476
1477 pub const RequiresComptime = enum(u2) { no, yes, unknown, wip };
1478
1479 pub const Status = enum(u3) {
1480 none,
1481 field_types_wip,
1482 have_field_types,
1483 layout_wip,
1484 have_layout,
1485 fully_resolved_wip,
1486 /// The types and all its fields have had their layout resolved.
1487 /// Even through pointer, which `have_layout` does not ensure.
1488 fully_resolved,
1489
1490 pub fn haveFieldTypes(status: Status) bool {
1491 return switch (status) {
1492 .none,
1493 .field_types_wip,
1494 => false,
1495 .have_field_types,
1496 .layout_wip,
1497 .have_layout,
1498 .fully_resolved_wip,
1499 .fully_resolved,
1500 => true,
1501 };
1502 }
1503
1504 pub fn haveLayout(status: Status) bool {
1505 return switch (status) {
1506 .none,
1507 .field_types_wip,
1508 .have_field_types,
1509 .layout_wip,
1510 => false,
1511 .have_layout,
1512 .fully_resolved_wip,
1513 .fully_resolved,
1514 => true,
1515 };
1516 }
1517 };
1518
1519 /// The returned pointer expires with any addition to the `InternPool`.
1520 pub fn flagsPtr(self: UnionType, ip: *const InternPool) *Tag.TypeUnion.Flags {
1521 return @ptrCast(&ip.extra.items[self.flags_index]);
1522 }
1523
1524 /// Look up field index based on field name.
1525 pub fn nameIndex(self: UnionType, ip: *const InternPool, name: NullTerminatedString) ?u32 {
1526 const map = &ip.maps.items[@intFromEnum(self.names_map.unwrap().?)];
1527 const adapter: NullTerminatedString.Adapter = .{ .strings = self.field_names.get(ip) };
1528 const field_index = map.getIndexAdapted(name, adapter) orelse return null;
1529 return @intCast(field_index);
1530 }
1531
1532 pub fn hasTag(self: UnionType, ip: *const InternPool) bool {
1533 return self.flagsPtr(ip).runtime_tag.hasTag();
1534 }
1535
1536 pub fn haveLayout(self: UnionType, ip: *const InternPool) bool {
1537 return self.flagsPtr(ip).status.haveLayout();
1538 }
1539
1540 pub fn getLayout(self: UnionType, ip: *const InternPool) std.builtin.Type.ContainerLayout {
1541 return self.flagsPtr(ip).layout;
1542 }
1543
1544 pub fn fieldAlign(self: UnionType, ip: *const InternPool, field_index: u32) Alignment {
1545 if (self.field_aligns.len == 0) return .none;
1546 return self.field_aligns.get(ip)[field_index];
1547 }
1548
1549 /// This does not mutate the field of UnionType.
1550 pub fn setZirIndex(self: @This(), ip: *InternPool, new_zir_index: Zir.Inst.Index) void {
1551 const flags_field_index = std.meta.fieldIndex(Tag.TypeUnion, "flags").?;
1552 const zir_index_field_index = std.meta.fieldIndex(Tag.TypeUnion, "zir_index").?;
1553 const ptr: *Zir.Inst.Index =
1554 @ptrCast(&ip.extra.items[self.flags_index - flags_field_index + zir_index_field_index]);
1555 ptr.* = new_zir_index;
1556 }
1557};
1558
1559/// Fetch all the interesting fields of a union type into a convenient data
1560/// structure.
1561/// This asserts that the union's enum tag type has been resolved.
1562pub fn loadUnionType(ip: *InternPool, key: Key.UnionType) UnionType {
1563 const type_union = ip.extraDataTrail(Tag.TypeUnion, key.extra_index);
1564 const enum_ty = type_union.data.tag_ty;
1565 const enum_info = ip.indexToKey(enum_ty).enum_type;
1566 const fields_len: u32 = @intCast(enum_info.names.len);
1567
1568 return .{
1569 .decl = type_union.data.decl,
1570 .namespace = type_union.data.namespace,
1571 .enum_tag_ty = enum_ty,
1572 .int_tag_ty = enum_info.tag_ty,
1573 .field_names = enum_info.names,
1574 .names_map = enum_info.names_map,
1575 .field_types = .{
1576 .start = type_union.end,
1577 .len = fields_len,
1578 },
1579 .field_aligns = .{
1580 .start = type_union.end + fields_len,
1581 .len = if (type_union.data.flags.any_aligned_fields) fields_len else 0,
1582 },
1583 .zir_index = type_union.data.zir_index,
1584 .flags_index = key.extra_index + std.meta.fieldIndex(Tag.TypeUnion, "flags").?,
1585 };
1586}
1587
13881588pub const Item = struct {
13891589 tag: Tag,
13901590 /// The doc comments on the respective Tag explain how to interpret this.
......@@ -1618,9 +1818,7 @@ pub const Index = enum(u32) {
16181818 type_struct_ns: struct { data: Module.Namespace.Index },
16191819 type_struct_anon: DataIsExtraIndexOfTypeStructAnon,
16201820 type_tuple_anon: DataIsExtraIndexOfTypeStructAnon,
1621 type_union_tagged: struct { data: Module.Union.Index },
1622 type_union_untagged: struct { data: Module.Union.Index },
1623 type_union_safety: struct { data: Module.Union.Index },
1821 type_union: struct { data: *Tag.TypeUnion },
16241822 type_function: struct {
16251823 const @"data.flags.has_comptime_bits" = opaque {};
16261824 const @"data.flags.has_noalias_bits" = opaque {};
......@@ -2057,15 +2255,9 @@ pub const Tag = enum(u8) {
20572255 /// An AnonStructType which has only types and values for fields.
20582256 /// data is extra index of `TypeStructAnon`.
20592257 type_tuple_anon,
2060 /// A tagged union type.
2061 /// `data` is `Module.Union.Index`.
2062 type_union_tagged,
2063 /// An untagged union type. It also has no safety tag.
2064 /// `data` is `Module.Union.Index`.
2065 type_union_untagged,
2066 /// An untagged union type which has a safety tag.
2067 /// `data` is `Module.Union.Index`.
2068 type_union_safety,
2258 /// A union type.
2259 /// `data` is extra index of `TypeUnion`.
2260 type_union,
20692261 /// A function body type.
20702262 /// `data` is extra index to `TypeFunction`.
20712263 type_function,
......@@ -2273,9 +2465,7 @@ pub const Tag = enum(u8) {
22732465 .type_struct_ns => unreachable,
22742466 .type_struct_anon => TypeStructAnon,
22752467 .type_tuple_anon => TypeStructAnon,
2276 .type_union_tagged => unreachable,
2277 .type_union_untagged => unreachable,
2278 .type_union_safety => unreachable,
2468 .type_union => TypeUnion,
22792469 .type_function => TypeFunction,
22802470
22812471 .undef => unreachable,
......@@ -2425,6 +2615,30 @@ pub const Tag = enum(u8) {
24252615 _: u9 = 0,
24262616 };
24272617 };
2618
2619 /// The number of fields is provided by the `tag_ty` field.
2620 /// Trailing:
2621 /// 0. field type: Index for each field; declaration order
2622 /// 1. field align: Alignment for each field; declaration order
2623 pub const TypeUnion = struct {
2624 flags: Flags,
2625 decl: Module.Decl.Index,
2626 namespace: Module.Namespace.Index,
2627 /// The enum that provides the list of field names and values.
2628 tag_ty: Index,
2629 zir_index: Zir.Inst.Index,
2630
2631 pub const Flags = packed struct(u32) {
2632 runtime_tag: UnionType.RuntimeTag,
2633 /// If false, the field alignment trailing data is omitted.
2634 any_aligned_fields: bool,
2635 layout: std.builtin.Type.ContainerLayout,
2636 status: UnionType.Status,
2637 requires_comptime: UnionType.RequiresComptime,
2638 assumed_runtime_bits: bool,
2639 _: u21 = 0,
2640 };
2641 };
24282642};
24292643
24302644/// State that is mutable during semantic analysis. This data is not used for
......@@ -2582,6 +2796,21 @@ pub const Alignment = enum(u6) {
25822796 assert(lhs != .none and rhs != .none);
25832797 return std.math.order(@intFromEnum(lhs), @intFromEnum(rhs));
25842798 }
2799
2800 /// An array of `Alignment` objects existing within the `extra` array.
2801 /// This type exists to provide a struct with lifetime that is
2802 /// not invalidated when items are added to the `InternPool`.
2803 pub const Slice = struct {
2804 start: u32,
2805 len: u32,
2806
2807 pub fn get(slice: Slice, ip: *const InternPool) []Alignment {
2808 // TODO: implement @ptrCast between slices changing the length
2809 //const bytes: []u8 = @ptrCast(ip.extra.items[slice.start..]);
2810 const bytes: []u8 = std.mem.sliceAsBytes(ip.extra.items[slice.start..]);
2811 return @ptrCast(bytes[0..slice.len]);
2812 }
2813 };
25852814};
25862815
25872816/// Used for non-sentineled arrays that have length fitting in u32, as well as
......@@ -2829,9 +3058,6 @@ pub fn deinit(ip: *InternPool, gpa: Allocator) void {
28293058 ip.structs_free_list.deinit(gpa);
28303059 ip.allocated_structs.deinit(gpa);
28313060
2832 ip.unions_free_list.deinit(gpa);
2833 ip.allocated_unions.deinit(gpa);
2834
28353061 ip.decls_free_list.deinit(gpa);
28363062 ip.allocated_decls.deinit(gpa);
28373063
......@@ -2953,18 +3179,7 @@ pub fn indexToKey(ip: *const InternPool, index: Index) Key {
29533179 } };
29543180 },
29553181
2956 .type_union_untagged => .{ .union_type = .{
2957 .index = @as(Module.Union.Index, @enumFromInt(data)),
2958 .runtime_tag = .none,
2959 } },
2960 .type_union_tagged => .{ .union_type = .{
2961 .index = @as(Module.Union.Index, @enumFromInt(data)),
2962 .runtime_tag = .tagged,
2963 } },
2964 .type_union_safety => .{ .union_type = .{
2965 .index = @as(Module.Union.Index, @enumFromInt(data)),
2966 .runtime_tag = .safety,
2967 } },
3182 .type_union => .{ .union_type = extraUnionType(ip, data) },
29683183
29693184 .type_enum_auto => {
29703185 const enum_auto = ip.extraDataTrail(EnumAuto, data);
......@@ -3279,9 +3494,7 @@ pub fn indexToKey(ip: *const InternPool, index: Index) Key {
32793494
32803495 .type_enum_auto,
32813496 .type_enum_explicit,
3282 .type_union_tagged,
3283 .type_union_untagged,
3284 .type_union_safety,
3497 .type_union,
32853498 => .{ .empty_enum_value = ty },
32863499
32873500 else => unreachable,
......@@ -3352,6 +3565,18 @@ fn extraErrorSet(ip: *const InternPool, extra_index: u32) Key.ErrorSetType {
33523565 };
33533566}
33543567
3568fn extraUnionType(ip: *const InternPool, extra_index: u32) Key.UnionType {
3569 const type_union = ip.extraData(Tag.TypeUnion, extra_index);
3570 return .{
3571 .decl = type_union.decl,
3572 .namespace = type_union.namespace,
3573 .flags = type_union.flags,
3574 .enum_tag_ty = type_union.tag_ty,
3575 .zir_index = type_union.zir_index,
3576 .extra_index = extra_index,
3577 };
3578}
3579
33553580fn extraFuncType(ip: *const InternPool, extra_index: u32) Key.FuncType {
33563581 const type_function = ip.extraDataTrail(Tag.TypeFunction, extra_index);
33573582 var index: usize = type_function.end;
......@@ -3678,16 +3903,7 @@ pub fn get(ip: *InternPool, gpa: Allocator, key: Key) Allocator.Error!Index {
36783903 return @enumFromInt(ip.items.len - 1);
36793904 },
36803905
3681 .union_type => |union_type| {
3682 ip.items.appendAssumeCapacity(.{
3683 .tag = switch (union_type.runtime_tag) {
3684 .none => .type_union_untagged,
3685 .safety => .type_union_safety,
3686 .tagged => .type_union_tagged,
3687 },
3688 .data = @intFromEnum(union_type.index),
3689 });
3690 },
3906 .union_type => unreachable, // use getUnionType() instead
36913907
36923908 .opaque_type => |opaque_type| {
36933909 ip.items.appendAssumeCapacity(.{
......@@ -3791,9 +4007,10 @@ pub fn get(ip: *InternPool, gpa: Allocator, key: Key) Allocator.Error!Index {
37914007 assert(ptr.addr == .field);
37924008 assert(base_index.index < ip.structPtrUnwrapConst(struct_type.index).?.fields.count());
37934009 },
3794 .union_type => |union_type| {
4010 .union_type => |union_key| {
4011 const union_type = ip.loadUnionType(union_key);
37954012 assert(ptr.addr == .field);
3796 assert(base_index.index < ip.unionPtrConst(union_type.index).fields.count());
4013 assert(base_index.index < union_type.field_names.len);
37974014 },
37984015 .ptr_type => |slice_type| {
37994016 assert(ptr.addr == .field);
......@@ -4359,6 +4576,76 @@ pub fn get(ip: *InternPool, gpa: Allocator, key: Key) Allocator.Error!Index {
43594576 return @enumFromInt(ip.items.len - 1);
43604577}
43614578
4579pub const UnionTypeInit = struct {
4580 flags: Tag.TypeUnion.Flags,
4581 decl: Module.Decl.Index,
4582 namespace: Module.Namespace.Index,
4583 zir_index: Zir.Inst.Index,
4584 fields_len: u32,
4585 enum_tag_ty: Index,
4586 /// May have length 0 which leaves the values unset until later.
4587 field_types: []const Index,
4588 /// May have length 0 which leaves the values unset until later.
4589 /// The logic for `any_aligned_fields` is asserted to have been done before
4590 /// calling this function.
4591 field_aligns: []const Alignment,
4592};
4593
4594pub fn getUnionType(ip: *InternPool, gpa: Allocator, ini: UnionTypeInit) Allocator.Error!Index {
4595 const prev_extra_len = ip.extra.items.len;
4596 const align_elements_len = if (ini.flags.any_aligned_fields) (ini.fields_len + 3) / 4 else 0;
4597 const align_element: u32 = @bitCast([1]u8{@intFromEnum(Alignment.none)} ** 4);
4598 try ip.extra.ensureUnusedCapacity(gpa, @typeInfo(Tag.TypeUnion).Struct.fields.len +
4599 ini.fields_len + // field types
4600 align_elements_len);
4601 try ip.items.ensureUnusedCapacity(gpa, 1);
4602
4603 const union_type_extra_index = ip.addExtraAssumeCapacity(Tag.TypeUnion{
4604 .flags = ini.flags,
4605 .decl = ini.decl,
4606 .namespace = ini.namespace,
4607 .tag_ty = ini.enum_tag_ty,
4608 .zir_index = ini.zir_index,
4609 });
4610
4611 // field types
4612 if (ini.field_types.len > 0) {
4613 assert(ini.field_types.len == ini.fields_len);
4614 ip.extra.appendSliceAssumeCapacity(@ptrCast(ini.field_types));
4615 } else {
4616 ip.extra.appendNTimesAssumeCapacity(@intFromEnum(Index.none), ini.fields_len);
4617 }
4618
4619 // field alignments
4620 if (ini.flags.any_aligned_fields) {
4621 ip.extra.appendNTimesAssumeCapacity(align_element, align_elements_len);
4622 if (ini.field_aligns.len > 0) {
4623 assert(ini.field_aligns.len == ini.fields_len);
4624 @memcpy((Alignment.Slice{
4625 .start = @intCast(ip.extra.items.len - align_elements_len),
4626 .len = @intCast(ini.field_aligns.len),
4627 }).get(ip), ini.field_aligns);
4628 }
4629 } else {
4630 assert(ini.field_aligns.len == 0);
4631 }
4632
4633 const adapter: KeyAdapter = .{ .intern_pool = ip };
4634 const gop = try ip.map.getOrPutAdapted(gpa, Key{
4635 .union_type = extraUnionType(ip, union_type_extra_index),
4636 }, adapter);
4637 if (gop.found_existing) {
4638 ip.extra.items.len = prev_extra_len;
4639 return @enumFromInt(gop.index);
4640 }
4641
4642 ip.items.appendAssumeCapacity(.{
4643 .tag = .type_union,
4644 .data = union_type_extra_index,
4645 });
4646 return @enumFromInt(ip.items.len - 1);
4647}
4648
43624649/// This is equivalent to `Key.FuncType` but adjusted to have a slice for `param_types`.
43634650pub const GetFuncTypeKey = struct {
43644651 param_types: []Index,
......@@ -5310,6 +5597,7 @@ fn addExtraAssumeCapacity(ip: *InternPool, extra: anytype) u32 {
53105597 Tag.TypeFunction.Flags,
53115598 Tag.TypePointer.PackedOffset,
53125599 Tag.Variable.Flags,
5600 Tag.TypeUnion.Flags,
53135601 => @bitCast(@field(extra, field.name)),
53145602
53155603 else => @compileError("bad field type: " ++ @typeName(field.type)),
......@@ -5380,6 +5668,7 @@ fn extraDataTrail(ip: *const InternPool, comptime T: type, index: usize) struct
53805668 Tag.TypePointer.Flags,
53815669 Tag.TypeFunction.Flags,
53825670 Tag.TypePointer.PackedOffset,
5671 Tag.TypeUnion.Flags,
53835672 Tag.Variable.Flags,
53845673 FuncAnalysis,
53855674 => @bitCast(int32),
......@@ -5893,7 +6182,7 @@ pub fn indexToUnionType(ip: *const InternPool, val: Index) Module.Union.Optional
58936182 assert(val != .none);
58946183 const tags = ip.items.items(.tag);
58956184 switch (tags[@intFromEnum(val)]) {
5896 .type_union_tagged, .type_union_untagged, .type_union_safety => {},
6185 .type_union => {},
58976186 else => return .none,
58986187 }
58996188 const datas = ip.items.items(.data);
......@@ -5946,6 +6235,10 @@ pub fn isEnumType(ip: *const InternPool, ty: Index) bool {
59466235 };
59476236}
59486237
6238pub fn isUnion(ip: *const InternPool, ty: Index) bool {
6239 return ip.indexToKey(ty) == .union_type;
6240}
6241
59496242pub fn isFunctionType(ip: *const InternPool, ty: Index) bool {
59506243 return ip.indexToKey(ty) == .func_type;
59516244}
......@@ -6010,13 +6303,11 @@ fn dumpStatsFallible(ip: *const InternPool, arena: Allocator) anyerror!void {
60106303 const limbs_size = 8 * ip.limbs.items.len;
60116304 // TODO: fields size is not taken into account
60126305 const structs_size = ip.allocated_structs.len *
6013 (@sizeOf(Module.Struct) + @sizeOf(Module.Namespace) + @sizeOf(Module.Decl));
6014 const unions_size = ip.allocated_unions.len *
6015 (@sizeOf(Module.Union) + @sizeOf(Module.Namespace) + @sizeOf(Module.Decl));
6306 (@sizeOf(Module.Struct) + @sizeOf(Module.Namespace));
6307 const decls_size = ip.allocated_decls.len * @sizeOf(Module.Decl);
60166308
60176309 // TODO: map overhead size is not taken into account
6018 const total_size = @sizeOf(InternPool) + items_size + extra_size + limbs_size +
6019 structs_size + unions_size;
6310 const total_size = @sizeOf(InternPool) + items_size + extra_size + limbs_size + structs_size + decls_size;
60206311
60216312 std.debug.print(
60226313 \\InternPool size: {d} bytes
......@@ -6024,7 +6315,7 @@ fn dumpStatsFallible(ip: *const InternPool, arena: Allocator) anyerror!void {
60246315 \\ {d} extra: {d} bytes
60256316 \\ {d} limbs: {d} bytes
60266317 \\ {d} structs: {d} bytes
6027 \\ {d} unions: {d} bytes
6318 \\ {d} decls: {d} bytes
60286319 \\
60296320 , .{
60306321 total_size,
......@@ -6036,8 +6327,8 @@ fn dumpStatsFallible(ip: *const InternPool, arena: Allocator) anyerror!void {
60366327 limbs_size,
60376328 ip.allocated_structs.len,
60386329 structs_size,
6039 ip.allocated_unions.len,
6040 unions_size,
6330 ip.allocated_decls.len,
6331 decls_size,
60416332 });
60426333
60436334 const tags = ip.items.items(.tag);
......@@ -6076,7 +6367,6 @@ fn dumpStatsFallible(ip: *const InternPool, arena: Allocator) anyerror!void {
60766367 const struct_obj = ip.structPtrConst(struct_index);
60776368 break :b @sizeOf(Module.Struct) +
60786369 @sizeOf(Module.Namespace) +
6079 @sizeOf(Module.Decl) +
60806370 (struct_obj.fields.count() * @sizeOf(Module.Struct.Field));
60816371 },
60826372 .type_struct_ns => @sizeOf(Module.Namespace),
......@@ -6089,10 +6379,18 @@ fn dumpStatsFallible(ip: *const InternPool, arena: Allocator) anyerror!void {
60896379 break :b @sizeOf(TypeStructAnon) + (@sizeOf(u32) * 2 * info.fields_len);
60906380 },
60916381
6092 .type_union_tagged,
6093 .type_union_untagged,
6094 .type_union_safety,
6095 => @sizeOf(Module.Union) + @sizeOf(Module.Namespace) + @sizeOf(Module.Decl),
6382 .type_union => b: {
6383 const info = ip.extraData(Tag.TypeUnion, data);
6384 const enum_info = ip.indexToKey(info.tag_ty).enum_type;
6385 const fields_len: u32 = @intCast(enum_info.names.len);
6386 const per_field = @sizeOf(u32); // field type
6387 // 1 byte per field for alignment, rounded up to the nearest 4 bytes
6388 const alignments = if (info.flags.any_aligned_fields)
6389 ((fields_len + 3) / 4) * 4
6390 else
6391 0;
6392 break :b @sizeOf(Tag.TypeUnion) + (fields_len * per_field) + alignments;
6393 },
60966394
60976395 .type_function => b: {
60986396 const info = ip.extraData(Tag.TypeFunction, data);
......@@ -6161,15 +6459,14 @@ fn dumpStatsFallible(ip: *const InternPool, arena: Allocator) anyerror!void {
61616459 .float_c_longdouble_f80 => @sizeOf(Float80),
61626460 .float_c_longdouble_f128 => @sizeOf(Float128),
61636461 .float_comptime_float => @sizeOf(Float128),
6164 .variable => @sizeOf(Tag.Variable) + @sizeOf(Module.Decl),
6165 .extern_func => @sizeOf(Tag.ExternFunc) + @sizeOf(Module.Decl),
6166 .func_decl => @sizeOf(Tag.FuncDecl) + @sizeOf(Module.Decl),
6462 .variable => @sizeOf(Tag.Variable),
6463 .extern_func => @sizeOf(Tag.ExternFunc),
6464 .func_decl => @sizeOf(Tag.FuncDecl),
61676465 .func_instance => b: {
61686466 const info = ip.extraData(Tag.FuncInstance, data);
61696467 const ty = ip.typeOf(info.generic_owner);
61706468 const params_len = ip.indexToKey(ty).func_type.param_types.len;
6171 break :b @sizeOf(Tag.FuncInstance) + @sizeOf(Index) * params_len +
6172 @sizeOf(Module.Decl);
6469 break :b @sizeOf(Tag.FuncInstance) + @sizeOf(Index) * params_len;
61736470 },
61746471 .func_coerced => @sizeOf(Tag.FuncCoerced),
61756472 .only_possible_value => 0,
......@@ -6230,9 +6527,7 @@ fn dumpAllFallible(ip: *const InternPool) anyerror!void {
62306527 .type_struct_ns,
62316528 .type_struct_anon,
62326529 .type_tuple_anon,
6233 .type_union_tagged,
6234 .type_union_untagged,
6235 .type_union_safety,
6530 .type_union,
62366531 .type_function,
62376532 .undef,
62386533 .runtime_value,
......@@ -6358,14 +6653,6 @@ pub fn structPtrUnwrapConst(ip: *const InternPool, index: Module.Struct.Optional
63586653 return structPtrConst(ip, index.unwrap() orelse return null);
63596654}
63606655
6361pub fn unionPtr(ip: *InternPool, index: Module.Union.Index) *Module.Union {
6362 return ip.allocated_unions.at(@intFromEnum(index));
6363}
6364
6365pub fn unionPtrConst(ip: *const InternPool, index: Module.Union.Index) *const Module.Union {
6366 return ip.allocated_unions.at(@intFromEnum(index));
6367}
6368
63696656pub fn declPtr(ip: *InternPool, index: Module.Decl.Index) *Module.Decl {
63706657 return ip.allocated_decls.at(@intFromEnum(index));
63716658}
......@@ -6400,28 +6687,6 @@ pub fn destroyStruct(ip: *InternPool, gpa: Allocator, index: Module.Struct.Index
64006687 };
64016688}
64026689
6403pub fn createUnion(
6404 ip: *InternPool,
6405 gpa: Allocator,
6406 initialization: Module.Union,
6407) Allocator.Error!Module.Union.Index {
6408 if (ip.unions_free_list.popOrNull()) |index| {
6409 ip.allocated_unions.at(@intFromEnum(index)).* = initialization;
6410 return index;
6411 }
6412 const ptr = try ip.allocated_unions.addOne(gpa);
6413 ptr.* = initialization;
6414 return @enumFromInt(ip.allocated_unions.len - 1);
6415}
6416
6417pub fn destroyUnion(ip: *InternPool, gpa: Allocator, index: Module.Union.Index) void {
6418 ip.unionPtr(index).* = undefined;
6419 ip.unions_free_list.append(gpa, index) catch {
6420 // In order to keep `destroyUnion` a non-fallible function, we ignore memory
6421 // allocation failures here, instead leaking the Union until garbage collection.
6422 };
6423}
6424
64256690pub fn createDecl(
64266691 ip: *InternPool,
64276692 gpa: Allocator,
......@@ -6667,9 +6932,7 @@ pub fn typeOf(ip: *const InternPool, index: Index) Index {
66676932 .type_struct_ns,
66686933 .type_struct_anon,
66696934 .type_tuple_anon,
6670 .type_union_tagged,
6671 .type_union_untagged,
6672 .type_union_safety,
6935 .type_union,
66736936 .type_function,
66746937 => .type_type,
66756938
......@@ -7005,10 +7268,7 @@ pub fn zigTypeTagOrPoison(ip: *const InternPool, index: Index) error{GenericPois
70057268 .type_tuple_anon,
70067269 => .Struct,
70077270
7008 .type_union_tagged,
7009 .type_union_untagged,
7010 .type_union_safety,
7011 => .Union,
7271 .type_union => .Union,
70127272
70137273 .type_function => .Fn,
70147274
src/Module.zig+141-261
......@@ -96,7 +96,7 @@ intern_pool: InternPool = .{},
9696/// Current uses that must be eliminated:
9797/// * Struct comptime_args
9898/// * Struct optimized_order
99/// * Union fields
99/// * comptime pointer mutation
100100/// This memory lives until the Module is destroyed.
101101tmp_hack_arena: std.heap.ArenaAllocator,
102102
......@@ -736,7 +736,7 @@ pub const Decl = struct {
736736
737737 /// If the Decl owns its value and it is a union, return it,
738738 /// otherwise null.
739 pub fn getOwnedUnion(decl: Decl, mod: *Module) ?*Union {
739 pub fn getOwnedUnion(decl: Decl, mod: *Module) ?InternPool.UnionType {
740740 if (!decl.owns_tv) return null;
741741 if (decl.val.ip_index == .none) return null;
742742 return mod.typeToUnion(decl.val.toType());
......@@ -778,7 +778,7 @@ pub const Decl = struct {
778778 else => switch (mod.intern_pool.indexToKey(decl.val.toIntern())) {
779779 .opaque_type => |opaque_type| opaque_type.namespace.toOptional(),
780780 .struct_type => |struct_type| struct_type.namespace,
781 .union_type => |union_type| mod.unionPtr(union_type.index).namespace.toOptional(),
781 .union_type => |union_type| union_type.namespace.toOptional(),
782782 .enum_type => |enum_type| enum_type.namespace,
783783 else => .none,
784784 },
......@@ -1064,246 +1064,6 @@ pub const Struct = struct {
10641064 }
10651065};
10661066
1067pub const Union = struct {
1068 /// An enum type which is used for the tag of the union.
1069 /// This type is created even for untagged unions, even when the memory
1070 /// layout does not store the tag.
1071 /// Whether zig chooses this type or the user specifies it, it is stored here.
1072 /// This will be set to the null type until status is `have_field_types`.
1073 tag_ty: Type,
1074 /// Set of field names in declaration order.
1075 fields: Fields,
1076 /// Represents the declarations inside this union.
1077 namespace: Namespace.Index,
1078 /// The Decl that corresponds to the union itself.
1079 owner_decl: Decl.Index,
1080 /// Index of the union_decl ZIR instruction.
1081 zir_index: Zir.Inst.Index,
1082
1083 layout: std.builtin.Type.ContainerLayout,
1084 status: enum {
1085 none,
1086 field_types_wip,
1087 have_field_types,
1088 layout_wip,
1089 have_layout,
1090 fully_resolved_wip,
1091 // The types and all its fields have had their layout resolved. Even through pointer,
1092 // which `have_layout` does not ensure.
1093 fully_resolved,
1094 },
1095 requires_comptime: PropertyBoolean = .unknown,
1096 assumed_runtime_bits: bool = false,
1097
1098 pub const Index = enum(u32) {
1099 _,
1100
1101 pub fn toOptional(i: Index) OptionalIndex {
1102 return @as(OptionalIndex, @enumFromInt(@intFromEnum(i)));
1103 }
1104 };
1105
1106 pub const OptionalIndex = enum(u32) {
1107 none = std.math.maxInt(u32),
1108 _,
1109
1110 pub fn init(oi: ?Index) OptionalIndex {
1111 return @as(OptionalIndex, @enumFromInt(@intFromEnum(oi orelse return .none)));
1112 }
1113
1114 pub fn unwrap(oi: OptionalIndex) ?Index {
1115 if (oi == .none) return null;
1116 return @as(Index, @enumFromInt(@intFromEnum(oi)));
1117 }
1118 };
1119
1120 pub const Field = struct {
1121 /// undefined until `status` is `have_field_types` or `have_layout`.
1122 ty: Type,
1123 /// 0 means the ABI alignment of the type.
1124 abi_align: Alignment,
1125
1126 /// Returns the field alignment, assuming the union is not packed.
1127 /// Keep implementation in sync with `Sema.unionFieldAlignment`.
1128 /// Prefer to call that function instead of this one during Sema.
1129 pub fn normalAlignment(field: Field, mod: *Module) u32 {
1130 return @as(u32, @intCast(field.abi_align.toByteUnitsOptional() orelse field.ty.abiAlignment(mod)));
1131 }
1132 };
1133
1134 pub const Fields = std.AutoArrayHashMapUnmanaged(InternPool.NullTerminatedString, Field);
1135
1136 pub fn getFullyQualifiedName(s: *Union, mod: *Module) !InternPool.NullTerminatedString {
1137 return mod.declPtr(s.owner_decl).getFullyQualifiedName(mod);
1138 }
1139
1140 pub fn srcLoc(self: Union, mod: *Module) SrcLoc {
1141 const owner_decl = mod.declPtr(self.owner_decl);
1142 return .{
1143 .file_scope = owner_decl.getFileScope(mod),
1144 .parent_decl_node = owner_decl.src_node,
1145 .lazy = LazySrcLoc.nodeOffset(0),
1146 };
1147 }
1148
1149 pub fn haveFieldTypes(u: Union) bool {
1150 return switch (u.status) {
1151 .none,
1152 .field_types_wip,
1153 => false,
1154 .have_field_types,
1155 .layout_wip,
1156 .have_layout,
1157 .fully_resolved_wip,
1158 .fully_resolved,
1159 => true,
1160 };
1161 }
1162
1163 pub fn hasAllZeroBitFieldTypes(u: Union, mod: *Module) bool {
1164 assert(u.haveFieldTypes());
1165 for (u.fields.values()) |field| {
1166 if (field.ty.hasRuntimeBits(mod)) return false;
1167 }
1168 return true;
1169 }
1170
1171 pub fn mostAlignedField(u: Union, mod: *Module) u32 {
1172 assert(u.haveFieldTypes());
1173 var most_alignment: u32 = 0;
1174 var most_index: usize = undefined;
1175 for (u.fields.values(), 0..) |field, i| {
1176 if (!field.ty.hasRuntimeBits(mod)) continue;
1177
1178 const field_align = field.normalAlignment(mod);
1179 if (field_align > most_alignment) {
1180 most_alignment = field_align;
1181 most_index = i;
1182 }
1183 }
1184 return @as(u32, @intCast(most_index));
1185 }
1186
1187 /// Returns 0 if the union is represented with 0 bits at runtime.
1188 pub fn abiAlignment(u: Union, mod: *Module, have_tag: bool) u32 {
1189 var max_align: u32 = 0;
1190 if (have_tag) max_align = u.tag_ty.abiAlignment(mod);
1191 for (u.fields.values()) |field| {
1192 if (!field.ty.hasRuntimeBits(mod)) continue;
1193
1194 const field_align = field.normalAlignment(mod);
1195 max_align = @max(max_align, field_align);
1196 }
1197 return max_align;
1198 }
1199
1200 pub fn abiSize(u: Union, mod: *Module, have_tag: bool) u64 {
1201 return u.getLayout(mod, have_tag).abi_size;
1202 }
1203
1204 pub const Layout = struct {
1205 abi_size: u64,
1206 abi_align: u32,
1207 most_aligned_field: u32,
1208 most_aligned_field_size: u64,
1209 biggest_field: u32,
1210 payload_size: u64,
1211 payload_align: u32,
1212 tag_align: u32,
1213 tag_size: u64,
1214 padding: u32,
1215 };
1216
1217 pub fn haveLayout(u: Union) bool {
1218 return switch (u.status) {
1219 .none,
1220 .field_types_wip,
1221 .have_field_types,
1222 .layout_wip,
1223 => false,
1224 .have_layout,
1225 .fully_resolved_wip,
1226 .fully_resolved,
1227 => true,
1228 };
1229 }
1230
1231 pub fn getLayout(u: Union, mod: *Module, have_tag: bool) Layout {
1232 assert(u.haveLayout());
1233 var most_aligned_field: u32 = undefined;
1234 var most_aligned_field_size: u64 = undefined;
1235 var biggest_field: u32 = undefined;
1236 var payload_size: u64 = 0;
1237 var payload_align: u32 = 0;
1238 const fields = u.fields.values();
1239 for (fields, 0..) |field, i| {
1240 if (!field.ty.hasRuntimeBitsIgnoreComptime(mod)) continue;
1241
1242 const field_align = field.abi_align.toByteUnitsOptional() orelse field.ty.abiAlignment(mod);
1243 const field_size = field.ty.abiSize(mod);
1244 if (field_size > payload_size) {
1245 payload_size = field_size;
1246 biggest_field = @as(u32, @intCast(i));
1247 }
1248 if (field_align > payload_align) {
1249 payload_align = @as(u32, @intCast(field_align));
1250 most_aligned_field = @as(u32, @intCast(i));
1251 most_aligned_field_size = field_size;
1252 }
1253 }
1254 payload_align = @max(payload_align, 1);
1255 if (!have_tag or !u.tag_ty.hasRuntimeBits(mod)) {
1256 return .{
1257 .abi_size = std.mem.alignForward(u64, payload_size, payload_align),
1258 .abi_align = payload_align,
1259 .most_aligned_field = most_aligned_field,
1260 .most_aligned_field_size = most_aligned_field_size,
1261 .biggest_field = biggest_field,
1262 .payload_size = payload_size,
1263 .payload_align = payload_align,
1264 .tag_align = 0,
1265 .tag_size = 0,
1266 .padding = 0,
1267 };
1268 }
1269 // Put the tag before or after the payload depending on which one's
1270 // alignment is greater.
1271 const tag_size = u.tag_ty.abiSize(mod);
1272 const tag_align = @max(1, u.tag_ty.abiAlignment(mod));
1273 var size: u64 = 0;
1274 var padding: u32 = undefined;
1275 if (tag_align >= payload_align) {
1276 // {Tag, Payload}
1277 size += tag_size;
1278 size = std.mem.alignForward(u64, size, payload_align);
1279 size += payload_size;
1280 const prev_size = size;
1281 size = std.mem.alignForward(u64, size, tag_align);
1282 padding = @as(u32, @intCast(size - prev_size));
1283 } else {
1284 // {Payload, Tag}
1285 size += payload_size;
1286 size = std.mem.alignForward(u64, size, tag_align);
1287 size += tag_size;
1288 const prev_size = size;
1289 size = std.mem.alignForward(u64, size, payload_align);
1290 padding = @as(u32, @intCast(size - prev_size));
1291 }
1292 return .{
1293 .abi_size = size,
1294 .abi_align = @max(tag_align, payload_align),
1295 .most_aligned_field = most_aligned_field,
1296 .most_aligned_field_size = most_aligned_field_size,
1297 .biggest_field = biggest_field,
1298 .payload_size = payload_size,
1299 .payload_align = payload_align,
1300 .tag_align = tag_align,
1301 .tag_size = tag_size,
1302 .padding = padding,
1303 };
1304 }
1305};
1306
13071067pub const DeclAdapter = struct {
13081068 mod: *Module,
13091069
......@@ -3182,10 +2942,6 @@ pub fn namespacePtr(mod: *Module, index: Namespace.Index) *Namespace {
31822942 return mod.intern_pool.namespacePtr(index);
31832943}
31842944
3185pub fn unionPtr(mod: *Module, index: Union.Index) *Union {
3186 return mod.intern_pool.unionPtr(index);
3187}
3188
31892945pub fn structPtr(mod: *Module, index: Struct.Index) *Struct {
31902946 return mod.intern_pool.structPtr(index);
31912947}
......@@ -3651,11 +3407,11 @@ fn updateZirRefs(mod: *Module, file: *File, old_zir: Zir) !void {
36513407 };
36523408 }
36533409
3654 if (decl.getOwnedUnion(mod)) |union_obj| {
3655 union_obj.zir_index = inst_map.get(union_obj.zir_index) orelse {
3410 if (decl.getOwnedUnion(mod)) |union_type| {
3411 union_type.setZirIndex(ip, inst_map.get(union_type.zir_index) orelse {
36563412 try file.deleted_decls.append(gpa, decl_index);
36573413 continue;
3658 };
3414 });
36593415 }
36603416
36613417 if (decl.getOwnedFunction(mod)) |func| {
......@@ -5550,14 +5306,6 @@ pub fn destroyStruct(mod: *Module, index: Struct.Index) void {
55505306 return mod.intern_pool.destroyStruct(mod.gpa, index);
55515307}
55525308
5553pub fn createUnion(mod: *Module, initialization: Union) Allocator.Error!Union.Index {
5554 return mod.intern_pool.createUnion(mod.gpa, initialization);
5555}
5556
5557pub fn destroyUnion(mod: *Module, index: Union.Index) void {
5558 return mod.intern_pool.destroyUnion(mod.gpa, index);
5559}
5560
55615309pub fn allocateNewDecl(
55625310 mod: *Module,
55635311 namespace: Namespace.Index,
......@@ -6956,10 +6704,14 @@ pub fn typeToStruct(mod: *Module, ty: Type) ?*Struct {
69566704 return mod.structPtr(struct_index);
69576705}
69586706
6959pub fn typeToUnion(mod: *Module, ty: Type) ?*Union {
6707/// This asserts that the union's enum tag type has been resolved.
6708pub fn typeToUnion(mod: *Module, ty: Type) ?InternPool.UnionType {
69606709 if (ty.ip_index == .none) return null;
6961 const union_index = mod.intern_pool.indexToUnionType(ty.toIntern()).unwrap() orelse return null;
6962 return mod.unionPtr(union_index);
6710 const ip = &mod.intern_pool;
6711 switch (ip.indexToKey(ty.ip_index)) {
6712 .union_type => |k| return ip.loadUnionType(k),
6713 else => return null,
6714 }
69636715}
69646716
69656717pub fn typeToFunc(mod: *Module, ty: Type) ?InternPool.Key.FuncType {
......@@ -7045,3 +6797,131 @@ pub fn getParamName(mod: *Module, func_index: InternPool.Index, index: u32) [:0]
70456797 else => unreachable,
70466798 };
70476799}
6800
6801pub const UnionLayout = struct {
6802 abi_size: u64,
6803 abi_align: u32,
6804 most_aligned_field: u32,
6805 most_aligned_field_size: u64,
6806 biggest_field: u32,
6807 payload_size: u64,
6808 payload_align: u32,
6809 tag_align: u32,
6810 tag_size: u64,
6811 padding: u32,
6812};
6813
6814pub fn getUnionLayout(mod: *Module, u: InternPool.UnionType) UnionLayout {
6815 const ip = &mod.intern_pool;
6816 assert(u.haveLayout(ip));
6817 var most_aligned_field: u32 = undefined;
6818 var most_aligned_field_size: u64 = undefined;
6819 var biggest_field: u32 = undefined;
6820 var payload_size: u64 = 0;
6821 var payload_align: u32 = 0;
6822 for (u.field_types.get(ip), 0..) |field_ty, i| {
6823 if (!field_ty.toType().hasRuntimeBitsIgnoreComptime(mod)) continue;
6824
6825 const field_align = u.fieldAlign(ip, @intCast(i)).toByteUnitsOptional() orelse
6826 field_ty.toType().abiAlignment(mod);
6827 const field_size = field_ty.toType().abiSize(mod);
6828 if (field_size > payload_size) {
6829 payload_size = field_size;
6830 biggest_field = @intCast(i);
6831 }
6832 if (field_align > payload_align) {
6833 payload_align = @intCast(field_align);
6834 most_aligned_field = @intCast(i);
6835 most_aligned_field_size = field_size;
6836 }
6837 }
6838 payload_align = @max(payload_align, 1);
6839 const have_tag = u.flagsPtr(ip).runtime_tag.hasTag();
6840 if (!have_tag or !u.enum_tag_ty.toType().hasRuntimeBits(mod)) {
6841 return .{
6842 .abi_size = std.mem.alignForward(u64, payload_size, payload_align),
6843 .abi_align = payload_align,
6844 .most_aligned_field = most_aligned_field,
6845 .most_aligned_field_size = most_aligned_field_size,
6846 .biggest_field = biggest_field,
6847 .payload_size = payload_size,
6848 .payload_align = payload_align,
6849 .tag_align = 0,
6850 .tag_size = 0,
6851 .padding = 0,
6852 };
6853 }
6854 // Put the tag before or after the payload depending on which one's
6855 // alignment is greater.
6856 const tag_size = u.enum_tag_ty.toType().abiSize(mod);
6857 const tag_align = @max(1, u.enum_tag_ty.toType().abiAlignment(mod));
6858 var size: u64 = 0;
6859 var padding: u32 = undefined;
6860 if (tag_align >= payload_align) {
6861 // {Tag, Payload}
6862 size += tag_size;
6863 size = std.mem.alignForward(u64, size, payload_align);
6864 size += payload_size;
6865 const prev_size = size;
6866 size = std.mem.alignForward(u64, size, tag_align);
6867 padding = @as(u32, @intCast(size - prev_size));
6868 } else {
6869 // {Payload, Tag}
6870 size += payload_size;
6871 size = std.mem.alignForward(u64, size, tag_align);
6872 size += tag_size;
6873 const prev_size = size;
6874 size = std.mem.alignForward(u64, size, payload_align);
6875 padding = @as(u32, @intCast(size - prev_size));
6876 }
6877 return .{
6878 .abi_size = size,
6879 .abi_align = @max(tag_align, payload_align),
6880 .most_aligned_field = most_aligned_field,
6881 .most_aligned_field_size = most_aligned_field_size,
6882 .biggest_field = biggest_field,
6883 .payload_size = payload_size,
6884 .payload_align = payload_align,
6885 .tag_align = tag_align,
6886 .tag_size = tag_size,
6887 .padding = padding,
6888 };
6889}
6890
6891pub fn unionAbiSize(mod: *Module, u: InternPool.UnionType) u64 {
6892 return mod.getUnionLayout(u).abi_size;
6893}
6894
6895/// Returns 0 if the union is represented with 0 bits at runtime.
6896/// TODO: this returns alignment in byte units should should be a u64
6897pub fn unionAbiAlignment(mod: *Module, u: InternPool.UnionType) u32 {
6898 const ip = &mod.intern_pool;
6899 const have_tag = u.flagsPtr(ip).runtime_tag.hasTag();
6900 var max_align: u32 = 0;
6901 if (have_tag) max_align = u.enum_tag_ty.toType().abiAlignment(mod);
6902 for (u.field_types.get(ip), 0..) |field_ty, field_index| {
6903 if (!field_ty.toType().hasRuntimeBits(mod)) continue;
6904
6905 const field_align = mod.unionFieldNormalAlignment(u, @intCast(field_index));
6906 max_align = @max(max_align, field_align);
6907 }
6908 return max_align;
6909}
6910
6911/// Returns the field alignment, assuming the union is not packed.
6912/// Keep implementation in sync with `Sema.unionFieldAlignment`.
6913/// Prefer to call that function instead of this one during Sema.
6914/// TODO: this returns alignment in byte units should should be a u64
6915pub fn unionFieldNormalAlignment(mod: *Module, u: InternPool.UnionType, field_index: u32) u32 {
6916 const ip = &mod.intern_pool;
6917 if (u.fieldAlign(ip, field_index).toByteUnitsOptional()) |a| return @intCast(a);
6918 const field_ty = u.field_types.get(ip)[field_index].toType();
6919 return field_ty.abiAlignment(mod);
6920}
6921
6922pub fn unionTagFieldIndex(mod: *Module, u: InternPool.UnionType, enum_tag: Value) ?u32 {
6923 const ip = &mod.intern_pool;
6924 assert(ip.typeOf(enum_tag.toIntern()) == u.enum_tag_ty);
6925 const enum_type = ip.indexToKey(u.enum_tag_ty).enum_type;
6926 return enum_type.tagValueIndex(ip, enum_tag.toIntern());
6927}
src/Sema.zig+408-505
......@@ -3022,18 +3022,18 @@ fn zirEnumDecl(
30223022
30233023 const mod = sema.mod;
30243024 const gpa = sema.gpa;
3025 const small = @as(Zir.Inst.EnumDecl.Small, @bitCast(extended.small));
3025 const small: Zir.Inst.EnumDecl.Small = @bitCast(extended.small);
30263026 var extra_index: usize = extended.operand;
30273027
30283028 const src: LazySrcLoc = if (small.has_src_node) blk: {
3029 const node_offset = @as(i32, @bitCast(sema.code.extra[extra_index]));
3029 const node_offset: i32 = @bitCast(sema.code.extra[extra_index]);
30303030 extra_index += 1;
30313031 break :blk LazySrcLoc.nodeOffset(node_offset);
30323032 } else sema.src;
30333033 const tag_ty_src: LazySrcLoc = .{ .node_offset_container_tag = src.node_offset.x };
30343034
30353035 const tag_type_ref = if (small.has_tag_type) blk: {
3036 const tag_type_ref = @as(Zir.Inst.Ref, @enumFromInt(sema.code.extra[extra_index]));
3036 const tag_type_ref: Zir.Inst.Ref = @enumFromInt(sema.code.extra[extra_index]);
30373037 extra_index += 1;
30383038 break :blk tag_type_ref;
30393039 } else .none;
......@@ -3310,7 +3310,11 @@ fn zirUnionDecl(
33103310
33113311 extra_index += @intFromBool(small.has_tag_type);
33123312 extra_index += @intFromBool(small.has_body_len);
3313 extra_index += @intFromBool(small.has_fields_len);
3313 const fields_len = if (small.has_fields_len) blk: {
3314 const fields_len = sema.code.extra[extra_index];
3315 extra_index += 1;
3316 break :blk fields_len;
3317 } else 0;
33143318
33153319 const decls_len = if (small.has_decls_len) blk: {
33163320 const decls_len = sema.code.extra[extra_index];
......@@ -3338,29 +3342,31 @@ fn zirUnionDecl(
33383342 const new_namespace = mod.namespacePtr(new_namespace_index);
33393343 errdefer mod.destroyNamespace(new_namespace_index);
33403344
3341 const union_index = try mod.createUnion(.{
3342 .owner_decl = new_decl_index,
3343 .tag_ty = Type.null,
3344 .fields = .{},
3345 .zir_index = inst,
3346 .layout = small.layout,
3347 .status = .none,
3348 .namespace = new_namespace_index,
3349 });
3350 errdefer mod.destroyUnion(union_index);
3351
33523345 const union_ty = ty: {
3353 const ty = try mod.intern_pool.get(gpa, .{ .union_type = .{
3354 .index = union_index,
3355 .runtime_tag = if (small.has_tag_type or small.auto_enum_tag)
3356 .tagged
3357 else if (small.layout != .Auto)
3358 .none
3359 else switch (block.sema.mod.optimizeMode()) {
3360 .Debug, .ReleaseSafe => .safety,
3361 .ReleaseFast, .ReleaseSmall => .none,
3346 const ty = try mod.intern_pool.getUnionType(gpa, .{
3347 .flags = .{
3348 .layout = small.layout,
3349 .status = .none,
3350 .runtime_tag = if (small.has_tag_type or small.auto_enum_tag)
3351 .tagged
3352 else if (small.layout != .Auto)
3353 .none
3354 else switch (block.wantSafety()) {
3355 true => .safety,
3356 false => .none,
3357 },
3358 .any_aligned_fields = small.any_aligned_fields,
3359 .requires_comptime = .unknown,
3360 .assumed_runtime_bits = false,
33623361 },
3363 } });
3362 .decl = new_decl_index,
3363 .namespace = new_namespace_index,
3364 .zir_index = inst,
3365 .fields_len = fields_len,
3366 .enum_tag_ty = .none,
3367 .field_types = &.{},
3368 .field_aligns = &.{},
3369 });
33643370 if (sema.builtin_type_target_index != .none) {
33653371 mod.intern_pool.resolveBuiltinType(sema.builtin_type_target_index, ty);
33663372 break :ty sema.builtin_type_target_index;
......@@ -4505,8 +4511,7 @@ fn validateUnionInit(
45054511 const field_src: LazySrcLoc = .{ .node_offset_initializer = field_ptr_data.src_node };
45064512 const field_ptr_extra = sema.code.extraData(Zir.Inst.Field, field_ptr_data.payload_index).data;
45074513 const field_name = try mod.intern_pool.getOrPutString(gpa, sema.code.nullTerminatedString(field_ptr_extra.field_name_start));
4508 // Validate the field access but ignore the index since we want the tag enum field index.
4509 _ = try sema.unionFieldIndex(block, union_ty, field_name, field_src);
4514 const field_index = try sema.unionFieldIndex(block, union_ty, field_name, field_src);
45104515 const air_tags = sema.air_instructions.items(.tag);
45114516 const air_datas = sema.air_instructions.items(.data);
45124517 const field_ptr_ref = sema.inst_map.get(field_ptr).?;
......@@ -4563,8 +4568,7 @@ fn validateUnionInit(
45634568 }
45644569
45654570 const tag_ty = union_ty.unionTagTypeHypothetical(mod);
4566 const enum_field_index = @as(u32, @intCast(tag_ty.enumFieldIndex(field_name, mod).?));
4567 const tag_val = try mod.enumValueFieldIndex(tag_ty, enum_field_index);
4571 const tag_val = try mod.enumValueFieldIndex(tag_ty, field_index);
45684572
45694573 if (init_val) |val| {
45704574 // Our task is to delete all the `field_ptr` and `store` instructions, and insert
......@@ -5227,14 +5231,15 @@ fn failWithBadStructFieldAccess(
52275231fn failWithBadUnionFieldAccess(
52285232 sema: *Sema,
52295233 block: *Block,
5230 union_obj: *Module.Union,
5234 union_obj: InternPool.UnionType,
52315235 field_src: LazySrcLoc,
52325236 field_name: InternPool.NullTerminatedString,
52335237) CompileError {
52345238 const mod = sema.mod;
52355239 const gpa = sema.gpa;
52365240
5237 const fqn = try union_obj.getFullyQualifiedName(mod);
5241 const decl = mod.declPtr(union_obj.decl);
5242 const fqn = try decl.getFullyQualifiedName(mod);
52385243
52395244 const msg = msg: {
52405245 const msg = try sema.errMsg(
......@@ -5244,7 +5249,7 @@ fn failWithBadUnionFieldAccess(
52445249 .{ field_name.fmt(&mod.intern_pool), fqn.fmt(&mod.intern_pool) },
52455250 );
52465251 errdefer msg.destroy(gpa);
5247 try mod.errNoteNonLazy(union_obj.srcLoc(mod), msg, "union declared here", .{});
5252 try mod.errNoteNonLazy(decl.srcLoc(mod), msg, "union declared here", .{});
52485253 break :msg msg;
52495254 };
52505255 return sema.failWithOwnedErrorMsg(msg);
......@@ -10500,6 +10505,7 @@ const SwitchProngAnalysis = struct {
1050010505 ) CompileError!Air.Inst.Ref {
1050110506 const sema = spa.sema;
1050210507 const mod = sema.mod;
10508 const ip = &mod.intern_pool;
1050310509
1050410510 const zir_datas = sema.code.instructions.items(.data);
1050510511 const switch_node_offset = zir_datas[spa.switch_block_inst].pl_node.src_node;
......@@ -10511,9 +10517,9 @@ const SwitchProngAnalysis = struct {
1051110517 if (inline_case_capture != .none) {
1051210518 const item_val = sema.resolveConstValue(block, .unneeded, inline_case_capture, "") catch unreachable;
1051310519 if (operand_ty.zigTypeTag(mod) == .Union) {
10514 const field_index = @as(u32, @intCast(operand_ty.unionTagFieldIndex(item_val, mod).?));
10520 const field_index: u32 = @intCast(operand_ty.unionTagFieldIndex(item_val, mod).?);
1051510521 const union_obj = mod.typeToUnion(operand_ty).?;
10516 const field_ty = union_obj.fields.values()[field_index].ty;
10522 const field_ty = union_obj.field_types.get(ip)[field_index].toType();
1051710523 if (capture_byref) {
1051810524 const ptr_field_ty = try mod.ptrType(.{
1051910525 .child = field_ty.toIntern(),
......@@ -10535,7 +10541,7 @@ const SwitchProngAnalysis = struct {
1053510541 return block.addStructFieldPtr(spa.operand_ptr, field_index, ptr_field_ty);
1053610542 } else {
1053710543 if (try sema.resolveDefinedValue(block, sema.src, spa.operand)) |union_val| {
10538 const tag_and_val = mod.intern_pool.indexToKey(union_val.toIntern()).un;
10544 const tag_and_val = ip.indexToKey(union_val.toIntern()).un;
1053910545 return Air.internedToRef(tag_and_val.val);
1054010546 }
1054110547 return block.addStructFieldVal(spa.operand, field_index, field_ty);
......@@ -10568,14 +10574,14 @@ const SwitchProngAnalysis = struct {
1056810574 const union_obj = mod.typeToUnion(operand_ty).?;
1056910575 const first_item_val = sema.resolveConstValue(block, .unneeded, case_vals[0], "") catch unreachable;
1057010576
10571 const first_field_index = @as(u32, @intCast(operand_ty.unionTagFieldIndex(first_item_val, mod).?));
10572 const first_field = union_obj.fields.values()[first_field_index];
10577 const first_field_index: u32 = mod.unionTagFieldIndex(union_obj, first_item_val).?;
10578 const first_field_ty = union_obj.field_types.get(ip)[first_field_index].toType();
1057310579
1057410580 const field_tys = try sema.arena.alloc(Type, case_vals.len);
1057510581 for (case_vals, field_tys) |item, *field_ty| {
1057610582 const item_val = sema.resolveConstValue(block, .unneeded, item, "") catch unreachable;
10577 const field_idx = @as(u32, @intCast(operand_ty.unionTagFieldIndex(item_val, sema.mod).?));
10578 field_ty.* = union_obj.fields.values()[field_idx].ty;
10583 const field_idx = mod.unionTagFieldIndex(union_obj, item_val).?;
10584 field_ty.* = union_obj.field_types.get(ip)[field_idx].toType();
1057910585 }
1058010586
1058110587 // Fast path: if all the operands are the same type already, we don't need to hit
......@@ -10682,7 +10688,7 @@ const SwitchProngAnalysis = struct {
1068210688
1068310689 if (try sema.resolveDefinedValue(block, operand_src, spa.operand)) |operand_val| {
1068410690 if (operand_val.isUndef(mod)) return mod.undefRef(capture_ty);
10685 const union_val = mod.intern_pool.indexToKey(operand_val.toIntern()).un;
10691 const union_val = ip.indexToKey(operand_val.toIntern()).un;
1068610692 if (union_val.tag.toValue().isUndef(mod)) return mod.undefRef(capture_ty);
1068710693 const uncoerced = Air.internedToRef(union_val.val);
1068810694 return sema.coerce(block, capture_ty, uncoerced, operand_src);
......@@ -10704,7 +10710,7 @@ const SwitchProngAnalysis = struct {
1070410710 }
1070510711 // All fields are in-memory coercible to the resolved type!
1070610712 // Just take the first field and bitcast the result.
10707 const uncoerced = try block.addStructFieldVal(spa.operand, first_field_index, first_field.ty);
10713 const uncoerced = try block.addStructFieldVal(spa.operand, first_field_index, first_field_ty);
1070810714 return block.addBitCast(capture_ty, uncoerced);
1070910715 };
1071010716
......@@ -12287,7 +12293,7 @@ fn zirSwitchBlock(sema: *Sema, block: *Block, inst: Zir.Inst.Index, operand_is_r
1228712293 for (seen_enum_fields, 0..) |seen_field, index| {
1228812294 if (seen_field != null) continue;
1228912295 const union_obj = mod.typeToUnion(maybe_union_ty).?;
12290 const field_ty = union_obj.fields.values()[index].ty;
12296 const field_ty = union_obj.field_types.get(ip)[index].toType();
1229112297 if (field_ty.zigTypeTag(mod) != .NoReturn) break true;
1229212298 } else false
1229312299 else
......@@ -12800,9 +12806,8 @@ fn zirHasField(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1280012806 break :hf struct_obj.fields.contains(field_name);
1280112807 },
1280212808 .union_type => |union_type| {
12803 const union_obj = mod.unionPtr(union_type.index);
12804 assert(union_obj.haveFieldTypes());
12805 break :hf union_obj.fields.contains(field_name);
12809 const union_obj = ip.loadUnionType(union_type);
12810 break :hf union_obj.nameIndex(ip, field_name) != null;
1280612811 },
1280712812 .enum_type => |enum_type| {
1280812813 break :hf enum_type.nameIndex(ip, field_name) != null;
......@@ -17271,16 +17276,15 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1727117276 };
1727217277
1727317278 try sema.resolveTypeLayout(ty); // Getting alignment requires type layout
17274 const layout = ty.containerLayout(mod);
17279 const union_obj = mod.typeToUnion(ty).?;
17280 const layout = union_obj.getLayout(ip);
1727517281
17276 const union_fields = ty.unionFields(mod);
17277 const union_field_vals = try gpa.alloc(InternPool.Index, union_fields.count());
17282 const union_field_vals = try gpa.alloc(InternPool.Index, union_obj.field_names.len);
1727817283 defer gpa.free(union_field_vals);
1727917284
1728017285 for (union_field_vals, 0..) |*field_val, i| {
17281 const field = union_fields.values()[i];
1728217286 // TODO: write something like getCoercedInts to avoid needing to dupe
17283 const name = try sema.arena.dupe(u8, ip.stringToSlice(union_fields.keys()[i]));
17287 const name = try sema.arena.dupe(u8, ip.stringToSlice(union_obj.field_names.get(ip)[i]));
1728417288 const name_val = v: {
1728517289 var anon_decl = try block.startAnonDecl();
1728617290 defer anon_decl.deinit();
......@@ -17304,15 +17308,16 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1730417308 };
1730517309
1730617310 const alignment = switch (layout) {
17307 .Auto, .Extern => try sema.unionFieldAlignment(field),
17311 .Auto, .Extern => try sema.unionFieldAlignment(union_obj, @intCast(i)),
1730817312 .Packed => 0,
1730917313 };
1731017314
17315 const field_ty = union_obj.field_types.get(ip)[i];
1731117316 const union_field_fields = .{
1731217317 // name: []const u8,
1731317318 name_val,
1731417319 // type: type,
17315 field.ty.toIntern(),
17320 field_ty,
1731617321 // alignment: comptime_int,
1731717322 (try mod.intValue(Type.comptime_int, alignment)).toIntern(),
1731817323 };
......@@ -18929,18 +18934,18 @@ fn unionInit(
1892918934 field_src: LazySrcLoc,
1893018935) CompileError!Air.Inst.Ref {
1893118936 const mod = sema.mod;
18937 const ip = &mod.intern_pool;
1893218938 const field_index = try sema.unionFieldIndex(block, union_ty, field_name, field_src);
18933 const field = union_ty.unionFields(mod).values()[field_index];
18934 const init = try sema.coerce(block, field.ty, uncasted_init, init_src);
18939 const field_ty = mod.typeToUnion(union_ty).?.field_types.get(ip)[field_index].toType();
18940 const init = try sema.coerce(block, field_ty, uncasted_init, init_src);
1893518941
1893618942 if (try sema.resolveMaybeUndefVal(init)) |init_val| {
1893718943 const tag_ty = union_ty.unionTagTypeHypothetical(mod);
18938 const enum_field_index = @as(u32, @intCast(tag_ty.enumFieldIndex(field_name, mod).?));
18939 const tag_val = try mod.enumValueFieldIndex(tag_ty, enum_field_index);
18944 const tag_val = try mod.enumValueFieldIndex(tag_ty, field_index);
1894018945 return Air.internedToRef((try mod.intern(.{ .un = .{
1894118946 .ty = union_ty.toIntern(),
1894218947 .tag = try tag_val.intern(tag_ty, mod),
18943 .val = try init_val.intern(field.ty, mod),
18948 .val = try init_val.intern(field_ty, mod),
1894418949 } })));
1894518950 }
1894618951
......@@ -18963,6 +18968,7 @@ fn zirStructInit(
1896318968 const src = inst_data.src();
1896418969
1896518970 const mod = sema.mod;
18971 const ip = &mod.intern_pool;
1896618972 const first_item = sema.code.extraData(Zir.Inst.StructInit.Item, extra.end).data;
1896718973 const first_field_type_data = zir_datas[first_item.field_type].pl_node;
1896818974 const first_field_type_extra = sema.code.extraData(Zir.Inst.FieldType, first_field_type_data.payload_index).data;
......@@ -18999,7 +19005,7 @@ fn zirStructInit(
1899919005 const field_type_data = zir_datas[item.data.field_type].pl_node;
1900019006 const field_src: LazySrcLoc = .{ .node_offset_initializer = field_type_data.src_node };
1900119007 const field_type_extra = sema.code.extraData(Zir.Inst.FieldType, field_type_data.payload_index).data;
19002 const field_name = try mod.intern_pool.getOrPutString(gpa, sema.code.nullTerminatedString(field_type_extra.name_start));
19008 const field_name = try ip.getOrPutString(gpa, sema.code.nullTerminatedString(field_type_extra.name_start));
1900319009 const field_index = if (resolved_ty.isTuple(mod))
1900419010 try sema.tupleFieldIndex(block, resolved_ty, field_name, field_src)
1900519011 else
......@@ -19040,19 +19046,18 @@ fn zirStructInit(
1904019046 const field_type_data = zir_datas[item.data.field_type].pl_node;
1904119047 const field_src: LazySrcLoc = .{ .node_offset_initializer = field_type_data.src_node };
1904219048 const field_type_extra = sema.code.extraData(Zir.Inst.FieldType, field_type_data.payload_index).data;
19043 const field_name = try mod.intern_pool.getOrPutString(gpa, sema.code.nullTerminatedString(field_type_extra.name_start));
19049 const field_name = try ip.getOrPutString(gpa, sema.code.nullTerminatedString(field_type_extra.name_start));
1904419050 const field_index = try sema.unionFieldIndex(block, resolved_ty, field_name, field_src);
1904519051 const tag_ty = resolved_ty.unionTagTypeHypothetical(mod);
19046 const enum_field_index = @as(u32, @intCast(tag_ty.enumFieldIndex(field_name, mod).?));
19047 const tag_val = try mod.enumValueFieldIndex(tag_ty, enum_field_index);
19052 const tag_val = try mod.enumValueFieldIndex(tag_ty, field_index);
1904819053
1904919054 const init_inst = try sema.resolveInst(item.data.init);
1905019055 if (try sema.resolveMaybeUndefVal(init_inst)) |val| {
19051 const field = resolved_ty.unionFields(mod).values()[field_index];
19056 const field_ty = mod.typeToUnion(resolved_ty).?.field_types.get(ip)[field_index].toType();
1905219057 return sema.addConstantMaybeRef(block, resolved_ty, (try mod.intern(.{ .un = .{
1905319058 .ty = resolved_ty.toIntern(),
1905419059 .tag = try tag_val.intern(tag_ty, mod),
19055 .val = try val.intern(field.ty, mod),
19060 .val = try val.intern(field_ty, mod),
1905619061 } })).toValue(), is_ref);
1905719062 }
1905819063
......@@ -19662,11 +19667,12 @@ fn fieldType(
1966219667 ty_src: LazySrcLoc,
1966319668) CompileError!Air.Inst.Ref {
1966419669 const mod = sema.mod;
19670 const ip = &mod.intern_pool;
1966519671 var cur_ty = aggregate_ty;
1966619672 while (true) {
1966719673 try sema.resolveTypeFields(cur_ty);
1966819674 switch (cur_ty.zigTypeTag(mod)) {
19669 .Struct => switch (mod.intern_pool.indexToKey(cur_ty.toIntern())) {
19675 .Struct => switch (ip.indexToKey(cur_ty.toIntern())) {
1967019676 .anon_struct_type => |anon_struct| {
1967119677 const field_index = try sema.anonStructFieldIndex(block, cur_ty, field_name, field_src);
1967219678 return Air.internedToRef(anon_struct.types[field_index]);
......@@ -19681,14 +19687,15 @@ fn fieldType(
1968119687 },
1968219688 .Union => {
1968319689 const union_obj = mod.typeToUnion(cur_ty).?;
19684 const field = union_obj.fields.get(field_name) orelse
19690 const field_index = union_obj.nameIndex(ip, field_name) orelse
1968519691 return sema.failWithBadUnionFieldAccess(block, union_obj, field_src, field_name);
19686 return Air.internedToRef(field.ty.toIntern());
19692 const field_ty = union_obj.field_types.get(ip)[field_index];
19693 return Air.internedToRef(field_ty);
1968719694 },
1968819695 .Optional => {
1968919696 // Struct/array init through optional requires the child type to not be a pointer.
1969019697 // If the child of .optional is a pointer it'll error on the next loop.
19691 cur_ty = mod.intern_pool.indexToKey(cur_ty.toIntern()).opt_type.toType();
19698 cur_ty = ip.indexToKey(cur_ty.toIntern()).opt_type.toType();
1969219699 continue;
1969319700 },
1969419701 .ErrorUnion => {
......@@ -20396,68 +20403,16 @@ fn zirReify(
2039620403 return sema.fail(block, src, "reified unions must have no decls", .{});
2039720404 }
2039820405 const layout = mod.toEnum(std.builtin.Type.ContainerLayout, layout_val);
20399
20400 // Because these three things each reference each other, `undefined`
20401 // placeholders are used before being set after the union type gains an
20402 // InternPool index.
20403
20404 const new_decl_index = try sema.createAnonymousDeclTypeNamed(block, src, .{
20405 .ty = Type.noreturn,
20406 .val = Value.@"unreachable",
20407 }, name_strategy, "union", inst);
20408 const new_decl = mod.declPtr(new_decl_index);
20409 new_decl.owns_tv = true;
20410 errdefer {
20411 new_decl.has_tv = false; // namespace and val were destroyed by later errdefers
20412 mod.abortAnonDecl(new_decl_index);
20413 }
20414
20415 const new_namespace_index = try mod.createNamespace(.{
20416 .parent = block.namespace.toOptional(),
20417 .ty = undefined,
20418 .file_scope = block.getFileScope(mod),
20419 });
20420 const new_namespace = mod.namespacePtr(new_namespace_index);
20421 errdefer mod.destroyNamespace(new_namespace_index);
20422
20423 const union_index = try mod.createUnion(.{
20424 .owner_decl = new_decl_index,
20425 .tag_ty = Type.null,
20426 .fields = .{},
20427 .zir_index = inst,
20428 .layout = layout,
20429 .status = .have_field_types,
20430 .namespace = new_namespace_index,
20431 });
20432 const union_obj = mod.unionPtr(union_index);
20433 errdefer mod.destroyUnion(union_index);
20434
20435 const union_ty = try ip.get(gpa, .{ .union_type = .{
20436 .index = union_index,
20437 .runtime_tag = if (!tag_type_val.isNull(mod))
20438 .tagged
20439 else if (layout != .Auto)
20440 .none
20441 else switch (mod.optimizeMode()) {
20442 .Debug, .ReleaseSafe => .safety,
20443 .ReleaseFast, .ReleaseSmall => .none,
20444 },
20445 } });
20446 // TODO: figure out InternPool removals for incremental compilation
20447 //errdefer ip.remove(union_ty);
20448
20449 new_decl.ty = Type.type;
20450 new_decl.val = union_ty.toValue();
20451 new_namespace.ty = union_ty.toType();
20406 const fields_len: u32 = @intCast(try sema.usizeCast(block, src, fields_val.sliceLen(mod)));
2045220407
2045320408 // Tag type
20454 const fields_len = try sema.usizeCast(block, src, fields_val.sliceLen(mod));
2045520409 var explicit_tags_seen: []bool = &.{};
2045620410 var enum_field_names: []InternPool.NullTerminatedString = &.{};
20411 var enum_tag_ty: InternPool.Index = .none;
2045720412 if (tag_type_val.optionalValue(mod)) |payload_val| {
20458 union_obj.tag_ty = payload_val.toType();
20413 enum_tag_ty = payload_val.toType().toIntern();
2045920414
20460 const enum_type = switch (ip.indexToKey(union_obj.tag_ty.toIntern())) {
20415 const enum_type = switch (ip.indexToKey(enum_tag_ty)) {
2046120416 .enum_type => |x| x,
2046220417 else => return sema.fail(block, src, "Type.Union.tag_type must be an enum type", .{}),
2046320418 };
......@@ -20469,7 +20424,13 @@ fn zirReify(
2046920424 }
2047020425
2047120426 // Fields
20472 try union_obj.fields.ensureTotalCapacity(mod.tmp_hack_arena.allocator(), fields_len);
20427 var any_aligned_fields: bool = false;
20428 var union_fields: std.MultiArrayList(struct {
20429 type: InternPool.Index,
20430 alignment: InternPool.Alignment,
20431 }) = .{};
20432 var field_name_table: std.AutoArrayHashMapUnmanaged(InternPool.NullTerminatedString, void) = .{};
20433 try field_name_table.ensureTotalCapacity(sema.arena, fields_len);
2047320434
2047420435 for (0..fields_len) |i| {
2047520436 const elem_val = try fields_val.elemValue(mod, i);
......@@ -20491,15 +20452,15 @@ fn zirReify(
2049120452 }
2049220453
2049320454 if (explicit_tags_seen.len > 0) {
20494 const tag_info = ip.indexToKey(union_obj.tag_ty.toIntern()).enum_type;
20455 const tag_info = ip.indexToKey(enum_tag_ty).enum_type;
2049520456 const enum_index = tag_info.nameIndex(ip, field_name) orelse {
2049620457 const msg = msg: {
2049720458 const msg = try sema.errMsg(block, src, "no field named '{}' in enum '{}'", .{
2049820459 field_name.fmt(ip),
20499 union_obj.tag_ty.fmt(mod),
20460 enum_tag_ty.toType().fmt(mod),
2050020461 });
2050120462 errdefer msg.destroy(gpa);
20502 try sema.addDeclaredHereNote(msg, union_obj.tag_ty);
20463 try sema.addDeclaredHereNote(msg, enum_tag_ty.toType());
2050320464 break :msg msg;
2050420465 };
2050520466 return sema.failWithOwnedErrorMsg(msg);
......@@ -20510,17 +20471,20 @@ fn zirReify(
2051020471 explicit_tags_seen[enum_index] = true;
2051120472 }
2051220473
20513 const gop = union_obj.fields.getOrPutAssumeCapacity(field_name);
20474 const gop = field_name_table.getOrPutAssumeCapacity(field_name);
2051420475 if (gop.found_existing) {
2051520476 // TODO: better source location
2051620477 return sema.fail(block, src, "duplicate union field {}", .{field_name.fmt(ip)});
2051720478 }
2051820479
2051920480 const field_ty = type_val.toType();
20520 gop.value_ptr.* = .{
20521 .ty = field_ty,
20522 .abi_align = Alignment.fromByteUnits((try alignment_val.getUnsignedIntAdvanced(mod, sema)).?),
20523 };
20481 const field_align = Alignment.fromByteUnits((try alignment_val.getUnsignedIntAdvanced(mod, sema)).?);
20482 any_aligned_fields = any_aligned_fields or field_align != .none;
20483
20484 try union_fields.append(sema.arena, .{
20485 .type = field_ty.toIntern(),
20486 .alignment = field_align,
20487 });
2052420488
2052520489 if (field_ty.zigTypeTag(mod) == .Opaque) {
2052620490 const msg = msg: {
......@@ -20532,7 +20496,7 @@ fn zirReify(
2053220496 };
2053320497 return sema.failWithOwnedErrorMsg(msg);
2053420498 }
20535 if (union_obj.layout == .Extern and !try sema.validateExternType(field_ty, .union_field)) {
20499 if (layout == .Extern and !try sema.validateExternType(field_ty, .union_field)) {
2053620500 const msg = msg: {
2053720501 const msg = try sema.errMsg(block, src, "extern unions cannot contain fields of type '{}'", .{field_ty.fmt(mod)});
2053820502 errdefer msg.destroy(gpa);
......@@ -20544,7 +20508,7 @@ fn zirReify(
2054420508 break :msg msg;
2054520509 };
2054620510 return sema.failWithOwnedErrorMsg(msg);
20547 } else if (union_obj.layout == .Packed and !(validatePackedType(field_ty, mod))) {
20511 } else if (layout == .Packed and !(validatePackedType(field_ty, mod))) {
2054820512 const msg = msg: {
2054920513 const msg = try sema.errMsg(block, src, "packed unions cannot contain fields of type '{}'", .{field_ty.fmt(mod)});
2055020514 errdefer msg.destroy(gpa);
......@@ -20560,28 +20524,79 @@ fn zirReify(
2056020524 }
2056120525
2056220526 if (explicit_tags_seen.len > 0) {
20563 const tag_info = ip.indexToKey(union_obj.tag_ty.toIntern()).enum_type;
20527 const tag_info = ip.indexToKey(enum_tag_ty).enum_type;
2056420528 if (tag_info.names.len > fields_len) {
2056520529 const msg = msg: {
2056620530 const msg = try sema.errMsg(block, src, "enum field(s) missing in union", .{});
2056720531 errdefer msg.destroy(gpa);
2056820532
20569 const enum_ty = union_obj.tag_ty;
2057020533 for (tag_info.names.get(ip), 0..) |field_name, field_index| {
2057120534 if (explicit_tags_seen[field_index]) continue;
20572 try sema.addFieldErrNote(enum_ty, field_index, msg, "field '{}' missing, declared here", .{
20535 try sema.addFieldErrNote(enum_tag_ty.toType(), field_index, msg, "field '{}' missing, declared here", .{
2057320536 field_name.fmt(ip),
2057420537 });
2057520538 }
20576 try sema.addDeclaredHereNote(msg, union_obj.tag_ty);
20539 try sema.addDeclaredHereNote(msg, enum_tag_ty.toType());
2057720540 break :msg msg;
2057820541 };
2057920542 return sema.failWithOwnedErrorMsg(msg);
2058020543 }
2058120544 } else {
20582 union_obj.tag_ty = try sema.generateUnionTagTypeSimple(block, enum_field_names, null);
20545 enum_tag_ty = try sema.generateUnionTagTypeSimple(block, enum_field_names, .none);
20546 }
20547
20548 // Because these three things each reference each other, `undefined`
20549 // placeholders are used before being set after the union type gains an
20550 // InternPool index.
20551
20552 const new_decl_index = try sema.createAnonymousDeclTypeNamed(block, src, .{
20553 .ty = Type.noreturn,
20554 .val = Value.@"unreachable",
20555 }, name_strategy, "union", inst);
20556 const new_decl = mod.declPtr(new_decl_index);
20557 new_decl.owns_tv = true;
20558 errdefer {
20559 new_decl.has_tv = false; // namespace and val were destroyed by later errdefers
20560 mod.abortAnonDecl(new_decl_index);
2058320561 }
2058420562
20563 const new_namespace_index = try mod.createNamespace(.{
20564 .parent = block.namespace.toOptional(),
20565 .ty = undefined,
20566 .file_scope = block.getFileScope(mod),
20567 });
20568 const new_namespace = mod.namespacePtr(new_namespace_index);
20569 errdefer mod.destroyNamespace(new_namespace_index);
20570
20571 const union_ty = try ip.getUnionType(gpa, .{
20572 .decl = new_decl_index,
20573 .namespace = new_namespace_index,
20574 .enum_tag_ty = enum_tag_ty,
20575 .fields_len = fields_len,
20576 .zir_index = inst,
20577 .flags = .{
20578 .layout = layout,
20579 .status = .have_field_types,
20580 .runtime_tag = if (!tag_type_val.isNull(mod))
20581 .tagged
20582 else if (layout != .Auto)
20583 .none
20584 else switch (block.wantSafety()) {
20585 true => .safety,
20586 false => .none,
20587 },
20588 .any_aligned_fields = any_aligned_fields,
20589 .requires_comptime = .unknown,
20590 .assumed_runtime_bits = false,
20591 },
20592 .field_types = union_fields.items(.type),
20593 .field_aligns = if (any_aligned_fields) union_fields.items(.alignment) else &.{},
20594 });
20595
20596 new_decl.ty = Type.type;
20597 new_decl.val = union_ty.toValue();
20598 new_namespace.ty = union_ty.toType();
20599
2058520600 const decl_val = sema.analyzeDeclVal(block, src, new_decl_index);
2058620601 try mod.finalizeAnonDecl(new_decl_index);
2058720602 return decl_val;
......@@ -23341,7 +23356,7 @@ fn zirFieldParentPtr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileEr
2334123356 if (mod.typeToStruct(parent_ty)) |struct_obj| {
2334223357 break :blk struct_obj.fields.values()[field_index].abi_align;
2334323358 } else if (mod.typeToUnion(parent_ty)) |union_obj| {
23344 break :blk union_obj.fields.values()[field_index].abi_align;
23359 break :blk union_obj.fieldAlign(ip, field_index);
2334523360 } else {
2334623361 break :blk .none;
2334723362 }
......@@ -24683,18 +24698,28 @@ fn validateVarType(
2468324698 is_extern: bool,
2468424699) CompileError!void {
2468524700 const mod = sema.mod;
24686 if (is_extern and !try sema.validateExternType(var_ty, .other)) {
24687 const msg = msg: {
24688 const msg = try sema.errMsg(block, src, "extern variable cannot have type '{}'", .{var_ty.fmt(mod)});
24689 errdefer msg.destroy(sema.gpa);
24690 const src_decl = mod.declPtr(block.src_decl);
24691 try sema.explainWhyTypeIsNotExtern(msg, src.toSrcLoc(src_decl, mod), var_ty, .other);
24692 break :msg msg;
24693 };
24694 return sema.failWithOwnedErrorMsg(msg);
24701 if (is_extern) {
24702 if (!try sema.validateExternType(var_ty, .other)) {
24703 const msg = msg: {
24704 const msg = try sema.errMsg(block, src, "extern variable cannot have type '{}'", .{var_ty.fmt(mod)});
24705 errdefer msg.destroy(sema.gpa);
24706 const src_decl = mod.declPtr(block.src_decl);
24707 try sema.explainWhyTypeIsNotExtern(msg, src.toSrcLoc(src_decl, mod), var_ty, .other);
24708 break :msg msg;
24709 };
24710 return sema.failWithOwnedErrorMsg(msg);
24711 }
24712 } else {
24713 if (var_ty.zigTypeTag(mod) == .Opaque) {
24714 return sema.fail(
24715 block,
24716 src,
24717 "non-extern variable with opaque type '{}'",
24718 .{var_ty.fmt(mod)},
24719 );
24720 }
2469524721 }
2469624722
24697 if (is_extern and var_ty.zigTypeTag(mod) == .Opaque) return;
2469824723 if (!try sema.typeRequiresComptime(var_ty)) return;
2469924724
2470024725 const msg = msg: {
......@@ -24735,6 +24760,7 @@ fn explainWhyTypeIsComptimeInner(
2473524760 type_set: *TypeSet,
2473624761) CompileError!void {
2473724762 const mod = sema.mod;
24763 const ip = &mod.intern_pool;
2473824764 switch (ty.zigTypeTag(mod)) {
2473924765 .Bool,
2474024766 .Int,
......@@ -24820,15 +24846,16 @@ fn explainWhyTypeIsComptimeInner(
2482024846 if ((try type_set.getOrPut(sema.gpa, ty.toIntern())).found_existing) return;
2482124847
2482224848 if (mod.typeToUnion(ty)) |union_obj| {
24823 for (union_obj.fields.values(), 0..) |field, i| {
24824 const field_src_loc = mod.fieldSrcLoc(union_obj.owner_decl, .{
24849 for (0..union_obj.field_types.len) |i| {
24850 const field_ty = union_obj.field_types.get(ip)[i].toType();
24851 const field_src_loc = mod.fieldSrcLoc(union_obj.decl, .{
2482524852 .index = i,
2482624853 .range = .type,
2482724854 });
2482824855
24829 if (try sema.typeRequiresComptime(field.ty)) {
24856 if (try sema.typeRequiresComptime(field_ty)) {
2483024857 try mod.errNoteNonLazy(field_src_loc, msg, "union requires comptime because of this field", .{});
24831 try sema.explainWhyTypeIsComptimeInner(msg, field_src_loc, field.ty, type_set);
24858 try sema.explainWhyTypeIsComptimeInner(msg, field_src_loc, field_ty, type_set);
2483224859 }
2483324860 }
2483424861 }
......@@ -25886,12 +25913,11 @@ fn fieldCallBind(
2588625913 },
2588725914 .Union => {
2588825915 try sema.resolveTypeFields(concrete_ty);
25889 const fields = concrete_ty.unionFields(mod);
25890 const field_index_usize = fields.getIndex(field_name) orelse break :find_field;
25891 const field_index = @as(u32, @intCast(field_index_usize));
25892 const field = fields.values()[field_index];
25916 const union_obj = mod.typeToUnion(concrete_ty).?;
25917 const field_index = union_obj.nameIndex(ip, field_name) orelse break :find_field;
25918 const field_ty = union_obj.field_types.get(ip)[field_index].toType();
2589325919
25894 return sema.finishFieldCallBind(block, src, ptr_ty, field.ty, field_index, object_ptr);
25920 return sema.finishFieldCallBind(block, src, ptr_ty, field_ty, field_index, object_ptr);
2589525921 },
2589625922 .Type => {
2589725923 const namespace = try sema.analyzeLoad(block, src, object_ptr, src);
......@@ -26378,24 +26404,24 @@ fn unionFieldPtr(
2637826404 try sema.resolveTypeFields(union_ty);
2637926405 const union_obj = mod.typeToUnion(union_ty).?;
2638026406 const field_index = try sema.unionFieldIndex(block, union_ty, field_name, field_name_src);
26381 const field = union_obj.fields.values()[field_index];
26407 const field_ty = union_obj.field_types.get(ip)[field_index].toType();
2638226408 const ptr_field_ty = try mod.ptrType(.{
26383 .child = field.ty.toIntern(),
26409 .child = field_ty.toIntern(),
2638426410 .flags = .{
2638526411 .is_const = union_ptr_info.flags.is_const,
2638626412 .is_volatile = union_ptr_info.flags.is_volatile,
2638726413 .address_space = union_ptr_info.flags.address_space,
26388 .alignment = if (union_obj.layout == .Auto) blk: {
26414 .alignment = if (union_obj.getLayout(ip) == .Auto) blk: {
2638926415 const union_align = union_ptr_info.flags.alignment.toByteUnitsOptional() orelse try sema.typeAbiAlignment(union_ty);
26390 const field_align = try sema.unionFieldAlignment(field);
26416 const field_align = try sema.unionFieldAlignment(union_obj, field_index);
2639126417 break :blk InternPool.Alignment.fromByteUnits(@min(union_align, field_align));
2639226418 } else union_ptr_info.flags.alignment,
2639326419 },
2639426420 .packed_offset = union_ptr_info.packed_offset,
2639526421 });
26396 const enum_field_index = @as(u32, @intCast(union_obj.tag_ty.enumFieldIndex(field_name, mod).?));
26422 const enum_field_index: u32 = @intCast(union_obj.enum_tag_ty.toType().enumFieldIndex(field_name, mod).?);
2639726423
26398 if (initializing and field.ty.zigTypeTag(mod) == .NoReturn) {
26424 if (initializing and field_ty.zigTypeTag(mod) == .NoReturn) {
2639926425 const msg = msg: {
2640026426 const msg = try sema.errMsg(block, src, "cannot initialize 'noreturn' field of union", .{});
2640126427 errdefer msg.destroy(sema.gpa);
......@@ -26410,7 +26436,7 @@ fn unionFieldPtr(
2641026436 }
2641126437
2641226438 if (try sema.resolveDefinedValue(block, src, union_ptr)) |union_ptr_val| ct: {
26413 switch (union_obj.layout) {
26439 switch (union_obj.getLayout(ip)) {
2641426440 .Auto => if (!initializing) {
2641526441 const union_val = (try sema.pointerDeref(block, src, union_ptr_val, union_ptr_ty)) orelse
2641626442 break :ct;
......@@ -26418,12 +26444,12 @@ fn unionFieldPtr(
2641826444 return sema.failWithUseOfUndef(block, src);
2641926445 }
2642026446 const un = ip.indexToKey(union_val.toIntern()).un;
26421 const field_tag = try mod.enumValueFieldIndex(union_obj.tag_ty, enum_field_index);
26447 const field_tag = try mod.enumValueFieldIndex(union_obj.enum_tag_ty.toType(), enum_field_index);
2642226448 const tag_matches = un.tag == field_tag.toIntern();
2642326449 if (!tag_matches) {
2642426450 const msg = msg: {
26425 const active_index = union_obj.tag_ty.enumTagFieldIndex(un.tag.toValue(), mod).?;
26426 const active_field_name = union_obj.tag_ty.enumFieldName(active_index, mod);
26451 const active_index = union_obj.enum_tag_ty.toType().enumTagFieldIndex(un.tag.toValue(), mod).?;
26452 const active_field_name = union_obj.enum_tag_ty.toType().enumFieldName(active_index, mod);
2642726453 const msg = try sema.errMsg(block, src, "access of union field '{}' while field '{}' is active", .{
2642826454 field_name.fmt(ip),
2642926455 active_field_name.fmt(ip),
......@@ -26447,17 +26473,17 @@ fn unionFieldPtr(
2644726473 }
2644826474
2644926475 try sema.requireRuntimeBlock(block, src, null);
26450 if (!initializing and union_obj.layout == .Auto and block.wantSafety() and
26451 union_ty.unionTagTypeSafety(mod) != null and union_obj.fields.count() > 1)
26476 if (!initializing and union_obj.getLayout(ip) == .Auto and block.wantSafety() and
26477 union_ty.unionTagTypeSafety(mod) != null and union_obj.field_names.len > 1)
2645226478 {
26453 const wanted_tag_val = try mod.enumValueFieldIndex(union_obj.tag_ty, enum_field_index);
26479 const wanted_tag_val = try mod.enumValueFieldIndex(union_obj.enum_tag_ty.toType(), enum_field_index);
2645426480 const wanted_tag = Air.internedToRef(wanted_tag_val.toIntern());
2645526481 // TODO would it be better if get_union_tag supported pointers to unions?
2645626482 const union_val = try block.addTyOp(.load, union_ty, union_ptr);
26457 const active_tag = try block.addTyOp(.get_union_tag, union_obj.tag_ty, union_val);
26483 const active_tag = try block.addTyOp(.get_union_tag, union_obj.enum_tag_ty.toType(), union_val);
2645826484 try sema.panicInactiveUnionField(block, src, active_tag, wanted_tag);
2645926485 }
26460 if (field.ty.zigTypeTag(mod) == .NoReturn) {
26486 if (field_ty.zigTypeTag(mod) == .NoReturn) {
2646126487 _ = try block.addNoOp(.unreach);
2646226488 return Air.Inst.Ref.unreachable_value;
2646326489 }
......@@ -26480,23 +26506,23 @@ fn unionFieldVal(
2648026506 try sema.resolveTypeFields(union_ty);
2648126507 const union_obj = mod.typeToUnion(union_ty).?;
2648226508 const field_index = try sema.unionFieldIndex(block, union_ty, field_name, field_name_src);
26483 const field = union_obj.fields.values()[field_index];
26484 const enum_field_index = @as(u32, @intCast(union_obj.tag_ty.enumFieldIndex(field_name, mod).?));
26509 const field_ty = union_obj.field_types.get(ip)[field_index].toType();
26510 const enum_field_index: u32 = @intCast(union_obj.enum_tag_ty.toType().enumFieldIndex(field_name, mod).?);
2648526511
2648626512 if (try sema.resolveMaybeUndefVal(union_byval)) |union_val| {
26487 if (union_val.isUndef(mod)) return mod.undefRef(field.ty);
26513 if (union_val.isUndef(mod)) return mod.undefRef(field_ty);
2648826514
2648926515 const un = ip.indexToKey(union_val.toIntern()).un;
26490 const field_tag = try mod.enumValueFieldIndex(union_obj.tag_ty, enum_field_index);
26516 const field_tag = try mod.enumValueFieldIndex(union_obj.enum_tag_ty.toType(), enum_field_index);
2649126517 const tag_matches = un.tag == field_tag.toIntern();
26492 switch (union_obj.layout) {
26518 switch (union_obj.getLayout(ip)) {
2649326519 .Auto => {
2649426520 if (tag_matches) {
2649526521 return Air.internedToRef(un.val);
2649626522 } else {
2649726523 const msg = msg: {
26498 const active_index = union_obj.tag_ty.enumTagFieldIndex(un.tag.toValue(), mod).?;
26499 const active_field_name = union_obj.tag_ty.enumFieldName(active_index, mod);
26524 const active_index = union_obj.enum_tag_ty.toType().enumTagFieldIndex(un.tag.toValue(), mod).?;
26525 const active_field_name = union_obj.enum_tag_ty.toType().enumFieldName(active_index, mod);
2650026526 const msg = try sema.errMsg(block, src, "access of union field '{}' while field '{}' is active", .{
2650126527 field_name.fmt(ip), active_field_name.fmt(ip),
2650226528 });
......@@ -26512,7 +26538,7 @@ fn unionFieldVal(
2651226538 return Air.internedToRef(un.val);
2651326539 } else {
2651426540 const old_ty = union_ty.unionFieldType(un.tag.toValue(), mod);
26515 if (try sema.bitCastVal(block, src, un.val.toValue(), old_ty, field.ty, 0)) |new_val| {
26541 if (try sema.bitCastVal(block, src, un.val.toValue(), old_ty, field_ty, 0)) |new_val| {
2651626542 return Air.internedToRef(new_val.toIntern());
2651726543 }
2651826544 }
......@@ -26521,19 +26547,19 @@ fn unionFieldVal(
2652126547 }
2652226548
2652326549 try sema.requireRuntimeBlock(block, src, null);
26524 if (union_obj.layout == .Auto and block.wantSafety() and
26525 union_ty.unionTagTypeSafety(mod) != null and union_obj.fields.count() > 1)
26550 if (union_obj.getLayout(ip) == .Auto and block.wantSafety() and
26551 union_ty.unionTagTypeSafety(mod) != null and union_obj.field_names.len > 1)
2652626552 {
26527 const wanted_tag_val = try mod.enumValueFieldIndex(union_obj.tag_ty, enum_field_index);
26553 const wanted_tag_val = try mod.enumValueFieldIndex(union_obj.enum_tag_ty.toType(), enum_field_index);
2652826554 const wanted_tag = Air.internedToRef(wanted_tag_val.toIntern());
26529 const active_tag = try block.addTyOp(.get_union_tag, union_obj.tag_ty, union_byval);
26555 const active_tag = try block.addTyOp(.get_union_tag, union_obj.enum_tag_ty.toType(), union_byval);
2653026556 try sema.panicInactiveUnionField(block, src, active_tag, wanted_tag);
2653126557 }
26532 if (field.ty.zigTypeTag(mod) == .NoReturn) {
26558 if (field_ty.zigTypeTag(mod) == .NoReturn) {
2653326559 _ = try block.addNoOp(.unreach);
2653426560 return Air.Inst.Ref.unreachable_value;
2653526561 }
26536 return block.addStructFieldVal(union_byval, field_index, field.ty);
26562 return block.addStructFieldVal(union_byval, field_index, field_ty);
2653726563}
2653826564
2653926565fn elemPtr(
......@@ -30048,14 +30074,14 @@ fn coerceEnumToUnion(
3004830074 };
3004930075
3005030076 const union_obj = mod.typeToUnion(union_ty).?;
30051 const field = union_obj.fields.values()[field_index];
30052 try sema.resolveTypeFields(field.ty);
30053 if (field.ty.zigTypeTag(mod) == .NoReturn) {
30077 const field_ty = union_obj.field_types.get(ip)[field_index].toType();
30078 try sema.resolveTypeFields(field_ty);
30079 if (field_ty.zigTypeTag(mod) == .NoReturn) {
3005430080 const msg = msg: {
3005530081 const msg = try sema.errMsg(block, inst_src, "cannot initialize 'noreturn' field of union", .{});
3005630082 errdefer msg.destroy(sema.gpa);
3005730083
30058 const field_name = union_obj.fields.keys()[field_index];
30084 const field_name = union_obj.field_names.get(ip)[field_index];
3005930085 try sema.addFieldErrNote(union_ty, field_index, msg, "field '{}' declared here", .{
3006030086 field_name.fmt(ip),
3006130087 });
......@@ -30064,12 +30090,12 @@ fn coerceEnumToUnion(
3006430090 };
3006530091 return sema.failWithOwnedErrorMsg(msg);
3006630092 }
30067 const opv = (try sema.typeHasOnePossibleValue(field.ty)) orelse {
30093 const opv = (try sema.typeHasOnePossibleValue(field_ty)) orelse {
3006830094 const msg = msg: {
30069 const field_name = union_obj.fields.keys()[field_index];
30095 const field_name = union_obj.field_names.get(ip)[field_index];
3007030096 const msg = try sema.errMsg(block, inst_src, "coercion from enum '{}' to union '{}' must initialize '{}' field '{}'", .{
3007130097 inst_ty.fmt(sema.mod), union_ty.fmt(sema.mod),
30072 field.ty.fmt(sema.mod), field_name.fmt(ip),
30098 field_ty.fmt(sema.mod), field_name.fmt(ip),
3007330099 });
3007430100 errdefer msg.destroy(sema.gpa);
3007530101
......@@ -30104,8 +30130,8 @@ fn coerceEnumToUnion(
3010430130 var msg: ?*Module.ErrorMsg = null;
3010530131 errdefer if (msg) |some| some.destroy(sema.gpa);
3010630132
30107 for (union_obj.fields.values(), 0..) |field, i| {
30108 if (field.ty.zigTypeTag(mod) == .NoReturn) {
30133 for (union_obj.field_types.get(ip), 0..) |field_ty, field_index| {
30134 if (field_ty.toType().zigTypeTag(mod) == .NoReturn) {
3010930135 const err_msg = msg orelse try sema.errMsg(
3011030136 block,
3011130137 inst_src,
......@@ -30114,7 +30140,7 @@ fn coerceEnumToUnion(
3011430140 );
3011530141 msg = err_msg;
3011630142
30117 try sema.addFieldErrNote(union_ty, i, err_msg, "'noreturn' field here", .{});
30143 try sema.addFieldErrNote(union_ty, field_index, err_msg, "'noreturn' field here", .{});
3011830144 }
3011930145 }
3012030146 if (msg) |some| {
......@@ -30138,11 +30164,9 @@ fn coerceEnumToUnion(
3013830164 );
3013930165 errdefer msg.destroy(sema.gpa);
3014030166
30141 var it = union_obj.fields.iterator();
30142 var field_index: usize = 0;
30143 while (it.next()) |field| : (field_index += 1) {
30144 const field_name = field.key_ptr.*;
30145 const field_ty = field.value_ptr.ty;
30167 for (0..union_obj.field_names.len) |field_index| {
30168 const field_name = union_obj.field_names.get(ip)[field_index];
30169 const field_ty = union_obj.field_types.get(ip)[field_index].toType();
3014630170 if (!(try sema.typeHasRuntimeBits(field_ty))) continue;
3014730171 try sema.addFieldErrNote(union_ty, field_index, msg, "field '{}' has type '{}'", .{
3014830172 field_name.fmt(ip),
......@@ -30886,6 +30910,9 @@ fn analyzeLoad(
3088630910 .Pointer => ptr_ty.childType(mod),
3088730911 else => return sema.fail(block, ptr_src, "expected pointer, found '{}'", .{ptr_ty.fmt(sema.mod)}),
3088830912 };
30913 if (elem_ty.zigTypeTag(mod) == .Opaque) {
30914 return sema.fail(block, ptr_src, "cannot load opaque type '{}'", .{elem_ty.fmt(mod)});
30915 }
3088930916
3089030917 if (try sema.typeHasOnePossibleValue(elem_ty)) |opv| {
3089130918 return Air.internedToRef(opv.toIntern());
......@@ -33816,7 +33843,7 @@ fn resolveStructLayout(sema: *Sema, ty: Type) CompileError!void {
3381633843 }
3381733844
3381833845 struct_obj.status = .have_layout;
33819 _ = try sema.resolveTypeRequiresComptime(ty);
33846 _ = try sema.typeRequiresComptime(ty);
3382033847
3382133848 if (struct_obj.assumed_runtime_bits and !(try sema.typeHasRuntimeBits(ty))) {
3382233849 const msg = try Module.ErrorMsg.create(
......@@ -34030,44 +34057,46 @@ fn checkMemOperand(sema: *Sema, block: *Block, src: LazySrcLoc, ty: Type) !void
3403034057
3403134058fn resolveUnionLayout(sema: *Sema, ty: Type) CompileError!void {
3403234059 const mod = sema.mod;
34060 const ip = &mod.intern_pool;
3403334061 try sema.resolveTypeFields(ty);
3403434062 const union_obj = mod.typeToUnion(ty).?;
34035 switch (union_obj.status) {
34063 switch (union_obj.flagsPtr(ip).status) {
3403634064 .none, .have_field_types => {},
3403734065 .field_types_wip, .layout_wip => {
3403834066 const msg = try Module.ErrorMsg.create(
3403934067 sema.gpa,
34040 union_obj.srcLoc(sema.mod),
34068 mod.declPtr(union_obj.decl).srcLoc(mod),
3404134069 "union '{}' depends on itself",
34042 .{ty.fmt(sema.mod)},
34070 .{ty.fmt(mod)},
3404334071 );
3404434072 return sema.failWithOwnedErrorMsg(msg);
3404534073 },
3404634074 .have_layout, .fully_resolved_wip, .fully_resolved => return,
3404734075 }
34048 const prev_status = union_obj.status;
34049 errdefer if (union_obj.status == .layout_wip) {
34050 union_obj.status = prev_status;
34076 const prev_status = union_obj.flagsPtr(ip).status;
34077 errdefer if (union_obj.flagsPtr(ip).status == .layout_wip) {
34078 union_obj.flagsPtr(ip).status = prev_status;
3405134079 };
3405234080
34053 union_obj.status = .layout_wip;
34054 for (union_obj.fields.values(), 0..) |field, i| {
34055 sema.resolveTypeLayout(field.ty) catch |err| switch (err) {
34081 union_obj.flagsPtr(ip).status = .layout_wip;
34082 for (0..union_obj.field_types.len) |field_index| {
34083 const field_ty = union_obj.field_types.get(ip)[field_index].toType();
34084 sema.resolveTypeLayout(field_ty) catch |err| switch (err) {
3405634085 error.AnalysisFail => {
3405734086 const msg = sema.err orelse return err;
34058 try sema.addFieldErrNote(ty, i, msg, "while checking this field", .{});
34087 try sema.addFieldErrNote(ty, field_index, msg, "while checking this field", .{});
3405934088 return err;
3406034089 },
3406134090 else => return err,
3406234091 };
3406334092 }
34064 union_obj.status = .have_layout;
34065 _ = try sema.resolveTypeRequiresComptime(ty);
34093 union_obj.flagsPtr(ip).status = .have_layout;
34094 _ = try sema.typeRequiresComptime(ty);
3406634095
34067 if (union_obj.assumed_runtime_bits and !(try sema.typeHasRuntimeBits(ty))) {
34096 if (union_obj.flagsPtr(ip).assumed_runtime_bits and !(try sema.typeHasRuntimeBits(ty))) {
3406834097 const msg = try Module.ErrorMsg.create(
3406934098 sema.gpa,
34070 union_obj.srcLoc(sema.mod),
34099 mod.declPtr(union_obj.decl).srcLoc(mod),
3407134100 "union layout depends on it having runtime bits",
3407234101 .{},
3407334102 );
......@@ -34075,163 +34104,6 @@ fn resolveUnionLayout(sema: *Sema, ty: Type) CompileError!void {
3407534104 }
3407634105}
3407734106
34078// In case of querying the ABI alignment of this struct, we will ask
34079// for hasRuntimeBits() of each field, so we need "requires comptime"
34080// to be known already before this function returns.
34081pub fn resolveTypeRequiresComptime(sema: *Sema, ty: Type) CompileError!bool {
34082 const mod = sema.mod;
34083
34084 return switch (ty.toIntern()) {
34085 .empty_struct_type => false,
34086 else => switch (mod.intern_pool.indexToKey(ty.toIntern())) {
34087 .int_type => false,
34088 .ptr_type => |ptr_type| {
34089 const child_ty = ptr_type.child.toType();
34090 if (child_ty.zigTypeTag(mod) == .Fn) {
34091 return mod.typeToFunc(child_ty).?.is_generic;
34092 } else {
34093 return sema.resolveTypeRequiresComptime(child_ty);
34094 }
34095 },
34096 .anyframe_type => |child| {
34097 if (child == .none) return false;
34098 return sema.resolveTypeRequiresComptime(child.toType());
34099 },
34100 .array_type => |array_type| return sema.resolveTypeRequiresComptime(array_type.child.toType()),
34101 .vector_type => |vector_type| return sema.resolveTypeRequiresComptime(vector_type.child.toType()),
34102 .opt_type => |child| return sema.resolveTypeRequiresComptime(child.toType()),
34103 .error_union_type => |error_union_type| return sema.resolveTypeRequiresComptime(error_union_type.payload_type.toType()),
34104 .error_set_type, .inferred_error_set_type => false,
34105
34106 .func_type => true,
34107
34108 .simple_type => |t| switch (t) {
34109 .f16,
34110 .f32,
34111 .f64,
34112 .f80,
34113 .f128,
34114 .usize,
34115 .isize,
34116 .c_char,
34117 .c_short,
34118 .c_ushort,
34119 .c_int,
34120 .c_uint,
34121 .c_long,
34122 .c_ulong,
34123 .c_longlong,
34124 .c_ulonglong,
34125 .c_longdouble,
34126 .anyopaque,
34127 .bool,
34128 .void,
34129 .anyerror,
34130 .adhoc_inferred_error_set,
34131 .noreturn,
34132 .generic_poison,
34133 .atomic_order,
34134 .atomic_rmw_op,
34135 .calling_convention,
34136 .address_space,
34137 .float_mode,
34138 .reduce_op,
34139 .call_modifier,
34140 .prefetch_options,
34141 .export_options,
34142 .extern_options,
34143 => false,
34144
34145 .type,
34146 .comptime_int,
34147 .comptime_float,
34148 .null,
34149 .undefined,
34150 .enum_literal,
34151 .type_info,
34152 => true,
34153 },
34154 .struct_type => |struct_type| {
34155 const struct_obj = mod.structPtrUnwrap(struct_type.index) orelse return false;
34156 switch (struct_obj.requires_comptime) {
34157 .no, .wip => return false,
34158 .yes => return true,
34159 .unknown => {
34160 var requires_comptime = false;
34161 struct_obj.requires_comptime = .wip;
34162 for (struct_obj.fields.values()) |field| {
34163 if (try sema.resolveTypeRequiresComptime(field.ty)) requires_comptime = true;
34164 }
34165 if (requires_comptime) {
34166 struct_obj.requires_comptime = .yes;
34167 } else {
34168 struct_obj.requires_comptime = .no;
34169 }
34170 return requires_comptime;
34171 },
34172 }
34173 },
34174
34175 .anon_struct_type => |tuple| {
34176 for (tuple.types, tuple.values) |field_ty, field_val| {
34177 const have_comptime_val = field_val != .none;
34178 if (!have_comptime_val and try sema.resolveTypeRequiresComptime(field_ty.toType())) {
34179 return true;
34180 }
34181 }
34182 return false;
34183 },
34184
34185 .union_type => |union_type| {
34186 const union_obj = mod.unionPtr(union_type.index);
34187 switch (union_obj.requires_comptime) {
34188 .no, .wip => return false,
34189 .yes => return true,
34190 .unknown => {
34191 var requires_comptime = false;
34192 union_obj.requires_comptime = .wip;
34193 for (union_obj.fields.values()) |field| {
34194 if (try sema.resolveTypeRequiresComptime(field.ty)) requires_comptime = true;
34195 }
34196 if (requires_comptime) {
34197 union_obj.requires_comptime = .yes;
34198 } else {
34199 union_obj.requires_comptime = .no;
34200 }
34201 return requires_comptime;
34202 },
34203 }
34204 },
34205
34206 .opaque_type => false,
34207
34208 .enum_type => |enum_type| try sema.resolveTypeRequiresComptime(enum_type.tag_ty.toType()),
34209
34210 // values, not types
34211 .undef,
34212 .runtime_value,
34213 .simple_value,
34214 .variable,
34215 .extern_func,
34216 .func,
34217 .int,
34218 .err,
34219 .error_union,
34220 .enum_literal,
34221 .enum_tag,
34222 .empty_enum_value,
34223 .float,
34224 .ptr,
34225 .opt,
34226 .aggregate,
34227 .un,
34228 // memoization, not types
34229 .memoized_call,
34230 => unreachable,
34231 },
34232 };
34233}
34234
3423534107/// Returns `error.AnalysisFail` if any of the types (recursively) failed to
3423634108/// be resolved.
3423734109pub fn resolveTypeFully(sema: *Sema, ty: Type) CompileError!void {
......@@ -34306,11 +34178,12 @@ fn resolveStructFully(sema: *Sema, ty: Type) CompileError!void {
3430634178
3430734179fn resolveUnionFully(sema: *Sema, ty: Type) CompileError!void {
3430834180 try sema.resolveUnionLayout(ty);
34181 try sema.resolveTypeFields(ty);
3430934182
3431034183 const mod = sema.mod;
34311 try sema.resolveTypeFields(ty);
34184 const ip = &mod.intern_pool;
3431234185 const union_obj = mod.typeToUnion(ty).?;
34313 switch (union_obj.status) {
34186 switch (union_obj.flagsPtr(ip).status) {
3431434187 .none, .have_field_types, .field_types_wip, .layout_wip, .have_layout => {},
3431534188 .fully_resolved_wip, .fully_resolved => return,
3431634189 }
......@@ -34319,14 +34192,15 @@ fn resolveUnionFully(sema: *Sema, ty: Type) CompileError!void {
3431934192 // After we have resolve union layout we have to go over the fields again to
3432034193 // make sure pointer fields get their child types resolved as well.
3432134194 // See also similar code for structs.
34322 const prev_status = union_obj.status;
34323 errdefer union_obj.status = prev_status;
34195 const prev_status = union_obj.flagsPtr(ip).status;
34196 errdefer union_obj.flagsPtr(ip).status = prev_status;
3432434197
34325 union_obj.status = .fully_resolved_wip;
34326 for (union_obj.fields.values()) |field| {
34327 try sema.resolveTypeFully(field.ty);
34198 union_obj.flagsPtr(ip).status = .fully_resolved_wip;
34199 for (0..union_obj.field_types.len) |field_index| {
34200 const field_ty = union_obj.field_types.get(ip)[field_index].toType();
34201 try sema.resolveTypeFully(field_ty);
3432834202 }
34329 union_obj.status = .fully_resolved;
34203 union_obj.flagsPtr(ip).status = .fully_resolved;
3433034204 }
3433134205
3433234206 // And let's not forget comptime-only status.
......@@ -34420,19 +34294,14 @@ pub fn resolveTypeFields(sema: *Sema, ty: Type) CompileError!void {
3442034294 else => switch (mod.intern_pool.items.items(.tag)[@intFromEnum(ty.toIntern())]) {
3442134295 .type_struct,
3442234296 .type_struct_ns,
34423 .type_union_tagged,
34424 .type_union_untagged,
34425 .type_union_safety,
34297 .type_union,
3442634298 .simple_type,
3442734299 => switch (mod.intern_pool.indexToKey(ty.toIntern())) {
3442834300 .struct_type => |struct_type| {
3442934301 const struct_obj = mod.structPtrUnwrap(struct_type.index) orelse return;
3443034302 try sema.resolveTypeFieldsStruct(ty, struct_obj);
3443134303 },
34432 .union_type => |union_type| {
34433 const union_obj = mod.unionPtr(union_type.index);
34434 try sema.resolveTypeFieldsUnion(ty, union_obj);
34435 },
34304 .union_type => |union_type| try sema.resolveTypeFieldsUnion(ty, union_type),
3443634305 .simple_type => |simple_type| try sema.resolveSimpleType(simple_type),
3443734306 else => unreachable,
3443834307 },
......@@ -34504,27 +34373,30 @@ fn resolveTypeFieldsStruct(
3450434373 try semaStructFields(sema.mod, struct_obj);
3450534374}
3450634375
34507fn resolveTypeFieldsUnion(sema: *Sema, ty: Type, union_obj: *Module.Union) CompileError!void {
34508 switch (sema.mod.declPtr(union_obj.owner_decl).analysis) {
34376fn resolveTypeFieldsUnion(sema: *Sema, ty: Type, union_type: InternPool.Key.UnionType) CompileError!void {
34377 const mod = sema.mod;
34378 const ip = &mod.intern_pool;
34379 const owner_decl = mod.declPtr(union_type.decl);
34380 switch (owner_decl.analysis) {
3450934381 .file_failure,
3451034382 .dependency_failure,
3451134383 .sema_failure,
3451234384 .sema_failure_retryable,
3451334385 => {
3451434386 sema.owner_decl.analysis = .dependency_failure;
34515 sema.owner_decl.generation = sema.mod.generation;
34387 sema.owner_decl.generation = mod.generation;
3451634388 return error.AnalysisFail;
3451734389 },
3451834390 else => {},
3451934391 }
34520 switch (union_obj.status) {
34392 switch (union_type.flagsPtr(ip).status) {
3452134393 .none => {},
3452234394 .field_types_wip => {
3452334395 const msg = try Module.ErrorMsg.create(
3452434396 sema.gpa,
34525 union_obj.srcLoc(sema.mod),
34397 owner_decl.srcLoc(mod),
3452634398 "union '{}' depends on itself",
34527 .{ty.fmt(sema.mod)},
34399 .{ty.fmt(mod)},
3452834400 );
3452934401 return sema.failWithOwnedErrorMsg(msg);
3453034402 },
......@@ -34536,10 +34408,10 @@ fn resolveTypeFieldsUnion(sema: *Sema, ty: Type, union_obj: *Module.Union) Compi
3453634408 => return,
3453734409 }
3453834410
34539 union_obj.status = .field_types_wip;
34540 errdefer union_obj.status = .none;
34541 try semaUnionFields(sema.mod, union_obj);
34542 union_obj.status = .have_field_types;
34411 union_type.flagsPtr(ip).status = .field_types_wip;
34412 errdefer union_type.flagsPtr(ip).status = .none;
34413 try semaUnionFields(mod, sema.arena, union_type);
34414 union_type.flagsPtr(ip).status = .have_field_types;
3454334415}
3454434416
3454534417/// Returns a normal error set corresponding to the fully populated inferred
......@@ -35027,24 +34899,24 @@ fn semaStructFields(mod: *Module, struct_obj: *Module.Struct) CompileError!void
3502734899 struct_obj.have_field_inits = true;
3502834900}
3502934901
35030fn semaUnionFields(mod: *Module, union_obj: *Module.Union) CompileError!void {
34902fn semaUnionFields(mod: *Module, arena: Allocator, union_type: InternPool.Key.UnionType) CompileError!void {
3503134903 const tracy = trace(@src());
3503234904 defer tracy.end();
3503334905
3503434906 const gpa = mod.gpa;
3503534907 const ip = &mod.intern_pool;
35036 const decl_index = union_obj.owner_decl;
35037 const zir = mod.namespacePtr(union_obj.namespace).file_scope.zir;
35038 const extended = zir.instructions.items(.data)[union_obj.zir_index].extended;
34908 const decl_index = union_type.decl;
34909 const zir = mod.namespacePtr(union_type.namespace).file_scope.zir;
34910 const extended = zir.instructions.items(.data)[union_type.zir_index].extended;
3503934911 assert(extended.opcode == .union_decl);
35040 const small = @as(Zir.Inst.UnionDecl.Small, @bitCast(extended.small));
34912 const small: Zir.Inst.UnionDecl.Small = @bitCast(extended.small);
3504134913 var extra_index: usize = extended.operand;
3504234914
3504334915 const src = LazySrcLoc.nodeOffset(0);
3504434916 extra_index += @intFromBool(small.has_src_node);
3504534917
3504634918 const tag_type_ref: Zir.Inst.Ref = if (small.has_tag_type) blk: {
35047 const ty_ref = @as(Zir.Inst.Ref, @enumFromInt(zir.extra[extra_index]));
34919 const ty_ref: Zir.Inst.Ref = @enumFromInt(zir.extra[extra_index]);
3504834920 extra_index += 1;
3504934921 break :blk ty_ref;
3505034922 } else .none;
......@@ -35077,16 +34949,13 @@ fn semaUnionFields(mod: *Module, union_obj: *Module.Union) CompileError!void {
3507734949
3507834950 const decl = mod.declPtr(decl_index);
3507934951
35080 var analysis_arena = std.heap.ArenaAllocator.init(gpa);
35081 defer analysis_arena.deinit();
35082
3508334952 var comptime_mutable_decls = std.ArrayList(Decl.Index).init(gpa);
3508434953 defer comptime_mutable_decls.deinit();
3508534954
3508634955 var sema: Sema = .{
3508734956 .mod = mod,
3508834957 .gpa = gpa,
35089 .arena = analysis_arena.allocator(),
34958 .arena = arena,
3509034959 .code = zir,
3509134960 .owner_decl = decl,
3509234961 .owner_decl_index = decl_index,
......@@ -35106,7 +34975,7 @@ fn semaUnionFields(mod: *Module, union_obj: *Module.Union) CompileError!void {
3510634975 .parent = null,
3510734976 .sema = &sema,
3510834977 .src_decl = decl_index,
35109 .namespace = union_obj.namespace,
34978 .namespace = union_type.namespace,
3511034979 .wip_capture_scope = wip_captures.scope,
3511134980 .instructions = .{},
3511234981 .inlining = null,
......@@ -35124,8 +34993,6 @@ fn semaUnionFields(mod: *Module, union_obj: *Module.Union) CompileError!void {
3512434993 _ = try ct_decl.internValue(mod);
3512534994 }
3512634995
35127 try union_obj.fields.ensureTotalCapacity(mod.tmp_hack_arena.allocator(), fields_len);
35128
3512934996 var int_tag_ty: Type = undefined;
3513034997 var enum_field_names: []InternPool.NullTerminatedString = &.{};
3513134998 var enum_field_vals: std.AutoArrayHashMapUnmanaged(InternPool.Index, void) = .{};
......@@ -35159,10 +35026,10 @@ fn semaUnionFields(mod: *Module, union_obj: *Module.Union) CompileError!void {
3515935026 }
3516035027 } else {
3516135028 // The provided type is the enum tag type.
35162 union_obj.tag_ty = provided_ty;
35163 const enum_type = switch (ip.indexToKey(union_obj.tag_ty.toIntern())) {
35029 union_type.tagTypePtr(ip).* = provided_ty.toIntern();
35030 const enum_type = switch (ip.indexToKey(provided_ty.toIntern())) {
3516435031 .enum_type => |x| x,
35165 else => return sema.fail(&block_scope, tag_ty_src, "expected enum tag type, found '{}'", .{union_obj.tag_ty.fmt(mod)}),
35032 else => return sema.fail(&block_scope, tag_ty_src, "expected enum tag type, found '{}'", .{provided_ty.fmt(mod)}),
3516635033 };
3516735034 // The fields of the union must match the enum exactly.
3516835035 // A flag per field is used to check for missing and extraneous fields.
......@@ -35176,6 +35043,15 @@ fn semaUnionFields(mod: *Module, union_obj: *Module.Union) CompileError!void {
3517635043 enum_field_names = try sema.arena.alloc(InternPool.NullTerminatedString, fields_len);
3517735044 }
3517835045
35046 var field_types: std.ArrayListUnmanaged(InternPool.Index) = .{};
35047 var field_aligns: std.ArrayListUnmanaged(InternPool.Alignment) = .{};
35048 var field_name_table: std.AutoArrayHashMapUnmanaged(InternPool.NullTerminatedString, void) = .{};
35049
35050 try field_types.ensureTotalCapacityPrecise(sema.arena, fields_len);
35051 if (small.any_aligned_fields)
35052 try field_aligns.ensureTotalCapacityPrecise(sema.arena, fields_len);
35053 try field_name_table.ensureTotalCapacity(sema.arena, fields_len);
35054
3517935055 const bits_per_field = 4;
3518035056 const fields_per_u32 = 32 / bits_per_field;
3518135057 const bit_bags_count = std.math.divCeil(usize, fields_len, fields_per_u32) catch unreachable;
......@@ -35206,19 +35082,19 @@ fn semaUnionFields(mod: *Module, union_obj: *Module.Union) CompileError!void {
3520635082 extra_index += 1;
3520735083
3520835084 const field_type_ref: Zir.Inst.Ref = if (has_type) blk: {
35209 const field_type_ref = @as(Zir.Inst.Ref, @enumFromInt(zir.extra[extra_index]));
35085 const field_type_ref: Zir.Inst.Ref = @enumFromInt(zir.extra[extra_index]);
3521035086 extra_index += 1;
3521135087 break :blk field_type_ref;
3521235088 } else .none;
3521335089
3521435090 const align_ref: Zir.Inst.Ref = if (has_align) blk: {
35215 const align_ref = @as(Zir.Inst.Ref, @enumFromInt(zir.extra[extra_index]));
35091 const align_ref: Zir.Inst.Ref = @enumFromInt(zir.extra[extra_index]);
3521635092 extra_index += 1;
3521735093 break :blk align_ref;
3521835094 } else .none;
3521935095
3522035096 const tag_ref: Air.Inst.Ref = if (has_tag) blk: {
35221 const tag_ref = @as(Zir.Inst.Ref, @enumFromInt(zir.extra[extra_index]));
35097 const tag_ref: Zir.Inst.Ref = @enumFromInt(zir.extra[extra_index]);
3522235098 extra_index += 1;
3522335099 break :blk try sema.resolveInst(tag_ref);
3522435100 } else .none;
......@@ -35227,7 +35103,7 @@ fn semaUnionFields(mod: *Module, union_obj: *Module.Union) CompileError!void {
3522735103 const enum_tag_val = if (tag_ref != .none) blk: {
3522835104 const val = sema.semaUnionFieldVal(&block_scope, .unneeded, int_tag_ty, tag_ref) catch |err| switch (err) {
3522935105 error.NeededSourceLocation => {
35230 const val_src = mod.fieldSrcLoc(union_obj.owner_decl, .{
35106 const val_src = mod.fieldSrcLoc(union_type.decl, .{
3523135107 .index = field_i,
3523235108 .range = .value,
3523335109 }).lazy;
......@@ -35250,8 +35126,8 @@ fn semaUnionFields(mod: *Module, union_obj: *Module.Union) CompileError!void {
3525035126 };
3525135127 const gop = enum_field_vals.getOrPutAssumeCapacity(enum_tag_val.toIntern());
3525235128 if (gop.found_existing) {
35253 const field_src = mod.fieldSrcLoc(union_obj.owner_decl, .{ .index = field_i }).lazy;
35254 const other_field_src = mod.fieldSrcLoc(union_obj.owner_decl, .{ .index = gop.index }).lazy;
35129 const field_src = mod.fieldSrcLoc(union_type.decl, .{ .index = field_i }).lazy;
35130 const other_field_src = mod.fieldSrcLoc(union_type.decl, .{ .index = gop.index }).lazy;
3525535131 const msg = msg: {
3525635132 const msg = try sema.errMsg(&block_scope, field_src, "enum tag value {} already taken", .{enum_tag_val.fmtValue(int_tag_ty, mod)});
3525735133 errdefer msg.destroy(gpa);
......@@ -35275,7 +35151,7 @@ fn semaUnionFields(mod: *Module, union_obj: *Module.Union) CompileError!void {
3527535151 else
3527635152 sema.resolveType(&block_scope, .unneeded, field_type_ref) catch |err| switch (err) {
3527735153 error.NeededSourceLocation => {
35278 const ty_src = mod.fieldSrcLoc(union_obj.owner_decl, .{
35154 const ty_src = mod.fieldSrcLoc(union_type.decl, .{
3527935155 .index = field_i,
3528035156 .range = .type,
3528135157 }).lazy;
......@@ -35289,17 +35165,16 @@ fn semaUnionFields(mod: *Module, union_obj: *Module.Union) CompileError!void {
3528935165 return error.GenericPoison;
3529035166 }
3529135167
35292 const gop = union_obj.fields.getOrPutAssumeCapacity(field_name);
35168 const gop = field_name_table.getOrPutAssumeCapacity(field_name);
3529335169 if (gop.found_existing) {
3529435170 const msg = msg: {
35295 const field_src = mod.fieldSrcLoc(union_obj.owner_decl, .{ .index = field_i }).lazy;
35171 const field_src = mod.fieldSrcLoc(union_type.decl, .{ .index = field_i }).lazy;
3529635172 const msg = try sema.errMsg(&block_scope, field_src, "duplicate union field: '{}'", .{
3529735173 field_name.fmt(ip),
3529835174 });
3529935175 errdefer msg.destroy(gpa);
3530035176
35301 const prev_field_index = union_obj.fields.getIndex(field_name).?;
35302 const prev_field_src = mod.fieldSrcLoc(union_obj.owner_decl, .{ .index = prev_field_index }).lazy;
35177 const prev_field_src = mod.fieldSrcLoc(union_type.decl, .{ .index = gop.index }).lazy;
3530335178 try mod.errNoteNonLazy(prev_field_src.toSrcLoc(decl, mod), msg, "other field here", .{});
3530435179 try sema.errNote(&block_scope, src, msg, "union declared here", .{});
3530535180 break :msg msg;
......@@ -35308,18 +35183,18 @@ fn semaUnionFields(mod: *Module, union_obj: *Module.Union) CompileError!void {
3530835183 }
3530935184
3531035185 if (explicit_tags_seen.len > 0) {
35311 const tag_info = ip.indexToKey(union_obj.tag_ty.toIntern()).enum_type;
35186 const tag_info = ip.indexToKey(union_type.tagTypePtr(ip).*).enum_type;
3531235187 const enum_index = tag_info.nameIndex(ip, field_name) orelse {
3531335188 const msg = msg: {
35314 const ty_src = mod.fieldSrcLoc(union_obj.owner_decl, .{
35189 const ty_src = mod.fieldSrcLoc(union_type.decl, .{
3531535190 .index = field_i,
3531635191 .range = .type,
3531735192 }).lazy;
3531835193 const msg = try sema.errMsg(&block_scope, ty_src, "no field named '{}' in enum '{}'", .{
35319 field_name.fmt(ip), union_obj.tag_ty.fmt(mod),
35194 field_name.fmt(ip), union_type.tagTypePtr(ip).toType().fmt(mod),
3532035195 });
3532135196 errdefer msg.destroy(sema.gpa);
35322 try sema.addDeclaredHereNote(msg, union_obj.tag_ty);
35197 try sema.addDeclaredHereNote(msg, union_type.tagTypePtr(ip).toType());
3532335198 break :msg msg;
3532435199 };
3532535200 return sema.failWithOwnedErrorMsg(msg);
......@@ -35328,11 +35203,29 @@ fn semaUnionFields(mod: *Module, union_obj: *Module.Union) CompileError!void {
3532835203 // to create the enum type in the first place.
3532935204 assert(!explicit_tags_seen[enum_index]);
3533035205 explicit_tags_seen[enum_index] = true;
35206
35207 // Enforce the enum fields and the union fields being in the same order.
35208 if (enum_index != field_i) {
35209 const msg = msg: {
35210 const ty_src = mod.fieldSrcLoc(union_type.decl, .{
35211 .index = field_i,
35212 .range = .type,
35213 }).lazy;
35214 const enum_field_src = mod.fieldSrcLoc(tag_info.decl, .{ .index = enum_index }).lazy;
35215 const msg = try sema.errMsg(&block_scope, ty_src, "union field '{}' ordered differently than corresponding enum field", .{
35216 field_name.fmt(ip),
35217 });
35218 errdefer msg.destroy(sema.gpa);
35219 try sema.errNote(&block_scope, enum_field_src, msg, "enum field here", .{});
35220 break :msg msg;
35221 };
35222 return sema.failWithOwnedErrorMsg(msg);
35223 }
3533135224 }
3533235225
3533335226 if (field_ty.zigTypeTag(mod) == .Opaque) {
3533435227 const msg = msg: {
35335 const ty_src = mod.fieldSrcLoc(union_obj.owner_decl, .{
35228 const ty_src = mod.fieldSrcLoc(union_type.decl, .{
3533635229 .index = field_i,
3533735230 .range = .type,
3533835231 }).lazy;
......@@ -35344,9 +35237,12 @@ fn semaUnionFields(mod: *Module, union_obj: *Module.Union) CompileError!void {
3534435237 };
3534535238 return sema.failWithOwnedErrorMsg(msg);
3534635239 }
35347 if (union_obj.layout == .Extern and !try sema.validateExternType(field_ty, .union_field)) {
35240 const layout = union_type.getLayout(ip);
35241 if (layout == .Extern and
35242 !try sema.validateExternType(field_ty, .union_field))
35243 {
3534835244 const msg = msg: {
35349 const ty_src = mod.fieldSrcLoc(union_obj.owner_decl, .{
35245 const ty_src = mod.fieldSrcLoc(union_type.decl, .{
3535035246 .index = field_i,
3535135247 .range = .type,
3535235248 });
......@@ -35359,9 +35255,9 @@ fn semaUnionFields(mod: *Module, union_obj: *Module.Union) CompileError!void {
3535935255 break :msg msg;
3536035256 };
3536135257 return sema.failWithOwnedErrorMsg(msg);
35362 } else if (union_obj.layout == .Packed and !(validatePackedType(field_ty, mod))) {
35258 } else if (layout == .Packed and !validatePackedType(field_ty, mod)) {
3536335259 const msg = msg: {
35364 const ty_src = mod.fieldSrcLoc(union_obj.owner_decl, .{
35260 const ty_src = mod.fieldSrcLoc(union_type.decl, .{
3536535261 .index = field_i,
3536635262 .range = .type,
3536735263 });
......@@ -35376,51 +35272,55 @@ fn semaUnionFields(mod: *Module, union_obj: *Module.Union) CompileError!void {
3537635272 return sema.failWithOwnedErrorMsg(msg);
3537735273 }
3537835274
35379 gop.value_ptr.* = .{
35380 .ty = field_ty,
35381 .abi_align = .none,
35382 };
35275 field_types.appendAssumeCapacity(field_ty.toIntern());
3538335276
35384 if (align_ref != .none) {
35385 gop.value_ptr.abi_align = sema.resolveAlign(&block_scope, .unneeded, align_ref) catch |err| switch (err) {
35386 error.NeededSourceLocation => {
35387 const align_src = mod.fieldSrcLoc(union_obj.owner_decl, .{
35388 .index = field_i,
35389 .range = .alignment,
35390 }).lazy;
35391 _ = try sema.resolveAlign(&block_scope, align_src, align_ref);
35392 unreachable;
35393 },
35394 else => |e| return e,
35395 };
35277 if (small.any_aligned_fields) {
35278 field_aligns.appendAssumeCapacity(if (align_ref != .none)
35279 sema.resolveAlign(&block_scope, .unneeded, align_ref) catch |err| switch (err) {
35280 error.NeededSourceLocation => {
35281 const align_src = mod.fieldSrcLoc(union_type.decl, .{
35282 .index = field_i,
35283 .range = .alignment,
35284 }).lazy;
35285 _ = try sema.resolveAlign(&block_scope, align_src, align_ref);
35286 unreachable;
35287 },
35288 else => |e| return e,
35289 }
35290 else
35291 .none);
3539635292 } else {
35397 gop.value_ptr.abi_align = .none;
35293 assert(align_ref == .none);
3539835294 }
3539935295 }
3540035296
35297 union_type.setFieldTypes(ip, field_types.items);
35298 union_type.setFieldAligns(ip, field_aligns.items);
35299
3540135300 if (explicit_tags_seen.len > 0) {
35402 const tag_info = ip.indexToKey(union_obj.tag_ty.toIntern()).enum_type;
35301 const tag_info = ip.indexToKey(union_type.tagTypePtr(ip).*).enum_type;
3540335302 if (tag_info.names.len > fields_len) {
3540435303 const msg = msg: {
3540535304 const msg = try sema.errMsg(&block_scope, src, "enum field(s) missing in union", .{});
3540635305 errdefer msg.destroy(sema.gpa);
3540735306
35408 const enum_ty = union_obj.tag_ty;
3540935307 for (tag_info.names.get(ip), 0..) |field_name, field_index| {
3541035308 if (explicit_tags_seen[field_index]) continue;
35411 try sema.addFieldErrNote(enum_ty, field_index, msg, "field '{}' missing, declared here", .{
35309 try sema.addFieldErrNote(union_type.tagTypePtr(ip).toType(), field_index, msg, "field '{}' missing, declared here", .{
3541235310 field_name.fmt(ip),
3541335311 });
3541435312 }
35415 try sema.addDeclaredHereNote(msg, union_obj.tag_ty);
35313 try sema.addDeclaredHereNote(msg, union_type.tagTypePtr(ip).toType());
3541635314 break :msg msg;
3541735315 };
3541835316 return sema.failWithOwnedErrorMsg(msg);
3541935317 }
3542035318 } else if (enum_field_vals.count() > 0) {
35421 union_obj.tag_ty = try sema.generateUnionTagTypeNumbered(&block_scope, enum_field_names, enum_field_vals.keys(), union_obj);
35319 const enum_ty = try sema.generateUnionTagTypeNumbered(&block_scope, enum_field_names, enum_field_vals.keys(), mod.declPtr(union_type.decl));
35320 union_type.tagTypePtr(ip).* = enum_ty;
3542235321 } else {
35423 union_obj.tag_ty = try sema.generateUnionTagTypeSimple(&block_scope, enum_field_names, union_obj);
35322 const enum_ty = try sema.generateUnionTagTypeSimple(&block_scope, enum_field_names, union_type.decl.toOptional());
35323 union_type.tagTypePtr(ip).* = enum_ty;
3542435324 }
3542535325}
3542635326
......@@ -35434,8 +35334,8 @@ fn generateUnionTagTypeNumbered(
3543435334 block: *Block,
3543535335 enum_field_names: []const InternPool.NullTerminatedString,
3543635336 enum_field_vals: []const InternPool.Index,
35437 union_obj: *Module.Union,
35438) !Type {
35337 decl: *Module.Decl,
35338) !InternPool.Index {
3543935339 const mod = sema.mod;
3544035340 const gpa = sema.gpa;
3544135341 const ip = &mod.intern_pool;
......@@ -35443,7 +35343,7 @@ fn generateUnionTagTypeNumbered(
3544335343 const src_decl = mod.declPtr(block.src_decl);
3544435344 const new_decl_index = try mod.allocateNewDecl(block.namespace, src_decl.src_node, block.wip_capture_scope);
3544535345 errdefer mod.destroyDecl(new_decl_index);
35446 const fqn = try union_obj.getFullyQualifiedName(mod);
35346 const fqn = try decl.getFullyQualifiedName(mod);
3544735347 const name = try ip.getOrPutStringFmt(gpa, "@typeInfo({}).Union.tag_type.?", .{fqn.fmt(ip)});
3544835348 try mod.initNewAnonDecl(new_decl_index, src_decl.src_line, .{
3544935349 .ty = Type.noreturn,
......@@ -35472,30 +35372,30 @@ fn generateUnionTagTypeNumbered(
3547235372 new_decl.val = enum_ty.toValue();
3547335373
3547435374 try mod.finalizeAnonDecl(new_decl_index);
35475 return enum_ty.toType();
35375 return enum_ty;
3547635376}
3547735377
3547835378fn generateUnionTagTypeSimple(
3547935379 sema: *Sema,
3548035380 block: *Block,
3548135381 enum_field_names: []const InternPool.NullTerminatedString,
35482 maybe_union_obj: ?*Module.Union,
35483) !Type {
35382 maybe_decl_index: Module.Decl.OptionalIndex,
35383) !InternPool.Index {
3548435384 const mod = sema.mod;
3548535385 const ip = &mod.intern_pool;
3548635386 const gpa = sema.gpa;
3548735387
3548835388 const new_decl_index = new_decl_index: {
35489 const union_obj = maybe_union_obj orelse {
35389 const decl_index = maybe_decl_index.unwrap() orelse {
3549035390 break :new_decl_index try mod.createAnonymousDecl(block, .{
3549135391 .ty = Type.noreturn,
3549235392 .val = Value.@"unreachable",
3549335393 });
3549435394 };
35395 const fqn = try mod.declPtr(decl_index).getFullyQualifiedName(mod);
3549535396 const src_decl = mod.declPtr(block.src_decl);
3549635397 const new_decl_index = try mod.allocateNewDecl(block.namespace, src_decl.src_node, block.wip_capture_scope);
3549735398 errdefer mod.destroyDecl(new_decl_index);
35498 const fqn = try union_obj.getFullyQualifiedName(mod);
3549935399 const name = try ip.getOrPutStringFmt(gpa, "@typeInfo({}).Union.tag_type.?", .{fqn.fmt(ip)});
3550035400 try mod.initNewAnonDecl(new_decl_index, src_decl.src_line, .{
3550135401 .ty = Type.noreturn,
......@@ -35524,7 +35424,7 @@ fn generateUnionTagTypeSimple(
3552435424 new_decl.val = enum_ty.toValue();
3552535425
3552635426 try mod.finalizeAnonDecl(new_decl_index);
35527 return enum_ty.toType();
35427 return enum_ty;
3552835428}
3552935429
3553035430fn getBuiltin(sema: *Sema, name: []const u8) CompileError!Air.Inst.Ref {
......@@ -35787,9 +35687,7 @@ pub fn typeHasOnePossibleValue(sema: *Sema, ty: Type) CompileError!?Value {
3578735687 .type_struct_ns,
3578835688 .type_struct_anon,
3578935689 .type_tuple_anon,
35790 .type_union_tagged,
35791 .type_union_untagged,
35792 .type_union_safety,
35690 .type_union,
3579335691 => switch (ip.indexToKey(ty.toIntern())) {
3579435692 inline .array_type, .vector_type => |seq_type, seq_tag| {
3579535693 const has_sentinel = seq_tag == .array_type and seq_type.sentinel != .none;
......@@ -35816,12 +35714,12 @@ pub fn typeHasOnePossibleValue(sema: *Sema, ty: Type) CompileError!?Value {
3581635714 field_val.* = field.default_val;
3581735715 continue;
3581835716 }
35819 if (field.ty.eql(ty, sema.mod)) {
35717 if (field.ty.eql(ty, mod)) {
3582035718 const msg = try Module.ErrorMsg.create(
3582135719 sema.gpa,
35822 s.srcLoc(sema.mod),
35720 s.srcLoc(mod),
3582335721 "struct '{}' depends on itself",
35824 .{ty.fmt(sema.mod)},
35722 .{ty.fmt(mod)},
3582535723 );
3582635724 try sema.addFieldErrNote(ty, i, msg, "while checking this field", .{});
3582735725 return sema.failWithOwnedErrorMsg(msg);
......@@ -35862,26 +35760,25 @@ pub fn typeHasOnePossibleValue(sema: *Sema, ty: Type) CompileError!?Value {
3586235760
3586335761 .union_type => |union_type| {
3586435762 try sema.resolveTypeFields(ty);
35865 const union_obj = mod.unionPtr(union_type.index);
35866 const tag_val = (try sema.typeHasOnePossibleValue(union_obj.tag_ty)) orelse
35763 const union_obj = ip.loadUnionType(union_type);
35764 const tag_val = (try sema.typeHasOnePossibleValue(union_obj.enum_tag_ty.toType())) orelse
3586735765 return null;
35868 const fields = union_obj.fields.values();
35869 if (fields.len == 0) {
35766 if (union_obj.field_types.len == 0) {
3587035767 const only = try mod.intern(.{ .empty_enum_value = ty.toIntern() });
3587135768 return only.toValue();
3587235769 }
35873 const only_field = fields[0];
35874 if (only_field.ty.eql(ty, sema.mod)) {
35770 const only_field_ty = union_obj.field_types.get(ip)[0].toType();
35771 if (only_field_ty.eql(ty, mod)) {
3587535772 const msg = try Module.ErrorMsg.create(
3587635773 sema.gpa,
35877 union_obj.srcLoc(sema.mod),
35774 mod.declPtr(union_obj.decl).srcLoc(mod),
3587835775 "union '{}' depends on itself",
35879 .{ty.fmt(sema.mod)},
35776 .{ty.fmt(mod)},
3588035777 );
3588135778 try sema.addFieldErrNote(ty, 0, msg, "while checking this field", .{});
3588235779 return sema.failWithOwnedErrorMsg(msg);
3588335780 }
35884 const val_val = (try sema.typeHasOnePossibleValue(only_field.ty)) orelse
35781 const val_val = (try sema.typeHasOnePossibleValue(only_field_ty)) orelse
3588535782 return null;
3588635783 const only = try mod.intern(.{ .un = .{
3588735784 .ty = ty.toIntern(),
......@@ -36225,10 +36122,11 @@ fn typePtrOrOptionalPtrTy(sema: *Sema, ty: Type) !?Type {
3622536122/// elsewhere in value.zig
3622636123pub fn typeRequiresComptime(sema: *Sema, ty: Type) CompileError!bool {
3622736124 const mod = sema.mod;
36125 const ip = &mod.intern_pool;
3622836126 return switch (ty.toIntern()) {
3622936127 .empty_struct_type => false,
3623036128
36231 else => switch (mod.intern_pool.indexToKey(ty.toIntern())) {
36129 else => switch (ip.indexToKey(ty.toIntern())) {
3623236130 .int_type => return false,
3623336131 .ptr_type => |ptr_type| {
3623436132 const child_ty = ptr_type.child.toType();
......@@ -36254,7 +36152,7 @@ pub fn typeRequiresComptime(sema: *Sema, ty: Type) CompileError!bool {
3625436152
3625536153 .func_type => true,
3625636154
36257 .simple_type => |t| return switch (t) {
36155 .simple_type => |t| switch (t) {
3625836156 .f16,
3625936157 .f32,
3626036158 .f64,
......@@ -36272,9 +36170,11 @@ pub fn typeRequiresComptime(sema: *Sema, ty: Type) CompileError!bool {
3627236170 .c_longlong,
3627336171 .c_ulonglong,
3627436172 .c_longdouble,
36173 .anyopaque,
3627536174 .bool,
3627636175 .void,
3627736176 .anyerror,
36177 .adhoc_inferred_error_set,
3627836178 .noreturn,
3627936179 .generic_poison,
3628036180 .atomic_order,
......@@ -36287,10 +36187,8 @@ pub fn typeRequiresComptime(sema: *Sema, ty: Type) CompileError!bool {
3628736187 .prefetch_options,
3628836188 .export_options,
3628936189 .extern_options,
36290 .adhoc_inferred_error_set,
3629136190 => false,
3629236191
36293 .anyopaque,
3629436192 .type,
3629536193 .comptime_int,
3629636194 .comptime_float,
......@@ -36335,30 +36233,31 @@ pub fn typeRequiresComptime(sema: *Sema, ty: Type) CompileError!bool {
3633536233 },
3633636234
3633736235 .union_type => |union_type| {
36338 const union_obj = mod.unionPtr(union_type.index);
36339 switch (union_obj.requires_comptime) {
36236 switch (union_type.flagsPtr(ip).requires_comptime) {
3634036237 .no, .wip => return false,
3634136238 .yes => return true,
3634236239 .unknown => {
36343 if (union_obj.status == .field_types_wip)
36240 if (union_type.flagsPtr(ip).status == .field_types_wip)
3634436241 return false;
3634536242
36346 try sema.resolveTypeFieldsUnion(ty, union_obj);
36243 try sema.resolveTypeFieldsUnion(ty, union_type);
36244 const union_obj = ip.loadUnionType(union_type);
3634736245
36348 union_obj.requires_comptime = .wip;
36349 for (union_obj.fields.values()) |field| {
36350 if (try sema.typeRequiresComptime(field.ty)) {
36351 union_obj.requires_comptime = .yes;
36246 union_obj.flagsPtr(ip).requires_comptime = .wip;
36247 for (0..union_obj.field_types.len) |field_index| {
36248 const field_ty = union_obj.field_types.get(ip)[field_index];
36249 if (try sema.typeRequiresComptime(field_ty.toType())) {
36250 union_obj.flagsPtr(ip).requires_comptime = .yes;
3635236251 return true;
3635336252 }
3635436253 }
36355 union_obj.requires_comptime = .no;
36254 union_obj.flagsPtr(ip).requires_comptime = .no;
3635636255 return false;
3635736256 },
3635836257 }
3635936258 },
3636036259
36361 .opaque_type => true,
36260 .opaque_type => false,
3636236261 .enum_type => |enum_type| try sema.typeRequiresComptime(enum_type.tag_ty.toType()),
3636336262
3636436263 // values, not types
......@@ -36404,12 +36303,15 @@ fn typeAbiAlignment(sema: *Sema, ty: Type) CompileError!u32 {
3640436303}
3640536304
3640636305/// Not valid to call for packed unions.
36407/// Keep implementation in sync with `Module.Union.Field.normalAlignment`.
36408fn unionFieldAlignment(sema: *Sema, field: Module.Union.Field) !u32 {
36409 return @as(u32, @intCast(if (field.ty.isNoReturn(sema.mod))
36410 0
36411 else
36412 field.abi_align.toByteUnitsOptional() orelse try sema.typeAbiAlignment(field.ty)));
36306/// Keep implementation in sync with `Module.unionFieldNormalAlignment`.
36307/// TODO: this returns alignment in byte units should should be a u64
36308fn unionFieldAlignment(sema: *Sema, u: InternPool.UnionType, field_index: u32) !u32 {
36309 const mod = sema.mod;
36310 const ip = &mod.intern_pool;
36311 if (u.fieldAlign(ip, field_index).toByteUnitsOptional()) |a| return @intCast(a);
36312 const field_ty = u.field_types.get(ip)[field_index].toType();
36313 if (field_ty.isNoReturn(sema.mod)) return 0;
36314 return @intCast(try sema.typeAbiAlignment(field_ty));
3641336315}
3641436316
3641536317/// Keep implementation in sync with `Module.Struct.Field.alignment`.
......@@ -36459,11 +36361,12 @@ fn unionFieldIndex(
3645936361 field_src: LazySrcLoc,
3646036362) !u32 {
3646136363 const mod = sema.mod;
36364 const ip = &mod.intern_pool;
3646236365 try sema.resolveTypeFields(union_ty);
3646336366 const union_obj = mod.typeToUnion(union_ty).?;
36464 const field_index_usize = union_obj.fields.getIndex(field_name) orelse
36367 const field_index = union_obj.nameIndex(ip, field_name) orelse
3646536368 return sema.failWithBadUnionFieldAccess(block, union_obj, field_src, field_name);
36466 return @as(u32, @intCast(field_index_usize));
36369 return @intCast(field_index);
3646736370}
3646836371
3646936372fn structFieldIndex(
src/TypedValue.zig+2-2
......@@ -88,7 +88,7 @@ pub fn print(
8888 try writer.writeAll(".{ ");
8989
9090 try print(.{
91 .ty = mod.unionPtr(ip.indexToKey(ty.toIntern()).union_type.index).tag_ty,
91 .ty = ip.indexToKey(ty.toIntern()).union_type.enum_tag_ty.toType(),
9292 .val = union_val.tag,
9393 }, writer, level - 1, mod);
9494 try writer.writeAll(" = ");
......@@ -357,7 +357,7 @@ pub fn print(
357357 try writer.print(".{i}", .{field_name.fmt(ip)});
358358 },
359359 .Union => {
360 const field_name = container_ty.unionFields(mod).keys()[@as(usize, @intCast(field.index))];
360 const field_name = mod.typeToUnion(container_ty).?.field_names.get(ip)[@intCast(field.index)];
361361 try writer.print(".{i}", .{field_name.fmt(ip)});
362362 },
363363 .Pointer => {
src/Zir.zig+2-1
......@@ -2956,7 +2956,8 @@ pub const Inst = struct {
29562956 /// true | true | union(enum(T)) { }
29572957 /// true | false | union(T) { }
29582958 auto_enum_tag: bool,
2959 _: u6 = undefined,
2959 any_aligned_fields: bool,
2960 _: u5 = undefined,
29602961 };
29612962 };
29622963
src/arch/aarch64/abi.zig+8-6
......@@ -75,14 +75,15 @@ pub fn classifyType(ty: Type, mod: *Module) Class {
7575
7676const sret_float_count = 4;
7777fn countFloats(ty: Type, mod: *Module, maybe_float_bits: *?u16) u8 {
78 const ip = &mod.intern_pool;
7879 const target = mod.getTarget();
7980 const invalid = std.math.maxInt(u8);
8081 switch (ty.zigTypeTag(mod)) {
8182 .Union => {
82 const fields = ty.unionFields(mod);
83 const union_obj = mod.typeToUnion(ty).?;
8384 var max_count: u8 = 0;
84 for (fields.values()) |field| {
85 const field_count = countFloats(field.ty, mod, maybe_float_bits);
85 for (union_obj.field_types.get(ip)) |field_ty| {
86 const field_count = countFloats(field_ty.toType(), mod, maybe_float_bits);
8687 if (field_count == invalid) return invalid;
8788 if (field_count > max_count) max_count = field_count;
8889 if (max_count > sret_float_count) return invalid;
......@@ -116,11 +117,12 @@ fn countFloats(ty: Type, mod: *Module, maybe_float_bits: *?u16) u8 {
116117}
117118
118119pub fn getFloatArrayType(ty: Type, mod: *Module) ?Type {
120 const ip = &mod.intern_pool;
119121 switch (ty.zigTypeTag(mod)) {
120122 .Union => {
121 const fields = ty.unionFields(mod);
122 for (fields.values()) |field| {
123 if (getFloatArrayType(field.ty, mod)) |some| return some;
123 const union_obj = mod.typeToUnion(ty).?;
124 for (union_obj.field_types.get(ip)) |field_ty| {
125 if (getFloatArrayType(field_ty.toType(), mod)) |some| return some;
124126 }
125127 return null;
126128 },
src/arch/arm/abi.zig+11-6
......@@ -29,6 +29,7 @@ pub fn classifyType(ty: Type, mod: *Module, ctx: Context) Class {
2929
3030 var maybe_float_bits: ?u16 = null;
3131 const max_byval_size = 512;
32 const ip = &mod.intern_pool;
3233 switch (ty.zigTypeTag(mod)) {
3334 .Struct => {
3435 const bit_size = ty.bitSize(mod);
......@@ -54,7 +55,8 @@ pub fn classifyType(ty: Type, mod: *Module, ctx: Context) Class {
5455 },
5556 .Union => {
5657 const bit_size = ty.bitSize(mod);
57 if (ty.containerLayout(mod) == .Packed) {
58 const union_obj = mod.typeToUnion(ty).?;
59 if (union_obj.getLayout(ip) == .Packed) {
5860 if (bit_size > 64) return .memory;
5961 return .byval;
6062 }
......@@ -62,8 +64,10 @@ pub fn classifyType(ty: Type, mod: *Module, ctx: Context) Class {
6264 const float_count = countFloats(ty, mod, &maybe_float_bits);
6365 if (float_count <= byval_float_count) return .byval;
6466
65 for (ty.unionFields(mod).values()) |field| {
66 if (field.ty.bitSize(mod) > 32 or field.normalAlignment(mod) > 32) {
67 for (union_obj.field_types.get(ip), 0..) |field_ty, field_index| {
68 if (field_ty.toType().bitSize(mod) > 32 or
69 mod.unionFieldNormalAlignment(union_obj, @intCast(field_index)) > 32)
70 {
6771 return Class.arrSize(bit_size, 64);
6872 }
6973 }
......@@ -117,14 +121,15 @@ pub fn classifyType(ty: Type, mod: *Module, ctx: Context) Class {
117121
118122const byval_float_count = 4;
119123fn countFloats(ty: Type, mod: *Module, maybe_float_bits: *?u16) u32 {
124 const ip = &mod.intern_pool;
120125 const target = mod.getTarget();
121126 const invalid = std.math.maxInt(u32);
122127 switch (ty.zigTypeTag(mod)) {
123128 .Union => {
124 const fields = ty.unionFields(mod);
129 const union_obj = mod.typeToUnion(ty).?;
125130 var max_count: u32 = 0;
126 for (fields.values()) |field| {
127 const field_count = countFloats(field.ty, mod, maybe_float_bits);
131 for (union_obj.field_types.get(ip)) |field_ty| {
132 const field_count = countFloats(field_ty.toType(), mod, maybe_float_bits);
128133 if (field_count == invalid) return invalid;
129134 if (field_count > max_count) max_count = field_count;
130135 if (max_count > byval_float_count) return invalid;
src/arch/wasm/CodeGen.zig+33-29
......@@ -1717,6 +1717,7 @@ fn arch(func: *const CodeGen) std.Target.Cpu.Arch {
17171717/// For a given `Type`, will return true when the type will be passed
17181718/// by reference, rather than by value
17191719fn isByRef(ty: Type, mod: *Module) bool {
1720 const ip = &mod.intern_pool;
17201721 const target = mod.getTarget();
17211722 switch (ty.zigTypeTag(mod)) {
17221723 .Type,
......@@ -1742,7 +1743,7 @@ fn isByRef(ty: Type, mod: *Module) bool {
17421743 => return ty.hasRuntimeBitsIgnoreComptime(mod),
17431744 .Union => {
17441745 if (mod.typeToUnion(ty)) |union_obj| {
1745 if (union_obj.layout == .Packed) {
1746 if (union_obj.getLayout(ip) == .Packed) {
17461747 return ty.abiSize(mod) > 8;
17471748 }
17481749 }
......@@ -2974,7 +2975,7 @@ fn lowerParentPtr(func: *CodeGen, ptr_val: Value, offset: u32) InnerError!WValue
29742975 .Union => switch (parent_ty.containerLayout(mod)) {
29752976 .Packed => 0,
29762977 else => blk: {
2977 const layout: Module.Union.Layout = parent_ty.unionGetLayout(mod);
2978 const layout: Module.UnionLayout = parent_ty.unionGetLayout(mod);
29782979 if (layout.payload_size == 0) break :blk 0;
29792980 if (layout.payload_align > layout.tag_align) break :blk 0;
29802981
......@@ -3058,8 +3059,9 @@ fn toTwosComplement(value: anytype, bits: u7) std.meta.Int(.unsigned, @typeInfo(
30583059
30593060fn lowerConstant(func: *CodeGen, arg_val: Value, ty: Type) InnerError!WValue {
30603061 const mod = func.bin_file.base.options.module.?;
3062 const ip = &mod.intern_pool;
30613063 var val = arg_val;
3062 switch (mod.intern_pool.indexToKey(val.ip_index)) {
3064 switch (ip.indexToKey(val.ip_index)) {
30633065 .runtime_value => |rt| val = rt.val.toValue(),
30643066 else => {},
30653067 }
......@@ -3110,7 +3112,7 @@ fn lowerConstant(func: *CodeGen, arg_val: Value, ty: Type) InnerError!WValue {
31103112 => unreachable, // comptime-only types
31113113 };
31123114
3113 switch (mod.intern_pool.indexToKey(val.ip_index)) {
3115 switch (ip.indexToKey(val.ip_index)) {
31143116 .int_type,
31153117 .ptr_type,
31163118 .array_type,
......@@ -3198,7 +3200,7 @@ fn lowerConstant(func: *CodeGen, arg_val: Value, ty: Type) InnerError!WValue {
31983200 return func.fail("Wasm TODO: lowerConstant error union with non-zero-bit payload type", .{});
31993201 },
32003202 .enum_tag => |enum_tag| {
3201 const int_tag_ty = mod.intern_pool.typeOf(enum_tag.int);
3203 const int_tag_ty = ip.typeOf(enum_tag.int);
32023204 return func.lowerConstant(enum_tag.int.toValue(), int_tag_ty.toType());
32033205 },
32043206 .float => |float| switch (float.storage) {
......@@ -3210,7 +3212,7 @@ fn lowerConstant(func: *CodeGen, arg_val: Value, ty: Type) InnerError!WValue {
32103212 .ptr => |ptr| switch (ptr.addr) {
32113213 .decl => |decl| return func.lowerDeclRefValue(.{ .ty = ty, .val = val }, decl, 0),
32123214 .mut_decl => |mut_decl| return func.lowerDeclRefValue(.{ .ty = ty, .val = val }, mut_decl.decl, 0),
3213 .int => |int| return func.lowerConstant(int.toValue(), mod.intern_pool.typeOf(int).toType()),
3215 .int => |int| return func.lowerConstant(int.toValue(), ip.typeOf(int).toType()),
32143216 .opt_payload, .elem, .field => return func.lowerParentPtr(val, 0),
32153217 else => return func.fail("Wasm TODO: lowerConstant for other const addr tag {}", .{ptr.addr}),
32163218 },
......@@ -3224,7 +3226,7 @@ fn lowerConstant(func: *CodeGen, arg_val: Value, ty: Type) InnerError!WValue {
32243226 } else {
32253227 return WValue{ .imm32 = @intFromBool(!val.isNull(mod)) };
32263228 },
3227 .aggregate => switch (mod.intern_pool.indexToKey(ty.ip_index)) {
3229 .aggregate => switch (ip.indexToKey(ty.ip_index)) {
32283230 .array_type => return func.fail("Wasm TODO: LowerConstant for {}", .{ty.fmt(mod)}),
32293231 .vector_type => {
32303232 assert(determineSimdStoreStrategy(ty, mod) == .direct);
......@@ -3245,11 +3247,12 @@ fn lowerConstant(func: *CodeGen, arg_val: Value, ty: Type) InnerError!WValue {
32453247 },
32463248 else => unreachable,
32473249 },
3248 .un => |union_obj| {
3250 .un => |un| {
32493251 // in this case we have a packed union which will not be passed by reference.
3250 const field_index = ty.unionTagFieldIndex(union_obj.tag.toValue(), func.bin_file.base.options.module.?).?;
3251 const field_ty = ty.unionFields(mod).values()[field_index].ty;
3252 return func.lowerConstant(union_obj.val.toValue(), field_ty);
3252 const union_obj = mod.typeToUnion(ty).?;
3253 const field_index = mod.unionTagFieldIndex(union_obj, un.tag.toValue()).?;
3254 const field_ty = union_obj.field_types.get(ip)[field_index].toType();
3255 return func.lowerConstant(un.val.toValue(), field_ty);
32533256 },
32543257 .memoized_call => unreachable,
32553258 }
......@@ -5163,6 +5166,7 @@ fn airAggregateInit(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
51635166
51645167fn airUnionInit(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
51655168 const mod = func.bin_file.base.options.module.?;
5169 const ip = &mod.intern_pool;
51665170 const ty_pl = func.air.instructions.items(.data)[inst].ty_pl;
51675171 const extra = func.air.extraData(Air.UnionInit, ty_pl.payload).data;
51685172
......@@ -5170,8 +5174,8 @@ fn airUnionInit(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
51705174 const union_ty = func.typeOfIndex(inst);
51715175 const layout = union_ty.unionGetLayout(mod);
51725176 const union_obj = mod.typeToUnion(union_ty).?;
5173 const field = union_obj.fields.values()[extra.field_index];
5174 const field_name = union_obj.fields.keys()[extra.field_index];
5177 const field_ty = union_obj.field_types.get(ip)[extra.field_index].toType();
5178 const field_name = union_obj.field_names.get(ip)[extra.field_index];
51755179
51765180 const tag_int = blk: {
51775181 const tag_ty = union_ty.unionTagTypeHypothetical(mod);
......@@ -5191,24 +5195,24 @@ fn airUnionInit(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
51915195 const result_ptr = try func.allocStack(union_ty);
51925196 const payload = try func.resolveInst(extra.init);
51935197 if (layout.tag_align >= layout.payload_align) {
5194 if (isByRef(field.ty, mod)) {
5198 if (isByRef(field_ty, mod)) {
51955199 const payload_ptr = try func.buildPointerOffset(result_ptr, layout.tag_size, .new);
5196 try func.store(payload_ptr, payload, field.ty, 0);
5200 try func.store(payload_ptr, payload, field_ty, 0);
51975201 } else {
5198 try func.store(result_ptr, payload, field.ty, @as(u32, @intCast(layout.tag_size)));
5202 try func.store(result_ptr, payload, field_ty, @intCast(layout.tag_size));
51995203 }
52005204
52015205 if (layout.tag_size > 0) {
5202 try func.store(result_ptr, tag_int, union_obj.tag_ty, 0);
5206 try func.store(result_ptr, tag_int, union_obj.enum_tag_ty.toType(), 0);
52035207 }
52045208 } else {
5205 try func.store(result_ptr, payload, field.ty, 0);
5209 try func.store(result_ptr, payload, field_ty, 0);
52065210 if (layout.tag_size > 0) {
52075211 try func.store(
52085212 result_ptr,
52095213 tag_int,
5210 union_obj.tag_ty,
5211 @as(u32, @intCast(layout.payload_size)),
5214 union_obj.enum_tag_ty.toType(),
5215 @intCast(layout.payload_size),
52125216 );
52135217 }
52145218 }
......@@ -5216,18 +5220,18 @@ fn airUnionInit(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
52165220 } else {
52175221 const operand = try func.resolveInst(extra.init);
52185222 const union_int_type = try mod.intType(.unsigned, @as(u16, @intCast(union_ty.bitSize(mod))));
5219 if (field.ty.zigTypeTag(mod) == .Float) {
5220 const int_type = try mod.intType(.unsigned, @as(u16, @intCast(field.ty.bitSize(mod))));
5221 const bitcasted = try func.bitcast(field.ty, int_type, operand);
5223 if (field_ty.zigTypeTag(mod) == .Float) {
5224 const int_type = try mod.intType(.unsigned, @intCast(field_ty.bitSize(mod)));
5225 const bitcasted = try func.bitcast(field_ty, int_type, operand);
52225226 const casted = try func.trunc(bitcasted, int_type, union_int_type);
5223 break :result try casted.toLocal(func, field.ty);
5224 } else if (field.ty.isPtrAtRuntime(mod)) {
5225 const int_type = try mod.intType(.unsigned, @as(u16, @intCast(field.ty.bitSize(mod))));
5227 break :result try casted.toLocal(func, field_ty);
5228 } else if (field_ty.isPtrAtRuntime(mod)) {
5229 const int_type = try mod.intType(.unsigned, @intCast(field_ty.bitSize(mod)));
52265230 const casted = try func.intcast(operand, int_type, union_int_type);
5227 break :result try casted.toLocal(func, field.ty);
5231 break :result try casted.toLocal(func, field_ty);
52285232 }
5229 const casted = try func.intcast(operand, field.ty, union_int_type);
5230 break :result try casted.toLocal(func, field.ty);
5233 const casted = try func.intcast(operand, field_ty, union_int_type);
5234 break :result try casted.toLocal(func, field_ty);
52315235 }
52325236 };
52335237
src/arch/wasm/abi.zig+18-11
......@@ -6,6 +6,7 @@
66
77const std = @import("std");
88const Target = std.Target;
9const assert = std.debug.assert;
910
1011const Type = @import("../../type.zig").Type;
1112const Module = @import("../../Module.zig");
......@@ -22,6 +23,7 @@ const direct: [2]Class = .{ .direct, .none };
2223/// or returned as value within a wasm function.
2324/// When all elements result in `.none`, no value must be passed in or returned.
2425pub fn classifyType(ty: Type, mod: *Module) [2]Class {
26 const ip = &mod.intern_pool;
2527 const target = mod.getTarget();
2628 if (!ty.hasRuntimeBitsIgnoreComptime(mod)) return none;
2729 switch (ty.zigTypeTag(mod)) {
......@@ -56,22 +58,24 @@ pub fn classifyType(ty: Type, mod: *Module) [2]Class {
5658 .Bool => return direct,
5759 .Array => return memory,
5860 .Optional => {
59 std.debug.assert(ty.isPtrLikeOptional(mod));
61 assert(ty.isPtrLikeOptional(mod));
6062 return direct;
6163 },
6264 .Pointer => {
63 std.debug.assert(!ty.isSlice(mod));
65 assert(!ty.isSlice(mod));
6466 return direct;
6567 },
6668 .Union => {
67 if (ty.containerLayout(mod) == .Packed) {
69 const union_obj = mod.typeToUnion(ty).?;
70 if (union_obj.getLayout(ip) == .Packed) {
6871 if (ty.bitSize(mod) <= 64) return direct;
6972 return .{ .direct, .direct };
7073 }
7174 const layout = ty.unionGetLayout(mod);
72 std.debug.assert(layout.tag_size == 0);
73 if (ty.unionFields(mod).count() > 1) return memory;
74 return classifyType(ty.unionFields(mod).values()[0].ty, mod);
75 assert(layout.tag_size == 0);
76 if (union_obj.field_names.len > 1) return memory;
77 const first_field_ty = union_obj.field_types.get(ip)[0].toType();
78 return classifyType(first_field_ty, mod);
7579 },
7680 .ErrorUnion,
7781 .Frame,
......@@ -94,6 +98,7 @@ pub fn classifyType(ty: Type, mod: *Module) [2]Class {
9498/// Asserts given type can be represented as scalar, such as
9599/// a struct with a single scalar field.
96100pub fn scalarType(ty: Type, mod: *Module) Type {
101 const ip = &mod.intern_pool;
97102 switch (ty.zigTypeTag(mod)) {
98103 .Struct => {
99104 switch (ty.containerLayout(mod)) {
......@@ -102,20 +107,22 @@ pub fn scalarType(ty: Type, mod: *Module) Type {
102107 return scalarType(struct_obj.backing_int_ty, mod);
103108 },
104109 else => {
105 std.debug.assert(ty.structFieldCount(mod) == 1);
110 assert(ty.structFieldCount(mod) == 1);
106111 return scalarType(ty.structFieldType(0, mod), mod);
107112 },
108113 }
109114 },
110115 .Union => {
111 if (ty.containerLayout(mod) != .Packed) {
112 const layout = ty.unionGetLayout(mod);
116 const union_obj = mod.typeToUnion(ty).?;
117 if (union_obj.getLayout(ip) != .Packed) {
118 const layout = mod.getUnionLayout(union_obj);
113119 if (layout.payload_size == 0 and layout.tag_size != 0) {
114120 return scalarType(ty.unionTagTypeSafety(mod).?, mod);
115121 }
116 std.debug.assert(ty.unionFields(mod).count() == 1);
122 assert(union_obj.field_types.len == 1);
117123 }
118 return scalarType(ty.unionFields(mod).values()[0].ty, mod);
124 const first_field_ty = union_obj.field_types.get(ip)[0].toType();
125 return scalarType(first_field_ty, mod);
119126 },
120127 else => return ty,
121128 }
src/arch/x86_64/CodeGen.zig+3-2
......@@ -11534,6 +11534,7 @@ fn airAggregateInit(self: *Self, inst: Air.Inst.Index) !void {
1153411534
1153511535fn airUnionInit(self: *Self, inst: Air.Inst.Index) !void {
1153611536 const mod = self.bin_file.options.module.?;
11537 const ip = &mod.intern_pool;
1153711538 const ty_pl = self.air.instructions.items(.data)[inst].ty_pl;
1153811539 const extra = self.air.extraData(Air.UnionInit, ty_pl.payload).data;
1153911540 const result: MCValue = result: {
......@@ -11553,8 +11554,8 @@ fn airUnionInit(self: *Self, inst: Air.Inst.Index) !void {
1155311554 const dst_mcv = try self.allocRegOrMem(inst, false);
1155411555
1155511556 const union_obj = mod.typeToUnion(union_ty).?;
11556 const field_name = union_obj.fields.keys()[extra.field_index];
11557 const tag_ty = union_obj.tag_ty;
11557 const field_name = union_obj.field_names.get(ip)[extra.field_index];
11558 const tag_ty = union_obj.enum_tag_ty.toType();
1155811559 const field_index = tag_ty.enumFieldIndex(field_name, mod).?;
1155911560 const tag_val = try mod.enumValueFieldIndex(tag_ty, field_index);
1156011561 const tag_int_val = try tag_val.intFromEnum(tag_ty, mod);
src/arch/x86_64/abi.zig+8-7
......@@ -69,6 +69,7 @@ pub const Context = enum { ret, arg, other };
6969/// There are a maximum of 8 possible return slots. Returned values are in
7070/// the beginning of the array; unused slots are filled with .none.
7171pub fn classifySystemV(ty: Type, mod: *Module, ctx: Context) [8]Class {
72 const ip = &mod.intern_pool;
7273 const target = mod.getTarget();
7374 const memory_class = [_]Class{
7475 .memory, .none, .none, .none,
......@@ -328,8 +329,9 @@ pub fn classifySystemV(ty: Type, mod: *Module, ctx: Context) [8]Class {
328329 // it contains unaligned fields, it has class MEMORY"
329330 // "If the size of the aggregate exceeds a single eightbyte, each is classified
330331 // separately.".
331 const ty_size = ty.abiSize(mod);
332 if (ty.containerLayout(mod) == .Packed) {
332 const union_obj = mod.typeToUnion(ty).?;
333 const ty_size = mod.unionAbiSize(union_obj);
334 if (union_obj.getLayout(ip) == .Packed) {
333335 assert(ty_size <= 128);
334336 result[0] = .integer;
335337 if (ty_size > 64) result[1] = .integer;
......@@ -338,15 +340,14 @@ pub fn classifySystemV(ty: Type, mod: *Module, ctx: Context) [8]Class {
338340 if (ty_size > 64)
339341 return memory_class;
340342
341 const fields = ty.unionFields(mod);
342 for (fields.values()) |field| {
343 if (field.abi_align != .none) {
344 if (field.abi_align.toByteUnitsOptional().? < field.ty.abiAlignment(mod)) {
343 for (union_obj.field_types.get(ip), 0..) |field_ty, field_index| {
344 if (union_obj.fieldAlign(ip, @intCast(field_index)).toByteUnitsOptional()) |a| {
345 if (a < field_ty.toType().abiAlignment(mod)) {
345346 return memory_class;
346347 }
347348 }
348349 // Combine this field with the previous one.
349 const field_class = classifySystemV(field.ty, mod, .other);
350 const field_class = classifySystemV(field_ty.toType(), mod, .other);
350351 for (&result, 0..) |*result_item, i| {
351352 const field_item = field_class[i];
352353 // "If both classes are equal, this is the resulting class."
src/codegen.zig+11-11
......@@ -185,8 +185,9 @@ pub fn generateSymbol(
185185 defer tracy.end();
186186
187187 const mod = bin_file.options.module.?;
188 const ip = &mod.intern_pool;
188189 var typed_value = arg_tv;
189 switch (mod.intern_pool.indexToKey(typed_value.val.toIntern())) {
190 switch (ip.indexToKey(typed_value.val.toIntern())) {
190191 .runtime_value => |rt| typed_value.val = rt.val.toValue(),
191192 else => {},
192193 }
......@@ -205,7 +206,7 @@ pub fn generateSymbol(
205206 return .ok;
206207 }
207208
208 switch (mod.intern_pool.indexToKey(typed_value.val.toIntern())) {
209 switch (ip.indexToKey(typed_value.val.toIntern())) {
209210 .int_type,
210211 .ptr_type,
211212 .array_type,
......@@ -385,7 +386,7 @@ pub fn generateSymbol(
385386 try code.appendNTimes(0, padding);
386387 }
387388 },
388 .aggregate => |aggregate| switch (mod.intern_pool.indexToKey(typed_value.ty.toIntern())) {
389 .aggregate => |aggregate| switch (ip.indexToKey(typed_value.ty.toIntern())) {
389390 .array_type => |array_type| switch (aggregate.storage) {
390391 .bytes => |bytes| try code.appendSlice(bytes),
391392 .elems, .repeated_elem => {
......@@ -442,7 +443,7 @@ pub fn generateSymbol(
442443 if (!field_ty.toType().hasRuntimeBits(mod)) continue;
443444
444445 const field_val = switch (aggregate.storage) {
445 .bytes => |bytes| try mod.intern_pool.get(mod.gpa, .{ .int = .{
446 .bytes => |bytes| try ip.get(mod.gpa, .{ .int = .{
446447 .ty = field_ty,
447448 .storage = .{ .u64 = bytes[index] },
448449 } }),
......@@ -484,7 +485,7 @@ pub fn generateSymbol(
484485 const field_ty = field.ty;
485486
486487 const field_val = switch (aggregate.storage) {
487 .bytes => |bytes| try mod.intern_pool.get(mod.gpa, .{ .int = .{
488 .bytes => |bytes| try ip.get(mod.gpa, .{ .int = .{
488489 .ty = field_ty.toIntern(),
489490 .storage = .{ .u64 = bytes[index] },
490491 } }),
......@@ -522,8 +523,8 @@ pub fn generateSymbol(
522523
523524 if (!field_ty.hasRuntimeBits(mod)) continue;
524525
525 const field_val = switch (mod.intern_pool.indexToKey(typed_value.val.toIntern()).aggregate.storage) {
526 .bytes => |bytes| try mod.intern_pool.get(mod.gpa, .{ .int = .{
526 const field_val = switch (ip.indexToKey(typed_value.val.toIntern()).aggregate.storage) {
527 .bytes => |bytes| try ip.get(mod.gpa, .{ .int = .{
527528 .ty = field_ty.toIntern(),
528529 .storage = .{ .u64 = bytes[field_offset.field] },
529530 } }),
......@@ -570,10 +571,9 @@ pub fn generateSymbol(
570571 }
571572 }
572573
573 const union_ty = mod.typeToUnion(typed_value.ty).?;
574 const union_obj = mod.typeToUnion(typed_value.ty).?;
574575 const field_index = typed_value.ty.unionTagFieldIndex(un.tag.toValue(), mod).?;
575 assert(union_ty.haveFieldTypes());
576 const field_ty = union_ty.fields.values()[field_index].ty;
576 const field_ty = union_obj.field_types.get(ip)[field_index].toType();
577577 if (!field_ty.hasRuntimeBits(mod)) {
578578 try code.appendNTimes(0xaa, math.cast(usize, layout.payload_size) orelse return error.Overflow);
579579 } else {
......@@ -593,7 +593,7 @@ pub fn generateSymbol(
593593
594594 if (layout.tag_size > 0 and layout.tag_align < layout.payload_align) {
595595 switch (try generateSymbol(bin_file, src_loc, .{
596 .ty = union_ty.tag_ty,
596 .ty = union_obj.enum_tag_ty.toType(),
597597 .val = un.tag.toValue(),
598598 }, code, debug_output, reloc_info)) {
599599 .ok => {},
src/codegen/c.zig+54-47
......@@ -708,8 +708,10 @@ pub const DeclGen = struct {
708708 location: ValueRenderLocation,
709709 ) error{ OutOfMemory, AnalysisFail }!void {
710710 const mod = dg.module;
711 const ip = &mod.intern_pool;
712
711713 var val = arg_val;
712 switch (mod.intern_pool.indexToKey(val.ip_index)) {
714 switch (ip.indexToKey(val.ip_index)) {
713715 .runtime_value => |rt| val = rt.val.toValue(),
714716 else => {},
715717 }
......@@ -836,9 +838,10 @@ pub const DeclGen = struct {
836838 if (layout.tag_size != 0) try writer.writeByte(',');
837839 try writer.writeAll(" .payload = {");
838840 }
839 for (ty.unionFields(mod).values()) |field| {
840 if (!field.ty.hasRuntimeBits(mod)) continue;
841 try dg.renderValue(writer, field.ty, val, initializer_type);
841 const union_obj = mod.typeToUnion(ty).?;
842 for (union_obj.field_types.get(ip)) |field_ty| {
843 if (!field_ty.toType().hasRuntimeBits(mod)) continue;
844 try dg.renderValue(writer, field_ty.toType(), val, initializer_type);
842845 break;
843846 }
844847 if (ty.unionTagTypeSafety(mod)) |_| try writer.writeByte('}');
......@@ -912,7 +915,7 @@ pub const DeclGen = struct {
912915 unreachable;
913916 }
914917
915 switch (mod.intern_pool.indexToKey(val.ip_index)) {
918 switch (ip.indexToKey(val.ip_index)) {
916919 // types, not values
917920 .int_type,
918921 .ptr_type,
......@@ -962,7 +965,7 @@ pub const DeclGen = struct {
962965 },
963966 },
964967 .err => |err| try writer.print("zig_error_{}", .{
965 fmtIdent(mod.intern_pool.stringToSlice(err.name)),
968 fmtIdent(ip.stringToSlice(err.name)),
966969 }),
967970 .error_union => |error_union| {
968971 const payload_ty = ty.errorUnionPayload(mod);
......@@ -1024,8 +1027,8 @@ pub const DeclGen = struct {
10241027 try writer.writeAll(" }");
10251028 },
10261029 .enum_tag => {
1027 const enum_tag = mod.intern_pool.indexToKey(val.ip_index).enum_tag;
1028 const int_tag_ty = mod.intern_pool.typeOf(enum_tag.int);
1030 const enum_tag = ip.indexToKey(val.ip_index).enum_tag;
1031 const int_tag_ty = ip.typeOf(enum_tag.int);
10291032 try dg.renderValue(writer, int_tag_ty.toType(), enum_tag.int.toValue(), location);
10301033 },
10311034 .float => {
......@@ -1205,7 +1208,7 @@ pub const DeclGen = struct {
12051208 try dg.renderValue(writer, Type.bool, is_null_val, initializer_type);
12061209 try writer.writeAll(" }");
12071210 },
1208 .aggregate => switch (mod.intern_pool.indexToKey(ty.ip_index)) {
1211 .aggregate => switch (ip.indexToKey(ty.ip_index)) {
12091212 .array_type, .vector_type => {
12101213 if (location == .FunctionArgument) {
12111214 try writer.writeByte('(');
......@@ -1278,8 +1281,8 @@ pub const DeclGen = struct {
12781281
12791282 if (!empty) try writer.writeByte(',');
12801283
1281 const field_val = switch (mod.intern_pool.indexToKey(val.ip_index).aggregate.storage) {
1282 .bytes => |bytes| try mod.intern_pool.get(mod.gpa, .{ .int = .{
1284 const field_val = switch (ip.indexToKey(val.ip_index).aggregate.storage) {
1285 .bytes => |bytes| try ip.get(mod.gpa, .{ .int = .{
12831286 .ty = field_ty,
12841287 .storage = .{ .u64 = bytes[field_i] },
12851288 } }),
......@@ -1309,8 +1312,8 @@ pub const DeclGen = struct {
13091312 if (!field.ty.hasRuntimeBitsIgnoreComptime(mod)) continue;
13101313
13111314 if (!empty) try writer.writeByte(',');
1312 const field_val = switch (mod.intern_pool.indexToKey(val.ip_index).aggregate.storage) {
1313 .bytes => |bytes| try mod.intern_pool.get(mod.gpa, .{ .int = .{
1315 const field_val = switch (ip.indexToKey(val.ip_index).aggregate.storage) {
1316 .bytes => |bytes| try ip.get(mod.gpa, .{ .int = .{
13141317 .ty = field.ty.toIntern(),
13151318 .storage = .{ .u64 = bytes[field_i] },
13161319 } }),
......@@ -1358,8 +1361,8 @@ pub const DeclGen = struct {
13581361 if (field.is_comptime) continue;
13591362 if (!field.ty.hasRuntimeBitsIgnoreComptime(mod)) continue;
13601363
1361 const field_val = switch (mod.intern_pool.indexToKey(val.ip_index).aggregate.storage) {
1362 .bytes => |bytes| try mod.intern_pool.get(mod.gpa, .{ .int = .{
1364 const field_val = switch (ip.indexToKey(val.ip_index).aggregate.storage) {
1365 .bytes => |bytes| try ip.get(mod.gpa, .{ .int = .{
13631366 .ty = field.ty.toIntern(),
13641367 .storage = .{ .u64 = bytes[field_i] },
13651368 } }),
......@@ -1400,8 +1403,8 @@ pub const DeclGen = struct {
14001403 try dg.renderType(writer, ty);
14011404 try writer.writeByte(')');
14021405
1403 const field_val = switch (mod.intern_pool.indexToKey(val.ip_index).aggregate.storage) {
1404 .bytes => |bytes| try mod.intern_pool.get(mod.gpa, .{ .int = .{
1406 const field_val = switch (ip.indexToKey(val.ip_index).aggregate.storage) {
1407 .bytes => |bytes| try ip.get(mod.gpa, .{ .int = .{
14051408 .ty = field.ty.toIntern(),
14061409 .storage = .{ .u64 = bytes[field_i] },
14071410 } }),
......@@ -1435,10 +1438,11 @@ pub const DeclGen = struct {
14351438 try writer.writeByte(')');
14361439 }
14371440
1438 const field_i = ty.unionTagFieldIndex(un.tag.toValue(), mod).?;
1439 const field_ty = ty.unionFields(mod).values()[field_i].ty;
1440 const field_name = ty.unionFields(mod).keys()[field_i];
1441 if (ty.containerLayout(mod) == .Packed) {
1441 const union_obj = mod.typeToUnion(ty).?;
1442 const field_i = mod.unionTagFieldIndex(union_obj, un.tag.toValue()).?;
1443 const field_ty = union_obj.field_types.get(ip)[field_i].toType();
1444 const field_name = union_obj.field_names.get(ip)[field_i];
1445 if (union_obj.getLayout(ip) == .Packed) {
14421446 if (field_ty.hasRuntimeBits(mod)) {
14431447 if (field_ty.isPtrAtRuntime(mod)) {
14441448 try writer.writeByte('(');
......@@ -1458,7 +1462,7 @@ pub const DeclGen = struct {
14581462
14591463 try writer.writeByte('{');
14601464 if (ty.unionTagTypeSafety(mod)) |tag_ty| {
1461 const layout = ty.unionGetLayout(mod);
1465 const layout = mod.getUnionLayout(union_obj);
14621466 if (layout.tag_size != 0) {
14631467 try writer.writeAll(" .tag = ");
14641468 try dg.renderValue(writer, tag_ty, un.tag.toValue(), initializer_type);
......@@ -1468,12 +1472,12 @@ pub const DeclGen = struct {
14681472 try writer.writeAll(" .payload = {");
14691473 }
14701474 if (field_ty.hasRuntimeBits(mod)) {
1471 try writer.print(" .{ } = ", .{fmtIdent(mod.intern_pool.stringToSlice(field_name))});
1475 try writer.print(" .{ } = ", .{fmtIdent(ip.stringToSlice(field_name))});
14721476 try dg.renderValue(writer, field_ty, un.val.toValue(), initializer_type);
14731477 try writer.writeByte(' ');
1474 } else for (ty.unionFields(mod).values()) |field| {
1475 if (!field.ty.hasRuntimeBits(mod)) continue;
1476 try dg.renderValue(writer, field.ty, Value.undef, initializer_type);
1478 } else for (union_obj.field_types.get(ip)) |this_field_ty| {
1479 if (!this_field_ty.toType().hasRuntimeBits(mod)) continue;
1480 try dg.renderValue(writer, this_field_ty.toType(), Value.undef, initializer_type);
14771481 break;
14781482 }
14791483 if (ty.unionTagTypeSafety(mod)) |_| try writer.writeByte('}');
......@@ -5237,22 +5241,25 @@ fn fieldLocation(
52375241 else
52385242 .begin,
52395243 },
5240 .Union => switch (container_ty.containerLayout(mod)) {
5241 .Auto, .Extern => {
5242 const field_ty = container_ty.structFieldType(field_index, mod);
5243 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod))
5244 return if (container_ty.unionTagTypeSafety(mod) != null and
5245 !container_ty.unionHasAllZeroBitFieldTypes(mod))
5246 .{ .field = .{ .identifier = "payload" } }
5244 .Union => {
5245 const union_obj = mod.typeToUnion(container_ty).?;
5246 return switch (union_obj.getLayout(ip)) {
5247 .Auto, .Extern => {
5248 const field_ty = union_obj.field_types.get(ip)[field_index].toType();
5249 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod))
5250 return if (container_ty.unionTagTypeSafety(mod) != null and
5251 !container_ty.unionHasAllZeroBitFieldTypes(mod))
5252 .{ .field = .{ .identifier = "payload" } }
5253 else
5254 .begin;
5255 const field_name = union_obj.field_names.get(ip)[field_index];
5256 return .{ .field = if (container_ty.unionTagTypeSafety(mod)) |_|
5257 .{ .payload_identifier = ip.stringToSlice(field_name) }
52475258 else
5248 .begin;
5249 const field_name = container_ty.unionFields(mod).keys()[field_index];
5250 return .{ .field = if (container_ty.unionTagTypeSafety(mod)) |_|
5251 .{ .payload_identifier = ip.stringToSlice(field_name) }
5252 else
5253 .{ .identifier = ip.stringToSlice(field_name) } };
5254 },
5255 .Packed => .begin,
5259 .{ .identifier = ip.stringToSlice(field_name) } };
5260 },
5261 .Packed => .begin,
5262 };
52565263 },
52575264 .Pointer => switch (container_ty.ptrSize(mod)) {
52585265 .Slice => switch (field_index) {
......@@ -5479,8 +5486,8 @@ fn airStructFieldVal(f: *Function, inst: Air.Inst.Index) !CValue {
54795486 .{ .identifier = ip.stringToSlice(struct_ty.structFieldName(extra.field_index, mod)) },
54805487
54815488 .union_type => |union_type| field_name: {
5482 const union_obj = mod.unionPtr(union_type.index);
5483 if (union_obj.layout == .Packed) {
5489 const union_obj = ip.loadUnionType(union_type);
5490 if (union_obj.flagsPtr(ip).layout == .Packed) {
54845491 const operand_lval = if (struct_byval == .constant) blk: {
54855492 const operand_local = try f.allocLocal(inst, struct_ty);
54865493 try f.writeCValue(writer, operand_local, .Other);
......@@ -5505,8 +5512,8 @@ fn airStructFieldVal(f: *Function, inst: Air.Inst.Index) !CValue {
55055512
55065513 return local;
55075514 } else {
5508 const name = union_obj.fields.keys()[extra.field_index];
5509 break :field_name if (union_type.hasTag()) .{
5515 const name = union_obj.field_names.get(ip)[extra.field_index];
5516 break :field_name if (union_type.hasTag(ip)) .{
55105517 .payload_identifier = ip.stringToSlice(name),
55115518 } else .{
55125519 .identifier = ip.stringToSlice(name),
......@@ -6902,14 +6909,14 @@ fn airUnionInit(f: *Function, inst: Air.Inst.Index) !CValue {
69026909
69036910 const union_ty = f.typeOfIndex(inst);
69046911 const union_obj = mod.typeToUnion(union_ty).?;
6905 const field_name = union_obj.fields.keys()[extra.field_index];
6912 const field_name = union_obj.field_names.get(ip)[extra.field_index];
69066913 const payload_ty = f.typeOf(extra.init);
69076914 const payload = try f.resolveInst(extra.init);
69086915 try reap(f, inst, &.{extra.init});
69096916
69106917 const writer = f.object.writer();
69116918 const local = try f.allocLocal(inst, union_ty);
6912 if (union_obj.layout == .Packed) {
6919 if (union_obj.getLayout(ip) == .Packed) {
69136920 try f.writeCValue(writer, local, .Other);
69146921 try writer.writeAll(" = ");
69156922 try f.writeCValue(writer, payload, .Initializer);
src/codegen/c/type.zig+13-13
......@@ -303,7 +303,7 @@ pub const CType = extern union {
303303 }
304304 pub fn unionPayloadAlign(union_ty: Type, mod: *Module) AlignAs {
305305 const union_obj = mod.typeToUnion(union_ty).?;
306 const union_payload_align = union_obj.abiAlignment(mod, false);
306 const union_payload_align = mod.unionAbiAlignment(union_obj);
307307 return init(union_payload_align, union_payload_align);
308308 }
309309
......@@ -1499,7 +1499,7 @@ pub const CType = extern union {
14991499 if (lookup.isMutable()) {
15001500 for (0..switch (zig_ty_tag) {
15011501 .Struct => ty.structFieldCount(mod),
1502 .Union => ty.unionFields(mod).count(),
1502 .Union => mod.typeToUnion(ty).?.field_names.len,
15031503 else => unreachable,
15041504 }) |field_i| {
15051505 const field_ty = ty.structFieldType(field_i, mod);
......@@ -1581,7 +1581,7 @@ pub const CType = extern union {
15811581 var is_packed = false;
15821582 for (0..switch (zig_ty_tag) {
15831583 .Struct => ty.structFieldCount(mod),
1584 .Union => ty.unionFields(mod).count(),
1584 .Union => mod.typeToUnion(ty).?.field_names.len,
15851585 else => unreachable,
15861586 }) |field_i| {
15871587 const field_ty = ty.structFieldType(field_i, mod);
......@@ -1912,6 +1912,7 @@ pub const CType = extern union {
19121912 kind: Kind,
19131913 convert: Convert,
19141914 ) !CType {
1915 const ip = &mod.intern_pool;
19151916 const arena = store.arena.allocator();
19161917 switch (convert.value) {
19171918 .cty => |c| return c.copy(arena),
......@@ -1932,7 +1933,7 @@ pub const CType = extern union {
19321933 const zig_ty_tag = ty.zigTypeTag(mod);
19331934 const fields_len = switch (zig_ty_tag) {
19341935 .Struct => ty.structFieldCount(mod),
1935 .Union => ty.unionFields(mod).count(),
1936 .Union => mod.typeToUnion(ty).?.field_names.len,
19361937 else => unreachable,
19371938 };
19381939
......@@ -1956,9 +1957,9 @@ pub const CType = extern union {
19561957 .name = try if (ty.isSimpleTuple(mod))
19571958 std.fmt.allocPrintZ(arena, "f{}", .{field_i})
19581959 else
1959 arena.dupeZ(u8, mod.intern_pool.stringToSlice(switch (zig_ty_tag) {
1960 arena.dupeZ(u8, ip.stringToSlice(switch (zig_ty_tag) {
19601961 .Struct => ty.structFieldName(field_i, mod),
1961 .Union => ty.unionFields(mod).keys()[field_i],
1962 .Union => mod.typeToUnion(ty).?.field_names.get(ip)[field_i],
19621963 else => unreachable,
19631964 })),
19641965 .type = store.set.typeToIndex(field_ty, mod, switch (kind) {
......@@ -2015,7 +2016,6 @@ pub const CType = extern union {
20152016 .function,
20162017 .varargs_function,
20172018 => {
2018 const ip = &mod.intern_pool;
20192019 const info = mod.typeToFunc(ty).?;
20202020 assert(!info.is_generic);
20212021 const param_kind: Kind = switch (kind) {
......@@ -2068,6 +2068,7 @@ pub const CType = extern union {
20682068
20692069 pub fn eql(self: @This(), ty: Type, cty: CType) bool {
20702070 const mod = self.lookup.getModule();
2071 const ip = &mod.intern_pool;
20712072 switch (self.convert.value) {
20722073 .cty => |c| return c.eql(cty),
20732074 .tag => |t| {
......@@ -2088,7 +2089,7 @@ pub const CType = extern union {
20882089 var c_field_i: usize = 0;
20892090 for (0..switch (zig_ty_tag) {
20902091 .Struct => ty.structFieldCount(mod),
2091 .Union => ty.unionFields(mod).count(),
2092 .Union => mod.typeToUnion(ty).?.field_names.len,
20922093 else => unreachable,
20932094 }) |field_i| {
20942095 const field_ty = ty.structFieldType(field_i, mod);
......@@ -2108,9 +2109,9 @@ pub const CType = extern union {
21082109 if (ty.isSimpleTuple(mod))
21092110 std.fmt.bufPrintZ(&name_buf, "f{}", .{field_i}) catch unreachable
21102111 else
2111 mod.intern_pool.stringToSlice(switch (zig_ty_tag) {
2112 ip.stringToSlice(switch (zig_ty_tag) {
21122113 .Struct => ty.structFieldName(field_i, mod),
2113 .Union => ty.unionFields(mod).keys()[field_i],
2114 .Union => mod.typeToUnion(ty).?.field_names.get(ip)[field_i],
21142115 else => unreachable,
21152116 }),
21162117 mem.span(c_field.name),
......@@ -2149,7 +2150,6 @@ pub const CType = extern union {
21492150 => {
21502151 if (ty.zigTypeTag(mod) != .Fn) return false;
21512152
2152 const ip = &mod.intern_pool;
21532153 const info = mod.typeToFunc(ty).?;
21542154 assert(!info.is_generic);
21552155 const data = cty.cast(Payload.Function).?.data;
......@@ -2217,7 +2217,7 @@ pub const CType = extern union {
22172217 const zig_ty_tag = ty.zigTypeTag(mod);
22182218 for (0..switch (ty.zigTypeTag(mod)) {
22192219 .Struct => ty.structFieldCount(mod),
2220 .Union => ty.unionFields(mod).count(),
2220 .Union => mod.typeToUnion(ty).?.field_names.len,
22212221 else => unreachable,
22222222 }) |field_i| {
22232223 const field_ty = ty.structFieldType(field_i, mod);
......@@ -2235,7 +2235,7 @@ pub const CType = extern union {
22352235 else
22362236 mod.intern_pool.stringToSlice(switch (zig_ty_tag) {
22372237 .Struct => ty.structFieldName(field_i, mod),
2238 .Union => ty.unionFields(mod).keys()[field_i],
2238 .Union => mod.typeToUnion(ty).?.field_names.get(ip)[field_i],
22392239 else => unreachable,
22402240 }));
22412241 autoHash(hasher, AlignAs.fieldAlign(ty, field_i, mod).@"align");
src/codegen/llvm.zig+55-55
......@@ -2382,7 +2382,7 @@ pub const Object = struct {
23822382 break :blk fwd_decl;
23832383 };
23842384
2385 switch (mod.intern_pool.indexToKey(ty.toIntern())) {
2385 switch (ip.indexToKey(ty.toIntern())) {
23862386 .anon_struct_type => |tuple| {
23872387 var di_fields: std.ArrayListUnmanaged(*llvm.DIType) = .{};
23882388 defer di_fields.deinit(gpa);
......@@ -2401,7 +2401,7 @@ pub const Object = struct {
24012401 offset = field_offset + field_size;
24022402
24032403 const field_name = if (tuple.names.len != 0)
2404 mod.intern_pool.stringToSlice(tuple.names[i])
2404 ip.stringToSlice(tuple.names[i])
24052405 else
24062406 try std.fmt.allocPrintZ(gpa, "{d}", .{i});
24072407 defer if (tuple.names.len == 0) gpa.free(field_name);
......@@ -2491,7 +2491,7 @@ pub const Object = struct {
24912491 const field_offset = std.mem.alignForward(u64, offset, field_align);
24922492 offset = field_offset + field_size;
24932493
2494 const field_name = mod.intern_pool.stringToSlice(fields.keys()[field_and_index.index]);
2494 const field_name = ip.stringToSlice(fields.keys()[field_and_index.index]);
24952495
24962496 try di_fields.append(gpa, dib.createMemberType(
24972497 fwd_decl.toScope(),
......@@ -2546,8 +2546,8 @@ pub const Object = struct {
25462546 break :blk fwd_decl;
25472547 };
25482548
2549 const union_obj = mod.typeToUnion(ty).?;
2550 if (!union_obj.haveFieldTypes() or !ty.hasRuntimeBitsIgnoreComptime(mod)) {
2549 const union_type = ip.indexToKey(ty.toIntern()).union_type;
2550 if (!union_type.haveFieldTypes(ip) or !ty.hasRuntimeBitsIgnoreComptime(mod)) {
25512551 const union_di_ty = try o.makeEmptyNamespaceDIType(owner_decl_index);
25522552 dib.replaceTemporary(fwd_decl, union_di_ty);
25532553 // The recursive call to `lowerDebugType` via `makeEmptyNamespaceDIType`
......@@ -2556,10 +2556,11 @@ pub const Object = struct {
25562556 return union_di_ty;
25572557 }
25582558
2559 const layout = ty.unionGetLayout(mod);
2559 const union_obj = ip.loadUnionType(union_type);
2560 const layout = mod.getUnionLayout(union_obj);
25602561
25612562 if (layout.payload_size == 0) {
2562 const tag_di_ty = try o.lowerDebugType(union_obj.tag_ty, .full);
2563 const tag_di_ty = try o.lowerDebugType(union_obj.enum_tag_ty.toType(), .full);
25632564 const di_fields = [_]*llvm.DIType{tag_di_ty};
25642565 const full_di_ty = dib.createStructType(
25652566 compile_unit_scope,
......@@ -2586,22 +2587,20 @@ pub const Object = struct {
25862587 var di_fields: std.ArrayListUnmanaged(*llvm.DIType) = .{};
25872588 defer di_fields.deinit(gpa);
25882589
2589 try di_fields.ensureUnusedCapacity(gpa, union_obj.fields.count());
2590 try di_fields.ensureUnusedCapacity(gpa, union_obj.field_names.len);
25902591
2591 var it = union_obj.fields.iterator();
2592 while (it.next()) |kv| {
2593 const field_name = kv.key_ptr.*;
2594 const field = kv.value_ptr.*;
2592 for (0..union_obj.field_names.len) |field_index| {
2593 const field_ty = union_obj.field_types.get(ip)[field_index];
2594 if (!field_ty.toType().hasRuntimeBitsIgnoreComptime(mod)) continue;
25952595
2596 if (!field.ty.hasRuntimeBitsIgnoreComptime(mod)) continue;
2597
2598 const field_size = field.ty.abiSize(mod);
2599 const field_align = field.normalAlignment(mod);
2596 const field_size = field_ty.toType().abiSize(mod);
2597 const field_align = mod.unionFieldNormalAlignment(union_obj, @intCast(field_index));
26002598
2601 const field_di_ty = try o.lowerDebugType(field.ty, .full);
2599 const field_di_ty = try o.lowerDebugType(field_ty.toType(), .full);
2600 const field_name = union_obj.field_names.get(ip)[field_index];
26022601 di_fields.appendAssumeCapacity(dib.createMemberType(
26032602 fwd_decl.toScope(),
2604 mod.intern_pool.stringToSlice(field_name),
2603 ip.stringToSlice(field_name),
26052604 null, // file
26062605 0, // line
26072606 field_size * 8, // size in bits
......@@ -2659,7 +2658,7 @@ pub const Object = struct {
26592658 layout.tag_align * 8, // align in bits
26602659 tag_offset * 8, // offset in bits
26612660 0, // flags
2662 try o.lowerDebugType(union_obj.tag_ty, .full),
2661 try o.lowerDebugType(union_obj.enum_tag_ty.toType(), .full),
26632662 );
26642663
26652664 const payload_di = dib.createMemberType(
......@@ -3078,6 +3077,7 @@ pub const Object = struct {
30783077 fn lowerTypeInner(o: *Object, t: Type) Allocator.Error!Builder.Type {
30793078 const mod = o.module;
30803079 const target = mod.getTarget();
3080 const ip = &mod.intern_pool;
30813081 return switch (t.toIntern()) {
30823082 .u0_type, .i0_type => unreachable,
30833083 inline .u1_type,
......@@ -3172,7 +3172,7 @@ pub const Object = struct {
31723172 .var_args_param_type,
31733173 .none,
31743174 => unreachable,
3175 else => switch (mod.intern_pool.indexToKey(t.toIntern())) {
3175 else => switch (ip.indexToKey(t.toIntern())) {
31763176 .int_type => |int_type| try o.builder.intType(int_type.bits),
31773177 .ptr_type => |ptr_type| type: {
31783178 const ptr_ty = try o.builder.ptrType(
......@@ -3264,7 +3264,7 @@ pub const Object = struct {
32643264 return int_ty;
32653265 }
32663266
3267 const name = try o.builder.string(mod.intern_pool.stringToSlice(
3267 const name = try o.builder.string(ip.stringToSlice(
32683268 try struct_obj.getFullyQualifiedName(mod),
32693269 ));
32703270 const ty = try o.builder.opaqueType(name);
......@@ -3357,40 +3357,40 @@ pub const Object = struct {
33573357 const gop = try o.type_map.getOrPut(o.gpa, t.toIntern());
33583358 if (gop.found_existing) return gop.value_ptr.*;
33593359
3360 const union_obj = mod.unionPtr(union_type.index);
3361 const layout = union_obj.getLayout(mod, union_type.hasTag());
3360 const union_obj = ip.loadUnionType(union_type);
3361 const layout = mod.getUnionLayout(union_obj);
33623362
3363 if (union_obj.layout == .Packed) {
3363 if (union_obj.flagsPtr(ip).layout == .Packed) {
33643364 const int_ty = try o.builder.intType(@intCast(t.bitSize(mod)));
33653365 gop.value_ptr.* = int_ty;
33663366 return int_ty;
33673367 }
33683368
33693369 if (layout.payload_size == 0) {
3370 const enum_tag_ty = try o.lowerType(union_obj.tag_ty);
3370 const enum_tag_ty = try o.lowerType(union_obj.enum_tag_ty.toType());
33713371 gop.value_ptr.* = enum_tag_ty;
33723372 return enum_tag_ty;
33733373 }
33743374
3375 const name = try o.builder.string(mod.intern_pool.stringToSlice(
3376 try union_obj.getFullyQualifiedName(mod),
3375 const name = try o.builder.string(ip.stringToSlice(
3376 try mod.declPtr(union_obj.decl).getFullyQualifiedName(mod),
33773377 ));
33783378 const ty = try o.builder.opaqueType(name);
33793379 gop.value_ptr.* = ty; // must be done before any recursive calls
33803380
3381 const aligned_field = union_obj.fields.values()[layout.most_aligned_field];
3382 const aligned_field_ty = try o.lowerType(aligned_field.ty);
3381 const aligned_field_ty = union_obj.field_types.get(ip)[layout.most_aligned_field].toType();
3382 const aligned_field_llvm_ty = try o.lowerType(aligned_field_ty);
33833383
33843384 const payload_ty = ty: {
33853385 if (layout.most_aligned_field_size == layout.payload_size) {
3386 break :ty aligned_field_ty;
3386 break :ty aligned_field_llvm_ty;
33873387 }
33883388 const padding_len = if (layout.tag_size == 0)
33893389 layout.abi_size - layout.most_aligned_field_size
33903390 else
33913391 layout.payload_size - layout.most_aligned_field_size;
33923392 break :ty try o.builder.structType(.@"packed", &.{
3393 aligned_field_ty,
3393 aligned_field_llvm_ty,
33943394 try o.builder.arrayType(padding_len, .i8),
33953395 });
33963396 };
......@@ -3402,7 +3402,7 @@ pub const Object = struct {
34023402 );
34033403 return ty;
34043404 }
3405 const enum_tag_ty = try o.lowerType(union_obj.tag_ty);
3405 const enum_tag_ty = try o.lowerType(union_obj.enum_tag_ty.toType());
34063406
34073407 // Put the tag before or after the payload depending on which one's
34083408 // alignment is greater.
......@@ -3430,7 +3430,7 @@ pub const Object = struct {
34303430 .opaque_type => |opaque_type| {
34313431 const gop = try o.type_map.getOrPut(o.gpa, t.toIntern());
34323432 if (!gop.found_existing) {
3433 const name = try o.builder.string(mod.intern_pool.stringToSlice(
3433 const name = try o.builder.string(ip.stringToSlice(
34343434 try mod.opaqueFullyQualifiedName(opaque_type),
34353435 ));
34363436 gop.value_ptr.* = try o.builder.opaqueType(name);
......@@ -3551,10 +3551,11 @@ pub const Object = struct {
35513551
35523552 fn lowerValue(o: *Object, arg_val: InternPool.Index) Error!Builder.Constant {
35533553 const mod = o.module;
3554 const ip = &mod.intern_pool;
35543555 const target = mod.getTarget();
35553556
35563557 var val = arg_val.toValue();
3557 const arg_val_key = mod.intern_pool.indexToKey(arg_val);
3558 const arg_val_key = ip.indexToKey(arg_val);
35583559 switch (arg_val_key) {
35593560 .runtime_value => |rt| val = rt.val.toValue(),
35603561 else => {},
......@@ -3563,7 +3564,7 @@ pub const Object = struct {
35633564 return o.builder.undefConst(try o.lowerType(arg_val_key.typeOf().toType()));
35643565 }
35653566
3566 const val_key = mod.intern_pool.indexToKey(val.toIntern());
3567 const val_key = ip.indexToKey(val.toIntern());
35673568 const ty = val_key.typeOf().toType();
35683569 return switch (val_key) {
35693570 .int_type,
......@@ -3749,7 +3750,7 @@ pub const Object = struct {
37493750 fields[0..llvm_ty_fields.len],
37503751 ), vals[0..llvm_ty_fields.len]);
37513752 },
3752 .aggregate => |aggregate| switch (mod.intern_pool.indexToKey(ty.toIntern())) {
3753 .aggregate => |aggregate| switch (ip.indexToKey(ty.toIntern())) {
37533754 .array_type => |array_type| switch (aggregate.storage) {
37543755 .bytes => |bytes| try o.builder.stringConst(try o.builder.string(bytes)),
37553756 .elems => |elems| {
......@@ -4024,11 +4025,10 @@ pub const Object = struct {
40244025 if (layout.payload_size == 0) return o.lowerValue(un.tag);
40254026
40264027 const union_obj = mod.typeToUnion(ty).?;
4027 const field_index = ty.unionTagFieldIndex(un.tag.toValue(), o.module).?;
4028 assert(union_obj.haveFieldTypes());
4028 const field_index = mod.unionTagFieldIndex(union_obj, un.tag.toValue()).?;
40294029
4030 const field_ty = union_obj.fields.values()[field_index].ty;
4031 if (union_obj.layout == .Packed) {
4030 const field_ty = union_obj.field_types.get(ip)[field_index].toType();
4031 if (union_obj.getLayout(ip) == .Packed) {
40324032 if (!field_ty.hasRuntimeBits(mod)) return o.builder.intConst(union_ty, 0);
40334033 const small_int_val = try o.builder.castConst(
40344034 if (field_ty.isPtrAtRuntime(mod)) .ptrtoint else .bitcast,
......@@ -9676,6 +9676,7 @@ pub const FuncGen = struct {
96769676 fn airUnionInit(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
96779677 const o = self.dg.object;
96789678 const mod = o.module;
9679 const ip = &mod.intern_pool;
96799680 const ty_pl = self.air.instructions.items(.data)[inst].ty_pl;
96809681 const extra = self.air.extraData(Air.UnionInit, ty_pl.payload).data;
96819682 const union_ty = self.typeOfIndex(inst);
......@@ -9683,13 +9684,13 @@ pub const FuncGen = struct {
96839684 const layout = union_ty.unionGetLayout(mod);
96849685 const union_obj = mod.typeToUnion(union_ty).?;
96859686
9686 if (union_obj.layout == .Packed) {
9687 if (union_obj.getLayout(ip) == .Packed) {
96879688 const big_bits = union_ty.bitSize(mod);
96889689 const int_llvm_ty = try o.builder.intType(@intCast(big_bits));
9689 const field = union_obj.fields.values()[extra.field_index];
9690 const field_ty = union_obj.field_types.get(ip)[extra.field_index].toType();
96909691 const non_int_val = try self.resolveInst(extra.init);
9691 const small_int_ty = try o.builder.intType(@intCast(field.ty.bitSize(mod)));
9692 const small_int_val = if (field.ty.isPtrAtRuntime(mod))
9692 const small_int_ty = try o.builder.intType(@intCast(field_ty.bitSize(mod)));
9693 const small_int_val = if (field_ty.isPtrAtRuntime(mod))
96939694 try self.wip.cast(.ptrtoint, non_int_val, small_int_ty, "")
96949695 else
96959696 try self.wip.cast(.bitcast, non_int_val, small_int_ty, "");
......@@ -9698,7 +9699,7 @@ pub const FuncGen = struct {
96989699
96999700 const tag_int = blk: {
97009701 const tag_ty = union_ty.unionTagTypeHypothetical(mod);
9701 const union_field_name = union_obj.fields.keys()[extra.field_index];
9702 const union_field_name = union_obj.field_names.get(ip)[extra.field_index];
97029703 const enum_field_index = tag_ty.enumFieldIndex(union_field_name, mod).?;
97039704 const tag_val = try mod.enumValueFieldIndex(tag_ty, enum_field_index);
97049705 const tag_int_val = try tag_val.intFromEnum(tag_ty, mod);
......@@ -9719,18 +9720,17 @@ pub const FuncGen = struct {
97199720 const alignment = Builder.Alignment.fromByteUnits(layout.abi_align);
97209721 const result_ptr = try self.buildAlloca(union_llvm_ty, alignment);
97219722 const llvm_payload = try self.resolveInst(extra.init);
9722 assert(union_obj.haveFieldTypes());
9723 const field = union_obj.fields.values()[extra.field_index];
9724 const field_llvm_ty = try o.lowerType(field.ty);
9725 const field_size = field.ty.abiSize(mod);
9726 const field_align = field.normalAlignment(mod);
9723 const field_ty = union_obj.field_types.get(ip)[extra.field_index].toType();
9724 const field_llvm_ty = try o.lowerType(field_ty);
9725 const field_size = field_ty.abiSize(mod);
9726 const field_align = mod.unionFieldNormalAlignment(union_obj, extra.field_index);
97279727 const llvm_usize = try o.lowerType(Type.usize);
97289728 const usize_zero = try o.builder.intValue(llvm_usize, 0);
97299729 const i32_zero = try o.builder.intValue(.i32, 0);
97309730
97319731 const llvm_union_ty = t: {
97329732 const payload_ty = p: {
9733 if (!field.ty.hasRuntimeBitsIgnoreComptime(mod)) {
9733 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) {
97349734 const padding_len = layout.payload_size;
97359735 break :p try o.builder.arrayType(padding_len, .i8);
97369736 }
......@@ -9743,7 +9743,7 @@ pub const FuncGen = struct {
97439743 });
97449744 };
97459745 if (layout.tag_size == 0) break :t try o.builder.structType(.normal, &.{payload_ty});
9746 const tag_ty = try o.lowerType(union_obj.tag_ty);
9746 const tag_ty = try o.lowerType(union_obj.enum_tag_ty.toType());
97479747 var fields: [3]Builder.Type = undefined;
97489748 var fields_len: usize = 2;
97499749 if (layout.tag_align >= layout.payload_align) {
......@@ -9761,7 +9761,7 @@ pub const FuncGen = struct {
97619761 // Now we follow the layout as expressed above with GEP instructions to set the
97629762 // tag and the payload.
97639763 const field_ptr_ty = try mod.ptrType(.{
9764 .child = field.ty.toIntern(),
9764 .child = field_ty.toIntern(),
97659765 .flags = .{ .alignment = InternPool.Alignment.fromNonzeroByteUnits(field_align) },
97669766 });
97679767 if (layout.tag_size == 0) {
......@@ -9786,9 +9786,9 @@ pub const FuncGen = struct {
97869786 const tag_index = @intFromBool(layout.tag_align < layout.payload_align);
97879787 const indices: [2]Builder.Value = .{ usize_zero, try o.builder.intValue(.i32, tag_index) };
97889788 const field_ptr = try self.wip.gep(.inbounds, llvm_union_ty, result_ptr, &indices, "");
9789 const tag_ty = try o.lowerType(union_obj.tag_ty);
9789 const tag_ty = try o.lowerType(union_obj.enum_tag_ty.toType());
97909790 const llvm_tag = try o.builder.intValue(tag_ty, tag_int);
9791 const tag_alignment = Builder.Alignment.fromByteUnits(union_obj.tag_ty.abiAlignment(mod));
9791 const tag_alignment = Builder.Alignment.fromByteUnits(union_obj.enum_tag_ty.toType().abiAlignment(mod));
97929792 _ = try self.wip.store(.normal, llvm_tag, field_ptr, tag_alignment);
97939793 }
97949794
src/codegen/spirv.zig+15-13
......@@ -619,9 +619,10 @@ pub const DeclGen = struct {
619619 fn lower(self: *@This(), ty: Type, arg_val: Value) !void {
620620 const dg = self.dg;
621621 const mod = dg.module;
622 const ip = &mod.intern_pool;
622623
623624 var val = arg_val;
624 switch (mod.intern_pool.indexToKey(val.toIntern())) {
625 switch (ip.indexToKey(val.toIntern())) {
625626 .runtime_value => |rt| val = rt.val.toValue(),
626627 else => {},
627628 }
......@@ -631,7 +632,7 @@ pub const DeclGen = struct {
631632 return try self.addUndef(size);
632633 }
633634
634 switch (mod.intern_pool.indexToKey(val.toIntern())) {
635 switch (ip.indexToKey(val.toIntern())) {
635636 .int_type,
636637 .ptr_type,
637638 .array_type,
......@@ -770,7 +771,7 @@ pub const DeclGen = struct {
770771 try self.addConstBool(payload_val != null);
771772 try self.addUndef(padding);
772773 },
773 .aggregate => |aggregate| switch (mod.intern_pool.indexToKey(ty.ip_index)) {
774 .aggregate => |aggregate| switch (ip.indexToKey(ty.ip_index)) {
774775 .array_type => |array_type| {
775776 const elem_ty = array_type.child.toType();
776777 switch (aggregate.storage) {
......@@ -801,7 +802,7 @@ pub const DeclGen = struct {
801802 if (field.is_comptime or !field.ty.hasRuntimeBits(mod)) continue;
802803
803804 const field_val = switch (aggregate.storage) {
804 .bytes => |bytes| try mod.intern_pool.get(mod.gpa, .{ .int = .{
805 .bytes => |bytes| try ip.get(mod.gpa, .{ .int = .{
805806 .ty = field.ty.toIntern(),
806807 .storage = .{ .u64 = bytes[i] },
807808 } }),
......@@ -828,13 +829,13 @@ pub const DeclGen = struct {
828829 return try self.lower(ty.unionTagTypeSafety(mod).?, un.tag.toValue());
829830 }
830831
831 const union_ty = mod.typeToUnion(ty).?;
832 if (union_ty.layout == .Packed) {
832 const union_obj = mod.typeToUnion(ty).?;
833 if (union_obj.getLayout(ip) == .Packed) {
833834 return dg.todo("packed union constants", .{});
834835 }
835836
836837 const active_field = ty.unionTagFieldIndex(un.tag.toValue(), dg.module).?;
837 const active_field_ty = union_ty.fields.values()[active_field].ty;
838 const active_field_ty = union_obj.field_types.get(ip)[active_field].toType();
838839
839840 const has_tag = layout.tag_size != 0;
840841 const tag_first = layout.tag_align >= layout.payload_align;
......@@ -1162,16 +1163,17 @@ pub const DeclGen = struct {
11621163 /// resulting struct will be *underaligned*.
11631164 fn resolveUnionType(self: *DeclGen, ty: Type, maybe_active_field: ?usize) !CacheRef {
11641165 const mod = self.module;
1166 const ip = &mod.intern_pool;
11651167 const layout = ty.unionGetLayout(mod);
1166 const union_ty = mod.typeToUnion(ty).?;
1168 const union_obj = mod.typeToUnion(ty).?;
11671169
1168 if (union_ty.layout == .Packed) {
1170 if (union_obj.getLayout(ip) == .Packed) {
11691171 return self.todo("packed union types", .{});
11701172 }
11711173
11721174 if (layout.payload_size == 0) {
11731175 // No payload, so represent this as just the tag type.
1174 return try self.resolveType(union_ty.tag_ty, .indirect);
1176 return try self.resolveType(union_obj.enum_tag_ty.toType(), .indirect);
11751177 }
11761178
11771179 var member_types = std.BoundedArray(CacheRef, 4){};
......@@ -1182,13 +1184,13 @@ pub const DeclGen = struct {
11821184 const u8_ty_ref = try self.intType(.unsigned, 8); // TODO: What if Int8Type is not enabled?
11831185
11841186 if (has_tag and tag_first) {
1185 const tag_ty_ref = try self.resolveType(union_ty.tag_ty, .indirect);
1187 const tag_ty_ref = try self.resolveType(union_obj.enum_tag_ty.toType(), .indirect);
11861188 member_types.appendAssumeCapacity(tag_ty_ref);
11871189 member_names.appendAssumeCapacity(try self.spv.resolveString("tag"));
11881190 }
11891191
11901192 const active_field = maybe_active_field orelse layout.most_aligned_field;
1191 const active_field_ty = union_ty.fields.values()[active_field].ty;
1193 const active_field_ty = union_obj.field_types.get(ip)[active_field].toType();
11921194
11931195 const active_field_size = if (active_field_ty.hasRuntimeBitsIgnoreComptime(mod)) blk: {
11941196 const active_payload_ty_ref = try self.resolveType(active_field_ty, .indirect);
......@@ -1205,7 +1207,7 @@ pub const DeclGen = struct {
12051207 }
12061208
12071209 if (has_tag and !tag_first) {
1208 const tag_ty_ref = try self.resolveType(union_ty.tag_ty, .indirect);
1210 const tag_ty_ref = try self.resolveType(union_obj.enum_tag_ty.toType(), .indirect);
12091211 member_types.appendAssumeCapacity(tag_ty_ref);
12101212 member_names.appendAssumeCapacity(try self.spv.resolveString("tag"));
12111213 }
src/link/Dwarf.zig+9-11
......@@ -166,6 +166,7 @@ pub const DeclState = struct {
166166 const dbg_info_buffer = &self.dbg_info;
167167 const target = mod.getTarget();
168168 const target_endian = target.cpu.arch.endian();
169 const ip = &mod.intern_pool;
169170
170171 switch (ty.zigTypeTag(mod)) {
171172 .NoReturn => unreachable,
......@@ -321,7 +322,7 @@ pub const DeclState = struct {
321322 // DW.AT.byte_size, DW.FORM.udata
322323 try leb128.writeULEB128(dbg_info_buffer.writer(), ty.abiSize(mod));
323324
324 switch (mod.intern_pool.indexToKey(ty.ip_index)) {
325 switch (ip.indexToKey(ty.ip_index)) {
325326 .anon_struct_type => |fields| {
326327 // DW.AT.name, DW.FORM.string
327328 try dbg_info_buffer.writer().print("{}\x00", .{ty.fmt(mod)});
......@@ -357,7 +358,7 @@ pub const DeclState = struct {
357358 0..,
358359 ) |field_name_ip, field, field_index| {
359360 if (!field.ty.hasRuntimeBits(mod)) continue;
360 const field_name = mod.intern_pool.stringToSlice(field_name_ip);
361 const field_name = ip.stringToSlice(field_name_ip);
361362 // DW.AT.member
362363 try dbg_info_buffer.ensureUnusedCapacity(field_name.len + 2);
363364 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevKind.struct_member));
......@@ -388,7 +389,6 @@ pub const DeclState = struct {
388389 try ty.print(dbg_info_buffer.writer(), mod);
389390 try dbg_info_buffer.append(0);
390391
391 const ip = &mod.intern_pool;
392392 const enum_type = ip.indexToKey(ty.ip_index).enum_type;
393393 for (enum_type.names.get(ip), 0..) |field_name_index, field_i| {
394394 const field_name = ip.stringToSlice(field_name_index);
......@@ -414,8 +414,8 @@ pub const DeclState = struct {
414414 try dbg_info_buffer.append(0);
415415 },
416416 .Union => {
417 const layout = ty.unionGetLayout(mod);
418417 const union_obj = mod.typeToUnion(ty).?;
418 const layout = mod.getUnionLayout(union_obj);
419419 const payload_offset = if (layout.tag_align >= layout.payload_align) layout.tag_size else 0;
420420 const tag_offset = if (layout.tag_align >= layout.payload_align) 0 else layout.payload_size;
421421 // TODO this is temporary to match current state of unions in Zig - we don't yet have
......@@ -457,19 +457,17 @@ pub const DeclState = struct {
457457 try dbg_info_buffer.append(0);
458458 }
459459
460 const fields = ty.unionFields(mod);
461 for (fields.keys()) |field_name| {
462 const field = fields.get(field_name).?;
463 if (!field.ty.hasRuntimeBits(mod)) continue;
460 for (union_obj.field_types.get(ip), union_obj.field_names.get(ip)) |field_ty, field_name| {
461 if (!field_ty.toType().hasRuntimeBits(mod)) continue;
464462 // DW.AT.member
465463 try dbg_info_buffer.append(@intFromEnum(AbbrevKind.struct_member));
466464 // DW.AT.name, DW.FORM.string
467 try dbg_info_buffer.appendSlice(mod.intern_pool.stringToSlice(field_name));
465 try dbg_info_buffer.appendSlice(ip.stringToSlice(field_name));
468466 try dbg_info_buffer.append(0);
469467 // DW.AT.type, DW.FORM.ref4
470468 const index = dbg_info_buffer.items.len;
471469 try dbg_info_buffer.resize(index + 4);
472 try self.addTypeRelocGlobal(atom_index, field.ty, @as(u32, @intCast(index)));
470 try self.addTypeRelocGlobal(atom_index, field_ty.toType(), @intCast(index));
473471 // DW.AT.data_member_location, DW.FORM.udata
474472 try dbg_info_buffer.append(0);
475473 }
......@@ -486,7 +484,7 @@ pub const DeclState = struct {
486484 // DW.AT.type, DW.FORM.ref4
487485 const index = dbg_info_buffer.items.len;
488486 try dbg_info_buffer.resize(index + 4);
489 try self.addTypeRelocGlobal(atom_index, union_obj.tag_ty, @as(u32, @intCast(index)));
487 try self.addTypeRelocGlobal(atom_index, union_obj.enum_tag_ty.toType(), @intCast(index));
490488 // DW.AT.data_member_location, DW.FORM.udata
491489 try leb128.writeULEB128(dbg_info_buffer.writer(), tag_offset);
492490
src/type.zig+177-195
......@@ -349,8 +349,7 @@ pub const Type = struct {
349349 },
350350
351351 .union_type => |union_type| {
352 const union_obj = mod.unionPtr(union_type.index);
353 const decl = mod.declPtr(union_obj.owner_decl);
352 const decl = mod.declPtr(union_type.decl);
354353 try decl.renderFullyQualifiedName(mod, writer);
355354 },
356355 .opaque_type => |opaque_type| {
......@@ -462,10 +461,11 @@ pub const Type = struct {
462461 ignore_comptime_only: bool,
463462 strat: AbiAlignmentAdvancedStrat,
464463 ) RuntimeBitsError!bool {
464 const ip = &mod.intern_pool;
465465 return switch (ty.toIntern()) {
466466 // False because it is a comptime-only type.
467467 .empty_struct_type => false,
468 else => switch (mod.intern_pool.indexToKey(ty.toIntern())) {
468 else => switch (ip.indexToKey(ty.toIntern())) {
469469 .int_type => |int_type| int_type.bits != 0,
470470 .ptr_type => |ptr_type| {
471471 // Pointers to zero-bit types still have a runtime address; however, pointers
......@@ -595,29 +595,36 @@ pub const Type = struct {
595595 },
596596
597597 .union_type => |union_type| {
598 const union_obj = mod.unionPtr(union_type.index);
599 switch (union_type.runtime_tag) {
598 switch (union_type.flagsPtr(ip).runtime_tag) {
600599 .none => {
601 if (union_obj.status == .field_types_wip) {
600 if (union_type.flagsPtr(ip).status == .field_types_wip) {
602601 // In this case, we guess that hasRuntimeBits() for this type is true,
603602 // and then later if our guess was incorrect, we emit a compile error.
604 union_obj.assumed_runtime_bits = true;
603 union_type.flagsPtr(ip).assumed_runtime_bits = true;
605604 return true;
606605 }
607606 },
608607 .safety, .tagged => {
609 if (try union_obj.tag_ty.hasRuntimeBitsAdvanced(mod, ignore_comptime_only, strat)) {
608 const tag_ty = union_type.tagTypePtr(ip).*;
609 // tag_ty will be `none` if this union's tag type is not resolved yet,
610 // in which case we want control flow to continue down below.
611 if (tag_ty != .none and
612 try tag_ty.toType().hasRuntimeBitsAdvanced(mod, ignore_comptime_only, strat))
613 {
610614 return true;
611615 }
612616 },
613617 }
614618 switch (strat) {
615619 .sema => |sema| _ = try sema.resolveTypeFields(ty),
616 .eager => assert(union_obj.haveFieldTypes()),
617 .lazy => if (!union_obj.haveFieldTypes()) return error.NeedLazy,
620 .eager => assert(union_type.flagsPtr(ip).status.haveFieldTypes()),
621 .lazy => if (!union_type.flagsPtr(ip).status.haveFieldTypes())
622 return error.NeedLazy,
618623 }
619 for (union_obj.fields.values()) |value| {
620 if (try value.ty.hasRuntimeBitsAdvanced(mod, ignore_comptime_only, strat))
624 const union_obj = ip.loadUnionType(union_type);
625 for (0..union_obj.field_types.len) |field_index| {
626 const field_ty = union_obj.field_types.get(ip)[field_index].toType();
627 if (try field_ty.hasRuntimeBitsAdvanced(mod, ignore_comptime_only, strat))
621628 return true;
622629 } else {
623630 return false;
......@@ -656,7 +663,8 @@ pub const Type = struct {
656663 /// readFrom/writeToMemory are supported only for types with a well-
657664 /// defined memory layout
658665 pub fn hasWellDefinedLayout(ty: Type, mod: *Module) bool {
659 return switch (mod.intern_pool.indexToKey(ty.toIntern())) {
666 const ip = &mod.intern_pool;
667 return switch (ip.indexToKey(ty.toIntern())) {
660668 .int_type,
661669 .vector_type,
662670 => true,
......@@ -728,8 +736,8 @@ pub const Type = struct {
728736 };
729737 return struct_obj.layout != .Auto;
730738 },
731 .union_type => |union_type| switch (union_type.runtime_tag) {
732 .none, .safety => mod.unionPtr(union_type.index).layout != .Auto,
739 .union_type => |union_type| switch (union_type.flagsPtr(ip).runtime_tag) {
740 .none, .safety => union_type.flagsPtr(ip).layout != .Auto,
733741 .tagged => false,
734742 },
735743 .enum_type => |enum_type| switch (enum_type.tag_mode) {
......@@ -867,6 +875,7 @@ pub const Type = struct {
867875 strat: AbiAlignmentAdvancedStrat,
868876 ) Module.CompileError!AbiAlignmentAdvanced {
869877 const target = mod.getTarget();
878 const ip = &mod.intern_pool;
870879
871880 const opt_sema = switch (strat) {
872881 .sema => |sema| sema,
......@@ -875,7 +884,7 @@ pub const Type = struct {
875884
876885 switch (ty.toIntern()) {
877886 .empty_struct_type => return AbiAlignmentAdvanced{ .scalar = 0 },
878 else => switch (mod.intern_pool.indexToKey(ty.toIntern())) {
887 else => switch (ip.indexToKey(ty.toIntern())) {
879888 .int_type => |int_type| {
880889 if (int_type.bits == 0) return AbiAlignmentAdvanced{ .scalar = 0 };
881890 return AbiAlignmentAdvanced{ .scalar = intAbiAlignment(int_type.bits, target) };
......@@ -1066,8 +1075,65 @@ pub const Type = struct {
10661075 },
10671076
10681077 .union_type => |union_type| {
1069 const union_obj = mod.unionPtr(union_type.index);
1070 return abiAlignmentAdvancedUnion(ty, mod, strat, union_obj, union_type.hasTag());
1078 if (opt_sema) |sema| {
1079 if (union_type.flagsPtr(ip).status == .field_types_wip) {
1080 // We'll guess "pointer-aligned", if the union has an
1081 // underaligned pointer field then some allocations
1082 // might require explicit alignment.
1083 return AbiAlignmentAdvanced{ .scalar = @divExact(target.ptrBitWidth(), 8) };
1084 }
1085 _ = try sema.resolveTypeFields(ty);
1086 }
1087 if (!union_type.haveFieldTypes(ip)) switch (strat) {
1088 .eager => unreachable, // union layout not resolved
1089 .sema => unreachable, // handled above
1090 .lazy => return .{ .val = (try mod.intern(.{ .int = .{
1091 .ty = .comptime_int_type,
1092 .storage = .{ .lazy_align = ty.toIntern() },
1093 } })).toValue() },
1094 };
1095 const union_obj = ip.loadUnionType(union_type);
1096 if (union_obj.field_names.len == 0) {
1097 if (union_obj.hasTag(ip)) {
1098 return abiAlignmentAdvanced(union_obj.enum_tag_ty.toType(), mod, strat);
1099 } else {
1100 return AbiAlignmentAdvanced{
1101 .scalar = @intFromBool(union_obj.flagsPtr(ip).layout == .Extern),
1102 };
1103 }
1104 }
1105
1106 var max_align: u32 = 0;
1107 if (union_obj.hasTag(ip)) max_align = union_obj.enum_tag_ty.toType().abiAlignment(mod);
1108 for (0..union_obj.field_names.len) |field_index| {
1109 const field_ty = union_obj.field_types.get(ip)[field_index].toType();
1110 const field_align = if (union_obj.field_aligns.len == 0)
1111 .none
1112 else
1113 union_obj.field_aligns.get(ip)[field_index];
1114 if (!(field_ty.hasRuntimeBitsAdvanced(mod, false, strat) catch |err| switch (err) {
1115 error.NeedLazy => return .{ .val = (try mod.intern(.{ .int = .{
1116 .ty = .comptime_int_type,
1117 .storage = .{ .lazy_align = ty.toIntern() },
1118 } })).toValue() },
1119 else => |e| return e,
1120 })) continue;
1121
1122 const field_align_bytes: u32 = @intCast(field_align.toByteUnitsOptional() orelse
1123 switch (try field_ty.abiAlignmentAdvanced(mod, strat)) {
1124 .scalar => |a| a,
1125 .val => switch (strat) {
1126 .eager => unreachable, // struct layout not resolved
1127 .sema => unreachable, // handled above
1128 .lazy => return .{ .val = (try mod.intern(.{ .int = .{
1129 .ty = .comptime_int_type,
1130 .storage = .{ .lazy_align = ty.toIntern() },
1131 } })).toValue() },
1132 },
1133 });
1134 max_align = @max(max_align, field_align_bytes);
1135 }
1136 return AbiAlignmentAdvanced{ .scalar = max_align };
10711137 },
10721138 .opaque_type => return AbiAlignmentAdvanced{ .scalar = 1 },
10731139 .enum_type => |enum_type| return AbiAlignmentAdvanced{ .scalar = enum_type.tag_ty.toType().abiAlignment(mod) },
......@@ -1177,71 +1243,6 @@ pub const Type = struct {
11771243 }
11781244 }
11791245
1180 pub fn abiAlignmentAdvancedUnion(
1181 ty: Type,
1182 mod: *Module,
1183 strat: AbiAlignmentAdvancedStrat,
1184 union_obj: *Module.Union,
1185 have_tag: bool,
1186 ) Module.CompileError!AbiAlignmentAdvanced {
1187 const opt_sema = switch (strat) {
1188 .sema => |sema| sema,
1189 else => null,
1190 };
1191 if (opt_sema) |sema| {
1192 if (union_obj.status == .field_types_wip) {
1193 // We'll guess "pointer-aligned", if the union has an
1194 // underaligned pointer field then some allocations
1195 // might require explicit alignment.
1196 const target = mod.getTarget();
1197 return AbiAlignmentAdvanced{ .scalar = @divExact(target.ptrBitWidth(), 8) };
1198 }
1199 _ = try sema.resolveTypeFields(ty);
1200 }
1201 if (!union_obj.haveFieldTypes()) switch (strat) {
1202 .eager => unreachable, // union layout not resolved
1203 .sema => unreachable, // handled above
1204 .lazy => return .{ .val = (try mod.intern(.{ .int = .{
1205 .ty = .comptime_int_type,
1206 .storage = .{ .lazy_align = ty.toIntern() },
1207 } })).toValue() },
1208 };
1209 if (union_obj.fields.count() == 0) {
1210 if (have_tag) {
1211 return abiAlignmentAdvanced(union_obj.tag_ty, mod, strat);
1212 } else {
1213 return AbiAlignmentAdvanced{ .scalar = @intFromBool(union_obj.layout == .Extern) };
1214 }
1215 }
1216
1217 var max_align: u32 = 0;
1218 if (have_tag) max_align = union_obj.tag_ty.abiAlignment(mod);
1219 for (union_obj.fields.values()) |field| {
1220 if (!(field.ty.hasRuntimeBitsAdvanced(mod, false, strat) catch |err| switch (err) {
1221 error.NeedLazy => return .{ .val = (try mod.intern(.{ .int = .{
1222 .ty = .comptime_int_type,
1223 .storage = .{ .lazy_align = ty.toIntern() },
1224 } })).toValue() },
1225 else => |e| return e,
1226 })) continue;
1227
1228 const field_align = @as(u32, @intCast(field.abi_align.toByteUnitsOptional() orelse
1229 switch (try field.ty.abiAlignmentAdvanced(mod, strat)) {
1230 .scalar => |a| a,
1231 .val => switch (strat) {
1232 .eager => unreachable, // struct layout not resolved
1233 .sema => unreachable, // handled above
1234 .lazy => return .{ .val = (try mod.intern(.{ .int = .{
1235 .ty = .comptime_int_type,
1236 .storage = .{ .lazy_align = ty.toIntern() },
1237 } })).toValue() },
1238 },
1239 }));
1240 max_align = @max(max_align, field_align);
1241 }
1242 return AbiAlignmentAdvanced{ .scalar = max_align };
1243 }
1244
12451246 /// May capture a reference to `ty`.
12461247 pub fn lazyAbiSize(ty: Type, mod: *Module) !Value {
12471248 switch (try ty.abiSizeAdvanced(mod, .lazy)) {
......@@ -1273,11 +1274,12 @@ pub const Type = struct {
12731274 strat: AbiAlignmentAdvancedStrat,
12741275 ) Module.CompileError!AbiSizeAdvanced {
12751276 const target = mod.getTarget();
1277 const ip = &mod.intern_pool;
12761278
12771279 switch (ty.toIntern()) {
12781280 .empty_struct_type => return AbiSizeAdvanced{ .scalar = 0 },
12791281
1280 else => switch (mod.intern_pool.indexToKey(ty.toIntern())) {
1282 else => switch (ip.indexToKey(ty.toIntern())) {
12811283 .int_type => |int_type| {
12821284 if (int_type.bits == 0) return AbiSizeAdvanced{ .scalar = 0 };
12831285 return AbiSizeAdvanced{ .scalar = intAbiSize(int_type.bits, target) };
......@@ -1484,8 +1486,18 @@ pub const Type = struct {
14841486 },
14851487
14861488 .union_type => |union_type| {
1487 const union_obj = mod.unionPtr(union_type.index);
1488 return abiSizeAdvancedUnion(ty, mod, strat, union_obj, union_type.hasTag());
1489 switch (strat) {
1490 .sema => |sema| try sema.resolveTypeLayout(ty),
1491 .lazy => if (!union_type.flagsPtr(ip).status.haveLayout()) return .{
1492 .val = (try mod.intern(.{ .int = .{
1493 .ty = .comptime_int_type,
1494 .storage = .{ .lazy_size = ty.toIntern() },
1495 } })).toValue(),
1496 },
1497 .eager => {},
1498 }
1499 const union_obj = ip.loadUnionType(union_type);
1500 return AbiSizeAdvanced{ .scalar = mod.unionAbiSize(union_obj) };
14891501 },
14901502 .opaque_type => unreachable, // no size available
14911503 .enum_type => |enum_type| return AbiSizeAdvanced{ .scalar = enum_type.tag_ty.toType().abiSize(mod) },
......@@ -1515,24 +1527,6 @@ pub const Type = struct {
15151527 }
15161528 }
15171529
1518 pub fn abiSizeAdvancedUnion(
1519 ty: Type,
1520 mod: *Module,
1521 strat: AbiAlignmentAdvancedStrat,
1522 union_obj: *Module.Union,
1523 have_tag: bool,
1524 ) Module.CompileError!AbiSizeAdvanced {
1525 switch (strat) {
1526 .sema => |sema| try sema.resolveTypeLayout(ty),
1527 .lazy => if (!union_obj.haveLayout()) return .{ .val = (try mod.intern(.{ .int = .{
1528 .ty = .comptime_int_type,
1529 .storage = .{ .lazy_size = ty.toIntern() },
1530 } })).toValue() },
1531 .eager => {},
1532 }
1533 return AbiSizeAdvanced{ .scalar = union_obj.abiSize(mod, have_tag) };
1534 }
1535
15361530 fn abiSizeAdvancedOptional(
15371531 ty: Type,
15381532 mod: *Module,
......@@ -1602,10 +1596,11 @@ pub const Type = struct {
16021596 opt_sema: ?*Sema,
16031597 ) Module.CompileError!u64 {
16041598 const target = mod.getTarget();
1599 const ip = &mod.intern_pool;
16051600
16061601 const strat: AbiAlignmentAdvancedStrat = if (opt_sema) |sema| .{ .sema = sema } else .eager;
16071602
1608 switch (mod.intern_pool.indexToKey(ty.toIntern())) {
1603 switch (ip.indexToKey(ty.toIntern())) {
16091604 .int_type => |int_type| return int_type.bits,
16101605 .ptr_type => |ptr_type| switch (ptr_type.flags.size) {
16111606 .Slice => return target.ptrBitWidth() * 2,
......@@ -1714,12 +1709,13 @@ pub const Type = struct {
17141709 if (ty.containerLayout(mod) != .Packed) {
17151710 return (try ty.abiSizeAdvanced(mod, strat)).scalar * 8;
17161711 }
1717 const union_obj = mod.unionPtr(union_type.index);
1718 assert(union_obj.haveFieldTypes());
1712 const union_obj = ip.loadUnionType(union_type);
1713 assert(union_obj.flagsPtr(ip).status.haveFieldTypes());
17191714
17201715 var size: u64 = 0;
1721 for (union_obj.fields.values()) |field| {
1722 size = @max(size, try bitSizeAdvanced(field.ty, mod, opt_sema));
1716 for (0..union_obj.field_types.len) |field_index| {
1717 const field_ty = union_obj.field_types.get(ip)[field_index];
1718 size = @max(size, try bitSizeAdvanced(field_ty.toType(), mod, opt_sema));
17231719 }
17241720 return size;
17251721 },
......@@ -1753,33 +1749,24 @@ pub const Type = struct {
17531749 /// Returns true if the type's layout is already resolved and it is safe
17541750 /// to use `abiSize`, `abiAlignment` and `bitSize` on it.
17551751 pub fn layoutIsResolved(ty: Type, mod: *Module) bool {
1756 switch (ty.zigTypeTag(mod)) {
1757 .Struct => {
1758 if (mod.typeToStruct(ty)) |struct_obj| {
1752 const ip = &mod.intern_pool;
1753 return switch (ip.indexToKey(ty.toIntern())) {
1754 .struct_type => |struct_type| {
1755 if (mod.structPtrUnwrap(struct_type.index)) |struct_obj| {
17591756 return struct_obj.haveLayout();
1757 } else {
1758 return true;
17601759 }
1761 return true;
1762 },
1763 .Union => {
1764 if (mod.typeToUnion(ty)) |union_obj| {
1765 return union_obj.haveLayout();
1766 }
1767 return true;
17681760 },
1769 .Array => {
1770 if (ty.arrayLenIncludingSentinel(mod) == 0) return true;
1771 return ty.childType(mod).layoutIsResolved(mod);
1772 },
1773 .Optional => {
1774 const payload_ty = ty.optionalChild(mod);
1775 return payload_ty.layoutIsResolved(mod);
1776 },
1777 .ErrorUnion => {
1778 const payload_ty = ty.errorUnionPayload(mod);
1779 return payload_ty.layoutIsResolved(mod);
1761 .union_type => |union_type| union_type.haveLayout(ip),
1762 .array_type => |array_type| {
1763 if ((array_type.len + @intFromBool(array_type.sentinel != .none)) == 0) return true;
1764 return array_type.child.toType().layoutIsResolved(mod);
17801765 },
1781 else => return true,
1782 }
1766 .opt_type => |child| child.toType().layoutIsResolved(mod),
1767 .error_union_type => |k| k.payload_type.toType().layoutIsResolved(mod),
1768 else => true,
1769 };
17831770 }
17841771
17851772 pub fn isSinglePointer(ty: Type, mod: *const Module) bool {
......@@ -1970,12 +1957,12 @@ pub const Type = struct {
19701957 /// Returns the tag type of a union, if the type is a union and it has a tag type.
19711958 /// Otherwise, returns `null`.
19721959 pub fn unionTagType(ty: Type, mod: *Module) ?Type {
1973 return switch (mod.intern_pool.indexToKey(ty.toIntern())) {
1974 .union_type => |union_type| switch (union_type.runtime_tag) {
1960 const ip = &mod.intern_pool;
1961 return switch (ip.indexToKey(ty.toIntern())) {
1962 .union_type => |union_type| switch (union_type.flagsPtr(ip).runtime_tag) {
19751963 .tagged => {
1976 const union_obj = mod.unionPtr(union_type.index);
1977 assert(union_obj.haveFieldTypes());
1978 return union_obj.tag_ty;
1964 assert(union_type.flagsPtr(ip).status.haveFieldTypes());
1965 return union_type.enum_tag_ty.toType();
19791966 },
19801967 else => null,
19811968 },
......@@ -1986,12 +1973,12 @@ pub const Type = struct {
19861973 /// Same as `unionTagType` but includes safety tag.
19871974 /// Codegen should use this version.
19881975 pub fn unionTagTypeSafety(ty: Type, mod: *Module) ?Type {
1989 return switch (mod.intern_pool.indexToKey(ty.toIntern())) {
1976 const ip = &mod.intern_pool;
1977 return switch (ip.indexToKey(ty.toIntern())) {
19901978 .union_type => |union_type| {
1991 if (!union_type.hasTag()) return null;
1992 const union_obj = mod.unionPtr(union_type.index);
1993 assert(union_obj.haveFieldTypes());
1994 return union_obj.tag_ty;
1979 if (!union_type.hasTag(ip)) return null;
1980 assert(union_type.haveFieldTypes(ip));
1981 return union_type.enum_tag_ty.toType();
19951982 },
19961983 else => null,
19971984 };
......@@ -2001,52 +1988,46 @@ pub const Type = struct {
20011988 /// not be stored at runtime.
20021989 pub fn unionTagTypeHypothetical(ty: Type, mod: *Module) Type {
20031990 const union_obj = mod.typeToUnion(ty).?;
2004 assert(union_obj.haveFieldTypes());
2005 return union_obj.tag_ty;
2006 }
2007
2008 pub fn unionFields(ty: Type, mod: *Module) Module.Union.Fields {
2009 const union_obj = mod.typeToUnion(ty).?;
2010 assert(union_obj.haveFieldTypes());
2011 return union_obj.fields;
1991 return union_obj.enum_tag_ty.toType();
20121992 }
20131993
20141994 pub fn unionFieldType(ty: Type, enum_tag: Value, mod: *Module) Type {
1995 const ip = &mod.intern_pool;
20151996 const union_obj = mod.typeToUnion(ty).?;
2016 const index = ty.unionTagFieldIndex(enum_tag, mod).?;
2017 assert(union_obj.haveFieldTypes());
2018 return union_obj.fields.values()[index].ty;
1997 const index = mod.unionTagFieldIndex(union_obj, enum_tag).?;
1998 return union_obj.field_types.get(ip)[index].toType();
20191999 }
20202000
2021 pub fn unionTagFieldIndex(ty: Type, enum_tag: Value, mod: *Module) ?usize {
2001 pub fn unionTagFieldIndex(ty: Type, enum_tag: Value, mod: *Module) ?u32 {
20222002 const union_obj = mod.typeToUnion(ty).?;
2023 const index = union_obj.tag_ty.enumTagFieldIndex(enum_tag, mod) orelse return null;
2024 const name = union_obj.tag_ty.enumFieldName(index, mod);
2025 return union_obj.fields.getIndex(name);
2003 return mod.unionTagFieldIndex(union_obj, enum_tag);
20262004 }
20272005
20282006 pub fn unionHasAllZeroBitFieldTypes(ty: Type, mod: *Module) bool {
2007 const ip = &mod.intern_pool;
20292008 const union_obj = mod.typeToUnion(ty).?;
2030 return union_obj.hasAllZeroBitFieldTypes(mod);
2009 for (union_obj.field_types.get(ip)) |field_ty| {
2010 if (field_ty.toType().hasRuntimeBits(mod)) return false;
2011 }
2012 return true;
20312013 }
20322014
2033 pub fn unionGetLayout(ty: Type, mod: *Module) Module.Union.Layout {
2034 const union_type = mod.intern_pool.indexToKey(ty.toIntern()).union_type;
2035 const union_obj = mod.unionPtr(union_type.index);
2036 return union_obj.getLayout(mod, union_type.hasTag());
2015 pub fn unionGetLayout(ty: Type, mod: *Module) Module.UnionLayout {
2016 const ip = &mod.intern_pool;
2017 const union_type = ip.indexToKey(ty.toIntern()).union_type;
2018 const union_obj = ip.loadUnionType(union_type);
2019 return mod.getUnionLayout(union_obj);
20372020 }
20382021
20392022 pub fn containerLayout(ty: Type, mod: *Module) std.builtin.Type.ContainerLayout {
2040 return switch (mod.intern_pool.indexToKey(ty.toIntern())) {
2023 const ip = &mod.intern_pool;
2024 return switch (ip.indexToKey(ty.toIntern())) {
20412025 .struct_type => |struct_type| {
20422026 const struct_obj = mod.structPtrUnwrap(struct_type.index) orelse return .Auto;
20432027 return struct_obj.layout;
20442028 },
20452029 .anon_struct_type => .Auto,
2046 .union_type => |union_type| {
2047 const union_obj = mod.unionPtr(union_type.index);
2048 return union_obj.layout;
2049 },
2030 .union_type => |union_type| union_type.flagsPtr(ip).layout,
20502031 else => unreachable,
20512032 };
20522033 }
......@@ -2570,14 +2551,16 @@ pub const Type = struct {
25702551 },
25712552
25722553 .union_type => |union_type| {
2573 const union_obj = mod.unionPtr(union_type.index);
2574 const tag_val = (try union_obj.tag_ty.onePossibleValue(mod)) orelse return null;
2575 if (union_obj.fields.count() == 0) {
2554 const union_obj = ip.loadUnionType(union_type);
2555 const tag_val = (try union_obj.enum_tag_ty.toType().onePossibleValue(mod)) orelse
2556 return null;
2557 if (union_obj.field_names.len == 0) {
25762558 const only = try mod.intern(.{ .empty_enum_value = ty.toIntern() });
25772559 return only.toValue();
25782560 }
2579 const only_field = union_obj.fields.values()[0];
2580 const val_val = (try only_field.ty.onePossibleValue(mod)) orelse return null;
2561 const only_field_ty = union_obj.field_types.get(ip)[0];
2562 const val_val = (try only_field_ty.toType().onePossibleValue(mod)) orelse
2563 return null;
25812564 const only = try mod.intern(.{ .un = .{
25822565 .ty = ty.toIntern(),
25832566 .tag = tag_val.toIntern(),
......@@ -2657,10 +2640,11 @@ pub const Type = struct {
26572640 /// TODO merge these implementations together with the "advanced" pattern seen
26582641 /// elsewhere in this file.
26592642 pub fn comptimeOnly(ty: Type, mod: *Module) bool {
2643 const ip = &mod.intern_pool;
26602644 return switch (ty.toIntern()) {
26612645 .empty_struct_type => false,
26622646
2663 else => switch (mod.intern_pool.indexToKey(ty.toIntern())) {
2647 else => switch (ip.indexToKey(ty.toIntern())) {
26642648 .int_type => false,
26652649 .ptr_type => |ptr_type| {
26662650 const child_ty = ptr_type.child.toType();
......@@ -2704,6 +2688,7 @@ pub const Type = struct {
27042688 .c_longlong,
27052689 .c_ulonglong,
27062690 .c_longdouble,
2691 .anyopaque,
27072692 .bool,
27082693 .void,
27092694 .anyerror,
......@@ -2722,7 +2707,6 @@ pub const Type = struct {
27222707 .extern_options,
27232708 => false,
27242709
2725 .anyopaque,
27262710 .type,
27272711 .comptime_int,
27282712 .comptime_float,
......@@ -2756,8 +2740,7 @@ pub const Type = struct {
27562740 },
27572741
27582742 .union_type => |union_type| {
2759 const union_obj = mod.unionPtr(union_type.index);
2760 switch (union_obj.requires_comptime) {
2743 switch (union_type.flagsPtr(ip).requires_comptime) {
27612744 .wip, .unknown => {
27622745 // Return false to avoid incorrect dependency loops.
27632746 // This will be handled correctly once merged with
......@@ -2769,7 +2752,7 @@ pub const Type = struct {
27692752 }
27702753 },
27712754
2772 .opaque_type => true,
2755 .opaque_type => false,
27732756
27742757 .enum_type => |enum_type| enum_type.tag_ty.toType().comptimeOnly(mod),
27752758
......@@ -2847,7 +2830,7 @@ pub const Type = struct {
28472830 return switch (mod.intern_pool.indexToKey(ty.toIntern())) {
28482831 .opaque_type => |opaque_type| opaque_type.namespace.toOptional(),
28492832 .struct_type => |struct_type| struct_type.namespace,
2850 .union_type => |union_type| mod.unionPtr(union_type.index).namespace.toOptional(),
2833 .union_type => |union_type| union_type.namespace.toOptional(),
28512834 .enum_type => |enum_type| enum_type.namespace,
28522835
28532836 else => .none,
......@@ -2935,7 +2918,7 @@ pub const Type = struct {
29352918 /// Asserts the type is an enum or a union.
29362919 pub fn intTagType(ty: Type, mod: *Module) Type {
29372920 return switch (mod.intern_pool.indexToKey(ty.toIntern())) {
2938 .union_type => |union_type| mod.unionPtr(union_type.index).tag_ty.intTagType(mod),
2921 .union_type => |union_type| union_type.enum_tag_ty.toType().intTagType(mod),
29392922 .enum_type => |enum_type| enum_type.tag_ty.toType(),
29402923 else => unreachable,
29412924 };
......@@ -3038,15 +3021,16 @@ pub const Type = struct {
30383021
30393022 /// Supports structs and unions.
30403023 pub fn structFieldType(ty: Type, index: usize, mod: *Module) Type {
3041 return switch (mod.intern_pool.indexToKey(ty.toIntern())) {
3024 const ip = &mod.intern_pool;
3025 return switch (ip.indexToKey(ty.toIntern())) {
30423026 .struct_type => |struct_type| {
30433027 const struct_obj = mod.structPtrUnwrap(struct_type.index).?;
30443028 assert(struct_obj.haveFieldTypes());
30453029 return struct_obj.fields.values()[index].ty;
30463030 },
30473031 .union_type => |union_type| {
3048 const union_obj = mod.unionPtr(union_type.index);
3049 return union_obj.fields.values()[index].ty;
3032 const union_obj = ip.loadUnionType(union_type);
3033 return union_obj.field_types.get(ip)[index].toType();
30503034 },
30513035 .anon_struct_type => |anon_struct| anon_struct.types[index].toType(),
30523036 else => unreachable,
......@@ -3054,7 +3038,8 @@ pub const Type = struct {
30543038 }
30553039
30563040 pub fn structFieldAlign(ty: Type, index: usize, mod: *Module) u32 {
3057 switch (mod.intern_pool.indexToKey(ty.toIntern())) {
3041 const ip = &mod.intern_pool;
3042 switch (ip.indexToKey(ty.toIntern())) {
30583043 .struct_type => |struct_type| {
30593044 const struct_obj = mod.structPtrUnwrap(struct_type.index).?;
30603045 assert(struct_obj.layout != .Packed);
......@@ -3064,8 +3049,8 @@ pub const Type = struct {
30643049 return anon_struct.types[index].toType().abiAlignment(mod);
30653050 },
30663051 .union_type => |union_type| {
3067 const union_obj = mod.unionPtr(union_type.index);
3068 return union_obj.fields.values()[index].normalAlignment(mod);
3052 const union_obj = ip.loadUnionType(union_type);
3053 return mod.unionFieldNormalAlignment(union_obj, @intCast(index));
30693054 },
30703055 else => unreachable,
30713056 }
......@@ -3198,7 +3183,8 @@ pub const Type = struct {
31983183
31993184 /// Supports structs and unions.
32003185 pub fn structFieldOffset(ty: Type, index: usize, mod: *Module) u64 {
3201 switch (mod.intern_pool.indexToKey(ty.toIntern())) {
3186 const ip = &mod.intern_pool;
3187 switch (ip.indexToKey(ty.toIntern())) {
32023188 .struct_type => |struct_type| {
32033189 const struct_obj = mod.structPtrUnwrap(struct_type.index).?;
32043190 assert(struct_obj.haveLayout());
......@@ -3234,10 +3220,10 @@ pub const Type = struct {
32343220 },
32353221
32363222 .union_type => |union_type| {
3237 if (!union_type.hasTag())
3223 if (!union_type.hasTag(ip))
32383224 return 0;
3239 const union_obj = mod.unionPtr(union_type.index);
3240 const layout = union_obj.getLayout(mod, true);
3225 const union_obj = ip.loadUnionType(union_type);
3226 const layout = mod.getUnionLayout(union_obj);
32413227 if (layout.tag_align >= layout.payload_align) {
32423228 // {Tag, Payload}
32433229 return std.mem.alignForward(u64, layout.tag_size, layout.payload_align);
......@@ -3262,8 +3248,7 @@ pub const Type = struct {
32623248 return struct_obj.srcLoc(mod);
32633249 },
32643250 .union_type => |union_type| {
3265 const union_obj = mod.unionPtr(union_type.index);
3266 return union_obj.srcLoc(mod);
3251 return mod.declPtr(union_type.decl).srcLoc(mod);
32673252 },
32683253 .opaque_type => |opaque_type| mod.opaqueSrcLoc(opaque_type),
32693254 .enum_type => |enum_type| mod.declPtr(enum_type.decl).srcLoc(mod),
......@@ -3281,10 +3266,7 @@ pub const Type = struct {
32813266 const struct_obj = mod.structPtrUnwrap(struct_type.index) orelse return null;
32823267 return struct_obj.owner_decl;
32833268 },
3284 .union_type => |union_type| {
3285 const union_obj = mod.unionPtr(union_type.index);
3286 return union_obj.owner_decl;
3287 },
3269 .union_type => |union_type| union_type.decl,
32883270 .opaque_type => |opaque_type| opaque_type.decl,
32893271 .enum_type => |enum_type| enum_type.decl,
32903272 else => null,
src/value.zig+16-12
......@@ -734,6 +734,7 @@ pub const Value = struct {
734734 buffer: []u8,
735735 bit_offset: usize,
736736 ) error{ ReinterpretDeclRef, OutOfMemory }!void {
737 const ip = &mod.intern_pool;
737738 const target = mod.getTarget();
738739 const endian = target.cpu.arch.endian();
739740 if (val.isUndef(mod)) {
......@@ -759,7 +760,7 @@ pub const Value = struct {
759760 const bits = ty.intInfo(mod).bits;
760761 if (bits == 0) return;
761762
762 switch (mod.intern_pool.indexToKey((try val.intFromEnum(ty, mod)).toIntern()).int.storage) {
763 switch (ip.indexToKey((try val.intFromEnum(ty, mod)).toIntern()).int.storage) {
763764 inline .u64, .i64 => |int| std.mem.writeVarPackedInt(buffer, bit_offset, bits, int, endian),
764765 .big_int => |bigint| bigint.writePackedTwosComplement(buffer, bit_offset, bits, endian),
765766 else => unreachable,
......@@ -794,7 +795,7 @@ pub const Value = struct {
794795 .Packed => {
795796 var bits: u16 = 0;
796797 const fields = ty.structFields(mod).values();
797 const storage = mod.intern_pool.indexToKey(val.toIntern()).aggregate.storage;
798 const storage = ip.indexToKey(val.toIntern()).aggregate.storage;
798799 for (fields, 0..) |field, i| {
799800 const field_bits = @as(u16, @intCast(field.ty.bitSize(mod)));
800801 const field_val = switch (storage) {
......@@ -807,16 +808,19 @@ pub const Value = struct {
807808 }
808809 },
809810 },
810 .Union => switch (ty.containerLayout(mod)) {
811 .Auto => unreachable, // Sema is supposed to have emitted a compile error already
812 .Extern => unreachable, // Handled in non-packed writeToMemory
813 .Packed => {
814 const field_index = ty.unionTagFieldIndex(val.unionTag(mod), mod);
815 const field_type = ty.unionFields(mod).values()[field_index.?].ty;
816 const field_val = try val.fieldValue(mod, field_index.?);
817
818 return field_val.writeToPackedMemory(field_type, mod, buffer, bit_offset);
819 },
811 .Union => {
812 const union_obj = mod.typeToUnion(ty).?;
813 switch (union_obj.getLayout(ip)) {
814 .Auto => unreachable, // Sema is supposed to have emitted a compile error already
815 .Extern => unreachable, // Handled in non-packed writeToMemory
816 .Packed => {
817 const field_index = mod.unionTagFieldIndex(union_obj, val.unionTag(mod)).?;
818 const field_type = union_obj.field_types.get(ip)[field_index].toType();
819 const field_val = try val.fieldValue(mod, field_index);
820
821 return field_val.writeToPackedMemory(field_type, mod, buffer, bit_offset);
822 },
823 }
820824 },
821825 .Pointer => {
822826 assert(!ty.isSlice(mod)); // No well defined layout.
test/behavior/union.zig+1-26
......@@ -1347,31 +1347,6 @@ test "noreturn field in union" {
13471347 try expect(count == 6);
13481348}
13491349
1350test "union and enum field order doesn't match" {
1351 if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO
1352 if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO
1353 if (builtin.zig_backend == .stage2_sparc64) return error.SkipZigTest; // TODO
1354 if (builtin.zig_backend == .stage2_spirv64) return error.SkipZigTest;
1355
1356 const MyTag = enum(u32) {
1357 b = 1337,
1358 a = 1666,
1359 };
1360 const MyUnion = union(MyTag) {
1361 a: f32,
1362 b: void,
1363 };
1364 var x: MyUnion = .{ .a = 666 };
1365 switch (x) {
1366 .a => |my_f32| {
1367 try expect(@TypeOf(my_f32) == f32);
1368 },
1369 .b => unreachable,
1370 }
1371 x = .b;
1372 try expect(x == .b);
1373}
1374
13751350test "@unionInit uses tag value instead of field index" {
13761351 if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO
13771352 if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO
......@@ -1383,8 +1358,8 @@ test "@unionInit uses tag value instead of field index" {
13831358 a = 3,
13841359 };
13851360 const U = union(E) {
1386 a: usize,
13871361 b: isize,
1362 a: usize,
13881363 };
13891364 var i: isize = -1;
13901365 var u = @unionInit(U, "b", i);
test/cases/compile_errors/access_inactive_union_field_comptime.zig+1-1
......@@ -1,4 +1,4 @@
1const Enum = enum(u32) { a, b };
1const Enum = enum(u32) { b, a };
22const TaggedUnion = union(Enum) {
33 b: []const u8,
44 a: []const u8,
test/cases/compile_errors/dereference_anyopaque.zig+1-2
......@@ -45,8 +45,7 @@ pub export fn entry() void {
4545// backend=llvm
4646//
4747// :11:22: error: comparison of 'void' with null
48// :25:51: error: values of type 'anyopaque' must be comptime-known, but operand value is runtime-known
49// :25:51: note: opaque type 'anyopaque' has undefined size
48// :25:51: error: cannot load opaque type 'anyopaque'
5049// :25:51: error: values of type 'fn(*anyopaque, usize, u8, usize) ?[*]u8' must be comptime-known, but operand value is runtime-known
5150// :25:51: note: use '*const fn(*anyopaque, usize, u8, usize) ?[*]u8' for a function pointer type
5251// :25:51: error: values of type 'fn(*anyopaque, []u8, u8, usize, usize) bool' must be comptime-known, but operand value is runtime-known
test/cases/compile_errors/directly_embedding_opaque_type_in_struct_and_union.zig+4-6
......@@ -15,12 +15,12 @@ export fn b() void {
1515 _ = bar;
1616}
1717export fn c() void {
18 const baz = &@as(opaque {}, undefined);
18 const baz = &@as(O, undefined);
1919 const qux = .{baz.*};
2020 _ = qux;
2121}
2222export fn d() void {
23 const baz = &@as(opaque {}, undefined);
23 const baz = &@as(O, undefined);
2424 const qux = .{ .a = baz.* };
2525 _ = qux;
2626}
......@@ -33,7 +33,5 @@ export fn d() void {
3333// :1:11: note: opaque declared here
3434// :7:10: error: opaque types have unknown size and therefore cannot be directly embedded in unions
3535// :1:11: note: opaque declared here
36// :19:18: error: opaque types have unknown size and therefore cannot be directly embedded in structs
37// :18:22: note: opaque declared here
38// :24:23: error: opaque types have unknown size and therefore cannot be directly embedded in structs
39// :23:22: note: opaque declared here
36// :19:22: error: cannot load opaque type 'tmp.O'
37// :24:28: error: cannot load opaque type 'tmp.O'
test/cases/compile_errors/non-const_variables_of_things_that_require_const_variables.zig+6-2
......@@ -27,6 +27,10 @@ export fn entry7() void {
2727 _ = f;
2828}
2929const Opaque = opaque {};
30export fn entry8() void {
31 var e: Opaque = undefined;
32 _ = &e;
33}
3034
3135// error
3236// backend=stage2
......@@ -39,7 +43,7 @@ const Opaque = opaque {};
3943// :14:9: error: variable of type 'comptime_float' must be const or comptime
4044// :14:9: note: to modify this variable at runtime, it must be given an explicit fixed-size number type
4145// :18:9: error: variable of type '@TypeOf(null)' must be const or comptime
42// :22:20: error: values of type 'tmp.Opaque' must be comptime-known, but operand value is runtime-known
43// :22:20: note: opaque type 'tmp.Opaque' has undefined size
46// :22:20: error: cannot load opaque type 'tmp.Opaque'
4447// :26:9: error: variable of type 'type' must be const or comptime
4548// :26:9: note: types are not available at runtime
49// :31:12: error: non-extern variable with opaque type 'tmp.Opaque'