authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2022-12-19 15:47:31-05:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2022-12-19 15:47:31-05:00
log0fb53bd245e258f69654119e5a1913d6d42dc181
treeb2fe08ac32aa43c42cf05d29985c326d20b57994
parent3542dbf0ea5bc1ddb1c5e1c856745dc07e6c0a18
parent0768115b01f01ab1c75da3e42ffcdc99078eaad2
signaturebadge-question-mark Signed by PGP key 4AEE18F83AFDEB23

Merge pull request #14000 from jacobly0/zero-bit-fields

codegen: fix taking the address of a field in a zero-bit struct

6 files changed, 89 insertions(+), 33 deletions(-)

lib/std/mem.zig+12-5
...@@ -3291,7 +3291,7 @@ pub fn nativeToBig(comptime T: type, x: T) T {...@@ -3291,7 +3291,7 @@ pub fn nativeToBig(comptime T: type, x: T) T {
3291/// - The delta required to align the pointer is not a multiple of the pointee's3291/// - The delta required to align the pointer is not a multiple of the pointee's
3292/// type.3292/// type.
3293pub fn alignPointerOffset(ptr: anytype, align_to: usize) ?usize {3293pub fn alignPointerOffset(ptr: anytype, align_to: usize) ?usize {
3294 assert(align_to != 0 and @popCount(align_to) == 1);3294 assert(isValidAlign(align_to));
32953295
3296 const T = @TypeOf(ptr);3296 const T = @TypeOf(ptr);
3297 const info = @typeInfo(T);3297 const info = @typeInfo(T);
...@@ -3751,6 +3751,7 @@ pub fn alignForwardLog2(addr: usize, log2_alignment: u8) usize {...@@ -3751,6 +3751,7 @@ pub fn alignForwardLog2(addr: usize, log2_alignment: u8) usize {
3751/// The alignment must be a power of 2 and greater than 0.3751/// The alignment must be a power of 2 and greater than 0.
3752/// Asserts that rounding up the address does not cause integer overflow.3752/// Asserts that rounding up the address does not cause integer overflow.
3753pub fn alignForwardGeneric(comptime T: type, addr: T, alignment: T) T {3753pub fn alignForwardGeneric(comptime T: type, addr: T, alignment: T) T {
3754 assert(isValidAlignGeneric(T, alignment));
3754 return alignBackwardGeneric(T, addr + (alignment - 1), alignment);3755 return alignBackwardGeneric(T, addr + (alignment - 1), alignment);
3755}3756}
37563757
...@@ -3846,7 +3847,7 @@ test "alignForward" {...@@ -3846,7 +3847,7 @@ test "alignForward" {
3846/// Round an address down to the previous (or current) aligned address.3847/// Round an address down to the previous (or current) aligned address.
3847/// Unlike `alignBackward`, `alignment` can be any positive number, not just a power of 2.3848/// Unlike `alignBackward`, `alignment` can be any positive number, not just a power of 2.
3848pub fn alignBackwardAnyAlign(i: usize, alignment: usize) usize {3849pub fn alignBackwardAnyAlign(i: usize, alignment: usize) usize {
3849 if (@popCount(alignment) == 1)3850 if (isValidAlign(alignment))
3850 return alignBackward(i, alignment);3851 return alignBackward(i, alignment);
3851 assert(alignment != 0);3852 assert(alignment != 0);
3852 return i - @mod(i, alignment);3853 return i - @mod(i, alignment);
...@@ -3861,7 +3862,7 @@ pub fn alignBackward(addr: usize, alignment: usize) usize {...@@ -3861,7 +3862,7 @@ pub fn alignBackward(addr: usize, alignment: usize) usize {
3861/// Round an address down to the previous (or current) aligned address.3862/// Round an address down to the previous (or current) aligned address.
3862/// The alignment must be a power of 2 and greater than 0.3863/// The alignment must be a power of 2 and greater than 0.
3863pub fn alignBackwardGeneric(comptime T: type, addr: T, alignment: T) T {3864pub fn alignBackwardGeneric(comptime T: type, addr: T, alignment: T) T {
3864 assert(@popCount(alignment) == 1);3865 assert(isValidAlignGeneric(T, alignment));
3865 // 000010000 // example alignment3866 // 000010000 // example alignment
3866 // 000001111 // subtract 13867 // 000001111 // subtract 1
3867 // 111110000 // binary not3868 // 111110000 // binary not
...@@ -3871,11 +3872,17 @@ pub fn alignBackwardGeneric(comptime T: type, addr: T, alignment: T) T {...@@ -3871,11 +3872,17 @@ pub fn alignBackwardGeneric(comptime T: type, addr: T, alignment: T) T {
3871/// Returns whether `alignment` is a valid alignment, meaning it is3872/// Returns whether `alignment` is a valid alignment, meaning it is
3872/// a positive power of 2.3873/// a positive power of 2.
3873pub fn isValidAlign(alignment: usize) bool {3874pub fn isValidAlign(alignment: usize) bool {
3874 return @popCount(alignment) == 1;3875 return isValidAlignGeneric(usize, alignment);
3876}
3877
3878/// Returns whether `alignment` is a valid alignment, meaning it is
3879/// a positive power of 2.
3880pub fn isValidAlignGeneric(comptime T: type, alignment: T) bool {
3881 return alignment > 0 and std.math.isPowerOfTwo(alignment);
3875}3882}
38763883
3877pub fn isAlignedAnyAlign(i: usize, alignment: usize) bool {3884pub fn isAlignedAnyAlign(i: usize, alignment: usize) bool {
3878 if (@popCount(alignment) == 1)3885 if (isValidAlign(alignment))
3879 return isAligned(i, alignment);3886 return isAligned(i, alignment);
3880 assert(alignment != 0);3887 assert(alignment != 0);
3881 return 0 == @mod(i, alignment);3888 return 0 == @mod(i, alignment);
src/codegen/c.zig+4-2
...@@ -653,7 +653,7 @@ pub const DeclGen = struct {...@@ -653,7 +653,7 @@ pub const DeclGen = struct {
653 }653 }
654 try writer.print("{ }", .{fmtIdent(field_info.name)});654 try writer.print("{ }", .{fmtIdent(field_info.name)});
655 } else {655 } else {
656 try dg.renderParentPtr(writer, field_ptr.container_ptr, field_info.ty);656 try dg.renderParentPtr(writer, field_ptr.container_ptr, container_ptr_ty);
657 }657 }
658 },658 },
659 .elem_ptr => {659 .elem_ptr => {
...@@ -5131,7 +5131,9 @@ fn structFieldPtr(f: *Function, inst: Air.Inst.Index, struct_ptr_ty: Type, struc...@@ -5131,7 +5131,9 @@ fn structFieldPtr(f: *Function, inst: Air.Inst.Index, struct_ptr_ty: Type, struc
5131 .begin, .end => {5131 .begin, .end => {
5132 try writer.writeByte('(');5132 try writer.writeByte('(');
5133 try f.writeCValue(writer, struct_ptr, .Other);5133 try f.writeCValue(writer, struct_ptr, .Other);
5134 try writer.print(")[{}]", .{@boolToInt(field_loc == .end)});5134 try writer.print(")[{}]", .{
5135 @boolToInt(field_loc == .end and struct_ty.hasRuntimeBitsIgnoreComptime()),
5136 });
5135 },5137 },
5136 .field => |field| if (extra_name != .none) {5138 .field => |field| if (extra_name != .none) {
5137 try f.writeCValueDerefMember(writer, struct_ptr, extra_name);5139 try f.writeCValueDerefMember(writer, struct_ptr, extra_name);
src/codegen/llvm.zig+18-11
...@@ -2969,7 +2969,7 @@ pub const DeclGen = struct {...@@ -2969,7 +2969,7 @@ pub const DeclGen = struct {
29692969
2970 comptime assert(struct_layout_version == 2);2970 comptime assert(struct_layout_version == 2);
2971 var offset: u64 = 0;2971 var offset: u64 = 0;
2972 var big_align: u32 = 0;2972 var big_align: u32 = 1;
2973 var any_underaligned_fields = false;2973 var any_underaligned_fields = false;
29742974
2975 for (struct_obj.fields.values()) |field| {2975 for (struct_obj.fields.values()) |field| {
...@@ -4033,16 +4033,23 @@ pub const DeclGen = struct {...@@ -4033,16 +4033,23 @@ pub const DeclGen = struct {
4033 const final_llvm_ty = (try dg.lowerType(ptr_child_ty)).pointerType(0);4033 const final_llvm_ty = (try dg.lowerType(ptr_child_ty)).pointerType(0);
4034 break :blk field_addr.constIntToPtr(final_llvm_ty);4034 break :blk field_addr.constIntToPtr(final_llvm_ty);
4035 }4035 }
4036 bitcast_needed = !field_ty.eql(ptr_child_ty, dg.module);
40374036
4038 var ty_buf: Type.Payload.Pointer = undefined;4037 var ty_buf: Type.Payload.Pointer = undefined;
4039 const llvm_field_index = llvmFieldIndex(parent_ty, field_index, target, &ty_buf).?;4038
4040 const indices: [2]*llvm.Value = .{
4041 llvm_u32.constInt(0, .False),
4042 llvm_u32.constInt(llvm_field_index, .False),
4043 };
4044 const parent_llvm_ty = try dg.lowerType(parent_ty);4039 const parent_llvm_ty = try dg.lowerType(parent_ty);
4045 break :blk parent_llvm_ty.constInBoundsGEP(parent_llvm_ptr, &indices, indices.len);4040 if (llvmFieldIndex(parent_ty, field_index, target, &ty_buf)) |llvm_field_index| {
4041 bitcast_needed = !field_ty.eql(ptr_child_ty, dg.module);
4042 const indices: [2]*llvm.Value = .{
4043 llvm_u32.constInt(0, .False),
4044 llvm_u32.constInt(llvm_field_index, .False),
4045 };
4046 break :blk parent_llvm_ty.constInBoundsGEP(parent_llvm_ptr, &indices, indices.len);
4047 } else {
4048 bitcast_needed = !parent_ty.eql(ptr_child_ty, dg.module);
4049 const llvm_index = llvm_u32.constInt(@boolToInt(parent_ty.hasRuntimeBitsIgnoreComptime()), .False);
4050 const indices: [1]*llvm.Value = .{llvm_index};
4051 break :blk parent_llvm_ty.constInBoundsGEP(parent_llvm_ptr, &indices, indices.len);
4052 }
4046 },4053 },
4047 .Pointer => {4054 .Pointer => {
4048 assert(parent_ty.isSlice());4055 assert(parent_ty.isSlice());
...@@ -4117,7 +4124,7 @@ pub const DeclGen = struct {...@@ -4117,7 +4124,7 @@ pub const DeclGen = struct {
4117 else => unreachable,4124 else => unreachable,
4118 };4125 };
4119 if (bitcast_needed) {4126 if (bitcast_needed) {
4120 return llvm_ptr.constBitCast((try dg.lowerType(ptr_child_ty)).pointerType(0));4127 return llvm_ptr.constBitCast((try dg.lowerPtrElemTy(ptr_child_ty)).pointerType(0));
4121 } else {4128 } else {
4122 return llvm_ptr;4129 return llvm_ptr;
4123 }4130 }
...@@ -9766,8 +9773,8 @@ pub const FuncGen = struct {...@@ -9766,8 +9773,8 @@ pub const FuncGen = struct {
9766 // end of the struct. Treat our struct pointer as an array of two and get9773 // end of the struct. Treat our struct pointer as an array of two and get
9767 // the index to the element at index `1` to get a pointer to the end of9774 // the index to the element at index `1` to get a pointer to the end of
9768 // the struct.9775 // the struct.
9769 const llvm_usize = try self.dg.lowerType(Type.usize);9776 const llvm_u32 = self.dg.context.intType(32);
9770 const llvm_index = llvm_usize.constInt(1, .False);9777 const llvm_index = llvm_u32.constInt(@boolToInt(struct_ty.hasRuntimeBitsIgnoreComptime()), .False);
9771 const indices: [1]*llvm.Value = .{llvm_index};9778 const indices: [1]*llvm.Value = .{llvm_index};
9772 return self.builder.buildInBoundsGEP(struct_llvm_ty, struct_ptr, &indices, indices.len, "");9779 return self.builder.buildInBoundsGEP(struct_llvm_ty, struct_ptr, &indices, indices.len, "");
9773 }9780 }
src/value.zig+10-2
...@@ -2915,8 +2915,16 @@ pub const Value = extern union {...@@ -2915,8 +2915,16 @@ pub const Value = extern union {
2915 .field_ptr => val.castTag(.field_ptr).?.data.container_ptr.isVariable(mod),2915 .field_ptr => val.castTag(.field_ptr).?.data.container_ptr.isVariable(mod),
2916 .eu_payload_ptr => val.castTag(.eu_payload_ptr).?.data.container_ptr.isVariable(mod),2916 .eu_payload_ptr => val.castTag(.eu_payload_ptr).?.data.container_ptr.isVariable(mod),
2917 .opt_payload_ptr => val.castTag(.opt_payload_ptr).?.data.container_ptr.isVariable(mod),2917 .opt_payload_ptr => val.castTag(.opt_payload_ptr).?.data.container_ptr.isVariable(mod),
2918 .decl_ref => mod.declPtr(val.castTag(.decl_ref).?.data).val.isVariable(mod),2918 .decl_ref => {
2919 .decl_ref_mut => mod.declPtr(val.castTag(.decl_ref_mut).?.data.decl_index).val.isVariable(mod),2919 const decl = mod.declPtr(val.castTag(.decl_ref).?.data);
2920 assert(decl.has_tv);
2921 return decl.val.isVariable(mod);
2922 },
2923 .decl_ref_mut => {
2924 const decl = mod.declPtr(val.castTag(.decl_ref_mut).?.data.decl_index);
2925 assert(decl.has_tv);
2926 return decl.val.isVariable(mod);
2927 },
29202928
2921 .variable => true,2929 .variable => true,
2922 else => false,2930 else => false,
test/behavior/bugs/3742.zig+2
...@@ -39,5 +39,7 @@ test "fixed" {...@@ -39,5 +39,7 @@ test "fixed" {
39 if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest;39 if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest;
40 if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest;40 if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest;
41 if (builtin.zig_backend == .stage2_sparc64) return error.SkipZigTest; // TODO41 if (builtin.zig_backend == .stage2_sparc64) return error.SkipZigTest; // TODO
42 if (builtin.zig_backend == .stage2_llvm and
43 builtin.cpu.arch == .aarch64 and builtin.os.tag == .windows) return error.SkipZigTest;
42 ArgSerializer.serializeCommand(GET.init("banana"));44 ArgSerializer.serializeCommand(GET.init("banana"));
43}45}
test/behavior/struct.zig+43-13
...@@ -1359,23 +1359,53 @@ test "under-aligned struct field" {...@@ -1359,23 +1359,53 @@ test "under-aligned struct field" {
1359 try expect(result == 1234);1359 try expect(result == 1234);
1360}1360}
13611361
1362test "address of zero-bit field is equal to address of only field" {1362test "fieldParentPtr of a zero-bit field" {
1363 if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO1363 if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO
1364 if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO1364 if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO
1365 if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO1365 if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO
13661366
1367 {1367 const S = struct {
1368 const A = struct { b: void = {}, u: u8 };1368 fn testStruct(comptime A: type) !void {
1369 var a = A{ .u = 0 };1369 {
1370 const a_ptr = @fieldParentPtr(A, "b", &a.b);1370 const a = A{ .u = 0 };
1371 try std.testing.expectEqual(&a, a_ptr);1371 const b_ptr = &a.b;
1372 }1372 const a_ptr = @fieldParentPtr(A, "b", b_ptr);
1373 {1373 try std.testing.expectEqual(&a, a_ptr);
1374 const A = struct { u: u8, b: void = {} };1374 }
1375 var a = A{ .u = 0 };1375 {
1376 const a_ptr = @fieldParentPtr(A, "b", &a.b);1376 var a = A{ .u = 0 };
1377 try std.testing.expectEqual(&a, a_ptr);1377 const b_ptr = &a.b;
1378 }1378 const a_ptr = @fieldParentPtr(A, "b", b_ptr);
1379 try std.testing.expectEqual(&a, a_ptr);
1380 }
1381 }
1382 fn testNestedStruct(comptime A: type) !void {
1383 {
1384 const a = A{ .u = 0 };
1385 const c_ptr = &a.b.c;
1386 const b_ptr = @fieldParentPtr(@TypeOf(a.b), "c", c_ptr);
1387 try std.testing.expectEqual(&a.b, b_ptr);
1388 const a_ptr = @fieldParentPtr(A, "b", b_ptr);
1389 try std.testing.expectEqual(&a, a_ptr);
1390 }
1391 {
1392 var a = A{ .u = 0 };
1393 const c_ptr = &a.b.c;
1394 const b_ptr = @fieldParentPtr(@TypeOf(a.b), "c", c_ptr);
1395 try std.testing.expectEqual(&a.b, b_ptr);
1396 const a_ptr = @fieldParentPtr(A, "b", b_ptr);
1397 try std.testing.expectEqual(&a, a_ptr);
1398 }
1399 }
1400 fn doTheTest() !void {
1401 try testStruct(struct { b: void = {}, u: u8 });
1402 try testStruct(struct { u: u8, b: void = {} });
1403 try testNestedStruct(struct { b: struct { c: void = {} } = .{}, u: u8 });
1404 try testNestedStruct(struct { u: u8, b: struct { c: void = {} } = .{} });
1405 }
1406 };
1407 try S.doTheTest();
1408 comptime try S.doTheTest();
1379}1409}
13801410
1381test "struct field has a pointer to an aligned version of itself" {1411test "struct field has a pointer to an aligned version of itself" {