authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2021-10-25 15:06:47-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2021-10-25 15:11:21-07:00
log8509e7111d80a07e778aa2a57d58d2bea6945014
treee7eedaf980ada713a6c3d2da3e6153751d03bed6
parenta132190cad80669306705b72276e9641401426fb

stage2: fix switch on tagged union capture-by-pointer

* AstGen: always use `typeof` and never `typeof_elem` on the `switch_cond`/`switch_cond_ref` instruction because both variants return a value and not a pointer. - Delete the `typeof_elem` ZIR instruction since it is no longer needed. * Sema: validateUnionInit now recognizes a comptime mutable value and no longer emits a compile error saying "cannot evaluate constant expression" - Still to-do is detecting comptime union values in a function that is not being executed at compile-time. - This is still to-do for structs too. * Sema: when emitting a call AIR instruction, call resolveTypeLayout on all the parameter types as well as the return type. * `Type.structFieldOffset` now works for unions in addition to structs.

7 files changed, 115 insertions(+), 97 deletions(-)

src/AstGen.zig+2-4
......@@ -2109,7 +2109,6 @@ fn unusedResultExpr(gz: *GenZir, scope: *Scope, statement: Ast.Node.Index) Inner
21092109 .negate,
21102110 .negate_wrap,
21112111 .typeof,
2112 .typeof_elem,
21132112 .xor,
21142113 .optional_type,
21152114 .optional_payload_safe,
......@@ -6028,8 +6027,7 @@ fn switchExpr(
60286027 const cond_tag: Zir.Inst.Tag = if (any_payload_is_ref) .switch_cond_ref else .switch_cond;
60296028 const cond = try parent_gz.addUnNode(cond_tag, raw_operand, operand_node);
60306029 // We need the type of the operand to use as the result location for all the prong items.
6031 const typeof_tag: Zir.Inst.Tag = if (any_payload_is_ref) .typeof_elem else .typeof;
6032 const cond_ty_inst = try parent_gz.addUnNode(typeof_tag, cond, operand_node);
6030 const cond_ty_inst = try parent_gz.addUnNode(.typeof, cond, operand_node);
60336031 const item_rl: ResultLoc = .{ .ty = cond_ty_inst };
60346032
60356033 // These contain the data that goes into the `extra` array for the SwitchBlock/SwitchBlockMulti.
......@@ -6214,7 +6212,7 @@ fn switchExpr(
62146212 .has_multi_cases = multi_cases_len != 0,
62156213 .has_else = special_prong == .@"else",
62166214 .has_under = special_prong == .under,
6217 .scalar_cases_len = @intCast(u28, scalar_cases_len),
6215 .scalar_cases_len = @intCast(Zir.Inst.SwitchBlock.Bits.ScalarCasesLen, scalar_cases_len),
62186216 },
62196217 });
62206218
src/Sema.zig+22-22
......@@ -608,7 +608,6 @@ pub fn analyzeBody(
608608 .size_of => try sema.zirSizeOf(block, inst),
609609 .bit_size_of => try sema.zirBitSizeOf(block, inst),
610610 .typeof => try sema.zirTypeof(block, inst),
611 .typeof_elem => try sema.zirTypeofElem(block, inst),
612611 .log2_int_type => try sema.zirLog2IntType(block, inst),
613612 .typeof_log2_int_type => try sema.zirTypeofLog2IntType(block, inst),
614613 .xor => try sema.zirBitwise(block, inst, .xor),
......@@ -2337,11 +2336,21 @@ fn validateUnionInit(
23372336 return sema.failWithBadUnionFieldAccess(block, union_obj, field_src, field_name);
23382337 const field_index = @intCast(u32, field_index_big);
23392338
2340 // TODO here we need to go back and see if we need to convert the union
2341 // to a comptime-known value. This will involve editing the AIR code we have
2342 // generated so far - in particular deleting some runtime pointer bitcast
2343 // instructions which are not actually needed if the initialization expression
2344 // ends up being comptime-known.
2339 // Handle the possibility of the union value being comptime-known.
2340 const union_ptr_inst = Air.refToIndex(sema.resolveInst(field_ptr_extra.lhs)).?;
2341 switch (sema.air_instructions.items(.tag)[union_ptr_inst]) {
2342 .constant => return, // In this case the tag has already been set. No validation to do.
2343 .bitcast => {
2344 // TODO here we need to go back and see if we need to convert the union
2345 // to a comptime-known value. In such case, we must delete all the instructions
2346 // added to the current block starting with the bitcast.
2347 // If the bitcast result ptr is an alloc, the alloc should be replaced with
2348 // a constant decl_ref.
2349 // Otherwise, the bitcast should be preserved and a store instruction should be
2350 // emitted to store the constant union value through the bitcast.
2351 },
2352 else => unreachable,
2353 }
23452354
23462355 // Otherwise, we set the new union tag now.
23472356 const new_tag = try sema.addConstant(
......@@ -4091,18 +4100,20 @@ fn analyzeCall(
40914100 zir_tags,
40924101 );
40934102 } else res: {
4103 try sema.requireRuntimeBlock(block, call_src);
4104
40944105 const args = try sema.arena.alloc(Air.Inst.Ref, uncasted_args.len);
40954106 for (uncasted_args) |uncasted_arg, i| {
4107 const arg_src = call_src; // TODO: better source location
40964108 if (i < fn_params_len) {
40974109 const param_ty = func_ty.fnParamType(i);
4098 const arg_src = call_src; // TODO: better source location
4110 try sema.resolveTypeLayout(block, arg_src, param_ty);
40994111 args[i] = try sema.coerce(block, param_ty, uncasted_arg, arg_src);
41004112 } else {
41014113 args[i] = uncasted_arg;
41024114 }
41034115 }
41044116
4105 try sema.requireRuntimeBlock(block, call_src);
41064117 try sema.resolveTypeLayout(block, call_src, func_ty_info.return_type);
41074118
41084119 try sema.air_extra.ensureUnusedCapacity(gpa, @typeInfo(Air.Call).Struct.fields.len +
......@@ -4173,6 +4184,7 @@ fn finishGenericCall(
41734184 const param_ty = new_fn_ty.fnParamType(runtime_i);
41744185 const arg_src = call_src; // TODO: better source location
41754186 const uncasted_arg = uncasted_args[total_i];
4187 try sema.resolveTypeLayout(block, arg_src, param_ty);
41764188 const casted_arg = try sema.coerce(block, param_ty, uncasted_arg, arg_src);
41774189 runtime_args[runtime_i] = casted_arg;
41784190 runtime_i += 1;
......@@ -5548,7 +5560,7 @@ fn zirSwitchCapture(
55485560 );
55495561 }
55505562 try sema.requireRuntimeBlock(block, operand_src);
5551 return block.addStructFieldPtr(operand_ptr, field_index, field.ty);
5563 return block.addStructFieldPtr(operand_ptr, field_index, field_ty_ptr);
55525564 }
55535565
55545566 const operand = if (operand_is_ref)
......@@ -5669,11 +5681,7 @@ fn zirSwitchBlock(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
56695681 const special_prong_src: LazySrcLoc = .{ .node_offset_switch_special_prong = src_node_offset };
56705682 const extra = sema.code.extraData(Zir.Inst.SwitchBlock, inst_data.payload_index);
56715683
5672 const operand_ptr = sema.resolveInst(extra.data.operand);
5673 const operand = if (extra.data.bits.is_ref)
5674 try sema.analyzeLoad(block, src, operand_ptr, operand_src)
5675 else
5676 operand_ptr;
5684 const operand = sema.resolveInst(extra.data.operand);
56775685
56785686 var header_extra_index: usize = extra.end;
56795687
......@@ -8675,14 +8683,6 @@ fn zirTypeof(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
86758683 return sema.addType(operand_ty);
86768684}
86778685
8678fn zirTypeofElem(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
8679 _ = block;
8680 const inst_data = sema.code.instructions.items(.data)[inst].un_node;
8681 const operand_ptr = sema.resolveInst(inst_data.operand);
8682 const elem_ty = sema.typeOf(operand_ptr).elemType();
8683 return sema.addType(elem_ty);
8684}
8685
86868686fn zirTypeofLog2IntType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
86878687 const inst_data = sema.code.instructions.items(.data)[inst].un_node;
86888688 const src = inst_data.src();
src/Zir.zig+11-6
......@@ -544,9 +544,6 @@ pub const Inst = struct {
544544 /// Returns the type of a value.
545545 /// Uses the `un_node` field.
546546 typeof,
547 /// Given a value which is a pointer, returns the element type.
548 /// Uses the `un_node` field.
549 typeof_elem,
550547 /// Given a value, look at the type of it, which must be an integer type.
551548 /// Returns the integer type for the RHS of a shift operation.
552549 /// Uses the `un_node` field.
......@@ -1045,7 +1042,6 @@ pub const Inst = struct {
10451042 .negate,
10461043 .negate_wrap,
10471044 .typeof,
1048 .typeof_elem,
10491045 .xor,
10501046 .optional_type,
10511047 .optional_payload_safe,
......@@ -1312,7 +1308,6 @@ pub const Inst = struct {
13121308 .negate = .un_node,
13131309 .negate_wrap = .un_node,
13141310 .typeof = .un_node,
1315 .typeof_elem = .un_node,
13161311 .typeof_log2_int_type = .un_node,
13171312 .log2_int_type = .un_node,
13181313 .@"unreachable" = .@"unreachable",
......@@ -2443,6 +2438,13 @@ pub const Inst = struct {
24432438 /// body member Index for every body_len
24442439 /// }
24452440 pub const SwitchBlock = struct {
2441 /// This is always a `switch_cond` or `switch_cond_ref` instruction.
2442 /// If it is a `switch_cond_ref` instruction, bits.is_ref is always true.
2443 /// If it is a `switch_cond` instruction, bits.is_ref is always false.
2444 /// Both `switch_cond` and `switch_cond_ref` return a value, not a pointer,
2445 /// that is useful for the case items, but cannot be used for capture values.
2446 /// For the capture values, Sema is expected to find the operand of this operand
2447 /// and use that.
24462448 operand: Ref,
24472449 bits: Bits,
24482450
......@@ -2454,8 +2456,11 @@ pub const Inst = struct {
24542456 /// If true, there is an underscore prong. This is mutually exclusive with `has_else`.
24552457 has_under: bool,
24562458 /// If true, the `operand` is a pointer to the value being switched on.
2459 /// TODO this flag is redundant with the tag of operand and can be removed.
24572460 is_ref: bool,
2458 scalar_cases_len: u28,
2461 scalar_cases_len: ScalarCasesLen,
2462
2463 pub const ScalarCasesLen = u28;
24592464
24602465 pub fn specialProng(bits: Bits) SpecialProng {
24612466 const has_else: u2 = @boolToInt(bits.has_else);
src/print_zir.zig-1
......@@ -184,7 +184,6 @@ const Writer = struct {
184184 .is_non_err,
185185 .is_non_err_ptr,
186186 .typeof,
187 .typeof_elem,
188187 .struct_init_empty,
189188 .type_info,
190189 .size_of,
src/type.zig+37-22
......@@ -3391,34 +3391,49 @@ pub const Type = extern union {
33913391 }
33923392 }
33933393
3394 /// Supports structs and unions.
33943395 pub fn structFieldOffset(ty: Type, index: usize, target: Target) u64 {
3395 const fields = ty.structFields();
3396 if (ty.castTag(.@"struct")) |payload| {
3397 const struct_obj = payload.data;
3398 assert(struct_obj.status == .have_layout);
3399 const is_packed = struct_obj.layout == .Packed;
3400 if (is_packed) @panic("TODO packed structs");
3401 }
3396 switch (ty.tag()) {
3397 .@"struct" => {
3398 const struct_obj = ty.castTag(.@"struct").?.data;
3399 assert(struct_obj.status == .have_layout);
3400 const is_packed = struct_obj.layout == .Packed;
3401 if (is_packed) @panic("TODO packed structs");
34023402
3403 var offset: u64 = 0;
3404 var big_align: u32 = 0;
3405 for (fields.values()) |field, i| {
3406 if (!field.ty.hasCodeGenBits()) continue;
3403 var offset: u64 = 0;
3404 var big_align: u32 = 0;
3405 for (struct_obj.fields.values()) |field, i| {
3406 if (!field.ty.hasCodeGenBits()) continue;
34073407
3408 const field_align = a: {
3409 if (field.abi_align.tag() == .abi_align_default) {
3410 break :a field.ty.abiAlignment(target);
3408 const field_align = a: {
3409 if (field.abi_align.tag() == .abi_align_default) {
3410 break :a field.ty.abiAlignment(target);
3411 } else {
3412 break :a @intCast(u32, field.abi_align.toUnsignedInt());
3413 }
3414 };
3415 big_align = @maximum(big_align, field_align);
3416 offset = std.mem.alignForwardGeneric(u64, offset, field_align);
3417 if (i == index) return offset;
3418 offset += field.ty.abiSize(target);
3419 }
3420 offset = std.mem.alignForwardGeneric(u64, offset, big_align);
3421 return offset;
3422 },
3423 .@"union" => return 0,
3424 .union_tagged => {
3425 const union_obj = ty.castTag(.union_tagged).?.data;
3426 const layout = union_obj.getLayout(target, true);
3427 if (layout.tag_align >= layout.payload_align) {
3428 // {Tag, Payload}
3429 return std.mem.alignForwardGeneric(u64, layout.tag_size, layout.payload_align);
34113430 } else {
3412 break :a @intCast(u32, field.abi_align.toUnsignedInt());
3431 // {Payload, Tag}
3432 return 0;
34133433 }
3414 };
3415 big_align = @maximum(big_align, field_align);
3416 offset = std.mem.alignForwardGeneric(u64, offset, field_align);
3417 if (i == index) return offset;
3418 offset += field.ty.abiSize(target);
3434 },
3435 else => unreachable,
34193436 }
3420 offset = std.mem.alignForwardGeneric(u64, offset, big_align);
3421 return offset;
34223437 }
34233438
34243439 pub fn declSrcLoc(ty: Type) Module.SrcLoc {
test/behavior/switch.zig+43
......@@ -219,3 +219,46 @@ test "switch on global mutable var isn't constant-folded" {
219219 poll();
220220 }
221221}
222
223const SwitchProngWithVarEnum = union(enum) {
224 One: i32,
225 Two: f32,
226 Meh: void,
227};
228
229test "switch prong with variable" {
230 try switchProngWithVarFn(SwitchProngWithVarEnum{ .One = 13 });
231 try switchProngWithVarFn(SwitchProngWithVarEnum{ .Two = 13.0 });
232 try switchProngWithVarFn(SwitchProngWithVarEnum{ .Meh = {} });
233}
234fn switchProngWithVarFn(a: SwitchProngWithVarEnum) !void {
235 switch (a) {
236 SwitchProngWithVarEnum.One => |x| {
237 try expect(x == 13);
238 },
239 SwitchProngWithVarEnum.Two => |x| {
240 try expect(x == 13.0);
241 },
242 SwitchProngWithVarEnum.Meh => |x| {
243 const v: void = x;
244 _ = v;
245 },
246 }
247}
248
249test "switch on enum using pointer capture" {
250 try testSwitchEnumPtrCapture();
251 comptime try testSwitchEnumPtrCapture();
252}
253
254fn testSwitchEnumPtrCapture() !void {
255 var value = SwitchProngWithVarEnum{ .One = 1234 };
256 switch (value) {
257 SwitchProngWithVarEnum.One => |*x| x.* += 1,
258 else => unreachable,
259 }
260 switch (value) {
261 SwitchProngWithVarEnum.One => |x| try expect(x == 1235),
262 else => unreachable,
263 }
264}
test/behavior/switch_stage1.zig-42
......@@ -3,48 +3,6 @@ const expect = std.testing.expect;
33const expectError = std.testing.expectError;
44const expectEqual = std.testing.expectEqual;
55
6test "switch prong with variable" {
7 try switchProngWithVarFn(SwitchProngWithVarEnum{ .One = 13 });
8 try switchProngWithVarFn(SwitchProngWithVarEnum{ .Two = 13.0 });
9 try switchProngWithVarFn(SwitchProngWithVarEnum{ .Meh = {} });
10}
11const SwitchProngWithVarEnum = union(enum) {
12 One: i32,
13 Two: f32,
14 Meh: void,
15};
16fn switchProngWithVarFn(a: SwitchProngWithVarEnum) !void {
17 switch (a) {
18 SwitchProngWithVarEnum.One => |x| {
19 try expect(x == 13);
20 },
21 SwitchProngWithVarEnum.Two => |x| {
22 try expect(x == 13.0);
23 },
24 SwitchProngWithVarEnum.Meh => |x| {
25 const v: void = x;
26 _ = v;
27 },
28 }
29}
30
31test "switch on enum using pointer capture" {
32 try testSwitchEnumPtrCapture();
33 comptime try testSwitchEnumPtrCapture();
34}
35
36fn testSwitchEnumPtrCapture() !void {
37 var value = SwitchProngWithVarEnum{ .One = 1234 };
38 switch (value) {
39 SwitchProngWithVarEnum.One => |*x| x.* += 1,
40 else => unreachable,
41 }
42 switch (value) {
43 SwitchProngWithVarEnum.One => |x| try expect(x == 1235),
44 else => unreachable,
45 }
46}
47
486test "switch handles all cases of number" {
497 try testSwitchHandleAllCases();
508 comptime try testSwitchHandleAllCases();