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 {
32913291/// - The delta required to align the pointer is not a multiple of the pointee's
32923292/// type.
32933293pub fn alignPointerOffset(ptr: anytype, align_to: usize) ?usize {
3294 assert(align_to != 0 and @popCount(align_to) == 1);
3294 assert(isValidAlign(align_to));
32953295
32963296 const T = @TypeOf(ptr);
32973297 const info = @typeInfo(T);
......@@ -3751,6 +3751,7 @@ pub fn alignForwardLog2(addr: usize, log2_alignment: u8) usize {
37513751/// The alignment must be a power of 2 and greater than 0.
37523752/// Asserts that rounding up the address does not cause integer overflow.
37533753pub fn alignForwardGeneric(comptime T: type, addr: T, alignment: T) T {
3754 assert(isValidAlignGeneric(T, alignment));
37543755 return alignBackwardGeneric(T, addr + (alignment - 1), alignment);
37553756}
37563757
......@@ -3846,7 +3847,7 @@ test "alignForward" {
38463847/// Round an address down to the previous (or current) aligned address.
38473848/// Unlike `alignBackward`, `alignment` can be any positive number, not just a power of 2.
38483849pub fn alignBackwardAnyAlign(i: usize, alignment: usize) usize {
3849 if (@popCount(alignment) == 1)
3850 if (isValidAlign(alignment))
38503851 return alignBackward(i, alignment);
38513852 assert(alignment != 0);
38523853 return i - @mod(i, alignment);
......@@ -3861,7 +3862,7 @@ pub fn alignBackward(addr: usize, alignment: usize) usize {
38613862/// Round an address down to the previous (or current) aligned address.
38623863/// The alignment must be a power of 2 and greater than 0.
38633864pub fn alignBackwardGeneric(comptime T: type, addr: T, alignment: T) T {
3864 assert(@popCount(alignment) == 1);
3865 assert(isValidAlignGeneric(T, alignment));
38653866 // 000010000 // example alignment
38663867 // 000001111 // subtract 1
38673868 // 111110000 // binary not
......@@ -3871,11 +3872,17 @@ pub fn alignBackwardGeneric(comptime T: type, addr: T, alignment: T) T {
38713872/// Returns whether `alignment` is a valid alignment, meaning it is
38723873/// a positive power of 2.
38733874pub 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);
38753882}
38763883
38773884pub fn isAlignedAnyAlign(i: usize, alignment: usize) bool {
3878 if (@popCount(alignment) == 1)
3885 if (isValidAlign(alignment))
38793886 return isAligned(i, alignment);
38803887 assert(alignment != 0);
38813888 return 0 == @mod(i, alignment);
src/codegen/c.zig+4-2
......@@ -653,7 +653,7 @@ pub const DeclGen = struct {
653653 }
654654 try writer.print("{ }", .{fmtIdent(field_info.name)});
655655 } 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);
657657 }
658658 },
659659 .elem_ptr => {
......@@ -5131,7 +5131,9 @@ fn structFieldPtr(f: *Function, inst: Air.Inst.Index, struct_ptr_ty: Type, struc
51315131 .begin, .end => {
51325132 try writer.writeByte('(');
51335133 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 });
51355137 },
51365138 .field => |field| if (extra_name != .none) {
51375139 try f.writeCValueDerefMember(writer, struct_ptr, extra_name);
src/codegen/llvm.zig+18-11
......@@ -2969,7 +2969,7 @@ pub const DeclGen = struct {
29692969
29702970 comptime assert(struct_layout_version == 2);
29712971 var offset: u64 = 0;
2972 var big_align: u32 = 0;
2972 var big_align: u32 = 1;
29732973 var any_underaligned_fields = false;
29742974
29752975 for (struct_obj.fields.values()) |field| {
......@@ -4033,16 +4033,23 @@ pub const DeclGen = struct {
40334033 const final_llvm_ty = (try dg.lowerType(ptr_child_ty)).pointerType(0);
40344034 break :blk field_addr.constIntToPtr(final_llvm_ty);
40354035 }
4036 bitcast_needed = !field_ty.eql(ptr_child_ty, dg.module);
40374036
40384037 var ty_buf: Type.Payload.Pointer = undefined;
4039 const llvm_field_index = llvmFieldIndex(parent_ty, field_index, target, &ty_buf).?;
4040 const indices: [2]*llvm.Value = .{
4041 llvm_u32.constInt(0, .False),
4042 llvm_u32.constInt(llvm_field_index, .False),
4043 };
4038
40444039 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 }
40464053 },
40474054 .Pointer => {
40484055 assert(parent_ty.isSlice());
......@@ -4117,7 +4124,7 @@ pub const DeclGen = struct {
41174124 else => unreachable,
41184125 };
41194126 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));
41214128 } else {
41224129 return llvm_ptr;
41234130 }
......@@ -9766,8 +9773,8 @@ pub const FuncGen = struct {
97669773 // end of the struct. Treat our struct pointer as an array of two and get
97679774 // the index to the element at index `1` to get a pointer to the end of
97689775 // the struct.
9769 const llvm_usize = try self.dg.lowerType(Type.usize);
9770 const llvm_index = llvm_usize.constInt(1, .False);
9776 const llvm_u32 = self.dg.context.intType(32);
9777 const llvm_index = llvm_u32.constInt(@boolToInt(struct_ty.hasRuntimeBitsIgnoreComptime()), .False);
97719778 const indices: [1]*llvm.Value = .{llvm_index};
97729779 return self.builder.buildInBoundsGEP(struct_llvm_ty, struct_ptr, &indices, indices.len, "");
97739780 }
src/value.zig+10-2
......@@ -2915,8 +2915,16 @@ pub const Value = extern union {
29152915 .field_ptr => val.castTag(.field_ptr).?.data.container_ptr.isVariable(mod),
29162916 .eu_payload_ptr => val.castTag(.eu_payload_ptr).?.data.container_ptr.isVariable(mod),
29172917 .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),
2919 .decl_ref_mut => mod.declPtr(val.castTag(.decl_ref_mut).?.data.decl_index).val.isVariable(mod),
2918 .decl_ref => {
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
29212929 .variable => true,
29222930 else => false,
test/behavior/bugs/3742.zig+2
......@@ -39,5 +39,7 @@ test "fixed" {
3939 if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest;
4040 if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest;
4141 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;
4244 ArgSerializer.serializeCommand(GET.init("banana"));
4345}
test/behavior/struct.zig+43-13
......@@ -1359,23 +1359,53 @@ test "under-aligned struct field" {
13591359 try expect(result == 1234);
13601360}
13611361
1362test "address of zero-bit field is equal to address of only field" {
1362test "fieldParentPtr of a zero-bit field" {
13631363 if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO
13641364 if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO
13651365 if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO
13661366
1367 {
1368 const A = struct { b: void = {}, u: u8 };
1369 var a = A{ .u = 0 };
1370 const a_ptr = @fieldParentPtr(A, "b", &a.b);
1371 try std.testing.expectEqual(&a, a_ptr);
1372 }
1373 {
1374 const A = struct { u: u8, b: void = {} };
1375 var a = A{ .u = 0 };
1376 const a_ptr = @fieldParentPtr(A, "b", &a.b);
1377 try std.testing.expectEqual(&a, a_ptr);
1378 }
1367 const S = struct {
1368 fn testStruct(comptime A: type) !void {
1369 {
1370 const a = A{ .u = 0 };
1371 const b_ptr = &a.b;
1372 const a_ptr = @fieldParentPtr(A, "b", b_ptr);
1373 try std.testing.expectEqual(&a, a_ptr);
1374 }
1375 {
1376 var a = A{ .u = 0 };
1377 const b_ptr = &a.b;
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();
13791409}
13801410
13811411test "struct field has a pointer to an aligned version of itself" {