authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2021-08-05 19:15:59-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2021-08-05 19:19:19-07:00
logc03a04a58942446b48e9294df991a17a3a6f7b48
tree9e306df81d9c1443bee81ccc499d76f620e23923
parente9e3a2994696a3131125ebc4b1f0eec7ca5306d9

stage2: return type expressions of generic functions

* ZIR encoding for function instructions have a body for the return type. This lets Sema for generic functions do the same thing it does for parameters, handling `error.GenericPoison` in the evaluation of the return type by marking the function as generic. * Sema: fix missing block around the new Decl arena finalization. This led to a memory corruption. * Added some floating point support to the LLVM backend but didn't get far enough to pass any new tests.

9 files changed, 344 insertions(+), 208 deletions(-)

src/AstGen.zig+39-31
......@@ -1041,6 +1041,7 @@ fn fnProtoExpr(
10411041 fn_proto: ast.full.FnProto,
10421042) InnerError!Zir.Inst.Ref {
10431043 const astgen = gz.astgen;
1044 const gpa = astgen.gpa;
10441045 const tree = astgen.tree;
10451046 const token_tags = tree.tokens.items(.tag);
10461047
......@@ -1083,7 +1084,6 @@ fn fnProtoExpr(
10831084 .param_anytype;
10841085 _ = try gz.addStrTok(tag, param_name, name_token);
10851086 } else {
1086 const gpa = astgen.gpa;
10871087 const param_type_node = param.type_expr;
10881088 assert(param_type_node != 0);
10891089 var param_gz = gz.makeSubBlock(scope);
......@@ -1113,15 +1113,13 @@ fn fnProtoExpr(
11131113 if (is_inferred_error) {
11141114 return astgen.failTok(maybe_bang, "function prototype may not have inferred error set", .{});
11151115 }
1116 const return_type_inst = try AstGen.expr(
1117 gz,
1118 scope,
1119 .{ .ty = .type_type },
1120 fn_proto.ast.return_type,
1121 );
1116 var ret_gz = gz.makeSubBlock(scope);
1117 defer ret_gz.instructions.deinit(gpa);
1118 const ret_ty = try expr(&ret_gz, scope, coerced_type_rl, fn_proto.ast.return_type);
1119 const ret_br = try ret_gz.addBreak(.break_inline, 0, ret_ty);
11221120
11231121 const cc: Zir.Inst.Ref = if (fn_proto.ast.callconv_expr != 0)
1124 try AstGen.expr(
1122 try expr(
11251123 gz,
11261124 scope,
11271125 .{ .ty = .calling_convention_type },
......@@ -1133,7 +1131,8 @@ fn fnProtoExpr(
11331131 const result = try gz.addFunc(.{
11341132 .src_node = fn_proto.ast.proto_node,
11351133 .param_block = 0,
1136 .ret_ty = return_type_inst,
1134 .ret_ty = ret_gz.instructions.items,
1135 .ret_br = ret_br,
11371136 .body = &[0]Zir.Inst.Index{},
11381137 .cc = cc,
11391138 .align_inst = align_inst,
......@@ -3005,12 +3004,10 @@ fn fnDecl(
30053004 break :inst try comptimeExpr(&decl_gz, params_scope, .{ .ty = .const_slice_u8_type }, fn_proto.ast.section_expr);
30063005 };
30073006
3008 const return_type_inst = try AstGen.expr(
3009 &decl_gz,
3010 params_scope,
3011 .{ .ty = .type_type },
3012 fn_proto.ast.return_type,
3013 );
3007 var ret_gz = gz.makeSubBlock(params_scope);
3008 defer ret_gz.instructions.deinit(gpa);
3009 const ret_ty = try expr(&decl_gz, params_scope, coerced_type_rl, fn_proto.ast.return_type);
3010 const ret_br = try ret_gz.addBreak(.break_inline, 0, ret_ty);
30143011
30153012 const cc: Zir.Inst.Ref = blk: {
30163013 if (fn_proto.ast.callconv_expr != 0) {
......@@ -3021,7 +3018,7 @@ fn fnDecl(
30213018 .{},
30223019 );
30233020 }
3024 break :blk try AstGen.expr(
3021 break :blk try expr(
30253022 &decl_gz,
30263023 params_scope,
30273024 .{ .ty = .calling_convention_type },
......@@ -3046,7 +3043,8 @@ fn fnDecl(
30463043 }
30473044 break :func try decl_gz.addFunc(.{
30483045 .src_node = decl_node,
3049 .ret_ty = return_type_inst,
3046 .ret_ty = ret_gz.instructions.items,
3047 .ret_br = ret_br,
30503048 .param_block = block_inst,
30513049 .body = &[0]Zir.Inst.Index{},
30523050 .cc = cc,
......@@ -3085,7 +3083,8 @@ fn fnDecl(
30853083 break :func try decl_gz.addFunc(.{
30863084 .src_node = decl_node,
30873085 .param_block = block_inst,
3088 .ret_ty = return_type_inst,
3086 .ret_ty = ret_gz.instructions.items,
3087 .ret_br = ret_br,
30893088 .body = fn_gz.instructions.items,
30903089 .cc = cc,
30913090 .align_inst = .none, // passed in the per-decl data
......@@ -3430,7 +3429,8 @@ fn testDecl(
34303429 const func_inst = try decl_block.addFunc(.{
34313430 .src_node = node,
34323431 .param_block = block_inst,
3433 .ret_ty = .void_type,
3432 .ret_ty = &.{},
3433 .ret_br = 0,
34343434 .body = fn_block.instructions.items,
34353435 .cc = .none,
34363436 .align_inst = .none,
......@@ -9127,7 +9127,8 @@ const GenZir = struct {
91279127 src_node: ast.Node.Index,
91289128 body: []const Zir.Inst.Index,
91299129 param_block: Zir.Inst.Index,
9130 ret_ty: Zir.Inst.Ref,
9130 ret_ty: []const Zir.Inst.Index,
9131 ret_br: Zir.Inst.Index,
91319132 cc: Zir.Inst.Ref,
91329133 align_inst: Zir.Inst.Ref,
91339134 lib_name: u32,
......@@ -9137,7 +9138,6 @@ const GenZir = struct {
91379138 is_extern: bool,
91389139 }) !Zir.Inst.Ref {
91399140 assert(args.src_node != 0);
9140 assert(args.ret_ty != .none);
91419141 const astgen = gz.astgen;
91429142 const gpa = astgen.gpa;
91439143
......@@ -9179,7 +9179,7 @@ const GenZir = struct {
91799179 try astgen.extra.ensureUnusedCapacity(
91809180 gpa,
91819181 @typeInfo(Zir.Inst.ExtendedFunc).Struct.fields.len +
9182 args.body.len + src_locs.len +
9182 args.ret_ty.len + args.body.len + src_locs.len +
91839183 @boolToInt(args.lib_name != 0) +
91849184 @boolToInt(args.align_inst != .none) +
91859185 @boolToInt(args.cc != .none),
......@@ -9187,7 +9187,7 @@ const GenZir = struct {
91879187 const payload_index = astgen.addExtraAssumeCapacity(Zir.Inst.ExtendedFunc{
91889188 .src_node = gz.nodeIndexToRelative(args.src_node),
91899189 .param_block = args.param_block,
9190 .return_type = args.ret_ty,
9190 .ret_body_len = @intCast(u32, args.ret_ty.len),
91919191 .body_len = @intCast(u32, args.body.len),
91929192 });
91939193 if (args.lib_name != 0) {
......@@ -9199,10 +9199,14 @@ const GenZir = struct {
91999199 if (args.align_inst != .none) {
92009200 astgen.extra.appendAssumeCapacity(@enumToInt(args.align_inst));
92019201 }
9202 astgen.extra.appendSliceAssumeCapacity(args.ret_ty);
92029203 astgen.extra.appendSliceAssumeCapacity(args.body);
92039204 astgen.extra.appendSliceAssumeCapacity(src_locs);
92049205
92059206 const new_index = @intCast(Zir.Inst.Index, astgen.instructions.len);
9207 if (args.ret_br != 0) {
9208 astgen.instructions.items(.data)[args.ret_br].@"break".block_inst = new_index;
9209 }
92069210 astgen.instructions.appendAssumeCapacity(.{
92079211 .tag = .extended,
92089212 .data = .{ .extended = .{
......@@ -9222,23 +9226,27 @@ const GenZir = struct {
92229226 gz.instructions.appendAssumeCapacity(new_index);
92239227 return indexToRef(new_index);
92249228 } else {
9225 try gz.astgen.extra.ensureUnusedCapacity(
9229 try astgen.extra.ensureUnusedCapacity(
92269230 gpa,
92279231 @typeInfo(Zir.Inst.Func).Struct.fields.len +
9228 args.body.len + src_locs.len,
9232 args.ret_ty.len + args.body.len + src_locs.len,
92299233 );
92309234
9231 const payload_index = gz.astgen.addExtraAssumeCapacity(Zir.Inst.Func{
9235 const payload_index = astgen.addExtraAssumeCapacity(Zir.Inst.Func{
92329236 .param_block = args.param_block,
9233 .return_type = args.ret_ty,
9237 .ret_body_len = @intCast(u32, args.ret_ty.len),
92349238 .body_len = @intCast(u32, args.body.len),
92359239 });
9236 gz.astgen.extra.appendSliceAssumeCapacity(args.body);
9237 gz.astgen.extra.appendSliceAssumeCapacity(src_locs);
9240 astgen.extra.appendSliceAssumeCapacity(args.ret_ty);
9241 astgen.extra.appendSliceAssumeCapacity(args.body);
9242 astgen.extra.appendSliceAssumeCapacity(src_locs);
92389243
92399244 const tag: Zir.Inst.Tag = if (args.is_inferred_error) .func_inferred else .func;
9240 const new_index = @intCast(Zir.Inst.Index, gz.astgen.instructions.len);
9241 gz.astgen.instructions.appendAssumeCapacity(.{
9245 const new_index = @intCast(Zir.Inst.Index, astgen.instructions.len);
9246 if (args.ret_br != 0) {
9247 astgen.instructions.items(.data)[args.ret_br].@"break".block_inst = new_index;
9248 }
9249 astgen.instructions.appendAssumeCapacity(.{
92429250 .tag = tag,
92439251 .data = .{ .pl_node = .{
92449252 .src_node = gz.nodeIndexToRelative(args.src_node),
src/Module.zig+3
......@@ -842,6 +842,9 @@ pub const Fn = struct {
842842
843843 pub fn getInferredErrorSet(func: *Fn) ?*std.StringHashMapUnmanaged(void) {
844844 const ret_ty = func.owner_decl.ty.fnReturnType();
845 if (ret_ty.tag() == .generic_poison) {
846 return null;
847 }
845848 if (ret_ty.zigTypeTag() == .ErrorUnion) {
846849 if (ret_ty.errorUnionSet().castTag(.error_set_inferred)) |payload| {
847850 return &payload.data.map;
src/Sema.zig+162-122
......@@ -2618,128 +2618,130 @@ fn analyzeCall(
26182618 break :new_func gop.key_ptr.*;
26192619 };
26202620
2621 try namespace.anon_decls.ensureUnusedCapacity(gpa, 1);
2622
2623 // Create a Decl for the new function.
2624 const new_decl = try mod.allocateNewDecl(namespace, module_fn.owner_decl.src_node);
2625 // TODO better names for generic function instantiations
2626 const name_index = mod.getNextAnonNameIndex();
2627 new_decl.name = try std.fmt.allocPrintZ(gpa, "{s}__anon_{d}", .{
2628 module_fn.owner_decl.name, name_index,
2629 });
2630 new_decl.src_line = module_fn.owner_decl.src_line;
2631 new_decl.is_pub = module_fn.owner_decl.is_pub;
2632 new_decl.is_exported = module_fn.owner_decl.is_exported;
2633 new_decl.has_align = module_fn.owner_decl.has_align;
2634 new_decl.has_linksection = module_fn.owner_decl.has_linksection;
2635 new_decl.zir_decl_index = module_fn.owner_decl.zir_decl_index;
2636 new_decl.alive = true; // This Decl is called at runtime.
2637 new_decl.has_tv = true;
2638 new_decl.owns_tv = true;
2639 new_decl.analysis = .in_progress;
2640 new_decl.generation = mod.generation;
2641
2642 namespace.anon_decls.putAssumeCapacityNoClobber(new_decl, {});
2643
2644 var new_decl_arena = std.heap.ArenaAllocator.init(sema.gpa);
2645 errdefer new_decl_arena.deinit();
2646
2647 // Re-run the block that creates the function, with the comptime parameters
2648 // pre-populated inside `inst_map`. This causes `param_comptime` and
2649 // `param_anytype_comptime` ZIR instructions to be ignored, resulting in a
2650 // new, monomorphized function, with the comptime parameters elided.
2651 var child_sema: Sema = .{
2652 .mod = mod,
2653 .gpa = gpa,
2654 .arena = sema.arena,
2655 .code = fn_zir,
2656 .owner_decl = new_decl,
2657 .namespace = namespace,
2658 .func = null,
2659 .owner_func = null,
2660 .comptime_args = try new_decl_arena.allocator.alloc(TypedValue, uncasted_args.len),
2661 .comptime_args_fn_inst = module_fn.zir_body_inst,
2662 .preallocated_new_func = new_module_func,
2663 };
2664 defer child_sema.deinit();
2665
2666 var child_block: Scope.Block = .{
2667 .parent = null,
2668 .sema = &child_sema,
2669 .src_decl = new_decl,
2670 .instructions = .{},
2671 .inlining = null,
2672 .is_comptime = true,
2673 };
2674 defer {
2675 child_block.instructions.deinit(gpa);
2676 child_block.params.deinit(gpa);
2677 }
2678
2679 try child_sema.inst_map.ensureUnusedCapacity(gpa, @intCast(u32, uncasted_args.len));
2680 var arg_i: usize = 0;
2681 for (fn_info.param_body) |inst| {
2682 const is_comptime = switch (zir_tags[inst]) {
2683 .param_comptime, .param_anytype_comptime => true,
2684 .param, .param_anytype => false,
2685 else => continue,
2686 } or func_ty_info.paramIsComptime(arg_i);
2687 const arg_src = call_src; // TODO: better source location
2688 const arg = uncasted_args[arg_i];
2689 if (try sema.resolveMaybeUndefVal(block, arg_src, arg)) |arg_val| {
2690 const child_arg = try child_sema.addConstant(sema.typeOf(arg), arg_val);
2691 child_sema.inst_map.putAssumeCapacityNoClobber(inst, child_arg);
2692 } else if (is_comptime) {
2693 return sema.failWithNeededComptime(block, arg_src);
2621 {
2622 try namespace.anon_decls.ensureUnusedCapacity(gpa, 1);
2623
2624 // Create a Decl for the new function.
2625 const new_decl = try mod.allocateNewDecl(namespace, module_fn.owner_decl.src_node);
2626 // TODO better names for generic function instantiations
2627 const name_index = mod.getNextAnonNameIndex();
2628 new_decl.name = try std.fmt.allocPrintZ(gpa, "{s}__anon_{d}", .{
2629 module_fn.owner_decl.name, name_index,
2630 });
2631 new_decl.src_line = module_fn.owner_decl.src_line;
2632 new_decl.is_pub = module_fn.owner_decl.is_pub;
2633 new_decl.is_exported = module_fn.owner_decl.is_exported;
2634 new_decl.has_align = module_fn.owner_decl.has_align;
2635 new_decl.has_linksection = module_fn.owner_decl.has_linksection;
2636 new_decl.zir_decl_index = module_fn.owner_decl.zir_decl_index;
2637 new_decl.alive = true; // This Decl is called at runtime.
2638 new_decl.has_tv = true;
2639 new_decl.owns_tv = true;
2640 new_decl.analysis = .in_progress;
2641 new_decl.generation = mod.generation;
2642
2643 namespace.anon_decls.putAssumeCapacityNoClobber(new_decl, {});
2644
2645 var new_decl_arena = std.heap.ArenaAllocator.init(sema.gpa);
2646 errdefer new_decl_arena.deinit();
2647
2648 // Re-run the block that creates the function, with the comptime parameters
2649 // pre-populated inside `inst_map`. This causes `param_comptime` and
2650 // `param_anytype_comptime` ZIR instructions to be ignored, resulting in a
2651 // new, monomorphized function, with the comptime parameters elided.
2652 var child_sema: Sema = .{
2653 .mod = mod,
2654 .gpa = gpa,
2655 .arena = sema.arena,
2656 .code = fn_zir,
2657 .owner_decl = new_decl,
2658 .namespace = namespace,
2659 .func = null,
2660 .owner_func = null,
2661 .comptime_args = try new_decl_arena.allocator.alloc(TypedValue, uncasted_args.len),
2662 .comptime_args_fn_inst = module_fn.zir_body_inst,
2663 .preallocated_new_func = new_module_func,
2664 };
2665 defer child_sema.deinit();
2666
2667 var child_block: Scope.Block = .{
2668 .parent = null,
2669 .sema = &child_sema,
2670 .src_decl = new_decl,
2671 .instructions = .{},
2672 .inlining = null,
2673 .is_comptime = true,
2674 };
2675 defer {
2676 child_block.instructions.deinit(gpa);
2677 child_block.params.deinit(gpa);
26942678 }
2695 arg_i += 1;
2696 }
2697 const new_func_inst = try child_sema.resolveBody(&child_block, fn_info.param_body);
2698 const new_func_val = try child_sema.resolveConstValue(&child_block, .unneeded, new_func_inst);
2699 const new_func = new_func_val.castTag(.function).?.data;
2700 assert(new_func == new_module_func);
27012679
2702 arg_i = 0;
2703 for (fn_info.param_body) |inst| {
2704 switch (zir_tags[inst]) {
2705 .param_comptime, .param_anytype_comptime, .param, .param_anytype => {},
2706 else => continue,
2680 try child_sema.inst_map.ensureUnusedCapacity(gpa, @intCast(u32, uncasted_args.len));
2681 var arg_i: usize = 0;
2682 for (fn_info.param_body) |inst| {
2683 const is_comptime = switch (zir_tags[inst]) {
2684 .param_comptime, .param_anytype_comptime => true,
2685 .param, .param_anytype => false,
2686 else => continue,
2687 } or func_ty_info.paramIsComptime(arg_i);
2688 const arg_src = call_src; // TODO: better source location
2689 const arg = uncasted_args[arg_i];
2690 if (try sema.resolveMaybeUndefVal(block, arg_src, arg)) |arg_val| {
2691 const child_arg = try child_sema.addConstant(sema.typeOf(arg), arg_val);
2692 child_sema.inst_map.putAssumeCapacityNoClobber(inst, child_arg);
2693 } else if (is_comptime) {
2694 return sema.failWithNeededComptime(block, arg_src);
2695 }
2696 arg_i += 1;
27072697 }
2708 const arg = child_sema.inst_map.get(inst).?;
2709 const arg_val = (child_sema.resolveMaybeUndefValAllowVariables(&child_block, .unneeded, arg) catch unreachable).?;
2698 const new_func_inst = try child_sema.resolveBody(&child_block, fn_info.param_body);
2699 const new_func_val = try child_sema.resolveConstValue(&child_block, .unneeded, new_func_inst);
2700 const new_func = new_func_val.castTag(.function).?.data;
2701 assert(new_func == new_module_func);
2702
2703 arg_i = 0;
2704 for (fn_info.param_body) |inst| {
2705 switch (zir_tags[inst]) {
2706 .param_comptime, .param_anytype_comptime, .param, .param_anytype => {},
2707 else => continue,
2708 }
2709 const arg = child_sema.inst_map.get(inst).?;
2710 const arg_val = (child_sema.resolveMaybeUndefValAllowVariables(&child_block, .unneeded, arg) catch unreachable).?;
27102711
2711 if (arg_val.tag() == .generic_poison) {
2712 child_sema.comptime_args[arg_i] = .{
2713 .ty = Type.initTag(.noreturn),
2714 .val = Value.initTag(.unreachable_value),
2715 };
2716 } else {
2717 child_sema.comptime_args[arg_i] = .{
2718 .ty = try child_sema.typeOf(arg).copy(&new_decl_arena.allocator),
2719 .val = try arg_val.copy(&new_decl_arena.allocator),
2720 };
2712 if (arg_val.tag() == .generic_poison) {
2713 child_sema.comptime_args[arg_i] = .{
2714 .ty = Type.initTag(.noreturn),
2715 .val = Value.initTag(.unreachable_value),
2716 };
2717 } else {
2718 child_sema.comptime_args[arg_i] = .{
2719 .ty = try child_sema.typeOf(arg).copy(&new_decl_arena.allocator),
2720 .val = try arg_val.copy(&new_decl_arena.allocator),
2721 };
2722 }
2723
2724 arg_i += 1;
27212725 }
27222726
2723 arg_i += 1;
2724 }
2727 // Populate the Decl ty/val with the function and its type.
2728 new_decl.ty = try child_sema.typeOf(new_func_inst).copy(&new_decl_arena.allocator);
2729 new_decl.val = try Value.Tag.function.create(&new_decl_arena.allocator, new_func);
2730 new_decl.analysis = .complete;
27252731
2726 // Populate the Decl ty/val with the function and its type.
2727 new_decl.ty = try child_sema.typeOf(new_func_inst).copy(&new_decl_arena.allocator);
2728 new_decl.val = try Value.Tag.function.create(&new_decl_arena.allocator, new_func);
2729 new_decl.analysis = .complete;
2732 // The generic function Decl is guaranteed to be the first dependency
2733 // of each of its instantiations.
2734 assert(new_decl.dependencies.keys().len == 0);
2735 try mod.declareDeclDependency(new_decl, module_fn.owner_decl);
27302736
2731 // Queue up a `codegen_func` work item for the new Fn. The `comptime_args` field
2732 // will be populated, ensuring it will have `analyzeBody` called with the ZIR
2733 // parameters mapped appropriately.
2734 try mod.comp.bin_file.allocateDeclIndexes(new_decl);
2735 try mod.comp.work_queue.writeItem(.{ .codegen_func = new_func });
2737 // Queue up a `codegen_func` work item for the new Fn. The `comptime_args` field
2738 // will be populated, ensuring it will have `analyzeBody` called with the ZIR
2739 // parameters mapped appropriately.
2740 try mod.comp.bin_file.allocateDeclIndexes(new_decl);
2741 try mod.comp.work_queue.writeItem(.{ .codegen_func = new_func });
27362742
2737 try new_decl.finalizeNewArena(&new_decl_arena);
2738
2739 // The generic function Decl is guaranteed to be the first dependency
2740 // of each of its instantiations.
2741 assert(new_decl.dependencies.keys().len == 0);
2742 try mod.declareDeclDependency(new_decl, module_fn.owner_decl);
2743 try new_decl.finalizeNewArena(&new_decl_arena);
2744 }
27432745
27442746 break :res try sema.finishGenericCall(
27452747 block,
......@@ -3478,12 +3480,15 @@ fn zirFunc(
34783480
34793481 const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
34803482 const extra = sema.code.extraData(Zir.Inst.Func, inst_data.payload_index);
3483 var extra_index = extra.end;
3484 const ret_ty_body = sema.code.extra[extra_index..][0..extra.data.ret_body_len];
3485 extra_index += ret_ty_body.len;
34813486
34823487 var body_inst: Zir.Inst.Index = 0;
34833488 var src_locs: Zir.Inst.Func.SrcLocs = undefined;
34843489 if (extra.data.body_len != 0) {
34853490 body_inst = inst;
3486 const extra_index = extra.end + extra.data.body_len;
3491 extra_index += extra.data.body_len;
34873492 src_locs = sema.code.extraData(Zir.Inst.Func.SrcLocs, extra_index).data;
34883493 }
34893494
......@@ -3496,7 +3501,7 @@ fn zirFunc(
34963501 block,
34973502 inst_data.src_node,
34983503 body_inst,
3499 extra.data.return_type,
3504 ret_ty_body,
35003505 cc,
35013506 Value.initTag(.null_value),
35023507 false,
......@@ -3512,7 +3517,7 @@ fn funcCommon(
35123517 block: *Scope.Block,
35133518 src_node_offset: i32,
35143519 body_inst: Zir.Inst.Index,
3515 zir_return_type: Zir.Inst.Ref,
3520 ret_ty_body: []const Zir.Inst.Index,
35163521 cc: std.builtin.CallingConvention,
35173522 align_val: Value,
35183523 var_args: bool,
......@@ -3523,7 +3528,37 @@ fn funcCommon(
35233528) CompileError!Air.Inst.Ref {
35243529 const src: LazySrcLoc = .{ .node_offset = src_node_offset };
35253530 const ret_ty_src: LazySrcLoc = .{ .node_offset_fn_type_ret_ty = src_node_offset };
3526 const bare_return_type = try sema.resolveType(block, ret_ty_src, zir_return_type);
3531
3532 // The return type body might be a type expression that depends on generic parameters.
3533 // In such case we need to use a generic_poison value for the return type and mark
3534 // the function as generic.
3535 var is_generic = false;
3536 const bare_return_type: Type = ret_ty: {
3537 if (ret_ty_body.len == 0) break :ret_ty Type.initTag(.void);
3538
3539 const err = err: {
3540 // Make sure any nested param instructions don't clobber our work.
3541 const prev_params = block.params;
3542 block.params = .{};
3543 defer {
3544 block.params.deinit(sema.gpa);
3545 block.params = prev_params;
3546 }
3547 if (sema.resolveBody(block, ret_ty_body)) |ret_ty_inst| {
3548 if (sema.analyzeAsType(block, ret_ty_src, ret_ty_inst)) |ret_ty| {
3549 break :ret_ty ret_ty;
3550 } else |err| break :err err;
3551 } else |err| break :err err;
3552 };
3553 switch (err) {
3554 error.GenericPoison => {
3555 // The type is not available until the generic instantiation.
3556 is_generic = true;
3557 break :ret_ty Type.initTag(.generic_poison);
3558 },
3559 else => |e| return e,
3560 }
3561 };
35273562
35283563 const mod = sema.mod;
35293564
......@@ -3540,8 +3575,9 @@ fn funcCommon(
35403575
35413576 const fn_ty: Type = fn_ty: {
35423577 // Hot path for some common function types.
3543 if (block.params.items.len == 0 and !var_args and align_val.tag() == .null_value and
3544 !inferred_error_set)
3578 // TODO can we eliminate some of these Type tag values? seems unnecessarily complicated.
3579 if (!is_generic and block.params.items.len == 0 and !var_args and
3580 align_val.tag() == .null_value and !inferred_error_set)
35453581 {
35463582 if (bare_return_type.zigTypeTag() == .NoReturn and cc == .Unspecified) {
35473583 break :fn_ty Type.initTag(.fn_noreturn_no_args);
......@@ -3560,7 +3596,6 @@ fn funcCommon(
35603596 }
35613597 }
35623598
3563 var is_generic = false;
35643599 const param_types = try sema.arena.alloc(Type, block.params.items.len);
35653600 const comptime_params = try sema.arena.alloc(bool, block.params.items.len);
35663601 for (block.params.items) |param, i| {
......@@ -3574,7 +3609,9 @@ fn funcCommon(
35743609 return mod.fail(&block.base, src, "TODO implement support for function prototypes to have alignment specified", .{});
35753610 }
35763611
3577 const return_type = if (!inferred_error_set) bare_return_type else blk: {
3612 const return_type = if (!inferred_error_set or bare_return_type.tag() == .generic_poison)
3613 bare_return_type
3614 else blk: {
35783615 const error_set_ty = try Type.Tag.error_set_inferred.create(sema.arena, .{
35793616 .func = new_func,
35803617 .map = .{},
......@@ -6944,6 +6981,9 @@ fn zirFuncExtended(
69446981 break :blk align_tv.val;
69456982 } else Value.initTag(.null_value);
69466983
6984 const ret_ty_body = sema.code.extra[extra_index..][0..extra.data.ret_body_len];
6985 extra_index += ret_ty_body.len;
6986
69476987 var body_inst: Zir.Inst.Index = 0;
69486988 var src_locs: Zir.Inst.Func.SrcLocs = undefined;
69496989 if (extra.data.body_len != 0) {
......@@ -6960,7 +7000,7 @@ fn zirFuncExtended(
69607000 block,
69617001 extra.data.src_node,
69627002 body_inst,
6963 extra.data.return_type,
7003 ret_ty_body,
69647004 cc,
69657005 align_val,
69667006 is_var_args,
src/Zir.zig+49-15
......@@ -2272,11 +2272,13 @@ pub const Inst = struct {
22722272 /// 0. lib_name: u32, // null terminated string index, if has_lib_name is set
22732273 /// 1. cc: Ref, // if has_cc is set
22742274 /// 2. align: Ref, // if has_align is set
2275 /// 3. body: Index // for each body_len
2276 /// 4. src_locs: Func.SrcLocs // if body_len != 0
2275 /// 3. return_type: Index // for each ret_body_len
2276 /// 4. body: Index // for each body_len
2277 /// 5. src_locs: Func.SrcLocs // if body_len != 0
22772278 pub const ExtendedFunc = struct {
22782279 src_node: i32,
2279 return_type: Ref,
2280 /// If this is 0 it means a void return type.
2281 ret_body_len: u32,
22802282 /// Points to the block that contains the param instructions for this function.
22812283 param_block: Index,
22822284 body_len: u32,
......@@ -2312,10 +2314,12 @@ pub const Inst = struct {
23122314 };
23132315
23142316 /// Trailing:
2315 /// 0. body: Index // for each body_len
2316 /// 1. src_locs: SrcLocs // if body_len != 0
2317 /// 0. return_type: Index // for each ret_body_len
2318 /// 1. body: Index // for each body_len
2319 /// 2. src_locs: SrcLocs // if body_len != 0
23172320 pub const Func = struct {
2318 return_type: Ref,
2321 /// If this is 0 it means a void return type.
2322 ret_body_len: u32,
23192323 /// Points to the block that contains the param instructions for this function.
23202324 param_block: Index,
23212325 body_len: u32,
......@@ -4344,15 +4348,21 @@ const Writer = struct {
43444348 const inst_data = self.code.instructions.items(.data)[inst].pl_node;
43454349 const src = inst_data.src();
43464350 const extra = self.code.extraData(Inst.Func, inst_data.payload_index);
4347 const body = self.code.extra[extra.end..][0..extra.data.body_len];
4351 var extra_index = extra.end;
4352
4353 const ret_ty_body = self.code.extra[extra_index..][0..extra.data.ret_body_len];
4354 extra_index += ret_ty_body.len;
4355
4356 const body = self.code.extra[extra_index..][0..extra.data.body_len];
4357 extra_index += body.len;
4358
43484359 var src_locs: Zir.Inst.Func.SrcLocs = undefined;
43494360 if (body.len != 0) {
4350 const extra_index = extra.end + body.len;
43514361 src_locs = self.code.extraData(Zir.Inst.Func.SrcLocs, extra_index).data;
43524362 }
43534363 return self.writeFuncCommon(
43544364 stream,
4355 extra.data.return_type,
4365 ret_ty_body,
43564366 inferred_error_set,
43574367 false,
43584368 false,
......@@ -4387,6 +4397,9 @@ const Writer = struct {
43874397 break :blk align_inst;
43884398 };
43894399
4400 const ret_ty_body = self.code.extra[extra_index..][0..extra.data.ret_body_len];
4401 extra_index += ret_ty_body.len;
4402
43904403 const body = self.code.extra[extra_index..][0..extra.data.body_len];
43914404 extra_index += body.len;
43924405
......@@ -4396,7 +4409,7 @@ const Writer = struct {
43964409 }
43974410 return self.writeFuncCommon(
43984411 stream,
4399 extra.data.return_type,
4412 ret_ty_body,
44004413 small.is_inferred_error,
44014414 small.is_var_args,
44024415 small.is_extern,
......@@ -4478,7 +4491,7 @@ const Writer = struct {
44784491 fn writeFuncCommon(
44794492 self: *Writer,
44804493 stream: anytype,
4481 ret_ty: Inst.Ref,
4494 ret_ty_body: []const Inst.Index,
44824495 inferred_error_set: bool,
44834496 var_args: bool,
44844497 is_extern: bool,
......@@ -4488,7 +4501,13 @@ const Writer = struct {
44884501 src: LazySrcLoc,
44894502 src_locs: Zir.Inst.Func.SrcLocs,
44904503 ) !void {
4491 try self.writeInstRef(stream, ret_ty);
4504 try stream.writeAll("ret_ty={\n");
4505 self.indent += 2;
4506 try self.writeBody(stream, ret_ty_body);
4507 self.indent -= 2;
4508 try stream.writeByteNTimes(' ', self.indent);
4509 try stream.writeAll("}");
4510
44924511 try self.writeOptionalInstRef(stream, ", cc=", cc);
44934512 try self.writeOptionalInstRef(stream, ", align=", align_inst);
44944513 try self.writeFlag(stream, ", vargs", var_args);
......@@ -4496,9 +4515,9 @@ const Writer = struct {
44964515 try self.writeFlag(stream, ", inferror", inferred_error_set);
44974516
44984517 if (body.len == 0) {
4499 try stream.writeAll(", {}) ");
4518 try stream.writeAll(", body={}) ");
45004519 } else {
4501 try stream.writeAll(", {\n");
4520 try stream.writeAll(", body={\n");
45024521 self.indent += 2;
45034522 try self.writeBody(stream, body);
45044523 self.indent -= 2;
......@@ -4932,6 +4951,7 @@ fn findDeclsBody(
49324951
49334952pub const FnInfo = struct {
49344953 param_body: []const Inst.Index,
4954 ret_ty_body: []const Inst.Index,
49354955 body: []const Inst.Index,
49364956 total_params_len: u32,
49374957};
......@@ -4942,13 +4962,22 @@ pub fn getFnInfo(zir: Zir, fn_inst: Inst.Index) FnInfo {
49424962 const info: struct {
49434963 param_block: Inst.Index,
49444964 body: []const Inst.Index,
4965 ret_ty_body: []const Inst.Index,
49454966 } = switch (tags[fn_inst]) {
49464967 .func, .func_inferred => blk: {
49474968 const inst_data = datas[fn_inst].pl_node;
49484969 const extra = zir.extraData(Inst.Func, inst_data.payload_index);
4949 const body = zir.extra[extra.end..][0..extra.data.body_len];
4970 var extra_index: usize = extra.end;
4971
4972 const ret_ty_body = zir.extra[extra_index..][0..extra.data.ret_body_len];
4973 extra_index += ret_ty_body.len;
4974
4975 const body = zir.extra[extra_index..][0..extra.data.body_len];
4976 extra_index += body.len;
4977
49504978 break :blk .{
49514979 .param_block = extra.data.param_block,
4980 .ret_ty_body = ret_ty_body,
49524981 .body = body,
49534982 };
49544983 },
......@@ -4961,9 +4990,13 @@ pub fn getFnInfo(zir: Zir, fn_inst: Inst.Index) FnInfo {
49614990 extra_index += @boolToInt(small.has_lib_name);
49624991 extra_index += @boolToInt(small.has_cc);
49634992 extra_index += @boolToInt(small.has_align);
4993 const ret_ty_body = zir.extra[extra_index..][0..extra.data.ret_body_len];
4994 extra_index += ret_ty_body.len;
49644995 const body = zir.extra[extra_index..][0..extra.data.body_len];
4996 extra_index += body.len;
49654997 break :blk .{
49664998 .param_block = extra.data.param_block,
4999 .ret_ty_body = ret_ty_body,
49675000 .body = body,
49685001 };
49695002 },
......@@ -4983,6 +5016,7 @@ pub fn getFnInfo(zir: Zir, fn_inst: Inst.Index) FnInfo {
49835016 }
49845017 return .{
49855018 .param_body = param_body,
5019 .ret_ty_body = info.ret_ty_body,
49865020 .body = info.body,
49875021 .total_params_len = total_params_len,
49885022 };
src/codegen/llvm.zig+15-1
......@@ -575,6 +575,14 @@ pub const DeclGen = struct {
575575 const info = t.intInfo(self.module.getTarget());
576576 return self.context.intType(info.bits);
577577 },
578 .Float => switch (t.floatBits(self.module.getTarget())) {
579 16 => return self.context.halfType(),
580 32 => return self.context.floatType(),
581 64 => return self.context.doubleType(),
582 80 => return self.context.x86FP80Type(),
583 128 => return self.context.fp128Type(),
584 else => unreachable,
585 },
578586 .Bool => return self.context.intType(1),
579587 .Pointer => {
580588 if (t.isSlice()) {
......@@ -661,7 +669,6 @@ pub const DeclGen = struct {
661669
662670 .BoundFn => @panic("TODO remove BoundFn from the language"),
663671
664 .Float,
665672 .Enum,
666673 .Union,
667674 .Opaque,
......@@ -699,6 +706,13 @@ pub const DeclGen = struct {
699706 }
700707 return llvm_int;
701708 },
709 .Float => {
710 if (tv.ty.floatBits(self.module.getTarget()) <= 64) {
711 const llvm_ty = try self.llvmType(tv.ty);
712 return llvm_ty.constReal(tv.val.toFloat(f64));
713 }
714 return self.todo("bitcast to f128 from an integer", .{});
715 },
702716 .Pointer => switch (tv.val.tag()) {
703717 .decl_ref => {
704718 if (tv.ty.isSlice()) {
src/codegen/llvm/bindings.zig+18
......@@ -31,6 +31,21 @@ pub const Context = opaque {
3131 pub const intType = LLVMIntTypeInContext;
3232 extern fn LLVMIntTypeInContext(C: *const Context, NumBits: c_uint) *const Type;
3333
34 pub const halfType = LLVMHalfTypeInContext;
35 extern fn LLVMHalfTypeInContext(C: *const Context) *const Type;
36
37 pub const floatType = LLVMFloatTypeInContext;
38 extern fn LLVMFloatTypeInContext(C: *const Context) *const Type;
39
40 pub const doubleType = LLVMDoubleTypeInContext;
41 extern fn LLVMDoubleTypeInContext(C: *const Context) *const Type;
42
43 pub const x86FP80Type = LLVMX86FP80TypeInContext;
44 extern fn LLVMX86FP80TypeInContext(C: *const Context) *const Type;
45
46 pub const fp128Type = LLVMFP128TypeInContext;
47 extern fn LLVMFP128TypeInContext(C: *const Context) *const Type;
48
3449 pub const voidType = LLVMVoidTypeInContext;
3550 extern fn LLVMVoidTypeInContext(C: *const Context) *const Type;
3651
......@@ -127,6 +142,9 @@ pub const Type = opaque {
127142 pub const constInt = LLVMConstInt;
128143 extern fn LLVMConstInt(IntTy: *const Type, N: c_ulonglong, SignExtend: Bool) *const Value;
129144
145 pub const constReal = LLVMConstReal;
146 extern fn LLVMConstReal(RealTy: *const Type, N: f64) *const Value;
147
130148 pub const constArray = LLVMConstArray;
131149 extern fn LLVMConstArray(ElementTy: *const Type, ConstantVals: [*]*const Value, Length: c_uint) *const Value;
132150
src/print_air.zig+1-1
......@@ -222,7 +222,7 @@ const Writer = struct {
222222 const extra = w.air.extraData(Air.Block, ty_pl.payload);
223223 const body = w.air.extra[extra.end..][0..extra.data.body_len];
224224
225 try s.writeAll("{\n");
225 try s.print("{}, {{\n", .{w.air.getRefType(ty_pl.ty)});
226226 const old_indent = w.indent;
227227 w.indent += 2;
228228 try w.writeBody(s, body);
test/behavior/generics.zig+56
......@@ -1,4 +1,5 @@
11const std = @import("std");
2const builtin = @import("builtin");
23const testing = std.testing;
34const expect = testing.expect;
45const expectEqual = testing.expectEqual;
......@@ -14,3 +15,58 @@ test "one param, explicit comptime" {
1415fn checkSize(comptime T: type) usize {
1516 return @sizeOf(T);
1617}
18
19test "simple generic fn" {
20 try expect(max(i32, 3, -1) == 3);
21 try expect(max(u8, 1, 100) == 100);
22 if (!builtin.zig_is_stage2) {
23 // TODO: stage2 is incorrectly emitting the following:
24 // error: cast of value 1.23e-01 to type 'f32' loses information
25 try expect(max(f32, 0.123, 0.456) == 0.456);
26 }
27 try expect(add(2, 3) == 5);
28}
29
30fn max(comptime T: type, a: T, b: T) T {
31 if (!builtin.zig_is_stage2) {
32 // TODO: stage2 is incorrectly emitting AIR that allocates a result
33 // value, stores to it, but then returns void instead of the result.
34 return if (a > b) a else b;
35 }
36 if (a > b) {
37 return a;
38 } else {
39 return b;
40 }
41}
42
43fn add(comptime a: i32, b: i32) i32 {
44 return (comptime a) + b;
45}
46
47const the_max = max(u32, 1234, 5678);
48test "compile time generic eval" {
49 try expect(the_max == 5678);
50}
51
52fn gimmeTheBigOne(a: u32, b: u32) u32 {
53 return max(u32, a, b);
54}
55
56fn shouldCallSameInstance(a: u32, b: u32) u32 {
57 return max(u32, a, b);
58}
59
60fn sameButWithFloats(a: f64, b: f64) f64 {
61 return max(f64, a, b);
62}
63
64test "fn with comptime args" {
65 try expect(gimmeTheBigOne(1234, 5678) == 5678);
66 try expect(shouldCallSameInstance(34, 12) == 34);
67 if (!builtin.zig_is_stage2) {
68 // TODO: stage2 llvm backend needs to use fcmp instead of icmp
69 // probably AIR should just have different instructions for floats.
70 try expect(sameButWithFloats(0.43, 0.49) == 0.49);
71 }
72}
test/behavior/generics_stage1.zig+1-38
......@@ -3,44 +3,7 @@ const testing = std.testing;
33const expect = testing.expect;
44const expectEqual = testing.expectEqual;
55
6test "simple generic fn" {
7 try expect(max(i32, 3, -1) == 3);
8 try expect(max(f32, 0.123, 0.456) == 0.456);
9 try expect(add(2, 3) == 5);
10}
11
12fn max(comptime T: type, a: T, b: T) T {
13 return if (a > b) a else b;
14}
15
16fn add(comptime a: i32, b: i32) i32 {
17 return (comptime a) + b;
18}
19
20const the_max = max(u32, 1234, 5678);
21test "compile time generic eval" {
22 try expect(the_max == 5678);
23}
24
25fn gimmeTheBigOne(a: u32, b: u32) u32 {
26 return max(u32, a, b);
27}
28
29fn shouldCallSameInstance(a: u32, b: u32) u32 {
30 return max(u32, a, b);
31}
32
33fn sameButWithFloats(a: f64, b: f64) f64 {
34 return max(f64, a, b);
35}
36
37test "fn with comptime args" {
38 try expect(gimmeTheBigOne(1234, 5678) == 5678);
39 try expect(shouldCallSameInstance(34, 12) == 34);
40 try expect(sameButWithFloats(0.43, 0.49) == 0.49);
41}
42
43test "var params" {
6test "anytype params" {
447 try expect(max_i32(12, 34) == 34);
458 try expect(max_f64(1.2, 3.4) == 3.4);
469}