authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2021-07-30 01:40:32-04:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2021-07-30 01:40:32-04:00
loge5e6ceda6a98cc89e63abb62beb8557ff9f3109e
tree4f099cece2f5dc1721b2843218b4cb072783fb6c
parent192b5d24cb4651ed2c6b6b1e5fee017d40ea5aa5
parent040c6eaaa03bbcfcdeadbe835c1c2f209e9f401e
signaturebadge-question-mark Signed by PGP key 4AEE18F83AFDEB23

Merge pull request #9486 from ziglang/comptime-pointers

stage2: more principled approach to comptime pointers and garbage collection of unused anon decls

16 files changed, 443 insertions(+), 380 deletions(-)

src/Air.zig-14
......@@ -15,7 +15,6 @@ instructions: std.MultiArrayList(Inst).Slice,
1515/// The first few indexes are reserved. See `ExtraIndex` for the values.
1616extra: []const u32,
1717values: []const Value,
18variables: []const *Module.Var,
1918
2019pub const ExtraIndex = enum(u32) {
2120 /// Payload index of the main `Block` in the `extra` array.
......@@ -193,20 +192,10 @@ pub const Inst = struct {
193192 /// Result type is always `u1`.
194193 /// Uses the `un_op` field.
195194 bool_to_int,
196 /// Stores a value onto the stack and returns a pointer to it.
197 /// TODO audit where this AIR instruction is emitted, maybe it should instead be emitting
198 /// alloca instruction and storing to the alloca.
199 /// Uses the `ty_op` field.
200 ref,
201195 /// Return a value from a function.
202196 /// Result type is always noreturn; no instructions in a block follow this one.
203197 /// Uses the `un_op` field.
204198 ret,
205 /// Returns a pointer to a global variable.
206 /// Uses the `ty_pl` field. Index is into the `variables` array.
207 /// TODO this can be modeled simply as a constant with a decl ref and then
208 /// the variables array can be removed from Air.
209 varptr,
210199 /// Write a value to a pointer. LHS is pointer, RHS is value.
211200 /// Result type is always void.
212201 /// Uses the `bin_op` field.
......@@ -454,7 +443,6 @@ pub fn typeOfIndex(air: Air, inst: Air.Inst.Index) Type {
454443 .assembly,
455444 .block,
456445 .constant,
457 .varptr,
458446 .struct_field_ptr,
459447 .struct_field_val,
460448 => return air.getRefType(datas[inst].ty_pl.ty),
......@@ -462,7 +450,6 @@ pub fn typeOfIndex(air: Air, inst: Air.Inst.Index) Type {
462450 .not,
463451 .bitcast,
464452 .load,
465 .ref,
466453 .floatcast,
467454 .intcast,
468455 .optional_payload,
......@@ -550,7 +537,6 @@ pub fn deinit(air: *Air, gpa: *std.mem.Allocator) void {
550537 air.instructions.deinit(gpa);
551538 gpa.free(air.extra);
552539 gpa.free(air.values);
553 gpa.free(air.variables);
554540 air.* = undefined;
555541}
556542
src/Compilation.zig+9-1
......@@ -2061,11 +2061,19 @@ pub fn performAllTheWork(self: *Compilation) error{ TimerUnsupported, OutOfMemor
20612061 .complete, .codegen_failure_retryable => {
20622062 if (build_options.omit_stage2)
20632063 @panic("sadly stage2 is omitted from this build to save memory on the CI server");
2064
20642065 const module = self.bin_file.options.module.?;
20652066 assert(decl.has_tv);
20662067 assert(decl.ty.hasCodeGenBits());
20672068
2068 try module.linkerUpdateDecl(decl);
2069 if (decl.alive) {
2070 try module.linkerUpdateDecl(decl);
2071 continue;
2072 }
2073
2074 // Instead of sending this decl to the linker, we actually will delete it
2075 // because we found out that it in fact was never referenced.
2076 module.deleteUnusedDecl(decl);
20692077 },
20702078 },
20712079 .codegen_func => |func| switch (func.owner_decl.analysis) {
src/Liveness.zig-2
......@@ -256,14 +256,12 @@ fn analyzeInst(
256256 .const_ty,
257257 .breakpoint,
258258 .dbg_stmt,
259 .varptr,
260259 .unreach,
261260 => return trackOperands(a, new_set, inst, main_tomb, .{ .none, .none, .none }),
262261
263262 .not,
264263 .bitcast,
265264 .load,
266 .ref,
267265 .floatcast,
268266 .intcast,
269267 .optional_payload,
src/Module.zig+97-10
......@@ -255,6 +255,15 @@ pub const Decl = struct {
255255 has_align: bool,
256256 /// Whether the ZIR code provides a linksection instruction.
257257 has_linksection: bool,
258 /// Flag used by garbage collection to mark and sweep.
259 /// Decls which correspond to an AST node always have this field set to `true`.
260 /// Anonymous Decls are initialized with this field set to `false` and then it
261 /// is the responsibility of machine code backends to mark it `true` whenever
262 /// a `decl_ref` Value is encountered that points to this Decl.
263 /// When the `codegen_decl` job is encountered in the main work queue, if the
264 /// Decl is marked alive, then it sends the Decl to the linker. Otherwise it
265 /// deletes the Decl on the spot.
266 alive: bool,
258267
259268 /// Represents the position of the code in the output file.
260269 /// This is populated regardless of semantic analysis and code generation.
......@@ -1324,6 +1333,42 @@ pub const Scope = struct {
13241333 block.instructions.appendAssumeCapacity(result_index);
13251334 return result_index;
13261335 }
1336
1337 pub fn startAnonDecl(block: *Block) !WipAnonDecl {
1338 return WipAnonDecl{
1339 .block = block,
1340 .new_decl_arena = std.heap.ArenaAllocator.init(block.sema.gpa),
1341 .finished = false,
1342 };
1343 }
1344
1345 pub const WipAnonDecl = struct {
1346 block: *Scope.Block,
1347 new_decl_arena: std.heap.ArenaAllocator,
1348 finished: bool,
1349
1350 pub fn arena(wad: *WipAnonDecl) *Allocator {
1351 return &wad.new_decl_arena.allocator;
1352 }
1353
1354 pub fn deinit(wad: *WipAnonDecl) void {
1355 if (!wad.finished) {
1356 wad.new_decl_arena.deinit();
1357 }
1358 wad.* = undefined;
1359 }
1360
1361 pub fn finish(wad: *WipAnonDecl, ty: Type, val: Value) !*Decl {
1362 const new_decl = try wad.block.sema.mod.createAnonymousDecl(&wad.block.base, .{
1363 .ty = ty,
1364 .val = val,
1365 });
1366 errdefer wad.block.sema.mod.deleteAnonDecl(&wad.block.base, new_decl);
1367 try new_decl.finalizeNewArena(&wad.new_decl_arena);
1368 wad.finished = true;
1369 return new_decl;
1370 }
1371 };
13271372 };
13281373};
13291374
......@@ -1700,6 +1745,7 @@ pub const SrcLoc = struct {
17001745
17011746 .node_offset_fn_type_cc => |node_off| {
17021747 const tree = try src_loc.file_scope.getTree(gpa);
1748 const node_datas = tree.nodes.items(.data);
17031749 const node_tags = tree.nodes.items(.tag);
17041750 const node = src_loc.declRelativeToNodeIndex(node_off);
17051751 var params: [1]ast.Node.Index = undefined;
......@@ -1708,6 +1754,13 @@ pub const SrcLoc = struct {
17081754 .fn_proto_multi => tree.fnProtoMulti(node),
17091755 .fn_proto_one => tree.fnProtoOne(&params, node),
17101756 .fn_proto => tree.fnProto(node),
1757 .fn_decl => switch (node_tags[node_datas[node].lhs]) {
1758 .fn_proto_simple => tree.fnProtoSimple(&params, node_datas[node].lhs),
1759 .fn_proto_multi => tree.fnProtoMulti(node_datas[node].lhs),
1760 .fn_proto_one => tree.fnProtoOne(&params, node_datas[node].lhs),
1761 .fn_proto => tree.fnProto(node_datas[node].lhs),
1762 else => unreachable,
1763 },
17111764 else => unreachable,
17121765 };
17131766 const main_tokens = tree.nodes.items(.main_token);
......@@ -2825,6 +2878,7 @@ pub fn semaFile(mod: *Module, file: *Scope.File) SemaError!void {
28252878 new_decl.val = struct_val;
28262879 new_decl.has_tv = true;
28272880 new_decl.owns_tv = true;
2881 new_decl.alive = true; // This Decl corresponds to a File and is therefore always alive.
28282882 new_decl.analysis = .in_progress;
28292883 new_decl.generation = mod.generation;
28302884
......@@ -2935,7 +2989,7 @@ fn semaDecl(mod: *Module, decl: *Decl) !bool {
29352989 const break_index = try sema.analyzeBody(&block_scope, body);
29362990 const result_ref = zir_datas[break_index].@"break".operand;
29372991 const src: LazySrcLoc = .{ .node_offset = 0 };
2938 const decl_tv = try sema.resolveInstConst(&block_scope, src, result_ref);
2992 const decl_tv = try sema.resolveInstValue(&block_scope, src, result_ref);
29392993 const align_val = blk: {
29402994 const align_ref = decl.zirAlignRef();
29412995 if (align_ref == .none) break :blk Value.initTag(.null_value);
......@@ -2946,6 +3000,7 @@ fn semaDecl(mod: *Module, decl: *Decl) !bool {
29463000 if (linksection_ref == .none) break :blk Value.initTag(.null_value);
29473001 break :blk (try sema.resolveInstConst(&block_scope, src, linksection_ref)).val;
29483002 };
3003 try sema.resolveTypeLayout(&block_scope, src, decl_tv.ty);
29493004
29503005 // We need the memory for the Type to go into the arena for the Decl
29513006 var decl_arena = std.heap.ArenaAllocator.init(gpa);
......@@ -2983,8 +3038,8 @@ fn semaDecl(mod: *Module, decl: *Decl) !bool {
29833038 const is_inline = decl_tv.ty.fnCallingConvention() == .Inline;
29843039 if (!is_inline and decl_tv.ty.hasCodeGenBits()) {
29853040 // We don't fully codegen the decl until later, but we do need to reserve a global
2986 // offset table index for it. This allows us to codegen decls out of dependency order,
2987 // increasing how many computations can be done in parallel.
3041 // offset table index for it. This allows us to codegen decls out of dependency
3042 // order, increasing how many computations can be done in parallel.
29883043 try mod.comp.bin_file.allocateDeclIndexes(decl);
29893044 try mod.comp.work_queue.writeItem(.{ .codegen_func = func });
29903045 if (type_changed and mod.emit_h != null) {
......@@ -3343,6 +3398,7 @@ fn scanDecl(iter: *ScanDeclIter, decl_sub_index: usize, flags: u4) SemaError!voi
33433398 new_decl.has_align = has_align;
33443399 new_decl.has_linksection = has_linksection;
33453400 new_decl.zir_decl_index = @intCast(u32, decl_sub_index);
3401 new_decl.alive = true; // This Decl corresponds to an AST node and therefore always alive.
33463402 return;
33473403 }
33483404 gpa.free(decl_name);
......@@ -3482,6 +3538,43 @@ pub fn clearDecl(
34823538 decl.analysis = .unreferenced;
34833539}
34843540
3541pub fn deleteUnusedDecl(mod: *Module, decl: *Decl) void {
3542 log.debug("deleteUnusedDecl {*} ({s})", .{ decl, decl.name });
3543
3544 // TODO: remove `allocateDeclIndexes` and make the API that the linker backends
3545 // are required to notice the first time `updateDecl` happens and keep track
3546 // of it themselves. However they can rely on getting a `freeDecl` call if any
3547 // `updateDecl` or `updateFunc` calls happen. This will allow us to avoid any call
3548 // into the linker backend here, since the linker backend will never have been told
3549 // about the Decl in the first place.
3550 // Until then, we did call `allocateDeclIndexes` on this anonymous Decl and so we
3551 // must call `freeDecl` in the linker backend now.
3552 if (decl.has_tv) {
3553 if (decl.ty.hasCodeGenBits()) {
3554 mod.comp.bin_file.freeDecl(decl);
3555 }
3556 }
3557
3558 const dependants = decl.dependants.keys();
3559 assert(dependants[0].namespace.anon_decls.swapRemove(decl));
3560
3561 for (dependants) |dep| {
3562 dep.removeDependency(decl);
3563 }
3564
3565 for (decl.dependencies.keys()) |dep| {
3566 dep.removeDependant(decl);
3567 }
3568 decl.destroy(mod);
3569}
3570
3571pub fn deleteAnonDecl(mod: *Module, scope: *Scope, decl: *Decl) void {
3572 log.debug("deleteAnonDecl {*} ({s})", .{ decl, decl.name });
3573 const scope_decl = scope.ownerDecl().?;
3574 assert(scope_decl.namespace.anon_decls.swapRemove(decl));
3575 decl.destroy(mod);
3576}
3577
34853578/// Delete all the Export objects that are caused by this Decl. Re-analysis of
34863579/// this Decl will cause them to be re-created (or not).
34873580fn deleteDeclExports(mod: *Module, decl: *Decl) void {
......@@ -3603,7 +3696,6 @@ pub fn analyzeFnBody(mod: *Module, decl: *Decl, func: *Fn) SemaError!Air {
36033696 .instructions = sema.air_instructions.toOwnedSlice(),
36043697 .extra = sema.air_extra.toOwnedSlice(gpa),
36053698 .values = sema.air_values.toOwnedSlice(gpa),
3606 .variables = sema.air_variables.toOwnedSlice(gpa),
36073699 };
36083700}
36093701
......@@ -3670,6 +3762,7 @@ fn allocateNewDecl(mod: *Module, namespace: *Scope.Namespace, src_node: ast.Node
36703762 .is_exported = false,
36713763 .has_linksection = false,
36723764 .has_align = false,
3765 .alive = false,
36733766 };
36743767 return new_decl;
36753768}
......@@ -3759,12 +3852,6 @@ pub fn analyzeExport(
37593852 errdefer de_gop.value_ptr.* = mod.gpa.shrink(de_gop.value_ptr.*, de_gop.value_ptr.len - 1);
37603853}
37613854
3762pub fn deleteAnonDecl(mod: *Module, scope: *Scope, decl: *Decl) void {
3763 const scope_decl = scope.ownerDecl().?;
3764 assert(scope_decl.namespace.anon_decls.swapRemove(decl));
3765 decl.destroy(mod);
3766}
3767
37683855/// Takes ownership of `name` even if it returns an error.
37693856pub fn createAnonymousDeclNamed(
37703857 mod: *Module,
src/Sema.zig+179-104
......@@ -14,7 +14,6 @@ code: Zir,
1414air_instructions: std.MultiArrayList(Air.Inst) = .{},
1515air_extra: std.ArrayListUnmanaged(u32) = .{},
1616air_values: std.ArrayListUnmanaged(Value) = .{},
17air_variables: std.ArrayListUnmanaged(*Module.Var) = .{},
1817/// Maps ZIR to AIR.
1918inst_map: InstMap = .{},
2019/// When analyzing an inline function call, owner_decl is the Decl of the caller
......@@ -76,7 +75,6 @@ pub fn deinit(sema: *Sema) void {
7675 sema.air_instructions.deinit(gpa);
7776 sema.air_extra.deinit(gpa);
7877 sema.air_values.deinit(gpa);
79 sema.air_variables.deinit(gpa);
8078 sema.inst_map.deinit(gpa);
8179 sema.decl_val_table.deinit(gpa);
8280 sema.* = undefined;
......@@ -639,16 +637,40 @@ fn analyzeAsType(
639637 return val.toType(sema.arena);
640638}
641639
640/// May return Value Tags: `variable`, `undef`.
641/// See `resolveConstValue` for an alternative.
642fn resolveValue(
643 sema: *Sema,
644 block: *Scope.Block,
645 src: LazySrcLoc,
646 air_ref: Air.Inst.Ref,
647) CompileError!Value {
648 if (try sema.resolveMaybeUndefValAllowVariables(block, src, air_ref)) |val| {
649 return val;
650 }
651 return sema.failWithNeededComptime(block, src);
652}
653
654/// Will not return Value Tags: `variable`, `undef`. Instead they will emit compile errors.
655/// See `resolveValue` for an alternative.
642656fn resolveConstValue(
643657 sema: *Sema,
644658 block: *Scope.Block,
645659 src: LazySrcLoc,
646660 air_ref: Air.Inst.Ref,
647661) CompileError!Value {
648 return (try sema.resolveDefinedValue(block, src, air_ref)) orelse
649 return sema.failWithNeededComptime(block, src);
662 if (try sema.resolveMaybeUndefValAllowVariables(block, src, air_ref)) |val| {
663 switch (val.tag()) {
664 .undef => return sema.failWithUseOfUndef(block, src),
665 .variable => return sema.failWithNeededComptime(block, src),
666 else => return val,
667 }
668 }
669 return sema.failWithNeededComptime(block, src);
650670}
651671
672/// Value Tag `variable` causes this function to return `null`.
673/// Value Tag `undef` causes this function to return a compile error.
652674fn resolveDefinedValue(
653675 sema: *Sema,
654676 block: *Scope.Block,
......@@ -664,11 +686,27 @@ fn resolveDefinedValue(
664686 return null;
665687}
666688
689/// Value Tag `variable` causes this function to return `null`.
690/// Value Tag `undef` causes this function to return the Value.
667691fn resolveMaybeUndefVal(
668692 sema: *Sema,
669693 block: *Scope.Block,
670694 src: LazySrcLoc,
671695 inst: Air.Inst.Ref,
696) CompileError!?Value {
697 const val = (try sema.resolveMaybeUndefValAllowVariables(block, src, inst)) orelse return null;
698 if (val.tag() == .variable) {
699 return null;
700 }
701 return val;
702}
703
704/// Returns all Value tags including `variable` and `undef`.
705fn resolveMaybeUndefValAllowVariables(
706 sema: *Sema,
707 block: *Scope.Block,
708 src: LazySrcLoc,
709 inst: Air.Inst.Ref,
672710) CompileError!?Value {
673711 // First section of indexes correspond to a set number of constant values.
674712 var i: usize = @enumToInt(inst);
......@@ -734,6 +772,8 @@ fn resolveInt(
734772 return val.toUnsignedInt();
735773}
736774
775// Returns a compile error if the value has tag `variable`. See `resolveInstValue` for
776// a function that does not.
737777pub fn resolveInstConst(
738778 sema: *Sema,
739779 block: *Scope.Block,
......@@ -748,6 +788,22 @@ pub fn resolveInstConst(
748788 };
749789}
750790
791// Value Tag may be `undef` or `variable`.
792// See `resolveInstConst` for an alternative.
793pub fn resolveInstValue(
794 sema: *Sema,
795 block: *Scope.Block,
796 src: LazySrcLoc,
797 zir_ref: Zir.Inst.Ref,
798) CompileError!TypedValue {
799 const air_ref = sema.resolveInst(zir_ref);
800 const val = try sema.resolveValue(block, src, air_ref);
801 return TypedValue{
802 .ty = sema.typeOf(air_ref),
803 .val = val,
804 };
805}
806
751807fn zirBitcastResultPtr(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
752808 const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
753809 const src = inst_data.src();
......@@ -1707,7 +1763,7 @@ fn zirStr(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) CompileError!A
17071763 });
17081764 errdefer sema.mod.deleteAnonDecl(&block.base, new_decl);
17091765 try new_decl.finalizeNewArena(&new_decl_arena);
1710 return sema.analyzeDeclRef(block, .unneeded, new_decl);
1766 return sema.analyzeDeclRef(new_decl);
17111767}
17121768
17131769fn zirInt(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
......@@ -2090,10 +2146,7 @@ fn zirExport(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) CompileErro
20902146 const linkage_index = struct_obj.fields.getIndex("linkage").?;
20912147 const section_index = struct_obj.fields.getIndex("section").?;
20922148 const export_name = try fields[name_index].toAllocatedBytes(sema.arena);
2093 const linkage = fields[linkage_index].toEnum(
2094 struct_obj.fields.values()[linkage_index].ty,
2095 std.builtin.GlobalLinkage,
2096 );
2149 const linkage = fields[linkage_index].toEnum(std.builtin.GlobalLinkage);
20972150
20982151 if (linkage != .Strong) {
20992152 return sema.mod.fail(&block.base, src, "TODO: implement exporting with non-strong linkage", .{});
......@@ -2194,7 +2247,7 @@ fn zirDeclRef(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) CompileErr
21942247 const src = inst_data.src();
21952248 const decl_name = inst_data.get(sema.code);
21962249 const decl = try sema.lookupIdentifier(block, src, decl_name);
2197 return sema.analyzeDeclRef(block, src, decl);
2250 return sema.analyzeDeclRef(decl);
21982251}
21992252
22002253fn zirDeclVal(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
......@@ -2864,12 +2917,13 @@ fn zirOptionalPayloadPtr(
28642917 const child_pointer = try Module.simplePtrType(sema.arena, child_type, !optional_ptr_ty.isConstPtr(), .One);
28652918
28662919 if (try sema.resolveDefinedValue(block, src, optional_ptr)) |pointer_val| {
2867 const val = try pointer_val.pointerDeref(sema.arena);
2868 if (val.isNull()) {
2869 return sema.mod.fail(&block.base, src, "unable to unwrap null", .{});
2920 if (try pointer_val.pointerDeref(sema.arena)) |val| {
2921 if (val.isNull()) {
2922 return sema.mod.fail(&block.base, src, "unable to unwrap null", .{});
2923 }
2924 // The same Value represents the pointer to the optional and the payload.
2925 return sema.addConstant(child_pointer, pointer_val);
28702926 }
2871 // The same Value represents the pointer to the optional and the payload.
2872 return sema.addConstant(child_pointer, pointer_val);
28732927 }
28742928
28752929 try sema.requireRuntimeBlock(block, src);
......@@ -2974,19 +3028,15 @@ fn zirErrUnionPayloadPtr(
29743028 const operand_pointer_ty = try Module.simplePtrType(sema.arena, payload_ty, !operand_ty.isConstPtr(), .One);
29753029
29763030 if (try sema.resolveDefinedValue(block, src, operand)) |pointer_val| {
2977 const val = try pointer_val.pointerDeref(sema.arena);
2978 if (val.getError()) |name| {
2979 return sema.mod.fail(&block.base, src, "caught unexpected error '{s}'", .{name});
3031 if (try pointer_val.pointerDeref(sema.arena)) |val| {
3032 if (val.getError()) |name| {
3033 return sema.mod.fail(&block.base, src, "caught unexpected error '{s}'", .{name});
3034 }
3035 return sema.addConstant(
3036 operand_pointer_ty,
3037 try Value.Tag.eu_payload_ptr.create(sema.arena, pointer_val),
3038 );
29803039 }
2981 const data = val.castTag(.error_union).?.data;
2982 // The same Value represents the pointer to the error union and the payload.
2983 return sema.addConstant(
2984 operand_pointer_ty,
2985 try Value.Tag.ref_val.create(
2986 sema.arena,
2987 data,
2988 ),
2989 );
29903040 }
29913041
29923042 try sema.requireRuntimeBlock(block, src);
......@@ -3038,10 +3088,11 @@ fn zirErrUnionCodePtr(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) Co
30383088 const result_ty = operand_ty.elemType().errorUnionSet();
30393089
30403090 if (try sema.resolveDefinedValue(block, src, operand)) |pointer_val| {
3041 const val = try pointer_val.pointerDeref(sema.arena);
3042 assert(val.getError() != null);
3043 const data = val.castTag(.error_union).?.data;
3044 return sema.addConstant(result_ty, data);
3091 if (try pointer_val.pointerDeref(sema.arena)) |val| {
3092 assert(val.getError() != null);
3093 const data = val.castTag(.error_union).?.data;
3094 return sema.addConstant(result_ty, data);
3095 }
30453096 }
30463097
30473098 try sema.requireRuntimeBlock(block, src);
......@@ -4872,10 +4923,13 @@ fn analyzeArithmetic(
48724923 log.debug("{s}({}, {}) result: {}", .{ @tagName(zir_tag), lhs_val, rhs_val, value });
48734924
48744925 return sema.addConstant(scalar_type, value);
4926 } else {
4927 try sema.requireRuntimeBlock(block, rhs_src);
48754928 }
4929 } else {
4930 try sema.requireRuntimeBlock(block, lhs_src);
48764931 }
48774932
4878 try sema.requireRuntimeBlock(block, src);
48794933 const air_tag: Air.Inst.Tag = switch (zir_tag) {
48804934 .add => .add,
48814935 .addwrap => .addwrap,
......@@ -6296,7 +6350,7 @@ fn zirFuncExtended(
62966350 const cc_ref = @intToEnum(Zir.Inst.Ref, sema.code.extra[extra_index]);
62976351 extra_index += 1;
62986352 const cc_tv = try sema.resolveInstConst(block, cc_src, cc_ref);
6299 break :blk cc_tv.val.toEnum(cc_tv.ty, std.builtin.CallingConvention);
6353 break :blk cc_tv.val.toEnum(std.builtin.CallingConvention);
63006354 } else .Unspecified;
63016355
63026356 const align_val: Value = if (small.has_align) blk: {
......@@ -6554,7 +6608,7 @@ fn safetyPanic(
65546608 });
65556609 errdefer sema.mod.deleteAnonDecl(&block.base, new_decl);
65566610 try new_decl.finalizeNewArena(&new_decl_arena);
6557 break :msg_inst try sema.analyzeDeclRef(block, .unneeded, new_decl);
6611 break :msg_inst try sema.analyzeDeclRef(new_decl);
65586612 };
65596613
65606614 const casted_msg_inst = try sema.coerce(block, Type.initTag(.const_slice_u8), msg_inst, src);
......@@ -6761,13 +6815,12 @@ fn fieldPtr(
67616815 switch (object_ty.zigTypeTag()) {
67626816 .Array => {
67636817 if (mem.eql(u8, field_name, "len")) {
6764 return sema.addConstant(
6765 Type.initTag(.single_const_pointer_to_comptime_int),
6766 try Value.Tag.ref_val.create(
6767 arena,
6768 try Value.Tag.int_u64.create(arena, object_ty.arrayLen()),
6769 ),
6770 );
6818 var anon_decl = try block.startAnonDecl();
6819 defer anon_decl.deinit();
6820 return sema.analyzeDeclRef(try anon_decl.finish(
6821 Type.initTag(.comptime_int),
6822 try Value.Tag.int_u64.create(anon_decl.arena(), object_ty.arrayLen()),
6823 ));
67716824 } else {
67726825 return mod.fail(
67736826 &block.base,
......@@ -6780,18 +6833,25 @@ fn fieldPtr(
67806833 .Pointer => {
67816834 const ptr_child = object_ty.elemType();
67826835 if (ptr_child.isSlice()) {
6836 // Here for the ptr and len fields what we need to do is the situation
6837 // when a temporary has its address taken, e.g. `&a[c..d].len`.
6838 // This value may be known at compile-time or runtime. In the former
6839 // case, it should create an anonymous Decl and return a decl_ref to it.
6840 // In the latter case, it should add an `alloc` instruction, store
6841 // the runtime value to it, and then return the `alloc`.
6842 // In both cases the pointer should be const.
67836843 if (mem.eql(u8, field_name, "ptr")) {
67846844 return mod.fail(
67856845 &block.base,
67866846 field_name_src,
6787 "cannot obtain reference to pointer field of slice '{}'",
6847 "TODO: implement reference to 'ptr' field of slice '{}'",
67886848 .{object_ty},
67896849 );
67906850 } else if (mem.eql(u8, field_name, "len")) {
67916851 return mod.fail(
67926852 &block.base,
67936853 field_name_src,
6794 "cannot obtain reference to length field of slice '{}'",
6854 "TODO: implement reference to 'len' field of slice '{}'",
67956855 .{object_ty},
67966856 );
67976857 } else {
......@@ -6805,13 +6865,12 @@ fn fieldPtr(
68056865 } else switch (ptr_child.zigTypeTag()) {
68066866 .Array => {
68076867 if (mem.eql(u8, field_name, "len")) {
6808 return sema.addConstant(
6809 Type.initTag(.single_const_pointer_to_comptime_int),
6810 try Value.Tag.ref_val.create(
6811 arena,
6812 try Value.Tag.int_u64.create(arena, ptr_child.arrayLen()),
6813 ),
6814 );
6868 var anon_decl = try block.startAnonDecl();
6869 defer anon_decl.deinit();
6870 return sema.analyzeDeclRef(try anon_decl.finish(
6871 Type.initTag(.comptime_int),
6872 try Value.Tag.int_u64.create(anon_decl.arena(), ptr_child.arrayLen()),
6873 ));
68156874 } else {
68166875 return mod.fail(
68176876 &block.base,
......@@ -6848,15 +6907,12 @@ fn fieldPtr(
68486907 });
68496908 } else (try mod.getErrorValue(field_name)).key;
68506909
6851 return sema.addConstant(
6852 try Module.simplePtrType(arena, child_type, false, .One),
6853 try Value.Tag.ref_val.create(
6854 arena,
6855 try Value.Tag.@"error".create(arena, .{
6856 .name = name,
6857 }),
6858 ),
6859 );
6910 var anon_decl = try block.startAnonDecl();
6911 defer anon_decl.deinit();
6912 return sema.analyzeDeclRef(try anon_decl.finish(
6913 child_type,
6914 try Value.Tag.@"error".create(anon_decl.arena(), .{ .name = name }),
6915 ));
68606916 },
68616917 .Struct, .Opaque, .Union => {
68626918 if (child_type.getNamespace()) |namespace| {
......@@ -6901,11 +6957,12 @@ fn fieldPtr(
69016957 return mod.failWithOwnedErrorMsg(&block.base, msg);
69026958 };
69036959 const field_index_u32 = @intCast(u32, field_index);
6904 const enum_val = try Value.Tag.enum_field_index.create(arena, field_index_u32);
6905 return sema.addConstant(
6906 try Module.simplePtrType(arena, child_type, false, .One),
6907 try Value.Tag.ref_val.create(arena, enum_val),
6908 );
6960 var anon_decl = try block.startAnonDecl();
6961 defer anon_decl.deinit();
6962 return sema.analyzeDeclRef(try anon_decl.finish(
6963 child_type,
6964 try Value.Tag.enum_field_index.create(anon_decl.arena(), field_index_u32),
6965 ));
69096966 },
69106967 else => return mod.fail(&block.base, src, "type '{}' has no members", .{child_type}),
69116968 }
......@@ -6951,7 +7008,7 @@ fn namespaceLookupRef(
69517008 decl_name: []const u8,
69527009) CompileError!?Air.Inst.Ref {
69537010 const decl = (try sema.namespaceLookup(block, src, namespace, decl_name)) orelse return null;
6954 return try sema.analyzeDeclRef(block, src, decl);
7011 return try sema.analyzeDeclRef(decl);
69557012}
69567013
69577014fn structFieldPtr(
......@@ -7207,13 +7264,15 @@ fn elemPtrArray(
72077264fn coerce(
72087265 sema: *Sema,
72097266 block: *Scope.Block,
7210 dest_type: Type,
7267 dest_type_unresolved: Type,
72117268 inst: Air.Inst.Ref,
72127269 inst_src: LazySrcLoc,
72137270) CompileError!Air.Inst.Ref {
7214 if (dest_type.tag() == .var_args_param) {
7271 if (dest_type_unresolved.tag() == .var_args_param) {
72157272 return sema.coerceVarArgParam(block, inst, inst_src);
72167273 }
7274 const dest_type_src = inst_src; // TODO better source location
7275 const dest_type = try sema.resolveTypeFields(block, dest_type_src, dest_type_unresolved);
72177276
72187277 const inst_ty = sema.typeOf(inst);
72197278 // If the types are the same, we can return the operand.
......@@ -7554,17 +7613,17 @@ fn analyzeDeclVal(
75547613 if (sema.decl_val_table.get(decl)) |result| {
75557614 return result;
75567615 }
7557 const decl_ref = try sema.analyzeDeclRef(block, src, decl);
7616 const decl_ref = try sema.analyzeDeclRef(decl);
75587617 const result = try sema.analyzeLoad(block, src, decl_ref, src);
75597618 if (Air.refToIndex(result)) |index| {
75607619 if (sema.air_instructions.items(.tag)[index] == .constant) {
7561 sema.decl_val_table.put(sema.gpa, decl, result) catch {};
7620 try sema.decl_val_table.put(sema.gpa, decl, result);
75627621 }
75637622 }
75647623 return result;
75657624}
75667625
7567fn analyzeDeclRef(sema: *Sema, block: *Scope.Block, src: LazySrcLoc, decl: *Decl) CompileError!Air.Inst.Ref {
7626fn analyzeDeclRef(sema: *Sema, decl: *Decl) CompileError!Air.Inst.Ref {
75687627 try sema.mod.declareDeclDependency(sema.owner_decl, decl);
75697628 sema.mod.ensureDeclAnalyzed(decl) catch |err| {
75707629 if (sema.func) |func| {
......@@ -7576,8 +7635,10 @@ fn analyzeDeclRef(sema: *Sema, block: *Scope.Block, src: LazySrcLoc, decl: *Decl
75767635 };
75777636
75787637 const decl_tv = try decl.typedValue();
7579 if (decl_tv.val.tag() == .variable) {
7580 return sema.analyzeVarRef(block, src, decl_tv);
7638 if (decl_tv.val.castTag(.variable)) |payload| {
7639 const variable = payload.data;
7640 const ty = try Module.simplePtrType(sema.arena, decl_tv.ty, variable.is_mutable, .One);
7641 return sema.addConstant(ty, try Value.Tag.decl_ref.create(sema.arena, decl));
75817642 }
75827643 return sema.addConstant(
75837644 try Module.simplePtrType(sema.arena, decl_tv.ty, false, .One),
......@@ -7585,26 +7646,6 @@ fn analyzeDeclRef(sema: *Sema, block: *Scope.Block, src: LazySrcLoc, decl: *Decl
75857646 );
75867647}
75877648
7588fn analyzeVarRef(sema: *Sema, block: *Scope.Block, src: LazySrcLoc, tv: TypedValue) CompileError!Air.Inst.Ref {
7589 const variable = tv.val.castTag(.variable).?.data;
7590
7591 const ty = try Module.simplePtrType(sema.arena, tv.ty, variable.is_mutable, .One);
7592 if (!variable.is_mutable and !variable.is_extern) {
7593 return sema.addConstant(ty, try Value.Tag.ref_val.create(sema.arena, variable.init));
7594 }
7595
7596 const gpa = sema.gpa;
7597 try sema.requireRuntimeBlock(block, src);
7598 try sema.air_variables.append(gpa, variable);
7599 return block.addInst(.{
7600 .tag = .varptr,
7601 .data = .{ .ty_pl = .{
7602 .ty = try sema.addType(ty),
7603 .payload = @intCast(u32, sema.air_variables.items.len - 1),
7604 } },
7605 });
7606}
7607
76087649fn analyzeRef(
76097650 sema: *Sema,
76107651 block: *Scope.Block,
......@@ -7612,14 +7653,21 @@ fn analyzeRef(
76127653 operand: Air.Inst.Ref,
76137654) CompileError!Air.Inst.Ref {
76147655 const operand_ty = sema.typeOf(operand);
7615 const ptr_type = try Module.simplePtrType(sema.arena, operand_ty, false, .One);
76167656
76177657 if (try sema.resolveMaybeUndefVal(block, src, operand)) |val| {
7618 return sema.addConstant(ptr_type, try Value.Tag.ref_val.create(sema.arena, val));
7658 var anon_decl = try block.startAnonDecl();
7659 defer anon_decl.deinit();
7660 return sema.analyzeDeclRef(try anon_decl.finish(
7661 operand_ty,
7662 try val.copy(anon_decl.arena()),
7663 ));
76197664 }
76207665
76217666 try sema.requireRuntimeBlock(block, src);
7622 return block.addTyOp(.ref, ptr_type, operand);
7667 const ptr_type = try Module.simplePtrType(sema.arena, operand_ty, false, .One);
7668 const alloc = try block.addTy(.alloc, ptr_type);
7669 try sema.storePtr(block, src, alloc, operand);
7670 return alloc;
76237671}
76247672
76257673fn analyzeLoad(
......@@ -7634,11 +7682,10 @@ fn analyzeLoad(
76347682 .Pointer => ptr_ty.elemType(),
76357683 else => return sema.mod.fail(&block.base, ptr_src, "expected pointer, found '{}'", .{ptr_ty}),
76367684 };
7637 if (try sema.resolveDefinedValue(block, ptr_src, ptr)) |ptr_val| blk: {
7638 if (ptr_val.tag() == .int_u64)
7639 break :blk; // do it at runtime
7640
7641 return sema.addConstant(elem_ty, try ptr_val.pointerDeref(sema.arena));
7685 if (try sema.resolveDefinedValue(block, ptr_src, ptr)) |ptr_val| {
7686 if (try ptr_val.pointerDeref(sema.arena)) |elem_val| {
7687 return sema.addConstant(elem_ty, elem_val);
7688 }
76427689 }
76437690
76447691 try sema.requireRuntimeBlock(block, src);
......@@ -8146,6 +8193,36 @@ fn resolvePeerTypes(
81468193 return sema.typeOf(chosen);
81478194}
81488195
8196pub fn resolveTypeLayout(
8197 sema: *Sema,
8198 block: *Scope.Block,
8199 src: LazySrcLoc,
8200 ty: Type,
8201) CompileError!void {
8202 switch (ty.zigTypeTag()) {
8203 .Pointer => {
8204 return sema.resolveTypeLayout(block, src, ty.elemType());
8205 },
8206 .Struct => {
8207 const resolved_ty = try sema.resolveTypeFields(block, src, ty);
8208 const struct_obj = resolved_ty.castTag(.@"struct").?.data;
8209 switch (struct_obj.status) {
8210 .none, .have_field_types => {},
8211 .field_types_wip, .layout_wip => {
8212 return sema.mod.fail(&block.base, src, "struct {} depends on itself", .{ty});
8213 },
8214 .have_layout => return,
8215 }
8216 struct_obj.status = .layout_wip;
8217 for (struct_obj.fields.values()) |field| {
8218 try sema.resolveTypeLayout(block, src, field.ty);
8219 }
8220 struct_obj.status = .have_layout;
8221 },
8222 else => {},
8223 }
8224}
8225
81498226fn resolveTypeFields(sema: *Sema, block: *Scope.Block, src: LazySrcLoc, ty: Type) CompileError!Type {
81508227 switch (ty.tag()) {
81518228 .@"struct" => {
......@@ -8153,9 +8230,7 @@ fn resolveTypeFields(sema: *Sema, block: *Scope.Block, src: LazySrcLoc, ty: Type
81538230 switch (struct_obj.status) {
81548231 .none => {},
81558232 .field_types_wip => {
8156 return sema.mod.fail(&block.base, src, "struct {} depends on itself", .{
8157 ty,
8158 });
8233 return sema.mod.fail(&block.base, src, "struct {} depends on itself", .{ty});
81598234 },
81608235 .have_field_types, .have_layout, .layout_wip => return ty,
81618236 }
......@@ -8447,12 +8522,12 @@ fn getTmpAir(sema: Sema) Air {
84478522 .instructions = sema.air_instructions.slice(),
84488523 .extra = sema.air_extra.items,
84498524 .values = sema.air_values.items,
8450 .variables = sema.air_variables.items,
84518525 };
84528526}
84538527
84548528pub fn addType(sema: *Sema, ty: Type) !Air.Inst.Ref {
84558529 switch (ty.tag()) {
8530 .u1 => return .u1_type,
84568531 .u8 => return .u8_type,
84578532 .i8 => return .i8_type,
84588533 .u16 => return .u16_type,
src/codegen.zig+3-45
......@@ -184,6 +184,7 @@ pub fn generateSymbol(
184184 if (typed_value.val.castTag(.decl_ref)) |payload| {
185185 const decl = payload.data;
186186 if (decl.analysis != .complete) return error.AnalysisFail;
187 decl.alive = true;
187188 // TODO handle the dependency of this symbol on the decl's vaddr.
188189 // If the decl changes vaddr, then this symbol needs to get regenerated.
189190 const vaddr = bin_file.getDeclVAddr(decl);
......@@ -848,13 +849,11 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
848849 .loop => try self.airLoop(inst),
849850 .not => try self.airNot(inst),
850851 .ptrtoint => try self.airPtrToInt(inst),
851 .ref => try self.airRef(inst),
852852 .ret => try self.airRet(inst),
853853 .store => try self.airStore(inst),
854854 .struct_field_ptr=> try self.airStructFieldPtr(inst),
855855 .struct_field_val=> try self.airStructFieldVal(inst),
856856 .switch_br => try self.airSwitch(inst),
857 .varptr => try self.airVarPtr(inst),
858857 .slice_ptr => try self.airSlicePtr(inst),
859858 .slice_len => try self.airSliceLen(inst),
860859
......@@ -1340,13 +1339,6 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
13401339 return self.finishAir(inst, result, .{ ty_op.operand, .none, .none });
13411340 }
13421341
1343 fn airVarPtr(self: *Self, inst: Air.Inst.Index) !void {
1344 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else switch (arch) {
1345 else => return self.fail("TODO implement varptr for {}", .{self.target.cpu.arch}),
1346 };
1347 return self.finishAir(inst, result, .{ .none, .none, .none });
1348 }
1349
13501342 fn airSlicePtr(self: *Self, inst: Air.Inst.Index) !void {
13511343 const ty_op = self.air.instructions.items(.data)[inst].ty_op;
13521344 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else switch (arch) {
......@@ -2833,38 +2825,6 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
28332825 return bt.finishAir(result);
28342826 }
28352827
2836 fn airRef(self: *Self, inst: Air.Inst.Index) !void {
2837 const ty_op = self.air.instructions.items(.data)[inst].ty_op;
2838 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
2839 const operand_ty = self.air.typeOf(ty_op.operand);
2840 const operand = try self.resolveInst(ty_op.operand);
2841 switch (operand) {
2842 .unreach => unreachable,
2843 .dead => unreachable,
2844 .none => break :result MCValue{ .none = {} },
2845
2846 .immediate,
2847 .register,
2848 .ptr_stack_offset,
2849 .ptr_embedded_in_code,
2850 .compare_flags_unsigned,
2851 .compare_flags_signed,
2852 => {
2853 const stack_offset = try self.allocMemPtr(inst);
2854 try self.genSetStack(operand_ty, stack_offset, operand);
2855 break :result MCValue{ .ptr_stack_offset = stack_offset };
2856 },
2857
2858 .stack_offset => |offset| break :result MCValue{ .ptr_stack_offset = offset },
2859 .embedded_in_code => |offset| break :result MCValue{ .ptr_embedded_in_code = offset },
2860 .memory => |vaddr| break :result MCValue{ .immediate = vaddr },
2861
2862 .undef => return self.fail("TODO implement ref on an undefined value", .{}),
2863 }
2864 };
2865 return self.finishAir(inst, result, .{ ty_op.operand, .none, .none });
2866 }
2867
28682828 fn ret(self: *Self, mcv: MCValue) !void {
28692829 const ret_ty = self.fn_type.fnReturnType();
28702830 try self.setRegOrMem(ret_ty, self.ret_mcv, mcv);
......@@ -4721,13 +4681,13 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
47214681 },
47224682 else => {
47234683 if (typed_value.val.castTag(.decl_ref)) |payload| {
4684 const decl = payload.data;
4685 decl.alive = true;
47244686 if (self.bin_file.cast(link.File.Elf)) |elf_file| {
4725 const decl = payload.data;
47264687 const got = &elf_file.program_headers.items[elf_file.phdr_got_index.?];
47274688 const got_addr = got.p_vaddr + decl.link.elf.offset_table_index * ptr_bytes;
47284689 return MCValue{ .memory = got_addr };
47294690 } else if (self.bin_file.cast(link.File.MachO)) |macho_file| {
4730 const decl = payload.data;
47314691 const got_addr = blk: {
47324692 const seg = macho_file.load_commands.items[macho_file.data_const_segment_cmd_index.?].Segment;
47334693 const got = seg.sections.items[macho_file.got_section_index.?];
......@@ -4739,11 +4699,9 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
47394699 };
47404700 return MCValue{ .memory = got_addr };
47414701 } else if (self.bin_file.cast(link.File.Coff)) |coff_file| {
4742 const decl = payload.data;
47434702 const got_addr = coff_file.offset_table_virtual_address + decl.link.coff.offset_table_index * ptr_bytes;
47444703 return MCValue{ .memory = got_addr };
47454704 } else if (self.bin_file.cast(link.File.Plan9)) |p9| {
4746 const decl = payload.data;
47474705 const got_addr = p9.bases.data + decl.link.plan9.got_index.? * ptr_bytes;
47484706 return MCValue{ .memory = got_addr };
47494707 } else {
src/codegen/c.zig+7-56
......@@ -262,6 +262,7 @@ pub const DeclGen = struct {
262262 .one => try writer.writeAll("1"),
263263 .decl_ref => {
264264 const decl = val.castTag(.decl_ref).?.data;
265 decl.alive = true;
265266
266267 // Determine if we must pointer cast.
267268 assert(decl.has_tv);
......@@ -281,36 +282,7 @@ pub const DeclGen = struct {
281282 const decl = val.castTag(.extern_fn).?.data;
282283 try writer.print("{s}", .{decl.name});
283284 },
284 else => switch (t.ptrSize()) {
285 .Slice => unreachable,
286 .Many => {
287 if (val.castTag(.ref_val)) |ref_val_payload| {
288 const sub_val = ref_val_payload.data;
289 if (sub_val.castTag(.bytes)) |bytes_payload| {
290 const bytes = bytes_payload.data;
291 try writer.writeByte('(');
292 try dg.renderType(writer, t);
293 // TODO: make our own C string escape instead of using std.zig.fmtEscapes
294 try writer.print(")\"{}\"", .{std.zig.fmtEscapes(bytes)});
295 } else {
296 unreachable;
297 }
298 } else {
299 unreachable;
300 }
301 },
302 .One => {
303 var arena = std.heap.ArenaAllocator.init(dg.module.gpa);
304 defer arena.deinit();
305
306 const elem_ty = t.elemType();
307 const elem_val = try val.pointerDeref(&arena.allocator);
308
309 try writer.writeAll("&");
310 try dg.renderValue(writer, elem_ty, elem_val);
311 },
312 .C => unreachable,
313 },
285 else => unreachable,
314286 },
315287 },
316288 .Array => {
......@@ -436,6 +408,7 @@ pub const DeclGen = struct {
436408 .one => try writer.writeAll("1"),
437409 .decl_ref => {
438410 const decl = val.castTag(.decl_ref).?.data;
411 decl.alive = true;
439412
440413 // Determine if we must pointer cast.
441414 assert(decl.has_tv);
......@@ -448,11 +421,13 @@ pub const DeclGen = struct {
448421 }
449422 },
450423 .function => {
451 const func = val.castTag(.function).?.data;
452 try writer.print("{s}", .{func.owner_decl.name});
424 const decl = val.castTag(.function).?.data.owner_decl;
425 decl.alive = true;
426 try writer.print("{s}", .{decl.name});
453427 },
454428 .extern_fn => {
455429 const decl = val.castTag(.extern_fn).?.data;
430 decl.alive = true;
456431 try writer.print("{s}", .{decl.name});
457432 },
458433 else => unreachable,
......@@ -934,10 +909,8 @@ fn genBody(o: *Object, body: []const Air.Inst.Index) error{ AnalysisFail, OutOfM
934909 .br => try airBr(o, inst),
935910 .switch_br => try airSwitchBr(o, inst),
936911 .wrap_optional => try airWrapOptional(o, inst),
937 .ref => try airRef(o, inst),
938912 .struct_field_ptr => try airStructFieldPtr(o, inst),
939913 .struct_field_val => try airStructFieldVal(o, inst),
940 .varptr => try airVarPtr(o, inst),
941914 .slice_ptr => try airSliceField(o, inst, ".ptr;\n"),
942915 .slice_len => try airSliceField(o, inst, ".len;\n"),
943916
......@@ -996,12 +969,6 @@ fn airSliceElemVal(o: *Object, inst: Air.Inst.Index, prefix: []const u8) !CValue
996969 return local;
997970}
998971
999fn airVarPtr(o: *Object, inst: Air.Inst.Index) !CValue {
1000 const ty_pl = o.air.instructions.items(.data)[inst].ty_pl;
1001 const variable = o.air.variables[ty_pl.payload];
1002 return CValue{ .decl_ref = variable.owner_decl };
1003}
1004
1005972fn airAlloc(o: *Object, inst: Air.Inst.Index) !CValue {
1006973 const writer = o.writer();
1007974 const inst_ty = o.air.typeOfIndex(inst);
......@@ -1653,22 +1620,6 @@ fn airOptionalPayload(o: *Object, inst: Air.Inst.Index) !CValue {
16531620 return local;
16541621}
16551622
1656fn airRef(o: *Object, inst: Air.Inst.Index) !CValue {
1657 if (o.liveness.isUnused(inst))
1658 return CValue.none;
1659
1660 const ty_op = o.air.instructions.items(.data)[inst].ty_op;
1661 const writer = o.writer();
1662 const operand = try o.resolveInst(ty_op.operand);
1663
1664 const inst_ty = o.air.typeOfIndex(inst);
1665 const local = try o.allocLocal(inst_ty, .Const);
1666 try writer.writeAll(" = ");
1667 try o.writeCValue(writer, operand);
1668 try writer.writeAll(";\n");
1669 return local;
1670}
1671
16721623fn airStructFieldPtr(o: *Object, inst: Air.Inst.Index) !CValue {
16731624 if (o.liveness.isUnused(inst))
16741625 return CValue.none;
src/codegen/llvm.zig+35-47
......@@ -673,17 +673,21 @@ pub const DeclGen = struct {
673673 }
674674
675675 fn genTypedValue(self: *DeclGen, tv: TypedValue) error{ OutOfMemory, CodegenFail }!*const llvm.Value {
676 const llvm_type = try self.llvmType(tv.ty);
677
678 if (tv.val.isUndef())
676 if (tv.val.isUndef()) {
677 const llvm_type = try self.llvmType(tv.ty);
679678 return llvm_type.getUndef();
679 }
680680
681681 switch (tv.ty.zigTypeTag()) {
682 .Bool => return if (tv.val.toBool()) llvm_type.constAllOnes() else llvm_type.constNull(),
682 .Bool => {
683 const llvm_type = try self.llvmType(tv.ty);
684 return if (tv.val.toBool()) llvm_type.constAllOnes() else llvm_type.constNull();
685 },
683686 .Int => {
684687 var bigint_space: Value.BigIntSpace = undefined;
685688 const bigint = tv.val.toBigInt(&bigint_space);
686689
690 const llvm_type = try self.llvmType(tv.ty);
687691 if (bigint.eqZero()) return llvm_type.constNull();
688692
689693 if (bigint.limbs.len != 1) {
......@@ -698,30 +702,18 @@ pub const DeclGen = struct {
698702 .Pointer => switch (tv.val.tag()) {
699703 .decl_ref => {
700704 const decl = tv.val.castTag(.decl_ref).?.data;
705 decl.alive = true;
701706 const val = try self.resolveGlobalDecl(decl);
702
703 const usize_type = try self.llvmType(Type.initTag(.usize));
704
705 // TODO: second index should be the index into the memory!
706 var indices: [2]*const llvm.Value = .{
707 usize_type.constNull(),
708 usize_type.constNull(),
709 };
710
711 return val.constInBoundsGEP(&indices, indices.len);
712 },
713 .ref_val => {
714 //const elem_value = tv.val.castTag(.ref_val).?.data;
715 //const elem_type = tv.ty.castPointer().?.data;
716 //const alloca = fg.?.buildAlloca(try self.llvmType(elem_type));
717 //_ = fg.?.builder.buildStore(try self.genTypedValue(.{ .ty = elem_type, .val = elem_value }, fg), alloca);
718 //return alloca;
719 // TODO eliminate the ref_val Value Tag
720 return self.todo("implement const of pointer tag ref_val", .{});
707 const llvm_type = try self.llvmType(tv.ty);
708 return val.constBitCast(llvm_type);
721709 },
722710 .variable => {
723 const variable = tv.val.castTag(.variable).?.data;
724 return self.resolveGlobalDecl(variable.owner_decl);
711 const decl = tv.val.castTag(.variable).?.data.owner_decl;
712 decl.alive = true;
713 const val = try self.resolveGlobalDecl(decl);
714 const llvm_var_type = try self.llvmType(tv.ty);
715 const llvm_type = llvm_var_type.pointerType(0);
716 return val.constBitCast(llvm_type);
725717 },
726718 .slice => {
727719 const slice = tv.val.castTag(.slice).?.data;
......@@ -800,6 +792,7 @@ pub const DeclGen = struct {
800792 .decl_ref => tv.val.castTag(.decl_ref).?.data,
801793 else => unreachable,
802794 };
795 fn_decl.alive = true;
803796 return self.resolveLlvmFunction(fn_decl);
804797 },
805798 .ErrorSet => {
......@@ -920,9 +913,7 @@ pub const FuncGen = struct {
920913 return self.dg.genTypedValue(.{ .ty = self.air.typeOf(inst), .val = val });
921914 }
922915 const inst_index = Air.refToIndex(inst).?;
923 if (self.func_inst_table.get(inst_index)) |value| return value;
924
925 return self.todo("implement global llvm values (or the value is not in the func_inst_table table)", .{});
916 return self.func_inst_table.get(inst_index).?;
926917 }
927918
928919 fn genBody(self: *FuncGen, body: []const Air.Inst.Index) error{ OutOfMemory, CodegenFail }!void {
......@@ -977,15 +968,14 @@ pub const FuncGen = struct {
977968 .ret => try self.airRet(inst),
978969 .store => try self.airStore(inst),
979970 .assembly => try self.airAssembly(inst),
980 .varptr => try self.airVarPtr(inst),
981971 .slice_ptr => try self.airSliceField(inst, 0),
982972 .slice_len => try self.airSliceField(inst, 1),
983973
984974 .struct_field_ptr => try self.airStructFieldPtr(inst),
985975 .struct_field_val => try self.airStructFieldVal(inst),
986976
987 .slice_elem_val => try self.airSliceElemVal(inst, false),
988 .ptr_slice_elem_val => try self.airSliceElemVal(inst, true),
977 .slice_elem_val => try self.airSliceElemVal(inst),
978 .ptr_slice_elem_val => try self.airPtrSliceElemVal(inst),
989979
990980 .optional_payload => try self.airOptionalPayload(inst, false),
991981 .optional_payload_ptr => try self.airOptionalPayload(inst, true),
......@@ -1001,7 +991,6 @@ pub const FuncGen = struct {
1001991
1002992 .constant => unreachable,
1003993 .const_ty => unreachable,
1004 .ref => unreachable, // TODO eradicate this instruction
1005994 .unreach => self.airUnreach(inst),
1006995 .dbg_stmt => blk: {
1007996 // TODO: implement debug info
......@@ -1180,30 +1169,29 @@ pub const FuncGen = struct {
11801169 return null;
11811170 }
11821171
1183 fn airVarPtr(self: *FuncGen, inst: Air.Inst.Index) !?*const llvm.Value {
1172 fn airSliceField(self: *FuncGen, inst: Air.Inst.Index, index: c_uint) !?*const llvm.Value {
11841173 if (self.liveness.isUnused(inst))
11851174 return null;
11861175
1187 const ty_pl = self.air.instructions.items(.data)[inst].ty_pl;
1188 const variable = self.air.variables[ty_pl.payload];
1189 const decl_llvm_value = self.dg.resolveGlobalDecl(variable.owner_decl);
1190 return decl_llvm_value;
1176 const ty_op = self.air.instructions.items(.data)[inst].ty_op;
1177 const operand = try self.resolveInst(ty_op.operand);
1178 return self.builder.buildExtractValue(operand, index, "");
11911179 }
11921180
1193 fn airSliceField(self: *FuncGen, inst: Air.Inst.Index, index: c_uint) !?*const llvm.Value {
1181 fn airSliceElemVal(self: *FuncGen, inst: Air.Inst.Index) !?*const llvm.Value {
11941182 if (self.liveness.isUnused(inst))
11951183 return null;
11961184
1197 const ty_op = self.air.instructions.items(.data)[inst].ty_op;
1198 const operand = try self.resolveInst(ty_op.operand);
1199 return self.builder.buildExtractValue(operand, index, "");
1185 const bin_op = self.air.instructions.items(.data)[inst].bin_op;
1186 const lhs = try self.resolveInst(bin_op.lhs);
1187 const rhs = try self.resolveInst(bin_op.rhs);
1188 const base_ptr = self.builder.buildExtractValue(lhs, 0, "");
1189 const indices: [1]*const llvm.Value = .{rhs};
1190 const ptr = self.builder.buildInBoundsGEP(base_ptr, &indices, indices.len, "");
1191 return self.builder.buildLoad(ptr, "");
12001192 }
12011193
1202 fn airSliceElemVal(
1203 self: *FuncGen,
1204 inst: Air.Inst.Index,
1205 operand_is_ptr: bool,
1206 ) !?*const llvm.Value {
1194 fn airPtrSliceElemVal(self: *FuncGen, inst: Air.Inst.Index) !?*const llvm.Value {
12071195 if (self.liveness.isUnused(inst))
12081196 return null;
12091197
......@@ -1211,7 +1199,7 @@ pub const FuncGen = struct {
12111199 const lhs = try self.resolveInst(bin_op.lhs);
12121200 const rhs = try self.resolveInst(bin_op.rhs);
12131201
1214 const base_ptr = if (!operand_is_ptr) lhs else ptr: {
1202 const base_ptr = ptr: {
12151203 const index_type = self.context.intType(32);
12161204 const indices: [2]*const llvm.Value = .{
12171205 index_type.constNull(),
src/codegen/llvm/bindings.zig+3
......@@ -112,6 +112,9 @@ pub const Value = opaque {
112112 ConstantIndices: [*]const *const Value,
113113 NumIndices: c_uint,
114114 ) *const Value;
115
116 pub const constBitCast = LLVMConstBitCast;
117 extern fn LLVMConstBitCast(ConstantVal: *const Value, ToType: *const Type) *const Value;
115118};
116119
117120pub const Type = opaque {
src/codegen/wasm.zig+32-28
......@@ -754,22 +754,21 @@ pub const Context = struct {
754754 }
755755
756756 /// Generates the wasm bytecode for the declaration belonging to `Context`
757 pub fn gen(self: *Context, typed_value: TypedValue) InnerError!Result {
758 switch (typed_value.ty.zigTypeTag()) {
757 pub fn gen(self: *Context, ty: Type, val: Value) InnerError!Result {
758 switch (ty.zigTypeTag()) {
759759 .Fn => {
760760 try self.genFunctype();
761 if (typed_value.val.castTag(.extern_fn)) |_| return Result.appended; // don't need code body for extern functions
761 if (val.tag() == .extern_fn) {
762 return Result.appended; // don't need code body for extern functions
763 }
762764 return self.fail("TODO implement wasm codegen for function pointers", .{});
763765 },
764766 .Array => {
765 if (typed_value.val.castTag(.bytes)) |payload| {
766 if (typed_value.ty.sentinel()) |sentinel| {
767 if (val.castTag(.bytes)) |payload| {
768 if (ty.sentinel()) |sentinel| {
767769 try self.code.appendSlice(payload.data);
768770
769 switch (try self.gen(.{
770 .ty = typed_value.ty.elemType(),
771 .val = sentinel,
772 })) {
771 switch (try self.gen(ty.elemType(), sentinel)) {
773772 .appended => return Result.appended,
774773 .externally_managed => |data| {
775774 try self.code.appendSlice(data);
......@@ -781,13 +780,17 @@ pub const Context = struct {
781780 } else return self.fail("TODO implement gen for more kinds of arrays", .{});
782781 },
783782 .Int => {
784 const info = typed_value.ty.intInfo(self.target);
783 const info = ty.intInfo(self.target);
785784 if (info.bits == 8 and info.signedness == .unsigned) {
786 const int_byte = typed_value.val.toUnsignedInt();
785 const int_byte = val.toUnsignedInt();
787786 try self.code.append(@intCast(u8, int_byte));
788787 return Result.appended;
789788 }
790 return self.fail("TODO: Implement codegen for int type: '{}'", .{typed_value.ty});
789 return self.fail("TODO: Implement codegen for int type: '{}'", .{ty});
790 },
791 .Enum => {
792 try self.emitConstant(val, ty);
793 return Result.appended;
791794 },
792795 else => |tag| return self.fail("TODO: Implement zig type codegen for type: '{s}'", .{tag}),
793796 }
......@@ -969,7 +972,7 @@ pub const Context = struct {
969972 return WValue{ .code_offset = offset };
970973 }
971974
972 fn emitConstant(self: *Context, value: Value, ty: Type) InnerError!void {
975 fn emitConstant(self: *Context, val: Value, ty: Type) InnerError!void {
973976 const writer = self.code.writer();
974977 switch (ty.zigTypeTag()) {
975978 .Int => {
......@@ -982,10 +985,10 @@ pub const Context = struct {
982985 const int_info = ty.intInfo(self.target);
983986 // write constant
984987 switch (int_info.signedness) {
985 .signed => try leb.writeILEB128(writer, value.toSignedInt()),
988 .signed => try leb.writeILEB128(writer, val.toSignedInt()),
986989 .unsigned => switch (int_info.bits) {
987 0...32 => try leb.writeILEB128(writer, @bitCast(i32, @intCast(u32, value.toUnsignedInt()))),
988 33...64 => try leb.writeILEB128(writer, @bitCast(i64, value.toUnsignedInt())),
990 0...32 => try leb.writeILEB128(writer, @bitCast(i32, @intCast(u32, val.toUnsignedInt()))),
991 33...64 => try leb.writeILEB128(writer, @bitCast(i64, val.toUnsignedInt())),
989992 else => |bits| return self.fail("Wasm TODO: emitConstant for integer with {d} bits", .{bits}),
990993 },
991994 }
......@@ -994,7 +997,7 @@ pub const Context = struct {
994997 // write opcode
995998 try writer.writeByte(wasm.opcode(.i32_const));
996999 // write constant
997 try leb.writeILEB128(writer, value.toSignedInt());
1000 try leb.writeILEB128(writer, val.toSignedInt());
9981001 },
9991002 .Float => {
10001003 // write opcode
......@@ -1005,14 +1008,15 @@ pub const Context = struct {
10051008 try writer.writeByte(wasm.opcode(opcode));
10061009 // write constant
10071010 switch (ty.floatBits(self.target)) {
1008 0...32 => try writer.writeIntLittle(u32, @bitCast(u32, value.toFloat(f32))),
1009 64 => try writer.writeIntLittle(u64, @bitCast(u64, value.toFloat(f64))),
1011 0...32 => try writer.writeIntLittle(u32, @bitCast(u32, val.toFloat(f32))),
1012 64 => try writer.writeIntLittle(u64, @bitCast(u64, val.toFloat(f64))),
10101013 else => |bits| return self.fail("Wasm TODO: emitConstant for float with {d} bits", .{bits}),
10111014 }
10121015 },
10131016 .Pointer => {
1014 if (value.castTag(.decl_ref)) |payload| {
1017 if (val.castTag(.decl_ref)) |payload| {
10151018 const decl = payload.data;
1019 decl.alive = true;
10161020
10171021 // offset into the offset table within the 'data' section
10181022 const ptr_width = self.target.cpu.arch.ptrBitWidth() / 8;
......@@ -1024,11 +1028,11 @@ pub const Context = struct {
10241028 try writer.writeByte(wasm.opcode(.i32_load));
10251029 try leb.writeULEB128(writer, @as(u32, 0));
10261030 try leb.writeULEB128(writer, @as(u32, 0));
1027 } else return self.fail("Wasm TODO: emitConstant for other const pointer tag {s}", .{value.tag()});
1031 } else return self.fail("Wasm TODO: emitConstant for other const pointer tag {s}", .{val.tag()});
10281032 },
10291033 .Void => {},
10301034 .Enum => {
1031 if (value.castTag(.enum_field_index)) |field_index| {
1035 if (val.castTag(.enum_field_index)) |field_index| {
10321036 switch (ty.tag()) {
10331037 .enum_simple => {
10341038 try writer.writeByte(wasm.opcode(.i32_const));
......@@ -1049,20 +1053,20 @@ pub const Context = struct {
10491053 } else {
10501054 var int_tag_buffer: Type.Payload.Bits = undefined;
10511055 const int_tag_ty = ty.intTagType(&int_tag_buffer);
1052 try self.emitConstant(value, int_tag_ty);
1056 try self.emitConstant(val, int_tag_ty);
10531057 }
10541058 },
10551059 .ErrorSet => {
1056 const error_index = self.global_error_set.get(value.getError().?).?;
1060 const error_index = self.global_error_set.get(val.getError().?).?;
10571061 try writer.writeByte(wasm.opcode(.i32_const));
10581062 try leb.writeULEB128(writer, error_index);
10591063 },
10601064 .ErrorUnion => {
1061 const data = value.castTag(.error_union).?.data;
1065 const data = val.castTag(.error_union).?.data;
10621066 const error_type = ty.errorUnionSet();
10631067 const payload_type = ty.errorUnionPayload();
1064 if (value.getError()) |_| {
1065 // write the error value
1068 if (val.getError()) |_| {
1069 // write the error val
10661070 try self.emitConstant(data, error_type);
10671071
10681072 // no payload, so write a '0' const
......@@ -1085,7 +1089,7 @@ pub const Context = struct {
10851089 }
10861090
10871091 /// Returns a `Value` as a signed 32 bit value.
1088 /// It's illegale to provide a value with a type that cannot be represented
1092 /// It's illegal to provide a value with a type that cannot be represented
10891093 /// as an integer value.
10901094 fn valueAsI32(self: Context, val: Value, ty: Type) i32 {
10911095 switch (ty.zigTypeTag()) {
src/link/Plan9.zig+14-5
......@@ -224,7 +224,9 @@ pub fn flushModule(self: *Plan9, comp: *Compilation) !void {
224224
225225 const mod = self.base.options.module orelse return error.LinkingWithoutZigSourceUnimplemented;
226226
227 assert(self.got_len == self.fn_decl_table.count() + self.data_decl_table.count());
227 // TODO I changed this assert from == to >= but this code all needs to be audited; see
228 // the comment in `freeDecl`.
229 assert(self.got_len >= self.fn_decl_table.count() + self.data_decl_table.count());
228230 const got_size = self.got_len * if (!self.sixtyfour_bit) @as(u32, 4) else 8;
229231 var got_table = try self.base.allocator.alloc(u8, got_size);
230232 defer self.base.allocator.free(got_table);
......@@ -358,11 +360,18 @@ fn addDeclExports(
358360}
359361
360362pub fn freeDecl(self: *Plan9, decl: *Module.Decl) void {
363 // TODO this is not the correct check for being function body,
364 // it could just be a function pointer.
365 // TODO audit the lifetimes of decls table entries. It's possible to get
366 // allocateDeclIndexes and then freeDecl without any updateDecl in between.
367 // However that is planned to change, see the TODO comment in Module.zig
368 // in the deleteUnusedDecl function.
361369 const is_fn = (decl.ty.zigTypeTag() == .Fn);
362 if (is_fn)
363 assert(self.fn_decl_table.swapRemove(decl))
364 else
365 assert(self.data_decl_table.swapRemove(decl));
370 if (is_fn) {
371 _ = self.fn_decl_table.swapRemove(decl);
372 } else {
373 _ = self.data_decl_table.swapRemove(decl);
374 }
366375}
367376
368377pub fn updateDeclExports(
src/link/Wasm.zig+1-1
......@@ -275,7 +275,7 @@ pub fn updateDecl(self: *Wasm, module: *Module, decl: *Module.Decl) !void {
275275 defer context.deinit();
276276
277277 // generate the 'code' section for the function declaration
278 const result = context.gen(.{ .ty = decl.ty, .val = decl.val }) catch |err| switch (err) {
278 const result = context.gen(decl.ty, decl.val) catch |err| switch (err) {
279279 error.CodegenFail => {
280280 decl.analysis = .codegen_failure;
281281 try module.failed_decls.put(module.gpa, decl, context.err_msg);
src/print_air.zig+1-12
......@@ -15,12 +15,11 @@ pub fn dump(gpa: *Allocator, air: Air, zir: Zir, liveness: Liveness) void {
1515 (@sizeOf(Air.Inst.Tag) + 8);
1616 const extra_bytes = air.extra.len * @sizeOf(u32);
1717 const values_bytes = air.values.len * @sizeOf(Value);
18 const variables_bytes = air.variables.len * @sizeOf(*Module.Var);
1918 const tomb_bytes = liveness.tomb_bits.len * @sizeOf(usize);
2019 const liveness_extra_bytes = liveness.extra.len * @sizeOf(u32);
2120 const liveness_special_bytes = liveness.special.count() * 8;
2221 const total_bytes = @sizeOf(Air) + instruction_bytes + extra_bytes +
23 values_bytes * variables_bytes + @sizeOf(Liveness) + liveness_extra_bytes +
22 values_bytes + @sizeOf(Liveness) + liveness_extra_bytes +
2423 liveness_special_bytes + tomb_bytes;
2524
2625 // zig fmt: off
......@@ -29,7 +28,6 @@ pub fn dump(gpa: *Allocator, air: Air, zir: Zir, liveness: Liveness) void {
2928 \\# AIR Instructions: {d} ({})
3029 \\# AIR Extra Data: {d} ({})
3130 \\# AIR Values Bytes: {d} ({})
32 \\# AIR Variables Bytes: {d} ({})
3331 \\# Liveness tomb_bits: {}
3432 \\# Liveness Extra Data: {d} ({})
3533 \\# Liveness special table: {d} ({})
......@@ -39,7 +37,6 @@ pub fn dump(gpa: *Allocator, air: Air, zir: Zir, liveness: Liveness) void {
3937 air.instructions.len, fmtIntSizeBin(instruction_bytes),
4038 air.extra.len, fmtIntSizeBin(extra_bytes),
4139 air.values.len, fmtIntSizeBin(values_bytes),
42 air.variables.len, fmtIntSizeBin(variables_bytes),
4340 fmtIntSizeBin(tomb_bytes),
4441 liveness.extra.len, fmtIntSizeBin(liveness_extra_bytes),
4542 liveness.special.count(), fmtIntSizeBin(liveness_special_bytes),
......@@ -152,7 +149,6 @@ const Writer = struct {
152149 .not,
153150 .bitcast,
154151 .load,
155 .ref,
156152 .floatcast,
157153 .intcast,
158154 .optional_payload,
......@@ -174,7 +170,6 @@ const Writer = struct {
174170
175171 .struct_field_ptr => try w.writeStructField(s, inst),
176172 .struct_field_val => try w.writeStructField(s, inst),
177 .varptr => try w.writeVarPtr(s, inst),
178173 .constant => try w.writeConstant(s, inst),
179174 .assembly => try w.writeAssembly(s, inst),
180175 .dbg_stmt => try w.writeDbgStmt(s, inst),
......@@ -243,12 +238,6 @@ const Writer = struct {
243238 try s.print(", {d}", .{extra.data.field_index});
244239 }
245240
246 fn writeVarPtr(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
247 _ = w;
248 _ = inst;
249 try s.writeAll("TODO");
250 }
251
252241 fn writeConstant(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
253242 const ty_pl = w.air.instructions.items(.data)[inst].ty_pl;
254243 const val = w.air.values[ty_pl.payload];
src/value.zig+58-52
......@@ -100,11 +100,10 @@ pub const Value = extern union {
100100 function,
101101 extern_fn,
102102 variable,
103 /// Represents a pointer to another immutable value.
104 ref_val,
105103 /// Represents a comptime variables storage.
106104 comptime_alloc,
107105 /// Represents a pointer to a decl, not the value of the decl.
106 /// When machine codegen backend sees this, it must set the Decl's `alive` field to true.
108107 decl_ref,
109108 elem_ptr,
110109 field_ptr,
......@@ -126,6 +125,8 @@ pub const Value = extern union {
126125 enum_field_index,
127126 @"error",
128127 error_union,
128 /// A pointer to the payload of an error union, based on a pointer to an error union.
129 eu_payload_ptr,
129130 /// An instance of a struct.
130131 @"struct",
131132 /// An instance of a union.
......@@ -214,9 +215,9 @@ pub const Value = extern union {
214215 .decl_ref,
215216 => Payload.Decl,
216217
217 .ref_val,
218218 .repeated,
219219 .error_union,
220 .eu_payload_ptr,
220221 => Payload.SubValue,
221222
222223 .bytes,
......@@ -407,15 +408,6 @@ pub const Value = extern union {
407408 .function => return self.copyPayloadShallow(allocator, Payload.Function),
408409 .extern_fn => return self.copyPayloadShallow(allocator, Payload.Decl),
409410 .variable => return self.copyPayloadShallow(allocator, Payload.Variable),
410 .ref_val => {
411 const payload = self.castTag(.ref_val).?;
412 const new_payload = try allocator.create(Payload.SubValue);
413 new_payload.* = .{
414 .base = payload.base,
415 .data = try payload.data.copy(allocator),
416 };
417 return Value{ .ptr_otherwise = &new_payload.base };
418 },
419411 .comptime_alloc => return self.copyPayloadShallow(allocator, Payload.ComptimeAlloc),
420412 .decl_ref => return self.copyPayloadShallow(allocator, Payload.Decl),
421413 .elem_ptr => {
......@@ -443,8 +435,8 @@ pub const Value = extern union {
443435 return Value{ .ptr_otherwise = &new_payload.base };
444436 },
445437 .bytes => return self.copyPayloadShallow(allocator, Payload.Bytes),
446 .repeated => {
447 const payload = self.castTag(.repeated).?;
438 .repeated, .error_union, .eu_payload_ptr => {
439 const payload = self.cast(Payload.SubValue).?;
448440 const new_payload = try allocator.create(Payload.SubValue);
449441 new_payload.* = .{
450442 .base = payload.base,
......@@ -489,15 +481,6 @@ pub const Value = extern union {
489481 },
490482 .enum_field_index => return self.copyPayloadShallow(allocator, Payload.U32),
491483 .@"error" => return self.copyPayloadShallow(allocator, Payload.Error),
492 .error_union => {
493 const payload = self.castTag(.error_union).?;
494 const new_payload = try allocator.create(Payload.SubValue);
495 new_payload.* = .{
496 .base = payload.base,
497 .data = try payload.data.copy(allocator),
498 };
499 return Value{ .ptr_otherwise = &new_payload.base };
500 },
501484 .@"struct" => @panic("TODO can't copy struct value without knowing the type"),
502485 .@"union" => @panic("TODO can't copy union value without knowing the type"),
503486
......@@ -609,11 +592,6 @@ pub const Value = extern union {
609592 .function => return out_stream.print("(function '{s}')", .{val.castTag(.function).?.data.owner_decl.name}),
610593 .extern_fn => return out_stream.writeAll("(extern function)"),
611594 .variable => return out_stream.writeAll("(variable)"),
612 .ref_val => {
613 const ref_val = val.castTag(.ref_val).?.data;
614 try out_stream.writeAll("&const ");
615 val = ref_val;
616 },
617595 .comptime_alloc => {
618596 const ref_val = val.castTag(.comptime_alloc).?.data.val;
619597 try out_stream.writeAll("&");
......@@ -648,6 +626,10 @@ pub const Value = extern union {
648626 // TODO to print this it should be error{ Set, Items }!T(val), but we need the type for that
649627 .error_union => return out_stream.print("error_union_val({})", .{val.castTag(.error_union).?.data}),
650628 .inferred_alloc => return out_stream.writeAll("(inferred allocation value)"),
629 .eu_payload_ptr => {
630 try out_stream.writeAll("(eu_payload_ptr)");
631 val = val.castTag(.eu_payload_ptr).?.data;
632 },
651633 };
652634 }
653635
......@@ -758,7 +740,6 @@ pub const Value = extern union {
758740 .function,
759741 .extern_fn,
760742 .variable,
761 .ref_val,
762743 .comptime_alloc,
763744 .decl_ref,
764745 .elem_ptr,
......@@ -780,18 +761,21 @@ pub const Value = extern union {
780761 .@"union",
781762 .inferred_alloc,
782763 .abi_align_default,
764 .eu_payload_ptr,
783765 => unreachable,
784766 };
785767 }
786768
787769 /// Asserts the type is an enum type.
788 pub fn toEnum(val: Value, enum_ty: Type, comptime E: type) E {
789 _ = enum_ty;
790 // TODO this needs to resolve other kinds of Value tags rather than
791 // assuming the tag will be .enum_field_index.
792 const field_index = val.castTag(.enum_field_index).?.data;
793 // TODO should `@intToEnum` do this `@intCast` for you?
794 return @intToEnum(E, @intCast(@typeInfo(E).Enum.tag_type, field_index));
770 pub fn toEnum(val: Value, comptime E: type) E {
771 switch (val.tag()) {
772 .enum_field_index => {
773 const field_index = val.castTag(.enum_field_index).?.data;
774 // TODO should `@intToEnum` do this `@intCast` for you?
775 return @intToEnum(E, @intCast(@typeInfo(E).Enum.tag_type, field_index));
776 },
777 else => unreachable,
778 }
795779 }
796780
797781 /// Asserts the value is an integer.
......@@ -1255,6 +1239,9 @@ pub const Value = extern union {
12551239 .slice => {
12561240 @panic("TODO Value.hash for slice");
12571241 },
1242 .eu_payload_ptr => {
1243 @panic("TODO Value.hash for eu_payload_ptr");
1244 },
12581245 .int_u64 => {
12591246 const payload = self.castTag(.int_u64).?;
12601247 std.hash.autoHash(&hasher, payload.data);
......@@ -1263,10 +1250,6 @@ pub const Value = extern union {
12631250 const payload = self.castTag(.int_i64).?;
12641251 std.hash.autoHash(&hasher, payload.data);
12651252 },
1266 .ref_val => {
1267 const payload = self.castTag(.ref_val).?;
1268 std.hash.autoHash(&hasher, payload.data.hash());
1269 },
12701253 .comptime_alloc => {
12711254 const payload = self.castTag(.comptime_alloc).?;
12721255 std.hash.autoHash(&hasher, payload.data.val.hash());
......@@ -1364,24 +1347,48 @@ pub const Value = extern union {
13641347
13651348 /// Asserts the value is a pointer and dereferences it.
13661349 /// Returns error.AnalysisFail if the pointer points to a Decl that failed semantic analysis.
1367 pub fn pointerDeref(self: Value, allocator: *Allocator) error{ AnalysisFail, OutOfMemory }!Value {
1368 return switch (self.tag()) {
1350 pub fn pointerDeref(
1351 self: Value,
1352 allocator: *Allocator,
1353 ) error{ AnalysisFail, OutOfMemory }!?Value {
1354 const sub_val: Value = switch (self.tag()) {
13691355 .comptime_alloc => self.castTag(.comptime_alloc).?.data.val,
1370 .ref_val => self.castTag(.ref_val).?.data,
1371 .decl_ref => self.castTag(.decl_ref).?.data.value(),
1372 .elem_ptr => {
1356 .decl_ref => try self.castTag(.decl_ref).?.data.value(),
1357 .elem_ptr => blk: {
13731358 const elem_ptr = self.castTag(.elem_ptr).?.data;
1374 const array_val = try elem_ptr.array_ptr.pointerDeref(allocator);
1375 return array_val.elemValue(allocator, elem_ptr.index);
1359 const array_val = (try elem_ptr.array_ptr.pointerDeref(allocator)) orelse return null;
1360 break :blk try array_val.elemValue(allocator, elem_ptr.index);
13761361 },
1377 .field_ptr => {
1362 .field_ptr => blk: {
13781363 const field_ptr = self.castTag(.field_ptr).?.data;
1379 const container_val = try field_ptr.container_ptr.pointerDeref(allocator);
1380 return container_val.fieldValue(allocator, field_ptr.field_index);
1364 const container_val = (try field_ptr.container_ptr.pointerDeref(allocator)) orelse return null;
1365 break :blk try container_val.fieldValue(allocator, field_ptr.field_index);
1366 },
1367 .eu_payload_ptr => blk: {
1368 const err_union_ptr = self.castTag(.eu_payload_ptr).?.data;
1369 const err_union_val = (try err_union_ptr.pointerDeref(allocator)) orelse return null;
1370 break :blk err_union_val.castTag(.error_union).?.data;
13811371 },
13821372
1373 .zero,
1374 .one,
1375 .int_u64,
1376 .int_i64,
1377 .int_big_positive,
1378 .int_big_negative,
1379 .variable,
1380 .extern_fn,
1381 .function,
1382 => return null,
1383
13831384 else => unreachable,
13841385 };
1386 if (sub_val.tag() == .variable) {
1387 // This would be loading a runtime value at compile-time so we return
1388 // the indicator that this pointer dereference requires being done at runtime.
1389 return null;
1390 }
1391 return sub_val;
13851392 }
13861393
13871394 pub fn sliceLen(val: Value) u64 {
......@@ -1390,7 +1397,6 @@ pub const Value = extern union {
13901397 .bytes => val.castTag(.bytes).?.data.len,
13911398 .array => val.castTag(.array).?.data.len,
13921399 .slice => val.castTag(.slice).?.data.len.toUnsignedInt(),
1393 .ref_val => sliceLen(val.castTag(.ref_val).?.data),
13941400 .decl_ref => {
13951401 const decl = val.castTag(.decl_ref).?.data;
13961402 if (decl.ty.zigTypeTag() == .Array) {
......@@ -1576,7 +1582,6 @@ pub const Value = extern union {
15761582 .int_i64,
15771583 .int_big_positive,
15781584 .int_big_negative,
1579 .ref_val,
15801585 .comptime_alloc,
15811586 .decl_ref,
15821587 .elem_ptr,
......@@ -1599,6 +1604,7 @@ pub const Value = extern union {
15991604 .@"union",
16001605 .null_value,
16011606 .abi_align_default,
1607 .eu_payload_ptr,
16021608 => false,
16031609
16041610 .undef => unreachable,
test/cases.zig+3-2
......@@ -1182,10 +1182,11 @@ pub fn addCases(ctx: *TestContext) !void {
11821182 var case = ctx.obj("extern variable has no type", linux_x64);
11831183 case.addError(
11841184 \\comptime {
1185 \\ _ = foo;
1185 \\ const x = foo + foo;
1186 \\ _ = x;
11861187 \\}
11871188 \\extern var foo: i32;
1188 , &[_][]const u8{":2:9: error: unable to resolve comptime value"});
1189 , &[_][]const u8{":2:15: error: unable to resolve comptime value"});
11891190 case.addError(
11901191 \\export fn entry() void {
11911192 \\ _ = foo;
test/stage2/cbe.zig+1-1
......@@ -49,7 +49,7 @@ pub fn addCases(ctx: *TestContext) !void {
4949 \\export fn foo() callconv(y) c_int {
5050 \\ return 0;
5151 \\}
52 \\var y: i32 = 1234;
52 \\var y: @import("std").builtin.CallingConvention = .C;
5353 , &.{
5454 ":2:22: error: unable to resolve comptime value",
5555 ":5:26: error: unable to resolve comptime value",