authorgravatar for mlugg@mlugg.co.ukMatthew Lugg <mlugg@mlugg.co.uk> 2023-06-20 13:39:35+01:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2023-06-24 16:47:49-07:00
logbe0c69957e7489423606023ad820599652a60e15
treeda3b52a40593e6d55f718a344fb660f8348a63ae
parent13853bef0df3c90633021850cc6d6abaeea03282

compiler: remove destination type from cast builtins

Resolves: #5909

7 files changed, 680 insertions(+), 356 deletions(-)

src/AstGen.zig+162-53
......@@ -335,6 +335,32 @@ const ResultInfo = struct {
335335 },
336336 }
337337 }
338
339 /// Find the result type for a cast builtin given the result location.
340 /// If the location does not have a known result type, emits an error on
341 /// the given node.
342 fn resultType(rl: Loc, gz: *GenZir, node: Ast.Node.Index, builtin_name: []const u8) !Zir.Inst.Ref {
343 const astgen = gz.astgen;
344 switch (rl) {
345 .discard, .none, .ref, .inferred_ptr => {},
346 .ty, .coerced_ty => |ty_ref| return ty_ref,
347 .ptr => |ptr| {
348 const ptr_ty = try gz.addUnNode(.typeof, ptr.inst, node);
349 return gz.addUnNode(.elem_type, ptr_ty, node);
350 },
351 .block_ptr => |block_scope| {
352 if (block_scope.rl_ty_inst != .none) return block_scope.rl_ty_inst;
353 if (block_scope.break_result_info.rl == .ptr) {
354 const ptr_ty = try gz.addUnNode(.typeof, block_scope.break_result_info.rl.ptr.inst, node);
355 return gz.addUnNode(.elem_type, ptr_ty, node);
356 }
357 },
358 }
359
360 return astgen.failNodeNotes(node, "{s} must have a known result type", .{builtin_name}, &.{
361 try astgen.errNoteNode(node, "use @as to provide explicit result type", .{}),
362 });
363 }
338364 };
339365
340366 const Context = enum {
......@@ -2521,6 +2547,7 @@ fn addEnsureResult(gz: *GenZir, maybe_unused_result: Zir.Inst.Ref, statement: As
25212547 .array_type,
25222548 .array_type_sentinel,
25232549 .elem_type_index,
2550 .elem_type,
25242551 .vector_type,
25252552 .indexable_ptr_len,
25262553 .anyframe_type,
......@@ -2662,7 +2689,6 @@ fn addEnsureResult(gz: *GenZir, maybe_unused_result: Zir.Inst.Ref, statement: As
26622689 .int_cast,
26632690 .ptr_cast,
26642691 .truncate,
2665 .align_cast,
26662692 .has_decl,
26672693 .has_field,
26682694 .clz,
......@@ -7924,11 +7950,10 @@ fn bitCast(
79247950 scope: *Scope,
79257951 ri: ResultInfo,
79267952 node: Ast.Node.Index,
7927 lhs: Ast.Node.Index,
7928 rhs: Ast.Node.Index,
7953 operand_node: Ast.Node.Index,
79297954) InnerError!Zir.Inst.Ref {
7930 const dest_type = try reachableTypeExpr(gz, scope, lhs, node);
7931 const operand = try reachableExpr(gz, scope, .{ .rl = .none }, rhs, node);
7955 const dest_type = try ri.rl.resultType(gz, node, "@bitCast");
7956 const operand = try reachableExpr(gz, scope, .{ .rl = .none }, operand_node, node);
79327957 const result = try gz.addPlNode(.bitcast, node, Zir.Inst.Bin{
79337958 .lhs = dest_type,
79347959 .rhs = operand,
......@@ -7936,6 +7961,116 @@ fn bitCast(
79367961 return rvalue(gz, ri, result, node);
79377962}
79387963
7964/// Handle one or more nested pointer cast builtins:
7965/// * @ptrCast
7966/// * @alignCast
7967/// * @addrSpaceCast
7968/// * @constCast
7969/// * @volatileCast
7970/// Any sequence of such builtins is treated as a single operation. This allowed
7971/// for sequences like `@ptrCast(@alignCast(ptr))` to work correctly despite the
7972/// intermediate result type being unknown.
7973fn ptrCast(
7974 gz: *GenZir,
7975 scope: *Scope,
7976 ri: ResultInfo,
7977 root_node: Ast.Node.Index,
7978) InnerError!Zir.Inst.Ref {
7979 const astgen = gz.astgen;
7980 const tree = astgen.tree;
7981 const main_tokens = tree.nodes.items(.main_token);
7982 const node_datas = tree.nodes.items(.data);
7983 const node_tags = tree.nodes.items(.tag);
7984
7985 var flags: Zir.Inst.FullPtrCastFlags = .{};
7986
7987 // Note that all pointer cast builtins have one parameter, so we only need
7988 // to handle `builtin_call_two`.
7989 var node = root_node;
7990 while (true) {
7991 switch (node_tags[node]) {
7992 .builtin_call_two, .builtin_call_two_comma => {},
7993 .grouped_expression => {
7994 // Handle the chaining even with redundant parentheses
7995 node = node_datas[node].lhs;
7996 continue;
7997 },
7998 else => break,
7999 }
8000
8001 if (node_datas[node].lhs == 0) break; // 0 args
8002 if (node_datas[node].rhs != 0) break; // 2 args
8003
8004 const builtin_token = main_tokens[node];
8005 const builtin_name = tree.tokenSlice(builtin_token);
8006 const info = BuiltinFn.list.get(builtin_name) orelse break;
8007 if (info.param_count != 1) break;
8008
8009 switch (info.tag) {
8010 else => break,
8011 inline .ptr_cast,
8012 .align_cast,
8013 .addrspace_cast,
8014 .const_cast,
8015 .volatile_cast,
8016 => |tag| {
8017 if (@field(flags, @tagName(tag))) {
8018 return astgen.failNode(node, "redundant {s}", .{builtin_name});
8019 }
8020 @field(flags, @tagName(tag)) = true;
8021 },
8022 }
8023
8024 node = node_datas[node].lhs;
8025 }
8026
8027 const flags_i = @bitCast(u5, flags);
8028 assert(flags_i != 0);
8029
8030 const ptr_only: Zir.Inst.FullPtrCastFlags = .{ .ptr_cast = true };
8031 if (flags_i == @bitCast(u5, ptr_only)) {
8032 // Special case: simpler representation
8033 return typeCast(gz, scope, ri, root_node, node, .ptr_cast, "@ptrCast");
8034 }
8035
8036 const no_result_ty_flags: Zir.Inst.FullPtrCastFlags = .{
8037 .const_cast = true,
8038 .volatile_cast = true,
8039 };
8040 if ((flags_i & ~@bitCast(u5, no_result_ty_flags)) == 0) {
8041 // Result type not needed
8042 const cursor = maybeAdvanceSourceCursorToMainToken(gz, root_node);
8043 const operand = try expr(gz, scope, .{ .rl = .none }, node);
8044 try emitDbgStmt(gz, cursor);
8045 const result = try gz.addExtendedPayloadSmall(.ptr_cast_no_dest, flags_i, Zir.Inst.UnNode{
8046 .node = gz.nodeIndexToRelative(root_node),
8047 .operand = operand,
8048 });
8049 return rvalue(gz, ri, result, root_node);
8050 }
8051
8052 // Full cast including result type
8053 const need_result_type_builtin = if (flags.ptr_cast)
8054 "@ptrCast"
8055 else if (flags.align_cast)
8056 "@alignCast"
8057 else if (flags.addrspace_cast)
8058 "@addrSpaceCast"
8059 else
8060 unreachable;
8061
8062 const cursor = maybeAdvanceSourceCursorToMainToken(gz, root_node);
8063 const result_type = try ri.rl.resultType(gz, root_node, need_result_type_builtin);
8064 const operand = try expr(gz, scope, .{ .rl = .none }, node);
8065 try emitDbgStmt(gz, cursor);
8066 const result = try gz.addExtendedPayloadSmall(.ptr_cast_full, flags_i, Zir.Inst.BinNode{
8067 .node = gz.nodeIndexToRelative(root_node),
8068 .lhs = result_type,
8069 .rhs = operand,
8070 });
8071 return rvalue(gz, ri, result, root_node);
8072}
8073
79398074fn typeOf(
79408075 gz: *GenZir,
79418076 scope: *Scope,
......@@ -8123,7 +8258,7 @@ fn builtinCall(
81238258
81248259 // zig fmt: off
81258260 .as => return as( gz, scope, ri, node, params[0], params[1]),
8126 .bit_cast => return bitCast( gz, scope, ri, node, params[0], params[1]),
8261 .bit_cast => return bitCast( gz, scope, ri, node, params[0]),
81278262 .TypeOf => return typeOf( gz, scope, ri, node, params),
81288263 .union_init => return unionInit(gz, scope, ri, node, params),
81298264 .c_import => return cImport( gz, scope, node, params[0]),
......@@ -8308,14 +8443,13 @@ fn builtinCall(
83088443 .Frame => return simpleUnOp(gz, scope, ri, node, .{ .rl = .none }, params[0], .frame_type),
83098444 .frame_size => return simpleUnOp(gz, scope, ri, node, .{ .rl = .none }, params[0], .frame_size),
83108445
8311 .int_from_float => return typeCast(gz, scope, ri, node, params[0], params[1], .int_from_float),
8312 .float_from_int => return typeCast(gz, scope, ri, node, params[0], params[1], .float_from_int),
8313 .ptr_from_int => return typeCast(gz, scope, ri, node, params[0], params[1], .ptr_from_int),
8314 .enum_from_int => return typeCast(gz, scope, ri, node, params[0], params[1], .enum_from_int),
8315 .float_cast => return typeCast(gz, scope, ri, node, params[0], params[1], .float_cast),
8316 .int_cast => return typeCast(gz, scope, ri, node, params[0], params[1], .int_cast),
8317 .ptr_cast => return typeCast(gz, scope, ri, node, params[0], params[1], .ptr_cast),
8318 .truncate => return typeCast(gz, scope, ri, node, params[0], params[1], .truncate),
8446 .int_from_float => return typeCast(gz, scope, ri, node, params[0], .int_from_float, builtin_name),
8447 .float_from_int => return typeCast(gz, scope, ri, node, params[0], .float_from_int, builtin_name),
8448 .ptr_from_int => return typeCast(gz, scope, ri, node, params[0], .ptr_from_int, builtin_name),
8449 .enum_from_int => return typeCast(gz, scope, ri, node, params[0], .enum_from_int, builtin_name),
8450 .float_cast => return typeCast(gz, scope, ri, node, params[0], .float_cast, builtin_name),
8451 .int_cast => return typeCast(gz, scope, ri, node, params[0], .int_cast, builtin_name),
8452 .truncate => return typeCast(gz, scope, ri, node, params[0], .truncate, builtin_name),
83198453 // zig fmt: on
83208454
83218455 .Type => {
......@@ -8368,49 +8502,22 @@ fn builtinCall(
83688502 });
83698503 return rvalue(gz, ri, result, node);
83708504 },
8371 .align_cast => {
8372 const dest_align = try comptimeExpr(gz, scope, align_ri, params[0]);
8373 const rhs = try expr(gz, scope, .{ .rl = .none }, params[1]);
8374 const result = try gz.addPlNode(.align_cast, node, Zir.Inst.Bin{
8375 .lhs = dest_align,
8376 .rhs = rhs,
8377 });
8378 return rvalue(gz, ri, result, node);
8379 },
83808505 .err_set_cast => {
83818506 try emitDbgNode(gz, node);
83828507
83838508 const result = try gz.addExtendedPayload(.err_set_cast, Zir.Inst.BinNode{
8384 .lhs = try typeExpr(gz, scope, params[0]),
8385 .rhs = try expr(gz, scope, .{ .rl = .none }, params[1]),
8509 .lhs = try ri.rl.resultType(gz, node, "@errSetCast"),
8510 .rhs = try expr(gz, scope, .{ .rl = .none }, params[0]),
83868511 .node = gz.nodeIndexToRelative(node),
83878512 });
83888513 return rvalue(gz, ri, result, node);
83898514 },
8390 .addrspace_cast => {
8391 const result = try gz.addExtendedPayload(.addrspace_cast, Zir.Inst.BinNode{
8392 .lhs = try comptimeExpr(gz, scope, .{ .rl = .{ .ty = .address_space_type } }, params[0]),
8393 .rhs = try expr(gz, scope, .{ .rl = .none }, params[1]),
8394 .node = gz.nodeIndexToRelative(node),
8395 });
8396 return rvalue(gz, ri, result, node);
8397 },
8398 .const_cast => {
8399 const operand = try expr(gz, scope, .{ .rl = .none }, params[0]);
8400 const result = try gz.addExtendedPayload(.const_cast, Zir.Inst.UnNode{
8401 .node = gz.nodeIndexToRelative(node),
8402 .operand = operand,
8403 });
8404 return rvalue(gz, ri, result, node);
8405 },
8406 .volatile_cast => {
8407 const operand = try expr(gz, scope, .{ .rl = .none }, params[0]);
8408 const result = try gz.addExtendedPayload(.volatile_cast, Zir.Inst.UnNode{
8409 .node = gz.nodeIndexToRelative(node),
8410 .operand = operand,
8411 });
8412 return rvalue(gz, ri, result, node);
8413 },
8515 .ptr_cast,
8516 .align_cast,
8517 .addrspace_cast,
8518 .const_cast,
8519 .volatile_cast,
8520 => return ptrCast(gz, scope, ri, node),
84148521
84158522 // zig fmt: off
84168523 .has_decl => return hasDeclOrField(gz, scope, ri, node, params[0], params[1], .has_decl),
......@@ -8725,13 +8832,13 @@ fn typeCast(
87258832 scope: *Scope,
87268833 ri: ResultInfo,
87278834 node: Ast.Node.Index,
8728 lhs_node: Ast.Node.Index,
8729 rhs_node: Ast.Node.Index,
8835 operand_node: Ast.Node.Index,
87308836 tag: Zir.Inst.Tag,
8837 builtin_name: []const u8,
87318838) InnerError!Zir.Inst.Ref {
87328839 const cursor = maybeAdvanceSourceCursorToMainToken(gz, node);
8733 const result_type = try typeExpr(gz, scope, lhs_node);
8734 const operand = try expr(gz, scope, .{ .rl = .none }, rhs_node);
8840 const result_type = try ri.rl.resultType(gz, node, builtin_name);
8841 const operand = try expr(gz, scope, .{ .rl = .none }, operand_node);
87358842
87368843 try emitDbgStmt(gz, cursor);
87378844 const result = try gz.addPlNode(tag, node, Zir.Inst.Bin{
......@@ -9432,6 +9539,7 @@ fn nodeMayNeedMemoryLocation(tree: *const Ast, start_node: Ast.Node.Index, have_
94329539 switch (builtin_info.needs_mem_loc) {
94339540 .never => return false,
94349541 .always => return true,
9542 .forward0 => node = node_datas[node].lhs,
94359543 .forward1 => node = node_datas[node].rhs,
94369544 }
94379545 // Missing builtin arg is not a parsing error, expect an error later.
......@@ -9448,6 +9556,7 @@ fn nodeMayNeedMemoryLocation(tree: *const Ast, start_node: Ast.Node.Index, have_
94489556 switch (builtin_info.needs_mem_loc) {
94499557 .never => return false,
94509558 .always => return true,
9559 .forward0 => node = params[0],
94519560 .forward1 => node = params[1],
94529561 }
94539562 // Missing builtin arg is not a parsing error, expect an error later.
src/Autodoc.zig-3
......@@ -1529,7 +1529,6 @@ fn walkInstruction(
15291529 .int_cast,
15301530 .ptr_cast,
15311531 .truncate,
1532 .align_cast,
15331532 .has_decl,
15341533 .has_field,
15351534 .div_exact,
......@@ -3024,8 +3023,6 @@ fn walkInstruction(
30243023 .int_from_error,
30253024 .error_from_int,
30263025 .reify,
3027 .const_cast,
3028 .volatile_cast,
30293026 => {
30303027 const extra = file.zir.extraData(Zir.Inst.UnNode, extended.operand).data;
30313028 const bin_index = self.exprs.items.len;
src/BuiltinFn.zig+15-13
......@@ -129,6 +129,8 @@ pub const MemLocRequirement = enum {
129129 never,
130130 /// The builtin always needs a memory location.
131131 always,
132 /// The builtin forwards the question to argument at index 0.
133 forward0,
132134 /// The builtin forwards the question to argument at index 1.
133135 forward1,
134136};
......@@ -168,14 +170,14 @@ pub const list = list: {
168170 "@addrSpaceCast",
169171 .{
170172 .tag = .addrspace_cast,
171 .param_count = 2,
173 .param_count = 1,
172174 },
173175 },
174176 .{
175177 "@alignCast",
176178 .{
177179 .tag = .align_cast,
178 .param_count = 2,
180 .param_count = 1,
179181 },
180182 },
181183 .{
......@@ -226,8 +228,8 @@ pub const list = list: {
226228 "@bitCast",
227229 .{
228230 .tag = .bit_cast,
229 .needs_mem_loc = .forward1,
230 .param_count = 2,
231 .needs_mem_loc = .forward0,
232 .param_count = 1,
231233 },
232234 },
233235 .{
......@@ -457,7 +459,7 @@ pub const list = list: {
457459 .{
458460 .tag = .err_set_cast,
459461 .eval_to_error = .always,
460 .param_count = 2,
462 .param_count = 1,
461463 },
462464 },
463465 .{
......@@ -502,14 +504,14 @@ pub const list = list: {
502504 "@floatCast",
503505 .{
504506 .tag = .float_cast,
505 .param_count = 2,
507 .param_count = 1,
506508 },
507509 },
508510 .{
509511 "@intFromFloat",
510512 .{
511513 .tag = .int_from_float,
512 .param_count = 2,
514 .param_count = 1,
513515 },
514516 },
515517 .{
......@@ -572,14 +574,14 @@ pub const list = list: {
572574 "@intCast",
573575 .{
574576 .tag = .int_cast,
575 .param_count = 2,
577 .param_count = 1,
576578 },
577579 },
578580 .{
579581 "@enumFromInt",
580582 .{
581583 .tag = .enum_from_int,
582 .param_count = 2,
584 .param_count = 1,
583585 },
584586 },
585587 .{
......@@ -594,14 +596,14 @@ pub const list = list: {
594596 "@floatFromInt",
595597 .{
596598 .tag = .float_from_int,
597 .param_count = 2,
599 .param_count = 1,
598600 },
599601 },
600602 .{
601603 "@ptrFromInt",
602604 .{
603605 .tag = .ptr_from_int,
604 .param_count = 2,
606 .param_count = 1,
605607 },
606608 },
607609 .{
......@@ -685,7 +687,7 @@ pub const list = list: {
685687 "@ptrCast",
686688 .{
687689 .tag = .ptr_cast,
688 .param_count = 2,
690 .param_count = 1,
689691 },
690692 },
691693 .{
......@@ -938,7 +940,7 @@ pub const list = list: {
938940 "@truncate",
939941 .{
940942 .tag = .truncate,
941 .param_count = 2,
943 .param_count = 1,
942944 },
943945 },
944946 .{
src/Sema.zig+443-264
......@@ -960,6 +960,7 @@ fn analyzeBodyInner(
960960 .elem_val => try sema.zirElemVal(block, inst),
961961 .elem_val_node => try sema.zirElemValNode(block, inst),
962962 .elem_type_index => try sema.zirElemTypeIndex(block, inst),
963 .elem_type => try sema.zirElemType(block, inst),
963964 .enum_literal => try sema.zirEnumLiteral(block, inst),
964965 .int_from_enum => try sema.zirIntFromEnum(block, inst),
965966 .enum_from_int => try sema.zirEnumFromInt(block, inst),
......@@ -1044,7 +1045,6 @@ fn analyzeBodyInner(
10441045 .int_cast => try sema.zirIntCast(block, inst),
10451046 .ptr_cast => try sema.zirPtrCast(block, inst),
10461047 .truncate => try sema.zirTruncate(block, inst),
1047 .align_cast => try sema.zirAlignCast(block, inst),
10481048 .has_decl => try sema.zirHasDecl(block, inst),
10491049 .has_field => try sema.zirHasField(block, inst),
10501050 .byte_swap => try sema.zirByteSwap(block, inst),
......@@ -1172,13 +1172,12 @@ fn analyzeBodyInner(
11721172 .reify => try sema.zirReify( block, extended, inst),
11731173 .builtin_async_call => try sema.zirBuiltinAsyncCall( block, extended),
11741174 .cmpxchg => try sema.zirCmpxchg( block, extended),
1175 .addrspace_cast => try sema.zirAddrSpaceCast( block, extended),
11761175 .c_va_arg => try sema.zirCVaArg( block, extended),
11771176 .c_va_copy => try sema.zirCVaCopy( block, extended),
11781177 .c_va_end => try sema.zirCVaEnd( block, extended),
11791178 .c_va_start => try sema.zirCVaStart( block, extended),
1180 .const_cast, => try sema.zirConstCast( block, extended),
1181 .volatile_cast, => try sema.zirVolatileCast( block, extended),
1179 .ptr_cast_full => try sema.zirPtrCastFull( block, extended),
1180 .ptr_cast_no_dest => try sema.zirPtrCastNoDest( block, extended),
11821181 .work_item_id => try sema.zirWorkItem( block, extended, extended.opcode),
11831182 .work_group_size => try sema.zirWorkItem( block, extended, extended.opcode),
11841183 .work_group_id => try sema.zirWorkItem( block, extended, extended.opcode),
......@@ -1821,6 +1820,24 @@ pub fn resolveType(sema: *Sema, block: *Block, src: LazySrcLoc, zir_ref: Zir.Ins
18211820 return ty;
18221821}
18231822
1823fn resolveCastDestType(sema: *Sema, block: *Block, src: LazySrcLoc, zir_ref: Zir.Inst.Ref, builtin_name: []const u8) !Type {
1824 return sema.resolveType(block, src, zir_ref) catch |err| switch (err) {
1825 error.GenericPoison => {
1826 // Cast builtins use their result type as the destination type, but
1827 // it could be an anytype argument, which we can't catch in AstGen.
1828 const msg = msg: {
1829 const msg = try sema.errMsg(block, src, "{s} must have a known result type", .{builtin_name});
1830 errdefer msg.destroy(sema.gpa);
1831 try sema.errNote(block, src, msg, "result type is unknown due to anytype parameter", .{});
1832 try sema.errNote(block, src, msg, "use @as to provide explicit result type", .{});
1833 break :msg msg;
1834 };
1835 return sema.failWithOwnedErrorMsg(msg);
1836 },
1837 else => |e| return e,
1838 };
1839}
1840
18241841fn analyzeAsType(
18251842 sema: *Sema,
18261843 block: *Block,
......@@ -7953,6 +7970,14 @@ fn zirElemTypeIndex(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErr
79537970 }
79547971}
79557972
7973fn zirElemType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
7974 const mod = sema.mod;
7975 const un_node = sema.code.instructions.items(.data)[inst].un_node;
7976 const ptr_ty = try sema.resolveType(block, .unneeded, un_node.operand);
7977 assert(ptr_ty.zigTypeTag(mod) == .Pointer); // validated by a previous instruction
7978 return sema.addType(ptr_ty.childType(mod));
7979}
7980
79567981fn zirVectorType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
79577982 const mod = sema.mod;
79587983 const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
......@@ -8278,13 +8303,12 @@ fn zirEnumFromInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
82788303 const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
82798304 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
82808305 const src = inst_data.src();
8281 const dest_ty_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
8282 const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
8283 const dest_ty = try sema.resolveType(block, dest_ty_src, extra.lhs);
8306 const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
8307 const dest_ty = try sema.resolveCastDestType(block, src, extra.lhs, "@enumFromInt");
82848308 const operand = try sema.resolveInst(extra.rhs);
82858309
82868310 if (dest_ty.zigTypeTag(mod) != .Enum) {
8287 return sema.fail(block, dest_ty_src, "expected enum, found '{}'", .{dest_ty.fmt(mod)});
8311 return sema.fail(block, src, "expected enum, found '{}'", .{dest_ty.fmt(mod)});
82888312 }
82898313 _ = try sema.checkIntType(block, operand_src, sema.typeOf(operand));
82908314
......@@ -9572,14 +9596,14 @@ fn zirIntCast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
95729596 defer tracy.end();
95739597
95749598 const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
9575 const dest_ty_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
9576 const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
9599 const src = inst_data.src();
9600 const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
95779601 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
95789602
9579 const dest_ty = try sema.resolveType(block, dest_ty_src, extra.lhs);
9603 const dest_ty = try sema.resolveCastDestType(block, src, extra.lhs, "@intCast");
95809604 const operand = try sema.resolveInst(extra.rhs);
95819605
9582 return sema.intCast(block, inst_data.src(), dest_ty, dest_ty_src, operand, operand_src, true);
9606 return sema.intCast(block, inst_data.src(), dest_ty, src, operand, operand_src, true);
95839607}
95849608
95859609fn intCast(
......@@ -9733,11 +9757,11 @@ fn zirBitcast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
97339757
97349758 const mod = sema.mod;
97359759 const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
9736 const dest_ty_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
9737 const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
9760 const src = inst_data.src();
9761 const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
97389762 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
97399763
9740 const dest_ty = try sema.resolveType(block, dest_ty_src, extra.lhs);
9764 const dest_ty = try sema.resolveCastDestType(block, src, extra.lhs, "@bitCast");
97419765 const operand = try sema.resolveInst(extra.rhs);
97429766 const operand_ty = sema.typeOf(operand);
97439767 switch (dest_ty.zigTypeTag(mod)) {
......@@ -9756,14 +9780,14 @@ fn zirBitcast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
97569780 .Type,
97579781 .Undefined,
97589782 .Void,
9759 => return sema.fail(block, dest_ty_src, "cannot @bitCast to '{}'", .{dest_ty.fmt(mod)}),
9783 => return sema.fail(block, src, "cannot @bitCast to '{}'", .{dest_ty.fmt(mod)}),
97609784
97619785 .Enum => {
97629786 const msg = msg: {
9763 const msg = try sema.errMsg(block, dest_ty_src, "cannot @bitCast to '{}'", .{dest_ty.fmt(mod)});
9787 const msg = try sema.errMsg(block, src, "cannot @bitCast to '{}'", .{dest_ty.fmt(mod)});
97649788 errdefer msg.destroy(sema.gpa);
97659789 switch (operand_ty.zigTypeTag(mod)) {
9766 .Int, .ComptimeInt => try sema.errNote(block, dest_ty_src, msg, "use @enumFromInt to cast from '{}'", .{operand_ty.fmt(mod)}),
9790 .Int, .ComptimeInt => try sema.errNote(block, src, msg, "use @enumFromInt to cast from '{}'", .{operand_ty.fmt(mod)}),
97679791 else => {},
97689792 }
97699793
......@@ -9774,11 +9798,11 @@ fn zirBitcast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
97749798
97759799 .Pointer => {
97769800 const msg = msg: {
9777 const msg = try sema.errMsg(block, dest_ty_src, "cannot @bitCast to '{}'", .{dest_ty.fmt(mod)});
9801 const msg = try sema.errMsg(block, src, "cannot @bitCast to '{}'", .{dest_ty.fmt(mod)});
97789802 errdefer msg.destroy(sema.gpa);
97799803 switch (operand_ty.zigTypeTag(mod)) {
9780 .Int, .ComptimeInt => try sema.errNote(block, dest_ty_src, msg, "use @ptrFromInt to cast from '{}'", .{operand_ty.fmt(mod)}),
9781 .Pointer => try sema.errNote(block, dest_ty_src, msg, "use @ptrCast to cast from '{}'", .{operand_ty.fmt(mod)}),
9804 .Int, .ComptimeInt => try sema.errNote(block, src, msg, "use @ptrFromInt to cast from '{}'", .{operand_ty.fmt(mod)}),
9805 .Pointer => try sema.errNote(block, src, msg, "use @ptrCast to cast from '{}'", .{operand_ty.fmt(mod)}),
97829806 else => {},
97839807 }
97849808
......@@ -9792,7 +9816,7 @@ fn zirBitcast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
97929816 .Union => "union",
97939817 else => unreachable,
97949818 };
9795 return sema.fail(block, dest_ty_src, "cannot @bitCast to '{}'; {s} does not have a guaranteed in-memory layout", .{
9819 return sema.fail(block, src, "cannot @bitCast to '{}'; {s} does not have a guaranteed in-memory layout", .{
97969820 dest_ty.fmt(mod), container,
97979821 });
97989822 },
......@@ -9876,11 +9900,11 @@ fn zirFloatCast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
98769900
98779901 const mod = sema.mod;
98789902 const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
9879 const dest_ty_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
9880 const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
9903 const src = inst_data.src();
9904 const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
98819905 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
98829906
9883 const dest_ty = try sema.resolveType(block, dest_ty_src, extra.lhs);
9907 const dest_ty = try sema.resolveCastDestType(block, src, extra.lhs, "@floatCast");
98849908 const operand = try sema.resolveInst(extra.rhs);
98859909
98869910 const target = mod.getTarget();
......@@ -9889,7 +9913,7 @@ fn zirFloatCast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
98899913 .Float => false,
98909914 else => return sema.fail(
98919915 block,
9892 dest_ty_src,
9916 src,
98939917 "expected float type, found '{}'",
98949918 .{dest_ty.fmt(mod)},
98959919 ),
......@@ -20552,50 +20576,6 @@ fn reifyStruct(
2055220576 return decl_val;
2055320577}
2055420578
20555fn zirAddrSpaceCast(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!Air.Inst.Ref {
20556 const mod = sema.mod;
20557 const extra = sema.code.extraData(Zir.Inst.BinNode, extended.operand).data;
20558 const src = LazySrcLoc.nodeOffset(extra.node);
20559 const addrspace_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = extra.node };
20560 const ptr_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = extra.node };
20561
20562 const dest_addrspace = try sema.analyzeAddressSpace(block, addrspace_src, extra.lhs, .pointer);
20563 const ptr = try sema.resolveInst(extra.rhs);
20564 const ptr_ty = sema.typeOf(ptr);
20565
20566 try sema.checkPtrOperand(block, ptr_src, ptr_ty);
20567
20568 var ptr_info = ptr_ty.ptrInfo(mod);
20569 const src_addrspace = ptr_info.flags.address_space;
20570 if (!target_util.addrSpaceCastIsValid(sema.mod.getTarget(), src_addrspace, dest_addrspace)) {
20571 const msg = msg: {
20572 const msg = try sema.errMsg(block, src, "invalid address space cast", .{});
20573 errdefer msg.destroy(sema.gpa);
20574 try sema.errNote(block, src, msg, "address space '{s}' is not compatible with address space '{s}'", .{ @tagName(src_addrspace), @tagName(dest_addrspace) });
20575 break :msg msg;
20576 };
20577 return sema.failWithOwnedErrorMsg(msg);
20578 }
20579
20580 ptr_info.flags.address_space = dest_addrspace;
20581 const dest_ptr_ty = try mod.ptrType(ptr_info);
20582 const dest_ty = if (ptr_ty.zigTypeTag(mod) == .Optional)
20583 try mod.optionalType(dest_ptr_ty.toIntern())
20584 else
20585 dest_ptr_ty;
20586
20587 try sema.requireRuntimeBlock(block, src, ptr_src);
20588 // TODO: Address space cast safety?
20589
20590 return block.addInst(.{
20591 .tag = .addrspace_cast,
20592 .data = .{ .ty_op = .{
20593 .ty = try sema.addType(dest_ty),
20594 .operand = ptr,
20595 } },
20596 });
20597}
20598
2059920579fn resolveVaListRef(sema: *Sema, block: *Block, src: LazySrcLoc, zir_ref: Zir.Inst.Ref) CompileError!Air.Inst.Ref {
2060020580 const va_list_ty = try sema.getBuiltinType("VaList");
2060120581 const va_list_ptr = try sema.mod.singleMutPtrType(va_list_ty);
......@@ -20711,14 +20691,14 @@ fn zirFrameSize(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
2071120691fn zirIntFromFloat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
2071220692 const mod = sema.mod;
2071320693 const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
20694 const src = inst_data.src();
2071420695 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
20715 const ty_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
20716 const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
20717 const dest_ty = try sema.resolveType(block, ty_src, extra.lhs);
20696 const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
20697 const dest_ty = try sema.resolveCastDestType(block, src, extra.lhs, "@intFromFloat");
2071820698 const operand = try sema.resolveInst(extra.rhs);
2071920699 const operand_ty = sema.typeOf(operand);
2072020700
20721 _ = try sema.checkIntType(block, ty_src, dest_ty);
20701 _ = try sema.checkIntType(block, src, dest_ty);
2072220702 try sema.checkFloatType(block, operand_src, operand_ty);
2072320703
2072420704 if (try sema.resolveMaybeUndefVal(operand)) |val| {
......@@ -20751,14 +20731,14 @@ fn zirIntFromFloat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErro
2075120731fn zirFloatFromInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
2075220732 const mod = sema.mod;
2075320733 const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
20734 const src = inst_data.src();
2075420735 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
20755 const ty_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
20756 const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
20757 const dest_ty = try sema.resolveType(block, ty_src, extra.lhs);
20736 const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
20737 const dest_ty = try sema.resolveCastDestType(block, src, extra.lhs, "@floatFromInt");
2075820738 const operand = try sema.resolveInst(extra.rhs);
2075920739 const operand_ty = sema.typeOf(operand);
2076020740
20761 try sema.checkFloatType(block, ty_src, dest_ty);
20741 try sema.checkFloatType(block, src, dest_ty);
2076220742 _ = try sema.checkIntType(block, operand_src, operand_ty);
2076320743
2076420744 if (try sema.resolveMaybeUndefVal(operand)) |val| {
......@@ -20779,21 +20759,20 @@ fn zirPtrFromInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
2077920759
2078020760 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
2078120761
20782 const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
20762 const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
2078320763 const operand_res = try sema.resolveInst(extra.rhs);
2078420764 const operand_coerced = try sema.coerce(block, Type.usize, operand_res, operand_src);
2078520765
20786 const type_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
20787 const ptr_ty = try sema.resolveType(block, src, extra.lhs);
20788 try sema.checkPtrType(block, type_src, ptr_ty);
20766 const ptr_ty = try sema.resolveCastDestType(block, src, extra.lhs, "@ptrFromInt");
20767 try sema.checkPtrType(block, src, ptr_ty);
2078920768 const elem_ty = ptr_ty.elemType2(mod);
2079020769 const ptr_align = try ptr_ty.ptrAlignmentAdvanced(mod, sema);
2079120770
2079220771 if (ptr_ty.isSlice(mod)) {
2079320772 const msg = msg: {
20794 const msg = try sema.errMsg(block, type_src, "integer cannot be converted to slice type '{}'", .{ptr_ty.fmt(sema.mod)});
20773 const msg = try sema.errMsg(block, src, "integer cannot be converted to slice type '{}'", .{ptr_ty.fmt(sema.mod)});
2079520774 errdefer msg.destroy(sema.gpa);
20796 try sema.errNote(block, type_src, msg, "slice length cannot be inferred from address", .{});
20775 try sema.errNote(block, src, msg, "slice length cannot be inferred from address", .{});
2079720776 break :msg msg;
2079820777 };
2079920778 return sema.failWithOwnedErrorMsg(msg);
......@@ -20841,12 +20820,11 @@ fn zirErrSetCast(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstDat
2084120820 const ip = &mod.intern_pool;
2084220821 const extra = sema.code.extraData(Zir.Inst.BinNode, extended.operand).data;
2084320822 const src = LazySrcLoc.nodeOffset(extra.node);
20844 const dest_ty_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = extra.node };
20845 const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = extra.node };
20846 const dest_ty = try sema.resolveType(block, dest_ty_src, extra.lhs);
20823 const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = extra.node };
20824 const dest_ty = try sema.resolveCastDestType(block, src, extra.lhs, "@errSetCast");
2084720825 const operand = try sema.resolveInst(extra.rhs);
2084820826 const operand_ty = sema.typeOf(operand);
20849 try sema.checkErrorSetType(block, dest_ty_src, dest_ty);
20827 try sema.checkErrorSetType(block, src, dest_ty);
2085020828 try sema.checkErrorSetType(block, operand_src, operand_ty);
2085120829
2085220830 // operand must be defined since it can be an invalid error value
......@@ -20869,7 +20847,7 @@ fn zirErrSetCast(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstDat
2086920847 break :disjoint true;
2087020848 }
2087120849
20872 try sema.resolveInferredErrorSetTy(block, dest_ty_src, dest_ty);
20850 try sema.resolveInferredErrorSetTy(block, src, dest_ty);
2087320851 try sema.resolveInferredErrorSetTy(block, operand_src, operand_ty);
2087420852 for (dest_ty.errorSetNames(mod)) |dest_err_name| {
2087520853 if (Type.errorSetHasFieldIp(ip, operand_ty.toIntern(), dest_err_name))
......@@ -20924,159 +20902,415 @@ fn zirErrSetCast(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstDat
2092420902 return block.addBitCast(dest_ty, operand);
2092520903}
2092620904
20905fn zirPtrCastFull(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!Air.Inst.Ref {
20906 const flags = @bitCast(Zir.Inst.FullPtrCastFlags, @truncate(u5, extended.small));
20907 const extra = sema.code.extraData(Zir.Inst.BinNode, extended.operand).data;
20908 const src = LazySrcLoc.nodeOffset(extra.node);
20909 const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = extra.node };
20910 const operand = try sema.resolveInst(extra.rhs);
20911 const dest_ty = try sema.resolveCastDestType(block, src, extra.lhs, "@ptrCast"); // TODO: better error message (builtin name)
20912 return sema.ptrCastFull(
20913 block,
20914 flags,
20915 src,
20916 operand,
20917 operand_src,
20918 dest_ty,
20919 );
20920}
20921
2092720922fn zirPtrCast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
20928 const mod = sema.mod;
2092920923 const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
2093020924 const src = inst_data.src();
20931 const dest_ty_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
20932 const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
20925 const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
2093320926 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
20934 const dest_ty = try sema.resolveType(block, dest_ty_src, extra.lhs);
20927 const dest_ty = try sema.resolveCastDestType(block, src, extra.lhs, "@ptrCast");
2093520928 const operand = try sema.resolveInst(extra.rhs);
20929
20930 return sema.ptrCastFull(
20931 block,
20932 .{ .ptr_cast = true },
20933 src,
20934 operand,
20935 operand_src,
20936 dest_ty,
20937 );
20938}
20939
20940fn ptrCastFull(
20941 sema: *Sema,
20942 block: *Block,
20943 flags: Zir.Inst.FullPtrCastFlags,
20944 src: LazySrcLoc,
20945 operand: Air.Inst.Ref,
20946 operand_src: LazySrcLoc,
20947 dest_ty: Type,
20948) CompileError!Air.Inst.Ref {
20949 const mod = sema.mod;
2093620950 const operand_ty = sema.typeOf(operand);
2093720951
20938 try sema.checkPtrType(block, dest_ty_src, dest_ty);
20952 try sema.checkPtrType(block, src, dest_ty);
2093920953 try sema.checkPtrOperand(block, operand_src, operand_ty);
2094020954
20941 const operand_info = operand_ty.ptrInfo(mod);
20955 const src_info = operand_ty.ptrInfo(mod);
2094220956 const dest_info = dest_ty.ptrInfo(mod);
20943 if (operand_info.flags.is_const and !dest_info.flags.is_const) {
20944 const msg = msg: {
20945 const msg = try sema.errMsg(block, src, "cast discards const qualifier", .{});
20946 errdefer msg.destroy(sema.gpa);
2094720957
20948 try sema.errNote(block, src, msg, "consider using '@constCast'", .{});
20949 break :msg msg;
20950 };
20951 return sema.failWithOwnedErrorMsg(msg);
20952 }
20953 if (operand_info.flags.is_volatile and !dest_info.flags.is_volatile) {
20954 const msg = msg: {
20955 const msg = try sema.errMsg(block, src, "cast discards volatile qualifier", .{});
20956 errdefer msg.destroy(sema.gpa);
20958 try sema.resolveTypeLayout(src_info.child.toType());
20959 try sema.resolveTypeLayout(dest_info.child.toType());
2095720960
20958 try sema.errNote(block, src, msg, "consider using '@volatileCast'", .{});
20959 break :msg msg;
20960 };
20961 return sema.failWithOwnedErrorMsg(msg);
20961 const src_slice_like = src_info.flags.size == .Slice or
20962 (src_info.flags.size == .One and src_info.child.toType().zigTypeTag(mod) == .Array);
20963
20964 const dest_slice_like = dest_info.flags.size == .Slice or
20965 (dest_info.flags.size == .One and dest_info.child.toType().zigTypeTag(mod) == .Array);
20966
20967 if (dest_info.flags.size == .Slice and !src_slice_like) {
20968 return sema.fail(block, src, "illegal pointer cast to slice", .{});
2096220969 }
20963 if (operand_info.flags.address_space != dest_info.flags.address_space) {
20964 const msg = msg: {
20965 const msg = try sema.errMsg(block, src, "cast changes pointer address space", .{});
20966 errdefer msg.destroy(sema.gpa);
2096720970
20968 try sema.errNote(block, src, msg, "consider using '@addrSpaceCast'", .{});
20969 break :msg msg;
20971 if (dest_info.flags.size == .Slice) {
20972 const src_elem_size = switch (src_info.flags.size) {
20973 .Slice => src_info.child.toType().abiSize(mod),
20974 // pointer to array
20975 .One => src_info.child.toType().childType(mod).abiSize(mod),
20976 else => unreachable,
2097020977 };
20971 return sema.failWithOwnedErrorMsg(msg);
20978 const dest_elem_size = dest_info.child.toType().abiSize(mod);
20979 if (src_elem_size != dest_elem_size) {
20980 return sema.fail(block, src, "TODO: implement @ptrCast between slices changing the length", .{});
20981 }
2097220982 }
2097320983
20974 const dest_is_slice = dest_ty.isSlice(mod);
20975 const operand_is_slice = operand_ty.isSlice(mod);
20976 if (dest_is_slice and !operand_is_slice) {
20977 return sema.fail(block, dest_ty_src, "illegal pointer cast to slice", .{});
20978 }
20979 const ptr = if (operand_is_slice and !dest_is_slice)
20980 try sema.analyzeSlicePtr(block, operand_src, operand, operand_ty)
20981 else
20982 operand;
20984 // The checking logic in this function must stay in sync with Sema.coerceInMemoryAllowedPtrs
2098320985
20984 const dest_elem_ty = dest_ty.elemType2(mod);
20985 try sema.resolveTypeLayout(dest_elem_ty);
20986 const dest_align = dest_ty.ptrAlignment(mod);
20987
20988 const operand_elem_ty = operand_ty.elemType2(mod);
20989 try sema.resolveTypeLayout(operand_elem_ty);
20990 const operand_align = operand_ty.ptrAlignment(mod);
20991
20992 // If the destination is less aligned than the source, preserve the source alignment
20993 const aligned_dest_ty = if (operand_align <= dest_align) dest_ty else blk: {
20994 // Unwrap the pointer (or pointer-like optional) type, set alignment, and re-wrap into result
20995 var dest_ptr_info = dest_ty.ptrInfo(mod);
20996 dest_ptr_info.flags.alignment = Alignment.fromNonzeroByteUnits(operand_align);
20997 if (dest_ty.zigTypeTag(mod) == .Optional) {
20998 break :blk try mod.optionalType((try mod.ptrType(dest_ptr_info)).toIntern());
20999 } else {
21000 break :blk try mod.ptrType(dest_ptr_info);
20986 if (!flags.ptr_cast) {
20987 check_size: {
20988 if (src_info.flags.size == dest_info.flags.size) break :check_size;
20989 if (src_slice_like and dest_slice_like) break :check_size;
20990 if (src_info.flags.size == .C) break :check_size;
20991 if (dest_info.flags.size == .C) break :check_size;
20992 return sema.failWithOwnedErrorMsg(msg: {
20993 const msg = try sema.errMsg(block, src, "cannot implicitly convert {s} pointer to {s} pointer", .{
20994 pointerSizeString(src_info.flags.size),
20995 pointerSizeString(dest_info.flags.size),
20996 });
20997 errdefer msg.destroy(sema.gpa);
20998 if (dest_info.flags.size == .Many and
20999 (src_info.flags.size == .Slice or
21000 (src_info.flags.size == .One and src_info.child.toType().zigTypeTag(mod) == .Array)))
21001 {
21002 try sema.errNote(block, src, msg, "use 'ptr' field to convert slice to many pointer", .{});
21003 } else {
21004 try sema.errNote(block, src, msg, "use @ptrCast to change pointer size", .{});
21005 }
21006 break :msg msg;
21007 });
21008 }
21009
21010 check_child: {
21011 const src_child = if (dest_info.flags.size == .Slice and src_info.flags.size == .One) blk: {
21012 // *[n]T -> []T
21013 break :blk src_info.child.toType().childType(mod);
21014 } else src_info.child.toType();
21015
21016 const dest_child = dest_info.child.toType();
21017
21018 const imc_res = try sema.coerceInMemoryAllowed(
21019 block,
21020 dest_child,
21021 src_child,
21022 !dest_info.flags.is_const,
21023 mod.getTarget(),
21024 src,
21025 operand_src,
21026 );
21027 if (imc_res == .ok) break :check_child;
21028 return sema.failWithOwnedErrorMsg(msg: {
21029 const msg = try sema.errMsg(block, src, "pointer element type '{}' cannot coerce into element type '{}'", .{
21030 src_child.fmt(mod),
21031 dest_child.fmt(mod),
21032 });
21033 errdefer msg.destroy(sema.gpa);
21034 try imc_res.report(sema, block, src, msg);
21035 try sema.errNote(block, src, msg, "use @ptrCast to cast pointer element type", .{});
21036 break :msg msg;
21037 });
21038 }
21039
21040 check_sent: {
21041 if (dest_info.sentinel == .none) break :check_sent;
21042 if (src_info.flags.size == .C) break :check_sent;
21043 if (src_info.sentinel != .none) {
21044 const coerced_sent = try mod.intern_pool.getCoerced(sema.gpa, src_info.sentinel, dest_info.child);
21045 if (dest_info.sentinel == coerced_sent) break :check_sent;
21046 }
21047 if (src_slice_like and src_info.flags.size == .One and dest_info.flags.size == .Slice) {
21048 // [*]nT -> []T
21049 const arr_ty = src_info.child.toType();
21050 if (arr_ty.sentinel(mod)) |src_sentinel| {
21051 const coerced_sent = try mod.intern_pool.getCoerced(sema.gpa, src_sentinel.toIntern(), dest_info.child);
21052 if (dest_info.sentinel == coerced_sent) break :check_sent;
21053 }
21054 }
21055 return sema.failWithOwnedErrorMsg(msg: {
21056 const msg = if (src_info.sentinel == .none) blk: {
21057 break :blk try sema.errMsg(block, src, "destination pointer requires '{}' sentinel", .{
21058 dest_info.sentinel.toValue().fmtValue(dest_info.child.toType(), mod),
21059 });
21060 } else blk: {
21061 break :blk try sema.errMsg(block, src, "pointer sentinel '{}' cannot coerce into pointer sentinel '{}'", .{
21062 src_info.sentinel.toValue().fmtValue(src_info.child.toType(), mod),
21063 dest_info.sentinel.toValue().fmtValue(dest_info.child.toType(), mod),
21064 });
21065 };
21066 errdefer msg.destroy(sema.gpa);
21067 try sema.errNote(block, src, msg, "use @ptrCast to cast pointer sentinel", .{});
21068 break :msg msg;
21069 });
2100121070 }
21002 };
2100321071
21004 if (dest_is_slice) {
21005 const operand_elem_size = operand_elem_ty.abiSize(mod);
21006 const dest_elem_size = dest_elem_ty.abiSize(mod);
21007 if (operand_elem_size != dest_elem_size) {
21008 return sema.fail(block, dest_ty_src, "TODO: implement @ptrCast between slices changing the length", .{});
21072 if (src_info.packed_offset.host_size != dest_info.packed_offset.host_size) {
21073 return sema.failWithOwnedErrorMsg(msg: {
21074 const msg = try sema.errMsg(block, src, "pointer host size '{}' cannot coerce into pointer host size '{}'", .{
21075 src_info.packed_offset.host_size,
21076 dest_info.packed_offset.host_size,
21077 });
21078 errdefer msg.destroy(sema.gpa);
21079 try sema.errNote(block, src, msg, "use @ptrCast to cast pointer host size", .{});
21080 break :msg msg;
21081 });
21082 }
21083
21084 if (src_info.packed_offset.bit_offset != dest_info.packed_offset.bit_offset) {
21085 return sema.failWithOwnedErrorMsg(msg: {
21086 const msg = try sema.errMsg(block, src, "pointer bit offset '{}' cannot coerce into pointer bit offset '{}'", .{
21087 src_info.packed_offset.bit_offset,
21088 dest_info.packed_offset.bit_offset,
21089 });
21090 errdefer msg.destroy(sema.gpa);
21091 try sema.errNote(block, src, msg, "use @ptrCast to cast pointer bit offset", .{});
21092 break :msg msg;
21093 });
21094 }
21095
21096 check_allowzero: {
21097 const src_allows_zero = operand_ty.ptrAllowsZero(mod);
21098 const dest_allows_zero = dest_ty.ptrAllowsZero(mod);
21099 if (!src_allows_zero) break :check_allowzero;
21100 if (dest_allows_zero) break :check_allowzero;
21101
21102 return sema.failWithOwnedErrorMsg(msg: {
21103 const msg = try sema.errMsg(block, src, "'{}' could have null values which are illegal in type '{}'", .{
21104 operand_ty.fmt(mod),
21105 dest_ty.fmt(mod),
21106 });
21107 errdefer msg.destroy(sema.gpa);
21108 try sema.errNote(block, src, msg, "use @ptrCast to assert the pointer is not null", .{});
21109 break :msg msg;
21110 });
2100921111 }
21112
21113 // TODO: vector index?
2101021114 }
2101121115
21012 if (dest_align > operand_align) {
21013 const msg = msg: {
21014 const msg = try sema.errMsg(block, src, "cast increases pointer alignment", .{});
21015 errdefer msg.destroy(sema.gpa);
21116 const src_align = src_info.flags.alignment.toByteUnitsOptional() orelse src_info.child.toType().abiAlignment(mod);
21117 const dest_align = dest_info.flags.alignment.toByteUnitsOptional() orelse dest_info.child.toType().abiAlignment(mod);
21118 if (!flags.align_cast) {
21119 if (dest_align > src_align) {
21120 return sema.failWithOwnedErrorMsg(msg: {
21121 const msg = try sema.errMsg(block, src, "cast increases pointer alignment", .{});
21122 errdefer msg.destroy(sema.gpa);
21123 try sema.errNote(block, operand_src, msg, "'{}' has alignment '{d}'", .{
21124 operand_ty.fmt(mod), src_align,
21125 });
21126 try sema.errNote(block, src, msg, "'{}' has alignment '{d}'", .{
21127 dest_ty.fmt(mod), dest_align,
21128 });
21129 try sema.errNote(block, src, msg, "use @alignCast to assert pointer alignment", .{});
21130 break :msg msg;
21131 });
21132 }
21133 }
2101621134
21017 try sema.errNote(block, operand_src, msg, "'{}' has alignment '{d}'", .{
21018 operand_ty.fmt(mod), operand_align,
21135 if (!flags.addrspace_cast) {
21136 if (src_info.flags.address_space != dest_info.flags.address_space) {
21137 return sema.failWithOwnedErrorMsg(msg: {
21138 const msg = try sema.errMsg(block, src, "cast changes pointer address space", .{});
21139 errdefer msg.destroy(sema.gpa);
21140 try sema.errNote(block, operand_src, msg, "'{}' has address space '{s}'", .{
21141 operand_ty.fmt(mod), @tagName(src_info.flags.address_space),
21142 });
21143 try sema.errNote(block, src, msg, "'{}' has address space '{s}'", .{
21144 dest_ty.fmt(mod), @tagName(dest_info.flags.address_space),
21145 });
21146 try sema.errNote(block, src, msg, "use @addrSpaceCast to cast pointer address space", .{});
21147 break :msg msg;
21148 });
21149 }
21150 } else {
21151 // Some address space casts are always disallowed
21152 if (!target_util.addrSpaceCastIsValid(mod.getTarget(), src_info.flags.address_space, dest_info.flags.address_space)) {
21153 return sema.failWithOwnedErrorMsg(msg: {
21154 const msg = try sema.errMsg(block, src, "invalid address space cast", .{});
21155 errdefer msg.destroy(sema.gpa);
21156 try sema.errNote(block, operand_src, msg, "address space '{s}' is not compatible with address space '{s}'", .{
21157 @tagName(src_info.flags.address_space),
21158 @tagName(dest_info.flags.address_space),
21159 });
21160 break :msg msg;
2101921161 });
21020 try sema.errNote(block, dest_ty_src, msg, "'{}' has alignment '{d}'", .{
21021 dest_ty.fmt(mod), dest_align,
21162 }
21163 }
21164
21165 if (!flags.const_cast) {
21166 if (src_info.flags.is_const and !dest_info.flags.is_const) {
21167 return sema.failWithOwnedErrorMsg(msg: {
21168 const msg = try sema.errMsg(block, src, "cast discards const qualifier", .{});
21169 errdefer msg.destroy(sema.gpa);
21170 try sema.errNote(block, src, msg, "use @constCast to discard const qualifier", .{});
21171 break :msg msg;
2102221172 });
21173 }
21174 }
2102321175
21024 try sema.errNote(block, src, msg, "consider using '@alignCast'", .{});
21025 break :msg msg;
21026 };
21027 return sema.failWithOwnedErrorMsg(msg);
21176 if (!flags.volatile_cast) {
21177 if (src_info.flags.is_volatile and !dest_info.flags.is_volatile) {
21178 return sema.failWithOwnedErrorMsg(msg: {
21179 const msg = try sema.errMsg(block, src, "cast discards volatile qualifier", .{});
21180 errdefer msg.destroy(sema.gpa);
21181 try sema.errNote(block, src, msg, "use @volatileCast to discard volatile qualifier", .{});
21182 break :msg msg;
21183 });
21184 }
2102821185 }
2102921186
21030 if (try sema.resolveMaybeUndefVal(ptr)) |operand_val| {
21031 if (!dest_ty.ptrAllowsZero(mod) and operand_val.isUndef(mod)) {
21032 return sema.failWithUseOfUndef(block, operand_src);
21187 const ptr = if (src_info.flags.size == .Slice and dest_info.flags.size != .Slice) ptr: {
21188 break :ptr try sema.analyzeSlicePtr(block, operand_src, operand, operand_ty);
21189 } else operand;
21190
21191 const dest_ptr_ty = if (dest_info.flags.size == .Slice and src_info.flags.size != .Slice) blk: {
21192 // Only convert to a many-pointer at first
21193 var info = dest_info;
21194 info.flags.size = .Many;
21195 const ty = try mod.ptrType(info);
21196 if (dest_ty.zigTypeTag(mod) == .Optional) {
21197 break :blk try mod.optionalType(ty.toIntern());
21198 } else {
21199 break :blk ty;
2103321200 }
21034 if (!dest_ty.ptrAllowsZero(mod) and operand_val.isNull(mod)) {
21035 return sema.fail(block, operand_src, "null pointer casted to type '{}'", .{dest_ty.fmt(mod)});
21201 } else dest_ty;
21202
21203 // Cannot do @addrSpaceCast at comptime
21204 if (!flags.addrspace_cast) {
21205 if (try sema.resolveMaybeUndefVal(ptr)) |ptr_val| {
21206 if (!dest_ty.ptrAllowsZero(mod) and ptr_val.isUndef(mod)) {
21207 return sema.failWithUseOfUndef(block, operand_src);
21208 }
21209 if (!dest_ty.ptrAllowsZero(mod) and ptr_val.isNull(mod)) {
21210 return sema.fail(block, operand_src, "null pointer casted to type '{}'", .{dest_ty.fmt(mod)});
21211 }
21212 if (dest_align > src_align) {
21213 if (try ptr_val.getUnsignedIntAdvanced(mod, null)) |addr| {
21214 if (addr % dest_align != 0) {
21215 return sema.fail(block, operand_src, "pointer address 0x{X} is not aligned to {d} bytes", .{ addr, dest_align });
21216 }
21217 }
21218 }
21219 if (dest_info.flags.size == .Slice and src_info.flags.size != .Slice) {
21220 if (ptr_val.isUndef(mod)) return sema.addConstUndef(dest_ty);
21221 const arr_len = try mod.intValue(Type.usize, src_info.child.toType().arrayLen(mod));
21222 return sema.addConstant((try mod.intern(.{ .ptr = .{
21223 .ty = dest_ty.toIntern(),
21224 .addr = mod.intern_pool.indexToKey(ptr_val.toIntern()).ptr.addr,
21225 .len = arr_len.toIntern(),
21226 } })).toValue());
21227 } else {
21228 assert(dest_ptr_ty.eql(dest_ty, mod));
21229 return sema.addConstant(try mod.getCoerced(ptr_val, dest_ty));
21230 }
2103621231 }
21037 return sema.addConstant(try mod.getCoerced(operand_val, aligned_dest_ty));
2103821232 }
2103921233
2104021234 try sema.requireRuntimeBlock(block, src, null);
21235
2104121236 if (block.wantSafety() and operand_ty.ptrAllowsZero(mod) and !dest_ty.ptrAllowsZero(mod) and
21042 (try sema.typeHasRuntimeBits(dest_ty.elemType2(mod)) or dest_ty.elemType2(mod).zigTypeTag(mod) == .Fn))
21237 (try sema.typeHasRuntimeBits(dest_info.child.toType()) or dest_info.child.toType().zigTypeTag(mod) == .Fn))
2104321238 {
2104421239 const ptr_int = try block.addUnOp(.int_from_ptr, ptr);
2104521240 const is_non_zero = try block.addBinOp(.cmp_neq, ptr_int, .zero_usize);
21046 const ok = if (operand_is_slice) ok: {
21047 const len = try sema.analyzeSliceLen(block, operand_src, operand);
21241 const ok = if (src_info.flags.size == .Slice and dest_info.flags.size == .Slice) ok: {
21242 const len = try sema.analyzeSliceLen(block, operand_src, ptr);
2104821243 const len_zero = try block.addBinOp(.cmp_eq, len, .zero_usize);
2104921244 break :ok try block.addBinOp(.bit_or, len_zero, is_non_zero);
2105021245 } else is_non_zero;
2105121246 try sema.addSafetyCheck(block, ok, .cast_to_null);
2105221247 }
2105321248
21054 return block.addBitCast(aligned_dest_ty, ptr);
21055}
21056
21057fn zirConstCast(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!Air.Inst.Ref {
21058 const mod = sema.mod;
21059 const extra = sema.code.extraData(Zir.Inst.UnNode, extended.operand).data;
21060 const src = LazySrcLoc.nodeOffset(extra.node);
21061 const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = extra.node };
21062 const operand = try sema.resolveInst(extra.operand);
21063 const operand_ty = sema.typeOf(operand);
21064 try sema.checkPtrOperand(block, operand_src, operand_ty);
21249 if (block.wantSafety() and dest_align > src_align and try sema.typeHasRuntimeBits(dest_info.child.toType())) {
21250 const align_minus_1 = try sema.addConstant(
21251 try mod.intValue(Type.usize, dest_align - 1),
21252 );
21253 const ptr_int = try block.addUnOp(.int_from_ptr, ptr);
21254 const remainder = try block.addBinOp(.bit_and, ptr_int, align_minus_1);
21255 const is_aligned = try block.addBinOp(.cmp_eq, remainder, .zero_usize);
21256 const ok = if (src_info.flags.size == .Slice and dest_info.flags.size == .Slice) ok: {
21257 const len = try sema.analyzeSliceLen(block, operand_src, ptr);
21258 const len_zero = try block.addBinOp(.cmp_eq, len, .zero_usize);
21259 break :ok try block.addBinOp(.bit_or, len_zero, is_aligned);
21260 } else is_aligned;
21261 try sema.addSafetyCheck(block, ok, .incorrect_alignment);
21262 }
2106521263
21066 var ptr_info = operand_ty.ptrInfo(mod);
21067 ptr_info.flags.is_const = false;
21068 const dest_ty = try mod.ptrType(ptr_info);
21264 // If we're going from an array pointer to a slice, this will only be the pointer part!
21265 const result_ptr = if (flags.addrspace_cast) ptr: {
21266 // We can't change address spaces with a bitcast, so this requires two instructions
21267 var intermediate_info = src_info;
21268 intermediate_info.flags.address_space = dest_info.flags.address_space;
21269 const intermediate_ptr_ty = try mod.ptrType(intermediate_info);
21270 const intermediate_ty = if (dest_ptr_ty.zigTypeTag(mod) == .Optional) blk: {
21271 break :blk try mod.optionalType(intermediate_ptr_ty.toIntern());
21272 } else intermediate_ptr_ty;
21273 const intermediate = try block.addInst(.{
21274 .tag = .addrspace_cast,
21275 .data = .{ .ty_op = .{
21276 .ty = try sema.addType(intermediate_ty),
21277 .operand = ptr,
21278 } },
21279 });
21280 if (intermediate_ty.eql(dest_ptr_ty, mod)) {
21281 // We only changed the address space, so no need for a bitcast
21282 break :ptr intermediate;
21283 }
21284 break :ptr try block.addBitCast(dest_ptr_ty, intermediate);
21285 } else ptr: {
21286 break :ptr try block.addBitCast(dest_ptr_ty, ptr);
21287 };
2106921288
21070 if (try sema.resolveMaybeUndefVal(operand)) |operand_val| {
21071 return sema.addConstant(try mod.getCoerced(operand_val, dest_ty));
21289 if (dest_info.flags.size == .Slice and src_info.flags.size != .Slice) {
21290 // We have to construct a slice using the operand's child's array length
21291 // Note that we know from the check at the start of the function that operand_ty is slice-like
21292 const arr_len = try sema.addConstant(
21293 try mod.intValue(Type.usize, src_info.child.toType().arrayLen(mod)),
21294 );
21295 return block.addInst(.{
21296 .tag = .slice,
21297 .data = .{ .ty_pl = .{
21298 .ty = try sema.addType(dest_ty),
21299 .payload = try sema.addExtra(Air.Bin{
21300 .lhs = result_ptr,
21301 .rhs = arr_len,
21302 }),
21303 } },
21304 });
21305 } else {
21306 assert(dest_ptr_ty.eql(dest_ty, mod));
21307 return result_ptr;
2107221308 }
21073
21074 try sema.requireRuntimeBlock(block, src, null);
21075 return block.addBitCast(dest_ty, operand);
2107621309}
2107721310
21078fn zirVolatileCast(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!Air.Inst.Ref {
21311fn zirPtrCastNoDest(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!Air.Inst.Ref {
2107921312 const mod = sema.mod;
21313 const flags = @bitCast(Zir.Inst.FullPtrCastFlags, @truncate(u5, extended.small));
2108021314 const extra = sema.code.extraData(Zir.Inst.UnNode, extended.operand).data;
2108121315 const src = LazySrcLoc.nodeOffset(extra.node);
2108221316 const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = extra.node };
......@@ -21085,11 +21319,12 @@ fn zirVolatileCast(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstD
2108521319 try sema.checkPtrOperand(block, operand_src, operand_ty);
2108621320
2108721321 var ptr_info = operand_ty.ptrInfo(mod);
21088 ptr_info.flags.is_volatile = false;
21322 if (flags.const_cast) ptr_info.flags.is_const = false;
21323 if (flags.volatile_cast) ptr_info.flags.is_volatile = false;
2108921324 const dest_ty = try mod.ptrType(ptr_info);
2109021325
2109121326 if (try sema.resolveMaybeUndefVal(operand)) |operand_val| {
21092 return sema.addConstant(operand_val);
21327 return sema.addConstant(try mod.getCoerced(operand_val, dest_ty));
2109321328 }
2109421329
2109521330 try sema.requireRuntimeBlock(block, src, null);
......@@ -21100,24 +21335,21 @@ fn zirTruncate(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
2110021335 const mod = sema.mod;
2110121336 const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
2110221337 const src = inst_data.src();
21103 const dest_ty_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
21104 const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
21338 const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
2110521339 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
21106 const dest_scalar_ty = try sema.resolveType(block, dest_ty_src, extra.lhs);
21340 const dest_ty = try sema.resolveCastDestType(block, src, extra.lhs, "@truncate");
21341 const dest_scalar_ty = try sema.checkIntOrVectorAllowComptime(block, dest_ty, src);
2110721342 const operand = try sema.resolveInst(extra.rhs);
21108 const dest_is_comptime_int = try sema.checkIntType(block, dest_ty_src, dest_scalar_ty);
2110921343 const operand_ty = sema.typeOf(operand);
2111021344 const operand_scalar_ty = try sema.checkIntOrVectorAllowComptime(block, operand_ty, operand_src);
21111 const is_vector = operand_ty.zigTypeTag(mod) == .Vector;
21112 const dest_ty = if (is_vector)
21113 try mod.vectorType(.{
21114 .len = operand_ty.vectorLen(mod),
21115 .child = dest_scalar_ty.toIntern(),
21116 })
21117 else
21118 dest_scalar_ty;
2111921345
21120 if (dest_is_comptime_int) {
21346 const operand_is_vector = operand_ty.zigTypeTag(mod) == .Vector;
21347 const dest_is_vector = dest_ty.zigTypeTag(mod) == .Vector;
21348 if (operand_is_vector != dest_is_vector) {
21349 return sema.fail(block, operand_src, "expected type '{}', found '{}'", .{ dest_ty.fmt(mod), operand_ty.fmt(mod) });
21350 }
21351
21352 if (dest_scalar_ty.zigTypeTag(mod) == .ComptimeInt) {
2112121353 return sema.coerce(block, dest_ty, operand, operand_src);
2112221354 }
2112321355
......@@ -21147,7 +21379,7 @@ fn zirTruncate(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
2114721379 .{ dest_ty.fmt(mod), operand_ty.fmt(mod) },
2114821380 );
2114921381 errdefer msg.destroy(sema.gpa);
21150 try sema.errNote(block, dest_ty_src, msg, "destination type has {d} bits", .{
21382 try sema.errNote(block, src, msg, "destination type has {d} bits", .{
2115121383 dest_info.bits,
2115221384 });
2115321385 try sema.errNote(block, operand_src, msg, "operand type has {d} bits", .{
......@@ -21161,7 +21393,7 @@ fn zirTruncate(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
2116121393
2116221394 if (try sema.resolveMaybeUndefValIntable(operand)) |val| {
2116321395 if (val.isUndef(mod)) return sema.addConstUndef(dest_ty);
21164 if (!is_vector) {
21396 if (!dest_is_vector) {
2116521397 return sema.addConstant(try mod.getCoerced(
2116621398 try val.intTrunc(operand_ty, sema.arena, dest_info.signedness, dest_info.bits, mod),
2116721399 dest_ty,
......@@ -21182,59 +21414,6 @@ fn zirTruncate(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
2118221414 return block.addTyOp(.trunc, dest_ty, operand);
2118321415}
2118421416
21185fn zirAlignCast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
21186 const mod = sema.mod;
21187 const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
21188 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
21189 const align_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
21190 const ptr_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
21191 const dest_align = try sema.resolveAlign(block, align_src, extra.lhs);
21192 const ptr = try sema.resolveInst(extra.rhs);
21193 const ptr_ty = sema.typeOf(ptr);
21194
21195 try sema.checkPtrOperand(block, ptr_src, ptr_ty);
21196
21197 var ptr_info = ptr_ty.ptrInfo(mod);
21198 ptr_info.flags.alignment = dest_align;
21199 var dest_ty = try mod.ptrType(ptr_info);
21200 if (ptr_ty.zigTypeTag(mod) == .Optional) {
21201 dest_ty = try mod.optionalType(dest_ty.toIntern());
21202 }
21203
21204 if (try sema.resolveDefinedValue(block, ptr_src, ptr)) |val| {
21205 if (try val.getUnsignedIntAdvanced(mod, null)) |addr| {
21206 const dest_align_bytes = dest_align.toByteUnitsOptional().?;
21207 if (addr % dest_align_bytes != 0) {
21208 return sema.fail(block, ptr_src, "pointer address 0x{X} is not aligned to {d} bytes", .{ addr, dest_align_bytes });
21209 }
21210 }
21211 return sema.addConstant(try mod.getCoerced(val, dest_ty));
21212 }
21213
21214 try sema.requireRuntimeBlock(block, inst_data.src(), ptr_src);
21215 if (block.wantSafety() and dest_align.order(Alignment.fromNonzeroByteUnits(1)).compare(.gt) and
21216 try sema.typeHasRuntimeBits(ptr_info.child.toType()))
21217 {
21218 const align_minus_1 = try sema.addConstant(
21219 try mod.intValue(Type.usize, dest_align.toByteUnitsOptional().? - 1),
21220 );
21221 const actual_ptr = if (ptr_ty.isSlice(mod))
21222 try sema.analyzeSlicePtr(block, ptr_src, ptr, ptr_ty)
21223 else
21224 ptr;
21225 const ptr_int = try block.addUnOp(.int_from_ptr, actual_ptr);
21226 const remainder = try block.addBinOp(.bit_and, ptr_int, align_minus_1);
21227 const is_aligned = try block.addBinOp(.cmp_eq, remainder, .zero_usize);
21228 const ok = if (ptr_ty.isSlice(mod)) ok: {
21229 const len = try sema.analyzeSliceLen(block, ptr_src, ptr);
21230 const len_zero = try block.addBinOp(.cmp_eq, len, .zero_usize);
21231 break :ok try block.addBinOp(.bit_or, len_zero, is_aligned);
21232 } else is_aligned;
21233 try sema.addSafetyCheck(block, ok, .incorrect_alignment);
21234 }
21235 return sema.bitCast(block, dest_ty, ptr, ptr_src, null);
21236}
21237
2123821417fn zirBitCount(
2123921418 sema: *Sema,
2124021419 block: *Block,
......@@ -21546,7 +21725,7 @@ fn checkPtrOperand(
2154621725 };
2154721726 return sema.failWithOwnedErrorMsg(msg);
2154821727 },
21549 .Optional => if (ty.isPtrLikeOptional(mod)) return,
21728 .Optional => if (ty.childType(mod).zigTypeTag(mod) == .Pointer) return,
2155021729 else => {},
2155121730 }
2155221731 return sema.fail(block, ty_src, "expected pointer type, found '{}'", .{ty.fmt(mod)});
......@@ -21577,7 +21756,7 @@ fn checkPtrType(
2157721756 };
2157821757 return sema.failWithOwnedErrorMsg(msg);
2157921758 },
21580 .Optional => if (ty.isPtrLikeOptional(mod)) return,
21759 .Optional => if (ty.childType(mod).zigTypeTag(mod) == .Pointer) return,
2158121760 else => {},
2158221761 }
2158321762 return sema.fail(block, ty_src, "expected pointer type, found '{}'", .{ty.fmt(mod)});
src/TypedValue.zig-5
......@@ -241,11 +241,6 @@ pub fn print(
241241 return;
242242 }
243243 try writer.writeAll("@enumFromInt(");
244 try print(.{
245 .ty = Type.type,
246 .val = enum_tag.ty.toValue(),
247 }, writer, level - 1, mod);
248 try writer.writeAll(", ");
249244 try print(.{
250245 .ty = ip.typeOf(enum_tag.int).toType(),
251246 .val = enum_tag.int.toValue(),
src/Zir.zig+30-14
......@@ -230,6 +230,9 @@ pub const Inst = struct {
230230 /// Given an indexable type, returns the type of the element at given index.
231231 /// Uses the `bin` union field. lhs is the indexable type, rhs is the index.
232232 elem_type_index,
233 /// Given a pointer type, returns its element type.
234 /// Uses the `un_node` field.
235 elem_type,
233236 /// Given a pointer to an indexable object, returns the len property. This is
234237 /// used by for loops. This instruction also emits a for-loop specific compile
235238 /// error if the indexable object is not indexable.
......@@ -838,13 +841,12 @@ pub const Inst = struct {
838841 int_cast,
839842 /// Implements the `@ptrCast` builtin.
840843 /// Uses `pl_node` with payload `Bin`. `lhs` is dest type, `rhs` is operand.
844 /// Not every `@ptrCast` will correspond to this instruction - see also
845 /// `ptr_cast_full` in `Extended`.
841846 ptr_cast,
842847 /// Implements the `@truncate` builtin.
843848 /// Uses `pl_node` with payload `Bin`. `lhs` is dest type, `rhs` is operand.
844849 truncate,
845 /// Implements the `@alignCast` builtin.
846 /// Uses `pl_node` with payload `Bin`. `lhs` is dest alignment, `rhs` is operand.
847 align_cast,
848850
849851 /// Implements the `@hasDecl` builtin.
850852 /// Uses the `pl_node` union field. Payload is `Bin`.
......@@ -1005,6 +1007,7 @@ pub const Inst = struct {
10051007 .array_type_sentinel,
10061008 .vector_type,
10071009 .elem_type_index,
1010 .elem_type,
10081011 .indexable_ptr_len,
10091012 .anyframe_type,
10101013 .as,
......@@ -1172,7 +1175,6 @@ pub const Inst = struct {
11721175 .int_cast,
11731176 .ptr_cast,
11741177 .truncate,
1175 .align_cast,
11761178 .has_field,
11771179 .clz,
11781180 .ctz,
......@@ -1309,6 +1311,7 @@ pub const Inst = struct {
13091311 .array_type_sentinel,
13101312 .vector_type,
13111313 .elem_type_index,
1314 .elem_type,
13121315 .indexable_ptr_len,
13131316 .anyframe_type,
13141317 .as,
......@@ -1454,7 +1457,6 @@ pub const Inst = struct {
14541457 .int_cast,
14551458 .ptr_cast,
14561459 .truncate,
1457 .align_cast,
14581460 .has_field,
14591461 .clz,
14601462 .ctz,
......@@ -1539,6 +1541,7 @@ pub const Inst = struct {
15391541 .array_type_sentinel = .pl_node,
15401542 .vector_type = .pl_node,
15411543 .elem_type_index = .bin,
1544 .elem_type = .un_node,
15421545 .indexable_ptr_len = .un_node,
15431546 .anyframe_type = .un_node,
15441547 .as = .bin,
......@@ -1717,7 +1720,6 @@ pub const Inst = struct {
17171720 .int_cast = .pl_node,
17181721 .ptr_cast = .pl_node,
17191722 .truncate = .pl_node,
1720 .align_cast = .pl_node,
17211723 .typeof_builtin = .pl_node,
17221724
17231725 .has_decl = .pl_node,
......@@ -1948,9 +1950,6 @@ pub const Inst = struct {
19481950 /// `small` 0=>weak 1=>strong
19491951 /// `operand` is payload index to `Cmpxchg`.
19501952 cmpxchg,
1951 /// Implement the builtin `@addrSpaceCast`
1952 /// `operand` is payload index to `BinNode`. `lhs` is dest type, `rhs` is operand.
1953 addrspace_cast,
19541953 /// Implement builtin `@cVaArg`.
19551954 /// `operand` is payload index to `BinNode`.
19561955 c_va_arg,
......@@ -1963,12 +1962,21 @@ pub const Inst = struct {
19631962 /// Implement builtin `@cVaStart`.
19641963 /// `operand` is `src_node: i32`.
19651964 c_va_start,
1966 /// Implements the `@constCast` builtin.
1967 /// `operand` is payload index to `UnNode`.
1968 const_cast,
1969 /// Implements the `@volatileCast` builtin.
1965 /// Implements the following builtins:
1966 /// `@ptrCast`, `@alignCast`, `@addrSpaceCast`, `@constCast`, `@volatileCast`.
1967 /// Represents an arbitrary nesting of the above builtins. Such a nesting is treated as a
1968 /// single operation which can modify multiple components of a pointer type.
1969 /// `operand` is payload index to `BinNode`.
1970 /// `small` contains `FullPtrCastFlags`.
1971 /// AST node is the root of the nested casts.
1972 /// `lhs` is dest type, `rhs` is operand.
1973 ptr_cast_full,
19701974 /// `operand` is payload index to `UnNode`.
1971 volatile_cast,
1975 /// `small` contains `FullPtrCastFlags`.
1976 /// Guaranteed to only have flags where no explicit destination type is
1977 /// required (const_cast and volatile_cast).
1978 /// AST node is the root of the nested casts.
1979 ptr_cast_no_dest,
19721980 /// Implements the `@workItemId` builtin.
19731981 /// `operand` is payload index to `UnNode`.
19741982 work_item_id,
......@@ -2806,6 +2814,14 @@ pub const Inst = struct {
28062814 dbg_var,
28072815 };
28082816
2817 pub const FullPtrCastFlags = packed struct(u5) {
2818 ptr_cast: bool = false,
2819 align_cast: bool = false,
2820 addrspace_cast: bool = false,
2821 const_cast: bool = false,
2822 volatile_cast: bool = false,
2823 };
2824
28092825 /// Trailing:
28102826 /// 0. src_node: i32, // if has_src_node
28112827 /// 1. tag_type: Ref, // if has_tag_type
src/print_zir.zig+30-4
......@@ -154,6 +154,7 @@ const Writer = struct {
154154 .alloc,
155155 .alloc_mut,
156156 .alloc_comptime_mut,
157 .elem_type,
157158 .indexable_ptr_len,
158159 .anyframe_type,
159160 .bit_not,
......@@ -329,7 +330,6 @@ const Writer = struct {
329330 .int_cast,
330331 .ptr_cast,
331332 .truncate,
332 .align_cast,
333333 .div_exact,
334334 .div_floor,
335335 .div_trunc,
......@@ -507,8 +507,6 @@ const Writer = struct {
507507 .reify,
508508 .c_va_copy,
509509 .c_va_end,
510 .const_cast,
511 .volatile_cast,
512510 .work_item_id,
513511 .work_group_size,
514512 .work_group_id,
......@@ -525,7 +523,6 @@ const Writer = struct {
525523 .err_set_cast,
526524 .wasm_memory_grow,
527525 .prefetch,
528 .addrspace_cast,
529526 .c_va_arg,
530527 => {
531528 const inst_data = self.code.extraData(Zir.Inst.BinNode, extended.operand).data;
......@@ -539,6 +536,8 @@ const Writer = struct {
539536
540537 .builtin_async_call => try self.writeBuiltinAsyncCall(stream, extended),
541538 .cmpxchg => try self.writeCmpxchg(stream, extended),
539 .ptr_cast_full => try self.writePtrCastFull(stream, extended),
540 .ptr_cast_no_dest => try self.writePtrCastNoDest(stream, extended),
542541 }
543542 }
544543
......@@ -964,6 +963,33 @@ const Writer = struct {
964963 try self.writeSrc(stream, src);
965964 }
966965
966 fn writePtrCastFull(self: *Writer, stream: anytype, extended: Zir.Inst.Extended.InstData) !void {
967 const flags = @bitCast(Zir.Inst.FullPtrCastFlags, @truncate(u5, extended.small));
968 const extra = self.code.extraData(Zir.Inst.BinNode, extended.operand).data;
969 const src = LazySrcLoc.nodeOffset(extra.node);
970 if (flags.ptr_cast) try stream.writeAll("ptr_cast, ");
971 if (flags.align_cast) try stream.writeAll("align_cast, ");
972 if (flags.addrspace_cast) try stream.writeAll("addrspace_cast, ");
973 if (flags.const_cast) try stream.writeAll("const_cast, ");
974 if (flags.volatile_cast) try stream.writeAll("volatile_cast, ");
975 try self.writeInstRef(stream, extra.lhs);
976 try stream.writeAll(", ");
977 try self.writeInstRef(stream, extra.rhs);
978 try stream.writeAll(")) ");
979 try self.writeSrc(stream, src);
980 }
981
982 fn writePtrCastNoDest(self: *Writer, stream: anytype, extended: Zir.Inst.Extended.InstData) !void {
983 const flags = @bitCast(Zir.Inst.FullPtrCastFlags, @truncate(u5, extended.small));
984 const extra = self.code.extraData(Zir.Inst.UnNode, extended.operand).data;
985 const src = LazySrcLoc.nodeOffset(extra.node);
986 if (flags.const_cast) try stream.writeAll("const_cast, ");
987 if (flags.volatile_cast) try stream.writeAll("volatile_cast, ");
988 try self.writeInstRef(stream, extra.operand);
989 try stream.writeAll(")) ");
990 try self.writeSrc(stream, src);
991 }
992
967993 fn writeAtomicLoad(self: *Writer, stream: anytype, inst: Zir.Inst.Index) !void {
968994 const inst_data = self.code.instructions.items(.data)[inst].pl_node;
969995 const extra = self.code.extraData(Zir.Inst.AtomicLoad, inst_data.payload_index).data;