authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2022-04-19 21:51:08-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2022-04-20 17:37:35-07:00
logf7596ae9423e9de8276629803147e1a243f2177b
treeb97f2a8e8fdb84a118f587bcbfd76918710587dd
parent4f527e5d36f66a83ff6a263a03f16e2c4d049f1e

stage2: use indexes for Decl objects

Rather than allocating Decl objects with an Allocator, we instead allocate them with a SegmentedList. This provides four advantages: * Stable memory so that one thread can access a Decl object while another thread allocates additional Decl objects from this list. * It allows us to use u32 indexes to reference Decl objects rather than pointers, saving memory in Type, Value, and dependency sets. * Using integers to reference Decl objects rather than pointers makes serialization trivial. * It provides a unique integer to be used for anonymous symbol names, avoiding multi-threaded contention on an atomic counter.

31 files changed, 2586 insertions(+), 2183 deletions(-)

lib/std/segmented_list.zig+18
......@@ -148,6 +148,24 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type
148148 return result;
149149 }
150150
151 /// Reduce length to `new_len`.
152 /// Invalidates pointers for the elements at index new_len and beyond.
153 pub fn shrinkRetainingCapacity(self: *Self, new_len: usize) void {
154 assert(new_len <= self.len);
155 self.len = new_len;
156 }
157
158 /// Invalidates all element pointers.
159 pub fn clearRetainingCapacity(self: *Self) void {
160 self.items.len = 0;
161 }
162
163 /// Invalidates all element pointers.
164 pub fn clearAndFree(self: *Self, allocator: Allocator) void {
165 self.setCapacity(allocator, 0) catch unreachable;
166 self.items.len = 0;
167 }
168
151169 /// Grows or shrinks capacity to match usage.
152170 /// TODO update this and related methods to match the conventions set by ArrayList
153171 pub fn setCapacity(self: *Self, allocator: Allocator, new_capacity: usize) Allocator.Error!void {
src/Compilation.zig+120-103
......@@ -191,22 +191,22 @@ pub const CSourceFile = struct {
191191
192192const Job = union(enum) {
193193 /// Write the constant value for a Decl to the output file.
194 codegen_decl: *Module.Decl,
194 codegen_decl: Module.Decl.Index,
195195 /// Write the machine code for a function to the output file.
196196 codegen_func: *Module.Fn,
197197 /// Render the .h file snippet for the Decl.
198 emit_h_decl: *Module.Decl,
198 emit_h_decl: Module.Decl.Index,
199199 /// The Decl needs to be analyzed and possibly export itself.
200200 /// It may have already be analyzed, or it may have been determined
201201 /// to be outdated; in this case perform semantic analysis again.
202 analyze_decl: *Module.Decl,
202 analyze_decl: Module.Decl.Index,
203203 /// The file that was loaded with `@embedFile` has changed on disk
204204 /// and has been re-loaded into memory. All Decls that depend on it
205205 /// need to be re-analyzed.
206206 update_embed_file: *Module.EmbedFile,
207207 /// The source file containing the Decl has been updated, and so the
208208 /// Decl may need its line number information updated in the debug info.
209 update_line_number: *Module.Decl,
209 update_line_number: Module.Decl.Index,
210210 /// The main source file for the package needs to be analyzed.
211211 analyze_pkg: *Package,
212212
......@@ -2105,17 +2105,18 @@ pub fn update(comp: *Compilation) !void {
21052105 // deletion set may grow as we call `clearDecl` within this loop,
21062106 // and more unreferenced Decls are revealed.
21072107 while (module.deletion_set.count() != 0) {
2108 const decl = module.deletion_set.keys()[0];
2108 const decl_index = module.deletion_set.keys()[0];
2109 const decl = module.declPtr(decl_index);
21092110 assert(decl.deletion_flag);
21102111 assert(decl.dependants.count() == 0);
21112112 const is_anon = if (decl.zir_decl_index == 0) blk: {
2112 break :blk decl.src_namespace.anon_decls.swapRemove(decl);
2113 break :blk decl.src_namespace.anon_decls.swapRemove(decl_index);
21132114 } else false;
21142115
2115 try module.clearDecl(decl, null);
2116 try module.clearDecl(decl_index, null);
21162117
21172118 if (is_anon) {
2118 decl.destroy(module);
2119 module.destroyDecl(decl_index);
21192120 }
21202121 }
21212122
......@@ -2444,13 +2445,15 @@ pub fn totalErrorCount(self: *Compilation) usize {
24442445 // the previous parse success, including compile errors, but we cannot
24452446 // emit them until the file succeeds parsing.
24462447 for (module.failed_decls.keys()) |key| {
2447 if (key.getFileScope().okToReportErrors()) {
2448 const decl = module.declPtr(key);
2449 if (decl.getFileScope().okToReportErrors()) {
24482450 total += 1;
24492451 }
24502452 }
24512453 if (module.emit_h) |emit_h| {
24522454 for (emit_h.failed_decls.keys()) |key| {
2453 if (key.getFileScope().okToReportErrors()) {
2455 const decl = module.declPtr(key);
2456 if (decl.getFileScope().okToReportErrors()) {
24542457 total += 1;
24552458 }
24562459 }
......@@ -2529,9 +2532,10 @@ pub fn getAllErrorsAlloc(self: *Compilation) !AllErrors {
25292532 {
25302533 var it = module.failed_decls.iterator();
25312534 while (it.next()) |entry| {
2535 const decl = module.declPtr(entry.key_ptr.*);
25322536 // Skip errors for Decls within files that had a parse failure.
25332537 // We'll try again once parsing succeeds.
2534 if (entry.key_ptr.*.getFileScope().okToReportErrors()) {
2538 if (decl.getFileScope().okToReportErrors()) {
25352539 try AllErrors.add(module, &arena, &errors, entry.value_ptr.*.*);
25362540 }
25372541 }
......@@ -2539,9 +2543,10 @@ pub fn getAllErrorsAlloc(self: *Compilation) !AllErrors {
25392543 if (module.emit_h) |emit_h| {
25402544 var it = emit_h.failed_decls.iterator();
25412545 while (it.next()) |entry| {
2546 const decl = module.declPtr(entry.key_ptr.*);
25422547 // Skip errors for Decls within files that had a parse failure.
25432548 // We'll try again once parsing succeeds.
2544 if (entry.key_ptr.*.getFileScope().okToReportErrors()) {
2549 if (decl.getFileScope().okToReportErrors()) {
25452550 try AllErrors.add(module, &arena, &errors, entry.value_ptr.*.*);
25462551 }
25472552 }
......@@ -2564,7 +2569,8 @@ pub fn getAllErrorsAlloc(self: *Compilation) !AllErrors {
25642569 const keys = module.compile_log_decls.keys();
25652570 const values = module.compile_log_decls.values();
25662571 // First one will be the error; subsequent ones will be notes.
2567 const src_loc = keys[0].nodeOffsetSrcLoc(values[0]);
2572 const err_decl = module.declPtr(keys[0]);
2573 const src_loc = err_decl.nodeOffsetSrcLoc(values[0]);
25682574 const err_msg = Module.ErrorMsg{
25692575 .src_loc = src_loc,
25702576 .msg = "found compile log statement",
......@@ -2573,8 +2579,9 @@ pub fn getAllErrorsAlloc(self: *Compilation) !AllErrors {
25732579 defer self.gpa.free(err_msg.notes);
25742580
25752581 for (keys[1..]) |key, i| {
2582 const note_decl = module.declPtr(key);
25762583 err_msg.notes[i] = .{
2577 .src_loc = key.nodeOffsetSrcLoc(values[i + 1]),
2584 .src_loc = note_decl.nodeOffsetSrcLoc(values[i + 1]),
25782585 .msg = "also here",
25792586 };
25802587 }
......@@ -2708,38 +2715,42 @@ pub fn performAllTheWork(
27082715
27092716fn processOneJob(comp: *Compilation, job: Job) !void {
27102717 switch (job) {
2711 .codegen_decl => |decl| switch (decl.analysis) {
2712 .unreferenced => unreachable,
2713 .in_progress => unreachable,
2714 .outdated => unreachable,
2715
2716 .file_failure,
2717 .sema_failure,
2718 .codegen_failure,
2719 .dependency_failure,
2720 .sema_failure_retryable,
2721 => return,
2722
2723 .complete, .codegen_failure_retryable => {
2724 if (build_options.omit_stage2)
2725 @panic("sadly stage2 is omitted from this build to save memory on the CI server");
2726
2727 const named_frame = tracy.namedFrame("codegen_decl");
2728 defer named_frame.end();
2729
2730 const module = comp.bin_file.options.module.?;
2731 assert(decl.has_tv);
2732
2733 if (decl.alive) {
2734 try module.linkerUpdateDecl(decl);
2735 return;
2736 }
2718 .codegen_decl => |decl_index| {
2719 if (build_options.omit_stage2)
2720 @panic("sadly stage2 is omitted from this build to save memory on the CI server");
27372721
2738 // Instead of sending this decl to the linker, we actually will delete it
2739 // because we found out that it in fact was never referenced.
2740 module.deleteUnusedDecl(decl);
2741 return;
2742 },
2722 const module = comp.bin_file.options.module.?;
2723 const decl = module.declPtr(decl_index);
2724
2725 switch (decl.analysis) {
2726 .unreferenced => unreachable,
2727 .in_progress => unreachable,
2728 .outdated => unreachable,
2729
2730 .file_failure,
2731 .sema_failure,
2732 .codegen_failure,
2733 .dependency_failure,
2734 .sema_failure_retryable,
2735 => return,
2736
2737 .complete, .codegen_failure_retryable => {
2738 const named_frame = tracy.namedFrame("codegen_decl");
2739 defer named_frame.end();
2740
2741 assert(decl.has_tv);
2742
2743 if (decl.alive) {
2744 try module.linkerUpdateDecl(decl_index);
2745 return;
2746 }
2747
2748 // Instead of sending this decl to the linker, we actually will delete it
2749 // because we found out that it in fact was never referenced.
2750 module.deleteUnusedDecl(decl_index);
2751 return;
2752 },
2753 }
27432754 },
27442755 .codegen_func => |func| {
27452756 if (build_options.omit_stage2)
......@@ -2754,68 +2765,73 @@ fn processOneJob(comp: *Compilation, job: Job) !void {
27542765 error.AnalysisFail => return,
27552766 };
27562767 },
2757 .emit_h_decl => |decl| switch (decl.analysis) {
2758 .unreferenced => unreachable,
2759 .in_progress => unreachable,
2760 .outdated => unreachable,
2761
2762 .file_failure,
2763 .sema_failure,
2764 .dependency_failure,
2765 .sema_failure_retryable,
2766 => return,
2767
2768 // emit-h only requires semantic analysis of the Decl to be complete,
2769 // it does not depend on machine code generation to succeed.
2770 .codegen_failure, .codegen_failure_retryable, .complete => {
2771 if (build_options.omit_stage2)
2772 @panic("sadly stage2 is omitted from this build to save memory on the CI server");
2773
2774 const named_frame = tracy.namedFrame("emit_h_decl");
2775 defer named_frame.end();
2776
2777 const gpa = comp.gpa;
2778 const module = comp.bin_file.options.module.?;
2779 const emit_h = module.emit_h.?;
2780 _ = try emit_h.decl_table.getOrPut(gpa, decl);
2781 const decl_emit_h = decl.getEmitH(module);
2782 const fwd_decl = &decl_emit_h.fwd_decl;
2783 fwd_decl.shrinkRetainingCapacity(0);
2784 var typedefs_arena = std.heap.ArenaAllocator.init(gpa);
2785 defer typedefs_arena.deinit();
2786
2787 var dg: c_codegen.DeclGen = .{
2788 .gpa = gpa,
2789 .module = module,
2790 .error_msg = null,
2791 .decl = decl,
2792 .fwd_decl = fwd_decl.toManaged(gpa),
2793 .typedefs = c_codegen.TypedefMap.initContext(gpa, .{
2794 .target = comp.getTarget(),
2795 }),
2796 .typedefs_arena = typedefs_arena.allocator(),
2797 };
2798 defer dg.fwd_decl.deinit();
2799 defer dg.typedefs.deinit();
2768 .emit_h_decl => |decl_index| {
2769 if (build_options.omit_stage2)
2770 @panic("sadly stage2 is omitted from this build to save memory on the CI server");
28002771
2801 c_codegen.genHeader(&dg) catch |err| switch (err) {
2802 error.AnalysisFail => {
2803 try emit_h.failed_decls.put(gpa, decl, dg.error_msg.?);
2804 return;
2805 },
2806 else => |e| return e,
2807 };
2772 const module = comp.bin_file.options.module.?;
2773 const decl = module.declPtr(decl_index);
2774
2775 switch (decl.analysis) {
2776 .unreferenced => unreachable,
2777 .in_progress => unreachable,
2778 .outdated => unreachable,
2779
2780 .file_failure,
2781 .sema_failure,
2782 .dependency_failure,
2783 .sema_failure_retryable,
2784 => return,
2785
2786 // emit-h only requires semantic analysis of the Decl to be complete,
2787 // it does not depend on machine code generation to succeed.
2788 .codegen_failure, .codegen_failure_retryable, .complete => {
2789 const named_frame = tracy.namedFrame("emit_h_decl");
2790 defer named_frame.end();
2791
2792 const gpa = comp.gpa;
2793 const emit_h = module.emit_h.?;
2794 _ = try emit_h.decl_table.getOrPut(gpa, decl_index);
2795 const decl_emit_h = emit_h.declPtr(decl_index);
2796 const fwd_decl = &decl_emit_h.fwd_decl;
2797 fwd_decl.shrinkRetainingCapacity(0);
2798 var typedefs_arena = std.heap.ArenaAllocator.init(gpa);
2799 defer typedefs_arena.deinit();
2800
2801 var dg: c_codegen.DeclGen = .{
2802 .gpa = gpa,
2803 .module = module,
2804 .error_msg = null,
2805 .decl_index = decl_index,
2806 .decl = decl,
2807 .fwd_decl = fwd_decl.toManaged(gpa),
2808 .typedefs = c_codegen.TypedefMap.initContext(gpa, .{
2809 .mod = module,
2810 }),
2811 .typedefs_arena = typedefs_arena.allocator(),
2812 };
2813 defer dg.fwd_decl.deinit();
2814 defer dg.typedefs.deinit();
28082815
2809 fwd_decl.* = dg.fwd_decl.moveToUnmanaged();
2810 fwd_decl.shrinkAndFree(gpa, fwd_decl.items.len);
2811 },
2816 c_codegen.genHeader(&dg) catch |err| switch (err) {
2817 error.AnalysisFail => {
2818 try emit_h.failed_decls.put(gpa, decl_index, dg.error_msg.?);
2819 return;
2820 },
2821 else => |e| return e,
2822 };
2823
2824 fwd_decl.* = dg.fwd_decl.moveToUnmanaged();
2825 fwd_decl.shrinkAndFree(gpa, fwd_decl.items.len);
2826 },
2827 }
28122828 },
2813 .analyze_decl => |decl| {
2829 .analyze_decl => |decl_index| {
28142830 if (build_options.omit_stage2)
28152831 @panic("sadly stage2 is omitted from this build to save memory on the CI server");
28162832
28172833 const module = comp.bin_file.options.module.?;
2818 module.ensureDeclAnalyzed(decl) catch |err| switch (err) {
2834 module.ensureDeclAnalyzed(decl_index) catch |err| switch (err) {
28192835 error.OutOfMemory => return error.OutOfMemory,
28202836 error.AnalysisFail => return,
28212837 };
......@@ -2833,7 +2849,7 @@ fn processOneJob(comp: *Compilation, job: Job) !void {
28332849 error.AnalysisFail => return,
28342850 };
28352851 },
2836 .update_line_number => |decl| {
2852 .update_line_number => |decl_index| {
28372853 if (build_options.omit_stage2)
28382854 @panic("sadly stage2 is omitted from this build to save memory on the CI server");
28392855
......@@ -2842,9 +2858,10 @@ fn processOneJob(comp: *Compilation, job: Job) !void {
28422858
28432859 const gpa = comp.gpa;
28442860 const module = comp.bin_file.options.module.?;
2861 const decl = module.declPtr(decl_index);
28452862 comp.bin_file.updateDeclLineNumber(module, decl) catch |err| {
28462863 try module.failed_decls.ensureUnusedCapacity(gpa, 1);
2847 module.failed_decls.putAssumeCapacityNoClobber(decl, try Module.ErrorMsg.create(
2864 module.failed_decls.putAssumeCapacityNoClobber(decl_index, try Module.ErrorMsg.create(
28482865 gpa,
28492866 decl.srcLoc(),
28502867 "unable to update line number: {s}",
......@@ -3472,7 +3489,7 @@ fn reportRetryableEmbedFileError(
34723489 const mod = comp.bin_file.options.module.?;
34733490 const gpa = mod.gpa;
34743491
3475 const src_loc: Module.SrcLoc = embed_file.owner_decl.srcLoc();
3492 const src_loc: Module.SrcLoc = mod.declPtr(embed_file.owner_decl).srcLoc();
34763493
34773494 const err_msg = if (embed_file.pkg.root_src_directory.path) |dir_path|
34783495 try Module.ErrorMsg.create(
src/Module.zig+529-381
......@@ -49,15 +49,15 @@ global_zir_cache: Compilation.Directory,
4949/// Used by AstGen worker to load and store ZIR cache.
5050local_zir_cache: Compilation.Directory,
5151/// It's rare for a decl to be exported, so we save memory by having a sparse
52/// map of Decl pointers to details about them being exported.
52/// map of Decl indexes to details about them being exported.
5353/// The Export memory is owned by the `export_owners` table; the slice itself
5454/// is owned by this table. The slice is guaranteed to not be empty.
55decl_exports: std.AutoArrayHashMapUnmanaged(*Decl, []*Export) = .{},
55decl_exports: std.AutoArrayHashMapUnmanaged(Decl.Index, []*Export) = .{},
5656/// This models the Decls that perform exports, so that `decl_exports` can be updated when a Decl
5757/// is modified. Note that the key of this table is not the Decl being exported, but the Decl that
5858/// is performing the export of another Decl.
5959/// This table owns the Export memory.
60export_owners: std.AutoArrayHashMapUnmanaged(*Decl, []*Export) = .{},
60export_owners: std.AutoArrayHashMapUnmanaged(Decl.Index, []*Export) = .{},
6161/// The set of all the Zig source files in the Module. We keep track of this in order
6262/// to iterate over it and check which source files have been modified on the file system when
6363/// an update is requested, as well as to cache `@import` results.
......@@ -89,10 +89,10 @@ align_stack_fns: std.AutoHashMapUnmanaged(*const Fn, SetAlignStack) = .{},
8989/// The ErrorMsg memory is owned by the decl, using Module's general purpose allocator.
9090/// Note that a Decl can succeed but the Fn it represents can fail. In this case,
9191/// a Decl can have a failed_decls entry but have analysis status of success.
92failed_decls: std.AutoArrayHashMapUnmanaged(*Decl, *ErrorMsg) = .{},
92failed_decls: std.AutoArrayHashMapUnmanaged(Decl.Index, *ErrorMsg) = .{},
9393/// Keep track of one `@compileLog` callsite per owner Decl.
9494/// The value is the AST node index offset from the Decl.
95compile_log_decls: std.AutoArrayHashMapUnmanaged(*Decl, i32) = .{},
95compile_log_decls: std.AutoArrayHashMapUnmanaged(Decl.Index, i32) = .{},
9696/// Using a map here for consistency with the other fields here.
9797/// The ErrorMsg memory is owned by the `File`, using Module's general purpose allocator.
9898failed_files: std.AutoArrayHashMapUnmanaged(*File, ?*ErrorMsg) = .{},
......@@ -102,11 +102,9 @@ failed_embed_files: std.AutoArrayHashMapUnmanaged(*EmbedFile, *ErrorMsg) = .{},
102102/// The ErrorMsg memory is owned by the `Export`, using Module's general purpose allocator.
103103failed_exports: std.AutoArrayHashMapUnmanaged(*Export, *ErrorMsg) = .{},
104104
105next_anon_name_index: usize = 0,
106
107105/// Candidates for deletion. After a semantic analysis update completes, this list
108106/// contains Decls that need to be deleted if they end up having no references to them.
109deletion_set: std.AutoArrayHashMapUnmanaged(*Decl, void) = .{},
107deletion_set: std.AutoArrayHashMapUnmanaged(Decl.Index, void) = .{},
110108
111109/// Error tags and their values, tag names are duped with mod.gpa.
112110/// Corresponds with `error_name_list`.
......@@ -137,7 +135,21 @@ compile_log_text: ArrayListUnmanaged(u8) = .{},
137135
138136emit_h: ?*GlobalEmitH,
139137
140test_functions: std.AutoArrayHashMapUnmanaged(*Decl, void) = .{},
138test_functions: std.AutoArrayHashMapUnmanaged(Decl.Index, void) = .{},
139
140/// Rather than allocating Decl objects with an Allocator, we instead allocate
141/// them with this SegmentedList. This provides four advantages:
142/// * Stable memory so that one thread can access a Decl object while another
143/// thread allocates additional Decl objects from this list.
144/// * It allows us to use u32 indexes to reference Decl objects rather than
145/// pointers, saving memory in Type, Value, and dependency sets.
146/// * Using integers to reference Decl objects rather than pointers makes
147/// serialization trivial.
148/// * It provides a unique integer to be used for anonymous symbol names, avoiding
149/// multi-threaded contention on an atomic counter.
150allocated_decls: std.SegmentedList(Decl, 0) = .{},
151/// When a Decl object is freed from `allocated_decls`, it is pushed into this stack.
152decls_free_list: std.ArrayListUnmanaged(Decl.Index) = .{},
141153
142154const MonomorphedFuncsSet = std.HashMapUnmanaged(
143155 *Fn,
......@@ -173,7 +185,7 @@ pub const MemoizedCallSet = std.HashMapUnmanaged(
173185);
174186
175187pub const MemoizedCall = struct {
176 target: std.Target,
188 module: *Module,
177189
178190 pub const Key = struct {
179191 func: *Fn,
......@@ -191,7 +203,7 @@ pub const MemoizedCall = struct {
191203 assert(a.args.len == b.args.len);
192204 for (a.args) |a_arg, arg_i| {
193205 const b_arg = b.args[arg_i];
194 if (!a_arg.eql(b_arg, ctx.target)) {
206 if (!a_arg.eql(b_arg, ctx.module)) {
195207 return false;
196208 }
197209 }
......@@ -210,7 +222,7 @@ pub const MemoizedCall = struct {
210222 // This logic must be kept in sync with the logic in `analyzeCall` that
211223 // computes the hash.
212224 for (key.args) |arg| {
213 arg.hash(&hasher, ctx.target);
225 arg.hash(&hasher, ctx.module);
214226 }
215227
216228 return hasher.final();
......@@ -231,9 +243,17 @@ pub const GlobalEmitH = struct {
231243 /// When emit_h is non-null, each Decl gets one more compile error slot for
232244 /// emit-h failing for that Decl. This table is also how we tell if a Decl has
233245 /// failed emit-h or succeeded.
234 failed_decls: std.AutoArrayHashMapUnmanaged(*Decl, *ErrorMsg) = .{},
246 failed_decls: std.AutoArrayHashMapUnmanaged(Decl.Index, *ErrorMsg) = .{},
235247 /// Tracks all decls in order to iterate over them and emit .h code for them.
236 decl_table: std.AutoArrayHashMapUnmanaged(*Decl, void) = .{},
248 decl_table: std.AutoArrayHashMapUnmanaged(Decl.Index, void) = .{},
249 /// Similar to the allocated_decls field of Module, this is where `EmitH` objects
250 /// are allocated. There will be exactly one EmitH object per Decl object, with
251 /// identical indexes.
252 allocated_emit_h: std.SegmentedList(EmitH, 0) = .{},
253
254 pub fn declPtr(global_emit_h: *GlobalEmitH, decl_index: Decl.Index) *EmitH {
255 return global_emit_h.allocated_emit_h.at(@enumToInt(decl_index));
256 }
237257};
238258
239259pub const ErrorInt = u32;
......@@ -244,12 +264,12 @@ pub const Export = struct {
244264 /// Represents the position of the export, if any, in the output file.
245265 link: link.File.Export,
246266 /// The Decl that performs the export. Note that this is *not* the Decl being exported.
247 owner_decl: *Decl,
267 owner_decl: Decl.Index,
248268 /// The Decl containing the export statement. Inline function calls
249269 /// may cause this to be different from the owner_decl.
250 src_decl: *Decl,
270 src_decl: Decl.Index,
251271 /// The Decl being exported. Note this is *not* the Decl performing the export.
252 exported_decl: *Decl,
272 exported_decl: Decl.Index,
253273 status: enum {
254274 in_progress,
255275 failed,
......@@ -259,22 +279,16 @@ pub const Export = struct {
259279 complete,
260280 },
261281
262 pub fn getSrcLoc(exp: Export) SrcLoc {
282 pub fn getSrcLoc(exp: Export, mod: *Module) SrcLoc {
283 const src_decl = mod.declPtr(exp.src_decl);
263284 return .{
264 .file_scope = exp.src_decl.getFileScope(),
265 .parent_decl_node = exp.src_decl.src_node,
285 .file_scope = src_decl.getFileScope(),
286 .parent_decl_node = src_decl.src_node,
266287 .lazy = exp.src,
267288 };
268289 }
269290};
270291
271/// When Module emit_h field is non-null, each Decl is allocated via this struct, so that
272/// there can be EmitH state attached to each Decl.
273pub const DeclPlusEmitH = struct {
274 decl: Decl,
275 emit_h: EmitH,
276};
277
278292pub const CaptureScope = struct {
279293 parent: ?*CaptureScope,
280294
......@@ -458,36 +472,33 @@ pub const Decl = struct {
458472 /// typed_value may need to be regenerated.
459473 dependencies: DepsTable = .{},
460474
461 pub const DepsTable = std.AutoArrayHashMapUnmanaged(*Decl, void);
462
463 pub fn clearName(decl: *Decl, gpa: Allocator) void {
464 gpa.free(mem.sliceTo(decl.name, 0));
465 decl.name = undefined;
466 }
475 pub const Index = enum(u32) {
476 _,
467477
468 pub fn destroy(decl: *Decl, module: *Module) void {
469 const gpa = module.gpa;
470 log.debug("destroy {*} ({s})", .{ decl, decl.name });
471 _ = module.test_functions.swapRemove(decl);
472 if (decl.deletion_flag) {
473 assert(module.deletion_set.swapRemove(decl));
478 pub fn toOptional(i: Index) OptionalIndex {
479 return @intToEnum(OptionalIndex, @enumToInt(i));
474480 }
475 if (decl.has_tv) {
476 if (decl.getInnerNamespace()) |namespace| {
477 namespace.destroyDecls(module);
478 }
479 decl.clearValues(gpa);
481 };
482
483 pub const OptionalIndex = enum(u32) {
484 none = std.math.maxInt(u32),
485 _,
486
487 pub fn init(oi: ?Index) OptionalIndex {
488 return oi orelse .none;
480489 }
481 decl.dependants.deinit(gpa);
482 decl.dependencies.deinit(gpa);
483 decl.clearName(gpa);
484 if (module.emit_h != null) {
485 const decl_plus_emit_h = @fieldParentPtr(DeclPlusEmitH, "decl", decl);
486 decl_plus_emit_h.emit_h.fwd_decl.deinit(gpa);
487 gpa.destroy(decl_plus_emit_h);
488 } else {
489 gpa.destroy(decl);
490
491 pub fn unwrap(oi: OptionalIndex) ?Index {
492 if (oi == .none) return null;
493 return @intToEnum(Index, @enumToInt(oi));
490494 }
495 };
496
497 pub const DepsTable = std.AutoArrayHashMapUnmanaged(Decl.Index, void);
498
499 pub fn clearName(decl: *Decl, gpa: Allocator) void {
500 gpa.free(mem.sliceTo(decl.name, 0));
501 decl.name = undefined;
491502 }
492503
493504 pub fn clearValues(decl: *Decl, gpa: Allocator) void {
......@@ -573,13 +584,6 @@ pub const Decl = struct {
573584 return @intToEnum(Zir.Inst.Ref, zir.extra[extra_index]);
574585 }
575586
576 /// Returns true if and only if the Decl is the top level struct associated with a File.
577 pub fn isRoot(decl: *const Decl) bool {
578 if (decl.src_namespace.parent != null)
579 return false;
580 return decl == decl.src_namespace.getDecl();
581 }
582
583587 pub fn relativeToLine(decl: Decl, offset: u32) u32 {
584588 return decl.src_line + offset;
585589 }
......@@ -622,20 +626,20 @@ pub const Decl = struct {
622626 return tree.tokens.items(.start)[decl.srcToken()];
623627 }
624628
625 pub fn renderFullyQualifiedName(decl: Decl, writer: anytype) !void {
629 pub fn renderFullyQualifiedName(decl: Decl, mod: *Module, writer: anytype) !void {
626630 const unqualified_name = mem.sliceTo(decl.name, 0);
627 return decl.src_namespace.renderFullyQualifiedName(unqualified_name, writer);
631 return decl.src_namespace.renderFullyQualifiedName(mod, unqualified_name, writer);
628632 }
629633
630 pub fn renderFullyQualifiedDebugName(decl: Decl, writer: anytype) !void {
634 pub fn renderFullyQualifiedDebugName(decl: Decl, mod: *Module, writer: anytype) !void {
631635 const unqualified_name = mem.sliceTo(decl.name, 0);
632 return decl.src_namespace.renderFullyQualifiedDebugName(unqualified_name, writer);
636 return decl.src_namespace.renderFullyQualifiedDebugName(mod, unqualified_name, writer);
633637 }
634638
635 pub fn getFullyQualifiedName(decl: Decl, gpa: Allocator) ![:0]u8 {
636 var buffer = std.ArrayList(u8).init(gpa);
639 pub fn getFullyQualifiedName(decl: Decl, mod: *Module) ![:0]u8 {
640 var buffer = std.ArrayList(u8).init(mod.gpa);
637641 defer buffer.deinit();
638 try decl.renderFullyQualifiedName(buffer.writer());
642 try decl.renderFullyQualifiedName(mod, buffer.writer());
639643 return buffer.toOwnedSliceSentinel(0);
640644 }
641645
......@@ -662,7 +666,6 @@ pub const Decl = struct {
662666 if (!decl.owns_tv) return null;
663667 const ty = (decl.val.castTag(.ty) orelse return null).data;
664668 const struct_obj = (ty.castTag(.@"struct") orelse return null).data;
665 assert(struct_obj.owner_decl == decl);
666669 return struct_obj;
667670 }
668671
......@@ -672,7 +675,6 @@ pub const Decl = struct {
672675 if (!decl.owns_tv) return null;
673676 const ty = (decl.val.castTag(.ty) orelse return null).data;
674677 const union_obj = (ty.cast(Type.Payload.Union) orelse return null).data;
675 assert(union_obj.owner_decl == decl);
676678 return union_obj;
677679 }
678680
......@@ -681,7 +683,6 @@ pub const Decl = struct {
681683 pub fn getFunction(decl: *const Decl) ?*Fn {
682684 if (!decl.owns_tv) return null;
683685 const func = (decl.val.castTag(.function) orelse return null).data;
684 assert(func.owner_decl == decl);
685686 return func;
686687 }
687688
......@@ -690,16 +691,14 @@ pub const Decl = struct {
690691 pub fn getExternFn(decl: *const Decl) ?*ExternFn {
691692 if (!decl.owns_tv) return null;
692693 const extern_fn = (decl.val.castTag(.extern_fn) orelse return null).data;
693 assert(extern_fn.owner_decl == decl);
694694 return extern_fn;
695695 }
696696
697697 /// If the Decl has a value and it is a variable, returns it,
698698 /// otherwise null.
699 pub fn getVariable(decl: *Decl) ?*Var {
699 pub fn getVariable(decl: *const Decl) ?*Var {
700700 if (!decl.owns_tv) return null;
701701 const variable = (decl.val.castTag(.variable) orelse return null).data;
702 assert(variable.owner_decl == decl);
703702 return variable;
704703 }
705704
......@@ -712,12 +711,10 @@ pub const Decl = struct {
712711 switch (ty.tag()) {
713712 .@"struct" => {
714713 const struct_obj = ty.castTag(.@"struct").?.data;
715 assert(struct_obj.owner_decl == decl);
716714 return &struct_obj.namespace;
717715 },
718716 .enum_full, .enum_nonexhaustive => {
719717 const enum_obj = ty.cast(Type.Payload.EnumFull).?.data;
720 assert(enum_obj.owner_decl == decl);
721718 return &enum_obj.namespace;
722719 },
723720 .empty_struct => {
......@@ -725,12 +722,10 @@ pub const Decl = struct {
725722 },
726723 .@"opaque" => {
727724 const opaque_obj = ty.cast(Type.Payload.Opaque).?.data;
728 assert(opaque_obj.owner_decl == decl);
729725 return &opaque_obj.namespace;
730726 },
731727 .@"union", .union_tagged => {
732728 const union_obj = ty.cast(Type.Payload.Union).?.data;
733 assert(union_obj.owner_decl == decl);
734729 return &union_obj.namespace;
735730 },
736731
......@@ -757,17 +752,11 @@ pub const Decl = struct {
757752 return decl.src_namespace.file_scope;
758753 }
759754
760 pub fn getEmitH(decl: *Decl, module: *Module) *EmitH {
761 assert(module.emit_h != null);
762 const decl_plus_emit_h = @fieldParentPtr(DeclPlusEmitH, "decl", decl);
763 return &decl_plus_emit_h.emit_h;
764 }
765
766 pub fn removeDependant(decl: *Decl, other: *Decl) void {
755 pub fn removeDependant(decl: *Decl, other: Decl.Index) void {
767756 assert(decl.dependants.swapRemove(other));
768757 }
769758
770 pub fn removeDependency(decl: *Decl, other: *Decl) void {
759 pub fn removeDependency(decl: *Decl, other: Decl.Index) void {
771760 assert(decl.dependencies.swapRemove(other));
772761 }
773762
......@@ -790,16 +779,6 @@ pub const Decl = struct {
790779 return decl.ty.abiAlignment(target);
791780 }
792781 }
793
794 pub fn markAlive(decl: *Decl) void {
795 if (decl.alive) return;
796 decl.alive = true;
797
798 // This is the first time we are marking this Decl alive. We must
799 // therefore recurse into its value and mark any Decl it references
800 // as also alive, so that any Decl referenced does not get garbage collected.
801 decl.val.markReferencedDeclsAlive();
802 }
803782};
804783
805784/// This state is attached to every Decl when Module emit_h is non-null.
......@@ -810,7 +789,7 @@ pub const EmitH = struct {
810789/// Represents the data that an explicit error set syntax provides.
811790pub const ErrorSet = struct {
812791 /// The Decl that corresponds to the error set itself.
813 owner_decl: *Decl,
792 owner_decl: Decl.Index,
814793 /// Offset from Decl node index, points to the error set AST node.
815794 node_offset: i32,
816795 /// The string bytes are stored in the owner Decl arena.
......@@ -819,10 +798,11 @@ pub const ErrorSet = struct {
819798
820799 pub const NameMap = std.StringArrayHashMapUnmanaged(void);
821800
822 pub fn srcLoc(self: ErrorSet) SrcLoc {
801 pub fn srcLoc(self: ErrorSet, mod: *Module) SrcLoc {
802 const owner_decl = mod.declPtr(self.owner_decl);
823803 return .{
824 .file_scope = self.owner_decl.getFileScope(),
825 .parent_decl_node = self.owner_decl.src_node,
804 .file_scope = owner_decl.getFileScope(),
805 .parent_decl_node = owner_decl.src_node,
826806 .lazy = .{ .node_offset = self.node_offset },
827807 };
828808 }
......@@ -844,12 +824,12 @@ pub const PropertyBoolean = enum { no, yes, unknown, wip };
844824
845825/// Represents the data that a struct declaration provides.
846826pub const Struct = struct {
847 /// The Decl that corresponds to the struct itself.
848 owner_decl: *Decl,
849827 /// Set of field names in declaration order.
850828 fields: Fields,
851829 /// Represents the declarations inside this struct.
852830 namespace: Namespace,
831 /// The Decl that corresponds to the struct itself.
832 owner_decl: Decl.Index,
853833 /// Offset from `owner_decl`, points to the struct AST node.
854834 node_offset: i32,
855835 /// Index of the struct_decl ZIR instruction.
......@@ -900,30 +880,32 @@ pub const Struct = struct {
900880 }
901881 };
902882
903 pub fn getFullyQualifiedName(s: *Struct, gpa: Allocator) ![:0]u8 {
904 return s.owner_decl.getFullyQualifiedName(gpa);
883 pub fn getFullyQualifiedName(s: *Struct, mod: *Module) ![:0]u8 {
884 return mod.declPtr(s.owner_decl).getFullyQualifiedName(mod);
905885 }
906886
907 pub fn srcLoc(s: Struct) SrcLoc {
887 pub fn srcLoc(s: Struct, mod: *Module) SrcLoc {
888 const owner_decl = mod.declPtr(s.owner_decl);
908889 return .{
909 .file_scope = s.owner_decl.getFileScope(),
910 .parent_decl_node = s.owner_decl.src_node,
890 .file_scope = owner_decl.getFileScope(),
891 .parent_decl_node = owner_decl.src_node,
911892 .lazy = .{ .node_offset = s.node_offset },
912893 };
913894 }
914895
915 pub fn fieldSrcLoc(s: Struct, gpa: Allocator, query: FieldSrcQuery) SrcLoc {
896 pub fn fieldSrcLoc(s: Struct, mod: *Module, query: FieldSrcQuery) SrcLoc {
916897 @setCold(true);
917 const tree = s.owner_decl.getFileScope().getTree(gpa) catch |err| {
898 const owner_decl = mod.declPtr(s.owner_decl);
899 const file = owner_decl.getFileScope();
900 const tree = file.getTree(mod.gpa) catch |err| {
918901 // In this case we emit a warning + a less precise source location.
919902 log.warn("unable to load {s}: {s}", .{
920 s.owner_decl.getFileScope().sub_file_path, @errorName(err),
903 file.sub_file_path, @errorName(err),
921904 });
922 return s.srcLoc();
905 return s.srcLoc(mod);
923906 };
924 const node = s.owner_decl.relativeToNodeIndex(s.node_offset);
907 const node = owner_decl.relativeToNodeIndex(s.node_offset);
925908 const node_tags = tree.nodes.items(.tag);
926 const file = s.owner_decl.getFileScope();
927909 switch (node_tags[node]) {
928910 .container_decl,
929911 .container_decl_trailing,
......@@ -1013,18 +995,19 @@ pub const Struct = struct {
1013995/// the number of fields.
1014996pub const EnumSimple = struct {
1015997 /// The Decl that corresponds to the enum itself.
1016 owner_decl: *Decl,
1017 /// Set of field names in declaration order.
1018 fields: NameMap,
998 owner_decl: Decl.Index,
1019999 /// Offset from `owner_decl`, points to the enum decl AST node.
10201000 node_offset: i32,
1001 /// Set of field names in declaration order.
1002 fields: NameMap,
10211003
10221004 pub const NameMap = EnumFull.NameMap;
10231005
1024 pub fn srcLoc(self: EnumSimple) SrcLoc {
1006 pub fn srcLoc(self: EnumSimple, mod: *Module) SrcLoc {
1007 const owner_decl = mod.declPtr(self.owner_decl);
10251008 return .{
1026 .file_scope = self.owner_decl.getFileScope(),
1027 .parent_decl_node = self.owner_decl.src_node,
1009 .file_scope = owner_decl.getFileScope(),
1010 .parent_decl_node = owner_decl.src_node,
10281011 .lazy = .{ .node_offset = self.node_offset },
10291012 };
10301013 }
......@@ -1035,7 +1018,9 @@ pub const EnumSimple = struct {
10351018/// are explicitly provided.
10361019pub const EnumNumbered = struct {
10371020 /// The Decl that corresponds to the enum itself.
1038 owner_decl: *Decl,
1021 owner_decl: Decl.Index,
1022 /// Offset from `owner_decl`, points to the enum decl AST node.
1023 node_offset: i32,
10391024 /// An integer type which is used for the numerical value of the enum.
10401025 /// Whether zig chooses this type or the user specifies it, it is stored here.
10411026 tag_ty: Type,
......@@ -1045,16 +1030,15 @@ pub const EnumNumbered = struct {
10451030 /// Entries are in declaration order, same as `fields`.
10461031 /// If this hash map is empty, it means the enum tags are auto-numbered.
10471032 values: ValueMap,
1048 /// Offset from `owner_decl`, points to the enum decl AST node.
1049 node_offset: i32,
10501033
10511034 pub const NameMap = EnumFull.NameMap;
10521035 pub const ValueMap = EnumFull.ValueMap;
10531036
1054 pub fn srcLoc(self: EnumNumbered) SrcLoc {
1037 pub fn srcLoc(self: EnumNumbered, mod: *Module) SrcLoc {
1038 const owner_decl = mod.declPtr(self.owner_decl);
10551039 return .{
1056 .file_scope = self.owner_decl.getFileScope(),
1057 .parent_decl_node = self.owner_decl.src_node,
1040 .file_scope = owner_decl.getFileScope(),
1041 .parent_decl_node = owner_decl.src_node,
10581042 .lazy = .{ .node_offset = self.node_offset },
10591043 };
10601044 }
......@@ -1064,7 +1048,9 @@ pub const EnumNumbered = struct {
10641048/// at least one tag value explicitly specified, or at least one declaration.
10651049pub const EnumFull = struct {
10661050 /// The Decl that corresponds to the enum itself.
1067 owner_decl: *Decl,
1051 owner_decl: Decl.Index,
1052 /// Offset from `owner_decl`, points to the enum decl AST node.
1053 node_offset: i32,
10681054 /// An integer type which is used for the numerical value of the enum.
10691055 /// Whether zig chooses this type or the user specifies it, it is stored here.
10701056 tag_ty: Type,
......@@ -1076,26 +1062,23 @@ pub const EnumFull = struct {
10761062 values: ValueMap,
10771063 /// Represents the declarations inside this enum.
10781064 namespace: Namespace,
1079 /// Offset from `owner_decl`, points to the enum decl AST node.
1080 node_offset: i32,
10811065 /// true if zig inferred this tag type, false if user specified it
10821066 tag_ty_inferred: bool,
10831067
10841068 pub const NameMap = std.StringArrayHashMapUnmanaged(void);
10851069 pub const ValueMap = std.ArrayHashMapUnmanaged(Value, void, Value.ArrayHashContext, false);
10861070
1087 pub fn srcLoc(self: EnumFull) SrcLoc {
1071 pub fn srcLoc(self: EnumFull, mod: *Module) SrcLoc {
1072 const owner_decl = mod.declPtr(self.owner_decl);
10881073 return .{
1089 .file_scope = self.owner_decl.getFileScope(),
1090 .parent_decl_node = self.owner_decl.src_node,
1074 .file_scope = owner_decl.getFileScope(),
1075 .parent_decl_node = owner_decl.src_node,
10911076 .lazy = .{ .node_offset = self.node_offset },
10921077 };
10931078 }
10941079};
10951080
10961081pub const Union = struct {
1097 /// The Decl that corresponds to the union itself.
1098 owner_decl: *Decl,
10991082 /// An enum type which is used for the tag of the union.
11001083 /// This type is created even for untagged unions, even when the memory
11011084 /// layout does not store the tag.
......@@ -1106,6 +1089,8 @@ pub const Union = struct {
11061089 fields: Fields,
11071090 /// Represents the declarations inside this union.
11081091 namespace: Namespace,
1092 /// The Decl that corresponds to the union itself.
1093 owner_decl: Decl.Index,
11091094 /// Offset from `owner_decl`, points to the union decl AST node.
11101095 node_offset: i32,
11111096 /// Index of the union_decl ZIR instruction.
......@@ -1145,30 +1130,32 @@ pub const Union = struct {
11451130
11461131 pub const Fields = std.StringArrayHashMapUnmanaged(Field);
11471132
1148 pub fn getFullyQualifiedName(s: *Union, gpa: Allocator) ![:0]u8 {
1149 return s.owner_decl.getFullyQualifiedName(gpa);
1133 pub fn getFullyQualifiedName(s: *Union, mod: *Module) ![:0]u8 {
1134 return mod.declPtr(s.owner_decl).getFullyQualifiedName(mod);
11501135 }
11511136
1152 pub fn srcLoc(self: Union) SrcLoc {
1137 pub fn srcLoc(self: Union, mod: *Module) SrcLoc {
1138 const owner_decl = mod.declPtr(self.owner_decl);
11531139 return .{
1154 .file_scope = self.owner_decl.getFileScope(),
1155 .parent_decl_node = self.owner_decl.src_node,
1140 .file_scope = owner_decl.getFileScope(),
1141 .parent_decl_node = owner_decl.src_node,
11561142 .lazy = .{ .node_offset = self.node_offset },
11571143 };
11581144 }
11591145
1160 pub fn fieldSrcLoc(u: Union, gpa: Allocator, query: FieldSrcQuery) SrcLoc {
1146 pub fn fieldSrcLoc(u: Union, mod: *Module, query: FieldSrcQuery) SrcLoc {
11611147 @setCold(true);
1162 const tree = u.owner_decl.getFileScope().getTree(gpa) catch |err| {
1148 const owner_decl = mod.declPtr(u.owner_decl);
1149 const file = owner_decl.getFileScope();
1150 const tree = file.getTree(mod.gpa) catch |err| {
11631151 // In this case we emit a warning + a less precise source location.
11641152 log.warn("unable to load {s}: {s}", .{
1165 u.owner_decl.getFileScope().sub_file_path, @errorName(err),
1153 file.sub_file_path, @errorName(err),
11661154 });
1167 return u.srcLoc();
1155 return u.srcLoc(mod);
11681156 };
1169 const node = u.owner_decl.relativeToNodeIndex(u.node_offset);
1157 const node = owner_decl.relativeToNodeIndex(u.node_offset);
11701158 const node_tags = tree.nodes.items(.tag);
1171 const file = u.owner_decl.getFileScope();
11721159 switch (node_tags[node]) {
11731160 .container_decl,
11741161 .container_decl_trailing,
......@@ -1348,22 +1335,23 @@ pub const Union = struct {
13481335
13491336pub const Opaque = struct {
13501337 /// The Decl that corresponds to the opaque itself.
1351 owner_decl: *Decl,
1352 /// Represents the declarations inside this opaque.
1353 namespace: Namespace,
1338 owner_decl: Decl.Index,
13541339 /// Offset from `owner_decl`, points to the opaque decl AST node.
13551340 node_offset: i32,
1341 /// Represents the declarations inside this opaque.
1342 namespace: Namespace,
13561343
1357 pub fn srcLoc(self: Opaque) SrcLoc {
1344 pub fn srcLoc(self: Opaque, mod: *Module) SrcLoc {
1345 const owner_decl = mod.declPtr(self.owner_decl);
13581346 return .{
1359 .file_scope = self.owner_decl.getFileScope(),
1360 .parent_decl_node = self.owner_decl.src_node,
1347 .file_scope = owner_decl.getFileScope(),
1348 .parent_decl_node = owner_decl.src_node,
13611349 .lazy = .{ .node_offset = self.node_offset },
13621350 };
13631351 }
13641352
1365 pub fn getFullyQualifiedName(s: *Opaque, gpa: Allocator) ![:0]u8 {
1366 return s.owner_decl.getFullyQualifiedName(gpa);
1353 pub fn getFullyQualifiedName(s: *Opaque, mod: *Module) ![:0]u8 {
1354 return mod.declPtr(s.owner_decl).getFullyQualifiedName(mod);
13671355 }
13681356};
13691357
......@@ -1371,7 +1359,7 @@ pub const Opaque = struct {
13711359/// arena allocator.
13721360pub const ExternFn = struct {
13731361 /// The Decl that corresponds to the function itself.
1374 owner_decl: *Decl,
1362 owner_decl: Decl.Index,
13751363 /// Library name if specified.
13761364 /// For example `extern "c" fn write(...) usize` would have 'c' as library name.
13771365 /// Allocated with Module's allocator; outlives the ZIR code.
......@@ -1389,7 +1377,12 @@ pub const ExternFn = struct {
13891377/// instead.
13901378pub const Fn = struct {
13911379 /// The Decl that corresponds to the function itself.
1392 owner_decl: *Decl,
1380 owner_decl: Decl.Index,
1381 /// The ZIR instruction that is a function instruction. Use this to find
1382 /// the body. We store this rather than the body directly so that when ZIR
1383 /// is regenerated on update(), we can map this to the new corresponding
1384 /// ZIR instruction.
1385 zir_body_inst: Zir.Inst.Index,
13931386 /// If this is not null, this function is a generic function instantiation, and
13941387 /// there is a `TypedValue` here for each parameter of the function.
13951388 /// Non-comptime parameters are marked with a `generic_poison` for the value.
......@@ -1403,11 +1396,6 @@ pub const Fn = struct {
14031396 /// parameter and tells whether it is anytype.
14041397 /// TODO apply the same enhancement for param_names below to this field.
14051398 anytype_args: [*]bool,
1406 /// The ZIR instruction that is a function instruction. Use this to find
1407 /// the body. We store this rather than the body directly so that when ZIR
1408 /// is regenerated on update(), we can map this to the new corresponding
1409 /// ZIR instruction.
1410 zir_body_inst: Zir.Inst.Index,
14111399
14121400 /// Prefer to use `getParamName` to access this because of the future improvement
14131401 /// we want to do mentioned in the TODO below.
......@@ -1537,8 +1525,9 @@ pub const Fn = struct {
15371525 return func.param_names[index];
15381526 }
15391527
1540 pub fn hasInferredErrorSet(func: Fn) bool {
1541 const zir = func.owner_decl.getFileScope().zir;
1528 pub fn hasInferredErrorSet(func: Fn, mod: *Module) bool {
1529 const owner_decl = mod.declPtr(func.owner_decl);
1530 const zir = owner_decl.getFileScope().zir;
15421531 const zir_tags = zir.instructions.items(.tag);
15431532 switch (zir_tags[func.zir_body_inst]) {
15441533 .func => return false,
......@@ -1556,7 +1545,7 @@ pub const Fn = struct {
15561545pub const Var = struct {
15571546 /// if is_extern == true this is undefined
15581547 init: Value,
1559 owner_decl: *Decl,
1548 owner_decl: Decl.Index,
15601549
15611550 /// Library name if specified.
15621551 /// For example `extern "c" var stderrp = ...` would have 'c' as library name.
......@@ -1576,14 +1565,16 @@ pub const Var = struct {
15761565};
15771566
15781567pub const DeclAdapter = struct {
1568 mod: *Module,
1569
15791570 pub fn hash(self: @This(), s: []const u8) u32 {
15801571 _ = self;
15811572 return @truncate(u32, std.hash.Wyhash.hash(0, s));
15821573 }
15831574
1584 pub fn eql(self: @This(), a: []const u8, b_decl: *Decl, b_index: usize) bool {
1585 _ = self;
1575 pub fn eql(self: @This(), a: []const u8, b_decl_index: Decl.Index, b_index: usize) bool {
15861576 _ = b_index;
1577 const b_decl = self.mod.declPtr(b_decl_index);
15871578 return mem.eql(u8, a, mem.sliceTo(b_decl.name, 0));
15881579 }
15891580};
......@@ -1599,25 +1590,30 @@ pub const Namespace = struct {
15991590 /// Declaration order is preserved via entry order.
16001591 /// Key memory is owned by `decl.name`.
16011592 /// Anonymous decls are not stored here; they are kept in `anon_decls` instead.
1602 decls: std.ArrayHashMapUnmanaged(*Decl, void, DeclContext, true) = .{},
1593 decls: std.ArrayHashMapUnmanaged(Decl.Index, void, DeclContext, true) = .{},
16031594
1604 anon_decls: std.AutoArrayHashMapUnmanaged(*Decl, void) = .{},
1595 anon_decls: std.AutoArrayHashMapUnmanaged(Decl.Index, void) = .{},
16051596
16061597 /// Key is usingnamespace Decl itself. To find the namespace being included,
16071598 /// the Decl Value has to be resolved as a Type which has a Namespace.
16081599 /// Value is whether the usingnamespace decl is marked `pub`.
1609 usingnamespace_set: std.AutoHashMapUnmanaged(*Decl, bool) = .{},
1600 usingnamespace_set: std.AutoHashMapUnmanaged(Decl.Index, bool) = .{},
16101601
16111602 const DeclContext = struct {
1612 pub fn hash(self: @This(), decl: *Decl) u32 {
1613 _ = self;
1603 module: *Module,
1604
1605 pub fn hash(ctx: @This(), decl_index: Decl.Index) u32 {
1606 const decl = ctx.module.declPtr(decl_index);
16141607 return @truncate(u32, std.hash.Wyhash.hash(0, mem.sliceTo(decl.name, 0)));
16151608 }
16161609
1617 pub fn eql(self: @This(), a: *Decl, b: *Decl, b_index: usize) bool {
1618 _ = self;
1610 pub fn eql(ctx: @This(), a_decl_index: Decl.Index, b_decl_index: Decl.Index, b_index: usize) bool {
16191611 _ = b_index;
1620 return mem.eql(u8, mem.sliceTo(a.name, 0), mem.sliceTo(b.name, 0));
1612 const a_decl = ctx.module.declPtr(a_decl_index);
1613 const b_decl = ctx.module.declPtr(b_decl_index);
1614 const a_name = mem.sliceTo(a_decl.name, 0);
1615 const b_name = mem.sliceTo(b_decl.name, 0);
1616 return mem.eql(u8, a_name, b_name);
16211617 }
16221618 };
16231619
......@@ -1637,13 +1633,13 @@ pub const Namespace = struct {
16371633 var anon_decls = ns.anon_decls;
16381634 ns.anon_decls = .{};
16391635
1640 for (decls.keys()) |decl| {
1641 decl.destroy(mod);
1636 for (decls.keys()) |decl_index| {
1637 mod.destroyDecl(decl_index);
16421638 }
16431639 decls.deinit(gpa);
16441640
16451641 for (anon_decls.keys()) |key| {
1646 key.destroy(mod);
1642 mod.destroyDecl(key);
16471643 }
16481644 anon_decls.deinit(gpa);
16491645 ns.usingnamespace_set.deinit(gpa);
......@@ -1652,7 +1648,7 @@ pub const Namespace = struct {
16521648 pub fn deleteAllDecls(
16531649 ns: *Namespace,
16541650 mod: *Module,
1655 outdated_decls: ?*std.AutoArrayHashMap(*Decl, void),
1651 outdated_decls: ?*std.AutoArrayHashMap(Decl.Index, void),
16561652 ) !void {
16571653 const gpa = mod.gpa;
16581654
......@@ -1669,13 +1665,13 @@ pub const Namespace = struct {
16691665
16701666 for (decls.keys()) |child_decl| {
16711667 mod.clearDecl(child_decl, outdated_decls) catch @panic("out of memory");
1672 child_decl.destroy(mod);
1668 mod.destroyDecl(child_decl);
16731669 }
16741670 decls.deinit(gpa);
16751671
16761672 for (anon_decls.keys()) |child_decl| {
16771673 mod.clearDecl(child_decl, outdated_decls) catch @panic("out of memory");
1678 child_decl.destroy(mod);
1674 mod.destroyDecl(child_decl);
16791675 }
16801676 anon_decls.deinit(gpa);
16811677
......@@ -1685,12 +1681,14 @@ pub const Namespace = struct {
16851681 // This renders e.g. "std.fs.Dir.OpenOptions"
16861682 pub fn renderFullyQualifiedName(
16871683 ns: Namespace,
1684 mod: *Module,
16881685 name: []const u8,
16891686 writer: anytype,
16901687 ) @TypeOf(writer).Error!void {
16911688 if (ns.parent) |parent| {
1692 const decl = ns.getDecl();
1693 try parent.renderFullyQualifiedName(mem.sliceTo(decl.name, 0), writer);
1689 const decl_index = ns.getDeclIndex();
1690 const decl = mod.declPtr(decl_index);
1691 try parent.renderFullyQualifiedName(mod, mem.sliceTo(decl.name, 0), writer);
16941692 } else {
16951693 try ns.file_scope.renderFullyQualifiedName(writer);
16961694 }
......@@ -1703,13 +1701,15 @@ pub const Namespace = struct {
17031701 /// This renders e.g. "std/fs.zig:Dir.OpenOptions"
17041702 pub fn renderFullyQualifiedDebugName(
17051703 ns: Namespace,
1704 mod: *Module,
17061705 name: []const u8,
17071706 writer: anytype,
17081707 ) @TypeOf(writer).Error!void {
17091708 var separator_char: u8 = '.';
17101709 if (ns.parent) |parent| {
1711 const decl = ns.getDecl();
1712 try parent.renderFullyQualifiedDebugName(mem.sliceTo(decl.name, 0), writer);
1710 const decl_index = ns.getDeclIndex();
1711 const decl = mod.declPtr(decl_index);
1712 try parent.renderFullyQualifiedDebugName(mod, mem.sliceTo(decl.name, 0), writer);
17131713 } else {
17141714 try ns.file_scope.renderFullyQualifiedDebugName(writer);
17151715 separator_char = ':';
......@@ -1720,12 +1720,14 @@ pub const Namespace = struct {
17201720 }
17211721 }
17221722
1723 pub fn getDecl(ns: Namespace) *Decl {
1723 pub fn getDeclIndex(ns: Namespace) Decl.Index {
17241724 return ns.ty.getOwnerDecl();
17251725 }
17261726};
17271727
17281728pub const File = struct {
1729 /// The Decl of the struct that represents this File.
1730 root_decl: Decl.OptionalIndex,
17291731 status: enum {
17301732 never_loaded,
17311733 retryable_failure,
......@@ -1749,16 +1751,14 @@ pub const File = struct {
17491751 zir: Zir,
17501752 /// Package that this file is a part of, managed externally.
17511753 pkg: *Package,
1752 /// The Decl of the struct that represents this File.
1753 root_decl: ?*Decl,
17541754
17551755 /// Used by change detection algorithm, after astgen, contains the
17561756 /// set of decls that existed in the previous ZIR but not in the new one.
1757 deleted_decls: std.ArrayListUnmanaged(*Decl) = .{},
1757 deleted_decls: std.ArrayListUnmanaged(Decl.Index) = .{},
17581758 /// Used by change detection algorithm, after astgen, contains the
17591759 /// set of decls that existed both in the previous ZIR and in the new one,
17601760 /// but their source code has been modified.
1761 outdated_decls: std.ArrayListUnmanaged(*Decl) = .{},
1761 outdated_decls: std.ArrayListUnmanaged(Decl.Index) = .{},
17621762
17631763 /// The most recent successful ZIR for this file, with no errors.
17641764 /// This is only populated when a previously successful ZIR
......@@ -1798,8 +1798,8 @@ pub const File = struct {
17981798 log.debug("deinit File {s}", .{file.sub_file_path});
17991799 file.deleted_decls.deinit(gpa);
18001800 file.outdated_decls.deinit(gpa);
1801 if (file.root_decl) |root_decl| {
1802 root_decl.destroy(mod);
1801 if (file.root_decl.unwrap()) |root_decl| {
1802 mod.destroyDecl(root_decl);
18031803 }
18041804 gpa.free(file.sub_file_path);
18051805 file.unload(gpa);
......@@ -1932,7 +1932,7 @@ pub const EmbedFile = struct {
19321932 /// The Decl that was created from the `@embedFile` to own this resource.
19331933 /// This is how zig knows what other Decl objects to invalidate if the file
19341934 /// changes on disk.
1935 owner_decl: *Decl,
1935 owner_decl: Decl.Index,
19361936
19371937 fn destroy(embed_file: *EmbedFile, mod: *Module) void {
19381938 const gpa = mod.gpa;
......@@ -2776,6 +2776,7 @@ pub fn deinit(mod: *Module) void {
27762776 }
27772777 emit_h.failed_decls.deinit(gpa);
27782778 emit_h.decl_table.deinit(gpa);
2779 emit_h.allocated_emit_h.deinit(gpa);
27792780 gpa.destroy(emit_h);
27802781 }
27812782
......@@ -2827,6 +2828,52 @@ pub fn deinit(mod: *Module) void {
28272828 }
28282829 mod.memoized_calls.deinit(gpa);
28292830 }
2831
2832 mod.decls_free_list.deinit(gpa);
2833 mod.allocated_decls.deinit(gpa);
2834}
2835
2836pub fn destroyDecl(mod: *Module, decl_index: Decl.Index) void {
2837 const gpa = mod.gpa;
2838 {
2839 const decl = mod.declPtr(decl_index);
2840 log.debug("destroy {*} ({s})", .{ decl, decl.name });
2841 _ = mod.test_functions.swapRemove(decl_index);
2842 if (decl.deletion_flag) {
2843 assert(mod.deletion_set.swapRemove(decl_index));
2844 }
2845 if (decl.has_tv) {
2846 if (decl.getInnerNamespace()) |namespace| {
2847 namespace.destroyDecls(mod);
2848 }
2849 decl.clearValues(gpa);
2850 }
2851 decl.dependants.deinit(gpa);
2852 decl.dependencies.deinit(gpa);
2853 decl.clearName(gpa);
2854 decl.* = undefined;
2855 }
2856 mod.decls_free_list.append(gpa, decl_index) catch {
2857 // In order to keep `destroyDecl` a non-fallible function, we ignore memory
2858 // allocation failures here, instead leaking the Decl until garbage collection.
2859 };
2860 if (mod.emit_h) |mod_emit_h| {
2861 const decl_emit_h = mod_emit_h.declPtr(decl_index);
2862 decl_emit_h.fwd_decl.deinit(gpa);
2863 decl_emit_h.* = undefined;
2864 }
2865}
2866
2867pub fn declPtr(mod: *Module, decl_index: Decl.Index) *Decl {
2868 return mod.allocated_decls.at(@enumToInt(decl_index));
2869}
2870
2871/// Returns true if and only if the Decl is the top level struct associated with a File.
2872pub fn declIsRoot(mod: *Module, decl_index: Decl.Index) bool {
2873 const decl = mod.declPtr(decl_index);
2874 if (decl.src_namespace.parent != null)
2875 return false;
2876 return decl_index == decl.src_namespace.getDeclIndex();
28302877}
28312878
28322879fn freeExportList(gpa: Allocator, export_list: []*Export) void {
......@@ -3230,14 +3277,14 @@ pub fn astGenFile(mod: *Module, file: *File) !void {
32303277 // We do not need to hold any locks at this time because all the Decl and Namespace
32313278 // objects being touched are specific to this File, and the only other concurrent
32323279 // tasks are touching other File objects.
3233 try updateZirRefs(gpa, file, prev_zir.*);
3280 try updateZirRefs(mod, file, prev_zir.*);
32343281 // At this point, `file.outdated_decls` and `file.deleted_decls` are populated,
32353282 // and semantic analysis will deal with them properly.
32363283 // No need to keep previous ZIR.
32373284 prev_zir.deinit(gpa);
32383285 gpa.destroy(prev_zir);
32393286 file.prev_zir = null;
3240 } else if (file.root_decl) |root_decl| {
3287 } else if (file.root_decl.unwrap()) |root_decl| {
32413288 // This is an update, but it is the first time the File has succeeded
32423289 // ZIR. We must mark it outdated since we have already tried to
32433290 // semantically analyze it.
......@@ -3251,7 +3298,8 @@ pub fn astGenFile(mod: *Module, file: *File) !void {
32513298/// * Decl.zir_index
32523299/// * Fn.zir_body_inst
32533300/// * Decl.zir_decl_index
3254fn updateZirRefs(gpa: Allocator, file: *File, old_zir: Zir) !void {
3301fn updateZirRefs(mod: *Module, file: *File, old_zir: Zir) !void {
3302 const gpa = mod.gpa;
32553303 const new_zir = file.zir;
32563304
32573305 // Maps from old ZIR to new ZIR, struct_decl, enum_decl, etc. Any instruction which
......@@ -3268,10 +3316,10 @@ fn updateZirRefs(gpa: Allocator, file: *File, old_zir: Zir) !void {
32683316 // Walk the Decl graph, updating ZIR indexes, strings, and populating
32693317 // the deleted and outdated lists.
32703318
3271 var decl_stack: std.ArrayListUnmanaged(*Decl) = .{};
3319 var decl_stack: std.ArrayListUnmanaged(Decl.Index) = .{};
32723320 defer decl_stack.deinit(gpa);
32733321
3274 const root_decl = file.root_decl.?;
3322 const root_decl = file.root_decl.unwrap().?;
32753323 try decl_stack.append(gpa, root_decl);
32763324
32773325 file.deleted_decls.clearRetainingCapacity();
......@@ -3281,7 +3329,8 @@ fn updateZirRefs(gpa: Allocator, file: *File, old_zir: Zir) !void {
32813329 // to re-generate ZIR for the File.
32823330 try file.outdated_decls.append(gpa, root_decl);
32833331
3284 while (decl_stack.popOrNull()) |decl| {
3332 while (decl_stack.popOrNull()) |decl_index| {
3333 const decl = mod.declPtr(decl_index);
32853334 // Anonymous decls and the root decl have this set to 0. We still need
32863335 // to walk them but we do not need to modify this value.
32873336 // Anonymous decls should not be marked outdated. They will be re-generated
......@@ -3292,7 +3341,7 @@ fn updateZirRefs(gpa: Allocator, file: *File, old_zir: Zir) !void {
32923341 log.debug("updateZirRefs {s}: delete {*} ({s})", .{
32933342 file.sub_file_path, decl, decl.name,
32943343 });
3295 try file.deleted_decls.append(gpa, decl);
3344 try file.deleted_decls.append(gpa, decl_index);
32963345 continue;
32973346 };
32983347 const old_hash = decl.contentsHashZir(old_zir);
......@@ -3302,7 +3351,7 @@ fn updateZirRefs(gpa: Allocator, file: *File, old_zir: Zir) !void {
33023351 log.debug("updateZirRefs {s}: outdated {*} ({s}) {d} => {d}", .{
33033352 file.sub_file_path, decl, decl.name, old_zir_decl_index, new_zir_decl_index,
33043353 });
3305 try file.outdated_decls.append(gpa, decl);
3354 try file.outdated_decls.append(gpa, decl_index);
33063355 } else {
33073356 log.debug("updateZirRefs {s}: unchanged {*} ({s}) {d} => {d}", .{
33083357 file.sub_file_path, decl, decl.name, old_zir_decl_index, new_zir_decl_index,
......@@ -3314,21 +3363,21 @@ fn updateZirRefs(gpa: Allocator, file: *File, old_zir: Zir) !void {
33143363
33153364 if (decl.getStruct()) |struct_obj| {
33163365 struct_obj.zir_index = inst_map.get(struct_obj.zir_index) orelse {
3317 try file.deleted_decls.append(gpa, decl);
3366 try file.deleted_decls.append(gpa, decl_index);
33183367 continue;
33193368 };
33203369 }
33213370
33223371 if (decl.getUnion()) |union_obj| {
33233372 union_obj.zir_index = inst_map.get(union_obj.zir_index) orelse {
3324 try file.deleted_decls.append(gpa, decl);
3373 try file.deleted_decls.append(gpa, decl_index);
33253374 continue;
33263375 };
33273376 }
33283377
33293378 if (decl.getFunction()) |func| {
33303379 func.zir_body_inst = inst_map.get(func.zir_body_inst) orelse {
3331 try file.deleted_decls.append(gpa, decl);
3380 try file.deleted_decls.append(gpa, decl_index);
33323381 continue;
33333382 };
33343383 }
......@@ -3485,10 +3534,12 @@ pub fn mapOldZirToNew(
34853534/// However the resolution status of the Type may not be fully resolved.
34863535/// For example an inferred error set is not resolved until after `analyzeFnBody`.
34873536/// is called.
3488pub fn ensureDeclAnalyzed(mod: *Module, decl: *Decl) SemaError!void {
3537pub fn ensureDeclAnalyzed(mod: *Module, decl_index: Decl.Index) SemaError!void {
34893538 const tracy = trace(@src());
34903539 defer tracy.end();
34913540
3541 const decl = mod.declPtr(decl_index);
3542
34923543 const subsequent_analysis = switch (decl.analysis) {
34933544 .in_progress => unreachable,
34943545
......@@ -3507,15 +3558,16 @@ pub fn ensureDeclAnalyzed(mod: *Module, decl: *Decl) SemaError!void {
35073558
35083559 // The exports this Decl performs will be re-discovered, so we remove them here
35093560 // prior to re-analysis.
3510 mod.deleteDeclExports(decl);
3561 mod.deleteDeclExports(decl_index);
35113562 // Dependencies will be re-discovered, so we remove them here prior to re-analysis.
3512 for (decl.dependencies.keys()) |dep| {
3513 dep.removeDependant(decl);
3563 for (decl.dependencies.keys()) |dep_index| {
3564 const dep = mod.declPtr(dep_index);
3565 dep.removeDependant(decl_index);
35143566 if (dep.dependants.count() == 0 and !dep.deletion_flag) {
35153567 log.debug("insert {*} ({s}) dependant {*} ({s}) into deletion set", .{
35163568 decl, decl.name, dep, dep.name,
35173569 });
3518 try mod.markDeclForDeletion(dep);
3570 try mod.markDeclForDeletion(dep_index);
35193571 }
35203572 }
35213573 decl.dependencies.clearRetainingCapacity();
......@@ -3530,7 +3582,7 @@ pub fn ensureDeclAnalyzed(mod: *Module, decl: *Decl) SemaError!void {
35303582 decl_prog_node.activate();
35313583 defer decl_prog_node.end();
35323584
3533 const type_changed = mod.semaDecl(decl) catch |err| switch (err) {
3585 const type_changed = mod.semaDecl(decl_index) catch |err| switch (err) {
35343586 error.AnalysisFail => {
35353587 if (decl.analysis == .in_progress) {
35363588 // If this decl caused the compile error, the analysis field would
......@@ -3545,7 +3597,7 @@ pub fn ensureDeclAnalyzed(mod: *Module, decl: *Decl) SemaError!void {
35453597 else => |e| {
35463598 decl.analysis = .sema_failure_retryable;
35473599 try mod.failed_decls.ensureUnusedCapacity(mod.gpa, 1);
3548 mod.failed_decls.putAssumeCapacityNoClobber(decl, try ErrorMsg.create(
3600 mod.failed_decls.putAssumeCapacityNoClobber(decl_index, try ErrorMsg.create(
35493601 mod.gpa,
35503602 decl.srcLoc(),
35513603 "unable to analyze: {s}",
......@@ -3559,7 +3611,8 @@ pub fn ensureDeclAnalyzed(mod: *Module, decl: *Decl) SemaError!void {
35593611 // We may need to chase the dependants and re-analyze them.
35603612 // However, if the decl is a function, and the type is the same, we do not need to.
35613613 if (type_changed or decl.ty.zigTypeTag() != .Fn) {
3562 for (decl.dependants.keys()) |dep| {
3614 for (decl.dependants.keys()) |dep_index| {
3615 const dep = mod.declPtr(dep_index);
35633616 switch (dep.analysis) {
35643617 .unreferenced => unreachable,
35653618 .in_progress => continue, // already doing analysis, ok
......@@ -3573,7 +3626,7 @@ pub fn ensureDeclAnalyzed(mod: *Module, decl: *Decl) SemaError!void {
35733626 .codegen_failure_retryable,
35743627 .complete,
35753628 => if (dep.generation != mod.generation) {
3576 try mod.markOutdatedDecl(dep);
3629 try mod.markOutdatedDecl(dep_index);
35773630 },
35783631 }
35793632 }
......@@ -3585,7 +3638,10 @@ pub fn ensureFuncBodyAnalyzed(mod: *Module, func: *Fn) SemaError!void {
35853638 const tracy = trace(@src());
35863639 defer tracy.end();
35873640
3588 switch (func.owner_decl.analysis) {
3641 const decl_index = func.owner_decl;
3642 const decl = mod.declPtr(decl_index);
3643
3644 switch (decl.analysis) {
35893645 .unreferenced => unreachable,
35903646 .in_progress => unreachable,
35913647 .outdated => unreachable,
......@@ -3607,13 +3663,12 @@ pub fn ensureFuncBodyAnalyzed(mod: *Module, func: *Fn) SemaError!void {
36073663 }
36083664
36093665 const gpa = mod.gpa;
3610 const decl = func.owner_decl;
36113666
36123667 var tmp_arena = std.heap.ArenaAllocator.init(gpa);
36133668 defer tmp_arena.deinit();
36143669 const sema_arena = tmp_arena.allocator();
36153670
3616 var air = mod.analyzeFnBody(decl, func, sema_arena) catch |err| switch (err) {
3671 var air = mod.analyzeFnBody(func, sema_arena) catch |err| switch (err) {
36173672 error.AnalysisFail => {
36183673 if (func.state == .in_progress) {
36193674 // If this decl caused the compile error, the analysis field would
......@@ -3635,7 +3690,7 @@ pub fn ensureFuncBodyAnalyzed(mod: *Module, func: *Fn) SemaError!void {
36353690
36363691 if (builtin.mode == .Debug and mod.comp.verbose_air) {
36373692 std.debug.print("# Begin Function AIR: {s}:\n", .{decl.name});
3638 @import("print_air.zig").dump(gpa, air, liveness);
3693 @import("print_air.zig").dump(mod, air, liveness);
36393694 std.debug.print("# End Function AIR: {s}\n\n", .{decl.name});
36403695 }
36413696
......@@ -3647,7 +3702,7 @@ pub fn ensureFuncBodyAnalyzed(mod: *Module, func: *Fn) SemaError!void {
36473702 },
36483703 else => {
36493704 try mod.failed_decls.ensureUnusedCapacity(gpa, 1);
3650 mod.failed_decls.putAssumeCapacityNoClobber(decl, try Module.ErrorMsg.create(
3705 mod.failed_decls.putAssumeCapacityNoClobber(decl_index, try Module.ErrorMsg.create(
36513706 gpa,
36523707 decl.srcLoc(),
36533708 "unable to codegen: {s}",
......@@ -3668,7 +3723,9 @@ pub fn updateEmbedFile(mod: *Module, embed_file: *EmbedFile) SemaError!void {
36683723
36693724 // TODO we can potentially relax this if we store some more information along
36703725 // with decl dependency edges
3671 for (embed_file.owner_decl.dependants.keys()) |dep| {
3726 const owner_decl = mod.declPtr(embed_file.owner_decl);
3727 for (owner_decl.dependants.keys()) |dep_index| {
3728 const dep = mod.declPtr(dep_index);
36723729 switch (dep.analysis) {
36733730 .unreferenced => unreachable,
36743731 .in_progress => continue, // already doing analysis, ok
......@@ -3682,7 +3739,7 @@ pub fn updateEmbedFile(mod: *Module, embed_file: *EmbedFile) SemaError!void {
36823739 .codegen_failure_retryable,
36833740 .complete,
36843741 => if (dep.generation != mod.generation) {
3685 try mod.markOutdatedDecl(dep);
3742 try mod.markOutdatedDecl(dep_index);
36863743 },
36873744 }
36883745 }
......@@ -3699,7 +3756,7 @@ pub fn semaFile(mod: *Module, file: *File) SemaError!void {
36993756 const tracy = trace(@src());
37003757 defer tracy.end();
37013758
3702 if (file.root_decl != null) return;
3759 if (file.root_decl != .none) return;
37033760
37043761 const gpa = mod.gpa;
37053762 var new_decl_arena = std.heap.ArenaAllocator.init(gpa);
......@@ -3724,10 +3781,11 @@ pub fn semaFile(mod: *Module, file: *File) SemaError!void {
37243781 .file_scope = file,
37253782 },
37263783 };
3727 const decl_name = try file.fullyQualifiedNameZ(gpa);
3728 const new_decl = try mod.allocateNewDecl(decl_name, &struct_obj.namespace, 0, null);
3729 file.root_decl = new_decl;
3730 struct_obj.owner_decl = new_decl;
3784 const new_decl_index = try mod.allocateNewDecl(&struct_obj.namespace, 0, null);
3785 const new_decl = mod.declPtr(new_decl_index);
3786 file.root_decl = new_decl_index.toOptional();
3787 struct_obj.owner_decl = new_decl_index;
3788 new_decl.name = try file.fullyQualifiedNameZ(gpa);
37313789 new_decl.src_line = 0;
37323790 new_decl.is_pub = true;
37333791 new_decl.is_exported = false;
......@@ -3757,6 +3815,7 @@ pub fn semaFile(mod: *Module, file: *File) SemaError!void {
37573815 .perm_arena = new_decl_arena_allocator,
37583816 .code = file.zir,
37593817 .owner_decl = new_decl,
3818 .owner_decl_index = new_decl_index,
37603819 .func = null,
37613820 .fn_ret_ty = Type.void,
37623821 .owner_func = null,
......@@ -3769,7 +3828,7 @@ pub fn semaFile(mod: *Module, file: *File) SemaError!void {
37693828 var block_scope: Sema.Block = .{
37703829 .parent = null,
37713830 .sema = &sema,
3772 .src_decl = new_decl,
3831 .src_decl = new_decl_index,
37733832 .namespace = &struct_obj.namespace,
37743833 .wip_capture_scope = wip_captures.scope,
37753834 .instructions = .{},
......@@ -3808,10 +3867,12 @@ pub fn semaFile(mod: *Module, file: *File) SemaError!void {
38083867/// Returns `true` if the Decl type changed.
38093868/// Returns `true` if this is the first time analyzing the Decl.
38103869/// Returns `false` otherwise.
3811fn semaDecl(mod: *Module, decl: *Decl) !bool {
3870fn semaDecl(mod: *Module, decl_index: Decl.Index) !bool {
38123871 const tracy = trace(@src());
38133872 defer tracy.end();
38143873
3874 const decl = mod.declPtr(decl_index);
3875
38153876 if (decl.getFileScope().status != .success_zir) {
38163877 return error.AnalysisFail;
38173878 }
......@@ -3838,13 +3899,14 @@ fn semaDecl(mod: *Module, decl: *Decl) !bool {
38383899 .perm_arena = decl_arena_allocator,
38393900 .code = zir,
38403901 .owner_decl = decl,
3902 .owner_decl_index = decl_index,
38413903 .func = null,
38423904 .fn_ret_ty = Type.void,
38433905 .owner_func = null,
38443906 };
38453907 defer sema.deinit();
38463908
3847 if (decl.isRoot()) {
3909 if (mod.declIsRoot(decl_index)) {
38483910 log.debug("semaDecl root {*} ({s})", .{ decl, decl.name });
38493911 const main_struct_inst = Zir.main_struct_inst;
38503912 const struct_obj = decl.getStruct().?;
......@@ -3864,7 +3926,7 @@ fn semaDecl(mod: *Module, decl: *Decl) !bool {
38643926 var block_scope: Sema.Block = .{
38653927 .parent = null,
38663928 .sema = &sema,
3867 .src_decl = decl,
3929 .src_decl = decl_index,
38683930 .namespace = decl.src_namespace,
38693931 .wip_capture_scope = wip_captures.scope,
38703932 .instructions = .{},
......@@ -3922,15 +3984,15 @@ fn semaDecl(mod: *Module, decl: *Decl) !bool {
39223984 const decl_arena_state = try decl_arena_allocator.create(std.heap.ArenaAllocator.State);
39233985
39243986 if (decl.is_usingnamespace) {
3925 if (!decl_tv.ty.eql(Type.type, target)) {
3987 if (!decl_tv.ty.eql(Type.type, mod)) {
39263988 return sema.fail(&block_scope, src, "expected type, found {}", .{
3927 decl_tv.ty.fmt(target),
3989 decl_tv.ty.fmt(mod),
39283990 });
39293991 }
39303992 var buffer: Value.ToTypeBuffer = undefined;
39313993 const ty = try decl_tv.val.toType(&buffer).copy(decl_arena_allocator);
39323994 if (ty.getNamespace() == null) {
3933 return sema.fail(&block_scope, src, "type {} has no namespace", .{ty.fmt(target)});
3995 return sema.fail(&block_scope, src, "type {} has no namespace", .{ty.fmt(mod)});
39343996 }
39353997
39363998 decl.ty = Type.type;
......@@ -3949,7 +4011,7 @@ fn semaDecl(mod: *Module, decl: *Decl) !bool {
39494011
39504012 if (decl_tv.val.castTag(.function)) |fn_payload| {
39514013 const func = fn_payload.data;
3952 const owns_tv = func.owner_decl == decl;
4014 const owns_tv = func.owner_decl == decl_index;
39534015 if (owns_tv) {
39544016 var prev_type_has_bits = false;
39554017 var prev_is_inline = false;
......@@ -3957,7 +4019,7 @@ fn semaDecl(mod: *Module, decl: *Decl) !bool {
39574019
39584020 if (decl.has_tv) {
39594021 prev_type_has_bits = decl.ty.isFnOrHasRuntimeBits();
3960 type_changed = !decl.ty.eql(decl_tv.ty, target);
4022 type_changed = !decl.ty.eql(decl_tv.ty, mod);
39614023 if (decl.getFunction()) |prev_func| {
39624024 prev_is_inline = prev_func.state == .inline_only;
39634025 }
......@@ -3982,13 +4044,13 @@ fn semaDecl(mod: *Module, decl: *Decl) !bool {
39824044 // We don't fully codegen the decl until later, but we do need to reserve a global
39834045 // offset table index for it. This allows us to codegen decls out of dependency
39844046 // order, increasing how many computations can be done in parallel.
3985 try mod.comp.bin_file.allocateDeclIndexes(decl);
4047 try mod.comp.bin_file.allocateDeclIndexes(decl_index);
39864048 try mod.comp.work_queue.writeItem(.{ .codegen_func = func });
39874049 if (type_changed and mod.emit_h != null) {
3988 try mod.comp.work_queue.writeItem(.{ .emit_h_decl = decl });
4050 try mod.comp.work_queue.writeItem(.{ .emit_h_decl = decl_index });
39894051 }
39904052 } else if (!prev_is_inline and prev_type_has_bits) {
3991 mod.comp.bin_file.freeDecl(decl);
4053 mod.comp.bin_file.freeDecl(decl_index);
39924054 }
39934055
39944056 const is_inline = decl.ty.fnCallingConvention() == .Inline;
......@@ -3999,14 +4061,14 @@ fn semaDecl(mod: *Module, decl: *Decl) !bool {
39994061 }
40004062 // The scope needs to have the decl in it.
40014063 const options: std.builtin.ExportOptions = .{ .name = mem.sliceTo(decl.name, 0) };
4002 try sema.analyzeExport(&block_scope, export_src, options, decl);
4064 try sema.analyzeExport(&block_scope, export_src, options, decl_index);
40034065 }
40044066 return type_changed or is_inline != prev_is_inline;
40054067 }
40064068 }
40074069 var type_changed = true;
40084070 if (decl.has_tv) {
4009 type_changed = !decl.ty.eql(decl_tv.ty, target);
4071 type_changed = !decl.ty.eql(decl_tv.ty, mod);
40104072 decl.clearValues(gpa);
40114073 }
40124074
......@@ -4016,7 +4078,7 @@ fn semaDecl(mod: *Module, decl: *Decl) !bool {
40164078 switch (decl_tv.val.tag()) {
40174079 .variable => {
40184080 const variable = decl_tv.val.castTag(.variable).?.data;
4019 if (variable.owner_decl == decl) {
4081 if (variable.owner_decl == decl_index) {
40204082 decl.owns_tv = true;
40214083 queue_linker_work = true;
40224084
......@@ -4026,7 +4088,7 @@ fn semaDecl(mod: *Module, decl: *Decl) !bool {
40264088 },
40274089 .extern_fn => {
40284090 const extern_fn = decl_tv.val.castTag(.extern_fn).?.data;
4029 if (extern_fn.owner_decl == decl) {
4091 if (extern_fn.owner_decl == decl_index) {
40304092 decl.owns_tv = true;
40314093 queue_linker_work = true;
40324094 is_extern = true;
......@@ -4065,11 +4127,11 @@ fn semaDecl(mod: *Module, decl: *Decl) !bool {
40654127 // codegen backend wants full access to the Decl Type.
40664128 try sema.resolveTypeFully(&block_scope, src, decl.ty);
40674129
4068 try mod.comp.bin_file.allocateDeclIndexes(decl);
4069 try mod.comp.work_queue.writeItem(.{ .codegen_decl = decl });
4130 try mod.comp.bin_file.allocateDeclIndexes(decl_index);
4131 try mod.comp.work_queue.writeItem(.{ .codegen_decl = decl_index });
40704132
40714133 if (type_changed and mod.emit_h != null) {
4072 try mod.comp.work_queue.writeItem(.{ .emit_h_decl = decl });
4134 try mod.comp.work_queue.writeItem(.{ .emit_h_decl = decl_index });
40734135 }
40744136 }
40754137
......@@ -4077,15 +4139,18 @@ fn semaDecl(mod: *Module, decl: *Decl) !bool {
40774139 const export_src = src; // TODO point to the export token
40784140 // The scope needs to have the decl in it.
40794141 const options: std.builtin.ExportOptions = .{ .name = mem.sliceTo(decl.name, 0) };
4080 try sema.analyzeExport(&block_scope, export_src, options, decl);
4142 try sema.analyzeExport(&block_scope, export_src, options, decl_index);
40814143 }
40824144
40834145 return type_changed;
40844146}
40854147
40864148/// Returns the depender's index of the dependee.
4087pub fn declareDeclDependency(mod: *Module, depender: *Decl, dependee: *Decl) !void {
4088 if (depender == dependee) return;
4149pub fn declareDeclDependency(mod: *Module, depender_index: Decl.Index, dependee_index: Decl.Index) !void {
4150 if (depender_index == dependee_index) return;
4151
4152 const depender = mod.declPtr(depender_index);
4153 const dependee = mod.declPtr(dependee_index);
40894154
40904155 log.debug("{*} ({s}) depends on {*} ({s})", .{
40914156 depender, depender.name, dependee, dependee.name,
......@@ -4096,11 +4161,11 @@ pub fn declareDeclDependency(mod: *Module, depender: *Decl, dependee: *Decl) !vo
40964161
40974162 if (dependee.deletion_flag) {
40984163 dependee.deletion_flag = false;
4099 assert(mod.deletion_set.swapRemove(dependee));
4164 assert(mod.deletion_set.swapRemove(dependee_index));
41004165 }
41014166
4102 dependee.dependants.putAssumeCapacity(depender, {});
4103 depender.dependencies.putAssumeCapacity(dependee, {});
4167 dependee.dependants.putAssumeCapacity(depender_index, {});
4168 depender.dependencies.putAssumeCapacity(dependee_index, {});
41044169}
41054170
41064171pub const ImportFileResult = struct {
......@@ -4146,7 +4211,7 @@ pub fn importPkg(mod: *Module, pkg: *Package) !ImportFileResult {
41464211 .zir = undefined,
41474212 .status = .never_loaded,
41484213 .pkg = pkg,
4149 .root_decl = null,
4214 .root_decl = .none,
41504215 };
41514216 return ImportFileResult{
41524217 .file = new_file,
......@@ -4214,7 +4279,7 @@ pub fn importFile(
42144279 .zir = undefined,
42154280 .status = .never_loaded,
42164281 .pkg = cur_file.pkg,
4217 .root_decl = null,
4282 .root_decl = .none,
42184283 };
42194284 return ImportFileResult{
42204285 .file = new_file,
......@@ -4388,8 +4453,8 @@ fn scanDecl(iter: *ScanDeclIter, decl_sub_index: usize, flags: u4) SemaError!voi
43884453 const line = iter.parent_decl.relativeToLine(line_off);
43894454 const decl_name_index = zir.extra[decl_sub_index + 5];
43904455 const decl_doccomment_index = zir.extra[decl_sub_index + 7];
4391 const decl_index = zir.extra[decl_sub_index + 6];
4392 const decl_block_inst_data = zir.instructions.items(.data)[decl_index].pl_node;
4456 const decl_zir_index = zir.extra[decl_sub_index + 6];
4457 const decl_block_inst_data = zir.instructions.items(.data)[decl_zir_index].pl_node;
43934458 const decl_node = iter.parent_decl.relativeToNodeIndex(decl_block_inst_data.src_node);
43944459
43954460 // Every Decl needs a name.
......@@ -4432,15 +4497,22 @@ fn scanDecl(iter: *ScanDeclIter, decl_sub_index: usize, flags: u4) SemaError!voi
44324497 if (is_usingnamespace) try namespace.usingnamespace_set.ensureUnusedCapacity(gpa, 1);
44334498
44344499 // We create a Decl for it regardless of analysis status.
4435 const gop = try namespace.decls.getOrPutAdapted(gpa, @as([]const u8, mem.sliceTo(decl_name, 0)), DeclAdapter{});
4500 const gop = try namespace.decls.getOrPutContextAdapted(
4501 gpa,
4502 @as([]const u8, mem.sliceTo(decl_name, 0)),
4503 DeclAdapter{ .mod = mod },
4504 Namespace.DeclContext{ .module = mod },
4505 );
44364506 if (!gop.found_existing) {
4437 const new_decl = try mod.allocateNewDecl(decl_name, namespace, decl_node, iter.parent_decl.src_scope);
4507 const new_decl_index = try mod.allocateNewDecl(namespace, decl_node, iter.parent_decl.src_scope);
4508 const new_decl = mod.declPtr(new_decl_index);
4509 new_decl.name = decl_name;
44384510 if (is_usingnamespace) {
4439 namespace.usingnamespace_set.putAssumeCapacity(new_decl, is_pub);
4511 namespace.usingnamespace_set.putAssumeCapacity(new_decl_index, is_pub);
44404512 }
44414513 log.debug("scan new {*} ({s}) into {*}", .{ new_decl, decl_name, namespace });
44424514 new_decl.src_line = line;
4443 gop.key_ptr.* = new_decl;
4515 gop.key_ptr.* = new_decl_index;
44444516 // Exported decls, comptime decls, usingnamespace decls, and
44454517 // test decls if in test mode, get analyzed.
44464518 const decl_pkg = namespace.file_scope.pkg;
......@@ -4451,7 +4523,7 @@ fn scanDecl(iter: *ScanDeclIter, decl_sub_index: usize, flags: u4) SemaError!voi
44514523 // the test name filter.
44524524 if (!mod.comp.bin_file.options.is_test) break :blk false;
44534525 if (decl_pkg != mod.main_pkg) break :blk false;
4454 try mod.test_functions.put(gpa, new_decl, {});
4526 try mod.test_functions.put(gpa, new_decl_index, {});
44554527 break :blk true;
44564528 },
44574529 else => blk: {
......@@ -4459,12 +4531,12 @@ fn scanDecl(iter: *ScanDeclIter, decl_sub_index: usize, flags: u4) SemaError!voi
44594531 if (!mod.comp.bin_file.options.is_test) break :blk false;
44604532 if (decl_pkg != mod.main_pkg) break :blk false;
44614533 // TODO check the name against --test-filter
4462 try mod.test_functions.put(gpa, new_decl, {});
4534 try mod.test_functions.put(gpa, new_decl_index, {});
44634535 break :blk true;
44644536 },
44654537 };
44664538 if (want_analysis) {
4467 mod.comp.work_queue.writeItemAssumeCapacity(.{ .analyze_decl = new_decl });
4539 mod.comp.work_queue.writeItemAssumeCapacity(.{ .analyze_decl = new_decl_index });
44684540 }
44694541 new_decl.is_pub = is_pub;
44704542 new_decl.is_exported = is_exported;
......@@ -4476,7 +4548,8 @@ fn scanDecl(iter: *ScanDeclIter, decl_sub_index: usize, flags: u4) SemaError!voi
44764548 return;
44774549 }
44784550 gpa.free(decl_name);
4479 const decl = gop.key_ptr.*;
4551 const decl_index = gop.key_ptr.*;
4552 const decl = mod.declPtr(decl_index);
44804553 log.debug("scan existing {*} ({s}) of {*}", .{ decl, decl.name, namespace });
44814554 // Update the AST node of the decl; even if its contents are unchanged, it may
44824555 // have been re-ordered.
......@@ -4497,17 +4570,17 @@ fn scanDecl(iter: *ScanDeclIter, decl_sub_index: usize, flags: u4) SemaError!voi
44974570 .elf => if (decl.fn_link.elf.len != 0) {
44984571 // TODO Look into detecting when this would be unnecessary by storing enough state
44994572 // in `Decl` to notice that the line number did not change.
4500 mod.comp.work_queue.writeItemAssumeCapacity(.{ .update_line_number = decl });
4573 mod.comp.work_queue.writeItemAssumeCapacity(.{ .update_line_number = decl_index });
45014574 },
45024575 .macho => if (decl.fn_link.macho.len != 0) {
45034576 // TODO Look into detecting when this would be unnecessary by storing enough state
45044577 // in `Decl` to notice that the line number did not change.
4505 mod.comp.work_queue.writeItemAssumeCapacity(.{ .update_line_number = decl });
4578 mod.comp.work_queue.writeItemAssumeCapacity(.{ .update_line_number = decl_index });
45064579 },
45074580 .plan9 => {
45084581 // TODO Look into detecting when this would be unnecessary by storing enough state
45094582 // in `Decl` to notice that the line number did not change.
4510 mod.comp.work_queue.writeItemAssumeCapacity(.{ .update_line_number = decl });
4583 mod.comp.work_queue.writeItemAssumeCapacity(.{ .update_line_number = decl_index });
45114584 },
45124585 .c, .wasm, .spirv, .nvptx => {},
45134586 }
......@@ -4517,25 +4590,27 @@ fn scanDecl(iter: *ScanDeclIter, decl_sub_index: usize, flags: u4) SemaError!voi
45174590/// Make it as if the semantic analysis for this Decl never happened.
45184591pub fn clearDecl(
45194592 mod: *Module,
4520 decl: *Decl,
4521 outdated_decls: ?*std.AutoArrayHashMap(*Decl, void),
4593 decl_index: Decl.Index,
4594 outdated_decls: ?*std.AutoArrayHashMap(Decl.Index, void),
45224595) Allocator.Error!void {
45234596 const tracy = trace(@src());
45244597 defer tracy.end();
45254598
4599 const decl = mod.declPtr(decl_index);
45264600 log.debug("clearing {*} ({s})", .{ decl, decl.name });
45274601
45284602 const gpa = mod.gpa;
45294603 try mod.deletion_set.ensureUnusedCapacity(gpa, decl.dependencies.count());
45304604
45314605 if (outdated_decls) |map| {
4532 _ = map.swapRemove(decl);
4606 _ = map.swapRemove(decl_index);
45334607 try map.ensureUnusedCapacity(decl.dependants.count());
45344608 }
45354609
45364610 // Remove itself from its dependencies.
4537 for (decl.dependencies.keys()) |dep| {
4538 dep.removeDependant(decl);
4611 for (decl.dependencies.keys()) |dep_index| {
4612 const dep = mod.declPtr(dep_index);
4613 dep.removeDependant(decl_index);
45394614 if (dep.dependants.count() == 0 and !dep.deletion_flag) {
45404615 log.debug("insert {*} ({s}) dependant {*} ({s}) into deletion set", .{
45414616 decl, decl.name, dep, dep.name,
......@@ -4543,35 +4618,36 @@ pub fn clearDecl(
45434618 // We don't recursively perform a deletion here, because during the update,
45444619 // another reference to it may turn up.
45454620 dep.deletion_flag = true;
4546 mod.deletion_set.putAssumeCapacity(dep, {});
4621 mod.deletion_set.putAssumeCapacity(dep_index, {});
45474622 }
45484623 }
45494624 decl.dependencies.clearRetainingCapacity();
45504625
45514626 // Anything that depends on this deleted decl needs to be re-analyzed.
4552 for (decl.dependants.keys()) |dep| {
4553 dep.removeDependency(decl);
4627 for (decl.dependants.keys()) |dep_index| {
4628 const dep = mod.declPtr(dep_index);
4629 dep.removeDependency(decl_index);
45544630 if (outdated_decls) |map| {
4555 map.putAssumeCapacity(dep, {});
4631 map.putAssumeCapacity(dep_index, {});
45564632 }
45574633 }
45584634 decl.dependants.clearRetainingCapacity();
45594635
4560 if (mod.failed_decls.fetchSwapRemove(decl)) |kv| {
4636 if (mod.failed_decls.fetchSwapRemove(decl_index)) |kv| {
45614637 kv.value.destroy(gpa);
45624638 }
45634639 if (mod.emit_h) |emit_h| {
4564 if (emit_h.failed_decls.fetchSwapRemove(decl)) |kv| {
4640 if (emit_h.failed_decls.fetchSwapRemove(decl_index)) |kv| {
45654641 kv.value.destroy(gpa);
45664642 }
4567 assert(emit_h.decl_table.swapRemove(decl));
4643 assert(emit_h.decl_table.swapRemove(decl_index));
45684644 }
4569 _ = mod.compile_log_decls.swapRemove(decl);
4570 mod.deleteDeclExports(decl);
4645 _ = mod.compile_log_decls.swapRemove(decl_index);
4646 mod.deleteDeclExports(decl_index);
45714647
45724648 if (decl.has_tv) {
45734649 if (decl.ty.isFnOrHasRuntimeBits()) {
4574 mod.comp.bin_file.freeDecl(decl);
4650 mod.comp.bin_file.freeDecl(decl_index);
45754651
45764652 // TODO instead of a union, put this memory trailing Decl objects,
45774653 // and allow it to be variably sized.
......@@ -4604,15 +4680,16 @@ pub fn clearDecl(
46044680
46054681 if (decl.deletion_flag) {
46064682 decl.deletion_flag = false;
4607 assert(mod.deletion_set.swapRemove(decl));
4683 assert(mod.deletion_set.swapRemove(decl_index));
46084684 }
46094685
46104686 decl.analysis = .unreferenced;
46114687}
46124688
46134689/// This function is exclusively called for anonymous decls.
4614pub fn deleteUnusedDecl(mod: *Module, decl: *Decl) void {
4615 log.debug("deleteUnusedDecl {*} ({s})", .{ decl, decl.name });
4690pub fn deleteUnusedDecl(mod: *Module, decl_index: Decl.Index) void {
4691 const decl = mod.declPtr(decl_index);
4692 log.debug("deleteUnusedDecl {d} ({s})", .{ decl_index, decl.name });
46164693
46174694 // TODO: remove `allocateDeclIndexes` and make the API that the linker backends
46184695 // are required to notice the first time `updateDecl` happens and keep track
......@@ -4626,55 +4703,58 @@ pub fn deleteUnusedDecl(mod: *Module, decl: *Decl) void {
46264703 .c => {}, // this linker backend has already migrated to the new API
46274704 else => if (decl.has_tv) {
46284705 if (decl.ty.isFnOrHasRuntimeBits()) {
4629 mod.comp.bin_file.freeDecl(decl);
4706 mod.comp.bin_file.freeDecl(decl_index);
46304707 }
46314708 },
46324709 }
46334710
4634 assert(!decl.isRoot());
4635 assert(decl.src_namespace.anon_decls.swapRemove(decl));
4711 assert(!mod.declIsRoot(decl_index));
4712 assert(decl.src_namespace.anon_decls.swapRemove(decl_index));
46364713
46374714 const dependants = decl.dependants.keys();
46384715 for (dependants) |dep| {
4639 dep.removeDependency(decl);
4716 mod.declPtr(dep).removeDependency(decl_index);
46404717 }
46414718
46424719 for (decl.dependencies.keys()) |dep| {
4643 dep.removeDependant(decl);
4720 mod.declPtr(dep).removeDependant(decl_index);
46444721 }
4645 decl.destroy(mod);
4722 mod.destroyDecl(decl_index);
46464723}
46474724
46484725/// We don't perform a deletion here, because this Decl or another one
46494726/// may end up referencing it before the update is complete.
4650fn markDeclForDeletion(mod: *Module, decl: *Decl) !void {
4727fn markDeclForDeletion(mod: *Module, decl_index: Decl.Index) !void {
4728 const decl = mod.declPtr(decl_index);
46514729 decl.deletion_flag = true;
4652 try mod.deletion_set.put(mod.gpa, decl, {});
4730 try mod.deletion_set.put(mod.gpa, decl_index, {});
46534731}
46544732
46554733/// Cancel the creation of an anon decl and delete any references to it.
46564734/// If other decls depend on this decl, they must be aborted first.
4657pub fn abortAnonDecl(mod: *Module, decl: *Decl) void {
4735pub fn abortAnonDecl(mod: *Module, decl_index: Decl.Index) void {
4736 const decl = mod.declPtr(decl_index);
46584737 log.debug("abortAnonDecl {*} ({s})", .{ decl, decl.name });
46594738
4660 assert(!decl.isRoot());
4661 assert(decl.src_namespace.anon_decls.swapRemove(decl));
4739 assert(!mod.declIsRoot(decl_index));
4740 assert(decl.src_namespace.anon_decls.swapRemove(decl_index));
46624741
46634742 // An aborted decl must not have dependants -- they must have
46644743 // been aborted first and removed from this list.
46654744 assert(decl.dependants.count() == 0);
46664745
4667 for (decl.dependencies.keys()) |dep| {
4668 dep.removeDependant(decl);
4746 for (decl.dependencies.keys()) |dep_index| {
4747 const dep = mod.declPtr(dep_index);
4748 dep.removeDependant(decl_index);
46694749 }
46704750
4671 decl.destroy(mod);
4751 mod.destroyDecl(decl_index);
46724752}
46734753
46744754/// Delete all the Export objects that are caused by this Decl. Re-analysis of
46754755/// this Decl will cause them to be re-created (or not).
4676fn deleteDeclExports(mod: *Module, decl: *Decl) void {
4677 const kv = mod.export_owners.fetchSwapRemove(decl) orelse return;
4756fn deleteDeclExports(mod: *Module, decl_index: Decl.Index) void {
4757 const kv = mod.export_owners.fetchSwapRemove(decl_index) orelse return;
46784758
46794759 for (kv.value) |exp| {
46804760 if (mod.decl_exports.getPtr(exp.exported_decl)) |value_ptr| {
......@@ -4683,7 +4763,7 @@ fn deleteDeclExports(mod: *Module, decl: *Decl) void {
46834763 var i: usize = 0;
46844764 var new_len = list.len;
46854765 while (i < new_len) {
4686 if (list[i].owner_decl == decl) {
4766 if (list[i].owner_decl == decl_index) {
46874767 mem.copyBackwards(*Export, list[i..], list[i + 1 .. new_len]);
46884768 new_len -= 1;
46894769 } else {
......@@ -4713,11 +4793,13 @@ fn deleteDeclExports(mod: *Module, decl: *Decl) void {
47134793 mod.gpa.free(kv.value);
47144794}
47154795
4716pub fn analyzeFnBody(mod: *Module, decl: *Decl, func: *Fn, arena: Allocator) SemaError!Air {
4796pub fn analyzeFnBody(mod: *Module, func: *Fn, arena: Allocator) SemaError!Air {
47174797 const tracy = trace(@src());
47184798 defer tracy.end();
47194799
47204800 const gpa = mod.gpa;
4801 const decl_index = func.owner_decl;
4802 const decl = mod.declPtr(decl_index);
47214803
47224804 // Use the Decl's arena for captured values.
47234805 var decl_arena = decl.value_arena.?.promote(gpa);
......@@ -4731,8 +4813,9 @@ pub fn analyzeFnBody(mod: *Module, decl: *Decl, func: *Fn, arena: Allocator) Sem
47314813 .perm_arena = decl_arena_allocator,
47324814 .code = decl.getFileScope().zir,
47334815 .owner_decl = decl,
4816 .owner_decl_index = decl_index,
47344817 .func = func,
4735 .fn_ret_ty = func.owner_decl.ty.fnReturnType(),
4818 .fn_ret_ty = decl.ty.fnReturnType(),
47364819 .owner_func = func,
47374820 };
47384821 defer sema.deinit();
......@@ -4748,7 +4831,7 @@ pub fn analyzeFnBody(mod: *Module, decl: *Decl, func: *Fn, arena: Allocator) Sem
47484831 var inner_block: Sema.Block = .{
47494832 .parent = null,
47504833 .sema = &sema,
4751 .src_decl = decl,
4834 .src_decl = decl_index,
47524835 .namespace = decl.src_namespace,
47534836 .wip_capture_scope = wip_captures.scope,
47544837 .instructions = .{},
......@@ -4903,10 +4986,11 @@ pub fn analyzeFnBody(mod: *Module, decl: *Decl, func: *Fn, arena: Allocator) Sem
49034986 };
49044987}
49054988
4906fn markOutdatedDecl(mod: *Module, decl: *Decl) !void {
4989fn markOutdatedDecl(mod: *Module, decl_index: Decl.Index) !void {
4990 const decl = mod.declPtr(decl_index);
49074991 log.debug("mark outdated {*} ({s})", .{ decl, decl.name });
4908 try mod.comp.work_queue.writeItem(.{ .analyze_decl = decl });
4909 if (mod.failed_decls.fetchSwapRemove(decl)) |kv| {
4992 try mod.comp.work_queue.writeItem(.{ .analyze_decl = decl_index });
4993 if (mod.failed_decls.fetchSwapRemove(decl_index)) |kv| {
49104994 kv.value.destroy(mod.gpa);
49114995 }
49124996 if (decl.has_tv and decl.owns_tv) {
......@@ -4916,33 +5000,43 @@ fn markOutdatedDecl(mod: *Module, decl: *Decl) !void {
49165000 }
49175001 }
49185002 if (mod.emit_h) |emit_h| {
4919 if (emit_h.failed_decls.fetchSwapRemove(decl)) |kv| {
5003 if (emit_h.failed_decls.fetchSwapRemove(decl_index)) |kv| {
49205004 kv.value.destroy(mod.gpa);
49215005 }
49225006 }
4923 _ = mod.compile_log_decls.swapRemove(decl);
5007 _ = mod.compile_log_decls.swapRemove(decl_index);
49245008 decl.analysis = .outdated;
49255009}
49265010
49275011pub fn allocateNewDecl(
49285012 mod: *Module,
4929 name: [:0]const u8,
49305013 namespace: *Namespace,
49315014 src_node: Ast.Node.Index,
49325015 src_scope: ?*CaptureScope,
4933) !*Decl {
4934 // If we have emit-h then we must allocate a bigger structure to store the emit-h state.
4935 const new_decl: *Decl = if (mod.emit_h != null) blk: {
4936 const parent_struct = try mod.gpa.create(DeclPlusEmitH);
4937 parent_struct.* = .{
4938 .emit_h = .{},
4939 .decl = undefined,
5016) !Decl.Index {
5017 const decl_and_index: struct {
5018 new_decl: *Decl,
5019 decl_index: Decl.Index,
5020 } = if (mod.decls_free_list.popOrNull()) |decl_index| d: {
5021 break :d .{
5022 .new_decl = mod.declPtr(decl_index),
5023 .decl_index = decl_index,
5024 };
5025 } else d: {
5026 const decl = try mod.allocated_decls.addOne(mod.gpa);
5027 errdefer mod.allocated_decls.shrinkRetainingCapacity(mod.allocated_decls.len - 1);
5028 if (mod.emit_h) |mod_emit_h| {
5029 const decl_emit_h = try mod_emit_h.allocated_emit_h.addOne(mod.gpa);
5030 decl_emit_h.* = .{};
5031 }
5032 break :d .{
5033 .new_decl = decl,
5034 .decl_index = @intToEnum(Decl.Index, mod.allocated_decls.len - 1),
49405035 };
4941 break :blk &parent_struct.decl;
4942 } else try mod.gpa.create(Decl);
5036 };
49435037
4944 new_decl.* = .{
4945 .name = name,
5038 decl_and_index.new_decl.* = .{
5039 .name = undefined,
49465040 .src_namespace = namespace,
49475041 .src_node = src_node,
49485042 .src_line = undefined,
......@@ -4986,7 +5080,7 @@ pub fn allocateNewDecl(
49865080 .is_usingnamespace = false,
49875081 };
49885082
4989 return new_decl;
5083 return decl_and_index.decl_index;
49905084}
49915085
49925086/// Get error value for error tag `name`.
......@@ -5010,18 +5104,9 @@ pub fn getErrorValue(mod: *Module, name: []const u8) !std.StringHashMapUnmanaged
50105104 };
50115105}
50125106
5013/// Takes ownership of `name` even if it returns an error.
5014pub fn createAnonymousDeclNamed(
5015 mod: *Module,
5016 block: *Sema.Block,
5017 typed_value: TypedValue,
5018 name: [:0]u8,
5019) !*Decl {
5020 return mod.createAnonymousDeclFromDeclNamed(block.src_decl, block.namespace, block.wip_capture_scope, typed_value, name);
5021}
5022
5023pub fn createAnonymousDecl(mod: *Module, block: *Sema.Block, typed_value: TypedValue) !*Decl {
5024 return mod.createAnonymousDeclFromDecl(block.src_decl, block.namespace, block.wip_capture_scope, typed_value);
5107pub fn createAnonymousDecl(mod: *Module, block: *Sema.Block, typed_value: TypedValue) !Decl.Index {
5108 const src_decl = mod.declPtr(block.src_decl);
5109 return mod.createAnonymousDeclFromDecl(src_decl, block.namespace, block.wip_capture_scope, typed_value);
50255110}
50265111
50275112pub fn createAnonymousDeclFromDecl(
......@@ -5030,30 +5115,31 @@ pub fn createAnonymousDeclFromDecl(
50305115 namespace: *Namespace,
50315116 src_scope: ?*CaptureScope,
50325117 tv: TypedValue,
5033) !*Decl {
5034 const name_index = mod.getNextAnonNameIndex();
5118) !Decl.Index {
5119 const new_decl_index = try mod.allocateNewDecl(namespace, src_decl.src_node, src_scope);
5120 errdefer mod.destroyDecl(new_decl_index);
50355121 const name = try std.fmt.allocPrintZ(mod.gpa, "{s}__anon_{d}", .{
5036 src_decl.name, name_index,
5122 src_decl.name, @enumToInt(new_decl_index),
50375123 });
5038 return mod.createAnonymousDeclFromDeclNamed(src_decl, namespace, src_scope, tv, name);
5124 try mod.initNewAnonDecl(new_decl_index, src_decl.src_line, namespace, tv, name);
5125 return new_decl_index;
50395126}
50405127
50415128/// Takes ownership of `name` even if it returns an error.
5042pub fn createAnonymousDeclFromDeclNamed(
5129pub fn initNewAnonDecl(
50435130 mod: *Module,
5044 src_decl: *Decl,
5131 new_decl_index: Decl.Index,
5132 src_line: u32,
50455133 namespace: *Namespace,
5046 src_scope: ?*CaptureScope,
50475134 typed_value: TypedValue,
50485135 name: [:0]u8,
5049) !*Decl {
5136) !void {
50505137 errdefer mod.gpa.free(name);
50515138
5052 try namespace.anon_decls.ensureUnusedCapacity(mod.gpa, 1);
5139 const new_decl = mod.declPtr(new_decl_index);
50535140
5054 const new_decl = try mod.allocateNewDecl(name, namespace, src_decl.src_node, src_scope);
5055
5056 new_decl.src_line = src_decl.src_line;
5141 new_decl.name = name;
5142 new_decl.src_line = src_line;
50575143 new_decl.ty = typed_value.ty;
50585144 new_decl.val = typed_value.val;
50595145 new_decl.@"align" = 0;
......@@ -5062,22 +5148,16 @@ pub fn createAnonymousDeclFromDeclNamed(
50625148 new_decl.analysis = .complete;
50635149 new_decl.generation = mod.generation;
50645150
5065 namespace.anon_decls.putAssumeCapacityNoClobber(new_decl, {});
5151 try namespace.anon_decls.putNoClobber(mod.gpa, new_decl_index, {});
50665152
50675153 // The Decl starts off with alive=false and the codegen backend will set alive=true
50685154 // if the Decl is referenced by an instruction or another constant. Otherwise,
50695155 // the Decl will be garbage collected by the `codegen_decl` task instead of sent
50705156 // to the linker.
50715157 if (typed_value.ty.isFnOrHasRuntimeBits()) {
5072 try mod.comp.bin_file.allocateDeclIndexes(new_decl);
5073 try mod.comp.anon_work_queue.writeItem(.{ .codegen_decl = new_decl });
5158 try mod.comp.bin_file.allocateDeclIndexes(new_decl_index);
5159 try mod.comp.anon_work_queue.writeItem(.{ .codegen_decl = new_decl_index });
50745160 }
5075
5076 return new_decl;
5077}
5078
5079pub fn getNextAnonNameIndex(mod: *Module) usize {
5080 return @atomicRmw(usize, &mod.next_anon_name_index, .Add, 1, .Monotonic);
50815161}
50825162
50835163pub fn makeIntType(arena: Allocator, signedness: std.builtin.Signedness, bits: u16) !Type {
......@@ -5339,12 +5419,12 @@ pub fn processOutdatedAndDeletedDecls(mod: *Module) !void {
53395419 // for the outdated decls, but we cannot queue up the tasks until after
53405420 // we find out which ones have been deleted, otherwise there would be
53415421 // deleted Decl pointers in the work queue.
5342 var outdated_decls = std.AutoArrayHashMap(*Decl, void).init(mod.gpa);
5422 var outdated_decls = std.AutoArrayHashMap(Decl.Index, void).init(mod.gpa);
53435423 defer outdated_decls.deinit();
53445424 for (mod.import_table.values()) |file| {
53455425 try outdated_decls.ensureUnusedCapacity(file.outdated_decls.items.len);
5346 for (file.outdated_decls.items) |decl| {
5347 outdated_decls.putAssumeCapacity(decl, {});
5426 for (file.outdated_decls.items) |decl_index| {
5427 outdated_decls.putAssumeCapacity(decl_index, {});
53485428 }
53495429 file.outdated_decls.clearRetainingCapacity();
53505430
......@@ -5356,15 +5436,16 @@ pub fn processOutdatedAndDeletedDecls(mod: *Module) !void {
53565436 // it may be both in this `deleted_decls` set, as well as in the
53575437 // `Module.deletion_set`. To avoid deleting it twice, we remove it from the
53585438 // deletion set at this time.
5359 for (file.deleted_decls.items) |decl| {
5439 for (file.deleted_decls.items) |decl_index| {
5440 const decl = mod.declPtr(decl_index);
53605441 log.debug("deleted from source: {*} ({s})", .{ decl, decl.name });
53615442
53625443 // Remove from the namespace it resides in, preserving declaration order.
53635444 assert(decl.zir_decl_index != 0);
5364 _ = decl.src_namespace.decls.orderedRemoveAdapted(@as([]const u8, mem.sliceTo(decl.name, 0)), DeclAdapter{});
5445 _ = decl.src_namespace.decls.orderedRemoveAdapted(@as([]const u8, mem.sliceTo(decl.name, 0)), DeclAdapter{ .mod = mod });
53655446
5366 try mod.clearDecl(decl, &outdated_decls);
5367 decl.destroy(mod);
5447 try mod.clearDecl(decl_index, &outdated_decls);
5448 mod.destroyDecl(decl_index);
53685449 }
53695450 file.deleted_decls.clearRetainingCapacity();
53705451 }
......@@ -5393,13 +5474,13 @@ pub fn processExports(mod: *Module) !void {
53935474 if (gop.found_existing) {
53945475 new_export.status = .failed_retryable;
53955476 try mod.failed_exports.ensureUnusedCapacity(gpa, 1);
5396 const src_loc = new_export.getSrcLoc();
5477 const src_loc = new_export.getSrcLoc(mod);
53975478 const msg = try ErrorMsg.create(gpa, src_loc, "exported symbol collision: {s}", .{
53985479 new_export.options.name,
53995480 });
54005481 errdefer msg.destroy(gpa);
54015482 const other_export = gop.value_ptr.*;
5402 const other_src_loc = other_export.getSrcLoc();
5483 const other_src_loc = other_export.getSrcLoc(mod);
54035484 try mod.errNoteNonLazy(other_src_loc, msg, "other symbol here", .{});
54045485 mod.failed_exports.putAssumeCapacityNoClobber(new_export, msg);
54055486 new_export.status = .failed;
......@@ -5413,7 +5494,7 @@ pub fn processExports(mod: *Module) !void {
54135494 const new_export = exports[0];
54145495 new_export.status = .failed_retryable;
54155496 try mod.failed_exports.ensureUnusedCapacity(gpa, 1);
5416 const src_loc = new_export.getSrcLoc();
5497 const src_loc = new_export.getSrcLoc(mod);
54175498 const msg = try ErrorMsg.create(gpa, src_loc, "unable to export: {s}", .{
54185499 @errorName(err),
54195500 });
......@@ -5427,12 +5508,14 @@ pub fn populateTestFunctions(mod: *Module) !void {
54275508 const gpa = mod.gpa;
54285509 const builtin_pkg = mod.main_pkg.table.get("builtin").?;
54295510 const builtin_file = (mod.importPkg(builtin_pkg) catch unreachable).file;
5430 const builtin_namespace = builtin_file.root_decl.?.src_namespace;
5431 const decl = builtin_namespace.decls.getKeyAdapted(@as([]const u8, "test_functions"), DeclAdapter{}).?;
5511 const root_decl = mod.declPtr(builtin_file.root_decl.unwrap().?);
5512 const builtin_namespace = root_decl.src_namespace;
5513 const decl_index = builtin_namespace.decls.getKeyAdapted(@as([]const u8, "test_functions"), DeclAdapter{ .mod = mod }).?;
5514 const decl = mod.declPtr(decl_index);
54325515 var buf: Type.SlicePtrFieldTypeBuffer = undefined;
54335516 const tmp_test_fn_ty = decl.ty.slicePtrFieldType(&buf).elemType();
54345517
5435 const array_decl = d: {
5518 const array_decl_index = d: {
54365519 // Add mod.test_functions to an array decl then make the test_functions
54375520 // decl reference it as a slice.
54385521 var new_decl_arena = std.heap.ArenaAllocator.init(gpa);
......@@ -5440,50 +5523,52 @@ pub fn populateTestFunctions(mod: *Module) !void {
54405523 const arena = new_decl_arena.allocator();
54415524
54425525 const test_fn_vals = try arena.alloc(Value, mod.test_functions.count());
5443 const array_decl = try mod.createAnonymousDeclFromDecl(decl, decl.src_namespace, null, .{
5526 const array_decl_index = try mod.createAnonymousDeclFromDecl(decl, decl.src_namespace, null, .{
54445527 .ty = try Type.Tag.array.create(arena, .{
54455528 .len = test_fn_vals.len,
54465529 .elem_type = try tmp_test_fn_ty.copy(arena),
54475530 }),
54485531 .val = try Value.Tag.aggregate.create(arena, test_fn_vals),
54495532 });
5533 const array_decl = mod.declPtr(array_decl_index);
54505534
54515535 // Add a dependency on each test name and function pointer.
54525536 try array_decl.dependencies.ensureUnusedCapacity(gpa, test_fn_vals.len * 2);
54535537
5454 for (mod.test_functions.keys()) |test_decl, i| {
5538 for (mod.test_functions.keys()) |test_decl_index, i| {
5539 const test_decl = mod.declPtr(test_decl_index);
54555540 const test_name_slice = mem.sliceTo(test_decl.name, 0);
5456 const test_name_decl = n: {
5541 const test_name_decl_index = n: {
54575542 var name_decl_arena = std.heap.ArenaAllocator.init(gpa);
54585543 errdefer name_decl_arena.deinit();
54595544 const bytes = try name_decl_arena.allocator().dupe(u8, test_name_slice);
5460 const test_name_decl = try mod.createAnonymousDeclFromDecl(array_decl, array_decl.src_namespace, null, .{
5545 const test_name_decl_index = try mod.createAnonymousDeclFromDecl(array_decl, array_decl.src_namespace, null, .{
54615546 .ty = try Type.Tag.array_u8.create(name_decl_arena.allocator(), bytes.len),
54625547 .val = try Value.Tag.bytes.create(name_decl_arena.allocator(), bytes),
54635548 });
5464 try test_name_decl.finalizeNewArena(&name_decl_arena);
5465 break :n test_name_decl;
5549 try mod.declPtr(test_name_decl_index).finalizeNewArena(&name_decl_arena);
5550 break :n test_name_decl_index;
54665551 };
5467 array_decl.dependencies.putAssumeCapacityNoClobber(test_decl, {});
5468 array_decl.dependencies.putAssumeCapacityNoClobber(test_name_decl, {});
5469 try mod.linkerUpdateDecl(test_name_decl);
5552 array_decl.dependencies.putAssumeCapacityNoClobber(test_decl_index, {});
5553 array_decl.dependencies.putAssumeCapacityNoClobber(test_name_decl_index, {});
5554 try mod.linkerUpdateDecl(test_name_decl_index);
54705555
54715556 const field_vals = try arena.create([3]Value);
54725557 field_vals.* = .{
54735558 try Value.Tag.slice.create(arena, .{
5474 .ptr = try Value.Tag.decl_ref.create(arena, test_name_decl),
5559 .ptr = try Value.Tag.decl_ref.create(arena, test_name_decl_index),
54755560 .len = try Value.Tag.int_u64.create(arena, test_name_slice.len),
54765561 }), // name
5477 try Value.Tag.decl_ref.create(arena, test_decl), // func
5562 try Value.Tag.decl_ref.create(arena, test_decl_index), // func
54785563 Value.initTag(.null_value), // async_frame_size
54795564 };
54805565 test_fn_vals[i] = try Value.Tag.aggregate.create(arena, field_vals);
54815566 }
54825567
54835568 try array_decl.finalizeNewArena(&new_decl_arena);
5484 break :d array_decl;
5569 break :d array_decl_index;
54855570 };
5486 try mod.linkerUpdateDecl(array_decl);
5571 try mod.linkerUpdateDecl(array_decl_index);
54875572
54885573 {
54895574 var new_decl_arena = std.heap.ArenaAllocator.init(gpa);
......@@ -5493,7 +5578,7 @@ pub fn populateTestFunctions(mod: *Module) !void {
54935578 // This copy accesses the old Decl Type/Value so it must be done before `clearValues`.
54945579 const new_ty = try Type.Tag.const_slice.create(arena, try tmp_test_fn_ty.copy(arena));
54955580 const new_val = try Value.Tag.slice.create(arena, .{
5496 .ptr = try Value.Tag.decl_ref.create(arena, array_decl),
5581 .ptr = try Value.Tag.decl_ref.create(arena, array_decl_index),
54975582 .len = try Value.Tag.int_u64.create(arena, mod.test_functions.count()),
54985583 });
54995584
......@@ -5506,15 +5591,17 @@ pub fn populateTestFunctions(mod: *Module) !void {
55065591
55075592 try decl.finalizeNewArena(&new_decl_arena);
55085593 }
5509 try mod.linkerUpdateDecl(decl);
5594 try mod.linkerUpdateDecl(decl_index);
55105595}
55115596
5512pub fn linkerUpdateDecl(mod: *Module, decl: *Decl) !void {
5597pub fn linkerUpdateDecl(mod: *Module, decl_index: Decl.Index) !void {
55135598 const comp = mod.comp;
55145599
55155600 if (comp.bin_file.options.emit == null) return;
55165601
5517 comp.bin_file.updateDecl(mod, decl) catch |err| switch (err) {
5602 const decl = mod.declPtr(decl_index);
5603
5604 comp.bin_file.updateDecl(mod, decl_index) catch |err| switch (err) {
55185605 error.OutOfMemory => return error.OutOfMemory,
55195606 error.AnalysisFail => {
55205607 decl.analysis = .codegen_failure;
......@@ -5523,7 +5610,7 @@ pub fn linkerUpdateDecl(mod: *Module, decl: *Decl) !void {
55235610 else => {
55245611 const gpa = mod.gpa;
55255612 try mod.failed_decls.ensureUnusedCapacity(gpa, 1);
5526 mod.failed_decls.putAssumeCapacityNoClobber(decl, try ErrorMsg.create(
5613 mod.failed_decls.putAssumeCapacityNoClobber(decl_index, try ErrorMsg.create(
55275614 gpa,
55285615 decl.srcLoc(),
55295616 "unable to codegen: {s}",
......@@ -5566,3 +5653,64 @@ fn reportRetryableFileError(
55665653 }
55675654 gop.value_ptr.* = err_msg;
55685655}
5656
5657pub fn markReferencedDeclsAlive(mod: *Module, val: Value) void {
5658 switch (val.tag()) {
5659 .decl_ref_mut => return mod.markDeclIndexAlive(val.castTag(.decl_ref_mut).?.data.decl_index),
5660 .extern_fn => return mod.markDeclIndexAlive(val.castTag(.extern_fn).?.data.owner_decl),
5661 .function => return mod.markDeclIndexAlive(val.castTag(.function).?.data.owner_decl),
5662 .variable => return mod.markDeclIndexAlive(val.castTag(.variable).?.data.owner_decl),
5663 .decl_ref => return mod.markDeclIndexAlive(val.cast(Value.Payload.Decl).?.data),
5664
5665 .repeated,
5666 .eu_payload,
5667 .opt_payload,
5668 .empty_array_sentinel,
5669 => return mod.markReferencedDeclsAlive(val.cast(Value.Payload.SubValue).?.data),
5670
5671 .eu_payload_ptr,
5672 .opt_payload_ptr,
5673 => return mod.markReferencedDeclsAlive(val.cast(Value.Payload.PayloadPtr).?.data.container_ptr),
5674
5675 .slice => {
5676 const slice = val.cast(Value.Payload.Slice).?.data;
5677 mod.markReferencedDeclsAlive(slice.ptr);
5678 mod.markReferencedDeclsAlive(slice.len);
5679 },
5680
5681 .elem_ptr => {
5682 const elem_ptr = val.cast(Value.Payload.ElemPtr).?.data;
5683 return mod.markReferencedDeclsAlive(elem_ptr.array_ptr);
5684 },
5685 .field_ptr => {
5686 const field_ptr = val.cast(Value.Payload.FieldPtr).?.data;
5687 return mod.markReferencedDeclsAlive(field_ptr.container_ptr);
5688 },
5689 .aggregate => {
5690 for (val.castTag(.aggregate).?.data) |field_val| {
5691 mod.markReferencedDeclsAlive(field_val);
5692 }
5693 },
5694 .@"union" => {
5695 const data = val.cast(Value.Payload.Union).?.data;
5696 mod.markReferencedDeclsAlive(data.tag);
5697 mod.markReferencedDeclsAlive(data.val);
5698 },
5699
5700 else => {},
5701 }
5702}
5703
5704pub fn markDeclAlive(mod: *Module, decl: *Decl) void {
5705 if (decl.alive) return;
5706 decl.alive = true;
5707
5708 // This is the first time we are marking this Decl alive. We must
5709 // therefore recurse into its value and mark any Decl it references
5710 // as also alive, so that any Decl referenced does not get garbage collected.
5711 mod.markReferencedDeclsAlive(decl.val);
5712}
5713
5714fn markDeclIndexAlive(mod: *Module, decl_index: Decl.Index) void {
5715 return mod.markDeclAlive(mod.declPtr(decl_index));
5716}
src/RangeSet.zig+16-16
......@@ -1,12 +1,14 @@
11const std = @import("std");
22const Order = std.math.Order;
3const Type = @import("type.zig").Type;
4const Value = @import("value.zig").Value;
3
54const RangeSet = @This();
5const Module = @import("Module.zig");
66const SwitchProngSrc = @import("Module.zig").SwitchProngSrc;
7const Type = @import("type.zig").Type;
8const Value = @import("value.zig").Value;
79
810ranges: std.ArrayList(Range),
9target: std.Target,
11module: *Module,
1012
1113pub const Range = struct {
1214 first: Value,
......@@ -14,10 +16,10 @@ pub const Range = struct {
1416 src: SwitchProngSrc,
1517};
1618
17pub fn init(allocator: std.mem.Allocator, target: std.Target) RangeSet {
19pub fn init(allocator: std.mem.Allocator, module: *Module) RangeSet {
1820 return .{
1921 .ranges = std.ArrayList(Range).init(allocator),
20 .target = target,
22 .module = module,
2123 };
2224}
2325
......@@ -32,11 +34,9 @@ pub fn add(
3234 ty: Type,
3335 src: SwitchProngSrc,
3436) !?SwitchProngSrc {
35 const target = self.target;
36
3737 for (self.ranges.items) |range| {
38 if (last.compare(.gte, range.first, ty, target) and
39 first.compare(.lte, range.last, ty, target))
38 if (last.compare(.gte, range.first, ty, self.module) and
39 first.compare(.lte, range.last, ty, self.module))
4040 {
4141 return range.src; // They overlap.
4242 }
......@@ -49,26 +49,24 @@ pub fn add(
4949 return null;
5050}
5151
52const LessThanContext = struct { ty: Type, target: std.Target };
52const LessThanContext = struct { ty: Type, module: *Module };
5353
5454/// Assumes a and b do not overlap
5555fn lessThan(ctx: LessThanContext, a: Range, b: Range) bool {
56 return a.first.compare(.lt, b.first, ctx.ty, ctx.target);
56 return a.first.compare(.lt, b.first, ctx.ty, ctx.module);
5757}
5858
5959pub fn spans(self: *RangeSet, first: Value, last: Value, ty: Type) !bool {
6060 if (self.ranges.items.len == 0)
6161 return false;
6262
63 const target = self.target;
64
6563 std.sort.sort(Range, self.ranges.items, LessThanContext{
6664 .ty = ty,
67 .target = target,
65 .module = self.module,
6866 }, lessThan);
6967
70 if (!self.ranges.items[0].first.eql(first, ty, target) or
71 !self.ranges.items[self.ranges.items.len - 1].last.eql(last, ty, target))
68 if (!self.ranges.items[0].first.eql(first, ty, self.module) or
69 !self.ranges.items[self.ranges.items.len - 1].last.eql(last, ty, self.module))
7270 {
7371 return false;
7472 }
......@@ -78,6 +76,8 @@ pub fn spans(self: *RangeSet, first: Value, last: Value, ty: Type) !bool {
7876 var counter = try std.math.big.int.Managed.init(self.ranges.allocator);
7977 defer counter.deinit();
8078
79 const target = self.module.getTarget();
80
8181 // look for gaps
8282 for (self.ranges.items[1..]) |cur, i| {
8383 // i starts counting from the second item.
src/Sema.zig+780-784
......@@ -24,6 +24,7 @@ inst_map: InstMap = .{},
2424/// and `src_decl` of `Block` is the `Decl` of the callee.
2525/// This `Decl` owns the arena memory of this `Sema`.
2626owner_decl: *Decl,
27owner_decl_index: Decl.Index,
2728/// For an inline or comptime function call, this will be the root parent function
2829/// which contains the callsite. Corresponds to `owner_decl`.
2930owner_func: ?*Module.Fn,
......@@ -47,7 +48,7 @@ comptime_break_inst: Zir.Inst.Index = undefined,
4748/// access to the source location set by the previous instruction which did
4849/// contain a mapped source location.
4950src: LazySrcLoc = .{ .token_offset = 0 },
50decl_val_table: std.AutoHashMapUnmanaged(*Decl, Air.Inst.Ref) = .{},
51decl_val_table: std.AutoHashMapUnmanaged(Decl.Index, Air.Inst.Ref) = .{},
5152/// When doing a generic function instantiation, this array collects a
5253/// `Value` object for each parameter that is comptime known and thus elided
5354/// from the generated function. This memory is allocated by a parent `Sema` and
......@@ -111,10 +112,6 @@ pub const Block = struct {
111112 parent: ?*Block,
112113 /// Shared among all child blocks.
113114 sema: *Sema,
114 /// This Decl is the Decl according to the Zig source code corresponding to this Block.
115 /// This can vary during inline or comptime function calls. See `Sema.owner_decl`
116 /// for the one that will be the same for all Block instances.
117 src_decl: *Decl,
118115 /// The namespace to use for lookups from this source block
119116 /// When analyzing fields, this is different from src_decl.src_namepsace.
120117 namespace: *Namespace,
......@@ -130,6 +127,10 @@ pub const Block = struct {
130127 /// If runtime_index is not 0 then one of these is guaranteed to be non null.
131128 runtime_cond: ?LazySrcLoc = null,
132129 runtime_loop: ?LazySrcLoc = null,
130 /// This Decl is the Decl according to the Zig source code corresponding to this Block.
131 /// This can vary during inline or comptime function calls. See `Sema.owner_decl`
132 /// for the one that will be the same for all Block instances.
133 src_decl: Decl.Index,
133134 /// Non zero if a non-inline loop or a runtime conditional have been encountered.
134135 /// Stores to to comptime variables are only allowed when var.runtime_index <= runtime_index.
135136 runtime_index: u32 = 0,
......@@ -512,20 +513,21 @@ pub const Block = struct {
512513 }
513514
514515 /// `alignment` value of 0 means to use ABI alignment.
515 pub fn finish(wad: *WipAnonDecl, ty: Type, val: Value, alignment: u32) !*Decl {
516 pub fn finish(wad: *WipAnonDecl, ty: Type, val: Value, alignment: u32) !Decl.Index {
516517 const sema = wad.block.sema;
517518 // Do this ahead of time because `createAnonymousDecl` depends on calling
518519 // `type.hasRuntimeBits()`.
519520 _ = try sema.typeHasRuntimeBits(wad.block, wad.src, ty);
520 const new_decl = try sema.mod.createAnonymousDecl(wad.block, .{
521 const new_decl_index = try sema.mod.createAnonymousDecl(wad.block, .{
521522 .ty = ty,
522523 .val = val,
523524 });
525 const new_decl = sema.mod.declPtr(new_decl_index);
524526 new_decl.@"align" = alignment;
525 errdefer sema.mod.abortAnonDecl(new_decl);
527 errdefer sema.mod.abortAnonDecl(new_decl_index);
526528 try new_decl.finalizeNewArena(&wad.new_decl_arena);
527529 wad.finished = true;
528 return new_decl;
530 return new_decl_index;
529531 }
530532 };
531533};
......@@ -676,7 +678,7 @@ fn analyzeBodyInner(
676678 crash_info.setBodyIndex(i);
677679 const inst = body[i];
678680 std.log.scoped(.sema_zir).debug("sema ZIR {s} %{d}", .{
679 block.src_decl.src_namespace.file_scope.sub_file_path, inst,
681 sema.mod.declPtr(block.src_decl).src_namespace.file_scope.sub_file_path, inst,
680682 });
681683 const air_inst: Air.Inst.Ref = switch (tags[inst]) {
682684 // zig fmt: off
......@@ -1383,8 +1385,7 @@ pub fn resolveConstString(
13831385 const wanted_type = Type.initTag(.const_slice_u8);
13841386 const coerced_inst = try sema.coerce(block, wanted_type, air_inst, src);
13851387 const val = try sema.resolveConstValue(block, src, coerced_inst);
1386 const target = sema.mod.getTarget();
1387 return val.toAllocatedBytes(wanted_type, sema.arena, target);
1388 return val.toAllocatedBytes(wanted_type, sema.arena, sema.mod);
13881389}
13891390
13901391pub fn resolveType(sema: *Sema, block: *Block, src: LazySrcLoc, zir_ref: Zir.Inst.Ref) !Type {
......@@ -1538,28 +1539,24 @@ fn failWithDivideByZero(sema: *Sema, block: *Block, src: LazySrcLoc) CompileErro
15381539}
15391540
15401541fn failWithModRemNegative(sema: *Sema, block: *Block, src: LazySrcLoc, lhs_ty: Type, rhs_ty: Type) CompileError {
1541 const target = sema.mod.getTarget();
15421542 return sema.fail(block, src, "remainder division with '{}' and '{}': signed integers and floats must use @rem or @mod", .{
1543 lhs_ty.fmt(target), rhs_ty.fmt(target),
1543 lhs_ty.fmt(sema.mod), rhs_ty.fmt(sema.mod),
15441544 });
15451545}
15461546
15471547fn failWithExpectedOptionalType(sema: *Sema, block: *Block, src: LazySrcLoc, optional_ty: Type) CompileError {
1548 const target = sema.mod.getTarget();
1549 return sema.fail(block, src, "expected optional type, found {}", .{optional_ty.fmt(target)});
1548 return sema.fail(block, src, "expected optional type, found {}", .{optional_ty.fmt(sema.mod)});
15501549}
15511550
15521551fn failWithArrayInitNotSupported(sema: *Sema, block: *Block, src: LazySrcLoc, ty: Type) CompileError {
1553 const target = sema.mod.getTarget();
15541552 return sema.fail(block, src, "type '{}' does not support array initialization syntax", .{
1555 ty.fmt(target),
1553 ty.fmt(sema.mod),
15561554 });
15571555}
15581556
15591557fn failWithStructInitNotSupported(sema: *Sema, block: *Block, src: LazySrcLoc, ty: Type) CompileError {
1560 const target = sema.mod.getTarget();
15611558 return sema.fail(block, src, "type '{}' does not support struct initialization syntax", .{
1562 ty.fmt(target),
1559 ty.fmt(sema.mod),
15631560 });
15641561}
15651562
......@@ -1570,9 +1567,8 @@ fn failWithErrorSetCodeMissing(
15701567 dest_err_set_ty: Type,
15711568 src_err_set_ty: Type,
15721569) CompileError {
1573 const target = sema.mod.getTarget();
15741570 return sema.fail(block, src, "expected type '{}', found type '{}'", .{
1575 dest_err_set_ty.fmt(target), src_err_set_ty.fmt(target),
1571 dest_err_set_ty.fmt(sema.mod), src_err_set_ty.fmt(sema.mod),
15761572 });
15771573}
15781574
......@@ -1586,7 +1582,9 @@ fn errNote(
15861582 comptime format: []const u8,
15871583 args: anytype,
15881584) error{OutOfMemory}!void {
1589 return sema.mod.errNoteNonLazy(src.toSrcLoc(block.src_decl), parent, format, args);
1585 const mod = sema.mod;
1586 const src_decl = mod.declPtr(block.src_decl);
1587 return mod.errNoteNonLazy(src.toSrcLoc(src_decl), parent, format, args);
15901588}
15911589
15921590fn addFieldErrNote(
......@@ -1598,10 +1596,12 @@ fn addFieldErrNote(
15981596 comptime format: []const u8,
15991597 args: anytype,
16001598) !void {
1601 const decl = container_ty.getOwnerDecl();
1599 const mod = sema.mod;
1600 const decl_index = container_ty.getOwnerDecl();
1601 const decl = mod.declPtr(decl_index);
16021602 const tree = try sema.getAstTree(block);
16031603 const field_src = enumFieldSrcLoc(decl, tree.*, container_ty.getNodeOffset(), field_index);
1604 try sema.mod.errNoteNonLazy(field_src.toSrcLoc(decl), parent, format, args);
1604 try mod.errNoteNonLazy(field_src.toSrcLoc(decl), parent, format, args);
16051605}
16061606
16071607fn errMsg(
......@@ -1611,7 +1611,9 @@ fn errMsg(
16111611 comptime format: []const u8,
16121612 args: anytype,
16131613) error{OutOfMemory}!*Module.ErrorMsg {
1614 return Module.ErrorMsg.create(sema.gpa, src.toSrcLoc(block.src_decl), format, args);
1614 const mod = sema.mod;
1615 const src_decl = mod.declPtr(block.src_decl);
1616 return Module.ErrorMsg.create(sema.gpa, src.toSrcLoc(src_decl), format, args);
16151617}
16161618
16171619pub fn fail(
......@@ -1654,7 +1656,7 @@ fn failWithOwnedErrorMsg(sema: *Sema, block: *Block, err_msg: *Module.ErrorMsg)
16541656 sema.owner_decl.analysis = .sema_failure;
16551657 sema.owner_decl.generation = mod.generation;
16561658 }
1657 const gop = mod.failed_decls.getOrPutAssumeCapacity(sema.owner_decl);
1659 const gop = mod.failed_decls.getOrPutAssumeCapacity(sema.owner_decl_index);
16581660 if (gop.found_existing) {
16591661 // If there are multiple errors for the same Decl, prefer the first one added.
16601662 err_msg.destroy(mod.gpa);
......@@ -1756,7 +1758,7 @@ fn zirCoerceResultPtr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileE
17561758 try inferred_alloc.stored_inst_list.append(sema.arena, operand);
17571759
17581760 try sema.requireRuntimeBlock(block, src);
1759 const ptr_ty = try Type.ptr(sema.arena, target, .{
1761 const ptr_ty = try Type.ptr(sema.arena, sema.mod, .{
17601762 .pointee_type = pointee_ty,
17611763 .@"align" = inferred_alloc.alignment,
17621764 .@"addrspace" = addr_space,
......@@ -1770,7 +1772,7 @@ fn zirCoerceResultPtr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileE
17701772 // The alloc will turn into a Decl.
17711773 var anon_decl = try block.startAnonDecl(src);
17721774 defer anon_decl.deinit();
1773 iac.data.decl = try anon_decl.finish(
1775 iac.data.decl_index = try anon_decl.finish(
17741776 try pointee_ty.copy(anon_decl.arena()),
17751777 Value.undef,
17761778 iac.data.alignment,
......@@ -1778,7 +1780,7 @@ fn zirCoerceResultPtr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileE
17781780 if (iac.data.alignment != 0) {
17791781 try sema.resolveTypeLayout(block, src, pointee_ty);
17801782 }
1781 const ptr_ty = try Type.ptr(sema.arena, target, .{
1783 const ptr_ty = try Type.ptr(sema.arena, sema.mod, .{
17821784 .pointee_type = pointee_ty,
17831785 .@"align" = iac.data.alignment,
17841786 .@"addrspace" = addr_space,
......@@ -1786,7 +1788,7 @@ fn zirCoerceResultPtr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileE
17861788 return sema.addConstant(
17871789 ptr_ty,
17881790 try Value.Tag.decl_ref_mut.create(sema.arena, .{
1789 .decl = iac.data.decl,
1791 .decl_index = iac.data.decl_index,
17901792 .runtime_index = block.runtime_index,
17911793 }),
17921794 );
......@@ -1827,7 +1829,7 @@ fn zirCoerceResultPtr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileE
18271829 }
18281830 }
18291831
1830 const ptr_ty = try Type.ptr(sema.arena, target, .{
1832 const ptr_ty = try Type.ptr(sema.arena, sema.mod, .{
18311833 .pointee_type = pointee_ty,
18321834 .@"addrspace" = addr_space,
18331835 });
......@@ -1848,7 +1850,7 @@ fn zirCoerceResultPtr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileE
18481850 }
18491851 const ty_op = air_datas[trash_inst].ty_op;
18501852 const operand_ty = sema.typeOf(ty_op.operand);
1851 const ptr_operand_ty = try Type.ptr(sema.arena, target, .{
1853 const ptr_operand_ty = try Type.ptr(sema.arena, sema.mod, .{
18521854 .pointee_type = operand_ty,
18531855 .@"addrspace" = addr_space,
18541856 });
......@@ -1924,18 +1926,19 @@ fn zirStructDecl(
19241926 errdefer new_decl_arena.deinit();
19251927 const new_decl_arena_allocator = new_decl_arena.allocator();
19261928
1929 const mod = sema.mod;
19271930 const struct_obj = try new_decl_arena_allocator.create(Module.Struct);
19281931 const struct_ty = try Type.Tag.@"struct".create(new_decl_arena_allocator, struct_obj);
19291932 const struct_val = try Value.Tag.ty.create(new_decl_arena_allocator, struct_ty);
1930 const type_name = try sema.createTypeName(block, small.name_strategy, "struct");
1931 const new_decl = try sema.mod.createAnonymousDeclNamed(block, .{
1933 const new_decl_index = try sema.createAnonymousDeclTypeNamed(block, .{
19321934 .ty = Type.type,
19331935 .val = struct_val,
1934 }, type_name);
1936 }, small.name_strategy, "struct");
1937 const new_decl = mod.declPtr(new_decl_index);
19351938 new_decl.owns_tv = true;
1936 errdefer sema.mod.abortAnonDecl(new_decl);
1939 errdefer mod.abortAnonDecl(new_decl_index);
19371940 struct_obj.* = .{
1938 .owner_decl = new_decl,
1941 .owner_decl = new_decl_index,
19391942 .fields = .{},
19401943 .node_offset = src.node_offset,
19411944 .zir_index = inst,
......@@ -1953,15 +1956,23 @@ fn zirStructDecl(
19531956 });
19541957 try sema.analyzeStructDecl(new_decl, inst, struct_obj);
19551958 try new_decl.finalizeNewArena(&new_decl_arena);
1956 return sema.analyzeDeclVal(block, src, new_decl);
1959 return sema.analyzeDeclVal(block, src, new_decl_index);
19571960}
19581961
1959fn createTypeName(
1962fn createAnonymousDeclTypeNamed(
19601963 sema: *Sema,
19611964 block: *Block,
1965 typed_value: TypedValue,
19621966 name_strategy: Zir.Inst.NameStrategy,
19631967 anon_prefix: []const u8,
1964) ![:0]u8 {
1968) !Decl.Index {
1969 const mod = sema.mod;
1970 const namespace = block.namespace;
1971 const src_scope = block.wip_capture_scope;
1972 const src_decl = mod.declPtr(block.src_decl);
1973 const new_decl_index = try mod.allocateNewDecl(namespace, src_decl.src_node, src_scope);
1974 errdefer mod.destroyDecl(new_decl_index);
1975
19651976 switch (name_strategy) {
19661977 .anon => {
19671978 // It would be neat to have "struct:line:column" but this name has
......@@ -1970,20 +1981,24 @@ fn createTypeName(
19701981 // semantically analyzed.
19711982 // This name is also used as the key in the parent namespace so it cannot be
19721983 // renamed.
1973 const name_index = sema.mod.getNextAnonNameIndex();
1974 return std.fmt.allocPrintZ(sema.gpa, "{s}__{s}_{d}", .{
1975 block.src_decl.name, anon_prefix, name_index,
1984 const name = try std.fmt.allocPrintZ(sema.gpa, "{s}__{s}_{d}", .{
1985 src_decl.name, anon_prefix, @enumToInt(new_decl_index),
19761986 });
1987 try mod.initNewAnonDecl(new_decl_index, src_decl.src_line, namespace, typed_value, name);
1988 return new_decl_index;
1989 },
1990 .parent => {
1991 const name = try sema.gpa.dupeZ(u8, mem.sliceTo(sema.mod.declPtr(block.src_decl).name, 0));
1992 try mod.initNewAnonDecl(new_decl_index, src_decl.src_line, namespace, typed_value, name);
1993 return new_decl_index;
19771994 },
1978 .parent => return sema.gpa.dupeZ(u8, mem.sliceTo(block.src_decl.name, 0)),
19791995 .func => {
1980 const target = sema.mod.getTarget();
19811996 const fn_info = sema.code.getFnInfo(sema.func.?.zir_body_inst);
19821997 const zir_tags = sema.code.instructions.items(.tag);
19831998
19841999 var buf = std.ArrayList(u8).init(sema.gpa);
19852000 defer buf.deinit();
1986 try buf.appendSlice(mem.sliceTo(block.src_decl.name, 0));
2001 try buf.appendSlice(mem.sliceTo(sema.mod.declPtr(block.src_decl).name, 0));
19872002 try buf.appendSlice("(");
19882003
19892004 var arg_i: usize = 0;
......@@ -1995,7 +2010,7 @@ fn createTypeName(
19952010 const arg_val = sema.resolveConstMaybeUndefVal(block, .unneeded, arg) catch unreachable;
19962011
19972012 if (arg_i != 0) try buf.appendSlice(",");
1998 try buf.writer().print("{}", .{arg_val.fmtValue(sema.typeOf(arg), target)});
2013 try buf.writer().print("{}", .{arg_val.fmtValue(sema.typeOf(arg), sema.mod)});
19992014
20002015 arg_i += 1;
20012016 continue;
......@@ -2004,7 +2019,9 @@ fn createTypeName(
20042019 };
20052020
20062021 try buf.appendSlice(")");
2007 return buf.toOwnedSliceSentinel(0);
2022 const name = try buf.toOwnedSliceSentinel(0);
2023 try mod.initNewAnonDecl(new_decl_index, src_decl.src_line, namespace, typed_value, name);
2024 return new_decl_index;
20082025 },
20092026 }
20102027}
......@@ -2064,16 +2081,16 @@ fn zirEnumDecl(
20642081 };
20652082 const enum_ty = Type.initPayload(&enum_ty_payload.base);
20662083 const enum_val = try Value.Tag.ty.create(new_decl_arena_allocator, enum_ty);
2067 const type_name = try sema.createTypeName(block, small.name_strategy, "enum");
2068 const new_decl = try mod.createAnonymousDeclNamed(block, .{
2084 const new_decl_index = try sema.createAnonymousDeclTypeNamed(block, .{
20692085 .ty = Type.type,
20702086 .val = enum_val,
2071 }, type_name);
2087 }, small.name_strategy, "enum");
2088 const new_decl = mod.declPtr(new_decl_index);
20722089 new_decl.owns_tv = true;
2073 errdefer mod.abortAnonDecl(new_decl);
2090 errdefer mod.abortAnonDecl(new_decl_index);
20742091
20752092 enum_obj.* = .{
2076 .owner_decl = new_decl,
2093 .owner_decl = new_decl_index,
20772094 .tag_ty = Type.@"null",
20782095 .tag_ty_inferred = true,
20792096 .fields = .{},
......@@ -2101,7 +2118,7 @@ fn zirEnumDecl(
21012118 enum_obj.tag_ty_inferred = false;
21022119 }
21032120 try new_decl.finalizeNewArena(&new_decl_arena);
2104 return sema.analyzeDeclVal(block, src, new_decl);
2121 return sema.analyzeDeclVal(block, src, new_decl_index);
21052122 }
21062123 extra_index += body.len;
21072124
......@@ -2116,8 +2133,13 @@ fn zirEnumDecl(
21162133 // should be the enum itself.
21172134
21182135 const prev_owner_decl = sema.owner_decl;
2136 const prev_owner_decl_index = sema.owner_decl_index;
21192137 sema.owner_decl = new_decl;
2120 defer sema.owner_decl = prev_owner_decl;
2138 sema.owner_decl_index = new_decl_index;
2139 defer {
2140 sema.owner_decl = prev_owner_decl;
2141 sema.owner_decl_index = prev_owner_decl_index;
2142 }
21212143
21222144 const prev_owner_func = sema.owner_func;
21232145 sema.owner_func = null;
......@@ -2133,7 +2155,7 @@ fn zirEnumDecl(
21332155 var enum_block: Block = .{
21342156 .parent = null,
21352157 .sema = sema,
2136 .src_decl = new_decl,
2158 .src_decl = new_decl_index,
21372159 .namespace = &enum_obj.namespace,
21382160 .wip_capture_scope = wip_captures.scope,
21392161 .instructions = .{},
......@@ -2168,7 +2190,7 @@ fn zirEnumDecl(
21682190 if (any_values) {
21692191 try enum_obj.values.ensureTotalCapacityContext(new_decl_arena_allocator, fields_len, .{
21702192 .ty = enum_obj.tag_ty,
2171 .target = target,
2193 .mod = mod,
21722194 });
21732195 }
21742196
......@@ -2196,8 +2218,8 @@ fn zirEnumDecl(
21962218 const gop = enum_obj.fields.getOrPutAssumeCapacity(field_name);
21972219 if (gop.found_existing) {
21982220 const tree = try sema.getAstTree(block);
2199 const field_src = enumFieldSrcLoc(block.src_decl, tree.*, src.node_offset, field_i);
2200 const other_tag_src = enumFieldSrcLoc(block.src_decl, tree.*, src.node_offset, gop.index);
2221 const field_src = enumFieldSrcLoc(sema.mod.declPtr(block.src_decl), tree.*, src.node_offset, field_i);
2222 const other_tag_src = enumFieldSrcLoc(sema.mod.declPtr(block.src_decl), tree.*, src.node_offset, gop.index);
22012223 const msg = msg: {
22022224 const msg = try sema.errMsg(block, field_src, "duplicate enum tag", .{});
22032225 errdefer msg.destroy(gpa);
......@@ -2218,7 +2240,7 @@ fn zirEnumDecl(
22182240 const copied_tag_val = try tag_val.copy(new_decl_arena_allocator);
22192241 enum_obj.values.putAssumeCapacityNoClobberContext(copied_tag_val, {}, .{
22202242 .ty = enum_obj.tag_ty,
2221 .target = target,
2243 .mod = mod,
22222244 });
22232245 } else if (any_values) {
22242246 const tag_val = if (last_tag_val) |val|
......@@ -2229,13 +2251,13 @@ fn zirEnumDecl(
22292251 const copied_tag_val = try tag_val.copy(new_decl_arena_allocator);
22302252 enum_obj.values.putAssumeCapacityNoClobberContext(copied_tag_val, {}, .{
22312253 .ty = enum_obj.tag_ty,
2232 .target = target,
2254 .mod = mod,
22332255 });
22342256 }
22352257 }
22362258
22372259 try new_decl.finalizeNewArena(&new_decl_arena);
2238 return sema.analyzeDeclVal(block, src, new_decl);
2260 return sema.analyzeDeclVal(block, src, new_decl_index);
22392261}
22402262
22412263fn zirUnionDecl(
......@@ -2279,15 +2301,16 @@ fn zirUnionDecl(
22792301 };
22802302 const union_ty = Type.initPayload(&union_payload.base);
22812303 const union_val = try Value.Tag.ty.create(new_decl_arena_allocator, union_ty);
2282 const type_name = try sema.createTypeName(block, small.name_strategy, "union");
2283 const new_decl = try sema.mod.createAnonymousDeclNamed(block, .{
2304 const mod = sema.mod;
2305 const new_decl_index = try sema.createAnonymousDeclTypeNamed(block, .{
22842306 .ty = Type.type,
22852307 .val = union_val,
2286 }, type_name);
2308 }, small.name_strategy, "union");
2309 const new_decl = mod.declPtr(new_decl_index);
22872310 new_decl.owns_tv = true;
2288 errdefer sema.mod.abortAnonDecl(new_decl);
2311 errdefer mod.abortAnonDecl(new_decl_index);
22892312 union_obj.* = .{
2290 .owner_decl = new_decl,
2313 .owner_decl = new_decl_index,
22912314 .tag_ty = Type.initTag(.@"null"),
22922315 .fields = .{},
22932316 .node_offset = src.node_offset,
......@@ -2304,10 +2327,10 @@ fn zirUnionDecl(
23042327 &union_obj.namespace, new_decl, new_decl.name,
23052328 });
23062329
2307 _ = try sema.mod.scanNamespace(&union_obj.namespace, extra_index, decls_len, new_decl);
2330 _ = try mod.scanNamespace(&union_obj.namespace, extra_index, decls_len, new_decl);
23082331
23092332 try new_decl.finalizeNewArena(&new_decl_arena);
2310 return sema.analyzeDeclVal(block, src, new_decl);
2333 return sema.analyzeDeclVal(block, src, new_decl_index);
23112334}
23122335
23132336fn zirOpaqueDecl(
......@@ -2347,16 +2370,16 @@ fn zirOpaqueDecl(
23472370 };
23482371 const opaque_ty = Type.initPayload(&opaque_ty_payload.base);
23492372 const opaque_val = try Value.Tag.ty.create(new_decl_arena_allocator, opaque_ty);
2350 const type_name = try sema.createTypeName(block, small.name_strategy, "opaque");
2351 const new_decl = try mod.createAnonymousDeclNamed(block, .{
2373 const new_decl_index = try sema.createAnonymousDeclTypeNamed(block, .{
23522374 .ty = Type.type,
23532375 .val = opaque_val,
2354 }, type_name);
2376 }, small.name_strategy, "opaque");
2377 const new_decl = mod.declPtr(new_decl_index);
23552378 new_decl.owns_tv = true;
2356 errdefer mod.abortAnonDecl(new_decl);
2379 errdefer mod.abortAnonDecl(new_decl_index);
23572380
23582381 opaque_obj.* = .{
2359 .owner_decl = new_decl,
2382 .owner_decl = new_decl_index,
23602383 .node_offset = src.node_offset,
23612384 .namespace = .{
23622385 .parent = block.namespace,
......@@ -2371,7 +2394,7 @@ fn zirOpaqueDecl(
23712394 extra_index = try mod.scanNamespace(&opaque_obj.namespace, extra_index, decls_len, new_decl);
23722395
23732396 try new_decl.finalizeNewArena(&new_decl_arena);
2374 return sema.analyzeDeclVal(block, src, new_decl);
2397 return sema.analyzeDeclVal(block, src, new_decl_index);
23752398}
23762399
23772400fn zirErrorSetDecl(
......@@ -2395,13 +2418,14 @@ fn zirErrorSetDecl(
23952418 const error_set = try new_decl_arena_allocator.create(Module.ErrorSet);
23962419 const error_set_ty = try Type.Tag.error_set.create(new_decl_arena_allocator, error_set);
23972420 const error_set_val = try Value.Tag.ty.create(new_decl_arena_allocator, error_set_ty);
2398 const type_name = try sema.createTypeName(block, name_strategy, "error");
2399 const new_decl = try sema.mod.createAnonymousDeclNamed(block, .{
2421 const mod = sema.mod;
2422 const new_decl_index = try sema.createAnonymousDeclTypeNamed(block, .{
24002423 .ty = Type.type,
24012424 .val = error_set_val,
2402 }, type_name);
2425 }, name_strategy, "error");
2426 const new_decl = mod.declPtr(new_decl_index);
24032427 new_decl.owns_tv = true;
2404 errdefer sema.mod.abortAnonDecl(new_decl);
2428 errdefer mod.abortAnonDecl(new_decl_index);
24052429
24062430 var names = Module.ErrorSet.NameMap{};
24072431 try names.ensureUnusedCapacity(new_decl_arena_allocator, extra.data.fields_len);
......@@ -2410,7 +2434,7 @@ fn zirErrorSetDecl(
24102434 const extra_index_end = extra_index + (extra.data.fields_len * 2);
24112435 while (extra_index < extra_index_end) : (extra_index += 2) { // +2 to skip over doc_string
24122436 const str_index = sema.code.extra[extra_index];
2413 const kv = try sema.mod.getErrorValue(sema.code.nullTerminatedString(str_index));
2437 const kv = try mod.getErrorValue(sema.code.nullTerminatedString(str_index));
24142438 const result = names.getOrPutAssumeCapacity(kv.key);
24152439 assert(!result.found_existing); // verified in AstGen
24162440 }
......@@ -2419,12 +2443,12 @@ fn zirErrorSetDecl(
24192443 Module.ErrorSet.sortNames(&names);
24202444
24212445 error_set.* = .{
2422 .owner_decl = new_decl,
2446 .owner_decl = new_decl_index,
24232447 .node_offset = inst_data.src_node,
24242448 .names = names,
24252449 };
24262450 try new_decl.finalizeNewArena(&new_decl_arena);
2427 return sema.analyzeDeclVal(block, src, new_decl);
2451 return sema.analyzeDeclVal(block, src, new_decl_index);
24282452}
24292453
24302454fn zirRetPtr(
......@@ -2444,7 +2468,7 @@ fn zirRetPtr(
24442468 }
24452469
24462470 const target = sema.mod.getTarget();
2447 const ptr_type = try Type.ptr(sema.arena, target, .{
2471 const ptr_type = try Type.ptr(sema.arena, sema.mod, .{
24482472 .pointee_type = sema.fn_ret_ty,
24492473 .@"addrspace" = target_util.defaultAddressSpace(target, .local),
24502474 });
......@@ -2535,14 +2559,13 @@ fn zirIndexablePtrLen(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileE
25352559 else
25362560 object_ty;
25372561
2538 const target = sema.mod.getTarget();
25392562 if (!array_ty.isIndexable()) {
25402563 const msg = msg: {
25412564 const msg = try sema.errMsg(
25422565 block,
25432566 src,
25442567 "type '{}' does not support indexing",
2545 .{array_ty.fmt(target)},
2568 .{array_ty.fmt(sema.mod)},
25462569 );
25472570 errdefer msg.destroy(sema.gpa);
25482571 try sema.errNote(
......@@ -2598,7 +2621,7 @@ fn zirAllocExtended(
25982621 return sema.addConstant(
25992622 inferred_alloc_ty,
26002623 try Value.Tag.inferred_alloc_comptime.create(sema.arena, .{
2601 .decl = undefined,
2624 .decl_index = undefined,
26022625 .alignment = alignment,
26032626 }),
26042627 );
......@@ -2612,7 +2635,7 @@ fn zirAllocExtended(
26122635 const target = sema.mod.getTarget();
26132636 try sema.requireRuntimeBlock(block, src);
26142637 try sema.resolveTypeLayout(block, src, var_ty);
2615 const ptr_type = try Type.ptr(sema.arena, target, .{
2638 const ptr_type = try Type.ptr(sema.arena, sema.mod, .{
26162639 .pointee_type = var_ty,
26172640 .@"align" = alignment,
26182641 .@"addrspace" = target_util.defaultAddressSpace(target, .local),
......@@ -2649,7 +2672,7 @@ fn zirMakePtrConst(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErro
26492672 const ptr_ty = sema.typeOf(ptr);
26502673 var ptr_info = ptr_ty.ptrInfo().data;
26512674 ptr_info.mutable = false;
2652 const const_ptr_ty = try Type.ptr(sema.arena, sema.mod.getTarget(), ptr_info);
2675 const const_ptr_ty = try Type.ptr(sema.arena, sema.mod, ptr_info);
26532676
26542677 if (try sema.resolveMaybeUndefVal(block, inst_data.src(), ptr)) |val| {
26552678 return sema.addConstant(const_ptr_ty, val);
......@@ -2669,7 +2692,7 @@ fn zirAllocInferredComptime(
26692692 return sema.addConstant(
26702693 inferred_alloc_ty,
26712694 try Value.Tag.inferred_alloc_comptime.create(sema.arena, .{
2672 .decl = undefined,
2695 .decl_index = undefined,
26732696 .alignment = 0,
26742697 }),
26752698 );
......@@ -2687,7 +2710,7 @@ fn zirAlloc(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.I
26872710 return sema.analyzeComptimeAlloc(block, var_ty, 0, ty_src);
26882711 }
26892712 const target = sema.mod.getTarget();
2690 const ptr_type = try Type.ptr(sema.arena, target, .{
2713 const ptr_type = try Type.ptr(sema.arena, sema.mod, .{
26912714 .pointee_type = var_ty,
26922715 .@"addrspace" = target_util.defaultAddressSpace(target, .local),
26932716 });
......@@ -2709,7 +2732,7 @@ fn zirAllocMut(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
27092732 }
27102733 try sema.validateVarType(block, ty_src, var_ty, false);
27112734 const target = sema.mod.getTarget();
2712 const ptr_type = try Type.ptr(sema.arena, target, .{
2735 const ptr_type = try Type.ptr(sema.arena, sema.mod, .{
27132736 .pointee_type = var_ty,
27142737 .@"addrspace" = target_util.defaultAddressSpace(target, .local),
27152738 });
......@@ -2735,7 +2758,7 @@ fn zirAllocInferred(
27352758 return sema.addConstant(
27362759 inferred_alloc_ty,
27372760 try Value.Tag.inferred_alloc_comptime.create(sema.arena, .{
2738 .decl = undefined,
2761 .decl_index = undefined,
27392762 .alignment = 0,
27402763 }),
27412764 );
......@@ -2776,11 +2799,12 @@ fn zirResolveInferredAlloc(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Com
27762799 switch (ptr_val.tag()) {
27772800 .inferred_alloc_comptime => {
27782801 const iac = ptr_val.castTag(.inferred_alloc_comptime).?;
2779 const decl = iac.data.decl;
2780 try sema.mod.declareDeclDependency(sema.owner_decl, decl);
2802 const decl_index = iac.data.decl_index;
2803 try sema.mod.declareDeclDependency(sema.owner_decl_index, decl_index);
27812804
2805 const decl = sema.mod.declPtr(decl_index);
27822806 const final_elem_ty = try decl.ty.copy(sema.arena);
2783 const final_ptr_ty = try Type.ptr(sema.arena, target, .{
2807 const final_ptr_ty = try Type.ptr(sema.arena, sema.mod, .{
27842808 .pointee_type = final_elem_ty,
27852809 .mutable = var_is_mut,
27862810 .@"align" = iac.data.alignment,
......@@ -2791,11 +2815,11 @@ fn zirResolveInferredAlloc(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Com
27912815
27922816 if (var_is_mut) {
27932817 sema.air_values.items[value_index] = try Value.Tag.decl_ref_mut.create(sema.arena, .{
2794 .decl = decl,
2818 .decl_index = decl_index,
27952819 .runtime_index = block.runtime_index,
27962820 });
27972821 } else {
2798 sema.air_values.items[value_index] = try Value.Tag.decl_ref.create(sema.arena, decl);
2822 sema.air_values.items[value_index] = try Value.Tag.decl_ref.create(sema.arena, decl_index);
27992823 }
28002824 },
28012825 .inferred_alloc => {
......@@ -2803,7 +2827,7 @@ fn zirResolveInferredAlloc(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Com
28032827 const peer_inst_list = inferred_alloc.data.stored_inst_list.items;
28042828 const final_elem_ty = try sema.resolvePeerTypes(block, ty_src, peer_inst_list, .none);
28052829
2806 const final_ptr_ty = try Type.ptr(sema.arena, target, .{
2830 const final_ptr_ty = try Type.ptr(sema.arena, sema.mod, .{
28072831 .pointee_type = final_elem_ty,
28082832 .mutable = var_is_mut,
28092833 .@"align" = inferred_alloc.data.alignment,
......@@ -2873,22 +2897,22 @@ fn zirResolveInferredAlloc(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Com
28732897 if (store_op.lhs != Air.indexToRef(bitcast_inst)) break :ct;
28742898 if (air_datas[bitcast_inst].ty_op.operand != Air.indexToRef(const_inst)) break :ct;
28752899
2876 const new_decl = d: {
2900 const new_decl_index = d: {
28772901 var anon_decl = try block.startAnonDecl(src);
28782902 defer anon_decl.deinit();
2879 const new_decl = try anon_decl.finish(
2903 const new_decl_index = try anon_decl.finish(
28802904 try final_elem_ty.copy(anon_decl.arena()),
28812905 try store_val.copy(anon_decl.arena()),
28822906 inferred_alloc.data.alignment,
28832907 );
2884 break :d new_decl;
2908 break :d new_decl_index;
28852909 };
2886 try sema.mod.declareDeclDependency(sema.owner_decl, new_decl);
2910 try sema.mod.declareDeclDependency(sema.owner_decl_index, new_decl_index);
28872911
28882912 // Even though we reuse the constant instruction, we still remove it from the
28892913 // block so that codegen does not see it.
28902914 block.instructions.shrinkRetainingCapacity(block.instructions.items.len - 3);
2891 sema.air_values.items[value_index] = try Value.Tag.decl_ref.create(sema.arena, new_decl);
2915 sema.air_values.items[value_index] = try Value.Tag.decl_ref.create(sema.arena, new_decl_index);
28922916 // if bitcast ty ref needs to be made const, make_ptr_const
28932917 // ZIR handles it later, so we can just use the ty ref here.
28942918 air_datas[ptr_inst].ty_pl.ty = air_datas[bitcast_inst].ty_op.ty;
......@@ -3218,10 +3242,11 @@ fn validateStructInit(
32183242 }
32193243
32203244 if (root_msg) |msg| {
3221 const fqn = try struct_obj.getFullyQualifiedName(gpa);
3245 const mod = sema.mod;
3246 const fqn = try struct_obj.getFullyQualifiedName(mod);
32223247 defer gpa.free(fqn);
3223 try sema.mod.errNoteNonLazy(
3224 struct_obj.srcLoc(),
3248 try mod.errNoteNonLazy(
3249 struct_obj.srcLoc(mod),
32253250 msg,
32263251 "struct '{s}' declared here",
32273252 .{fqn},
......@@ -3325,10 +3350,10 @@ fn validateStructInit(
33253350 }
33263351
33273352 if (root_msg) |msg| {
3328 const fqn = try struct_obj.getFullyQualifiedName(gpa);
3353 const fqn = try struct_obj.getFullyQualifiedName(sema.mod);
33293354 defer gpa.free(fqn);
33303355 try sema.mod.errNoteNonLazy(
3331 struct_obj.srcLoc(),
3356 struct_obj.srcLoc(sema.mod),
33323357 msg,
33333358 "struct '{s}' declared here",
33343359 .{fqn},
......@@ -3497,9 +3522,8 @@ fn failWithBadMemberAccess(
34973522 else => unreachable,
34983523 };
34993524 const msg = msg: {
3500 const target = sema.mod.getTarget();
35013525 const msg = try sema.errMsg(block, field_src, "{s} '{}' has no member named '{s}'", .{
3502 kw_name, agg_ty.fmt(target), field_name,
3526 kw_name, agg_ty.fmt(sema.mod), field_name,
35033527 });
35043528 errdefer msg.destroy(sema.gpa);
35053529 try sema.addDeclaredHereNote(msg, agg_ty);
......@@ -3517,7 +3541,7 @@ fn failWithBadStructFieldAccess(
35173541) CompileError {
35183542 const gpa = sema.gpa;
35193543
3520 const fqn = try struct_obj.getFullyQualifiedName(gpa);
3544 const fqn = try struct_obj.getFullyQualifiedName(sema.mod);
35213545 defer gpa.free(fqn);
35223546
35233547 const msg = msg: {
......@@ -3528,7 +3552,7 @@ fn failWithBadStructFieldAccess(
35283552 .{ field_name, fqn },
35293553 );
35303554 errdefer msg.destroy(gpa);
3531 try sema.mod.errNoteNonLazy(struct_obj.srcLoc(), msg, "struct declared here", .{});
3555 try sema.mod.errNoteNonLazy(struct_obj.srcLoc(sema.mod), msg, "struct declared here", .{});
35323556 break :msg msg;
35333557 };
35343558 return sema.failWithOwnedErrorMsg(block, msg);
......@@ -3543,7 +3567,7 @@ fn failWithBadUnionFieldAccess(
35433567) CompileError {
35443568 const gpa = sema.gpa;
35453569
3546 const fqn = try union_obj.getFullyQualifiedName(gpa);
3570 const fqn = try union_obj.getFullyQualifiedName(sema.mod);
35473571 defer gpa.free(fqn);
35483572
35493573 const msg = msg: {
......@@ -3554,14 +3578,14 @@ fn failWithBadUnionFieldAccess(
35543578 .{ field_name, fqn },
35553579 );
35563580 errdefer msg.destroy(gpa);
3557 try sema.mod.errNoteNonLazy(union_obj.srcLoc(), msg, "union declared here", .{});
3581 try sema.mod.errNoteNonLazy(union_obj.srcLoc(sema.mod), msg, "union declared here", .{});
35583582 break :msg msg;
35593583 };
35603584 return sema.failWithOwnedErrorMsg(block, msg);
35613585}
35623586
35633587fn addDeclaredHereNote(sema: *Sema, parent: *Module.ErrorMsg, decl_ty: Type) !void {
3564 const src_loc = decl_ty.declSrcLocOrNull() orelse return;
3588 const src_loc = decl_ty.declSrcLocOrNull(sema.mod) orelse return;
35653589 const category = switch (decl_ty.zigTypeTag()) {
35663590 .Union => "union",
35673591 .Struct => "struct",
......@@ -3645,7 +3669,7 @@ fn storeToInferredAlloc(
36453669 try inferred_alloc.data.stored_inst_list.append(sema.arena, operand);
36463670 // Create a runtime bitcast instruction with exactly the type the pointer wants.
36473671 const target = sema.mod.getTarget();
3648 const ptr_ty = try Type.ptr(sema.arena, target, .{
3672 const ptr_ty = try Type.ptr(sema.arena, sema.mod, .{
36493673 .pointee_type = operand_ty,
36503674 .@"align" = inferred_alloc.data.alignment,
36513675 .@"addrspace" = target_util.defaultAddressSpace(target, .local),
......@@ -3670,7 +3694,7 @@ fn storeToInferredAllocComptime(
36703694 }
36713695 var anon_decl = try block.startAnonDecl(src);
36723696 defer anon_decl.deinit();
3673 iac.data.decl = try anon_decl.finish(
3697 iac.data.decl_index = try anon_decl.finish(
36743698 try operand_ty.copy(anon_decl.arena()),
36753699 try operand_val.copy(anon_decl.arena()),
36763700 iac.data.alignment,
......@@ -3869,7 +3893,6 @@ fn zirCompileLog(
38693893 const src_node = extra.data.src_node;
38703894 const src: LazySrcLoc = .{ .node_offset = src_node };
38713895 const args = sema.code.refSlice(extra.end, extended.small);
3872 const target = sema.mod.getTarget();
38733896
38743897 for (args) |arg_ref, i| {
38753898 if (i != 0) try writer.print(", ", .{});
......@@ -3878,15 +3901,15 @@ fn zirCompileLog(
38783901 const arg_ty = sema.typeOf(arg);
38793902 if (try sema.resolveMaybeUndefVal(block, src, arg)) |val| {
38803903 try writer.print("@as({}, {})", .{
3881 arg_ty.fmt(target), val.fmtValue(arg_ty, target),
3904 arg_ty.fmt(sema.mod), val.fmtValue(arg_ty, sema.mod),
38823905 });
38833906 } else {
3884 try writer.print("@as({}, [runtime value])", .{arg_ty.fmt(target)});
3907 try writer.print("@as({}, [runtime value])", .{arg_ty.fmt(sema.mod)});
38853908 }
38863909 }
38873910 try writer.print("\n", .{});
38883911
3889 const gop = try sema.mod.compile_log_decls.getOrPut(sema.gpa, sema.owner_decl);
3912 const gop = try sema.mod.compile_log_decls.getOrPut(sema.gpa, sema.owner_decl_index);
38903913 if (!gop.found_existing) {
38913914 gop.value_ptr.* = src_node;
38923915 }
......@@ -3996,7 +4019,8 @@ fn zirCImport(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index) CompileEr
39964019 // Ignore the result, all the relevant operations have written to c_import_buf already.
39974020 _ = try sema.analyzeBodyBreak(&child_block, body);
39984021
3999 const c_import_res = sema.mod.comp.cImport(c_import_buf.items) catch |err|
4022 const mod = sema.mod;
4023 const c_import_res = mod.comp.cImport(c_import_buf.items) catch |err|
40004024 return sema.fail(&child_block, src, "C import failed: {s}", .{@errorName(err)});
40014025
40024026 if (c_import_res.errors.len != 0) {
......@@ -4004,12 +4028,12 @@ fn zirCImport(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index) CompileEr
40044028 const msg = try sema.errMsg(&child_block, src, "C import failed", .{});
40054029 errdefer msg.destroy(sema.gpa);
40064030
4007 if (!sema.mod.comp.bin_file.options.link_libc)
4031 if (!mod.comp.bin_file.options.link_libc)
40084032 try sema.errNote(&child_block, src, msg, "libc headers not available; compilation does not link against libc", .{});
40094033
40104034 for (c_import_res.errors) |_| {
40114035 // TODO integrate with LazySrcLoc
4012 // try sema.mod.errNoteNonLazy(.{}, msg, "{s}", .{clang_err.msg_ptr[0..clang_err.msg_len]});
4036 // try mod.errNoteNonLazy(.{}, msg, "{s}", .{clang_err.msg_ptr[0..clang_err.msg_len]});
40134037 // if (clang_err.filename_ptr) |p| p[0..clang_err.filename_len] else "(no file)",
40144038 // clang_err.line + 1,
40154039 // clang_err.column + 1,
......@@ -4027,20 +4051,21 @@ fn zirCImport(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index) CompileEr
40274051 error.OutOfMemory => return error.OutOfMemory,
40284052 else => unreachable, // we pass null for root_src_dir_path
40294053 };
4030 const std_pkg = sema.mod.main_pkg.table.get("std").?;
4031 const builtin_pkg = sema.mod.main_pkg.table.get("builtin").?;
4054 const std_pkg = mod.main_pkg.table.get("std").?;
4055 const builtin_pkg = mod.main_pkg.table.get("builtin").?;
40324056 try c_import_pkg.add(sema.gpa, "builtin", builtin_pkg);
40334057 try c_import_pkg.add(sema.gpa, "std", std_pkg);
40344058
4035 const result = sema.mod.importPkg(c_import_pkg) catch |err|
4059 const result = mod.importPkg(c_import_pkg) catch |err|
40364060 return sema.fail(&child_block, src, "C import failed: {s}", .{@errorName(err)});
40374061
4038 sema.mod.astGenFile(result.file) catch |err|
4062 mod.astGenFile(result.file) catch |err|
40394063 return sema.fail(&child_block, src, "C import failed: {s}", .{@errorName(err)});
40404064
4041 try sema.mod.semaFile(result.file);
4042 const file_root_decl = result.file.root_decl.?;
4043 try sema.mod.declareDeclDependency(sema.owner_decl, file_root_decl);
4065 try mod.semaFile(result.file);
4066 const file_root_decl_index = result.file.root_decl.unwrap().?;
4067 const file_root_decl = mod.declPtr(file_root_decl_index);
4068 try mod.declareDeclDependency(sema.owner_decl_index, file_root_decl_index);
40444069 return sema.addConstant(file_root_decl.ty, file_root_decl.val);
40454070}
40464071
......@@ -4139,6 +4164,7 @@ fn analyzeBlockBody(
41394164 defer tracy.end();
41404165
41414166 const gpa = sema.gpa;
4167 const mod = sema.mod;
41424168
41434169 // Blocks must terminate with noreturn instruction.
41444170 assert(child_block.instructions.items.len != 0);
......@@ -4173,16 +4199,16 @@ fn analyzeBlockBody(
41734199
41744200 const type_src = src; // TODO: better source location
41754201 const valid_rt = try sema.validateRunTimeType(child_block, type_src, resolved_ty, false);
4176 const target = sema.mod.getTarget();
41774202 if (!valid_rt) {
41784203 const msg = msg: {
4179 const msg = try sema.errMsg(child_block, type_src, "value with comptime only type '{}' depends on runtime control flow", .{resolved_ty.fmt(target)});
4204 const msg = try sema.errMsg(child_block, type_src, "value with comptime only type '{}' depends on runtime control flow", .{resolved_ty.fmt(mod)});
41804205 errdefer msg.destroy(sema.gpa);
41814206
41824207 const runtime_src = child_block.runtime_cond orelse child_block.runtime_loop.?;
41834208 try sema.errNote(child_block, runtime_src, msg, "runtime control flow here", .{});
41844209
4185 try sema.explainWhyTypeIsComptime(child_block, type_src, msg, type_src.toSrcLoc(child_block.src_decl), resolved_ty);
4210 const child_src_decl = mod.declPtr(child_block.src_decl);
4211 try sema.explainWhyTypeIsComptime(child_block, type_src, msg, type_src.toSrcLoc(child_src_decl), resolved_ty);
41864212
41874213 break :msg msg;
41884214 };
......@@ -4204,7 +4230,7 @@ fn analyzeBlockBody(
42044230 const br_operand = sema.air_instructions.items(.data)[br].br.operand;
42054231 const br_operand_src = src;
42064232 const br_operand_ty = sema.typeOf(br_operand);
4207 if (br_operand_ty.eql(resolved_ty, target)) {
4233 if (br_operand_ty.eql(resolved_ty, mod)) {
42084234 // No type coercion needed.
42094235 continue;
42104236 }
......@@ -4262,9 +4288,9 @@ fn zirExport(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void
42624288 if (extra.namespace != .none) {
42634289 return sema.fail(block, src, "TODO: implement exporting with field access", .{});
42644290 }
4265 const decl = try sema.lookupIdentifier(block, operand_src, decl_name);
4291 const decl_index = try sema.lookupIdentifier(block, operand_src, decl_name);
42664292 const options = try sema.resolveExportOptions(block, options_src, extra.options);
4267 try sema.analyzeExport(block, src, options, decl);
4293 try sema.analyzeExport(block, src, options, decl_index);
42684294}
42694295
42704296fn zirExportValue(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void {
......@@ -4278,11 +4304,11 @@ fn zirExportValue(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
42784304 const options_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
42794305 const operand = try sema.resolveInstConst(block, operand_src, extra.operand);
42804306 const options = try sema.resolveExportOptions(block, options_src, extra.options);
4281 const decl = switch (operand.val.tag()) {
4307 const decl_index = switch (operand.val.tag()) {
42824308 .function => operand.val.castTag(.function).?.data.owner_decl,
42834309 else => return sema.fail(block, operand_src, "TODO implement exporting arbitrary Value objects", .{}), // TODO put this Value into an anonymous Decl and then export it.
42844310 };
4285 try sema.analyzeExport(block, src, options, decl);
4311 try sema.analyzeExport(block, src, options, decl_index);
42864312}
42874313
42884314pub fn analyzeExport(
......@@ -4290,18 +4316,18 @@ pub fn analyzeExport(
42904316 block: *Block,
42914317 src: LazySrcLoc,
42924318 borrowed_options: std.builtin.ExportOptions,
4293 exported_decl: *Decl,
4319 exported_decl_index: Decl.Index,
42944320) !void {
42954321 const Export = Module.Export;
42964322 const mod = sema.mod;
4297 const target = mod.getTarget();
42984323
4299 try mod.ensureDeclAnalyzed(exported_decl);
4324 try mod.ensureDeclAnalyzed(exported_decl_index);
4325 const exported_decl = mod.declPtr(exported_decl_index);
43004326 // TODO run the same checks as we do for C ABI struct fields
43014327 switch (exported_decl.ty.zigTypeTag()) {
43024328 .Fn, .Int, .Enum, .Struct, .Union, .Array, .Float => {},
43034329 else => return sema.fail(block, src, "unable to export type '{}'", .{
4304 exported_decl.ty.fmt(target),
4330 exported_decl.ty.fmt(sema.mod),
43054331 }),
43064332 }
43074333
......@@ -4319,13 +4345,6 @@ pub fn analyzeExport(
43194345 const section: ?[]const u8 = if (borrowed_options.section) |s| try gpa.dupe(u8, s) else null;
43204346 errdefer if (section) |s| gpa.free(s);
43214347
4322 const src_decl = block.src_decl;
4323 const owner_decl = sema.owner_decl;
4324
4325 log.debug("exporting Decl '{s}' as symbol '{s}' from Decl '{s}'", .{
4326 exported_decl.name, symbol_name, owner_decl.name,
4327 });
4328
43294348 new_export.* = .{
43304349 .options = .{
43314350 .name = symbol_name,
......@@ -4343,14 +4362,14 @@ pub fn analyzeExport(
43434362 .spirv => .{ .spirv = {} },
43444363 .nvptx => .{ .nvptx = {} },
43454364 },
4346 .owner_decl = owner_decl,
4347 .src_decl = src_decl,
4348 .exported_decl = exported_decl,
4365 .owner_decl = sema.owner_decl_index,
4366 .src_decl = block.src_decl,
4367 .exported_decl = exported_decl_index,
43494368 .status = .in_progress,
43504369 };
43514370
43524371 // Add to export_owners table.
4353 const eo_gop = mod.export_owners.getOrPutAssumeCapacity(owner_decl);
4372 const eo_gop = mod.export_owners.getOrPutAssumeCapacity(sema.owner_decl_index);
43544373 if (!eo_gop.found_existing) {
43554374 eo_gop.value_ptr.* = &[0]*Export{};
43564375 }
......@@ -4359,7 +4378,7 @@ pub fn analyzeExport(
43594378 errdefer eo_gop.value_ptr.* = gpa.shrink(eo_gop.value_ptr.*, eo_gop.value_ptr.len - 1);
43604379
43614380 // Add to exported_decl table.
4362 const de_gop = mod.decl_exports.getOrPutAssumeCapacity(exported_decl);
4381 const de_gop = mod.decl_exports.getOrPutAssumeCapacity(exported_decl_index);
43634382 if (!de_gop.found_existing) {
43644383 de_gop.value_ptr.* = &[0]*Export{};
43654384 }
......@@ -4381,7 +4400,8 @@ fn zirSetAlignStack(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErr
43814400 const func = sema.owner_func orelse
43824401 return sema.fail(block, src, "@setAlignStack outside function body", .{});
43834402
4384 switch (func.owner_decl.ty.fnCallingConvention()) {
4403 const fn_owner_decl = sema.mod.declPtr(func.owner_decl);
4404 switch (fn_owner_decl.ty.fnCallingConvention()) {
43854405 .Naked => return sema.fail(block, src, "@setAlignStack in naked function", .{}),
43864406 .Inline => return sema.fail(block, src, "@setAlignStack in inline function", .{}),
43874407 else => {},
......@@ -4561,8 +4581,8 @@ fn zirDeclRef(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
45614581 const inst_data = sema.code.instructions.items(.data)[inst].str_tok;
45624582 const src = inst_data.src();
45634583 const decl_name = inst_data.get(sema.code);
4564 const decl = try sema.lookupIdentifier(block, src, decl_name);
4565 return sema.analyzeDeclRef(decl);
4584 const decl_index = try sema.lookupIdentifier(block, src, decl_name);
4585 return sema.analyzeDeclRef(decl_index);
45664586}
45674587
45684588fn zirDeclVal(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
......@@ -4573,11 +4593,11 @@ fn zirDeclVal(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
45734593 return sema.analyzeDeclVal(block, src, decl);
45744594}
45754595
4576fn lookupIdentifier(sema: *Sema, block: *Block, src: LazySrcLoc, name: []const u8) !*Decl {
4596fn lookupIdentifier(sema: *Sema, block: *Block, src: LazySrcLoc, name: []const u8) !Decl.Index {
45774597 var namespace = block.namespace;
45784598 while (true) {
4579 if (try sema.lookupInNamespace(block, src, namespace, name, false)) |decl| {
4580 return decl;
4599 if (try sema.lookupInNamespace(block, src, namespace, name, false)) |decl_index| {
4600 return decl_index;
45814601 }
45824602 namespace = namespace.parent orelse break;
45834603 }
......@@ -4593,12 +4613,13 @@ fn lookupInNamespace(
45934613 namespace: *Namespace,
45944614 ident_name: []const u8,
45954615 observe_usingnamespace: bool,
4596) CompileError!?*Decl {
4616) CompileError!?Decl.Index {
45974617 const mod = sema.mod;
45984618
4599 const namespace_decl = namespace.getDecl();
4619 const namespace_decl_index = namespace.getDeclIndex();
4620 const namespace_decl = sema.mod.declPtr(namespace_decl_index);
46004621 if (namespace_decl.analysis == .file_failure) {
4601 try mod.declareDeclDependency(sema.owner_decl, namespace_decl);
4622 try mod.declareDeclDependency(sema.owner_decl_index, namespace_decl_index);
46024623 return error.AnalysisFail;
46034624 }
46044625
......@@ -4610,7 +4631,7 @@ fn lookupInNamespace(
46104631 defer checked_namespaces.deinit(gpa);
46114632
46124633 // Keep track of name conflicts for error notes.
4613 var candidates: std.ArrayListUnmanaged(*Decl) = .{};
4634 var candidates: std.ArrayListUnmanaged(Decl.Index) = .{};
46144635 defer candidates.deinit(gpa);
46154636
46164637 try checked_namespaces.put(gpa, namespace, {});
......@@ -4618,23 +4639,25 @@ fn lookupInNamespace(
46184639
46194640 while (check_i < checked_namespaces.count()) : (check_i += 1) {
46204641 const check_ns = checked_namespaces.keys()[check_i];
4621 if (check_ns.decls.getKeyAdapted(ident_name, Module.DeclAdapter{})) |decl| {
4642 if (check_ns.decls.getKeyAdapted(ident_name, Module.DeclAdapter{ .mod = mod })) |decl_index| {
46224643 // Skip decls which are not marked pub, which are in a different
46234644 // file than the `a.b`/`@hasDecl` syntax.
4645 const decl = mod.declPtr(decl_index);
46244646 if (decl.is_pub or src_file == decl.getFileScope()) {
4625 try candidates.append(gpa, decl);
4647 try candidates.append(gpa, decl_index);
46264648 }
46274649 }
46284650 var it = check_ns.usingnamespace_set.iterator();
46294651 while (it.next()) |entry| {
4630 const sub_usingnamespace_decl = entry.key_ptr.*;
4652 const sub_usingnamespace_decl_index = entry.key_ptr.*;
4653 const sub_usingnamespace_decl = mod.declPtr(sub_usingnamespace_decl_index);
46314654 const sub_is_pub = entry.value_ptr.*;
46324655 if (!sub_is_pub and src_file != sub_usingnamespace_decl.getFileScope()) {
46334656 // Skip usingnamespace decls which are not marked pub, which are in
46344657 // a different file than the `a.b`/`@hasDecl` syntax.
46354658 continue;
46364659 }
4637 try sema.ensureDeclAnalyzed(sub_usingnamespace_decl);
4660 try sema.ensureDeclAnalyzed(sub_usingnamespace_decl_index);
46384661 const ns_ty = sub_usingnamespace_decl.val.castTag(.ty).?.data;
46394662 const sub_ns = ns_ty.getNamespace().?;
46404663 try checked_namespaces.put(gpa, sub_ns, {});
......@@ -4644,15 +4667,16 @@ fn lookupInNamespace(
46444667 switch (candidates.items.len) {
46454668 0 => {},
46464669 1 => {
4647 const decl = candidates.items[0];
4648 try mod.declareDeclDependency(sema.owner_decl, decl);
4649 return decl;
4670 const decl_index = candidates.items[0];
4671 try mod.declareDeclDependency(sema.owner_decl_index, decl_index);
4672 return decl_index;
46504673 },
46514674 else => {
46524675 const msg = msg: {
46534676 const msg = try sema.errMsg(block, src, "ambiguous reference", .{});
46544677 errdefer msg.destroy(gpa);
4655 for (candidates.items) |candidate| {
4678 for (candidates.items) |candidate_index| {
4679 const candidate = mod.declPtr(candidate_index);
46564680 const src_loc = candidate.srcLoc();
46574681 try mod.errNoteNonLazy(src_loc, msg, "declared here", .{});
46584682 }
......@@ -4661,9 +4685,9 @@ fn lookupInNamespace(
46614685 return sema.failWithOwnedErrorMsg(block, msg);
46624686 },
46634687 }
4664 } else if (namespace.decls.getKeyAdapted(ident_name, Module.DeclAdapter{})) |decl| {
4665 try mod.declareDeclDependency(sema.owner_decl, decl);
4666 return decl;
4688 } else if (namespace.decls.getKeyAdapted(ident_name, Module.DeclAdapter{ .mod = mod })) |decl_index| {
4689 try mod.declareDeclDependency(sema.owner_decl_index, decl_index);
4690 return decl_index;
46674691 }
46684692
46694693 log.debug("{*} ({s}) depends on non-existence of '{s}' in {*} ({s})", .{
......@@ -4672,7 +4696,7 @@ fn lookupInNamespace(
46724696 // TODO This dependency is too strong. Really, it should only be a dependency
46734697 // on the non-existence of `ident_name` in the namespace. We can lessen the number of
46744698 // outdated declarations by making this dependency more sophisticated.
4675 try mod.declareDeclDependency(sema.owner_decl, namespace_decl);
4699 try mod.declareDeclDependency(sema.owner_decl_index, namespace_decl_index);
46764700 return null;
46774701}
46784702
......@@ -4725,13 +4749,14 @@ const GenericCallAdapter = struct {
47254749 /// Unlike comptime_args, the Type here is not always present.
47264750 /// .generic_poison is used to communicate non-anytype parameters.
47274751 comptime_tvs: []const TypedValue,
4728 target: std.Target,
4752 module: *Module,
47294753
47304754 pub fn eql(ctx: @This(), adapted_key: void, other_key: *Module.Fn) bool {
47314755 _ = adapted_key;
47324756 // The generic function Decl is guaranteed to be the first dependency
47334757 // of each of its instantiations.
4734 const generic_owner_decl = other_key.owner_decl.dependencies.keys()[0];
4758 const other_owner_decl = ctx.module.declPtr(other_key.owner_decl);
4759 const generic_owner_decl = other_owner_decl.dependencies.keys()[0];
47354760 if (ctx.generic_fn.owner_decl != generic_owner_decl) return false;
47364761
47374762 const other_comptime_args = other_key.comptime_args.?;
......@@ -4747,18 +4772,18 @@ const GenericCallAdapter = struct {
47474772
47484773 if (this_is_anytype) {
47494774 // Both are anytype parameters.
4750 if (!this_arg.ty.eql(other_arg.ty, ctx.target)) {
4775 if (!this_arg.ty.eql(other_arg.ty, ctx.module)) {
47514776 return false;
47524777 }
47534778 if (this_is_comptime) {
47544779 // Both are comptime and anytype parameters with matching types.
4755 if (!this_arg.val.eql(other_arg.val, other_arg.ty, ctx.target)) {
4780 if (!this_arg.val.eql(other_arg.val, other_arg.ty, ctx.module)) {
47564781 return false;
47574782 }
47584783 }
47594784 } else if (this_is_comptime) {
47604785 // Both are comptime parameters but not anytype parameters.
4761 if (!this_arg.val.eql(other_arg.val, other_arg.ty, ctx.target)) {
4786 if (!this_arg.val.eql(other_arg.val, other_arg.ty, ctx.module)) {
47624787 return false;
47634788 }
47644789 }
......@@ -4787,7 +4812,6 @@ fn analyzeCall(
47874812 const mod = sema.mod;
47884813
47894814 const callee_ty = sema.typeOf(func);
4790 const target = sema.mod.getTarget();
47914815 const func_ty = func_ty: {
47924816 switch (callee_ty.zigTypeTag()) {
47934817 .Fn => break :func_ty callee_ty,
......@@ -4799,7 +4823,7 @@ fn analyzeCall(
47994823 },
48004824 else => {},
48014825 }
4802 return sema.fail(block, func_src, "type '{}' not a function", .{callee_ty.fmt(target)});
4826 return sema.fail(block, func_src, "type '{}' not a function", .{callee_ty.fmt(sema.mod)});
48034827 };
48044828
48054829 const func_ty_info = func_ty.fnInfo();
......@@ -4891,7 +4915,7 @@ fn analyzeCall(
48914915 const result: Air.Inst.Ref = if (is_inline_call) res: {
48924916 const func_val = try sema.resolveConstValue(block, func_src, func);
48934917 const module_fn = switch (func_val.tag()) {
4894 .decl_ref => func_val.castTag(.decl_ref).?.data.val.castTag(.function).?.data,
4918 .decl_ref => mod.declPtr(func_val.castTag(.decl_ref).?.data).val.castTag(.function).?.data,
48954919 .function => func_val.castTag(.function).?.data,
48964920 .extern_fn => return sema.fail(block, call_src, "{s} call of extern function", .{
48974921 @as([]const u8, if (is_comptime_call) "comptime" else "inline"),
......@@ -4922,7 +4946,8 @@ fn analyzeCall(
49224946 // In order to save a bit of stack space, directly modify Sema rather
49234947 // than create a child one.
49244948 const parent_zir = sema.code;
4925 sema.code = module_fn.owner_decl.getFileScope().zir;
4949 const fn_owner_decl = mod.declPtr(module_fn.owner_decl);
4950 sema.code = fn_owner_decl.getFileScope().zir;
49264951 defer sema.code = parent_zir;
49274952
49284953 const parent_inst_map = sema.inst_map;
......@@ -4936,14 +4961,14 @@ fn analyzeCall(
49364961 sema.func = module_fn;
49374962 defer sema.func = parent_func;
49384963
4939 var wip_captures = try WipCaptureScope.init(gpa, sema.perm_arena, module_fn.owner_decl.src_scope);
4964 var wip_captures = try WipCaptureScope.init(gpa, sema.perm_arena, fn_owner_decl.src_scope);
49404965 defer wip_captures.deinit();
49414966
49424967 var child_block: Block = .{
49434968 .parent = null,
49444969 .sema = sema,
49454970 .src_decl = module_fn.owner_decl,
4946 .namespace = module_fn.owner_decl.src_namespace,
4971 .namespace = fn_owner_decl.src_namespace,
49474972 .wip_capture_scope = wip_captures.scope,
49484973 .instructions = .{},
49494974 .label = null,
......@@ -4976,7 +5001,7 @@ fn analyzeCall(
49765001 // comptime state.
49775002 var should_memoize = true;
49785003
4979 var new_fn_info = module_fn.owner_decl.ty.fnInfo();
5004 var new_fn_info = fn_owner_decl.ty.fnInfo();
49805005 new_fn_info.param_types = try sema.arena.alloc(Type, new_fn_info.param_types.len);
49815006 new_fn_info.comptime_params = (try sema.arena.alloc(bool, new_fn_info.param_types.len)).ptr;
49825007
......@@ -5073,7 +5098,7 @@ fn analyzeCall(
50735098 const bare_return_type = try sema.analyzeAsType(&child_block, ret_ty_src, ret_ty_inst);
50745099 // Create a fresh inferred error set type for inline/comptime calls.
50755100 const fn_ret_ty = blk: {
5076 if (module_fn.hasInferredErrorSet()) {
5101 if (module_fn.hasInferredErrorSet(mod)) {
50775102 const node = try sema.gpa.create(Module.Fn.InferredErrorSetListNode);
50785103 node.data = .{ .func = module_fn };
50795104 if (parent_func) |some| {
......@@ -5097,7 +5122,7 @@ fn analyzeCall(
50975122 // bug generating invalid LLVM IR.
50985123 const res2: Air.Inst.Ref = res2: {
50995124 if (should_memoize and is_comptime_call) {
5100 if (mod.memoized_calls.getContext(memoized_call_key, .{ .target = target })) |result| {
5125 if (mod.memoized_calls.getContext(memoized_call_key, .{ .module = mod })) |result| {
51015126 const ty_inst = try sema.addType(fn_ret_ty);
51025127 try sema.air_values.append(gpa, result.val);
51035128 sema.air_instructions.set(block_inst, .{
......@@ -5150,7 +5175,13 @@ fn analyzeCall(
51505175 };
51515176
51525177 if (!is_comptime_call) {
5153 try sema.emitDbgInline(block, module_fn, parent_func.?, parent_func.?.owner_decl.ty, .dbg_inline_end);
5178 try sema.emitDbgInline(
5179 block,
5180 module_fn,
5181 parent_func.?,
5182 mod.declPtr(parent_func.?.owner_decl).ty,
5183 .dbg_inline_end,
5184 );
51545185 }
51555186
51565187 if (should_memoize and is_comptime_call) {
......@@ -5172,7 +5203,7 @@ fn analyzeCall(
51725203 try mod.memoized_calls.putContext(gpa, memoized_call_key, .{
51735204 .val = try result_val.copy(arena),
51745205 .arena = arena_allocator.state,
5175 }, .{ .target = sema.mod.getTarget() });
5206 }, .{ .module = mod });
51765207 delete_memoized_call_key = false;
51775208 }
51785209 }
......@@ -5239,13 +5270,14 @@ fn instantiateGenericCall(
52395270 const func_val = try sema.resolveConstValue(block, func_src, func);
52405271 const module_fn = switch (func_val.tag()) {
52415272 .function => func_val.castTag(.function).?.data,
5242 .decl_ref => func_val.castTag(.decl_ref).?.data.val.castTag(.function).?.data,
5273 .decl_ref => mod.declPtr(func_val.castTag(.decl_ref).?.data).val.castTag(.function).?.data,
52435274 else => unreachable,
52445275 };
52455276 // Check the Module's generic function map with an adapted context, so that we
52465277 // can match against `uncasted_args` rather than doing the work below to create a
52475278 // generic Scope only to junk it if it matches an existing instantiation.
5248 const namespace = module_fn.owner_decl.src_namespace;
5279 const fn_owner_decl = mod.declPtr(module_fn.owner_decl);
5280 const namespace = fn_owner_decl.src_namespace;
52495281 const fn_zir = namespace.file_scope.zir;
52505282 const fn_info = fn_zir.getFnInfo(module_fn.zir_body_inst);
52515283 const zir_tags = fn_zir.instructions.items(.tag);
......@@ -5261,7 +5293,6 @@ fn instantiateGenericCall(
52615293 std.hash.autoHash(&hasher, @ptrToInt(module_fn));
52625294
52635295 const comptime_tvs = try sema.arena.alloc(TypedValue, func_ty_info.param_types.len);
5264 const target = sema.mod.getTarget();
52655296
52665297 {
52675298 var i: usize = 0;
......@@ -5290,9 +5321,9 @@ fn instantiateGenericCall(
52905321 const arg_src = call_src; // TODO better source location
52915322 const arg_ty = sema.typeOf(uncasted_args[i]);
52925323 const arg_val = try sema.resolveValue(block, arg_src, uncasted_args[i]);
5293 arg_val.hash(arg_ty, &hasher, target);
5324 arg_val.hash(arg_ty, &hasher, mod);
52945325 if (is_anytype) {
5295 arg_ty.hashWithHasher(&hasher, target);
5326 arg_ty.hashWithHasher(&hasher, mod);
52965327 comptime_tvs[i] = .{
52975328 .ty = arg_ty,
52985329 .val = arg_val,
......@@ -5305,7 +5336,7 @@ fn instantiateGenericCall(
53055336 }
53065337 } else if (is_anytype) {
53075338 const arg_ty = sema.typeOf(uncasted_args[i]);
5308 arg_ty.hashWithHasher(&hasher, target);
5339 arg_ty.hashWithHasher(&hasher, mod);
53095340 comptime_tvs[i] = .{
53105341 .ty = arg_ty,
53115342 .val = Value.initTag(.generic_poison),
......@@ -5328,7 +5359,7 @@ fn instantiateGenericCall(
53285359 .precomputed_hash = precomputed_hash,
53295360 .func_ty_info = func_ty_info,
53305361 .comptime_tvs = comptime_tvs,
5331 .target = target,
5362 .module = mod,
53325363 };
53335364 const gop = try mod.monomorphed_funcs.getOrPutAdapted(gpa, {}, adapter);
53345365 const callee = if (!gop.found_existing) callee: {
......@@ -5343,37 +5374,40 @@ fn instantiateGenericCall(
53435374 try namespace.anon_decls.ensureUnusedCapacity(gpa, 1);
53445375
53455376 // Create a Decl for the new function.
5346 const src_decl = namespace.getDecl();
5377 const src_decl_index = namespace.getDeclIndex();
5378 const src_decl = mod.declPtr(src_decl_index);
5379 const new_decl_index = try mod.allocateNewDecl(namespace, fn_owner_decl.src_node, src_decl.src_scope);
5380 errdefer mod.destroyDecl(new_decl_index);
5381 const new_decl = mod.declPtr(new_decl_index);
53475382 // TODO better names for generic function instantiations
5348 const name_index = mod.getNextAnonNameIndex();
53495383 const decl_name = try std.fmt.allocPrintZ(gpa, "{s}__anon_{d}", .{
5350 module_fn.owner_decl.name, name_index,
5384 fn_owner_decl.name, @enumToInt(new_decl_index),
53515385 });
5352 const new_decl = try mod.allocateNewDecl(decl_name, namespace, module_fn.owner_decl.src_node, src_decl.src_scope);
5353 errdefer new_decl.destroy(mod);
5354 new_decl.src_line = module_fn.owner_decl.src_line;
5355 new_decl.is_pub = module_fn.owner_decl.is_pub;
5356 new_decl.is_exported = module_fn.owner_decl.is_exported;
5357 new_decl.has_align = module_fn.owner_decl.has_align;
5358 new_decl.has_linksection_or_addrspace = module_fn.owner_decl.has_linksection_or_addrspace;
5359 new_decl.@"addrspace" = module_fn.owner_decl.@"addrspace";
5360 new_decl.zir_decl_index = module_fn.owner_decl.zir_decl_index;
5386 new_decl.name = decl_name;
5387 new_decl.src_line = fn_owner_decl.src_line;
5388 new_decl.is_pub = fn_owner_decl.is_pub;
5389 new_decl.is_exported = fn_owner_decl.is_exported;
5390 new_decl.has_align = fn_owner_decl.has_align;
5391 new_decl.has_linksection_or_addrspace = fn_owner_decl.has_linksection_or_addrspace;
5392 new_decl.@"addrspace" = fn_owner_decl.@"addrspace";
5393 new_decl.zir_decl_index = fn_owner_decl.zir_decl_index;
53615394 new_decl.alive = true; // This Decl is called at runtime.
53625395 new_decl.analysis = .in_progress;
53635396 new_decl.generation = mod.generation;
53645397
5365 namespace.anon_decls.putAssumeCapacityNoClobber(new_decl, {});
5366 errdefer assert(namespace.anon_decls.orderedRemove(new_decl));
5398 namespace.anon_decls.putAssumeCapacityNoClobber(new_decl_index, {});
5399 errdefer assert(namespace.anon_decls.orderedRemove(new_decl_index));
53675400
53685401 // The generic function Decl is guaranteed to be the first dependency
53695402 // of each of its instantiations.
53705403 assert(new_decl.dependencies.keys().len == 0);
5371 try mod.declareDeclDependency(new_decl, module_fn.owner_decl);
5404 try mod.declareDeclDependency(new_decl_index, module_fn.owner_decl);
53725405 // Resolving the new function type below will possibly declare more decl dependencies
53735406 // and so we remove them all here in case of error.
53745407 errdefer {
5375 for (new_decl.dependencies.keys()) |dep| {
5376 dep.removeDependant(new_decl);
5408 for (new_decl.dependencies.keys()) |dep_index| {
5409 const dep = mod.declPtr(dep_index);
5410 dep.removeDependant(new_decl_index);
53775411 }
53785412 }
53795413
......@@ -5392,6 +5426,7 @@ fn instantiateGenericCall(
53925426 .perm_arena = new_decl_arena_allocator,
53935427 .code = fn_zir,
53945428 .owner_decl = new_decl,
5429 .owner_decl_index = new_decl_index,
53955430 .func = null,
53965431 .fn_ret_ty = Type.void,
53975432 .owner_func = null,
......@@ -5407,7 +5442,7 @@ fn instantiateGenericCall(
54075442 var child_block: Block = .{
54085443 .parent = null,
54095444 .sema = &child_sema,
5410 .src_decl = new_decl,
5445 .src_decl = new_decl_index,
54115446 .namespace = namespace,
54125447 .wip_capture_scope = wip_captures.scope,
54135448 .instructions = .{},
......@@ -5564,7 +5599,7 @@ fn instantiateGenericCall(
55645599 // Queue up a `codegen_func` work item for the new Fn. The `comptime_args` field
55655600 // will be populated, ensuring it will have `analyzeBody` called with the ZIR
55665601 // parameters mapped appropriately.
5567 try mod.comp.bin_file.allocateDeclIndexes(new_decl);
5602 try mod.comp.bin_file.allocateDeclIndexes(new_decl_index);
55685603 try mod.comp.work_queue.writeItem(.{ .codegen_func = new_func });
55695604
55705605 try new_decl.finalizeNewArena(&new_decl_arena);
......@@ -5577,7 +5612,7 @@ fn instantiateGenericCall(
55775612 try sema.requireRuntimeBlock(block, call_src);
55785613
55795614 const comptime_args = callee.comptime_args.?;
5580 const new_fn_info = callee.owner_decl.ty.fnInfo();
5615 const new_fn_info = mod.declPtr(callee.owner_decl).ty.fnInfo();
55815616 const runtime_args_len = @intCast(u32, new_fn_info.param_types.len);
55825617 const runtime_args = try sema.arena.alloc(Air.Inst.Ref, runtime_args_len);
55835618 {
......@@ -5700,8 +5735,7 @@ fn zirArrayType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
57005735 const bin_inst = sema.code.instructions.items(.data)[inst].bin;
57015736 const len = try sema.resolveInt(block, .unneeded, bin_inst.lhs, Type.usize);
57025737 const elem_type = try sema.resolveType(block, .unneeded, bin_inst.rhs);
5703 const target = sema.mod.getTarget();
5704 const array_ty = try Type.array(sema.arena, len, null, elem_type, target);
5738 const array_ty = try Type.array(sema.arena, len, null, elem_type, sema.mod);
57055739
57065740 return sema.addType(array_ty);
57075741}
......@@ -5720,8 +5754,7 @@ fn zirArrayTypeSentinel(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Compil
57205754 const uncasted_sentinel = sema.resolveInst(extra.sentinel);
57215755 const sentinel = try sema.coerce(block, elem_type, uncasted_sentinel, sentinel_src);
57225756 const sentinel_val = try sema.resolveConstValue(block, sentinel_src, sentinel);
5723 const target = sema.mod.getTarget();
5724 const array_ty = try Type.array(sema.arena, len, sentinel_val, elem_type, target);
5757 const array_ty = try Type.array(sema.arena, len, sentinel_val, elem_type, sema.mod);
57255758
57265759 return sema.addType(array_ty);
57275760}
......@@ -5748,14 +5781,13 @@ fn zirErrorUnionType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileEr
57485781 const rhs_src: LazySrcLoc = .{ .node_offset_bin_rhs = inst_data.src_node };
57495782 const error_set = try sema.resolveType(block, lhs_src, extra.lhs);
57505783 const payload = try sema.resolveType(block, rhs_src, extra.rhs);
5751 const target = sema.mod.getTarget();
57525784
57535785 if (error_set.zigTypeTag() != .ErrorSet) {
57545786 return sema.fail(block, lhs_src, "expected error set type, found {}", .{
5755 error_set.fmt(target),
5787 error_set.fmt(sema.mod),
57565788 });
57575789 }
5758 const err_union_ty = try Type.errorUnion(sema.arena, error_set, payload, target);
5790 const err_union_ty = try Type.errorUnion(sema.arena, error_set, payload, sema.mod);
57595791 return sema.addType(err_union_ty);
57605792}
57615793
......@@ -5862,11 +5894,10 @@ fn zirMergeErrorSets(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileEr
58625894 }
58635895 const lhs_ty = try sema.analyzeAsType(block, lhs_src, lhs);
58645896 const rhs_ty = try sema.analyzeAsType(block, rhs_src, rhs);
5865 const target = sema.mod.getTarget();
58665897 if (lhs_ty.zigTypeTag() != .ErrorSet)
5867 return sema.fail(block, lhs_src, "expected error set type, found {}", .{lhs_ty.fmt(target)});
5898 return sema.fail(block, lhs_src, "expected error set type, found {}", .{lhs_ty.fmt(sema.mod)});
58685899 if (rhs_ty.zigTypeTag() != .ErrorSet)
5869 return sema.fail(block, rhs_src, "expected error set type, found {}", .{rhs_ty.fmt(target)});
5900 return sema.fail(block, rhs_src, "expected error set type, found {}", .{rhs_ty.fmt(sema.mod)});
58705901
58715902 // Anything merged with anyerror is anyerror.
58725903 if (lhs_ty.tag() == .anyerror or rhs_ty.tag() == .anyerror) {
......@@ -5912,7 +5943,6 @@ fn zirEnumToInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
59125943 const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
59135944 const operand = sema.resolveInst(inst_data.operand);
59145945 const operand_ty = sema.typeOf(operand);
5915 const target = sema.mod.getTarget();
59165946
59175947 const enum_tag: Air.Inst.Ref = switch (operand_ty.zigTypeTag()) {
59185948 .Enum => operand,
......@@ -5929,7 +5959,7 @@ fn zirEnumToInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
59295959 },
59305960 else => {
59315961 return sema.fail(block, operand_src, "expected enum or tagged union, found {}", .{
5932 operand_ty.fmt(target),
5962 operand_ty.fmt(sema.mod),
59335963 });
59345964 },
59355965 };
......@@ -5953,7 +5983,6 @@ fn zirEnumToInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
59535983}
59545984
59555985fn zirIntToEnum(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
5956 const target = sema.mod.getTarget();
59575986 const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
59585987 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
59595988 const src = inst_data.src();
......@@ -5963,7 +5992,7 @@ fn zirIntToEnum(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
59635992 const operand = sema.resolveInst(extra.rhs);
59645993
59655994 if (dest_ty.zigTypeTag() != .Enum) {
5966 return sema.fail(block, dest_ty_src, "expected enum, found {}", .{dest_ty.fmt(target)});
5995 return sema.fail(block, dest_ty_src, "expected enum, found {}", .{dest_ty.fmt(sema.mod)});
59675996 }
59685997
59695998 if (try sema.resolveMaybeUndefVal(block, operand_src, operand)) |int_val| {
......@@ -5973,17 +6002,17 @@ fn zirIntToEnum(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
59736002 if (int_val.isUndef()) {
59746003 return sema.failWithUseOfUndef(block, operand_src);
59756004 }
5976 if (!dest_ty.enumHasInt(int_val, target)) {
6005 if (!dest_ty.enumHasInt(int_val, sema.mod)) {
59776006 const msg = msg: {
59786007 const msg = try sema.errMsg(
59796008 block,
59806009 src,
59816010 "enum '{}' has no tag with value {}",
5982 .{ dest_ty.fmt(target), int_val.fmtValue(sema.typeOf(operand), target) },
6011 .{ dest_ty.fmt(sema.mod), int_val.fmtValue(sema.typeOf(operand), sema.mod) },
59836012 );
59846013 errdefer msg.destroy(sema.gpa);
59856014 try sema.mod.errNoteNonLazy(
5986 dest_ty.declSrcLoc(),
6015 dest_ty.declSrcLoc(sema.mod),
59876016 msg,
59886017 "enum declared here",
59896018 .{},
......@@ -6028,14 +6057,13 @@ fn analyzeOptionalPayloadPtr(
60286057 const optional_ptr_ty = sema.typeOf(optional_ptr);
60296058 assert(optional_ptr_ty.zigTypeTag() == .Pointer);
60306059
6031 const target = sema.mod.getTarget();
60326060 const opt_type = optional_ptr_ty.elemType();
60336061 if (opt_type.zigTypeTag() != .Optional) {
6034 return sema.fail(block, src, "expected optional type, found {}", .{opt_type.fmt(target)});
6062 return sema.fail(block, src, "expected optional type, found {}", .{opt_type.fmt(sema.mod)});
60356063 }
60366064
60376065 const child_type = try opt_type.optionalChildAlloc(sema.arena);
6038 const child_pointer = try Type.ptr(sema.arena, target, .{
6066 const child_pointer = try Type.ptr(sema.arena, sema.mod, .{
60396067 .pointee_type = child_type,
60406068 .mutable = !optional_ptr_ty.isConstPtr(),
60416069 .@"addrspace" = optional_ptr_ty.ptrAddressSpace(),
......@@ -6106,8 +6134,7 @@ fn zirOptionalPayload(
61066134 return sema.failWithExpectedOptionalType(block, src, operand_ty);
61076135 }
61086136 const ptr_info = operand_ty.ptrInfo().data;
6109 const target = sema.mod.getTarget();
6110 break :t try Type.ptr(sema.arena, target, .{
6137 break :t try Type.ptr(sema.arena, sema.mod, .{
61116138 .pointee_type = try ptr_info.pointee_type.copy(sema.arena),
61126139 .@"align" = ptr_info.@"align",
61136140 .@"addrspace" = ptr_info.@"addrspace",
......@@ -6154,9 +6181,8 @@ fn zirErrUnionPayload(
61546181 const operand_src = src;
61556182 const operand_ty = sema.typeOf(operand);
61566183 if (operand_ty.zigTypeTag() != .ErrorUnion) {
6157 const target = sema.mod.getTarget();
61586184 return sema.fail(block, operand_src, "expected error union type, found '{}'", .{
6159 operand_ty.fmt(target),
6185 operand_ty.fmt(sema.mod),
61606186 });
61616187 }
61626188
......@@ -6205,15 +6231,14 @@ fn analyzeErrUnionPayloadPtr(
62056231 const operand_ty = sema.typeOf(operand);
62066232 assert(operand_ty.zigTypeTag() == .Pointer);
62076233
6208 const target = sema.mod.getTarget();
62096234 if (operand_ty.elemType().zigTypeTag() != .ErrorUnion) {
62106235 return sema.fail(block, src, "expected error union type, found {}", .{
6211 operand_ty.elemType().fmt(target),
6236 operand_ty.elemType().fmt(sema.mod),
62126237 });
62136238 }
62146239
62156240 const payload_ty = operand_ty.elemType().errorUnionPayload();
6216 const operand_pointer_ty = try Type.ptr(sema.arena, target, .{
6241 const operand_pointer_ty = try Type.ptr(sema.arena, sema.mod, .{
62176242 .pointee_type = payload_ty,
62186243 .mutable = !operand_ty.isConstPtr(),
62196244 .@"addrspace" = operand_ty.ptrAddressSpace(),
......@@ -6272,10 +6297,9 @@ fn zirErrUnionCode(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErro
62726297 const src = inst_data.src();
62736298 const operand = sema.resolveInst(inst_data.operand);
62746299 const operand_ty = sema.typeOf(operand);
6275 const target = sema.mod.getTarget();
62766300 if (operand_ty.zigTypeTag() != .ErrorUnion) {
62776301 return sema.fail(block, src, "expected error union type, found '{}'", .{
6278 operand_ty.fmt(target),
6302 operand_ty.fmt(sema.mod),
62796303 });
62806304 }
62816305
......@@ -6302,9 +6326,8 @@ fn zirErrUnionCodePtr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileE
63026326 assert(operand_ty.zigTypeTag() == .Pointer);
63036327
63046328 if (operand_ty.elemType().zigTypeTag() != .ErrorUnion) {
6305 const target = sema.mod.getTarget();
63066329 return sema.fail(block, src, "expected error union type, found {}", .{
6307 operand_ty.elemType().fmt(target),
6330 operand_ty.elemType().fmt(sema.mod),
63086331 });
63096332 }
63106333
......@@ -6329,10 +6352,9 @@ fn zirEnsureErrPayloadVoid(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Com
63296352 const src = inst_data.src();
63306353 const operand = sema.resolveInst(inst_data.operand);
63316354 const operand_ty = sema.typeOf(operand);
6332 const target = sema.mod.getTarget();
63336355 if (operand_ty.zigTypeTag() != .ErrorUnion) {
63346356 return sema.fail(block, src, "expected error union type, found '{}'", .{
6335 operand_ty.fmt(target),
6357 operand_ty.fmt(sema.mod),
63366358 });
63376359 }
63386360 if (operand_ty.errorUnionPayload().zigTypeTag() != .Void) {
......@@ -6606,7 +6628,7 @@ fn funcCommon(
66066628 errdefer sema.gpa.destroy(new_extern_fn);
66076629
66086630 new_extern_fn.* = Module.ExternFn{
6609 .owner_decl = sema.owner_decl,
6631 .owner_decl = sema.owner_decl_index,
66106632 .lib_name = null,
66116633 };
66126634
......@@ -6645,7 +6667,7 @@ fn funcCommon(
66456667 new_func.* = .{
66466668 .state = anal_state,
66476669 .zir_body_inst = func_inst,
6648 .owner_decl = sema.owner_decl,
6670 .owner_decl = sema.owner_decl_index,
66496671 .comptime_args = comptime_args,
66506672 .anytype_args = undefined,
66516673 .hash = hash,
......@@ -6838,8 +6860,7 @@ fn zirPtrToInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
68386860 const ptr = sema.resolveInst(inst_data.operand);
68396861 const ptr_ty = sema.typeOf(ptr);
68406862 if (!ptr_ty.isPtrAtRuntime()) {
6841 const target = sema.mod.getTarget();
6842 return sema.fail(block, ptr_src, "expected pointer, found '{}'", .{ptr_ty.fmt(target)});
6863 return sema.fail(block, ptr_src, "expected pointer, found '{}'", .{ptr_ty.fmt(sema.mod)});
68436864 }
68446865 if (try sema.resolveMaybeUndefVal(block, ptr_src, ptr)) |ptr_val| {
68456866 return sema.addConstant(Type.usize, ptr_val);
......@@ -7018,7 +7039,6 @@ fn zirBitcast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
70187039 const dest_ty_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
70197040 const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
70207041 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
7021 const target = sema.mod.getTarget();
70227042
70237043 const dest_ty = try sema.resolveType(block, dest_ty_src, extra.lhs);
70247044 switch (dest_ty.zigTypeTag()) {
......@@ -7038,10 +7058,10 @@ fn zirBitcast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
70387058 .Type,
70397059 .Undefined,
70407060 .Void,
7041 => return sema.fail(block, dest_ty_src, "invalid type '{}' for @bitCast", .{dest_ty.fmt(target)}),
7061 => return sema.fail(block, dest_ty_src, "invalid type '{}' for @bitCast", .{dest_ty.fmt(sema.mod)}),
70427062
70437063 .Pointer => return sema.fail(block, dest_ty_src, "cannot @bitCast to '{}', use @ptrCast to cast to a pointer", .{
7044 dest_ty.fmt(target),
7064 dest_ty.fmt(sema.mod),
70457065 }),
70467066 .Struct, .Union => if (dest_ty.containerLayout() == .Auto) {
70477067 const container = switch (dest_ty.zigTypeTag()) {
......@@ -7050,7 +7070,7 @@ fn zirBitcast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
70507070 else => unreachable,
70517071 };
70527072 return sema.fail(block, dest_ty_src, "cannot @bitCast to '{}', {s} does not have a guaranteed in-memory layout", .{
7053 dest_ty.fmt(target), container,
7073 dest_ty.fmt(sema.mod), container,
70547074 });
70557075 },
70567076 .BoundFn => @panic("TODO remove this type from the language and compiler"),
......@@ -7088,7 +7108,7 @@ fn zirFloatCast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
70887108 block,
70897109 dest_ty_src,
70907110 "expected float type, found '{}'",
7091 .{dest_ty.fmt(target)},
7111 .{dest_ty.fmt(sema.mod)},
70927112 ),
70937113 };
70947114
......@@ -7099,7 +7119,7 @@ fn zirFloatCast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
70997119 block,
71007120 operand_src,
71017121 "expected float type, found '{}'",
7102 .{operand_ty.fmt(target)},
7122 .{operand_ty.fmt(sema.mod)},
71037123 ),
71047124 }
71057125
......@@ -7241,7 +7261,6 @@ fn zirSwitchCapture(
72417261 const operand_ptr = sema.resolveInst(cond_info.operand);
72427262 const operand_ptr_ty = sema.typeOf(operand_ptr);
72437263 const operand_ty = if (operand_is_ref) operand_ptr_ty.childType() else operand_ptr_ty;
7244 const target = sema.mod.getTarget();
72457264
72467265 const operand = if (operand_is_ref)
72477266 try sema.analyzeLoad(block, operand_src, operand_ptr, operand_src)
......@@ -7277,7 +7296,7 @@ fn zirSwitchCapture(
72777296 // Previous switch validation ensured this will succeed
72787297 const first_item_val = sema.resolveConstValue(block, .unneeded, first_item) catch unreachable;
72797298
7280 const first_field_index = @intCast(u32, enum_ty.enumTagFieldIndex(first_item_val, target).?);
7299 const first_field_index = @intCast(u32, enum_ty.enumTagFieldIndex(first_item_val, sema.mod).?);
72817300 const first_field = union_obj.fields.values()[first_field_index];
72827301
72837302 for (items[1..]) |item| {
......@@ -7285,16 +7304,16 @@ fn zirSwitchCapture(
72857304 // Previous switch validation ensured this will succeed
72867305 const item_val = sema.resolveConstValue(block, .unneeded, item_ref) catch unreachable;
72877306
7288 const field_index = enum_ty.enumTagFieldIndex(item_val, target).?;
7307 const field_index = enum_ty.enumTagFieldIndex(item_val, sema.mod).?;
72897308 const field = union_obj.fields.values()[field_index];
7290 if (!field.ty.eql(first_field.ty, target)) {
7309 if (!field.ty.eql(first_field.ty, sema.mod)) {
72917310 const first_item_src = switch_src; // TODO better source location
72927311 const item_src = switch_src;
72937312 const msg = msg: {
72947313 const msg = try sema.errMsg(block, switch_src, "capture group with incompatible types", .{});
72957314 errdefer msg.destroy(sema.gpa);
7296 try sema.errNote(block, first_item_src, msg, "type '{}' here", .{first_field.ty.fmt(target)});
7297 try sema.errNote(block, item_src, msg, "type '{}' here", .{field.ty.fmt(target)});
7315 try sema.errNote(block, first_item_src, msg, "type '{}' here", .{first_field.ty.fmt(sema.mod)});
7316 try sema.errNote(block, item_src, msg, "type '{}' here", .{field.ty.fmt(sema.mod)});
72987317 break :msg msg;
72997318 };
73007319 return sema.failWithOwnedErrorMsg(block, msg);
......@@ -7304,7 +7323,7 @@ fn zirSwitchCapture(
73047323 if (is_ref) {
73057324 assert(operand_is_ref);
73067325
7307 const field_ty_ptr = try Type.ptr(sema.arena, target, .{
7326 const field_ty_ptr = try Type.ptr(sema.arena, sema.mod, .{
73087327 .pointee_type = first_field.ty,
73097328 .@"addrspace" = .generic,
73107329 .mutable = operand_ptr_ty.ptrIsMutable(),
......@@ -7388,7 +7407,6 @@ fn zirSwitchCond(
73887407 else
73897408 operand_ptr;
73907409 const operand_ty = sema.typeOf(operand);
7391 const target = sema.mod.getTarget();
73927410
73937411 switch (operand_ty.zigTypeTag()) {
73947412 .Type,
......@@ -7436,7 +7454,7 @@ fn zirSwitchCond(
74367454 .Vector,
74377455 .Frame,
74387456 .AnyFrame,
7439 => return sema.fail(block, src, "switch on type '{}'", .{operand_ty.fmt(target)}),
7457 => return sema.fail(block, src, "switch on type '{}'", .{operand_ty.fmt(sema.mod)}),
74407458 }
74417459}
74427460
......@@ -7588,10 +7606,10 @@ fn zirSwitchBlock(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
75887606 );
75897607 }
75907608 try sema.mod.errNoteNonLazy(
7591 operand_ty.declSrcLoc(),
7609 operand_ty.declSrcLoc(sema.mod),
75927610 msg,
75937611 "enum '{}' declared here",
7594 .{operand_ty.fmt(target)},
7612 .{operand_ty.fmt(sema.mod)},
75957613 );
75967614 break :msg msg;
75977615 };
......@@ -7705,10 +7723,10 @@ fn zirSwitchBlock(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
77057723
77067724 if (maybe_msg) |msg| {
77077725 try sema.mod.errNoteNonLazy(
7708 operand_ty.declSrcLoc(),
7726 operand_ty.declSrcLoc(sema.mod),
77097727 msg,
77107728 "error set '{}' declared here",
7711 .{operand_ty.fmt(target)},
7729 .{operand_ty.fmt(sema.mod)},
77127730 );
77137731 return sema.failWithOwnedErrorMsg(block, msg);
77147732 }
......@@ -7738,7 +7756,7 @@ fn zirSwitchBlock(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
77387756 },
77397757 .Union => return sema.fail(block, src, "TODO validate switch .Union", .{}),
77407758 .Int, .ComptimeInt => {
7741 var range_set = RangeSet.init(gpa, target);
7759 var range_set = RangeSet.init(gpa, sema.mod);
77427760 defer range_set.deinit();
77437761
77447762 var extra_index: usize = special.end;
......@@ -7914,13 +7932,13 @@ fn zirSwitchBlock(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
79147932 block,
79157933 src,
79167934 "else prong required when switching on type '{}'",
7917 .{operand_ty.fmt(target)},
7935 .{operand_ty.fmt(sema.mod)},
79187936 );
79197937 }
79207938
79217939 var seen_values = ValueSrcMap.initContext(gpa, .{
79227940 .ty = operand_ty,
7923 .target = target,
7941 .mod = sema.mod,
79247942 });
79257943 defer seen_values.deinit();
79267944
......@@ -7985,7 +8003,7 @@ fn zirSwitchBlock(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
79858003 .ComptimeFloat,
79868004 .Float,
79878005 => return sema.fail(block, operand_src, "invalid switch operand type '{}'", .{
7988 operand_ty.fmt(target),
8006 operand_ty.fmt(sema.mod),
79898007 }),
79908008 }
79918009
......@@ -8035,7 +8053,7 @@ fn zirSwitchBlock(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
80358053 const item = sema.resolveInst(item_ref);
80368054 // Validation above ensured these will succeed.
80378055 const item_val = sema.resolveConstValue(&child_block, .unneeded, item) catch unreachable;
8038 if (operand_val.eql(item_val, operand_ty, target)) {
8056 if (operand_val.eql(item_val, operand_ty, sema.mod)) {
80398057 return sema.resolveBlockBody(block, src, &child_block, body, inst, merges);
80408058 }
80418059 }
......@@ -8057,7 +8075,7 @@ fn zirSwitchBlock(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
80578075 const item = sema.resolveInst(item_ref);
80588076 // Validation above ensured these will succeed.
80598077 const item_val = sema.resolveConstValue(&child_block, .unneeded, item) catch unreachable;
8060 if (operand_val.eql(item_val, operand_ty, target)) {
8078 if (operand_val.eql(item_val, operand_ty, sema.mod)) {
80618079 return sema.resolveBlockBody(block, src, &child_block, body, inst, merges);
80628080 }
80638081 }
......@@ -8072,8 +8090,8 @@ fn zirSwitchBlock(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
80728090 // Validation above ensured these will succeed.
80738091 const first_tv = sema.resolveInstConst(&child_block, .unneeded, item_first) catch unreachable;
80748092 const last_tv = sema.resolveInstConst(&child_block, .unneeded, item_last) catch unreachable;
8075 if (Value.compare(operand_val, .gte, first_tv.val, operand_ty, target) and
8076 Value.compare(operand_val, .lte, last_tv.val, operand_ty, target))
8093 if (Value.compare(operand_val, .gte, first_tv.val, operand_ty, sema.mod) and
8094 Value.compare(operand_val, .lte, last_tv.val, operand_ty, sema.mod))
80778095 {
80788096 return sema.resolveBlockBody(block, src, &child_block, body, inst, merges);
80798097 }
......@@ -8385,7 +8403,7 @@ fn resolveSwitchItemVal(
83858403 return TypedValue{ .ty = item_ty, .val = val };
83868404 } else |err| switch (err) {
83878405 error.NeededSourceLocation => {
8388 const src = switch_prong_src.resolve(sema.gpa, block.src_decl, switch_node_offset, range_expand);
8406 const src = switch_prong_src.resolve(sema.gpa, sema.mod.declPtr(block.src_decl), switch_node_offset, range_expand);
83898407 return TypedValue{
83908408 .ty = item_ty,
83918409 .val = try sema.resolveConstValue(block, src, item),
......@@ -8434,19 +8452,18 @@ fn validateSwitchItemEnum(
84348452 switch_prong_src: Module.SwitchProngSrc,
84358453) CompileError!void {
84368454 const item_tv = try sema.resolveSwitchItemVal(block, item_ref, src_node_offset, switch_prong_src, .none);
8437 const target = sema.mod.getTarget();
8438 const field_index = item_tv.ty.enumTagFieldIndex(item_tv.val, target) orelse {
8455 const field_index = item_tv.ty.enumTagFieldIndex(item_tv.val, sema.mod) orelse {
84398456 const msg = msg: {
8440 const src = switch_prong_src.resolve(sema.gpa, block.src_decl, src_node_offset, .none);
8457 const src = switch_prong_src.resolve(sema.gpa, sema.mod.declPtr(block.src_decl), src_node_offset, .none);
84418458 const msg = try sema.errMsg(
84428459 block,
84438460 src,
84448461 "enum '{}' has no tag with value '{}'",
8445 .{ item_tv.ty.fmt(target), item_tv.val.fmtValue(item_tv.ty, target) },
8462 .{ item_tv.ty.fmt(sema.mod), item_tv.val.fmtValue(item_tv.ty, sema.mod) },
84468463 );
84478464 errdefer msg.destroy(sema.gpa);
84488465 try sema.mod.errNoteNonLazy(
8449 item_tv.ty.declSrcLoc(),
8466 item_tv.ty.declSrcLoc(sema.mod),
84508467 msg,
84518468 "enum declared here",
84528469 .{},
......@@ -8487,8 +8504,9 @@ fn validateSwitchDupe(
84878504) CompileError!void {
84888505 const prev_prong_src = maybe_prev_src orelse return;
84898506 const gpa = sema.gpa;
8490 const src = switch_prong_src.resolve(gpa, block.src_decl, src_node_offset, .none);
8491 const prev_src = prev_prong_src.resolve(gpa, block.src_decl, src_node_offset, .none);
8507 const block_src_decl = sema.mod.declPtr(block.src_decl);
8508 const src = switch_prong_src.resolve(gpa, block_src_decl, src_node_offset, .none);
8509 const prev_src = prev_prong_src.resolve(gpa, block_src_decl, src_node_offset, .none);
84928510 const msg = msg: {
84938511 const msg = try sema.errMsg(
84948512 block,
......@@ -8525,7 +8543,8 @@ fn validateSwitchItemBool(
85258543 false_count.* += 1;
85268544 }
85278545 if (true_count.* + false_count.* > 2) {
8528 const src = switch_prong_src.resolve(sema.gpa, block.src_decl, src_node_offset, .none);
8546 const block_src_decl = sema.mod.declPtr(block.src_decl);
8547 const src = switch_prong_src.resolve(sema.gpa, block_src_decl, src_node_offset, .none);
85298548 return sema.fail(block, src, "duplicate switch value", .{});
85308549 }
85318550}
......@@ -8558,13 +8577,12 @@ fn validateSwitchNoRange(
85588577 const operand_src: LazySrcLoc = .{ .node_offset_switch_operand = src_node_offset };
85598578 const range_src: LazySrcLoc = .{ .node_offset_switch_range = src_node_offset };
85608579
8561 const target = sema.mod.getTarget();
85628580 const msg = msg: {
85638581 const msg = try sema.errMsg(
85648582 block,
85658583 operand_src,
85668584 "ranges not allowed when switching on type '{}'",
8567 .{operand_ty.fmt(target)},
8585 .{operand_ty.fmt(sema.mod)},
85688586 );
85698587 errdefer msg.destroy(sema.gpa);
85708588 try sema.errNote(
......@@ -8587,7 +8605,6 @@ fn zirHasField(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
85878605 const unresolved_ty = try sema.resolveType(block, ty_src, extra.lhs);
85888606 const field_name = try sema.resolveConstString(block, name_src, extra.rhs);
85898607 const ty = try sema.resolveTypeFields(block, ty_src, unresolved_ty);
8590 const target = sema.mod.getTarget();
85918608
85928609 const has_field = hf: {
85938610 if (ty.isSlice()) {
......@@ -8610,7 +8627,7 @@ fn zirHasField(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
86108627 .Enum => ty.enumFields().contains(field_name),
86118628 .Array => mem.eql(u8, field_name, "len"),
86128629 else => return sema.fail(block, ty_src, "type '{}' does not support '@hasField'", .{
8613 ty.fmt(target),
8630 ty.fmt(sema.mod),
86148631 }),
86158632 };
86168633 };
......@@ -8633,7 +8650,8 @@ fn zirHasDecl(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
86338650 try checkNamespaceType(sema, block, lhs_src, container_type);
86348651
86358652 const namespace = container_type.getNamespace() orelse return Air.Inst.Ref.bool_false;
8636 if (try sema.lookupInNamespace(block, src, namespace, decl_name, true)) |decl| {
8653 if (try sema.lookupInNamespace(block, src, namespace, decl_name, true)) |decl_index| {
8654 const decl = sema.mod.declPtr(decl_index);
86378655 if (decl.is_pub or decl.getFileScope() == block.getFileScope()) {
86388656 return Air.Inst.Ref.bool_true;
86398657 }
......@@ -8661,8 +8679,9 @@ fn zirImport(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
86618679 },
86628680 };
86638681 try mod.semaFile(result.file);
8664 const file_root_decl = result.file.root_decl.?;
8665 try mod.declareDeclDependency(sema.owner_decl, file_root_decl);
8682 const file_root_decl_index = result.file.root_decl.unwrap().?;
8683 const file_root_decl = mod.declPtr(file_root_decl_index);
8684 try mod.declareDeclDependency(sema.owner_decl_index, file_root_decl_index);
86668685 return sema.addConstant(file_root_decl.ty, file_root_decl.val);
86678686}
86688687
......@@ -8763,7 +8782,7 @@ fn zirShl(
87638782 }
87648783 const int_info = scalar_ty.intInfo(target);
87658784 const truncated = try shifted.intTrunc(lhs_ty, sema.arena, int_info.signedness, int_info.bits, target);
8766 if (truncated.compare(.eq, shifted, lhs_ty, target)) {
8785 if (truncated.compare(.eq, shifted, lhs_ty, sema.mod)) {
87678786 break :val shifted;
87688787 }
87698788 return sema.addConstUndef(lhs_ty);
......@@ -8927,7 +8946,7 @@ fn zirBitNot(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
89278946
89288947 if (scalar_type.zigTypeTag() != .Int) {
89298948 return sema.fail(block, src, "unable to perform binary not operation on type '{}'", .{
8930 operand_type.fmt(target),
8949 operand_type.fmt(sema.mod),
89318950 });
89328951 }
89338952
......@@ -8939,7 +8958,7 @@ fn zirBitNot(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
89398958 var elem_val_buf: Value.ElemValueBuffer = undefined;
89408959 const elems = try sema.arena.alloc(Value, vec_len);
89418960 for (elems) |*elem, i| {
8942 const elem_val = val.elemValueBuffer(i, &elem_val_buf);
8961 const elem_val = val.elemValueBuffer(sema.mod, i, &elem_val_buf);
89438962 elem.* = try elem_val.bitwiseNot(scalar_type, sema.arena, target);
89448963 }
89458964 return sema.addConstant(
......@@ -9047,14 +9066,13 @@ fn zirArrayCat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
90479066 const lhs_src: LazySrcLoc = .{ .node_offset_bin_lhs = inst_data.src_node };
90489067 const rhs_src: LazySrcLoc = .{ .node_offset_bin_rhs = inst_data.src_node };
90499068
9050 const target = sema.mod.getTarget();
90519069 const lhs_info = (try sema.getArrayCatInfo(block, lhs_src, lhs)) orelse
9052 return sema.fail(block, lhs_src, "expected array, found '{}'", .{lhs_ty.fmt(target)});
9070 return sema.fail(block, lhs_src, "expected array, found '{}'", .{lhs_ty.fmt(sema.mod)});
90539071 const rhs_info = (try sema.getArrayCatInfo(block, rhs_src, rhs)) orelse
9054 return sema.fail(block, rhs_src, "expected array, found '{}'", .{rhs_ty.fmt(target)});
9055 if (!lhs_info.elem_type.eql(rhs_info.elem_type, target)) {
9072 return sema.fail(block, rhs_src, "expected array, found '{}'", .{rhs_ty.fmt(sema.mod)});
9073 if (!lhs_info.elem_type.eql(rhs_info.elem_type, sema.mod)) {
90569074 return sema.fail(block, rhs_src, "expected array of type '{}', found '{}'", .{
9057 lhs_info.elem_type.fmt(target), rhs_ty.fmt(target),
9075 lhs_info.elem_type.fmt(sema.mod), rhs_ty.fmt(sema.mod),
90589076 });
90599077 }
90609078
......@@ -9062,7 +9080,7 @@ fn zirArrayCat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
90629080 // will catch this if it is a problem.
90639081 var res_sent: ?Value = null;
90649082 if (rhs_info.sentinel != null and lhs_info.sentinel != null) {
9065 if (rhs_info.sentinel.?.eql(lhs_info.sentinel.?, lhs_info.elem_type, target)) {
9083 if (rhs_info.sentinel.?.eql(lhs_info.sentinel.?, lhs_info.elem_type, sema.mod)) {
90669084 res_sent = lhs_info.sentinel.?;
90679085 }
90689086 }
......@@ -9084,14 +9102,14 @@ fn zirArrayCat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
90849102 {
90859103 var i: usize = 0;
90869104 while (i < lhs_len) : (i += 1) {
9087 const val = try lhs_sub_val.elemValue(sema.arena, i);
9105 const val = try lhs_sub_val.elemValue(sema.mod, sema.arena, i);
90889106 buf[i] = try val.copy(anon_decl.arena());
90899107 }
90909108 }
90919109 {
90929110 var i: usize = 0;
90939111 while (i < rhs_len) : (i += 1) {
9094 const val = try rhs_sub_val.elemValue(sema.arena, i);
9112 const val = try rhs_sub_val.elemValue(sema.mod, sema.arena, i);
90959113 buf[lhs_len + i] = try val.copy(anon_decl.arena());
90969114 }
90979115 }
......@@ -9123,7 +9141,6 @@ fn zirArrayCat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
91239141
91249142fn getArrayCatInfo(sema: *Sema, block: *Block, src: LazySrcLoc, inst: Air.Inst.Ref) !?Type.ArrayInfo {
91259143 const t = sema.typeOf(inst);
9126 const target = sema.mod.getTarget();
91279144 return switch (t.zigTypeTag()) {
91289145 .Array => t.arrayInfo(),
91299146 .Pointer => blk: {
......@@ -9133,7 +9150,7 @@ fn getArrayCatInfo(sema: *Sema, block: *Block, src: LazySrcLoc, inst: Air.Inst.R
91339150 return Type.ArrayInfo{
91349151 .elem_type = t.childType(),
91359152 .sentinel = t.sentinel(),
9136 .len = val.sliceLen(target),
9153 .len = val.sliceLen(sema.mod),
91379154 };
91389155 }
91399156 if (ptrinfo.pointee_type.zigTypeTag() != .Array) return null;
......@@ -9229,10 +9246,9 @@ fn zirArrayMul(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
92299246 if (lhs_ty.isTuple()) {
92309247 return sema.analyzeTupleMul(block, inst_data.src_node, lhs, factor);
92319248 }
9232 const target = sema.mod.getTarget();
92339249
92349250 const mulinfo = (try sema.getArrayCatInfo(block, lhs_src, lhs)) orelse
9235 return sema.fail(block, lhs_src, "expected array, found '{}'", .{lhs_ty.fmt(target)});
9251 return sema.fail(block, lhs_src, "expected array, found '{}'", .{lhs_ty.fmt(sema.mod)});
92369252
92379253 const final_len_u64 = std.math.mul(u64, mulinfo.len, factor) catch
92389254 return sema.fail(block, rhs_src, "operation results in overflow", .{});
......@@ -9264,7 +9280,7 @@ fn zirArrayMul(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
92649280 // Optimization for the common pattern of a single element repeated N times, such
92659281 // as zero-filling a byte array.
92669282 const val = if (lhs_len == 1) blk: {
9267 const elem_val = try lhs_sub_val.elemValue(sema.arena, 0);
9283 const elem_val = try lhs_sub_val.elemValue(sema.mod, sema.arena, 0);
92689284 const copied_val = try elem_val.copy(anon_decl.arena());
92699285 break :blk try Value.Tag.repeated.create(anon_decl.arena(), copied_val);
92709286 } else blk: {
......@@ -9273,7 +9289,7 @@ fn zirArrayMul(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
92739289 while (i < factor) : (i += 1) {
92749290 var j: usize = 0;
92759291 while (j < lhs_len) : (j += 1) {
9276 const val = try lhs_sub_val.elemValue(sema.arena, j);
9292 const val = try lhs_sub_val.elemValue(sema.mod, sema.arena, j);
92779293 buf[lhs_len * i + j] = try val.copy(anon_decl.arena());
92789294 }
92799295 }
......@@ -9310,9 +9326,8 @@ fn zirNegate(
93109326 const rhs_ty = sema.typeOf(rhs);
93119327 const rhs_scalar_ty = rhs_ty.scalarType();
93129328
9313 const target = sema.mod.getTarget();
93149329 if (tag_override == .sub and rhs_scalar_ty.isUnsignedInt()) {
9315 return sema.fail(block, src, "negation of type '{}'", .{rhs_ty.fmt(target)});
9330 return sema.fail(block, src, "negation of type '{}'", .{rhs_ty.fmt(sema.mod)});
93169331 }
93179332
93189333 const lhs = if (rhs_ty.zigTypeTag() == .Vector)
......@@ -9364,12 +9379,13 @@ fn zirOverflowArithmetic(
93649379 const ptr = sema.resolveInst(extra.ptr);
93659380
93669381 const lhs_ty = sema.typeOf(lhs);
9367 const target = sema.mod.getTarget();
9382 const mod = sema.mod;
9383 const target = mod.getTarget();
93689384
93699385 // Note, the types of lhs/rhs (also for shifting)/ptr are already correct as ensured by astgen.
93709386 const dest_ty = lhs_ty;
93719387 if (dest_ty.zigTypeTag() != .Int) {
9372 return sema.fail(block, src, "expected integer type, found '{}'", .{dest_ty.fmt(target)});
9388 return sema.fail(block, src, "expected integer type, found '{}'", .{dest_ty.fmt(mod)});
93739389 }
93749390
93759391 const maybe_lhs_val = try sema.resolveMaybeUndefVal(block, lhs_src, lhs);
......@@ -9445,7 +9461,7 @@ fn zirOverflowArithmetic(
94459461 if (!lhs_val.isUndef()) {
94469462 if (lhs_val.compareWithZero(.eq)) {
94479463 break :result .{ .overflowed = .no, .wrapped = lhs };
9448 } else if (lhs_val.compare(.eq, Value.one, dest_ty, target)) {
9464 } else if (lhs_val.compare(.eq, Value.one, dest_ty, mod)) {
94499465 break :result .{ .overflowed = .no, .wrapped = rhs };
94509466 }
94519467 }
......@@ -9455,7 +9471,7 @@ fn zirOverflowArithmetic(
94559471 if (!rhs_val.isUndef()) {
94569472 if (rhs_val.compareWithZero(.eq)) {
94579473 break :result .{ .overflowed = .no, .wrapped = rhs };
9458 } else if (rhs_val.compare(.eq, Value.one, dest_ty, target)) {
9474 } else if (rhs_val.compare(.eq, Value.one, dest_ty, mod)) {
94599475 break :result .{ .overflowed = .no, .wrapped = lhs };
94609476 }
94619477 }
......@@ -9596,7 +9612,8 @@ fn analyzeArithmetic(
95969612 });
95979613 }
95989614
9599 const target = sema.mod.getTarget();
9615 const mod = sema.mod;
9616 const target = mod.getTarget();
96009617 const maybe_lhs_val = try sema.resolveMaybeUndefVal(block, lhs_src, casted_lhs);
96019618 const maybe_rhs_val = try sema.resolveMaybeUndefVal(block, rhs_src, casted_rhs);
96029619 const rs: struct { src: LazySrcLoc, air_tag: Air.Inst.Tag } = rs: {
......@@ -9834,7 +9851,7 @@ fn analyzeArithmetic(
98349851 if (lhs_val.isUndef()) {
98359852 if (lhs_scalar_ty.isSignedInt() and rhs_scalar_ty.isSignedInt()) {
98369853 if (maybe_rhs_val) |rhs_val| {
9837 if (rhs_val.compare(.neq, Value.negative_one, resolved_type, target)) {
9854 if (rhs_val.compare(.neq, Value.negative_one, resolved_type, mod)) {
98389855 return sema.addConstUndef(resolved_type);
98399856 }
98409857 }
......@@ -9909,7 +9926,7 @@ fn analyzeArithmetic(
99099926 if (lhs_val.isUndef()) {
99109927 if (lhs_scalar_ty.isSignedInt() and rhs_scalar_ty.isSignedInt()) {
99119928 if (maybe_rhs_val) |rhs_val| {
9912 if (rhs_val.compare(.neq, Value.negative_one, resolved_type, target)) {
9929 if (rhs_val.compare(.neq, Value.negative_one, resolved_type, mod)) {
99139930 return sema.addConstUndef(resolved_type);
99149931 }
99159932 }
......@@ -9972,7 +9989,7 @@ fn analyzeArithmetic(
99729989 if (lhs_val.isUndef()) {
99739990 if (lhs_scalar_ty.isSignedInt() and rhs_scalar_ty.isSignedInt()) {
99749991 if (maybe_rhs_val) |rhs_val| {
9975 if (rhs_val.compare(.neq, Value.negative_one, resolved_type, target)) {
9992 if (rhs_val.compare(.neq, Value.negative_one, resolved_type, mod)) {
99769993 return sema.addConstUndef(resolved_type);
99779994 }
99789995 }
......@@ -10062,7 +10079,7 @@ fn analyzeArithmetic(
1006210079 if (lhs_val.compareWithZero(.eq)) {
1006310080 return sema.addConstant(resolved_type, Value.zero);
1006410081 }
10065 if (lhs_val.compare(.eq, Value.one, resolved_type, target)) {
10082 if (lhs_val.compare(.eq, Value.one, resolved_type, mod)) {
1006610083 return casted_rhs;
1006710084 }
1006810085 }
......@@ -10078,7 +10095,7 @@ fn analyzeArithmetic(
1007810095 if (rhs_val.compareWithZero(.eq)) {
1007910096 return sema.addConstant(resolved_type, Value.zero);
1008010097 }
10081 if (rhs_val.compare(.eq, Value.one, resolved_type, target)) {
10098 if (rhs_val.compare(.eq, Value.one, resolved_type, mod)) {
1008210099 return casted_lhs;
1008310100 }
1008410101 if (maybe_lhs_val) |lhs_val| {
......@@ -10113,7 +10130,7 @@ fn analyzeArithmetic(
1011310130 if (lhs_val.compareWithZero(.eq)) {
1011410131 return sema.addConstant(resolved_type, Value.zero);
1011510132 }
10116 if (lhs_val.compare(.eq, Value.one, resolved_type, target)) {
10133 if (lhs_val.compare(.eq, Value.one, resolved_type, mod)) {
1011710134 return casted_rhs;
1011810135 }
1011910136 }
......@@ -10125,7 +10142,7 @@ fn analyzeArithmetic(
1012510142 if (rhs_val.compareWithZero(.eq)) {
1012610143 return sema.addConstant(resolved_type, Value.zero);
1012710144 }
10128 if (rhs_val.compare(.eq, Value.one, resolved_type, target)) {
10145 if (rhs_val.compare(.eq, Value.one, resolved_type, mod)) {
1012910146 return casted_lhs;
1013010147 }
1013110148 if (maybe_lhs_val) |lhs_val| {
......@@ -10149,7 +10166,7 @@ fn analyzeArithmetic(
1014910166 if (lhs_val.compareWithZero(.eq)) {
1015010167 return sema.addConstant(resolved_type, Value.zero);
1015110168 }
10152 if (lhs_val.compare(.eq, Value.one, resolved_type, target)) {
10169 if (lhs_val.compare(.eq, Value.one, resolved_type, mod)) {
1015310170 return casted_rhs;
1015410171 }
1015510172 }
......@@ -10161,7 +10178,7 @@ fn analyzeArithmetic(
1016110178 if (rhs_val.compareWithZero(.eq)) {
1016210179 return sema.addConstant(resolved_type, Value.zero);
1016310180 }
10164 if (rhs_val.compare(.eq, Value.one, resolved_type, target)) {
10181 if (rhs_val.compare(.eq, Value.one, resolved_type, mod)) {
1016510182 return casted_lhs;
1016610183 }
1016710184 if (maybe_lhs_val) |lhs_val| {
......@@ -10431,7 +10448,7 @@ fn analyzePtrArithmetic(
1043110448 if (air_tag == .ptr_sub) {
1043210449 return sema.fail(block, op_src, "TODO implement Sema comptime pointer subtraction", .{});
1043310450 }
10434 const new_ptr_val = try ptr_val.elemPtr(ptr_ty, sema.arena, offset_int, target);
10451 const new_ptr_val = try ptr_val.elemPtr(ptr_ty, sema.arena, offset_int, sema.mod);
1043510452 return sema.addConstant(new_ptr_ty, new_ptr_val);
1043610453 } else break :rs offset_src;
1043710454 } else break :rs ptr_src;
......@@ -10605,7 +10622,6 @@ fn zirCmpEq(
1060510622 const rhs_src: LazySrcLoc = .{ .node_offset_bin_rhs = inst_data.src_node };
1060610623 const lhs = sema.resolveInst(extra.lhs);
1060710624 const rhs = sema.resolveInst(extra.rhs);
10608 const target = sema.mod.getTarget();
1060910625
1061010626 const lhs_ty = sema.typeOf(lhs);
1061110627 const rhs_ty = sema.typeOf(rhs);
......@@ -10630,7 +10646,7 @@ fn zirCmpEq(
1063010646
1063110647 if (lhs_ty_tag == .Null or rhs_ty_tag == .Null) {
1063210648 const non_null_type = if (lhs_ty_tag == .Null) rhs_ty else lhs_ty;
10633 return sema.fail(block, src, "comparison of '{}' with null", .{non_null_type.fmt(target)});
10649 return sema.fail(block, src, "comparison of '{}' with null", .{non_null_type.fmt(sema.mod)});
1063410650 }
1063510651
1063610652 if (lhs_ty_tag == .Union and (rhs_ty_tag == .EnumLiteral or rhs_ty_tag == .Enum)) {
......@@ -10670,7 +10686,7 @@ fn zirCmpEq(
1067010686 if (lhs_ty_tag == .Type and rhs_ty_tag == .Type) {
1067110687 const lhs_as_type = try sema.analyzeAsType(block, lhs_src, lhs);
1067210688 const rhs_as_type = try sema.analyzeAsType(block, rhs_src, rhs);
10673 if (lhs_as_type.eql(rhs_as_type, target) == (op == .eq)) {
10689 if (lhs_as_type.eql(rhs_as_type, sema.mod) == (op == .eq)) {
1067410690 return Air.Inst.Ref.bool_true;
1067510691 } else {
1067610692 return Air.Inst.Ref.bool_false;
......@@ -10747,10 +10763,9 @@ fn analyzeCmp(
1074710763 }
1074810764 const instructions = &[_]Air.Inst.Ref{ lhs, rhs };
1074910765 const resolved_type = try sema.resolvePeerTypes(block, src, instructions, .{ .override = &[_]LazySrcLoc{ lhs_src, rhs_src } });
10750 const target = sema.mod.getTarget();
1075110766 if (!resolved_type.isSelfComparable(is_equality_cmp)) {
1075210767 return sema.fail(block, src, "{s} operator not allowed for type '{}'", .{
10753 @tagName(op), resolved_type.fmt(target),
10768 @tagName(op), resolved_type.fmt(sema.mod),
1075410769 });
1075510770 }
1075610771 const casted_lhs = try sema.coerce(block, resolved_type, lhs, lhs_src);
......@@ -10768,7 +10783,6 @@ fn cmpSelf(
1076810783 rhs_src: LazySrcLoc,
1076910784) CompileError!Air.Inst.Ref {
1077010785 const resolved_type = sema.typeOf(casted_lhs);
10771 const target = sema.mod.getTarget();
1077210786 const runtime_src: LazySrcLoc = src: {
1077310787 if (try sema.resolveMaybeUndefVal(block, lhs_src, casted_lhs)) |lhs_val| {
1077410788 if (lhs_val.isUndef()) return sema.addConstUndef(Type.bool);
......@@ -10777,11 +10791,11 @@ fn cmpSelf(
1077710791
1077810792 if (resolved_type.zigTypeTag() == .Vector) {
1077910793 const result_ty = try Type.vector(sema.arena, resolved_type.vectorLen(), Type.@"bool");
10780 const cmp_val = try lhs_val.compareVector(op, rhs_val, resolved_type, sema.arena, target);
10794 const cmp_val = try lhs_val.compareVector(op, rhs_val, resolved_type, sema.arena, sema.mod);
1078110795 return sema.addConstant(result_ty, cmp_val);
1078210796 }
1078310797
10784 if (lhs_val.compare(op, rhs_val, resolved_type, target)) {
10798 if (lhs_val.compare(op, rhs_val, resolved_type, sema.mod)) {
1078510799 return Air.Inst.Ref.bool_true;
1078610800 } else {
1078710801 return Air.Inst.Ref.bool_false;
......@@ -10849,7 +10863,7 @@ fn zirSizeOf(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
1084910863 .Null,
1085010864 .BoundFn,
1085110865 .Opaque,
10852 => return sema.fail(block, src, "no size available for type '{}'", .{operand_ty.fmt(target)}),
10866 => return sema.fail(block, src, "no size available for type '{}'", .{operand_ty.fmt(sema.mod)}),
1085310867
1085410868 .Type,
1085510869 .EnumLiteral,
......@@ -10892,9 +10906,9 @@ fn zirThis(
1089210906 block: *Block,
1089310907 extended: Zir.Inst.Extended.InstData,
1089410908) CompileError!Air.Inst.Ref {
10895 const this_decl = block.namespace.getDecl();
10909 const this_decl_index = block.namespace.getDeclIndex();
1089610910 const src: LazySrcLoc = .{ .node_offset = @bitCast(i32, extended.operand) };
10897 return sema.analyzeDeclVal(block, src, this_decl);
10911 return sema.analyzeDeclVal(block, src, this_decl_index);
1089810912}
1089910913
1090010914fn zirClosureCapture(
......@@ -10927,7 +10941,7 @@ fn zirClosureGet(
1092710941) CompileError!Air.Inst.Ref {
1092810942 // TODO CLOSURE: Test this with inline functions
1092910943 const inst_data = sema.code.instructions.items(.data)[inst].inst_node;
10930 var scope: *CaptureScope = block.src_decl.src_scope.?;
10944 var scope: *CaptureScope = sema.mod.declPtr(block.src_decl).src_scope.?;
1093110945 // Note: The target closure must be in this scope list.
1093210946 // If it's not here, the zir is invalid, or the list is broken.
1093310947 const tv = while (true) {
......@@ -10973,11 +10987,12 @@ fn zirBuiltinSrc(
1097310987 const src: LazySrcLoc = .{ .node_offset = @bitCast(i32, extended.operand) };
1097410988 const extra = sema.code.extraData(Zir.Inst.LineColumn, extended.operand).data;
1097510989 const func = sema.func orelse return sema.fail(block, src, "@src outside function", .{});
10990 const fn_owner_decl = sema.mod.declPtr(func.owner_decl);
1097610991
1097710992 const func_name_val = blk: {
1097810993 var anon_decl = try block.startAnonDecl(src);
1097910994 defer anon_decl.deinit();
10980 const name = std.mem.span(func.owner_decl.name);
10995 const name = std.mem.span(fn_owner_decl.name);
1098110996 const bytes = try anon_decl.arena().dupe(u8, name[0 .. name.len + 1]);
1098210997 const new_decl = try anon_decl.finish(
1098310998 try Type.Tag.array_u8_sentinel_0.create(anon_decl.arena(), bytes.len - 1),
......@@ -10990,7 +11005,7 @@ fn zirBuiltinSrc(
1099011005 const file_name_val = blk: {
1099111006 var anon_decl = try block.startAnonDecl(src);
1099211007 defer anon_decl.deinit();
10993 const name = try func.owner_decl.getFileScope().fullPathZ(anon_decl.arena());
11008 const name = try fn_owner_decl.getFileScope().fullPathZ(anon_decl.arena());
1099411009 const new_decl = try anon_decl.finish(
1099511010 try Type.Tag.array_u8_sentinel_0.create(anon_decl.arena(), name.len),
1099611011 try Value.Tag.bytes.create(anon_decl.arena(), name[0 .. name.len + 1]),
......@@ -11118,24 +11133,26 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1111811133 }
1111911134
1112011135 const args_val = v: {
11121 const fn_info_decl = (try sema.namespaceLookup(
11136 const fn_info_decl_index = (try sema.namespaceLookup(
1112211137 block,
1112311138 src,
1112411139 type_info_ty.getNamespace().?,
1112511140 "Fn",
1112611141 )).?;
11127 try sema.mod.declareDeclDependency(sema.owner_decl, fn_info_decl);
11128 try sema.ensureDeclAnalyzed(fn_info_decl);
11142 try sema.mod.declareDeclDependency(sema.owner_decl_index, fn_info_decl_index);
11143 try sema.ensureDeclAnalyzed(fn_info_decl_index);
11144 const fn_info_decl = sema.mod.declPtr(fn_info_decl_index);
1112911145 var fn_ty_buffer: Value.ToTypeBuffer = undefined;
1113011146 const fn_ty = fn_info_decl.val.toType(&fn_ty_buffer);
11131 const param_info_decl = (try sema.namespaceLookup(
11147 const param_info_decl_index = (try sema.namespaceLookup(
1113211148 block,
1113311149 src,
1113411150 fn_ty.getNamespace().?,
1113511151 "Param",
1113611152 )).?;
11137 try sema.mod.declareDeclDependency(sema.owner_decl, param_info_decl);
11138 try sema.ensureDeclAnalyzed(param_info_decl);
11153 try sema.mod.declareDeclDependency(sema.owner_decl_index, param_info_decl_index);
11154 try sema.ensureDeclAnalyzed(param_info_decl_index);
11155 const param_info_decl = sema.mod.declPtr(param_info_decl_index);
1113911156 var param_buffer: Value.ToTypeBuffer = undefined;
1114011157 const param_ty = param_info_decl.val.toType(&param_buffer);
1114111158 const new_decl = try params_anon_decl.finish(
......@@ -11307,14 +11324,15 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1130711324
1130811325 // Get the Error type
1130911326 const error_field_ty = t: {
11310 const set_field_ty_decl = (try sema.namespaceLookup(
11327 const set_field_ty_decl_index = (try sema.namespaceLookup(
1131111328 block,
1131211329 src,
1131311330 type_info_ty.getNamespace().?,
1131411331 "Error",
1131511332 )).?;
11316 try sema.mod.declareDeclDependency(sema.owner_decl, set_field_ty_decl);
11317 try sema.ensureDeclAnalyzed(set_field_ty_decl);
11333 try sema.mod.declareDeclDependency(sema.owner_decl_index, set_field_ty_decl_index);
11334 try sema.ensureDeclAnalyzed(set_field_ty_decl_index);
11335 const set_field_ty_decl = sema.mod.declPtr(set_field_ty_decl_index);
1131811336 var buffer: Value.ToTypeBuffer = undefined;
1131911337 break :t try set_field_ty_decl.val.toType(&buffer).copy(fields_anon_decl.arena());
1132011338 };
......@@ -11416,14 +11434,15 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1141611434 defer fields_anon_decl.deinit();
1141711435
1141811436 const enum_field_ty = t: {
11419 const enum_field_ty_decl = (try sema.namespaceLookup(
11437 const enum_field_ty_decl_index = (try sema.namespaceLookup(
1142011438 block,
1142111439 src,
1142211440 type_info_ty.getNamespace().?,
1142311441 "EnumField",
1142411442 )).?;
11425 try sema.mod.declareDeclDependency(sema.owner_decl, enum_field_ty_decl);
11426 try sema.ensureDeclAnalyzed(enum_field_ty_decl);
11443 try sema.mod.declareDeclDependency(sema.owner_decl_index, enum_field_ty_decl_index);
11444 try sema.ensureDeclAnalyzed(enum_field_ty_decl_index);
11445 const enum_field_ty_decl = sema.mod.declPtr(enum_field_ty_decl_index);
1142711446 var buffer: Value.ToTypeBuffer = undefined;
1142811447 break :t try enum_field_ty_decl.val.toType(&buffer).copy(fields_anon_decl.arena());
1142911448 };
......@@ -11514,14 +11533,15 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1151411533 defer fields_anon_decl.deinit();
1151511534
1151611535 const union_field_ty = t: {
11517 const union_field_ty_decl = (try sema.namespaceLookup(
11536 const union_field_ty_decl_index = (try sema.namespaceLookup(
1151811537 block,
1151911538 src,
1152011539 type_info_ty.getNamespace().?,
1152111540 "UnionField",
1152211541 )).?;
11523 try sema.mod.declareDeclDependency(sema.owner_decl, union_field_ty_decl);
11524 try sema.ensureDeclAnalyzed(union_field_ty_decl);
11542 try sema.mod.declareDeclDependency(sema.owner_decl_index, union_field_ty_decl_index);
11543 try sema.ensureDeclAnalyzed(union_field_ty_decl_index);
11544 const union_field_ty_decl = sema.mod.declPtr(union_field_ty_decl_index);
1152511545 var buffer: Value.ToTypeBuffer = undefined;
1152611546 break :t try union_field_ty_decl.val.toType(&buffer).copy(fields_anon_decl.arena());
1152711547 };
......@@ -11621,14 +11641,15 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1162111641 defer fields_anon_decl.deinit();
1162211642
1162311643 const struct_field_ty = t: {
11624 const struct_field_ty_decl = (try sema.namespaceLookup(
11644 const struct_field_ty_decl_index = (try sema.namespaceLookup(
1162511645 block,
1162611646 src,
1162711647 type_info_ty.getNamespace().?,
1162811648 "StructField",
1162911649 )).?;
11630 try sema.mod.declareDeclDependency(sema.owner_decl, struct_field_ty_decl);
11631 try sema.ensureDeclAnalyzed(struct_field_ty_decl);
11650 try sema.mod.declareDeclDependency(sema.owner_decl_index, struct_field_ty_decl_index);
11651 try sema.ensureDeclAnalyzed(struct_field_ty_decl_index);
11652 const struct_field_ty_decl = sema.mod.declPtr(struct_field_ty_decl_index);
1163211653 var buffer: Value.ToTypeBuffer = undefined;
1163311654 break :t try struct_field_ty_decl.val.toType(&buffer).copy(fields_anon_decl.arena());
1163411655 };
......@@ -11811,14 +11832,15 @@ fn typeInfoDecls(
1181111832 defer decls_anon_decl.deinit();
1181211833
1181311834 const declaration_ty = t: {
11814 const declaration_ty_decl = (try sema.namespaceLookup(
11835 const declaration_ty_decl_index = (try sema.namespaceLookup(
1181511836 block,
1181611837 src,
1181711838 type_info_ty.getNamespace().?,
1181811839 "Declaration",
1181911840 )).?;
11820 try sema.mod.declareDeclDependency(sema.owner_decl, declaration_ty_decl);
11821 try sema.ensureDeclAnalyzed(declaration_ty_decl);
11841 try sema.mod.declareDeclDependency(sema.owner_decl_index, declaration_ty_decl_index);
11842 try sema.ensureDeclAnalyzed(declaration_ty_decl_index);
11843 const declaration_ty_decl = sema.mod.declPtr(declaration_ty_decl_index);
1182211844 var buffer: Value.ToTypeBuffer = undefined;
1182311845 break :t try declaration_ty_decl.val.toType(&buffer).copy(decls_anon_decl.arena());
1182411846 };
......@@ -11827,7 +11849,8 @@ fn typeInfoDecls(
1182711849 const decls_len = if (opt_namespace) |ns| ns.decls.count() else 0;
1182811850 const decls_vals = try decls_anon_decl.arena().alloc(Value, decls_len);
1182911851 for (decls_vals) |*decls_val, i| {
11830 const decl = opt_namespace.?.decls.keys()[i];
11852 const decl_index = opt_namespace.?.decls.keys()[i];
11853 const decl = sema.mod.declPtr(decl_index);
1183111854 const name_val = v: {
1183211855 var anon_decl = try block.startAnonDecl(src);
1183311856 defer anon_decl.deinit();
......@@ -11947,12 +11970,11 @@ fn log2IntType(sema: *Sema, block: *Block, operand: Type, src: LazySrcLoc) Compi
1194711970 },
1194811971 else => {},
1194911972 }
11950 const target = sema.mod.getTarget();
1195111973 return sema.fail(
1195211974 block,
1195311975 src,
1195411976 "bit shifting operation expected integer type, found '{}'",
11955 .{operand.fmt(target)},
11977 .{operand.fmt(sema.mod)},
1195611978 );
1195711979}
1195811980
......@@ -12426,8 +12448,7 @@ fn zirPtrTypeSimple(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErr
1242612448
1242712449 const inst_data = sema.code.instructions.items(.data)[inst].ptr_type_simple;
1242812450 const elem_type = try sema.resolveType(block, .unneeded, inst_data.elem_type);
12429 const target = sema.mod.getTarget();
12430 const ty = try Type.ptr(sema.arena, target, .{
12451 const ty = try Type.ptr(sema.arena, sema.mod, .{
1243112452 .pointee_type = elem_type,
1243212453 .@"addrspace" = .generic,
1243312454 .mutable = inst_data.is_mutable,
......@@ -12466,7 +12487,7 @@ fn zirPtrType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
1246612487 // Check if this happens to be the lazy alignment of our element type, in
1246712488 // which case we can make this 0 without resolving it.
1246812489 if (val.castTag(.lazy_align)) |payload| {
12469 if (payload.data.eql(unresolved_elem_ty, target)) {
12490 if (payload.data.eql(unresolved_elem_ty, sema.mod)) {
1247012491 break :blk 0;
1247112492 }
1247212493 }
......@@ -12505,7 +12526,7 @@ fn zirPtrType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
1250512526 try sema.resolveTypeLayout(block, elem_ty_src, elem_ty);
1250612527 break :t elem_ty;
1250712528 };
12508 const ty = try Type.ptr(sema.arena, target, .{
12529 const ty = try Type.ptr(sema.arena, sema.mod, .{
1250912530 .pointee_type = elem_ty,
1251012531 .sentinel = sentinel,
1251112532 .@"align" = abi_align,
......@@ -12754,10 +12775,10 @@ fn finishStructInit(
1275412775 const gpa = sema.gpa;
1275512776
1275612777 if (root_msg) |msg| {
12757 const fqn = try struct_obj.getFullyQualifiedName(gpa);
12778 const fqn = try struct_obj.getFullyQualifiedName(sema.mod);
1275812779 defer gpa.free(fqn);
1275912780 try sema.mod.errNoteNonLazy(
12760 struct_obj.srcLoc(),
12781 struct_obj.srcLoc(sema.mod),
1276112782 msg,
1276212783 "struct '{s}' declared here",
1276312784 .{fqn},
......@@ -12782,7 +12803,7 @@ fn finishStructInit(
1278212803
1278312804 if (is_ref) {
1278412805 const target = sema.mod.getTarget();
12785 const alloc_ty = try Type.ptr(sema.arena, target, .{
12806 const alloc_ty = try Type.ptr(sema.arena, sema.mod, .{
1278612807 .pointee_type = struct_ty,
1278712808 .@"addrspace" = target_util.defaultAddressSpace(target, .local),
1278812809 });
......@@ -12851,7 +12872,7 @@ fn zirStructInitAnon(
1285112872
1285212873 if (is_ref) {
1285312874 const target = sema.mod.getTarget();
12854 const alloc_ty = try Type.ptr(sema.arena, target, .{
12875 const alloc_ty = try Type.ptr(sema.arena, sema.mod, .{
1285512876 .pointee_type = tuple_ty,
1285612877 .@"addrspace" = target_util.defaultAddressSpace(target, .local),
1285712878 });
......@@ -12862,7 +12883,7 @@ fn zirStructInitAnon(
1286212883 const item = sema.code.extraData(Zir.Inst.StructInitAnon.Item, extra_index);
1286312884 extra_index = item.end;
1286412885
12865 const field_ptr_ty = try Type.ptr(sema.arena, target, .{
12886 const field_ptr_ty = try Type.ptr(sema.arena, sema.mod, .{
1286612887 .mutable = true,
1286712888 .@"addrspace" = target_util.defaultAddressSpace(target, .local),
1286812889 .pointee_type = field_ty,
......@@ -12949,13 +12970,13 @@ fn zirArrayInit(
1294912970
1295012971 if (is_ref) {
1295112972 const target = sema.mod.getTarget();
12952 const alloc_ty = try Type.ptr(sema.arena, target, .{
12973 const alloc_ty = try Type.ptr(sema.arena, sema.mod, .{
1295312974 .pointee_type = array_ty,
1295412975 .@"addrspace" = target_util.defaultAddressSpace(target, .local),
1295512976 });
1295612977 const alloc = try block.addTy(.alloc, alloc_ty);
1295712978
12958 const elem_ptr_ty = try Type.ptr(sema.arena, target, .{
12979 const elem_ptr_ty = try Type.ptr(sema.arena, sema.mod, .{
1295912980 .mutable = true,
1296012981 .@"addrspace" = target_util.defaultAddressSpace(target, .local),
1296112982 .pointee_type = elem_ty,
......@@ -13017,14 +13038,14 @@ fn zirArrayInitAnon(
1301713038
1301813039 if (is_ref) {
1301913040 const target = sema.mod.getTarget();
13020 const alloc_ty = try Type.ptr(sema.arena, target, .{
13041 const alloc_ty = try Type.ptr(sema.arena, sema.mod, .{
1302113042 .pointee_type = tuple_ty,
1302213043 .@"addrspace" = target_util.defaultAddressSpace(target, .local),
1302313044 });
1302413045 const alloc = try block.addTy(.alloc, alloc_ty);
1302513046 for (operands) |operand, i_usize| {
1302613047 const i = @intCast(u32, i_usize);
13027 const field_ptr_ty = try Type.ptr(sema.arena, target, .{
13048 const field_ptr_ty = try Type.ptr(sema.arena, sema.mod, .{
1302813049 .mutable = true,
1302913050 .@"addrspace" = target_util.defaultAddressSpace(target, .local),
1303013051 .pointee_type = types[i],
......@@ -13096,7 +13117,6 @@ fn fieldType(
1309613117 ty_src: LazySrcLoc,
1309713118) CompileError!Air.Inst.Ref {
1309813119 const resolved_ty = try sema.resolveTypeFields(block, ty_src, aggregate_ty);
13099 const target = sema.mod.getTarget();
1310013120 var cur_ty = resolved_ty;
1310113121 while (true) {
1310213122 switch (cur_ty.zigTypeTag()) {
......@@ -13127,7 +13147,7 @@ fn fieldType(
1312713147 else => {},
1312813148 }
1312913149 return sema.fail(block, ty_src, "expected struct or union; found '{}'", .{
13130 resolved_ty.fmt(target),
13150 resolved_ty.fmt(sema.mod),
1313113151 });
1313213152 }
1313313153}
......@@ -13216,10 +13236,10 @@ fn zirUnaryMath(
1321613236 const scalar_ty = operand_ty.scalarType();
1321713237 switch (scalar_ty.zigTypeTag()) {
1321813238 .ComptimeFloat, .Float => {},
13219 else => return sema.fail(block, operand_src, "expected vector of floats or float type, found '{}'", .{scalar_ty.fmt(target)}),
13239 else => return sema.fail(block, operand_src, "expected vector of floats or float type, found '{}'", .{scalar_ty.fmt(sema.mod)}),
1322013240 }
1322113241 },
13222 else => return sema.fail(block, operand_src, "expected vector of floats or float type, found '{}'", .{operand_ty.fmt(target)}),
13242 else => return sema.fail(block, operand_src, "expected vector of floats or float type, found '{}'", .{operand_ty.fmt(sema.mod)}),
1322313243 }
1322413244
1322513245 switch (operand_ty.zigTypeTag()) {
......@@ -13234,7 +13254,7 @@ fn zirUnaryMath(
1323413254 var elem_buf: Value.ElemValueBuffer = undefined;
1323513255 const elems = try sema.arena.alloc(Value, vec_len);
1323613256 for (elems) |*elem, i| {
13237 const elem_val = val.elemValueBuffer(i, &elem_buf);
13257 const elem_val = val.elemValueBuffer(sema.mod, i, &elem_buf);
1323813258 elem.* = try eval(elem_val, scalar_ty, sema.arena, target);
1323913259 }
1324013260 return sema.addConstant(
......@@ -13267,7 +13287,7 @@ fn zirTagName(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
1326713287 const src = inst_data.src();
1326813288 const operand = sema.resolveInst(inst_data.operand);
1326913289 const operand_ty = sema.typeOf(operand);
13270 const target = sema.mod.getTarget();
13290 const mod = sema.mod;
1327113291
1327213292 try sema.resolveTypeLayout(block, operand_src, operand_ty);
1327313293 const enum_ty = switch (operand_ty.zigTypeTag()) {
......@@ -13278,31 +13298,33 @@ fn zirTagName(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
1327813298 },
1327913299 .Enum => operand_ty,
1328013300 .Union => operand_ty.unionTagType() orelse {
13281 const decl = operand_ty.getOwnerDecl();
13301 const decl_index = operand_ty.getOwnerDecl();
13302 const decl = mod.declPtr(decl_index);
1328213303 const msg = msg: {
1328313304 const msg = try sema.errMsg(block, src, "union '{s}' is untagged", .{
1328413305 decl.name,
1328513306 });
1328613307 errdefer msg.destroy(sema.gpa);
13287 try sema.mod.errNoteNonLazy(decl.srcLoc(), msg, "declared here", .{});
13308 try mod.errNoteNonLazy(decl.srcLoc(), msg, "declared here", .{});
1328813309 break :msg msg;
1328913310 };
1329013311 return sema.failWithOwnedErrorMsg(block, msg);
1329113312 },
1329213313 else => return sema.fail(block, operand_src, "expected enum or union; found {}", .{
13293 operand_ty.fmt(target),
13314 operand_ty.fmt(mod),
1329413315 }),
1329513316 };
13296 const enum_decl = enum_ty.getOwnerDecl();
13317 const enum_decl_index = enum_ty.getOwnerDecl();
1329713318 const casted_operand = try sema.coerce(block, enum_ty, operand, operand_src);
1329813319 if (try sema.resolveDefinedValue(block, operand_src, casted_operand)) |val| {
13299 const field_index = enum_ty.enumTagFieldIndex(val, target) orelse {
13320 const field_index = enum_ty.enumTagFieldIndex(val, mod) orelse {
13321 const enum_decl = mod.declPtr(enum_decl_index);
1330013322 const msg = msg: {
1330113323 const msg = try sema.errMsg(block, src, "no field with value {} in enum '{s}'", .{
1330213324 casted_operand, enum_decl.name,
1330313325 });
1330413326 errdefer msg.destroy(sema.gpa);
13305 try sema.mod.errNoteNonLazy(enum_decl.srcLoc(), msg, "declared here", .{});
13327 try mod.errNoteNonLazy(enum_decl.srcLoc(), msg, "declared here", .{});
1330613328 break :msg msg;
1330713329 };
1330813330 return sema.failWithOwnedErrorMsg(block, msg);
......@@ -13317,6 +13339,7 @@ fn zirTagName(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
1331713339}
1331813340
1331913341fn zirReify(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
13342 const mod = sema.mod;
1332013343 const inst_data = sema.code.instructions.items(.data)[inst].un_node;
1332113344 const src = inst_data.src();
1332213345 const type_info_ty = try sema.resolveBuiltinTypeFields(block, src, "Type");
......@@ -13326,8 +13349,8 @@ fn zirReify(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.I
1332613349 const val = try sema.resolveConstValue(block, operand_src, type_info);
1332713350 const union_val = val.cast(Value.Payload.Union).?.data;
1332813351 const tag_ty = type_info_ty.unionTagType().?;
13329 const target = sema.mod.getTarget();
13330 const tag_index = tag_ty.enumTagFieldIndex(union_val.tag, target).?;
13352 const target = mod.getTarget();
13353 const tag_index = tag_ty.enumTagFieldIndex(union_val.tag, mod).?;
1333113354 switch (@intToEnum(std.builtin.TypeId, tag_index)) {
1333213355 .Type => return Air.Inst.Ref.type_type,
1333313356 .Void => return Air.Inst.Ref.void_type,
......@@ -13406,14 +13429,14 @@ fn zirReify(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.I
1340613429 return sema.fail(block, src, "sentinels are only allowed on slices and unknown-length pointers", .{});
1340713430 }
1340813431 const sentinel_ptr_val = sentinel_val.castTag(.opt_payload).?.data;
13409 const ptr_ty = try Type.ptr(sema.arena, target, .{
13432 const ptr_ty = try Type.ptr(sema.arena, mod, .{
1341013433 .@"addrspace" = .generic,
1341113434 .pointee_type = child_ty,
1341213435 });
1341313436 actual_sentinel = (try sema.pointerDeref(block, src, sentinel_ptr_val, ptr_ty)).?;
1341413437 }
1341513438
13416 const ty = try Type.ptr(sema.arena, target, .{
13439 const ty = try Type.ptr(sema.arena, mod, .{
1341713440 .size = ptr_size,
1341813441 .mutable = !is_const_val.toBool(),
1341913442 .@"volatile" = is_volatile_val.toBool(),
......@@ -13439,14 +13462,14 @@ fn zirReify(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.I
1343913462 var buffer: Value.ToTypeBuffer = undefined;
1344013463 const child_ty = try child_val.toType(&buffer).copy(sema.arena);
1344113464 const sentinel = if (sentinel_val.castTag(.opt_payload)) |p| blk: {
13442 const ptr_ty = try Type.ptr(sema.arena, target, .{
13465 const ptr_ty = try Type.ptr(sema.arena, mod, .{
1344313466 .@"addrspace" = .generic,
1344413467 .pointee_type = child_ty,
1344513468 });
1344613469 break :blk (try sema.pointerDeref(block, src, p.data, ptr_ty)).?;
1344713470 } else null;
1344813471
13449 const ty = try Type.array(sema.arena, len, sentinel, child_ty, target);
13472 const ty = try Type.array(sema.arena, len, sentinel, child_ty, sema.mod);
1345013473 return sema.addType(ty);
1345113474 },
1345213475 .Optional => {
......@@ -13483,8 +13506,9 @@ fn zirReify(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.I
1348313506 const payload_val = union_val.val.optionalValue() orelse
1348413507 return sema.addType(Type.initTag(.anyerror));
1348513508 const slice_val = payload_val.castTag(.slice).?.data;
13486 const decl = slice_val.ptr.pointerDecl().?;
13487 try sema.ensureDeclAnalyzed(decl);
13509 const decl_index = slice_val.ptr.pointerDecl().?;
13510 try sema.ensureDeclAnalyzed(decl_index);
13511 const decl = mod.declPtr(decl_index);
1348813512 const array_val = decl.val.castTag(.aggregate).?.data;
1348913513
1349013514 var names: Module.ErrorSet.NameMap = .{};
......@@ -13494,9 +13518,9 @@ fn zirReify(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.I
1349413518 // TODO use reflection instead of magic numbers here
1349513519 // error_set: type,
1349613520 const name_val = struct_val[0];
13497 const name_str = try name_val.toAllocatedBytes(Type.initTag(.const_slice_u8), sema.arena, target);
13521 const name_str = try name_val.toAllocatedBytes(Type.initTag(.const_slice_u8), sema.arena, sema.mod);
1349813522
13499 const kv = try sema.mod.getErrorValue(name_str);
13523 const kv = try mod.getErrorValue(name_str);
1350013524 names.putAssumeCapacityNoClobber(kv.key, {});
1350113525 }
1350213526
......@@ -13518,7 +13542,7 @@ fn zirReify(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.I
1351813542 const is_tuple_val = struct_val[3];
1351913543
1352013544 // Decls
13521 if (decls_val.sliceLen(target) > 0) {
13545 if (decls_val.sliceLen(mod) > 0) {
1352213546 return sema.fail(block, src, "reified structs must have no decls", .{});
1352313547 }
1352413548
......@@ -13548,11 +13572,10 @@ fn zirReify(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.I
1354813572 }
1354913573
1355013574 // Decls
13551 if (decls_val.sliceLen(target) > 0) {
13575 if (decls_val.sliceLen(mod) > 0) {
1355213576 return sema.fail(block, src, "reified enums must have no decls", .{});
1355313577 }
1355413578
13555 const mod = sema.mod;
1355613579 const gpa = sema.gpa;
1355713580 var new_decl_arena = std.heap.ArenaAllocator.init(gpa);
1355813581 errdefer new_decl_arena.deinit();
......@@ -13572,20 +13595,20 @@ fn zirReify(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.I
1357213595 };
1357313596 const enum_ty = Type.initPayload(&enum_ty_payload.base);
1357413597 const enum_val = try Value.Tag.ty.create(new_decl_arena_allocator, enum_ty);
13575 const type_name = try sema.createTypeName(block, .anon, "enum");
13576 const new_decl = try mod.createAnonymousDeclNamed(block, .{
13598 const new_decl_index = try sema.createAnonymousDeclTypeNamed(block, .{
1357713599 .ty = Type.type,
1357813600 .val = enum_val,
13579 }, type_name);
13601 }, .anon, "enum");
13602 const new_decl = mod.declPtr(new_decl_index);
1358013603 new_decl.owns_tv = true;
13581 errdefer mod.abortAnonDecl(new_decl);
13604 errdefer mod.abortAnonDecl(new_decl_index);
1358213605
1358313606 // Enum tag type
1358413607 var buffer: Value.ToTypeBuffer = undefined;
1358513608 const int_tag_ty = try tag_type_val.toType(&buffer).copy(new_decl_arena_allocator);
1358613609
1358713610 enum_obj.* = .{
13588 .owner_decl = new_decl,
13611 .owner_decl = new_decl_index,
1358913612 .tag_ty = int_tag_ty,
1359013613 .tag_ty_inferred = false,
1359113614 .fields = .{},
......@@ -13599,17 +13622,17 @@ fn zirReify(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.I
1359913622 };
1360013623
1360113624 // Fields
13602 const fields_len = try sema.usizeCast(block, src, fields_val.sliceLen(target));
13625 const fields_len = try sema.usizeCast(block, src, fields_val.sliceLen(mod));
1360313626 if (fields_len > 0) {
1360413627 try enum_obj.fields.ensureTotalCapacity(new_decl_arena_allocator, fields_len);
1360513628 try enum_obj.values.ensureTotalCapacityContext(new_decl_arena_allocator, fields_len, .{
1360613629 .ty = enum_obj.tag_ty,
13607 .target = target,
13630 .mod = mod,
1360813631 });
1360913632
1361013633 var i: usize = 0;
1361113634 while (i < fields_len) : (i += 1) {
13612 const elem_val = try fields_val.elemValue(sema.arena, i);
13635 const elem_val = try fields_val.elemValue(sema.mod, sema.arena, i);
1361313636 const field_struct_val = elem_val.castTag(.aggregate).?.data;
1361413637 // TODO use reflection instead of magic numbers here
1361513638 // name: []const u8
......@@ -13620,7 +13643,7 @@ fn zirReify(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.I
1362013643 const field_name = try name_val.toAllocatedBytes(
1362113644 Type.initTag(.const_slice_u8),
1362213645 new_decl_arena_allocator,
13623 target,
13646 sema.mod,
1362413647 );
1362513648
1362613649 const gop = enum_obj.fields.getOrPutAssumeCapacity(field_name);
......@@ -13632,13 +13655,13 @@ fn zirReify(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.I
1363213655 const copied_tag_val = try value_val.copy(new_decl_arena_allocator);
1363313656 enum_obj.values.putAssumeCapacityNoClobberContext(copied_tag_val, {}, .{
1363413657 .ty = enum_obj.tag_ty,
13635 .target = target,
13658 .mod = mod,
1363613659 });
1363713660 }
1363813661 }
1363913662
1364013663 try new_decl.finalizeNewArena(&new_decl_arena);
13641 return sema.analyzeDeclVal(block, src, new_decl);
13664 return sema.analyzeDeclVal(block, src, new_decl_index);
1364213665 },
1364313666 .Opaque => {
1364413667 const struct_val = union_val.val.castTag(.aggregate).?.data;
......@@ -13646,11 +13669,10 @@ fn zirReify(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.I
1364613669 const decls_val = struct_val[0];
1364713670
1364813671 // Decls
13649 if (decls_val.sliceLen(target) > 0) {
13672 if (decls_val.sliceLen(mod) > 0) {
1365013673 return sema.fail(block, src, "reified opaque must have no decls", .{});
1365113674 }
1365213675
13653 const mod = sema.mod;
1365413676 var new_decl_arena = std.heap.ArenaAllocator.init(sema.gpa);
1365513677 errdefer new_decl_arena.deinit();
1365613678 const new_decl_arena_allocator = new_decl_arena.allocator();
......@@ -13663,16 +13685,16 @@ fn zirReify(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.I
1366313685 };
1366413686 const opaque_ty = Type.initPayload(&opaque_ty_payload.base);
1366513687 const opaque_val = try Value.Tag.ty.create(new_decl_arena_allocator, opaque_ty);
13666 const type_name = try sema.createTypeName(block, .anon, "opaque");
13667 const new_decl = try mod.createAnonymousDeclNamed(block, .{
13688 const new_decl_index = try sema.createAnonymousDeclTypeNamed(block, .{
1366813689 .ty = Type.type,
1366913690 .val = opaque_val,
13670 }, type_name);
13691 }, .anon, "opaque");
13692 const new_decl = mod.declPtr(new_decl_index);
1367113693 new_decl.owns_tv = true;
13672 errdefer mod.abortAnonDecl(new_decl);
13694 errdefer mod.abortAnonDecl(new_decl_index);
1367313695
1367413696 opaque_obj.* = .{
13675 .owner_decl = new_decl,
13697 .owner_decl = new_decl_index,
1367613698 .node_offset = src.node_offset,
1367713699 .namespace = .{
1367813700 .parent = block.namespace,
......@@ -13682,7 +13704,7 @@ fn zirReify(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.I
1368213704 };
1368313705
1368413706 try new_decl.finalizeNewArena(&new_decl_arena);
13685 return sema.analyzeDeclVal(block, src, new_decl);
13707 return sema.analyzeDeclVal(block, src, new_decl_index);
1368613708 },
1368713709 .Union => {
1368813710 // TODO use reflection instead of magic numbers here
......@@ -13697,7 +13719,7 @@ fn zirReify(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.I
1369713719 const decls_val = struct_val[3];
1369813720
1369913721 // Decls
13700 if (decls_val.sliceLen(target) > 0) {
13722 if (decls_val.sliceLen(mod) > 0) {
1370113723 return sema.fail(block, src, "reified unions must have no decls", .{});
1370213724 }
1370313725
......@@ -13714,15 +13736,15 @@ fn zirReify(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.I
1371413736 };
1371513737 const union_ty = Type.initPayload(&union_payload.base);
1371613738 const new_union_val = try Value.Tag.ty.create(new_decl_arena_allocator, union_ty);
13717 const type_name = try sema.createTypeName(block, .anon, "union");
13718 const new_decl = try sema.mod.createAnonymousDeclNamed(block, .{
13739 const new_decl_index = try sema.createAnonymousDeclTypeNamed(block, .{
1371913740 .ty = Type.type,
1372013741 .val = new_union_val,
13721 }, type_name);
13742 }, .anon, "union");
13743 const new_decl = mod.declPtr(new_decl_index);
1372213744 new_decl.owns_tv = true;
13723 errdefer sema.mod.abortAnonDecl(new_decl);
13745 errdefer mod.abortAnonDecl(new_decl_index);
1372413746 union_obj.* = .{
13725 .owner_decl = new_decl,
13747 .owner_decl = new_decl_index,
1372613748 .tag_ty = Type.initTag(.@"null"),
1372713749 .fields = .{},
1372813750 .node_offset = src.node_offset,
......@@ -13737,7 +13759,7 @@ fn zirReify(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.I
1373713759 };
1373813760
1373913761 // Tag type
13740 const fields_len = try sema.usizeCast(block, src, fields_val.sliceLen(target));
13762 const fields_len = try sema.usizeCast(block, src, fields_val.sliceLen(mod));
1374113763 union_obj.tag_ty = if (tag_type_val.optionalValue()) |payload_val| blk: {
1374213764 var buffer: Value.ToTypeBuffer = undefined;
1374313765 break :blk try payload_val.toType(&buffer).copy(new_decl_arena_allocator);
......@@ -13749,7 +13771,7 @@ fn zirReify(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.I
1374913771
1375013772 var i: usize = 0;
1375113773 while (i < fields_len) : (i += 1) {
13752 const elem_val = try fields_val.elemValue(sema.arena, i);
13774 const elem_val = try fields_val.elemValue(sema.mod, sema.arena, i);
1375313775 const field_struct_val = elem_val.castTag(.aggregate).?.data;
1375413776 // TODO use reflection instead of magic numbers here
1375513777 // name: []const u8
......@@ -13762,7 +13784,7 @@ fn zirReify(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.I
1376213784 const field_name = try name_val.toAllocatedBytes(
1376313785 Type.initTag(.const_slice_u8),
1376413786 new_decl_arena_allocator,
13765 target,
13787 sema.mod,
1376613788 );
1376713789
1376813790 const gop = union_obj.fields.getOrPutAssumeCapacity(field_name);
......@@ -13780,7 +13802,7 @@ fn zirReify(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.I
1378013802 }
1378113803
1378213804 try new_decl.finalizeNewArena(&new_decl_arena);
13783 return sema.analyzeDeclVal(block, src, new_decl);
13805 return sema.analyzeDeclVal(block, src, new_decl_index);
1378413806 },
1378513807 .Fn => return sema.fail(block, src, "TODO: Sema.zirReify for Fn", .{}),
1378613808 .BoundFn => @panic("TODO delete BoundFn from the language"),
......@@ -13794,9 +13816,7 @@ fn reifyTuple(
1379413816 src: LazySrcLoc,
1379513817 fields_val: Value,
1379613818) CompileError!Air.Inst.Ref {
13797 const target = sema.mod.getTarget();
13798
13799 const fields_len = try sema.usizeCast(block, src, fields_val.sliceLen(target));
13819 const fields_len = try sema.usizeCast(block, src, fields_val.sliceLen(sema.mod));
1380013820 if (fields_len == 0) return sema.addType(Type.initTag(.empty_struct_literal));
1380113821
1380213822 const types = try sema.arena.alloc(Type, fields_len);
......@@ -13808,7 +13828,7 @@ fn reifyTuple(
1380813828
1380913829 var i: usize = 0;
1381013830 while (i < fields_len) : (i += 1) {
13811 const elem_val = try fields_val.elemValue(sema.arena, i);
13831 const elem_val = try fields_val.elemValue(sema.mod, sema.arena, i);
1381213832 const field_struct_val = elem_val.castTag(.aggregate).?.data;
1381313833 // TODO use reflection instead of magic numbers here
1381413834 // name: []const u8
......@@ -13821,7 +13841,7 @@ fn reifyTuple(
1382113841 const field_name = try name_val.toAllocatedBytes(
1382213842 Type.initTag(.const_slice_u8),
1382313843 sema.arena,
13824 target,
13844 sema.mod,
1382513845 );
1382613846
1382713847 const field_index = std.fmt.parseUnsigned(u32, field_name, 10) catch |err| {
......@@ -13850,7 +13870,7 @@ fn reifyTuple(
1385013870
1385113871 const default_val = if (default_value_val.optionalValue()) |opt_val| blk: {
1385213872 const payload_val = if (opt_val.pointerDecl()) |opt_decl|
13853 opt_decl.val
13873 sema.mod.declPtr(opt_decl).val
1385413874 else
1385513875 opt_val;
1385613876 break :blk try payload_val.copy(sema.arena);
......@@ -13883,15 +13903,16 @@ fn reifyStruct(
1388313903 const struct_obj = try new_decl_arena_allocator.create(Module.Struct);
1388413904 const struct_ty = try Type.Tag.@"struct".create(new_decl_arena_allocator, struct_obj);
1388513905 const new_struct_val = try Value.Tag.ty.create(new_decl_arena_allocator, struct_ty);
13886 const type_name = try sema.createTypeName(block, .anon, "struct");
13887 const new_decl = try sema.mod.createAnonymousDeclNamed(block, .{
13906 const mod = sema.mod;
13907 const new_decl_index = try sema.createAnonymousDeclTypeNamed(block, .{
1388813908 .ty = Type.type,
1388913909 .val = new_struct_val,
13890 }, type_name);
13910 }, .anon, "struct");
13911 const new_decl = mod.declPtr(new_decl_index);
1389113912 new_decl.owns_tv = true;
13892 errdefer sema.mod.abortAnonDecl(new_decl);
13913 errdefer mod.abortAnonDecl(new_decl_index);
1389313914 struct_obj.* = .{
13894 .owner_decl = new_decl,
13915 .owner_decl = new_decl_index,
1389513916 .fields = .{},
1389613917 .node_offset = src.node_offset,
1389713918 .zir_index = inst,
......@@ -13905,14 +13926,14 @@ fn reifyStruct(
1390513926 },
1390613927 };
1390713928
13908 const target = sema.mod.getTarget();
13929 const target = mod.getTarget();
1390913930
1391013931 // Fields
13911 const fields_len = try sema.usizeCast(block, src, fields_val.sliceLen(target));
13932 const fields_len = try sema.usizeCast(block, src, fields_val.sliceLen(mod));
1391213933 try struct_obj.fields.ensureTotalCapacity(new_decl_arena_allocator, fields_len);
1391313934 var i: usize = 0;
1391413935 while (i < fields_len) : (i += 1) {
13915 const elem_val = try fields_val.elemValue(sema.arena, i);
13936 const elem_val = try fields_val.elemValue(sema.mod, sema.arena, i);
1391613937 const field_struct_val = elem_val.castTag(.aggregate).?.data;
1391713938 // TODO use reflection instead of magic numbers here
1391813939 // name: []const u8
......@@ -13929,7 +13950,7 @@ fn reifyStruct(
1392913950 const field_name = try name_val.toAllocatedBytes(
1393013951 Type.initTag(.const_slice_u8),
1393113952 new_decl_arena_allocator,
13932 target,
13953 mod,
1393313954 );
1393413955
1393513956 const gop = struct_obj.fields.getOrPutAssumeCapacity(field_name);
......@@ -13940,7 +13961,7 @@ fn reifyStruct(
1394013961
1394113962 const default_val = if (default_value_val.optionalValue()) |opt_val| blk: {
1394213963 const payload_val = if (opt_val.pointerDecl()) |opt_decl|
13943 opt_decl.val
13964 mod.declPtr(opt_decl).val
1394413965 else
1394513966 opt_val;
1394613967 break :blk try payload_val.copy(new_decl_arena_allocator);
......@@ -13957,7 +13978,7 @@ fn reifyStruct(
1395713978 }
1395813979
1395913980 try new_decl.finalizeNewArena(&new_decl_arena);
13960 return sema.analyzeDeclVal(block, src, new_decl);
13981 return sema.analyzeDeclVal(block, src, new_decl_index);
1396113982}
1396213983
1396313984fn zirTypeName(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
......@@ -13968,8 +13989,7 @@ fn zirTypeName(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1396813989 var anon_decl = try block.startAnonDecl(LazySrcLoc.unneeded);
1396913990 defer anon_decl.deinit();
1397013991
13971 const target = sema.mod.getTarget();
13972 const bytes = try ty.nameAllocArena(anon_decl.arena(), target);
13992 const bytes = try ty.nameAllocArena(anon_decl.arena(), sema.mod);
1397313993
1397413994 const new_decl = try anon_decl.finish(
1397513995 try Type.Tag.array_u8_sentinel_0.create(anon_decl.arena(), bytes.len),
......@@ -14010,7 +14030,7 @@ fn zirFloatToInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
1401014030 error.FloatCannotFit => {
1401114031 return sema.fail(block, operand_src, "integer value {d} cannot be stored in type '{}'", .{
1401214032 std.math.floor(val.toFloat(f64)),
14013 dest_ty.fmt(target),
14033 dest_ty.fmt(sema.mod),
1401414034 });
1401514035 },
1401614036 else => |e| return e,
......@@ -14064,9 +14084,9 @@ fn zirIntToPtr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1406414084 if (try sema.resolveDefinedValue(block, operand_src, operand_coerced)) |val| {
1406514085 const addr = val.toUnsignedInt(target);
1406614086 if (!type_res.isAllowzeroPtr() and addr == 0)
14067 return sema.fail(block, operand_src, "pointer type '{}' does not allow address zero", .{type_res.fmt(target)});
14087 return sema.fail(block, operand_src, "pointer type '{}' does not allow address zero", .{type_res.fmt(sema.mod)});
1406814088 if (addr != 0 and addr % ptr_align != 0)
14069 return sema.fail(block, operand_src, "pointer type '{}' requires aligned address", .{type_res.fmt(target)});
14089 return sema.fail(block, operand_src, "pointer type '{}' requires aligned address", .{type_res.fmt(sema.mod)});
1407014090
1407114091 const val_payload = try sema.arena.create(Value.Payload.U64);
1407214092 val_payload.* = .{
......@@ -14110,7 +14130,6 @@ fn zirErrSetCast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
1411014130 const dest_ty = try sema.resolveType(block, dest_ty_src, extra.lhs);
1411114131 const operand = sema.resolveInst(extra.rhs);
1411214132 const operand_ty = sema.typeOf(operand);
14113 const target = sema.mod.getTarget();
1411414133 try sema.checkErrorSetType(block, dest_ty_src, dest_ty);
1411514134 try sema.checkErrorSetType(block, operand_src, operand_ty);
1411614135
......@@ -14124,7 +14143,7 @@ fn zirErrSetCast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
1412414143 block,
1412514144 src,
1412614145 "error.{s} not a member of error set '{}'",
14127 .{ error_name, dest_ty.fmt(target) },
14146 .{ error_name, dest_ty.fmt(sema.mod) },
1412814147 );
1412914148 }
1413014149 }
......@@ -14178,11 +14197,11 @@ fn zirPtrCast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
1417814197 var buf: Type.Payload.ElemType = undefined;
1417914198 var dest_ptr_info = dest_ty.optionalChild(&buf).ptrInfo().data;
1418014199 dest_ptr_info.@"align" = operand_align;
14181 break :blk try Type.optional(sema.arena, try Type.ptr(sema.arena, target, dest_ptr_info));
14200 break :blk try Type.optional(sema.arena, try Type.ptr(sema.arena, sema.mod, dest_ptr_info));
1418214201 } else {
1418314202 var dest_ptr_info = dest_ty.ptrInfo().data;
1418414203 dest_ptr_info.@"align" = operand_align;
14185 break :blk try Type.ptr(sema.arena, target, dest_ptr_info);
14204 break :blk try Type.ptr(sema.arena, sema.mod, dest_ptr_info);
1418614205 }
1418714206 };
1418814207
......@@ -14235,7 +14254,7 @@ fn zirTruncate(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1423514254
1423614255 if (operand_info.signedness != dest_info.signedness) {
1423714256 return sema.fail(block, operand_src, "expected {s} integer type, found '{}'", .{
14238 @tagName(dest_info.signedness), operand_ty.fmt(target),
14257 @tagName(dest_info.signedness), operand_ty.fmt(sema.mod),
1423914258 });
1424014259 }
1424114260 if (operand_info.bits < dest_info.bits) {
......@@ -14244,7 +14263,7 @@ fn zirTruncate(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1424414263 block,
1424514264 src,
1424614265 "destination type '{}' has more bits than source type '{}'",
14247 .{ dest_ty.fmt(target), operand_ty.fmt(target) },
14266 .{ dest_ty.fmt(sema.mod), operand_ty.fmt(sema.mod) },
1424814267 );
1424914268 errdefer msg.destroy(sema.gpa);
1425014269 try sema.errNote(block, dest_ty_src, msg, "destination type has {d} bits", .{
......@@ -14270,7 +14289,7 @@ fn zirTruncate(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1427014289 var elem_buf: Value.ElemValueBuffer = undefined;
1427114290 const elems = try sema.arena.alloc(Value, operand_ty.vectorLen());
1427214291 for (elems) |*elem, i| {
14273 const elem_val = val.elemValueBuffer(i, &elem_buf);
14292 const elem_val = val.elemValueBuffer(sema.mod, i, &elem_buf);
1427414293 elem.* = try elem_val.intTrunc(operand_scalar_ty, sema.arena, dest_info.signedness, dest_info.bits, target);
1427514294 }
1427614295 return sema.addConstant(
......@@ -14302,8 +14321,7 @@ fn zirAlignCast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
1430214321 // TODO insert safety check that the alignment is correct
1430314322
1430414323 const ptr_info = ptr_ty.ptrInfo().data;
14305 const target = sema.mod.getTarget();
14306 const dest_ty = try Type.ptr(sema.arena, target, .{
14324 const dest_ty = try Type.ptr(sema.arena, sema.mod, .{
1430714325 .pointee_type = ptr_info.pointee_type,
1430814326 .@"align" = dest_align,
1430914327 .@"addrspace" = ptr_info.@"addrspace",
......@@ -14346,7 +14364,7 @@ fn zirBitCount(
1434614364 const elems = try sema.arena.alloc(Value, vec_len);
1434714365 const scalar_ty = operand_ty.scalarType();
1434814366 for (elems) |*elem, i| {
14349 const elem_val = val.elemValueBuffer(i, &elem_buf);
14367 const elem_val = val.elemValueBuffer(sema.mod, i, &elem_buf);
1435014368 const count = comptimeOp(elem_val, scalar_ty, target);
1435114369 elem.* = try Value.Tag.int_u64.create(sema.arena, count);
1435214370 }
......@@ -14386,7 +14404,7 @@ fn zirByteSwap(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1438614404 block,
1438714405 ty_src,
1438814406 "@byteSwap requires the number of bits to be evenly divisible by 8, but {} has {} bits",
14389 .{ scalar_ty.fmt(target), bits },
14407 .{ scalar_ty.fmt(sema.mod), bits },
1439014408 );
1439114409 }
1439214410
......@@ -14414,7 +14432,7 @@ fn zirByteSwap(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1441414432 var elem_buf: Value.ElemValueBuffer = undefined;
1441514433 const elems = try sema.arena.alloc(Value, vec_len);
1441614434 for (elems) |*elem, i| {
14417 const elem_val = val.elemValueBuffer(i, &elem_buf);
14435 const elem_val = val.elemValueBuffer(sema.mod, i, &elem_buf);
1441814436 elem.* = try elem_val.byteSwap(operand_ty, target, sema.arena);
1441914437 }
1442014438 return sema.addConstant(
......@@ -14462,7 +14480,7 @@ fn zirBitReverse(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
1446214480 var elem_buf: Value.ElemValueBuffer = undefined;
1446314481 const elems = try sema.arena.alloc(Value, vec_len);
1446414482 for (elems) |*elem, i| {
14465 const elem_val = val.elemValueBuffer(i, &elem_buf);
14483 const elem_val = val.elemValueBuffer(sema.mod, i, &elem_buf);
1446614484 elem.* = try elem_val.bitReverse(operand_ty, target, sema.arena);
1446714485 }
1446814486 return sema.addConstant(
......@@ -14506,7 +14524,7 @@ fn bitOffsetOf(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!u6
1450614524 block,
1450714525 lhs_src,
1450814526 "expected struct type, found '{}'",
14509 .{ty.fmt(target)},
14527 .{ty.fmt(sema.mod)},
1451014528 );
1451114529 }
1451214530
......@@ -14516,7 +14534,7 @@ fn bitOffsetOf(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!u6
1451614534 block,
1451714535 rhs_src,
1451814536 "struct '{}' has no field '{s}'",
14519 .{ ty.fmt(target), field_name },
14537 .{ ty.fmt(sema.mod), field_name },
1452014538 );
1452114539 };
1452214540
......@@ -14542,20 +14560,18 @@ fn bitOffsetOf(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!u6
1454214560}
1454314561
1454414562fn checkNamespaceType(sema: *Sema, block: *Block, src: LazySrcLoc, ty: Type) CompileError!void {
14545 const target = sema.mod.getTarget();
1454614563 switch (ty.zigTypeTag()) {
1454714564 .Struct, .Enum, .Union, .Opaque => return,
14548 else => return sema.fail(block, src, "expected struct, enum, union, or opaque; found '{}'", .{ty.fmt(target)}),
14565 else => return sema.fail(block, src, "expected struct, enum, union, or opaque; found '{}'", .{ty.fmt(sema.mod)}),
1454914566 }
1455014567}
1455114568
1455214569/// Returns `true` if the type was a comptime_int.
1455314570fn checkIntType(sema: *Sema, block: *Block, src: LazySrcLoc, ty: Type) CompileError!bool {
14554 const target = sema.mod.getTarget();
1455514571 switch (try ty.zigTypeTagOrPoison()) {
1455614572 .ComptimeInt => return true,
1455714573 .Int => return false,
14558 else => return sema.fail(block, src, "expected integer type, found '{}'", .{ty.fmt(target)}),
14574 else => return sema.fail(block, src, "expected integer type, found '{}'", .{ty.fmt(sema.mod)}),
1455914575 }
1456014576}
1456114577
......@@ -14565,7 +14581,6 @@ fn checkPtrOperand(
1456514581 ty_src: LazySrcLoc,
1456614582 ty: Type,
1456714583) CompileError!void {
14568 const target = sema.mod.getTarget();
1456914584 switch (ty.zigTypeTag()) {
1457014585 .Pointer => return,
1457114586 .Fn => {
......@@ -14574,7 +14589,7 @@ fn checkPtrOperand(
1457414589 block,
1457514590 ty_src,
1457614591 "expected pointer, found {}",
14577 .{ty.fmt(target)},
14592 .{ty.fmt(sema.mod)},
1457814593 );
1457914594 errdefer msg.destroy(sema.gpa);
1458014595
......@@ -14587,7 +14602,7 @@ fn checkPtrOperand(
1458714602 .Optional => if (ty.isPtrLikeOptional()) return,
1458814603 else => {},
1458914604 }
14590 return sema.fail(block, ty_src, "expected pointer type, found '{}'", .{ty.fmt(target)});
14605 return sema.fail(block, ty_src, "expected pointer type, found '{}'", .{ty.fmt(sema.mod)});
1459114606}
1459214607
1459314608fn checkPtrType(
......@@ -14596,7 +14611,6 @@ fn checkPtrType(
1459614611 ty_src: LazySrcLoc,
1459714612 ty: Type,
1459814613) CompileError!void {
14599 const target = sema.mod.getTarget();
1460014614 switch (ty.zigTypeTag()) {
1460114615 .Pointer => return,
1460214616 .Fn => {
......@@ -14605,7 +14619,7 @@ fn checkPtrType(
1460514619 block,
1460614620 ty_src,
1460714621 "expected pointer type, found '{}'",
14608 .{ty.fmt(target)},
14622 .{ty.fmt(sema.mod)},
1460914623 );
1461014624 errdefer msg.destroy(sema.gpa);
1461114625
......@@ -14618,7 +14632,7 @@ fn checkPtrType(
1461814632 .Optional => if (ty.isPtrLikeOptional()) return,
1461914633 else => {},
1462014634 }
14621 return sema.fail(block, ty_src, "expected pointer type, found '{}'", .{ty.fmt(target)});
14635 return sema.fail(block, ty_src, "expected pointer type, found '{}'", .{ty.fmt(sema.mod)});
1462214636}
1462314637
1462414638fn checkVectorElemType(
......@@ -14631,8 +14645,7 @@ fn checkVectorElemType(
1463114645 .Int, .Float, .Bool => return,
1463214646 else => if (ty.isPtrAtRuntime()) return,
1463314647 }
14634 const target = sema.mod.getTarget();
14635 return sema.fail(block, ty_src, "expected integer, float, bool, or pointer for the vector element type; found '{}'", .{ty.fmt(target)});
14648 return sema.fail(block, ty_src, "expected integer, float, bool, or pointer for the vector element type; found '{}'", .{ty.fmt(sema.mod)});
1463614649}
1463714650
1463814651fn checkFloatType(
......@@ -14641,10 +14654,9 @@ fn checkFloatType(
1464114654 ty_src: LazySrcLoc,
1464214655 ty: Type,
1464314656) CompileError!void {
14644 const target = sema.mod.getTarget();
1464514657 switch (ty.zigTypeTag()) {
1464614658 .ComptimeInt, .ComptimeFloat, .Float => {},
14647 else => return sema.fail(block, ty_src, "expected float type, found '{}'", .{ty.fmt(target)}),
14659 else => return sema.fail(block, ty_src, "expected float type, found '{}'", .{ty.fmt(sema.mod)}),
1464814660 }
1464914661}
1465014662
......@@ -14654,14 +14666,13 @@ fn checkNumericType(
1465414666 ty_src: LazySrcLoc,
1465514667 ty: Type,
1465614668) CompileError!void {
14657 const target = sema.mod.getTarget();
1465814669 switch (ty.zigTypeTag()) {
1465914670 .ComptimeFloat, .Float, .ComptimeInt, .Int => {},
1466014671 .Vector => switch (ty.childType().zigTypeTag()) {
1466114672 .ComptimeFloat, .Float, .ComptimeInt, .Int => {},
1466214673 else => |t| return sema.fail(block, ty_src, "expected number, found '{}'", .{t}),
1466314674 },
14664 else => return sema.fail(block, ty_src, "expected number, found '{}'", .{ty.fmt(target)}),
14675 else => return sema.fail(block, ty_src, "expected number, found '{}'", .{ty.fmt(sema.mod)}),
1466514676 }
1466614677}
1466714678
......@@ -14697,7 +14708,7 @@ fn checkAtomicOperandType(
1469714708 block,
1469814709 ty_src,
1469914710 "expected bool, integer, float, enum, or pointer type; found {}",
14700 .{ty.fmt(target)},
14711 .{ty.fmt(sema.mod)},
1470114712 );
1470214713 },
1470314714 };
......@@ -14761,7 +14772,6 @@ fn checkIntOrVector(
1476114772 operand_src: LazySrcLoc,
1476214773) CompileError!Type {
1476314774 const operand_ty = sema.typeOf(operand);
14764 const target = sema.mod.getTarget();
1476514775 switch (try operand_ty.zigTypeTagOrPoison()) {
1476614776 .Int => return operand_ty,
1476714777 .Vector => {
......@@ -14769,12 +14779,12 @@ fn checkIntOrVector(
1476914779 switch (try elem_ty.zigTypeTagOrPoison()) {
1477014780 .Int => return elem_ty,
1477114781 else => return sema.fail(block, operand_src, "expected vector of integers; found vector of '{}'", .{
14772 elem_ty.fmt(target),
14782 elem_ty.fmt(sema.mod),
1477314783 }),
1477414784 }
1477514785 },
1477614786 else => return sema.fail(block, operand_src, "expected integer or vector, found '{}'", .{
14777 operand_ty.fmt(target),
14787 operand_ty.fmt(sema.mod),
1477814788 }),
1477914789 }
1478014790}
......@@ -14786,7 +14796,6 @@ fn checkIntOrVectorAllowComptime(
1478614796 operand_src: LazySrcLoc,
1478714797) CompileError!Type {
1478814798 const operand_ty = sema.typeOf(operand);
14789 const target = sema.mod.getTarget();
1479014799 switch (try operand_ty.zigTypeTagOrPoison()) {
1479114800 .Int, .ComptimeInt => return operand_ty,
1479214801 .Vector => {
......@@ -14794,21 +14803,20 @@ fn checkIntOrVectorAllowComptime(
1479414803 switch (try elem_ty.zigTypeTagOrPoison()) {
1479514804 .Int, .ComptimeInt => return elem_ty,
1479614805 else => return sema.fail(block, operand_src, "expected vector of integers; found vector of '{}'", .{
14797 elem_ty.fmt(target),
14806 elem_ty.fmt(sema.mod),
1479814807 }),
1479914808 }
1480014809 },
1480114810 else => return sema.fail(block, operand_src, "expected integer or vector, found '{}'", .{
14802 operand_ty.fmt(target),
14811 operand_ty.fmt(sema.mod),
1480314812 }),
1480414813 }
1480514814}
1480614815
1480714816fn checkErrorSetType(sema: *Sema, block: *Block, src: LazySrcLoc, ty: Type) CompileError!void {
14808 const target = sema.mod.getTarget();
1480914817 switch (ty.zigTypeTag()) {
1481014818 .ErrorSet => return,
14811 else => return sema.fail(block, src, "expected error set type, found '{}'", .{ty.fmt(target)}),
14819 else => return sema.fail(block, src, "expected error set type, found '{}'", .{ty.fmt(sema.mod)}),
1481214820 }
1481314821}
1481414822
......@@ -14892,10 +14900,9 @@ fn checkVectorizableBinaryOperands(
1489214900 return sema.failWithOwnedErrorMsg(block, msg);
1489314901 }
1489414902 } else {
14895 const target = sema.mod.getTarget();
1489614903 const msg = msg: {
1489714904 const msg = try sema.errMsg(block, src, "mixed scalar and vector operands: {} and {}", .{
14898 lhs_ty.fmt(target), rhs_ty.fmt(target),
14905 lhs_ty.fmt(sema.mod), rhs_ty.fmt(sema.mod),
1489914906 });
1490014907 errdefer msg.destroy(sema.gpa);
1490114908 if (lhs_is_vector) {
......@@ -14934,9 +14941,8 @@ fn resolveExportOptions(
1493414941 return sema.fail(block, src, "TODO: implement exporting with linksection", .{});
1493514942 }
1493614943 const name_ty = Type.initTag(.const_slice_u8);
14937 const target = sema.mod.getTarget();
1493814944 return std.builtin.ExportOptions{
14939 .name = try name_val.toAllocatedBytes(name_ty, sema.arena, target),
14945 .name = try name_val.toAllocatedBytes(name_ty, sema.arena, sema.mod),
1494014946 .linkage = linkage_val.toEnum(std.builtin.GlobalLinkage),
1494114947 .section = null, // TODO
1494214948 };
......@@ -14995,13 +15001,12 @@ fn zirCmpxchg(
1499515001 const ptr_ty = sema.typeOf(ptr);
1499615002 const elem_ty = ptr_ty.elemType();
1499715003 try sema.checkAtomicOperandType(block, elem_ty_src, elem_ty);
14998 const target = sema.mod.getTarget();
1499915004 if (elem_ty.zigTypeTag() == .Float) {
1500015005 return sema.fail(
1500115006 block,
1500215007 elem_ty_src,
1500315008 "expected bool, integer, enum, or pointer type; found '{}'",
15004 .{elem_ty.fmt(target)},
15009 .{elem_ty.fmt(sema.mod)},
1500515010 );
1500615011 }
1500715012 const expected_value = try sema.coerce(block, elem_ty, sema.resolveInst(extra.expected_value), expected_src);
......@@ -15038,7 +15043,7 @@ fn zirCmpxchg(
1503815043 return sema.addConstUndef(result_ty);
1503915044 }
1504015045 const stored_val = (try sema.pointerDeref(block, ptr_src, ptr_val, ptr_ty)) orelse break :rs ptr_src;
15041 const result_val = if (stored_val.eql(expected_val, elem_ty, target)) blk: {
15046 const result_val = if (stored_val.eql(expected_val, elem_ty, sema.mod)) blk: {
1504215047 try sema.storePtr(block, src, ptr, new_value);
1504315048 break :blk Value.@"null";
1504415049 } else try Value.Tag.opt_payload.create(sema.arena, stored_val);
......@@ -15103,7 +15108,7 @@ fn zirReduce(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
1510315108 const target = sema.mod.getTarget();
1510415109
1510515110 if (operand_ty.zigTypeTag() != .Vector) {
15106 return sema.fail(block, operand_src, "expected vector, found {}", .{operand_ty.fmt(target)});
15111 return sema.fail(block, operand_src, "expected vector, found {}", .{operand_ty.fmt(sema.mod)});
1510715112 }
1510815113
1510915114 const scalar_ty = operand_ty.childType();
......@@ -15113,13 +15118,13 @@ fn zirReduce(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
1511315118 .And, .Or, .Xor => switch (scalar_ty.zigTypeTag()) {
1511415119 .Int, .Bool => {},
1511515120 else => return sema.fail(block, operand_src, "@reduce operation '{s}' requires integer or boolean operand; found {}", .{
15116 @tagName(operation), operand_ty.fmt(target),
15121 @tagName(operation), operand_ty.fmt(sema.mod),
1511715122 }),
1511815123 },
1511915124 .Min, .Max, .Add, .Mul => switch (scalar_ty.zigTypeTag()) {
1512015125 .Int, .Float => {},
1512115126 else => return sema.fail(block, operand_src, "@reduce operation '{s}' requires integer or float operand; found {}", .{
15122 @tagName(operation), operand_ty.fmt(target),
15127 @tagName(operation), operand_ty.fmt(sema.mod),
1512315128 }),
1512415129 },
1512515130 }
......@@ -15134,11 +15139,11 @@ fn zirReduce(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
1513415139 if (try sema.resolveMaybeUndefVal(block, operand_src, operand)) |operand_val| {
1513515140 if (operand_val.isUndef()) return sema.addConstUndef(scalar_ty);
1513615141
15137 var accum: Value = try operand_val.elemValue(sema.arena, 0);
15142 var accum: Value = try operand_val.elemValue(sema.mod, sema.arena, 0);
1513815143 var elem_buf: Value.ElemValueBuffer = undefined;
1513915144 var i: u32 = 1;
1514015145 while (i < vec_len) : (i += 1) {
15141 const elem_val = operand_val.elemValueBuffer(i, &elem_buf);
15146 const elem_val = operand_val.elemValueBuffer(sema.mod, i, &elem_buf);
1514215147 switch (operation) {
1514315148 .And => accum = try accum.bitwiseAnd(elem_val, scalar_ty, sema.arena, target),
1514415149 .Or => accum = try accum.bitwiseOr(elem_val, scalar_ty, sema.arena, target),
......@@ -15174,11 +15179,10 @@ fn zirShuffle(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
1517415179 var b = sema.resolveInst(extra.b);
1517515180 var mask = sema.resolveInst(extra.mask);
1517615181 var mask_ty = sema.typeOf(mask);
15177 const target = sema.mod.getTarget();
1517815182
1517915183 const mask_len = switch (sema.typeOf(mask).zigTypeTag()) {
1518015184 .Array, .Vector => sema.typeOf(mask).arrayLen(),
15181 else => return sema.fail(block, mask_src, "expected vector or array, found {}", .{sema.typeOf(mask).fmt(target)}),
15185 else => return sema.fail(block, mask_src, "expected vector or array, found {}", .{sema.typeOf(mask).fmt(sema.mod)}),
1518215186 };
1518315187 mask_ty = try Type.Tag.vector.create(sema.arena, .{
1518415188 .len = mask_len,
......@@ -15210,21 +15214,20 @@ fn analyzeShuffle(
1521015214 .elem_type = elem_ty,
1521115215 });
1521215216
15213 const target = sema.mod.getTarget();
1521415217 var maybe_a_len = switch (sema.typeOf(a).zigTypeTag()) {
1521515218 .Array, .Vector => sema.typeOf(a).arrayLen(),
1521615219 .Undefined => null,
1521715220 else => return sema.fail(block, a_src, "expected vector or array with element type {}, found {}", .{
15218 elem_ty.fmt(target),
15219 sema.typeOf(a).fmt(target),
15221 elem_ty.fmt(sema.mod),
15222 sema.typeOf(a).fmt(sema.mod),
1522015223 }),
1522115224 };
1522215225 var maybe_b_len = switch (sema.typeOf(b).zigTypeTag()) {
1522315226 .Array, .Vector => sema.typeOf(b).arrayLen(),
1522415227 .Undefined => null,
1522515228 else => return sema.fail(block, b_src, "expected vector or array with element type {}, found {}", .{
15226 elem_ty.fmt(target),
15227 sema.typeOf(b).fmt(target),
15229 elem_ty.fmt(sema.mod),
15230 sema.typeOf(b).fmt(sema.mod),
1522815231 }),
1522915232 };
1523015233 if (maybe_a_len == null and maybe_b_len == null) {
......@@ -15253,7 +15256,7 @@ fn analyzeShuffle(
1525315256 var i: usize = 0;
1525415257 while (i < mask_len) : (i += 1) {
1525515258 var buf: Value.ElemValueBuffer = undefined;
15256 const elem = mask.elemValueBuffer(i, &buf);
15259 const elem = mask.elemValueBuffer(sema.mod, i, &buf);
1525715260 if (elem.isUndef()) continue;
1525815261 const int = elem.toSignedInt();
1525915262 var unsigned: u32 = undefined;
......@@ -15272,7 +15275,7 @@ fn analyzeShuffle(
1527215275
1527315276 try sema.errNote(block, operand_info[chosen][1], msg, "selected index {d} out of bounds of {}", .{
1527415277 unsigned,
15275 operand_info[chosen][2].fmt(target),
15278 operand_info[chosen][2].fmt(sema.mod),
1527615279 });
1527715280
1527815281 if (chosen == 1) {
......@@ -15292,7 +15295,7 @@ fn analyzeShuffle(
1529215295 i = 0;
1529315296 while (i < mask_len) : (i += 1) {
1529415297 var buf: Value.ElemValueBuffer = undefined;
15295 const mask_elem_val = mask.elemValueBuffer(i, &buf);
15298 const mask_elem_val = mask.elemValueBuffer(sema.mod, i, &buf);
1529615299 if (mask_elem_val.isUndef()) {
1529715300 values[i] = Value.undef;
1529815301 continue;
......@@ -15300,9 +15303,9 @@ fn analyzeShuffle(
1530015303 const int = mask_elem_val.toSignedInt();
1530115304 const unsigned = if (int >= 0) @intCast(u32, int) else @intCast(u32, ~int);
1530215305 if (int >= 0) {
15303 values[i] = try a_val.elemValue(sema.arena, unsigned);
15306 values[i] = try a_val.elemValue(sema.mod, sema.arena, unsigned);
1530415307 } else {
15305 values[i] = try b_val.elemValue(sema.arena, unsigned);
15308 values[i] = try b_val.elemValue(sema.mod, sema.arena, unsigned);
1530615309 }
1530715310 }
1530815311 const res_val = try Value.Tag.aggregate.create(sema.arena, values);
......@@ -15358,7 +15361,6 @@ fn analyzeShuffle(
1535815361fn zirSelect(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
1535915362 const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
1536015363 const extra = sema.code.extraData(Zir.Inst.Select, inst_data.payload_index).data;
15361 const target = sema.mod.getTarget();
1536215364
1536315365 const elem_ty_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
1536415366 const pred_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node };
......@@ -15372,7 +15374,7 @@ fn zirSelect(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
1537215374
1537315375 const vec_len_u64 = switch (try pred_ty.zigTypeTagOrPoison()) {
1537415376 .Vector, .Array => pred_ty.arrayLen(),
15375 else => return sema.fail(block, pred_src, "expected vector or array, found '{}'", .{pred_ty.fmt(target)}),
15377 else => return sema.fail(block, pred_src, "expected vector or array, found '{}'", .{pred_ty.fmt(sema.mod)}),
1537615378 };
1537715379 const vec_len = try sema.usizeCast(block, pred_src, vec_len_u64);
1537815380
......@@ -15399,12 +15401,12 @@ fn zirSelect(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
1539915401 var buf: Value.ElemValueBuffer = undefined;
1540015402 const elems = try sema.gpa.alloc(Value, vec_len);
1540115403 for (elems) |*elem, i| {
15402 const pred_elem_val = pred_val.elemValueBuffer(i, &buf);
15404 const pred_elem_val = pred_val.elemValueBuffer(sema.mod, i, &buf);
1540315405 const should_choose_a = pred_elem_val.toBool();
1540415406 if (should_choose_a) {
15405 elem.* = a_val.elemValueBuffer(i, &buf);
15407 elem.* = a_val.elemValueBuffer(sema.mod, i, &buf);
1540615408 } else {
15407 elem.* = b_val.elemValueBuffer(i, &buf);
15409 elem.* = b_val.elemValueBuffer(sema.mod, i, &buf);
1540815410 }
1540915411 }
1541015412
......@@ -15630,7 +15632,7 @@ fn zirMulAdd(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
1563015632
1563115633 switch (ty.zigTypeTag()) {
1563215634 .ComptimeFloat, .Float, .Vector => {},
15633 else => return sema.fail(block, src, "expected vector of floats or float type, found '{}'", .{ty.fmt(target)}),
15635 else => return sema.fail(block, src, "expected vector of floats or float type, found '{}'", .{ty.fmt(sema.mod)}),
1563415636 }
1563515637
1563615638 const runtime_src = if (maybe_mulend1) |mulend1_val| rs: {
......@@ -15704,10 +15706,9 @@ fn zirBuiltinCall(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
1570415706 break :modifier modifier_val.toEnum(std.builtin.CallOptions.Modifier);
1570515707 };
1570615708
15707 const target = sema.mod.getTarget();
1570815709 const args_ty = sema.typeOf(args);
1570915710 if (!args_ty.isTuple() and args_ty.tag() != .empty_struct_literal) {
15710 return sema.fail(block, args_src, "expected a tuple, found {}", .{args_ty.fmt(target)});
15711 return sema.fail(block, args_src, "expected a tuple, found {}", .{args_ty.fmt(sema.mod)});
1571115712 }
1571215713
1571315714 var resolved_args: []Air.Inst.Ref = undefined;
......@@ -15744,10 +15745,9 @@ fn zirFieldParentPtr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileEr
1574415745 const field_name = try sema.resolveConstString(block, name_src, extra.field_name);
1574515746 const field_ptr = sema.resolveInst(extra.field_ptr);
1574615747 const field_ptr_ty = sema.typeOf(field_ptr);
15747 const target = sema.mod.getTarget();
1574815748
1574915749 if (struct_ty.zigTypeTag() != .Struct) {
15750 return sema.fail(block, ty_src, "expected struct type, found '{}'", .{struct_ty.fmt(target)});
15750 return sema.fail(block, ty_src, "expected struct type, found '{}'", .{struct_ty.fmt(sema.mod)});
1575115751 }
1575215752 try sema.resolveTypeLayout(block, ty_src, struct_ty);
1575315753
......@@ -15756,7 +15756,7 @@ fn zirFieldParentPtr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileEr
1575615756 return sema.failWithBadStructFieldAccess(block, struct_obj, name_src, field_name);
1575715757
1575815758 if (field_ptr_ty.zigTypeTag() != .Pointer) {
15759 return sema.fail(block, ty_src, "expected pointer type, found '{}'", .{field_ptr_ty.fmt(target)});
15759 return sema.fail(block, ty_src, "expected pointer type, found '{}'", .{field_ptr_ty.fmt(sema.mod)});
1576015760 }
1576115761 const field = struct_obj.fields.values()[field_index];
1576215762 const field_ptr_ty_info = field_ptr_ty.ptrInfo().data;
......@@ -15773,11 +15773,11 @@ fn zirFieldParentPtr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileEr
1577315773 ptr_ty_data.@"align" = field.abi_align;
1577415774 }
1577515775
15776 const actual_field_ptr_ty = try Type.ptr(sema.arena, target, ptr_ty_data);
15776 const actual_field_ptr_ty = try Type.ptr(sema.arena, sema.mod, ptr_ty_data);
1577715777 const casted_field_ptr = try sema.coerce(block, actual_field_ptr_ty, field_ptr, ptr_src);
1577815778
1577915779 ptr_ty_data.pointee_type = struct_ty;
15780 const result_ptr = try Type.ptr(sema.arena, target, ptr_ty_data);
15780 const result_ptr = try Type.ptr(sema.arena, sema.mod, ptr_ty_data);
1578115781
1578215782 if (try sema.resolveDefinedValue(block, src, casted_field_ptr)) |field_ptr_val| {
1578315783 const payload = field_ptr_val.castTag(.field_ptr).?.data;
......@@ -15850,8 +15850,8 @@ fn analyzeMinMax(
1585015850 var rhs_buf: Value.ElemValueBuffer = undefined;
1585115851 const elems = try sema.arena.alloc(Value, vec_len);
1585215852 for (elems) |*elem, i| {
15853 const lhs_elem_val = lhs_val.elemValueBuffer(i, &lhs_buf);
15854 const rhs_elem_val = rhs_val.elemValueBuffer(i, &rhs_buf);
15853 const lhs_elem_val = lhs_val.elemValueBuffer(sema.mod, i, &lhs_buf);
15854 const rhs_elem_val = rhs_val.elemValueBuffer(sema.mod, i, &rhs_buf);
1585515855 elem.* = opFunc(lhs_elem_val, rhs_elem_val, target);
1585615856 }
1585715857 return sema.addConstant(
......@@ -15878,18 +15878,17 @@ fn zirMemcpy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void
1587815878 const len_src: LazySrcLoc = .{ .node_offset_builtin_call_arg2 = inst_data.src_node };
1587915879 const dest_ptr = sema.resolveInst(extra.dest);
1588015880 const dest_ptr_ty = sema.typeOf(dest_ptr);
15881 const target = sema.mod.getTarget();
1588215881
1588315882 try sema.checkPtrOperand(block, dest_src, dest_ptr_ty);
1588415883 if (dest_ptr_ty.isConstPtr()) {
15885 return sema.fail(block, dest_src, "cannot store through const pointer '{}'", .{dest_ptr_ty.fmt(target)});
15884 return sema.fail(block, dest_src, "cannot store through const pointer '{}'", .{dest_ptr_ty.fmt(sema.mod)});
1588615885 }
1588715886
1588815887 const uncasted_src_ptr = sema.resolveInst(extra.source);
1588915888 const uncasted_src_ptr_ty = sema.typeOf(uncasted_src_ptr);
1589015889 try sema.checkPtrOperand(block, src_src, uncasted_src_ptr_ty);
1589115890 const src_ptr_info = uncasted_src_ptr_ty.ptrInfo().data;
15892 const wanted_src_ptr_ty = try Type.ptr(sema.arena, target, .{
15891 const wanted_src_ptr_ty = try Type.ptr(sema.arena, sema.mod, .{
1589315892 .pointee_type = dest_ptr_ty.elemType2(),
1589415893 .@"align" = src_ptr_info.@"align",
1589515894 .@"addrspace" = src_ptr_info.@"addrspace",
......@@ -15936,10 +15935,9 @@ fn zirMemset(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void
1593615935 const len_src: LazySrcLoc = .{ .node_offset_builtin_call_arg2 = inst_data.src_node };
1593715936 const dest_ptr = sema.resolveInst(extra.dest);
1593815937 const dest_ptr_ty = sema.typeOf(dest_ptr);
15939 const target = sema.mod.getTarget();
1594015938 try sema.checkPtrOperand(block, dest_src, dest_ptr_ty);
1594115939 if (dest_ptr_ty.isConstPtr()) {
15942 return sema.fail(block, dest_src, "cannot store through const pointer '{}'", .{dest_ptr_ty.fmt(target)});
15940 return sema.fail(block, dest_src, "cannot store through const pointer '{}'", .{dest_ptr_ty.fmt(sema.mod)});
1594315941 }
1594415942 const elem_ty = dest_ptr_ty.elemType2();
1594515943 const value = try sema.coerce(block, elem_ty, sema.resolveInst(extra.byte), value_src);
......@@ -16057,7 +16055,7 @@ fn zirVarExtended(
1605716055 });
1605816056
1605916057 new_var.* = .{
16060 .owner_decl = sema.owner_decl,
16058 .owner_decl = sema.owner_decl_index,
1606116059 .init = init_val,
1606216060 .is_extern = small.is_extern,
1606316061 .is_mutable = true, // TODO get rid of this unused field
......@@ -16294,7 +16292,7 @@ fn zirBuiltinExtern(
1629416292
1629516293 var ty = try sema.resolveType(block, ty_src, extra.lhs);
1629616294 const options_inst = sema.resolveInst(extra.rhs);
16297 const target = sema.mod.getTarget();
16295 const mod = sema.mod;
1629816296
1629916297 const options = options: {
1630016298 const extern_options_ty = try sema.getBuiltinType(block, options_src, "ExternOptions");
......@@ -16315,11 +16313,11 @@ fn zirBuiltinExtern(
1631516313 var library_name: ?[]const u8 = null;
1631616314 if (!library_name_val.isNull()) {
1631716315 const payload = library_name_val.castTag(.opt_payload).?.data;
16318 library_name = try payload.toAllocatedBytes(Type.initTag(.const_slice_u8), sema.arena, target);
16316 library_name = try payload.toAllocatedBytes(Type.initTag(.const_slice_u8), sema.arena, mod);
1631916317 }
1632016318
1632116319 break :options std.builtin.ExternOptions{
16322 .name = try name_val.toAllocatedBytes(Type.initTag(.const_slice_u8), sema.arena, target),
16320 .name = try name_val.toAllocatedBytes(Type.initTag(.const_slice_u8), sema.arena, mod),
1632316321 .library_name = library_name,
1632416322 .linkage = linkage_val.toEnum(std.builtin.GlobalLinkage),
1632516323 .is_thread_local = is_thread_local_val.toBool(),
......@@ -16344,8 +16342,10 @@ fn zirBuiltinExtern(
1634416342
1634516343 // TODO check duplicate extern
1634616344
16347 const new_decl = try sema.mod.allocateNewDecl(try sema.gpa.dupeZ(u8, options.name), sema.owner_decl.src_namespace, sema.owner_decl.src_node, null);
16348 errdefer new_decl.destroy(sema.mod);
16345 const new_decl_index = try mod.allocateNewDecl(sema.owner_decl.src_namespace, sema.owner_decl.src_node, null);
16346 errdefer mod.destroyDecl(new_decl_index);
16347 const new_decl = mod.declPtr(new_decl_index);
16348 new_decl.name = try sema.gpa.dupeZ(u8, options.name);
1634916349
1635016350 var new_decl_arena = std.heap.ArenaAllocator.init(sema.gpa);
1635116351 errdefer new_decl_arena.deinit();
......@@ -16355,7 +16355,7 @@ fn zirBuiltinExtern(
1635516355 errdefer new_decl_arena_allocator.destroy(new_var);
1635616356
1635716357 new_var.* = .{
16358 .owner_decl = sema.owner_decl,
16358 .owner_decl = sema.owner_decl_index,
1635916359 .init = Value.initTag(.unreachable_value),
1636016360 .is_extern = true,
1636116361 .is_mutable = false, // TODO get rid of this unused field
......@@ -16378,13 +16378,13 @@ fn zirBuiltinExtern(
1637816378 new_decl.@"linksection" = null;
1637916379 new_decl.has_tv = true;
1638016380 new_decl.analysis = .complete;
16381 new_decl.generation = sema.mod.generation;
16381 new_decl.generation = mod.generation;
1638216382
1638316383 const arena_state = try new_decl_arena_allocator.create(std.heap.ArenaAllocator.State);
1638416384 arena_state.* = new_decl_arena.state;
1638516385 new_decl.value_arena = arena_state;
1638616386
16387 const ref = try sema.analyzeDeclRef(new_decl);
16387 const ref = try sema.analyzeDeclRef(new_decl_index);
1638816388 try sema.requireRuntimeBlock(block, src);
1638916389 return block.addBitCast(ty, ref);
1639016390}
......@@ -16412,12 +16412,14 @@ fn validateVarType(
1641216412) CompileError!void {
1641316413 if (try sema.validateRunTimeType(block, src, var_ty, is_extern)) return;
1641416414
16415 const target = sema.mod.getTarget();
16415 const mod = sema.mod;
16416
1641616417 const msg = msg: {
16417 const msg = try sema.errMsg(block, src, "variable of type '{}' must be const or comptime", .{var_ty.fmt(target)});
16418 const msg = try sema.errMsg(block, src, "variable of type '{}' must be const or comptime", .{var_ty.fmt(mod)});
1641816419 errdefer msg.destroy(sema.gpa);
1641916420
16420 try sema.explainWhyTypeIsComptime(block, src, msg, src.toSrcLoc(block.src_decl), var_ty);
16421 const src_decl = mod.declPtr(block.src_decl);
16422 try sema.explainWhyTypeIsComptime(block, src, msg, src.toSrcLoc(src_decl), var_ty);
1642116423
1642216424 break :msg msg;
1642316425 };
......@@ -16489,7 +16491,6 @@ fn explainWhyTypeIsComptime(
1648916491 ty: Type,
1649016492) CompileError!void {
1649116493 const mod = sema.mod;
16492 const target = mod.getTarget();
1649316494 switch (ty.zigTypeTag()) {
1649416495 .Bool,
1649516496 .Int,
......@@ -16503,7 +16504,7 @@ fn explainWhyTypeIsComptime(
1650316504
1650416505 .Fn => {
1650516506 try mod.errNoteNonLazy(src_loc, msg, "use '*const {}' for a function pointer type", .{
16506 ty.fmt(target),
16507 ty.fmt(sema.mod),
1650716508 });
1650816509 },
1650916510
......@@ -16534,7 +16535,7 @@ fn explainWhyTypeIsComptime(
1653416535 if (ty.castTag(.@"struct")) |payload| {
1653516536 const struct_obj = payload.data;
1653616537 for (struct_obj.fields.values()) |field, i| {
16537 const field_src_loc = struct_obj.fieldSrcLoc(sema.gpa, .{
16538 const field_src_loc = struct_obj.fieldSrcLoc(sema.mod, .{
1653816539 .index = i,
1653916540 .range = .type,
1654016541 });
......@@ -16551,7 +16552,7 @@ fn explainWhyTypeIsComptime(
1655116552 if (ty.cast(Type.Payload.Union)) |payload| {
1655216553 const union_obj = payload.data;
1655316554 for (union_obj.fields.values()) |field, i| {
16554 const field_src_loc = union_obj.fieldSrcLoc(sema.gpa, .{
16555 const field_src_loc = union_obj.fieldSrcLoc(sema.mod, .{
1655516556 .index = i,
1655616557 .range = .type,
1655716558 });
......@@ -16668,7 +16669,7 @@ fn panicWithMsg(
1666816669 const unresolved_stack_trace_ty = try sema.getBuiltinType(block, src, "StackTrace");
1666916670 const stack_trace_ty = try sema.resolveTypeFields(block, src, unresolved_stack_trace_ty);
1667016671 const target = mod.getTarget();
16671 const ptr_stack_trace_ty = try Type.ptr(arena, target, .{
16672 const ptr_stack_trace_ty = try Type.ptr(arena, mod, .{
1667216673 .pointee_type = stack_trace_ty,
1667316674 .@"addrspace" = target_util.defaultAddressSpace(target, .global_constant), // TODO might need a place that is more dynamic
1667416675 });
......@@ -16748,8 +16749,6 @@ fn fieldVal(
1674816749 else
1674916750 object_ty;
1675016751
16751 const target = sema.mod.getTarget();
16752
1675316752 switch (inner_ty.zigTypeTag()) {
1675416753 .Array => {
1675516754 if (mem.eql(u8, field_name, "len")) {
......@@ -16762,7 +16761,7 @@ fn fieldVal(
1676216761 block,
1676316762 field_name_src,
1676416763 "no member named '{s}' in '{}'",
16765 .{ field_name, object_ty.fmt(target) },
16764 .{ field_name, object_ty.fmt(sema.mod) },
1676616765 );
1676716766 }
1676816767 },
......@@ -16786,7 +16785,7 @@ fn fieldVal(
1678616785 block,
1678716786 field_name_src,
1678816787 "no member named '{s}' in '{}'",
16789 .{ field_name, object_ty.fmt(target) },
16788 .{ field_name, object_ty.fmt(sema.mod) },
1679016789 );
1679116790 }
1679216791 } else if (ptr_info.pointee_type.zigTypeTag() == .Array) {
......@@ -16800,7 +16799,7 @@ fn fieldVal(
1680016799 block,
1680116800 field_name_src,
1680216801 "no member named '{s}' in '{}'",
16803 .{ field_name, ptr_info.pointee_type.fmt(target) },
16802 .{ field_name, ptr_info.pointee_type.fmt(sema.mod) },
1680416803 );
1680516804 }
1680616805 }
......@@ -16822,7 +16821,7 @@ fn fieldVal(
1682216821 break :blk entry.key_ptr.*;
1682316822 }
1682416823 return sema.fail(block, src, "no error named '{s}' in '{}'", .{
16825 field_name, child_type.fmt(target),
16824 field_name, child_type.fmt(sema.mod),
1682616825 });
1682716826 } else (try sema.mod.getErrorValue(field_name)).key;
1682816827
......@@ -16876,10 +16875,10 @@ fn fieldVal(
1687616875 else => unreachable,
1687716876 };
1687816877 return sema.fail(block, src, "{s} '{}' has no member named '{s}'", .{
16879 kw_name, child_type.fmt(target), field_name,
16878 kw_name, child_type.fmt(sema.mod), field_name,
1688016879 });
1688116880 },
16882 else => return sema.fail(block, src, "type '{}' has no members", .{child_type.fmt(target)}),
16881 else => return sema.fail(block, src, "type '{}' has no members", .{child_type.fmt(sema.mod)}),
1688316882 }
1688416883 },
1688516884 .Struct => if (is_pointer_to) {
......@@ -16898,7 +16897,7 @@ fn fieldVal(
1689816897 },
1689916898 else => {},
1690016899 }
16901 return sema.fail(block, src, "type '{}' does not support field access", .{object_ty.fmt(target)});
16900 return sema.fail(block, src, "type '{}' does not support field access", .{object_ty.fmt(sema.mod)});
1690216901}
1690316902
1690416903fn fieldPtr(
......@@ -16912,12 +16911,11 @@ fn fieldPtr(
1691216911 // When editing this function, note that there is corresponding logic to be edited
1691316912 // in `fieldVal`. This function takes a pointer and returns a pointer.
1691416913
16915 const target = sema.mod.getTarget();
1691616914 const object_ptr_src = src; // TODO better source location
1691716915 const object_ptr_ty = sema.typeOf(object_ptr);
1691816916 const object_ty = switch (object_ptr_ty.zigTypeTag()) {
1691916917 .Pointer => object_ptr_ty.elemType(),
16920 else => return sema.fail(block, object_ptr_src, "expected pointer, found '{}'", .{object_ptr_ty.fmt(target)}),
16918 else => return sema.fail(block, object_ptr_src, "expected pointer, found '{}'", .{object_ptr_ty.fmt(sema.mod)}),
1692116919 };
1692216920
1692316921 // Zig allows dereferencing a single pointer during field lookup. Note that
......@@ -16945,7 +16943,7 @@ fn fieldPtr(
1694516943 block,
1694616944 field_name_src,
1694716945 "no member named '{s}' in '{}'",
16948 .{ field_name, object_ty.fmt(target) },
16946 .{ field_name, object_ty.fmt(sema.mod) },
1694916947 );
1695016948 }
1695116949 },
......@@ -16971,7 +16969,7 @@ fn fieldPtr(
1697116969 }
1697216970 try sema.requireRuntimeBlock(block, src);
1697316971
16974 const result_ty = try Type.ptr(sema.arena, target, .{
16972 const result_ty = try Type.ptr(sema.arena, sema.mod, .{
1697516973 .pointee_type = slice_ptr_ty,
1697616974 .mutable = object_ptr_ty.ptrIsMutable(),
1697716975 .@"addrspace" = object_ptr_ty.ptrAddressSpace(),
......@@ -16985,13 +16983,13 @@ fn fieldPtr(
1698516983
1698616984 return sema.analyzeDeclRef(try anon_decl.finish(
1698716985 Type.usize,
16988 try Value.Tag.int_u64.create(anon_decl.arena(), val.sliceLen(target)),
16986 try Value.Tag.int_u64.create(anon_decl.arena(), val.sliceLen(sema.mod)),
1698916987 0, // default alignment
1699016988 ));
1699116989 }
1699216990 try sema.requireRuntimeBlock(block, src);
1699316991
16994 const result_ty = try Type.ptr(sema.arena, target, .{
16992 const result_ty = try Type.ptr(sema.arena, sema.mod, .{
1699516993 .pointee_type = Type.usize,
1699616994 .mutable = object_ptr_ty.ptrIsMutable(),
1699716995 .@"addrspace" = object_ptr_ty.ptrAddressSpace(),
......@@ -17003,7 +17001,7 @@ fn fieldPtr(
1700317001 block,
1700417002 field_name_src,
1700517003 "no member named '{s}' in '{}'",
17006 .{ field_name, object_ty.fmt(target) },
17004 .{ field_name, object_ty.fmt(sema.mod) },
1700717005 );
1700817006 }
1700917007 },
......@@ -17027,7 +17025,7 @@ fn fieldPtr(
1702717025 break :blk entry.key_ptr.*;
1702817026 }
1702917027 return sema.fail(block, src, "no error named '{s}' in '{}'", .{
17030 field_name, child_type.fmt(target),
17028 field_name, child_type.fmt(sema.mod),
1703117029 });
1703217030 } else (try sema.mod.getErrorValue(field_name)).key;
1703317031
......@@ -17085,7 +17083,7 @@ fn fieldPtr(
1708517083 }
1708617084 return sema.failWithBadMemberAccess(block, child_type, field_name_src, field_name);
1708717085 },
17088 else => return sema.fail(block, src, "type '{}' has no members", .{child_type.fmt(target)}),
17086 else => return sema.fail(block, src, "type '{}' has no members", .{child_type.fmt(sema.mod)}),
1708917087 }
1709017088 },
1709117089 .Struct => {
......@@ -17104,7 +17102,7 @@ fn fieldPtr(
1710417102 },
1710517103 else => {},
1710617104 }
17107 return sema.fail(block, src, "type '{}' does not support field access (fieldPtr, {}.{s})", .{ object_ty.fmt(target), object_ptr_ty.fmt(target), field_name });
17105 return sema.fail(block, src, "type '{}' does not support field access (fieldPtr, {}.{s})", .{ object_ty.fmt(sema.mod), object_ptr_ty.fmt(sema.mod), field_name });
1710817106}
1710917107
1711017108fn fieldCallBind(
......@@ -17118,13 +17116,12 @@ fn fieldCallBind(
1711817116 // When editing this function, note that there is corresponding logic to be edited
1711917117 // in `fieldVal`. This function takes a pointer and returns a pointer.
1712017118
17121 const target = sema.mod.getTarget();
1712217119 const raw_ptr_src = src; // TODO better source location
1712317120 const raw_ptr_ty = sema.typeOf(raw_ptr);
1712417121 const inner_ty = if (raw_ptr_ty.zigTypeTag() == .Pointer and raw_ptr_ty.ptrSize() == .One)
1712517122 raw_ptr_ty.childType()
1712617123 else
17127 return sema.fail(block, raw_ptr_src, "expected single pointer, found '{}'", .{raw_ptr_ty.fmt(target)});
17124 return sema.fail(block, raw_ptr_src, "expected single pointer, found '{}'", .{raw_ptr_ty.fmt(sema.mod)});
1712817125
1712917126 // Optionally dereference a second pointer to get the concrete type.
1713017127 const is_double_ptr = inner_ty.zigTypeTag() == .Pointer and inner_ty.ptrSize() == .One;
......@@ -17184,7 +17181,7 @@ fn fieldCallBind(
1718417181 first_param_type.zigTypeTag() == .Pointer and
1718517182 (first_param_type.ptrSize() == .One or
1718617183 first_param_type.ptrSize() == .C) and
17187 first_param_type.childType().eql(concrete_ty, target)))
17184 first_param_type.childType().eql(concrete_ty, sema.mod)))
1718817185 {
1718917186 // zig fmt: on
1719017187 // TODO: bound fn calls on rvalues should probably
......@@ -17195,7 +17192,7 @@ fn fieldCallBind(
1719517192 .arg0_inst = object_ptr,
1719617193 });
1719717194 return sema.addConstant(ty, value);
17198 } else if (first_param_type.eql(concrete_ty, target)) {
17195 } else if (first_param_type.eql(concrete_ty, sema.mod)) {
1719917196 var deref = try sema.analyzeLoad(block, src, object_ptr, src);
1720017197 const ty = Type.Tag.bound_fn.init();
1720117198 const value = try Value.Tag.bound_fn.create(arena, .{
......@@ -17211,7 +17208,7 @@ fn fieldCallBind(
1721117208 else => {},
1721217209 }
1721317210
17214 return sema.fail(block, src, "type '{}' has no field or member function named '{s}'", .{ concrete_ty.fmt(target), field_name });
17211 return sema.fail(block, src, "type '{}' has no field or member function named '{s}'", .{ concrete_ty.fmt(sema.mod), field_name });
1721517212}
1721617213
1721717214fn finishFieldCallBind(
......@@ -17224,8 +17221,7 @@ fn finishFieldCallBind(
1722417221 object_ptr: Air.Inst.Ref,
1722517222) CompileError!Air.Inst.Ref {
1722617223 const arena = sema.arena;
17227 const target = sema.mod.getTarget();
17228 const ptr_field_ty = try Type.ptr(arena, target, .{
17224 const ptr_field_ty = try Type.ptr(arena, sema.mod, .{
1722917225 .pointee_type = field_ty,
1723017226 .mutable = ptr_ty.ptrIsMutable(),
1723117227 .@"addrspace" = ptr_ty.ptrAddressSpace(),
......@@ -17254,9 +17250,10 @@ fn namespaceLookup(
1725417250 src: LazySrcLoc,
1725517251 namespace: *Namespace,
1725617252 decl_name: []const u8,
17257) CompileError!?*Decl {
17253) CompileError!?Decl.Index {
1725817254 const gpa = sema.gpa;
17259 if (try sema.lookupInNamespace(block, src, namespace, decl_name, true)) |decl| {
17255 if (try sema.lookupInNamespace(block, src, namespace, decl_name, true)) |decl_index| {
17256 const decl = sema.mod.declPtr(decl_index);
1726017257 if (!decl.is_pub and decl.getFileScope() != block.getFileScope()) {
1726117258 const msg = msg: {
1726217259 const msg = try sema.errMsg(block, src, "'{s}' is not marked 'pub'", .{
......@@ -17268,7 +17265,7 @@ fn namespaceLookup(
1726817265 };
1726917266 return sema.failWithOwnedErrorMsg(block, msg);
1727017267 }
17271 return decl;
17268 return decl_index;
1727217269 }
1727317270 return null;
1727417271}
......@@ -17377,7 +17374,7 @@ fn structFieldPtrByIndex(
1737717374 ptr_ty_data.@"align" = field.abi_align;
1737817375 }
1737917376
17380 const ptr_field_ty = try Type.ptr(sema.arena, target, ptr_ty_data);
17377 const ptr_field_ty = try Type.ptr(sema.arena, sema.mod, ptr_ty_data);
1738117378
1738217379 if (field.is_comptime) {
1738317380 var anon_decl = try block.startAnonDecl(field_src);
......@@ -17476,15 +17473,14 @@ fn tupleFieldIndex(
1747617473 field_name: []const u8,
1747717474 field_name_src: LazySrcLoc,
1747817475) CompileError!u32 {
17479 const target = sema.mod.getTarget();
1748017476 const field_index = std.fmt.parseUnsigned(u32, field_name, 10) catch |err| {
1748117477 return sema.fail(block, field_name_src, "tuple {} has no such field '{s}': {s}", .{
17482 tuple_ty.fmt(target), field_name, @errorName(err),
17478 tuple_ty.fmt(sema.mod), field_name, @errorName(err),
1748317479 });
1748417480 };
1748517481 if (field_index >= tuple_ty.structFieldCount()) {
1748617482 return sema.fail(block, field_name_src, "tuple {} has no such field '{s}'", .{
17487 tuple_ty.fmt(target), field_name,
17483 tuple_ty.fmt(sema.mod), field_name,
1748817484 });
1748917485 }
1749017486 return field_index;
......@@ -17535,8 +17531,7 @@ fn unionFieldPtr(
1753517531 const union_obj = union_ty.cast(Type.Payload.Union).?.data;
1753617532 const field_index = try sema.unionFieldIndex(block, union_ty, field_name, field_name_src);
1753717533 const field = union_obj.fields.values()[field_index];
17538 const target = sema.mod.getTarget();
17539 const ptr_field_ty = try Type.ptr(arena, target, .{
17534 const ptr_field_ty = try Type.ptr(arena, sema.mod, .{
1754017535 .pointee_type = field.ty,
1754117536 .mutable = union_ptr_ty.ptrIsMutable(),
1754217537 .@"addrspace" = union_ptr_ty.ptrAddressSpace(),
......@@ -17559,7 +17554,7 @@ fn unionFieldPtr(
1755917554 // .data = field_index,
1756017555 //};
1756117556 //const field_tag = Value.initPayload(&field_tag_buf.base);
17562 //const tag_matches = tag_and_val.tag.eql(field_tag, union_obj.tag_ty, target);
17557 //const tag_matches = tag_and_val.tag.eql(field_tag, union_obj.tag_ty, mod);
1756317558 //if (!tag_matches) {
1756417559 // // TODO enhance this saying which one was active
1756517560 // // and which one was accessed, and showing where the union was declared.
......@@ -17608,8 +17603,7 @@ fn unionFieldVal(
1760817603 .data = field_index,
1760917604 };
1761017605 const field_tag = Value.initPayload(&field_tag_buf.base);
17611 const target = sema.mod.getTarget();
17612 const tag_matches = tag_and_val.tag.eql(field_tag, union_obj.tag_ty, target);
17606 const tag_matches = tag_and_val.tag.eql(field_tag, union_obj.tag_ty, sema.mod);
1761317607 switch (union_obj.layout) {
1761417608 .Auto => {
1761517609 if (tag_matches) {
......@@ -17630,7 +17624,7 @@ fn unionFieldVal(
1763017624 if (tag_matches) {
1763117625 return sema.addConstant(field.ty, tag_and_val.val);
1763217626 } else {
17633 const old_ty = union_ty.unionFieldType(tag_and_val.tag, target);
17627 const old_ty = union_ty.unionFieldType(tag_and_val.tag, sema.mod);
1763417628 const new_val = try sema.bitCastVal(block, src, tag_and_val.val, old_ty, field.ty, 0);
1763517629 return sema.addConstant(field.ty, new_val);
1763617630 }
......@@ -17655,17 +17649,17 @@ fn elemPtr(
1765517649 const target = sema.mod.getTarget();
1765617650 const indexable_ty = switch (indexable_ptr_ty.zigTypeTag()) {
1765717651 .Pointer => indexable_ptr_ty.elemType(),
17658 else => return sema.fail(block, indexable_ptr_src, "expected pointer, found '{}'", .{indexable_ptr_ty.fmt(target)}),
17652 else => return sema.fail(block, indexable_ptr_src, "expected pointer, found '{}'", .{indexable_ptr_ty.fmt(sema.mod)}),
1765917653 };
1766017654 if (!indexable_ty.isIndexable()) {
17661 return sema.fail(block, src, "element access of non-indexable type '{}'", .{indexable_ty.fmt(target)});
17655 return sema.fail(block, src, "element access of non-indexable type '{}'", .{indexable_ty.fmt(sema.mod)});
1766217656 }
1766317657
1766417658 switch (indexable_ty.zigTypeTag()) {
1766517659 .Pointer => {
1766617660 // In all below cases, we have to deref the ptr operand to get the actual indexable pointer.
1766717661 const indexable = try sema.analyzeLoad(block, indexable_ptr_src, indexable_ptr, indexable_ptr_src);
17668 const result_ty = try indexable_ty.elemPtrType(sema.arena, target);
17662 const result_ty = try indexable_ty.elemPtrType(sema.arena, sema.mod);
1766917663 switch (indexable_ty.ptrSize()) {
1767017664 .Slice => return sema.elemPtrSlice(block, indexable_ptr_src, indexable, elem_index_src, elem_index),
1767117665 .Many, .C => {
......@@ -17676,7 +17670,7 @@ fn elemPtr(
1767617670 const ptr_val = maybe_ptr_val orelse break :rs indexable_ptr_src;
1767717671 const index_val = maybe_index_val orelse break :rs elem_index_src;
1767817672 const index = @intCast(usize, index_val.toUnsignedInt(target));
17679 const elem_ptr = try ptr_val.elemPtr(indexable_ty, sema.arena, index, target);
17673 const elem_ptr = try ptr_val.elemPtr(indexable_ty, sema.arena, index, sema.mod);
1768017674 return sema.addConstant(result_ty, elem_ptr);
1768117675 };
1768217676
......@@ -17713,7 +17707,7 @@ fn elemVal(
1771317707 const target = sema.mod.getTarget();
1771417708
1771517709 if (!indexable_ty.isIndexable()) {
17716 return sema.fail(block, src, "element access of non-indexable type '{}'", .{indexable_ty.fmt(target)});
17710 return sema.fail(block, src, "element access of non-indexable type '{}'", .{indexable_ty.fmt(sema.mod)});
1771717711 }
1771817712
1771917713 // TODO in case of a vector of pointers, we need to detect whether the element
......@@ -17731,7 +17725,7 @@ fn elemVal(
1773117725 const indexable_val = maybe_indexable_val orelse break :rs indexable_src;
1773217726 const index_val = maybe_index_val orelse break :rs elem_index_src;
1773317727 const index = @intCast(usize, index_val.toUnsignedInt(target));
17734 const elem_ptr_val = try indexable_val.elemPtr(indexable_ty, sema.arena, index, target);
17728 const elem_ptr_val = try indexable_val.elemPtr(indexable_ty, sema.arena, index, sema.mod);
1773517729 if (try sema.pointerDeref(block, indexable_src, elem_ptr_val, indexable_ty)) |elem_val| {
1773617730 return sema.addConstant(indexable_ty.elemType2(), elem_val);
1773717731 }
......@@ -17785,8 +17779,7 @@ fn tupleFieldPtr(
1778517779 }
1778617780
1778717781 const field_ty = tuple_fields.types[field_index];
17788 const target = sema.mod.getTarget();
17789 const ptr_field_ty = try Type.ptr(sema.arena, target, .{
17782 const ptr_field_ty = try Type.ptr(sema.arena, sema.mod, .{
1779017783 .pointee_type = field_ty,
1779117784 .mutable = tuple_ptr_ty.ptrIsMutable(),
1779217785 .@"addrspace" = tuple_ptr_ty.ptrAddressSpace(),
......@@ -17881,7 +17874,7 @@ fn elemValArray(
1788117874 }
1788217875 if (maybe_index_val) |index_val| {
1788317876 const index = @intCast(usize, index_val.toUnsignedInt(target));
17884 const elem_val = try array_val.elemValue(sema.arena, index);
17877 const elem_val = try array_val.elemValue(sema.mod, sema.arena, index);
1788517878 return sema.addConstant(elem_ty, elem_val);
1788617879 }
1788717880 }
......@@ -17914,7 +17907,7 @@ fn elemPtrArray(
1791417907 const array_sent = array_ty.sentinel() != null;
1791517908 const array_len = array_ty.arrayLen();
1791617909 const array_len_s = array_len + @boolToInt(array_sent);
17917 const elem_ptr_ty = try array_ptr_ty.elemPtrType(sema.arena, target);
17910 const elem_ptr_ty = try array_ptr_ty.elemPtrType(sema.arena, sema.mod);
1791817911
1791917912 if (array_len_s == 0) {
1792017913 return sema.fail(block, elem_index_src, "indexing into empty array", .{});
......@@ -17937,7 +17930,7 @@ fn elemPtrArray(
1793717930 }
1793817931 if (maybe_index_val) |index_val| {
1793917932 const index = @intCast(usize, index_val.toUnsignedInt(target));
17940 const elem_ptr = try array_ptr_val.elemPtr(array_ptr_ty, sema.arena, index, target);
17933 const elem_ptr = try array_ptr_val.elemPtr(array_ptr_ty, sema.arena, index, sema.mod);
1794117934 return sema.addConstant(elem_ptr_ty, elem_ptr);
1794217935 }
1794317936 }
......@@ -17977,7 +17970,7 @@ fn elemValSlice(
1797717970
1797817971 if (maybe_slice_val) |slice_val| {
1797917972 runtime_src = elem_index_src;
17980 const slice_len = slice_val.sliceLen(target);
17973 const slice_len = slice_val.sliceLen(sema.mod);
1798117974 const slice_len_s = slice_len + @boolToInt(slice_sent);
1798217975 if (slice_len_s == 0) {
1798317976 return sema.fail(block, elem_index_src, "indexing into empty slice", .{});
......@@ -17988,7 +17981,7 @@ fn elemValSlice(
1798817981 const sentinel_label: []const u8 = if (slice_sent) " +1 (sentinel)" else "";
1798917982 return sema.fail(block, elem_index_src, "index {d} outside slice of length {d}{s}", .{ index, slice_len, sentinel_label });
1799017983 }
17991 const elem_ptr_val = try slice_val.elemPtr(slice_ty, sema.arena, index, target);
17984 const elem_ptr_val = try slice_val.elemPtr(slice_ty, sema.arena, index, sema.mod);
1799217985 if (try sema.pointerDeref(block, slice_src, elem_ptr_val, slice_ty)) |elem_val| {
1799317986 return sema.addConstant(elem_ty, elem_val);
1799417987 }
......@@ -17999,7 +17992,7 @@ fn elemValSlice(
1799917992 try sema.requireRuntimeBlock(block, runtime_src);
1800017993 if (block.wantSafety()) {
1800117994 const len_inst = if (maybe_slice_val) |slice_val|
18002 try sema.addIntUnsigned(Type.usize, slice_val.sliceLen(target))
17995 try sema.addIntUnsigned(Type.usize, slice_val.sliceLen(sema.mod))
1800317996 else
1800417997 try block.addTyOp(.slice_len, Type.usize, slice);
1800517998 const cmp_op: Air.Inst.Tag = if (slice_sent) .cmp_lte else .cmp_lt;
......@@ -18020,7 +18013,7 @@ fn elemPtrSlice(
1802018013 const target = sema.mod.getTarget();
1802118014 const slice_ty = sema.typeOf(slice);
1802218015 const slice_sent = slice_ty.sentinel() != null;
18023 const elem_ptr_ty = try slice_ty.elemPtrType(sema.arena, target);
18016 const elem_ptr_ty = try slice_ty.elemPtrType(sema.arena, sema.mod);
1802418017
1802518018 const maybe_undef_slice_val = try sema.resolveMaybeUndefVal(block, slice_src, slice);
1802618019 // index must be defined since it can index out of bounds
......@@ -18030,7 +18023,7 @@ fn elemPtrSlice(
1803018023 if (slice_val.isUndef()) {
1803118024 return sema.addConstUndef(elem_ptr_ty);
1803218025 }
18033 const slice_len = slice_val.sliceLen(target);
18026 const slice_len = slice_val.sliceLen(sema.mod);
1803418027 const slice_len_s = slice_len + @boolToInt(slice_sent);
1803518028 if (slice_len_s == 0) {
1803618029 return sema.fail(block, elem_index_src, "indexing into empty slice", .{});
......@@ -18041,7 +18034,7 @@ fn elemPtrSlice(
1804118034 const sentinel_label: []const u8 = if (slice_sent) " +1 (sentinel)" else "";
1804218035 return sema.fail(block, elem_index_src, "index {d} outside slice of length {d}{s}", .{ index, slice_len, sentinel_label });
1804318036 }
18044 const elem_ptr_val = try slice_val.elemPtr(slice_ty, sema.arena, index, target);
18037 const elem_ptr_val = try slice_val.elemPtr(slice_ty, sema.arena, index, sema.mod);
1804518038 return sema.addConstant(elem_ptr_ty, elem_ptr_val);
1804618039 }
1804718040 }
......@@ -18052,7 +18045,7 @@ fn elemPtrSlice(
1805218045 const len_inst = len: {
1805318046 if (maybe_undef_slice_val) |slice_val|
1805418047 if (!slice_val.isUndef())
18055 break :len try sema.addIntUnsigned(Type.usize, slice_val.sliceLen(target));
18048 break :len try sema.addIntUnsigned(Type.usize, slice_val.sliceLen(sema.mod));
1805618049 break :len try block.addTyOp(.slice_len, Type.usize, slice);
1805718050 };
1805818051 const cmp_op: Air.Inst.Tag = if (slice_sent) .cmp_lte else .cmp_lt;
......@@ -18079,7 +18072,7 @@ fn coerce(
1807918072 const inst_ty = try sema.resolveTypeFields(block, inst_src, sema.typeOf(inst));
1808018073 const target = sema.mod.getTarget();
1808118074 // If the types are the same, we can return the operand.
18082 if (dest_ty.eql(inst_ty, target))
18075 if (dest_ty.eql(inst_ty, sema.mod))
1808318076 return inst;
1808418077
1808518078 const arena = sema.arena;
......@@ -18185,7 +18178,7 @@ fn coerce(
1818518178 // *[N:s]T to [*]T
1818618179 if (dest_info.sentinel) |dst_sentinel| {
1818718180 if (array_ty.sentinel()) |src_sentinel| {
18188 if (src_sentinel.eql(dst_sentinel, dst_elem_type, target)) {
18181 if (src_sentinel.eql(dst_sentinel, dst_elem_type, sema.mod)) {
1818918182 return sema.coerceCompatiblePtrs(block, dest_ty, inst, inst_src);
1819018183 }
1819118184 }
......@@ -18254,7 +18247,7 @@ fn coerce(
1825418247 }
1825518248 if (inst_info.size == .Slice) {
1825618249 if (dest_info.sentinel == null or inst_info.sentinel == null or
18257 !dest_info.sentinel.?.eql(inst_info.sentinel.?, dest_info.pointee_type, target))
18250 !dest_info.sentinel.?.eql(inst_info.sentinel.?, dest_info.pointee_type, sema.mod))
1825818251 break :p;
1825918252
1826018253 const slice_ptr = try sema.analyzeSlicePtr(block, inst_src, inst, inst_ty);
......@@ -18334,7 +18327,7 @@ fn coerce(
1833418327 }
1833518328
1833618329 if (dest_info.sentinel == null or inst_info.sentinel == null or
18337 !dest_info.sentinel.?.eql(inst_info.sentinel.?, dest_info.pointee_type, target))
18330 !dest_info.sentinel.?.eql(inst_info.sentinel.?, dest_info.pointee_type, sema.mod))
1833818331 break :p;
1833918332
1834018333 const slice_ptr = try sema.analyzeSlicePtr(block, inst_src, inst, inst_ty);
......@@ -18347,11 +18340,16 @@ fn coerce(
1834718340 const val = (try sema.resolveDefinedValue(block, inst_src, inst)) orelse break :float;
1834818341
1834918342 if (val.floatHasFraction()) {
18350 return sema.fail(block, inst_src, "fractional component prevents float value {} from coercion to type '{}'", .{ val.fmtValue(inst_ty, target), dest_ty.fmt(target) });
18343 return sema.fail(
18344 block,
18345 inst_src,
18346 "fractional component prevents float value {} from coercion to type '{}'",
18347 .{ val.fmtValue(inst_ty, sema.mod), dest_ty.fmt(sema.mod) },
18348 );
1835118349 }
1835218350 const result_val = val.floatToInt(sema.arena, inst_ty, dest_ty, target) catch |err| switch (err) {
1835318351 error.FloatCannotFit => {
18354 return sema.fail(block, inst_src, "integer value {d} cannot be stored in type '{}'", .{ std.math.floor(val.toFloat(f64)), dest_ty.fmt(target) });
18352 return sema.fail(block, inst_src, "integer value {d} cannot be stored in type '{}'", .{ std.math.floor(val.toFloat(f64)), dest_ty.fmt(sema.mod) });
1835518353 },
1835618354 else => |e| return e,
1835718355 };
......@@ -18361,7 +18359,7 @@ fn coerce(
1836118359 if (try sema.resolveDefinedValue(block, inst_src, inst)) |val| {
1836218360 // comptime known integer to other number
1836318361 if (!val.intFitsInType(dest_ty, target)) {
18364 return sema.fail(block, inst_src, "type {} cannot represent integer value {}", .{ dest_ty.fmt(target), val.fmtValue(inst_ty, target) });
18362 return sema.fail(block, inst_src, "type {} cannot represent integer value {}", .{ dest_ty.fmt(sema.mod), val.fmtValue(inst_ty, sema.mod) });
1836518363 }
1836618364 return try sema.addConstant(dest_ty, val);
1836718365 }
......@@ -18391,12 +18389,12 @@ fn coerce(
1839118389 .Float => {
1839218390 if (try sema.resolveDefinedValue(block, inst_src, inst)) |val| {
1839318391 const result_val = try val.floatCast(sema.arena, dest_ty, target);
18394 if (!val.eql(result_val, dest_ty, target)) {
18392 if (!val.eql(result_val, dest_ty, sema.mod)) {
1839518393 return sema.fail(
1839618394 block,
1839718395 inst_src,
1839818396 "type {} cannot represent float value {}",
18399 .{ dest_ty.fmt(target), val.fmtValue(inst_ty, target) },
18397 .{ dest_ty.fmt(sema.mod), val.fmtValue(inst_ty, sema.mod) },
1840018398 );
1840118399 }
1840218400 return try sema.addConstant(dest_ty, result_val);
......@@ -18415,12 +18413,12 @@ fn coerce(
1841518413 const result_val = try val.intToFloat(sema.arena, inst_ty, dest_ty, target);
1841618414 // TODO implement this compile error
1841718415 //const int_again_val = try result_val.floatToInt(sema.arena, inst_ty);
18418 //if (!int_again_val.eql(val, inst_ty, target)) {
18416 //if (!int_again_val.eql(val, inst_ty, mod)) {
1841918417 // return sema.fail(
1842018418 // block,
1842118419 // inst_src,
1842218420 // "type {} cannot represent integer value {}",
18423 // .{ dest_ty.fmt(target), val },
18421 // .{ dest_ty.fmt(sema.mod), val },
1842418422 // );
1842518423 //}
1842618424 return try sema.addConstant(dest_ty, result_val);
......@@ -18441,11 +18439,11 @@ fn coerce(
1844118439 block,
1844218440 inst_src,
1844318441 "enum '{}' has no field named '{s}'",
18444 .{ dest_ty.fmt(target), bytes },
18442 .{ dest_ty.fmt(sema.mod), bytes },
1844518443 );
1844618444 errdefer msg.destroy(sema.gpa);
1844718445 try sema.mod.errNoteNonLazy(
18448 dest_ty.declSrcLoc(),
18446 dest_ty.declSrcLoc(sema.mod),
1844918447 msg,
1845018448 "enum declared here",
1845118449 .{},
......@@ -18462,7 +18460,7 @@ fn coerce(
1846218460 .Union => blk: {
1846318461 // union to its own tag type
1846418462 const union_tag_ty = inst_ty.unionTagType() orelse break :blk;
18465 if (union_tag_ty.eql(dest_ty, target)) {
18463 if (union_tag_ty.eql(dest_ty, sema.mod)) {
1846618464 return sema.unionToTag(block, dest_ty, inst, inst_src);
1846718465 }
1846818466 },
......@@ -18557,7 +18555,7 @@ fn coerce(
1855718555 return sema.addConstUndef(dest_ty);
1855818556 }
1855918557
18560 return sema.fail(block, inst_src, "expected {}, found {}", .{ dest_ty.fmt(target), inst_ty.fmt(target) });
18558 return sema.fail(block, inst_src, "expected {}, found {}", .{ dest_ty.fmt(sema.mod), inst_ty.fmt(sema.mod) });
1856118559}
1856218560
1856318561const InMemoryCoercionResult = enum {
......@@ -18586,7 +18584,7 @@ fn coerceInMemoryAllowed(
1858618584 dest_src: LazySrcLoc,
1858718585 src_src: LazySrcLoc,
1858818586) CompileError!InMemoryCoercionResult {
18589 if (dest_ty.eql(src_ty, target))
18587 if (dest_ty.eql(src_ty, sema.mod))
1859018588 return .ok;
1859118589
1859218590 // Differently-named integers with the same number of bits.
......@@ -18650,7 +18648,7 @@ fn coerceInMemoryAllowed(
1865018648 }
1865118649 const ok_sent = dest_info.sentinel == null or
1865218650 (src_info.sentinel != null and
18653 dest_info.sentinel.?.eql(src_info.sentinel.?, dest_info.elem_type, target));
18651 dest_info.sentinel.?.eql(src_info.sentinel.?, dest_info.elem_type, sema.mod));
1865418652 if (!ok_sent) {
1865518653 return .no_match;
1865618654 }
......@@ -18893,7 +18891,7 @@ fn coerceInMemoryAllowedPtrs(
1889318891
1889418892 const ok_sent = dest_info.sentinel == null or src_info.size == .C or
1889518893 (src_info.sentinel != null and
18896 dest_info.sentinel.?.eql(src_info.sentinel.?, dest_info.pointee_type, target));
18894 dest_info.sentinel.?.eql(src_info.sentinel.?, dest_info.pointee_type, sema.mod));
1889718895 if (!ok_sent) {
1889818896 return .no_match;
1889918897 }
......@@ -18934,7 +18932,7 @@ fn coerceInMemoryAllowedPtrs(
1893418932 // resolved and we compare the alignment numerically.
1893518933 alignment: {
1893618934 if (src_info.@"align" == 0 and dest_info.@"align" == 0 and
18937 dest_info.pointee_type.eql(src_info.pointee_type, target))
18935 dest_info.pointee_type.eql(src_info.pointee_type, sema.mod))
1893818936 {
1893918937 break :alignment;
1894018938 }
......@@ -19089,8 +19087,7 @@ fn obtainBitCastedVectorPtr(sema: *Sema, ptr: Air.Inst.Ref) ?Air.Inst.Ref {
1908919087 // We have a pointer-to-array and a pointer-to-vector. If the elements and
1909019088 // lengths match, return the result.
1909119089 const vector_ty = sema.typeOf(prev_ptr).childType();
19092 const target = sema.mod.getTarget();
19093 if (array_ty.childType().eql(vector_ty.childType(), target) and
19090 if (array_ty.childType().eql(vector_ty.childType(), sema.mod) and
1909419091 array_ty.arrayLen() == vector_ty.vectorLen())
1909519092 {
1909619093 return prev_ptr;
......@@ -19114,8 +19111,8 @@ fn storePtrVal(
1911419111
1911519112 const bitcasted_val = try sema.bitCastVal(block, src, operand_val, operand_ty, mut_kit.ty, 0);
1911619113
19117 const arena = mut_kit.beginArena(sema.gpa);
19118 defer mut_kit.finishArena();
19114 const arena = mut_kit.beginArena(sema.mod);
19115 defer mut_kit.finishArena(sema.mod);
1911919116
1912019117 mut_kit.val.* = try bitcasted_val.copy(arena);
1912119118}
......@@ -19126,13 +19123,15 @@ const ComptimePtrMutationKit = struct {
1912619123 ty: Type,
1912719124 decl_arena: std.heap.ArenaAllocator = undefined,
1912819125
19129 fn beginArena(self: *ComptimePtrMutationKit, gpa: Allocator) Allocator {
19130 self.decl_arena = self.decl_ref_mut.decl.value_arena.?.promote(gpa);
19126 fn beginArena(self: *ComptimePtrMutationKit, mod: *Module) Allocator {
19127 const decl = mod.declPtr(self.decl_ref_mut.decl_index);
19128 self.decl_arena = decl.value_arena.?.promote(mod.gpa);
1913119129 return self.decl_arena.allocator();
1913219130 }
1913319131
19134 fn finishArena(self: *ComptimePtrMutationKit) void {
19135 self.decl_ref_mut.decl.value_arena.?.* = self.decl_arena.state;
19132 fn finishArena(self: *ComptimePtrMutationKit, mod: *Module) void {
19133 const decl = mod.declPtr(self.decl_ref_mut.decl_index);
19134 decl.value_arena.?.* = self.decl_arena.state;
1913619135 self.decl_arena = undefined;
1913719136 }
1913819137};
......@@ -19154,10 +19153,11 @@ fn beginComptimePtrMutation(
1915419153 switch (ptr_val.tag()) {
1915519154 .decl_ref_mut => {
1915619155 const decl_ref_mut = ptr_val.castTag(.decl_ref_mut).?.data;
19156 const decl = sema.mod.declPtr(decl_ref_mut.decl_index);
1915719157 return ComptimePtrMutationKit{
1915819158 .decl_ref_mut = decl_ref_mut,
19159 .val = &decl_ref_mut.decl.val,
19160 .ty = decl_ref_mut.decl.ty,
19159 .val = &decl.val,
19160 .ty = decl.ty,
1916119161 };
1916219162 },
1916319163 .elem_ptr => {
......@@ -19178,8 +19178,8 @@ fn beginComptimePtrMutation(
1917819178 // An array has been initialized to undefined at comptime and now we
1917919179 // are for the first time setting an element. We must change the representation
1918019180 // of the array from `undef` to `array`.
19181 const arena = parent.beginArena(sema.gpa);
19182 defer parent.finishArena();
19181 const arena = parent.beginArena(sema.mod);
19182 defer parent.finishArena(sema.mod);
1918319183
1918419184 const array_len_including_sentinel =
1918519185 try sema.usizeCast(block, src, parent.ty.arrayLenIncludingSentinel());
......@@ -19200,8 +19200,8 @@ fn beginComptimePtrMutation(
1920019200 // If we wanted to avoid this, there would need to be special detection
1920119201 // elsewhere to identify when writing a value to an array element that is stored
1920219202 // using the `bytes` tag, and handle it without making a call to this function.
19203 const arena = parent.beginArena(sema.gpa);
19204 defer parent.finishArena();
19203 const arena = parent.beginArena(sema.mod);
19204 defer parent.finishArena(sema.mod);
1920519205
1920619206 const bytes = parent.val.castTag(.bytes).?.data;
1920719207 const dest_len = parent.ty.arrayLenIncludingSentinel();
......@@ -19229,8 +19229,8 @@ fn beginComptimePtrMutation(
1922919229 // need to be special detection elsewhere to identify when writing a value to an
1923019230 // array element that is stored using the `repeated` tag, and handle it
1923119231 // without making a call to this function.
19232 const arena = parent.beginArena(sema.gpa);
19233 defer parent.finishArena();
19232 const arena = parent.beginArena(sema.mod);
19233 defer parent.finishArena(sema.mod);
1923419234
1923519235 const repeated_val = try parent.val.castTag(.repeated).?.data.copy(arena);
1923619236 const array_len_including_sentinel =
......@@ -19281,8 +19281,8 @@ fn beginComptimePtrMutation(
1928119281 // A struct or union has been initialized to undefined at comptime and now we
1928219282 // are for the first time setting a field. We must change the representation
1928319283 // of the struct/union from `undef` to `struct`/`union`.
19284 const arena = parent.beginArena(sema.gpa);
19285 defer parent.finishArena();
19284 const arena = parent.beginArena(sema.mod);
19285 defer parent.finishArena(sema.mod);
1928619286
1928719287 switch (parent.ty.zigTypeTag()) {
1928819288 .Struct => {
......@@ -19322,8 +19322,8 @@ fn beginComptimePtrMutation(
1932219322 },
1932319323 .@"union" => {
1932419324 // We need to set the active field of the union.
19325 const arena = parent.beginArena(sema.gpa);
19326 defer parent.finishArena();
19325 const arena = parent.beginArena(sema.mod);
19326 defer parent.finishArena(sema.mod);
1932719327
1932819328 const payload = &parent.val.castTag(.@"union").?.data;
1932919329 payload.tag = try Value.Tag.enum_field_index.create(arena, field_index);
......@@ -19347,8 +19347,8 @@ fn beginComptimePtrMutation(
1934719347 // An error union has been initialized to undefined at comptime and now we
1934819348 // are for the first time setting the payload. We must change the
1934919349 // representation of the error union from `undef` to `opt_payload`.
19350 const arena = parent.beginArena(sema.gpa);
19351 defer parent.finishArena();
19350 const arena = parent.beginArena(sema.mod);
19351 defer parent.finishArena(sema.mod);
1935219352
1935319353 const payload = try arena.create(Value.Payload.SubValue);
1935419354 payload.* = .{
......@@ -19380,8 +19380,8 @@ fn beginComptimePtrMutation(
1938019380 // An optional has been initialized to undefined at comptime and now we
1938119381 // are for the first time setting the payload. We must change the
1938219382 // representation of the optional from `undef` to `opt_payload`.
19383 const arena = parent.beginArena(sema.gpa);
19384 defer parent.finishArena();
19383 const arena = parent.beginArena(sema.mod);
19384 defer parent.finishArena(sema.mod);
1938519385
1938619386 const payload = try arena.create(Value.Payload.SubValue);
1938719387 payload.* = .{
......@@ -19451,12 +19451,13 @@ fn beginComptimePtrLoad(
1945119451 .decl_ref,
1945219452 .decl_ref_mut,
1945319453 => blk: {
19454 const decl = switch (ptr_val.tag()) {
19454 const decl_index = switch (ptr_val.tag()) {
1945519455 .decl_ref => ptr_val.castTag(.decl_ref).?.data,
19456 .decl_ref_mut => ptr_val.castTag(.decl_ref_mut).?.data.decl,
19456 .decl_ref_mut => ptr_val.castTag(.decl_ref_mut).?.data.decl_index,
1945719457 else => unreachable,
1945819458 };
1945919459 const is_mutable = ptr_val.tag() == .decl_ref_mut;
19460 const decl = sema.mod.declPtr(decl_index);
1946019461 const decl_tv = try decl.typedValue();
1946119462 if (decl_tv.val.tag() == .variable) return error.RuntimeLoad;
1946219463
......@@ -19477,7 +19478,9 @@ fn beginComptimePtrLoad(
1947719478 // This code assumes that elem_ptrs have been "flattened" in order for direct dereference
1947819479 // to succeed, meaning that elem ptrs of the same elem_ty are coalesced. Here we check that
1947919480 // our parent is not an elem_ptr with the same elem_ty, since that would be "unflattened"
19480 if (elem_ptr.array_ptr.castTag(.elem_ptr)) |parent_elem_ptr| assert(!(parent_elem_ptr.data.elem_ty.eql(elem_ty, target)));
19481 if (elem_ptr.array_ptr.castTag(.elem_ptr)) |parent_elem_ptr| {
19482 assert(!(parent_elem_ptr.data.elem_ty.eql(elem_ty, sema.mod)));
19483 }
1948119484
1948219485 if (elem_ptr.index != 0) {
1948319486 if (elem_ty.hasWellDefinedLayout()) {
......@@ -19510,11 +19513,11 @@ fn beginComptimePtrLoad(
1951019513 if (maybe_array_ty) |load_ty| {
1951119514 // It's possible that we're loading a [N]T, in which case we'd like to slice
1951219515 // the pointee array directly from our parent array.
19513 if (load_ty.isArrayOrVector() and load_ty.childType().eql(elem_ty, target)) {
19516 if (load_ty.isArrayOrVector() and load_ty.childType().eql(elem_ty, sema.mod)) {
1951419517 const N = try sema.usizeCast(block, src, load_ty.arrayLenIncludingSentinel());
1951519518 deref.pointee = if (elem_ptr.index + N <= check_len) TypedValue{
19516 .ty = try Type.array(sema.arena, N, null, elem_ty, target),
19517 .val = try array_tv.val.sliceArray(sema.arena, elem_ptr.index, elem_ptr.index + N),
19519 .ty = try Type.array(sema.arena, N, null, elem_ty, sema.mod),
19520 .val = try array_tv.val.sliceArray(sema.mod, sema.arena, elem_ptr.index, elem_ptr.index + N),
1951819521 } else null;
1951919522 break :blk deref;
1952019523 }
......@@ -19522,7 +19525,7 @@ fn beginComptimePtrLoad(
1952219525
1952319526 deref.pointee = if (elem_ptr.index < check_len) TypedValue{
1952419527 .ty = elem_ty,
19525 .val = try array_tv.val.elemValue(sema.arena, elem_ptr.index),
19528 .val = try array_tv.val.elemValue(sema.mod, sema.arena, elem_ptr.index),
1952619529 } else null;
1952719530 break :blk deref;
1952819531 },
......@@ -19637,9 +19640,9 @@ fn bitCast(
1963719640
1963819641 if (old_bits != dest_bits) {
1963919642 return sema.fail(block, inst_src, "@bitCast size mismatch: destination type '{}' has {d} bits but source type '{}' has {d} bits", .{
19640 dest_ty.fmt(target),
19643 dest_ty.fmt(sema.mod),
1964119644 dest_bits,
19642 old_ty.fmt(target),
19645 old_ty.fmt(sema.mod),
1964319646 old_bits,
1964419647 });
1964519648 }
......@@ -19662,7 +19665,7 @@ pub fn bitCastVal(
1966219665 buffer_offset: usize,
1966319666) !Value {
1966419667 const target = sema.mod.getTarget();
19665 if (old_ty.eql(new_ty, target)) return val;
19668 if (old_ty.eql(new_ty, sema.mod)) return val;
1966619669
1966719670 // For types with well-defined memory layouts, we serialize them a byte buffer,
1966819671 // then deserialize to the new type.
......@@ -19718,12 +19721,11 @@ fn coerceEnumToUnion(
1971819721 inst_src: LazySrcLoc,
1971919722) !Air.Inst.Ref {
1972019723 const inst_ty = sema.typeOf(inst);
19721 const target = sema.mod.getTarget();
1972219724
1972319725 const tag_ty = union_ty.unionTagType() orelse {
1972419726 const msg = msg: {
1972519727 const msg = try sema.errMsg(block, inst_src, "expected {}, found {}", .{
19726 union_ty.fmt(target), inst_ty.fmt(target),
19728 union_ty.fmt(sema.mod), inst_ty.fmt(sema.mod),
1972719729 });
1972819730 errdefer msg.destroy(sema.gpa);
1972919731 try sema.errNote(block, union_ty_src, msg, "cannot coerce enum to untagged union", .{});
......@@ -19736,10 +19738,10 @@ fn coerceEnumToUnion(
1973619738 const enum_tag = try sema.coerce(block, tag_ty, inst, inst_src);
1973719739 if (try sema.resolveDefinedValue(block, inst_src, enum_tag)) |val| {
1973819740 const union_obj = union_ty.cast(Type.Payload.Union).?.data;
19739 const field_index = union_obj.tag_ty.enumTagFieldIndex(val, target) orelse {
19741 const field_index = union_obj.tag_ty.enumTagFieldIndex(val, sema.mod) orelse {
1974019742 const msg = msg: {
1974119743 const msg = try sema.errMsg(block, inst_src, "union {} has no tag with value {}", .{
19742 union_ty.fmt(target), val.fmtValue(tag_ty, target),
19744 union_ty.fmt(sema.mod), val.fmtValue(tag_ty, sema.mod),
1974319745 });
1974419746 errdefer msg.destroy(sema.gpa);
1974519747 try sema.addDeclaredHereNote(msg, union_ty);
......@@ -19753,7 +19755,7 @@ fn coerceEnumToUnion(
1975319755 const msg = msg: {
1975419756 const field_name = union_obj.fields.keys()[field_index];
1975519757 const msg = try sema.errMsg(block, inst_src, "coercion from enum '{}' to union '{}' must initialize '{}' field '{s}'", .{
19756 inst_ty.fmt(target), union_ty.fmt(target), field_ty.fmt(target), field_name,
19758 inst_ty.fmt(sema.mod), union_ty.fmt(sema.mod), field_ty.fmt(sema.mod), field_name,
1975719759 });
1975819760 errdefer msg.destroy(sema.gpa);
1975919761
......@@ -19775,7 +19777,7 @@ fn coerceEnumToUnion(
1977519777 if (tag_ty.isNonexhaustiveEnum()) {
1977619778 const msg = msg: {
1977719779 const msg = try sema.errMsg(block, inst_src, "runtime coercion to union {} from non-exhaustive enum", .{
19778 union_ty.fmt(target),
19780 union_ty.fmt(sema.mod),
1977919781 });
1978019782 errdefer msg.destroy(sema.gpa);
1978119783 try sema.addDeclaredHereNote(msg, tag_ty);
......@@ -19795,7 +19797,7 @@ fn coerceEnumToUnion(
1979519797 block,
1979619798 inst_src,
1979719799 "runtime coercion from enum '{}' to union '{}' which has non-void fields",
19798 .{ tag_ty.fmt(target), union_ty.fmt(target) },
19800 .{ tag_ty.fmt(sema.mod), union_ty.fmt(sema.mod) },
1979919801 );
1980019802 errdefer msg.destroy(sema.gpa);
1980119803
......@@ -19804,7 +19806,7 @@ fn coerceEnumToUnion(
1980419806 while (it.next()) |field| {
1980519807 const field_name = field.key_ptr.*;
1980619808 const field_ty = field.value_ptr.ty;
19807 try sema.addFieldErrNote(block, union_ty, field_index, msg, "field '{s}' has type '{}'", .{ field_name, field_ty.fmt(target) });
19809 try sema.addFieldErrNote(block, union_ty, field_index, msg, "field '{s}' has type '{}'", .{ field_name, field_ty.fmt(sema.mod) });
1980819810 field_index += 1;
1980919811 }
1981019812 try sema.addDeclaredHereNote(msg, union_ty);
......@@ -19892,7 +19894,7 @@ fn coerceArrayLike(
1989219894 if (dest_len != inst_len) {
1989319895 const msg = msg: {
1989419896 const msg = try sema.errMsg(block, inst_src, "expected {}, found {}", .{
19895 dest_ty.fmt(target), inst_ty.fmt(target),
19897 dest_ty.fmt(sema.mod), inst_ty.fmt(sema.mod),
1989619898 });
1989719899 errdefer msg.destroy(sema.gpa);
1989819900 try sema.errNote(block, dest_ty_src, msg, "destination has length {d}", .{dest_len});
......@@ -19959,12 +19961,11 @@ fn coerceTupleToArray(
1995919961 const inst_ty = sema.typeOf(inst);
1996019962 const inst_len = inst_ty.arrayLen();
1996119963 const dest_len = try sema.usizeCast(block, dest_ty_src, dest_ty.arrayLen());
19962 const target = sema.mod.getTarget();
1996319964
1996419965 if (dest_len != inst_len) {
1996519966 const msg = msg: {
1996619967 const msg = try sema.errMsg(block, inst_src, "expected {}, found {}", .{
19967 dest_ty.fmt(target), inst_ty.fmt(target),
19968 dest_ty.fmt(sema.mod), inst_ty.fmt(sema.mod),
1996819969 });
1996919970 errdefer msg.destroy(sema.gpa);
1997019971 try sema.errNote(block, dest_ty_src, msg, "destination has length {d}", .{dest_len});
......@@ -20017,8 +20018,7 @@ fn coerceTupleToSlicePtrs(
2001720018 const tuple_ty = sema.typeOf(ptr_tuple).childType();
2001820019 const tuple = try sema.analyzeLoad(block, tuple_src, ptr_tuple, tuple_src);
2001920020 const slice_info = slice_ty.ptrInfo().data;
20020 const target = sema.mod.getTarget();
20021 const array_ty = try Type.array(sema.arena, tuple_ty.structFieldCount(), slice_info.sentinel, slice_info.pointee_type, target);
20021 const array_ty = try Type.array(sema.arena, tuple_ty.structFieldCount(), slice_info.sentinel, slice_info.pointee_type, sema.mod);
2002220022 const array_inst = try sema.coerceTupleToArray(block, array_ty, slice_ty_src, tuple, tuple_src);
2002320023 if (slice_info.@"align" != 0) {
2002420024 return sema.fail(block, slice_ty_src, "TODO: override the alignment of the array decl we create here", .{});
......@@ -20141,23 +20141,23 @@ fn analyzeDeclVal(
2014120141 sema: *Sema,
2014220142 block: *Block,
2014320143 src: LazySrcLoc,
20144 decl: *Decl,
20144 decl_index: Decl.Index,
2014520145) CompileError!Air.Inst.Ref {
20146 if (sema.decl_val_table.get(decl)) |result| {
20146 if (sema.decl_val_table.get(decl_index)) |result| {
2014720147 return result;
2014820148 }
20149 const decl_ref = try sema.analyzeDeclRef(decl);
20149 const decl_ref = try sema.analyzeDeclRef(decl_index);
2015020150 const result = try sema.analyzeLoad(block, src, decl_ref, src);
2015120151 if (Air.refToIndex(result)) |index| {
2015220152 if (sema.air_instructions.items(.tag)[index] == .constant) {
20153 try sema.decl_val_table.put(sema.gpa, decl, result);
20153 try sema.decl_val_table.put(sema.gpa, decl_index, result);
2015420154 }
2015520155 }
2015620156 return result;
2015720157}
2015820158
20159fn ensureDeclAnalyzed(sema: *Sema, decl: *Decl) CompileError!void {
20160 sema.mod.ensureDeclAnalyzed(decl) catch |err| {
20159fn ensureDeclAnalyzed(sema: *Sema, decl_index: Decl.Index) CompileError!void {
20160 sema.mod.ensureDeclAnalyzed(decl_index) catch |err| {
2016120161 if (sema.owner_func) |owner_func| {
2016220162 owner_func.state = .dependency_failure;
2016320163 } else {
......@@ -20186,7 +20186,7 @@ fn refValue(sema: *Sema, block: *Block, src: LazySrcLoc, ty: Type, val: Value) !
2018620186 try val.copy(anon_decl.arena()),
2018720187 0, // default alignment
2018820188 );
20189 try sema.mod.declareDeclDependency(sema.owner_decl, decl);
20189 try sema.mod.declareDeclDependency(sema.owner_decl_index, decl);
2019020190 return try Value.Tag.decl_ref.create(sema.arena, decl);
2019120191}
2019220192
......@@ -20197,29 +20197,29 @@ fn optRefValue(sema: *Sema, block: *Block, src: LazySrcLoc, ty: Type, opt_val: ?
2019720197 return result;
2019820198}
2019920199
20200fn analyzeDeclRef(sema: *Sema, decl: *Decl) CompileError!Air.Inst.Ref {
20201 try sema.mod.declareDeclDependency(sema.owner_decl, decl);
20202 try sema.ensureDeclAnalyzed(decl);
20200fn analyzeDeclRef(sema: *Sema, decl_index: Decl.Index) CompileError!Air.Inst.Ref {
20201 try sema.mod.declareDeclDependency(sema.owner_decl_index, decl_index);
20202 try sema.ensureDeclAnalyzed(decl_index);
2020320203
20204 const target = sema.mod.getTarget();
20204 const decl = sema.mod.declPtr(decl_index);
2020520205 const decl_tv = try decl.typedValue();
2020620206 if (decl_tv.val.castTag(.variable)) |payload| {
2020720207 const variable = payload.data;
20208 const ty = try Type.ptr(sema.arena, target, .{
20208 const ty = try Type.ptr(sema.arena, sema.mod, .{
2020920209 .pointee_type = decl_tv.ty,
2021020210 .mutable = variable.is_mutable,
2021120211 .@"addrspace" = decl.@"addrspace",
2021220212 .@"align" = decl.@"align",
2021320213 });
20214 return sema.addConstant(ty, try Value.Tag.decl_ref.create(sema.arena, decl));
20214 return sema.addConstant(ty, try Value.Tag.decl_ref.create(sema.arena, decl_index));
2021520215 }
2021620216 return sema.addConstant(
20217 try Type.ptr(sema.arena, target, .{
20217 try Type.ptr(sema.arena, sema.mod, .{
2021820218 .pointee_type = decl_tv.ty,
2021920219 .mutable = false,
2022020220 .@"addrspace" = decl.@"addrspace",
2022120221 }),
20222 try Value.Tag.decl_ref.create(sema.arena, decl),
20222 try Value.Tag.decl_ref.create(sema.arena, decl_index),
2022320223 );
2022420224}
2022520225
......@@ -20243,13 +20243,12 @@ fn analyzeRef(
2024320243
2024420244 try sema.requireRuntimeBlock(block, src);
2024520245 const address_space = target_util.defaultAddressSpace(sema.mod.getTarget(), .local);
20246 const target = sema.mod.getTarget();
20247 const ptr_type = try Type.ptr(sema.arena, target, .{
20246 const ptr_type = try Type.ptr(sema.arena, sema.mod, .{
2024820247 .pointee_type = operand_ty,
2024920248 .mutable = false,
2025020249 .@"addrspace" = address_space,
2025120250 });
20252 const mut_ptr_type = try Type.ptr(sema.arena, target, .{
20251 const mut_ptr_type = try Type.ptr(sema.arena, sema.mod, .{
2025320252 .pointee_type = operand_ty,
2025420253 .@"addrspace" = address_space,
2025520254 });
......@@ -20267,11 +20266,10 @@ fn analyzeLoad(
2026720266 ptr: Air.Inst.Ref,
2026820267 ptr_src: LazySrcLoc,
2026920268) CompileError!Air.Inst.Ref {
20270 const target = sema.mod.getTarget();
2027120269 const ptr_ty = sema.typeOf(ptr);
2027220270 const elem_ty = switch (ptr_ty.zigTypeTag()) {
2027320271 .Pointer => ptr_ty.childType(),
20274 else => return sema.fail(block, ptr_src, "expected pointer, found '{}'", .{ptr_ty.fmt(target)}),
20272 else => return sema.fail(block, ptr_src, "expected pointer, found '{}'", .{ptr_ty.fmt(sema.mod)}),
2027520273 };
2027620274 if (try sema.resolveDefinedValue(block, ptr_src, ptr)) |ptr_val| {
2027720275 if (try sema.pointerDeref(block, ptr_src, ptr_val, ptr_ty)) |elem_val| {
......@@ -20310,8 +20308,7 @@ fn analyzeSliceLen(
2031020308 if (slice_val.isUndef()) {
2031120309 return sema.addConstUndef(Type.usize);
2031220310 }
20313 const target = sema.mod.getTarget();
20314 return sema.addIntUnsigned(Type.usize, slice_val.sliceLen(target));
20311 return sema.addIntUnsigned(Type.usize, slice_val.sliceLen(sema.mod));
2031520312 }
2031620313 try sema.requireRuntimeBlock(block, src);
2031720314 return block.addTyOp(.slice_len, Type.usize, slice_inst);
......@@ -20417,8 +20414,9 @@ fn analyzeSlice(
2041720414 const target = sema.mod.getTarget();
2041820415 const ptr_ptr_child_ty = switch (ptr_ptr_ty.zigTypeTag()) {
2041920416 .Pointer => ptr_ptr_ty.elemType(),
20420 else => return sema.fail(block, ptr_src, "expected pointer, found '{}'", .{ptr_ptr_ty.fmt(target)}),
20417 else => return sema.fail(block, ptr_src, "expected pointer, found '{}'", .{ptr_ptr_ty.fmt(sema.mod)}),
2042120418 };
20419 const mod = sema.mod;
2042220420
2042320421 var array_ty = ptr_ptr_child_ty;
2042420422 var slice_ty = ptr_ptr_ty;
......@@ -20465,7 +20463,7 @@ fn analyzeSlice(
2046520463 elem_ty = ptr_ptr_child_ty.childType();
2046620464 },
2046720465 },
20468 else => return sema.fail(block, ptr_src, "slice of non-array type '{}'", .{ptr_ptr_child_ty.fmt(target)}),
20466 else => return sema.fail(block, ptr_src, "slice of non-array type '{}'", .{ptr_ptr_child_ty.fmt(mod)}),
2046920467 }
2047020468
2047120469 const ptr = if (slice_ty.isSlice())
......@@ -20492,7 +20490,7 @@ fn analyzeSlice(
2049220490 sema.arena,
2049320491 array_ty.arrayLenIncludingSentinel(),
2049420492 );
20495 if (end_val.compare(.gt, len_s_val, Type.usize, target)) {
20493 if (end_val.compare(.gt, len_s_val, Type.usize, mod)) {
2049620494 const sentinel_label: []const u8 = if (array_ty.sentinel() != null)
2049720495 " +1 (sentinel)"
2049820496 else
......@@ -20503,8 +20501,8 @@ fn analyzeSlice(
2050320501 end_src,
2050420502 "end index {} out of bounds for array of length {}{s}",
2050520503 .{
20506 end_val.fmtValue(Type.usize, target),
20507 len_val.fmtValue(Type.usize, target),
20504 end_val.fmtValue(Type.usize, mod),
20505 len_val.fmtValue(Type.usize, mod),
2050820506 sentinel_label,
2050920507 },
2051020508 );
......@@ -20513,7 +20511,7 @@ fn analyzeSlice(
2051320511 // end_is_len is only true if we are NOT using the sentinel
2051420512 // length. For sentinel-length, we don't want the type to
2051520513 // contain the sentinel.
20516 if (end_val.eql(len_val, Type.usize, target)) {
20514 if (end_val.eql(len_val, Type.usize, mod)) {
2051720515 end_is_len = true;
2051820516 }
2051920517 }
......@@ -20529,10 +20527,10 @@ fn analyzeSlice(
2052920527 const has_sentinel = slice_ty.sentinel() != null;
2053020528 var int_payload: Value.Payload.U64 = .{
2053120529 .base = .{ .tag = .int_u64 },
20532 .data = slice_val.sliceLen(target) + @boolToInt(has_sentinel),
20530 .data = slice_val.sliceLen(mod) + @boolToInt(has_sentinel),
2053320531 };
2053420532 const slice_len_val = Value.initPayload(&int_payload.base);
20535 if (end_val.compare(.gt, slice_len_val, Type.usize, target)) {
20533 if (end_val.compare(.gt, slice_len_val, Type.usize, mod)) {
2053620534 const sentinel_label: []const u8 = if (has_sentinel)
2053720535 " +1 (sentinel)"
2053820536 else
......@@ -20543,8 +20541,8 @@ fn analyzeSlice(
2054320541 end_src,
2054420542 "end index {} out of bounds for slice of length {d}{s}",
2054520543 .{
20546 end_val.fmtValue(Type.usize, target),
20547 slice_val.sliceLen(target),
20544 end_val.fmtValue(Type.usize, mod),
20545 slice_val.sliceLen(mod),
2054820546 sentinel_label,
2054920547 },
2055020548 );
......@@ -20557,7 +20555,7 @@ fn analyzeSlice(
2055720555 int_payload.data -= 1;
2055820556 }
2055920557
20560 if (end_val.eql(slice_len_val, Type.usize, target)) {
20558 if (end_val.eql(slice_len_val, Type.usize, mod)) {
2056120559 end_is_len = true;
2056220560 }
2056320561 }
......@@ -20590,14 +20588,14 @@ fn analyzeSlice(
2059020588 // requirement: start <= end
2059120589 if (try sema.resolveDefinedValue(block, src, end)) |end_val| {
2059220590 if (try sema.resolveDefinedValue(block, src, start)) |start_val| {
20593 if (start_val.compare(.gt, end_val, Type.usize, target)) {
20591 if (start_val.compare(.gt, end_val, Type.usize, mod)) {
2059420592 return sema.fail(
2059520593 block,
2059620594 start_src,
2059720595 "start index {} is larger than end index {}",
2059820596 .{
20599 start_val.fmtValue(Type.usize, target),
20600 end_val.fmtValue(Type.usize, target),
20597 start_val.fmtValue(Type.usize, mod),
20598 end_val.fmtValue(Type.usize, mod),
2060120599 },
2060220600 );
2060320601 }
......@@ -20613,8 +20611,8 @@ fn analyzeSlice(
2061320611 if (opt_new_len_val) |new_len_val| {
2061420612 const new_len_int = new_len_val.toUnsignedInt(target);
2061520613
20616 const return_ty = try Type.ptr(sema.arena, target, .{
20617 .pointee_type = try Type.array(sema.arena, new_len_int, sentinel, elem_ty, target),
20614 const return_ty = try Type.ptr(sema.arena, mod, .{
20615 .pointee_type = try Type.array(sema.arena, new_len_int, sentinel, elem_ty, mod),
2061820616 .sentinel = null,
2061920617 .@"align" = new_ptr_ty_info.@"align",
2062020618 .@"addrspace" = new_ptr_ty_info.@"addrspace",
......@@ -20641,7 +20639,7 @@ fn analyzeSlice(
2064120639 return sema.fail(block, ptr_src, "non-zero length slice of undefined pointer", .{});
2064220640 }
2064320641
20644 const return_ty = try Type.ptr(sema.arena, target, .{
20642 const return_ty = try Type.ptr(sema.arena, mod, .{
2064520643 .pointee_type = elem_ty,
2064620644 .sentinel = sentinel,
2064720645 .@"align" = new_ptr_ty_info.@"align",
......@@ -20667,7 +20665,7 @@ fn analyzeSlice(
2066720665 if (try sema.resolveDefinedValue(block, src, ptr_or_slice)) |slice_val| {
2066820666 // we don't need to add one for sentinels because the
2066920667 // underlying value data includes the sentinel
20670 break :blk try sema.addIntUnsigned(Type.usize, slice_val.sliceLen(target));
20668 break :blk try sema.addIntUnsigned(Type.usize, slice_val.sliceLen(mod));
2067120669 }
2067220670
2067320671 const slice_len_inst = try block.addTyOp(.slice_len, Type.usize, ptr_or_slice);
......@@ -20920,7 +20918,6 @@ fn cmpVector(
2092020918 try sema.checkVectorizableBinaryOperands(block, src, lhs_ty, rhs_ty, lhs_src, rhs_src);
2092120919
2092220920 const result_ty = try Type.vector(sema.arena, lhs_ty.vectorLen(), Type.@"bool");
20923 const target = sema.mod.getTarget();
2092420921
2092520922 const runtime_src: LazySrcLoc = src: {
2092620923 if (try sema.resolveMaybeUndefVal(block, lhs_src, lhs)) |lhs_val| {
......@@ -20928,7 +20925,7 @@ fn cmpVector(
2092820925 if (lhs_val.isUndef() or rhs_val.isUndef()) {
2092920926 return sema.addConstUndef(result_ty);
2093020927 }
20931 const cmp_val = try lhs_val.compareVector(op, rhs_val, lhs_ty, sema.arena, target);
20928 const cmp_val = try lhs_val.compareVector(op, rhs_val, lhs_ty, sema.arena, sema.mod);
2093220929 return sema.addConstant(result_ty, cmp_val);
2093320930 } else {
2093420931 break :src rhs_src;
......@@ -21080,7 +21077,7 @@ fn resolvePeerTypes(
2108021077 const candidate_ty_tag = try candidate_ty.zigTypeTagOrPoison();
2108121078 const chosen_ty_tag = try chosen_ty.zigTypeTagOrPoison();
2108221079
21083 if (candidate_ty.eql(chosen_ty, target))
21080 if (candidate_ty.eql(chosen_ty, sema.mod))
2108421081 continue;
2108521082
2108621083 switch (candidate_ty_tag) {
......@@ -21496,27 +21493,27 @@ fn resolvePeerTypes(
2149621493 // the source locations.
2149721494 const chosen_src = candidate_srcs.resolve(
2149821495 sema.gpa,
21499 block.src_decl,
21496 sema.mod.declPtr(block.src_decl),
2150021497 chosen_i,
2150121498 );
2150221499 const candidate_src = candidate_srcs.resolve(
2150321500 sema.gpa,
21504 block.src_decl,
21501 sema.mod.declPtr(block.src_decl),
2150521502 candidate_i + 1,
2150621503 );
2150721504
2150821505 const msg = msg: {
2150921506 const msg = try sema.errMsg(block, src, "incompatible types: '{}' and '{}'", .{
21510 chosen_ty.fmt(target),
21511 candidate_ty.fmt(target),
21507 chosen_ty.fmt(sema.mod),
21508 candidate_ty.fmt(sema.mod),
2151221509 });
2151321510 errdefer msg.destroy(sema.gpa);
2151421511
2151521512 if (chosen_src) |src_loc|
21516 try sema.errNote(block, src_loc, msg, "type '{}' here", .{chosen_ty.fmt(target)});
21513 try sema.errNote(block, src_loc, msg, "type '{}' here", .{chosen_ty.fmt(sema.mod)});
2151721514
2151821515 if (candidate_src) |src_loc|
21519 try sema.errNote(block, src_loc, msg, "type '{}' here", .{candidate_ty.fmt(target)});
21516 try sema.errNote(block, src_loc, msg, "type '{}' here", .{candidate_ty.fmt(sema.mod)});
2152021517
2152121518 break :msg msg;
2152221519 };
......@@ -21538,13 +21535,13 @@ fn resolvePeerTypes(
2153821535 else => unreachable,
2153921536 };
2154021537
21541 const new_ptr_ty = try Type.ptr(sema.arena, target, info.data);
21538 const new_ptr_ty = try Type.ptr(sema.arena, sema.mod, info.data);
2154221539 const opt_ptr_ty = if (any_are_null)
2154321540 try Type.optional(sema.arena, new_ptr_ty)
2154421541 else
2154521542 new_ptr_ty;
2154621543 const set_ty = err_set_ty orelse return opt_ptr_ty;
21547 return try Type.errorUnion(sema.arena, set_ty, opt_ptr_ty, target);
21544 return try Type.errorUnion(sema.arena, set_ty, opt_ptr_ty, sema.mod);
2154821545 }
2154921546
2155021547 if (seen_const) {
......@@ -21554,24 +21551,24 @@ fn resolvePeerTypes(
2155421551 const ptr_ty = chosen_ty.errorUnionPayload();
2155521552 var info = ptr_ty.ptrInfo();
2155621553 info.data.mutable = false;
21557 const new_ptr_ty = try Type.ptr(sema.arena, target, info.data);
21554 const new_ptr_ty = try Type.ptr(sema.arena, sema.mod, info.data);
2155821555 const opt_ptr_ty = if (any_are_null)
2155921556 try Type.optional(sema.arena, new_ptr_ty)
2156021557 else
2156121558 new_ptr_ty;
2156221559 const set_ty = err_set_ty orelse chosen_ty.errorUnionSet();
21563 return try Type.errorUnion(sema.arena, set_ty, opt_ptr_ty, target);
21560 return try Type.errorUnion(sema.arena, set_ty, opt_ptr_ty, sema.mod);
2156421561 },
2156521562 .Pointer => {
2156621563 var info = chosen_ty.ptrInfo();
2156721564 info.data.mutable = false;
21568 const new_ptr_ty = try Type.ptr(sema.arena, target, info.data);
21565 const new_ptr_ty = try Type.ptr(sema.arena, sema.mod, info.data);
2156921566 const opt_ptr_ty = if (any_are_null)
2157021567 try Type.optional(sema.arena, new_ptr_ty)
2157121568 else
2157221569 new_ptr_ty;
2157321570 const set_ty = err_set_ty orelse return opt_ptr_ty;
21574 return try Type.errorUnion(sema.arena, set_ty, opt_ptr_ty, target);
21571 return try Type.errorUnion(sema.arena, set_ty, opt_ptr_ty, sema.mod);
2157521572 },
2157621573 else => return chosen_ty,
2157721574 }
......@@ -21583,16 +21580,16 @@ fn resolvePeerTypes(
2158321580 else => try Type.optional(sema.arena, chosen_ty),
2158421581 };
2158521582 const set_ty = err_set_ty orelse return opt_ty;
21586 return try Type.errorUnion(sema.arena, set_ty, opt_ty, target);
21583 return try Type.errorUnion(sema.arena, set_ty, opt_ty, sema.mod);
2158721584 }
2158821585
2158921586 if (err_set_ty) |ty| switch (chosen_ty.zigTypeTag()) {
2159021587 .ErrorSet => return ty,
2159121588 .ErrorUnion => {
2159221589 const payload_ty = chosen_ty.errorUnionPayload();
21593 return try Type.errorUnion(sema.arena, ty, payload_ty, target);
21590 return try Type.errorUnion(sema.arena, ty, payload_ty, sema.mod);
2159421591 },
21595 else => return try Type.errorUnion(sema.arena, ty, chosen_ty, target),
21592 else => return try Type.errorUnion(sema.arena, ty, chosen_ty, sema.mod),
2159621593 };
2159721594
2159821595 return chosen_ty;
......@@ -21670,12 +21667,11 @@ fn resolveStructLayout(
2167021667) CompileError!void {
2167121668 const resolved_ty = try sema.resolveTypeFields(block, src, ty);
2167221669 if (resolved_ty.castTag(.@"struct")) |payload| {
21673 const target = sema.mod.getTarget();
2167421670 const struct_obj = payload.data;
2167521671 switch (struct_obj.status) {
2167621672 .none, .have_field_types => {},
2167721673 .field_types_wip, .layout_wip => {
21678 return sema.fail(block, src, "struct {} depends on itself", .{ty.fmt(target)});
21674 return sema.fail(block, src, "struct {} depends on itself", .{ty.fmt(sema.mod)});
2167921675 },
2168021676 .have_layout, .fully_resolved_wip, .fully_resolved => return,
2168121677 }
......@@ -21703,11 +21699,10 @@ fn resolveUnionLayout(
2170321699) CompileError!void {
2170421700 const resolved_ty = try sema.resolveTypeFields(block, src, ty);
2170521701 const union_obj = resolved_ty.cast(Type.Payload.Union).?.data;
21706 const target = sema.mod.getTarget();
2170721702 switch (union_obj.status) {
2170821703 .none, .have_field_types => {},
2170921704 .field_types_wip, .layout_wip => {
21710 return sema.fail(block, src, "union {} depends on itself", .{ty.fmt(target)});
21705 return sema.fail(block, src, "union {} depends on itself", .{ty.fmt(sema.mod)});
2171121706 },
2171221707 .have_layout, .fully_resolved_wip, .fully_resolved => return,
2171321708 }
......@@ -21774,10 +21769,6 @@ fn resolveStructFully(
2177421769 .fully_resolved_wip, .fully_resolved => return,
2177521770 }
2177621771
21777 log.debug("resolveStructFully {*} ('{s}')", .{
21778 struct_obj.owner_decl, struct_obj.owner_decl.name,
21779 });
21780
2178121772 {
2178221773 // After we have resolve struct layout we have to go over the fields again to
2178321774 // make sure pointer fields get their child types resolved as well.
......@@ -21866,11 +21857,10 @@ fn resolveTypeFieldsStruct(
2186621857 ty: Type,
2186721858 struct_obj: *Module.Struct,
2186821859) CompileError!void {
21869 const target = sema.mod.getTarget();
2187021860 switch (struct_obj.status) {
2187121861 .none => {},
2187221862 .field_types_wip => {
21873 return sema.fail(block, src, "struct {} depends on itself", .{ty.fmt(target)});
21863 return sema.fail(block, src, "struct {} depends on itself", .{ty.fmt(sema.mod)});
2187421864 },
2187521865 .have_field_types,
2187621866 .have_layout,
......@@ -21897,11 +21887,10 @@ fn resolveTypeFieldsUnion(
2189721887 ty: Type,
2189821888 union_obj: *Module.Union,
2189921889) CompileError!void {
21900 const target = sema.mod.getTarget();
2190121890 switch (union_obj.status) {
2190221891 .none => {},
2190321892 .field_types_wip => {
21904 return sema.fail(block, src, "union {} depends on itself", .{ty.fmt(target)});
21893 return sema.fail(block, src, "union {} depends on itself", .{ty.fmt(sema.mod)});
2190521894 },
2190621895 .have_field_types,
2190721896 .have_layout,
......@@ -21945,7 +21934,8 @@ fn resolveInferredErrorSet(
2194521934 // `*Module.Fn`. Not only is the function not relevant to the inferred error set
2194621935 // in this case, it may be a generic function which would cause an assertion failure
2194721936 // if we called `ensureFuncBodyAnalyzed` on it here.
21948 if (ies.func.owner_decl.ty.fnInfo().return_type.errorUnionSet().castTag(.error_set_inferred).?.data == ies) {
21937 const ies_func_owner_decl = sema.mod.declPtr(ies.func.owner_decl);
21938 if (ies_func_owner_decl.ty.fnInfo().return_type.errorUnionSet().castTag(.error_set_inferred).?.data == ies) {
2194921939 // In this case we are dealing with the actual InferredErrorSet object that
2195021940 // corresponds to the function, not one created to track an inline/comptime call.
2195121941 try sema.ensureFuncBodyAnalyzed(ies.func);
......@@ -21986,7 +21976,7 @@ fn semaStructFields(
2198621976 defer tracy.end();
2198721977
2198821978 const gpa = mod.gpa;
21989 const decl = struct_obj.owner_decl;
21979 const decl_index = struct_obj.owner_decl;
2199021980 const zir = struct_obj.namespace.file_scope.zir;
2199121981 const extended = zir.instructions.items(.data)[struct_obj.zir_index].extended;
2199221982 assert(extended.opcode == .struct_decl);
......@@ -22026,6 +22016,7 @@ fn semaStructFields(
2202622016 }
2202722017 extra_index += body.len;
2202822018
22019 const decl = mod.declPtr(decl_index);
2202922020 var decl_arena = decl.value_arena.?.promote(gpa);
2203022021 defer decl.value_arena.?.* = decl_arena.state;
2203122022 const decl_arena_allocator = decl_arena.allocator();
......@@ -22040,6 +22031,7 @@ fn semaStructFields(
2204022031 .perm_arena = decl_arena_allocator,
2204122032 .code = zir,
2204222033 .owner_decl = decl,
22034 .owner_decl_index = decl_index,
2204322035 .func = null,
2204422036 .fn_ret_ty = Type.void,
2204522037 .owner_func = null,
......@@ -22052,7 +22044,7 @@ fn semaStructFields(
2205222044 var block_scope: Block = .{
2205322045 .parent = null,
2205422046 .sema = &sema,
22055 .src_decl = decl,
22047 .src_decl = decl_index,
2205622048 .namespace = &struct_obj.namespace,
2205722049 .wip_capture_scope = wip_captures.scope,
2205822050 .instructions = .{},
......@@ -22171,7 +22163,7 @@ fn semaUnionFields(block: *Block, mod: *Module, union_obj: *Module.Union) Compil
2217122163 defer tracy.end();
2217222164
2217322165 const gpa = mod.gpa;
22174 const decl = union_obj.owner_decl;
22166 const decl_index = union_obj.owner_decl;
2217522167 const zir = union_obj.namespace.file_scope.zir;
2217622168 const extended = zir.instructions.items(.data)[union_obj.zir_index].extended;
2217722169 assert(extended.opcode == .union_decl);
......@@ -22217,8 +22209,10 @@ fn semaUnionFields(block: *Block, mod: *Module, union_obj: *Module.Union) Compil
2221722209 }
2221822210 extra_index += body.len;
2221922211
22220 var decl_arena = union_obj.owner_decl.value_arena.?.promote(gpa);
22221 defer union_obj.owner_decl.value_arena.?.* = decl_arena.state;
22212 const decl = mod.declPtr(decl_index);
22213
22214 var decl_arena = decl.value_arena.?.promote(gpa);
22215 defer decl.value_arena.?.* = decl_arena.state;
2222222216 const decl_arena_allocator = decl_arena.allocator();
2222322217
2222422218 var analysis_arena = std.heap.ArenaAllocator.init(gpa);
......@@ -22231,6 +22225,7 @@ fn semaUnionFields(block: *Block, mod: *Module, union_obj: *Module.Union) Compil
2223122225 .perm_arena = decl_arena_allocator,
2223222226 .code = zir,
2223322227 .owner_decl = decl,
22228 .owner_decl_index = decl_index,
2223422229 .func = null,
2223522230 .fn_ret_ty = Type.void,
2223622231 .owner_func = null,
......@@ -22243,7 +22238,7 @@ fn semaUnionFields(block: *Block, mod: *Module, union_obj: *Module.Union) Compil
2224322238 var block_scope: Block = .{
2224422239 .parent = null,
2224522240 .sema = &sema,
22246 .src_decl = decl,
22241 .src_decl = decl_index,
2224722242 .namespace = &union_obj.namespace,
2224822243 .wip_capture_scope = wip_captures.scope,
2224922244 .instructions = .{},
......@@ -22353,7 +22348,7 @@ fn semaUnionFields(block: *Block, mod: *Module, union_obj: *Module.Union) Compil
2235322348 const copied_val = try val.copy(decl_arena_allocator);
2235422349 map.putAssumeCapacityContext(copied_val, {}, .{
2235522350 .ty = int_tag_ty,
22356 .target = target,
22351 .mod = mod,
2235722352 });
2235822353 } else {
2235922354 const val = if (last_tag_val) |val|
......@@ -22365,7 +22360,7 @@ fn semaUnionFields(block: *Block, mod: *Module, union_obj: *Module.Union) Compil
2236522360 const copied_val = try val.copy(decl_arena_allocator);
2236622361 map.putAssumeCapacityContext(copied_val, {}, .{
2236722362 .ty = int_tag_ty,
22368 .target = target,
22363 .mod = mod,
2236922364 });
2237022365 }
2237122366 }
......@@ -22411,7 +22406,7 @@ fn semaUnionFields(block: *Block, mod: *Module, union_obj: *Module.Union) Compil
2241122406 const enum_has_field = names.orderedRemove(field_name);
2241222407 if (!enum_has_field) {
2241322408 const msg = msg: {
22414 const msg = try sema.errMsg(block, src, "enum '{}' has no field named '{s}'", .{ union_obj.tag_ty.fmt(target), field_name });
22409 const msg = try sema.errMsg(block, src, "enum '{}' has no field named '{s}'", .{ union_obj.tag_ty.fmt(sema.mod), field_name });
2241522410 errdefer msg.destroy(sema.gpa);
2241622411 try sema.addDeclaredHereNote(msg, union_obj.tag_ty);
2241722412 break :msg msg;
......@@ -22475,15 +22470,16 @@ fn generateUnionTagTypeNumbered(
2247522470 const enum_ty = Type.initPayload(&enum_ty_payload.base);
2247622471 const enum_val = try Value.Tag.ty.create(new_decl_arena_allocator, enum_ty);
2247722472 // TODO better type name
22478 const new_decl = try mod.createAnonymousDecl(block, .{
22473 const new_decl_index = try mod.createAnonymousDecl(block, .{
2247922474 .ty = Type.type,
2248022475 .val = enum_val,
2248122476 });
22477 const new_decl = mod.declPtr(new_decl_index);
2248222478 new_decl.owns_tv = true;
22483 errdefer mod.abortAnonDecl(new_decl);
22479 errdefer mod.abortAnonDecl(new_decl_index);
2248422480
2248522481 enum_obj.* = .{
22486 .owner_decl = new_decl,
22482 .owner_decl = new_decl_index,
2248722483 .tag_ty = int_ty,
2248822484 .fields = .{},
2248922485 .values = .{},
......@@ -22493,7 +22489,7 @@ fn generateUnionTagTypeNumbered(
2249322489 try enum_obj.fields.ensureTotalCapacity(new_decl_arena_allocator, fields_len);
2249422490 try enum_obj.values.ensureTotalCapacityContext(new_decl_arena_allocator, fields_len, .{
2249522491 .ty = int_ty,
22496 .target = sema.mod.getTarget(),
22492 .mod = mod,
2249722493 });
2249822494 try new_decl.finalizeNewArena(&new_decl_arena);
2249922495 return enum_ty;
......@@ -22515,15 +22511,16 @@ fn generateUnionTagTypeSimple(sema: *Sema, block: *Block, fields_len: usize) !Ty
2251522511 const enum_ty = Type.initPayload(&enum_ty_payload.base);
2251622512 const enum_val = try Value.Tag.ty.create(new_decl_arena_allocator, enum_ty);
2251722513 // TODO better type name
22518 const new_decl = try mod.createAnonymousDecl(block, .{
22514 const new_decl_index = try mod.createAnonymousDecl(block, .{
2251922515 .ty = Type.type,
2252022516 .val = enum_val,
2252122517 });
22518 const new_decl = mod.declPtr(new_decl_index);
2252222519 new_decl.owns_tv = true;
22523 errdefer mod.abortAnonDecl(new_decl);
22520 errdefer mod.abortAnonDecl(new_decl_index);
2252422521
2252522522 enum_obj.* = .{
22526 .owner_decl = new_decl,
22523 .owner_decl = new_decl_index,
2252722524 .fields = .{},
2252822525 .node_offset = 0,
2252922526 };
......@@ -22545,7 +22542,7 @@ fn getBuiltin(
2254522542 const opt_builtin_inst = try sema.namespaceLookupRef(
2254622543 block,
2254722544 src,
22548 std_file.root_decl.?.src_namespace,
22545 mod.declPtr(std_file.root_decl.unwrap().?).src_namespace,
2254922546 "builtin",
2255022547 );
2255122548 const builtin_inst = try sema.analyzeLoad(block, src, opt_builtin_inst.?, src);
......@@ -22984,8 +22981,7 @@ fn analyzeComptimeAlloc(
2298422981 // Needed to make an anon decl with type `var_type` (the `finish()` call below).
2298522982 _ = try sema.typeHasOnePossibleValue(block, src, var_type);
2298622983
22987 const target = sema.mod.getTarget();
22988 const ptr_type = try Type.ptr(sema.arena, target, .{
22984 const ptr_type = try Type.ptr(sema.arena, sema.mod, .{
2298922985 .pointee_type = var_type,
2299022986 .@"addrspace" = target_util.defaultAddressSpace(sema.mod.getTarget(), .global_constant),
2299122987 .@"align" = alignment,
......@@ -22994,7 +22990,7 @@ fn analyzeComptimeAlloc(
2299422990 var anon_decl = try block.startAnonDecl(src);
2299522991 defer anon_decl.deinit();
2299622992
22997 const decl = try anon_decl.finish(
22993 const decl_index = try anon_decl.finish(
2299822994 try var_type.copy(anon_decl.arena()),
2299922995 // There will be stores before the first load, but they may be to sub-elements or
2300022996 // sub-fields. So we need to initialize with undef to allow the mechanism to expand
......@@ -23002,12 +22998,13 @@ fn analyzeComptimeAlloc(
2300222998 Value.undef,
2300322999 alignment,
2300423000 );
23001 const decl = sema.mod.declPtr(decl_index);
2300523002 decl.@"align" = alignment;
2300623003
23007 try sema.mod.declareDeclDependency(sema.owner_decl, decl);
23004 try sema.mod.declareDeclDependency(sema.owner_decl_index, decl_index);
2300823005 return sema.addConstant(ptr_type, try Value.Tag.decl_ref_mut.create(sema.arena, .{
2300923006 .runtime_index = block.runtime_index,
23010 .decl = decl,
23007 .decl_index = decl_index,
2301123008 }));
2301223009}
2301323010
......@@ -23099,7 +23096,7 @@ fn pointerDeref(sema: *Sema, block: *Block, src: LazySrcLoc, ptr_val: Value, ptr
2309923096 // The type is not in-memory coercible or the direct dereference failed, so it must
2310023097 // be bitcast according to the pointer type we are performing the load through.
2310123098 if (!load_ty.hasWellDefinedLayout())
23102 return sema.fail(block, src, "comptime dereference requires {} to have a well-defined layout, but it does not.", .{load_ty.fmt(target)});
23099 return sema.fail(block, src, "comptime dereference requires {} to have a well-defined layout, but it does not.", .{load_ty.fmt(sema.mod)});
2310323100
2310423101 const load_sz = try sema.typeAbiSize(block, src, load_ty);
2310523102
......@@ -23114,11 +23111,11 @@ fn pointerDeref(sema: *Sema, block: *Block, src: LazySrcLoc, ptr_val: Value, ptr
2311423111 if (deref.ty_without_well_defined_layout) |bad_ty| {
2311523112 // We got no parent for bit-casting, or the parent we got was too small. Either way, the problem
2311623113 // is that some type we encountered when de-referencing does not have a well-defined layout.
23117 return sema.fail(block, src, "comptime dereference requires {} to have a well-defined layout, but it does not.", .{bad_ty.fmt(target)});
23114 return sema.fail(block, src, "comptime dereference requires {} to have a well-defined layout, but it does not.", .{bad_ty.fmt(sema.mod)});
2311823115 } else {
2311923116 // If all encountered types had well-defined layouts, the parent is the root decl and it just
2312023117 // wasn't big enough for the load.
23121 return sema.fail(block, src, "dereference of {} exceeds bounds of containing decl of type {}", .{ ptr_ty.fmt(target), deref.parent.?.tv.ty.fmt(target) });
23118 return sema.fail(block, src, "dereference of {} exceeds bounds of containing decl of type {}", .{ ptr_ty.fmt(sema.mod), deref.parent.?.tv.ty.fmt(sema.mod) });
2312223119 }
2312323120}
2312423121
......@@ -23484,9 +23481,8 @@ fn anonStructFieldIndex(
2348423481 return @intCast(u32, i);
2348523482 }
2348623483 }
23487 const target = sema.mod.getTarget();
2348823484 return sema.fail(block, field_src, "anonymous struct {} has no such field '{s}'", .{
23489 struct_ty.fmt(target), field_name,
23485 struct_ty.fmt(sema.mod), field_name,
2349023486 });
2349123487}
2349223488
src/TypedValue.zig+29-23
......@@ -1,6 +1,7 @@
11const std = @import("std");
22const Type = @import("type.zig").Type;
33const Value = @import("value.zig").Value;
4const Module = @import("Module.zig");
45const Allocator = std.mem.Allocator;
56const TypedValue = @This();
67const Target = std.Target;
......@@ -31,13 +32,13 @@ pub fn copy(self: TypedValue, arena: Allocator) error{OutOfMemory}!TypedValue {
3132 };
3233}
3334
34pub fn eql(a: TypedValue, b: TypedValue, target: std.Target) bool {
35 if (!a.ty.eql(b.ty, target)) return false;
36 return a.val.eql(b.val, a.ty, target);
35pub fn eql(a: TypedValue, b: TypedValue, mod: *Module) bool {
36 if (!a.ty.eql(b.ty, mod)) return false;
37 return a.val.eql(b.val, a.ty, mod);
3738}
3839
39pub fn hash(tv: TypedValue, hasher: *std.hash.Wyhash, target: std.Target) void {
40 return tv.val.hash(tv.ty, hasher, target);
40pub fn hash(tv: TypedValue, hasher: *std.hash.Wyhash, mod: *Module) void {
41 return tv.val.hash(tv.ty, hasher, mod);
4142}
4243
4344pub fn enumToInt(tv: TypedValue, buffer: *Value.Payload.U64) Value {
......@@ -48,7 +49,7 @@ const max_aggregate_items = 100;
4849
4950const FormatContext = struct {
5051 tv: TypedValue,
51 target: Target,
52 mod: *Module,
5253};
5354
5455pub fn format(
......@@ -59,7 +60,7 @@ pub fn format(
5960) !void {
6061 _ = options;
6162 comptime std.debug.assert(fmt.len == 0);
62 return ctx.tv.print(writer, 3, ctx.target);
63 return ctx.tv.print(writer, 3, ctx.mod);
6364}
6465
6566/// Prints the Value according to the Type, not according to the Value Tag.
......@@ -67,8 +68,9 @@ pub fn print(
6768 tv: TypedValue,
6869 writer: anytype,
6970 level: u8,
70 target: std.Target,
71 mod: *Module,
7172) @TypeOf(writer).Error!void {
73 const target = mod.getTarget();
7274 var val = tv.val;
7375 var ty = tv.ty;
7476 while (true) switch (val.tag()) {
......@@ -156,7 +158,7 @@ pub fn print(
156158 try print(.{
157159 .ty = fields[i].ty,
158160 .val = vals[i],
159 }, writer, level - 1, target);
161 }, writer, level - 1, mod);
160162 }
161163 return writer.writeAll(" }");
162164 } else {
......@@ -170,7 +172,7 @@ pub fn print(
170172 try print(.{
171173 .ty = elem_ty,
172174 .val = vals[i],
173 }, writer, level - 1, target);
175 }, writer, level - 1, mod);
174176 }
175177 return writer.writeAll(" }");
176178 }
......@@ -185,12 +187,12 @@ pub fn print(
185187 try print(.{
186188 .ty = ty.unionTagType().?,
187189 .val = union_val.tag,
188 }, writer, level - 1, target);
190 }, writer, level - 1, mod);
189191 try writer.writeAll(" = ");
190192 try print(.{
191 .ty = ty.unionFieldType(union_val.tag, target),
193 .ty = ty.unionFieldType(union_val.tag, mod),
192194 .val = union_val.val,
193 }, writer, level - 1, target);
195 }, writer, level - 1, mod);
194196
195197 return writer.writeAll(" }");
196198 },
......@@ -205,7 +207,7 @@ pub fn print(
205207 },
206208 .bool_true => return writer.writeAll("true"),
207209 .bool_false => return writer.writeAll("false"),
208 .ty => return val.castTag(.ty).?.data.print(writer, target),
210 .ty => return val.castTag(.ty).?.data.print(writer, mod),
209211 .int_type => {
210212 const int_type = val.castTag(.int_type).?.data;
211213 return writer.print("{s}{d}", .{
......@@ -222,28 +224,32 @@ pub fn print(
222224 const x = sub_ty.abiAlignment(target);
223225 return writer.print("{d}", .{x});
224226 },
225 .function => return writer.print("(function '{s}')", .{val.castTag(.function).?.data.owner_decl.name}),
227 .function => return writer.print("(function '{s}')", .{
228 mod.declPtr(val.castTag(.function).?.data.owner_decl).name,
229 }),
226230 .extern_fn => return writer.writeAll("(extern function)"),
227231 .variable => return writer.writeAll("(variable)"),
228232 .decl_ref_mut => {
229 const decl = val.castTag(.decl_ref_mut).?.data.decl;
233 const decl_index = val.castTag(.decl_ref_mut).?.data.decl_index;
234 const decl = mod.declPtr(decl_index);
230235 if (level == 0) {
231236 return writer.print("(decl ref mut '{s}')", .{decl.name});
232237 }
233238 return print(.{
234239 .ty = decl.ty,
235240 .val = decl.val,
236 }, writer, level - 1, target);
241 }, writer, level - 1, mod);
237242 },
238243 .decl_ref => {
239 const decl = val.castTag(.decl_ref).?.data;
244 const decl_index = val.castTag(.decl_ref).?.data;
245 const decl = mod.declPtr(decl_index);
240246 if (level == 0) {
241247 return writer.print("(decl ref '{s}')", .{decl.name});
242248 }
243249 return print(.{
244250 .ty = decl.ty,
245251 .val = decl.val,
246 }, writer, level - 1, target);
252 }, writer, level - 1, mod);
247253 },
248254 .elem_ptr => {
249255 const elem_ptr = val.castTag(.elem_ptr).?.data;
......@@ -251,7 +257,7 @@ pub fn print(
251257 try print(.{
252258 .ty = elem_ptr.elem_ty,
253259 .val = elem_ptr.array_ptr,
254 }, writer, level - 1, target);
260 }, writer, level - 1, mod);
255261 return writer.print("[{}]", .{elem_ptr.index});
256262 },
257263 .field_ptr => {
......@@ -260,7 +266,7 @@ pub fn print(
260266 try print(.{
261267 .ty = field_ptr.container_ty,
262268 .val = field_ptr.container_ptr,
263 }, writer, level - 1, target);
269 }, writer, level - 1, mod);
264270
265271 if (field_ptr.container_ty.zigTypeTag() == .Struct) {
266272 const field_name = field_ptr.container_ty.structFields().keys()[field_ptr.field_index];
......@@ -288,7 +294,7 @@ pub fn print(
288294 };
289295 while (i < max_aggregate_items) : (i += 1) {
290296 if (i != 0) try writer.writeAll(", ");
291 try print(elem_tv, writer, level - 1, target);
297 try print(elem_tv, writer, level - 1, mod);
292298 }
293299 return writer.writeAll(" }");
294300 },
......@@ -300,7 +306,7 @@ pub fn print(
300306 try print(.{
301307 .ty = ty.elemType2(),
302308 .val = ty.sentinel().?,
303 }, writer, level - 1, target);
309 }, writer, level - 1, mod);
304310 return writer.writeAll(" }");
305311 },
306312 .slice => return writer.writeAll("(slice)"),
src/arch/aarch64/CodeGen.zig+34-24
......@@ -237,8 +237,10 @@ pub fn generate(
237237 @panic("Attempted to compile for architecture that was disabled by build configuration");
238238 }
239239
240 assert(module_fn.owner_decl.has_tv);
241 const fn_type = module_fn.owner_decl.ty;
240 const mod = bin_file.options.module.?;
241 const fn_owner_decl = mod.declPtr(module_fn.owner_decl);
242 assert(fn_owner_decl.has_tv);
243 const fn_type = fn_owner_decl.ty;
242244
243245 var branch_stack = std.ArrayList(Branch).init(bin_file.allocator);
244246 defer {
......@@ -819,9 +821,9 @@ fn allocMemPtr(self: *Self, inst: Air.Inst.Index) !u32 {
819821 return @as(u32, 0);
820822 }
821823
822 const target = self.target.*;
823824 const abi_size = math.cast(u32, elem_ty.abiSize(self.target.*)) catch {
824 return self.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(target)});
825 const mod = self.bin_file.options.module.?;
826 return self.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(mod)});
825827 };
826828 // TODO swap this for inst.ty.ptrAlign
827829 const abi_align = elem_ty.abiAlignment(self.target.*);
......@@ -830,9 +832,9 @@ fn allocMemPtr(self: *Self, inst: Air.Inst.Index) !u32 {
830832
831833fn allocRegOrMem(self: *Self, inst: Air.Inst.Index, reg_ok: bool) !MCValue {
832834 const elem_ty = self.air.typeOfIndex(inst);
833 const target = self.target.*;
834835 const abi_size = math.cast(u32, elem_ty.abiSize(self.target.*)) catch {
835 return self.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(target)});
836 const mod = self.bin_file.options.module.?;
837 return self.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(mod)});
836838 };
837839 const abi_align = elem_ty.abiAlignment(self.target.*);
838840 if (abi_align > self.stack_align)
......@@ -1422,7 +1424,7 @@ fn binOp(
14221424 lhs_ty: Type,
14231425 rhs_ty: Type,
14241426) InnerError!MCValue {
1425 const target = self.target.*;
1427 const mod = self.bin_file.options.module.?;
14261428 switch (tag) {
14271429 .add,
14281430 .sub,
......@@ -1432,7 +1434,7 @@ fn binOp(
14321434 .Float => return self.fail("TODO binary operations on floats", .{}),
14331435 .Vector => return self.fail("TODO binary operations on vectors", .{}),
14341436 .Int => {
1435 assert(lhs_ty.eql(rhs_ty, target));
1437 assert(lhs_ty.eql(rhs_ty, mod));
14361438 const int_info = lhs_ty.intInfo(self.target.*);
14371439 if (int_info.bits <= 64) {
14381440 // Only say yes if the operation is
......@@ -1483,7 +1485,7 @@ fn binOp(
14831485 switch (lhs_ty.zigTypeTag()) {
14841486 .Vector => return self.fail("TODO binary operations on vectors", .{}),
14851487 .Int => {
1486 assert(lhs_ty.eql(rhs_ty, target));
1488 assert(lhs_ty.eql(rhs_ty, mod));
14871489 const int_info = lhs_ty.intInfo(self.target.*);
14881490 if (int_info.bits <= 64) {
14891491 // TODO add optimisations for multiplication
......@@ -1534,7 +1536,7 @@ fn binOp(
15341536 switch (lhs_ty.zigTypeTag()) {
15351537 .Vector => return self.fail("TODO binary operations on vectors", .{}),
15361538 .Int => {
1537 assert(lhs_ty.eql(rhs_ty, target));
1539 assert(lhs_ty.eql(rhs_ty, mod));
15381540 const int_info = lhs_ty.intInfo(self.target.*);
15391541 if (int_info.bits <= 64) {
15401542 // TODO implement bitwise operations with immediates
......@@ -2425,12 +2427,12 @@ fn airArg(self: *Self, inst: Air.Inst.Index) !void {
24252427 const ty = self.air.typeOfIndex(inst);
24262428
24272429 const result = self.args[arg_index];
2428 const target = self.target.*;
24292430 const mcv = switch (result) {
24302431 // Copy registers to the stack
24312432 .register => |reg| blk: {
2433 const mod = self.bin_file.options.module.?;
24322434 const abi_size = math.cast(u32, ty.abiSize(self.target.*)) catch {
2433 return self.fail("type '{}' too big to fit into stack frame", .{ty.fmt(target)});
2435 return self.fail("type '{}' too big to fit into stack frame", .{ty.fmt(mod)});
24342436 };
24352437 const abi_align = ty.abiAlignment(self.target.*);
24362438 const stack_offset = try self.allocMem(inst, abi_size, abi_align);
......@@ -2537,17 +2539,19 @@ fn airCall(self: *Self, inst: Air.Inst.Index, modifier: std.builtin.CallOptions.
25372539
25382540 // Due to incremental compilation, how function calls are generated depends
25392541 // on linking.
2542 const mod = self.bin_file.options.module.?;
25402543 if (self.air.value(callee)) |func_value| {
25412544 if (self.bin_file.tag == link.File.Elf.base_tag or self.bin_file.tag == link.File.Coff.base_tag) {
25422545 if (func_value.castTag(.function)) |func_payload| {
25432546 const func = func_payload.data;
25442547 const ptr_bits = self.target.cpu.arch.ptrBitWidth();
25452548 const ptr_bytes: u64 = @divExact(ptr_bits, 8);
2549 const fn_owner_decl = mod.declPtr(func.owner_decl);
25462550 const got_addr = if (self.bin_file.cast(link.File.Elf)) |elf_file| blk: {
25472551 const got = &elf_file.program_headers.items[elf_file.phdr_got_index.?];
2548 break :blk @intCast(u32, got.p_vaddr + func.owner_decl.link.elf.offset_table_index * ptr_bytes);
2552 break :blk @intCast(u32, got.p_vaddr + fn_owner_decl.link.elf.offset_table_index * ptr_bytes);
25492553 } else if (self.bin_file.cast(link.File.Coff)) |coff_file|
2550 coff_file.offset_table_virtual_address + func.owner_decl.link.coff.offset_table_index * ptr_bytes
2554 coff_file.offset_table_virtual_address + fn_owner_decl.link.coff.offset_table_index * ptr_bytes
25512555 else
25522556 unreachable;
25532557
......@@ -2565,8 +2569,9 @@ fn airCall(self: *Self, inst: Air.Inst.Index, modifier: std.builtin.CallOptions.
25652569 } else if (self.bin_file.cast(link.File.MachO)) |macho_file| {
25662570 if (func_value.castTag(.function)) |func_payload| {
25672571 const func = func_payload.data;
2572 const fn_owner_decl = mod.declPtr(func.owner_decl);
25682573 try self.genSetReg(Type.initTag(.u64), .x30, .{
2569 .got_load = func.owner_decl.link.macho.local_sym_index,
2574 .got_load = fn_owner_decl.link.macho.local_sym_index,
25702575 });
25712576 // blr x30
25722577 _ = try self.addInst(.{
......@@ -2575,7 +2580,7 @@ fn airCall(self: *Self, inst: Air.Inst.Index, modifier: std.builtin.CallOptions.
25752580 });
25762581 } else if (func_value.castTag(.extern_fn)) |func_payload| {
25772582 const extern_fn = func_payload.data;
2578 const decl_name = extern_fn.owner_decl.name;
2583 const decl_name = mod.declPtr(extern_fn.owner_decl).name;
25792584 if (extern_fn.lib_name) |lib_name| {
25802585 log.debug("TODO enforce that '{s}' is expected in '{s}' library", .{
25812586 decl_name,
......@@ -2588,7 +2593,7 @@ fn airCall(self: *Self, inst: Air.Inst.Index, modifier: std.builtin.CallOptions.
25882593 .tag = .call_extern,
25892594 .data = .{
25902595 .extern_fn = .{
2591 .atom_index = self.mod_fn.owner_decl.link.macho.local_sym_index,
2596 .atom_index = mod.declPtr(self.mod_fn.owner_decl).link.macho.local_sym_index,
25922597 .sym_name = n_strx,
25932598 },
25942599 },
......@@ -2602,7 +2607,7 @@ fn airCall(self: *Self, inst: Air.Inst.Index, modifier: std.builtin.CallOptions.
26022607 const ptr_bits = self.target.cpu.arch.ptrBitWidth();
26032608 const ptr_bytes: u64 = @divExact(ptr_bits, 8);
26042609 const got_addr = p9.bases.data;
2605 const got_index = func_payload.data.owner_decl.link.plan9.got_index.?;
2610 const got_index = mod.declPtr(func_payload.data.owner_decl).link.plan9.got_index.?;
26062611 const fn_got_addr = got_addr + got_index * ptr_bytes;
26072612
26082613 try self.genSetReg(Type.initTag(.usize), .x30, .{ .memory = fn_got_addr });
......@@ -3478,12 +3483,13 @@ fn genSetStack(self: *Self, ty: Type, stack_offset: u32, mcv: MCValue) InnerErro
34783483 .direct_load => .load_memory_ptr_direct,
34793484 else => unreachable,
34803485 };
3486 const mod = self.bin_file.options.module.?;
34813487 _ = try self.addInst(.{
34823488 .tag = tag,
34833489 .data = .{
34843490 .payload = try self.addExtra(Mir.LoadMemoryPie{
34853491 .register = @enumToInt(src_reg),
3486 .atom_index = self.mod_fn.owner_decl.link.macho.local_sym_index,
3492 .atom_index = mod.declPtr(self.mod_fn.owner_decl).link.macho.local_sym_index,
34873493 .sym_index = sym_index,
34883494 }),
34893495 },
......@@ -3597,12 +3603,13 @@ fn genSetReg(self: *Self, ty: Type, reg: Register, mcv: MCValue) InnerError!void
35973603 .direct_load => .load_memory_direct,
35983604 else => unreachable,
35993605 };
3606 const mod = self.bin_file.options.module.?;
36003607 _ = try self.addInst(.{
36013608 .tag = tag,
36023609 .data = .{
36033610 .payload = try self.addExtra(Mir.LoadMemoryPie{
36043611 .register = @enumToInt(reg),
3605 .atom_index = self.mod_fn.owner_decl.link.macho.local_sym_index,
3612 .atom_index = mod.declPtr(self.mod_fn.owner_decl).link.macho.local_sym_index,
36063613 .sym_index = sym_index,
36073614 }),
36083615 },
......@@ -3860,7 +3867,7 @@ fn getResolvedInstValue(self: *Self, inst: Air.Inst.Index) MCValue {
38603867 }
38613868}
38623869
3863fn lowerDeclRef(self: *Self, tv: TypedValue, decl: *Module.Decl) InnerError!MCValue {
3870fn lowerDeclRef(self: *Self, tv: TypedValue, decl_index: Module.Decl.Index) InnerError!MCValue {
38643871 const ptr_bits = self.target.cpu.arch.ptrBitWidth();
38653872 const ptr_bytes: u64 = @divExact(ptr_bits, 8);
38663873
......@@ -3872,7 +3879,10 @@ fn lowerDeclRef(self: *Self, tv: TypedValue, decl: *Module.Decl) InnerError!MCVa
38723879 }
38733880 }
38743881
3875 decl.alive = true;
3882 const mod = self.bin_file.options.module.?;
3883 const decl = mod.declPtr(decl_index);
3884 mod.markDeclAlive(decl);
3885
38763886 if (self.bin_file.cast(link.File.Elf)) |elf_file| {
38773887 const got = &elf_file.program_headers.items[elf_file.phdr_got_index.?];
38783888 const got_addr = got.p_vaddr + decl.link.elf.offset_table_index * ptr_bytes;
......@@ -3886,7 +3896,7 @@ fn lowerDeclRef(self: *Self, tv: TypedValue, decl: *Module.Decl) InnerError!MCVa
38863896 const got_addr = coff_file.offset_table_virtual_address + decl.link.coff.offset_table_index * ptr_bytes;
38873897 return MCValue{ .memory = got_addr };
38883898 } else if (self.bin_file.cast(link.File.Plan9)) |p9| {
3889 try p9.seeDecl(decl);
3899 try p9.seeDecl(decl_index);
38903900 const got_addr = p9.bases.data + decl.link.plan9.got_index.? * ptr_bytes;
38913901 return MCValue{ .memory = got_addr };
38923902 } else {
......@@ -3922,7 +3932,7 @@ fn genTypedValue(self: *Self, typed_value: TypedValue) InnerError!MCValue {
39223932 return self.lowerDeclRef(typed_value, payload.data);
39233933 }
39243934 if (typed_value.val.castTag(.decl_ref_mut)) |payload| {
3925 return self.lowerDeclRef(typed_value, payload.data.decl);
3935 return self.lowerDeclRef(typed_value, payload.data.decl_index);
39263936 }
39273937 const target = self.target.*;
39283938
src/arch/arm/CodeGen.zig+33-20
......@@ -271,8 +271,10 @@ pub fn generate(
271271 @panic("Attempted to compile for architecture that was disabled by build configuration");
272272 }
273273
274 assert(module_fn.owner_decl.has_tv);
275 const fn_type = module_fn.owner_decl.ty;
274 const mod = bin_file.options.module.?;
275 const fn_owner_decl = mod.declPtr(module_fn.owner_decl);
276 assert(fn_owner_decl.has_tv);
277 const fn_type = fn_owner_decl.ty;
276278
277279 var branch_stack = std.ArrayList(Branch).init(bin_file.allocator);
278280 defer {
......@@ -838,9 +840,9 @@ fn allocMemPtr(self: *Self, inst: Air.Inst.Index) !u32 {
838840 return @as(u32, 0);
839841 }
840842
841 const target = self.target.*;
842843 const abi_size = math.cast(u32, elem_ty.abiSize(self.target.*)) catch {
843 return self.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(target)});
844 const mod = self.bin_file.options.module.?;
845 return self.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(mod)});
844846 };
845847 // TODO swap this for inst.ty.ptrAlign
846848 const abi_align = elem_ty.abiAlignment(self.target.*);
......@@ -849,9 +851,9 @@ fn allocMemPtr(self: *Self, inst: Air.Inst.Index) !u32 {
849851
850852fn allocRegOrMem(self: *Self, inst: Air.Inst.Index, reg_ok: bool) !MCValue {
851853 const elem_ty = self.air.typeOfIndex(inst);
852 const target = self.target.*;
853854 const abi_size = math.cast(u32, elem_ty.abiSize(self.target.*)) catch {
854 return self.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(target)});
855 const mod = self.bin_file.options.module.?;
856 return self.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(mod)});
855857 };
856858 const abi_align = elem_ty.abiAlignment(self.target.*);
857859 if (abi_align > self.stack_align)
......@@ -1204,7 +1206,8 @@ fn minMax(
12041206 .Float => return self.fail("TODO ARM min/max on floats", .{}),
12051207 .Vector => return self.fail("TODO ARM min/max on vectors", .{}),
12061208 .Int => {
1207 assert(lhs_ty.eql(rhs_ty, self.target.*));
1209 const mod = self.bin_file.options.module.?;
1210 assert(lhs_ty.eql(rhs_ty, mod));
12081211 const int_info = lhs_ty.intInfo(self.target.*);
12091212 if (int_info.bits <= 32) {
12101213 const lhs_is_register = lhs == .register;
......@@ -1372,7 +1375,8 @@ fn airOverflow(self: *Self, inst: Air.Inst.Index) !void {
13721375 switch (lhs_ty.zigTypeTag()) {
13731376 .Vector => return self.fail("TODO implement add_with_overflow/sub_with_overflow for vectors", .{}),
13741377 .Int => {
1375 assert(lhs_ty.eql(rhs_ty, self.target.*));
1378 const mod = self.bin_file.options.module.?;
1379 assert(lhs_ty.eql(rhs_ty, mod));
13761380 const int_info = lhs_ty.intInfo(self.target.*);
13771381 if (int_info.bits < 32) {
13781382 const stack_offset = try self.allocMem(inst, tuple_size, tuple_align);
......@@ -1472,7 +1476,8 @@ fn airMulWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
14721476 switch (lhs_ty.zigTypeTag()) {
14731477 .Vector => return self.fail("TODO implement mul_with_overflow for vectors", .{}),
14741478 .Int => {
1475 assert(lhs_ty.eql(rhs_ty, self.target.*));
1479 const mod = self.bin_file.options.module.?;
1480 assert(lhs_ty.eql(rhs_ty, mod));
14761481 const int_info = lhs_ty.intInfo(self.target.*);
14771482 if (int_info.bits <= 16) {
14781483 const stack_offset = try self.allocMem(inst, tuple_size, tuple_align);
......@@ -2682,7 +2687,6 @@ fn binOp(
26822687 lhs_ty: Type,
26832688 rhs_ty: Type,
26842689) InnerError!MCValue {
2685 const target = self.target.*;
26862690 switch (tag) {
26872691 .add,
26882692 .sub,
......@@ -2692,7 +2696,8 @@ fn binOp(
26922696 .Float => return self.fail("TODO ARM binary operations on floats", .{}),
26932697 .Vector => return self.fail("TODO ARM binary operations on vectors", .{}),
26942698 .Int => {
2695 assert(lhs_ty.eql(rhs_ty, target));
2699 const mod = self.bin_file.options.module.?;
2700 assert(lhs_ty.eql(rhs_ty, mod));
26962701 const int_info = lhs_ty.intInfo(self.target.*);
26972702 if (int_info.bits <= 32) {
26982703 // Only say yes if the operation is
......@@ -2740,7 +2745,8 @@ fn binOp(
27402745 .Float => return self.fail("TODO ARM binary operations on floats", .{}),
27412746 .Vector => return self.fail("TODO ARM binary operations on vectors", .{}),
27422747 .Int => {
2743 assert(lhs_ty.eql(rhs_ty, target));
2748 const mod = self.bin_file.options.module.?;
2749 assert(lhs_ty.eql(rhs_ty, mod));
27442750 const int_info = lhs_ty.intInfo(self.target.*);
27452751 if (int_info.bits <= 32) {
27462752 // TODO add optimisations for multiplication
......@@ -2794,7 +2800,8 @@ fn binOp(
27942800 switch (lhs_ty.zigTypeTag()) {
27952801 .Vector => return self.fail("TODO ARM binary operations on vectors", .{}),
27962802 .Int => {
2797 assert(lhs_ty.eql(rhs_ty, target));
2803 const mod = self.bin_file.options.module.?;
2804 assert(lhs_ty.eql(rhs_ty, mod));
27982805 const int_info = lhs_ty.intInfo(self.target.*);
27992806 if (int_info.bits <= 32) {
28002807 const lhs_immediate_ok = lhs == .immediate and Instruction.Operand.fromU32(lhs.immediate) != null;
......@@ -3100,8 +3107,9 @@ fn addDbgInfoTypeReloc(self: *Self, ty: Type) error{OutOfMemory}!void {
31003107 const dbg_info = &dw.dbg_info;
31013108 const index = dbg_info.items.len;
31023109 try dbg_info.resize(index + 4); // DW.AT.type, DW.FORM.ref4
3110 const mod = self.bin_file.options.module.?;
31033111 const atom = switch (self.bin_file.tag) {
3104 .elf => &self.mod_fn.owner_decl.link.elf.dbg_info_atom,
3112 .elf => &mod.declPtr(self.mod_fn.owner_decl).link.elf.dbg_info_atom,
31053113 .macho => unreachable,
31063114 else => unreachable,
31073115 };
......@@ -3318,11 +3326,13 @@ fn airCall(self: *Self, inst: Air.Inst.Index, modifier: std.builtin.CallOptions.
33183326 const func = func_payload.data;
33193327 const ptr_bits = self.target.cpu.arch.ptrBitWidth();
33203328 const ptr_bytes: u64 = @divExact(ptr_bits, 8);
3329 const mod = self.bin_file.options.module.?;
3330 const fn_owner_decl = mod.declPtr(func.owner_decl);
33213331 const got_addr = if (self.bin_file.cast(link.File.Elf)) |elf_file| blk: {
33223332 const got = &elf_file.program_headers.items[elf_file.phdr_got_index.?];
3323 break :blk @intCast(u32, got.p_vaddr + func.owner_decl.link.elf.offset_table_index * ptr_bytes);
3333 break :blk @intCast(u32, got.p_vaddr + fn_owner_decl.link.elf.offset_table_index * ptr_bytes);
33243334 } else if (self.bin_file.cast(link.File.Coff)) |coff_file|
3325 coff_file.offset_table_virtual_address + func.owner_decl.link.coff.offset_table_index * ptr_bytes
3335 coff_file.offset_table_virtual_address + fn_owner_decl.link.coff.offset_table_index * ptr_bytes
33263336 else
33273337 unreachable;
33283338
......@@ -4924,11 +4934,14 @@ fn getResolvedInstValue(self: *Self, inst: Air.Inst.Index) MCValue {
49244934 }
49254935}
49264936
4927fn lowerDeclRef(self: *Self, tv: TypedValue, decl: *Module.Decl) InnerError!MCValue {
4937fn lowerDeclRef(self: *Self, tv: TypedValue, decl_index: Module.Decl.Index) InnerError!MCValue {
49284938 const ptr_bits = self.target.cpu.arch.ptrBitWidth();
49294939 const ptr_bytes: u64 = @divExact(ptr_bits, 8);
49304940
4931 decl.alive = true;
4941 const mod = self.bin_file.options.module.?;
4942 const decl = mod.declPtr(decl_index);
4943 mod.markDeclAlive(decl);
4944
49324945 if (self.bin_file.cast(link.File.Elf)) |elf_file| {
49334946 const got = &elf_file.program_headers.items[elf_file.phdr_got_index.?];
49344947 const got_addr = got.p_vaddr + decl.link.elf.offset_table_index * ptr_bytes;
......@@ -4939,7 +4952,7 @@ fn lowerDeclRef(self: *Self, tv: TypedValue, decl: *Module.Decl) InnerError!MCVa
49394952 const got_addr = coff_file.offset_table_virtual_address + decl.link.coff.offset_table_index * ptr_bytes;
49404953 return MCValue{ .memory = got_addr };
49414954 } else if (self.bin_file.cast(link.File.Plan9)) |p9| {
4942 try p9.seeDecl(decl);
4955 try p9.seeDecl(decl_index);
49434956 const got_addr = p9.bases.data + decl.link.plan9.got_index.? * ptr_bytes;
49444957 return MCValue{ .memory = got_addr };
49454958 } else {
......@@ -4976,7 +4989,7 @@ fn genTypedValue(self: *Self, typed_value: TypedValue) InnerError!MCValue {
49764989 return self.lowerDeclRef(typed_value, payload.data);
49774990 }
49784991 if (typed_value.val.castTag(.decl_ref_mut)) |payload| {
4979 return self.lowerDeclRef(typed_value, payload.data.decl);
4992 return self.lowerDeclRef(typed_value, payload.data.decl_index);
49804993 }
49814994 const target = self.target.*;
49824995
src/arch/riscv64/CodeGen.zig+26-16
......@@ -229,8 +229,10 @@ pub fn generate(
229229 @panic("Attempted to compile for architecture that was disabled by build configuration");
230230 }
231231
232 assert(module_fn.owner_decl.has_tv);
233 const fn_type = module_fn.owner_decl.ty;
232 const mod = bin_file.options.module.?;
233 const fn_owner_decl = mod.declPtr(module_fn.owner_decl);
234 assert(fn_owner_decl.has_tv);
235 const fn_type = fn_owner_decl.ty;
234236
235237 var branch_stack = std.ArrayList(Branch).init(bin_file.allocator);
236238 defer {
......@@ -738,8 +740,9 @@ fn addDbgInfoTypeReloc(self: *Self, ty: Type) !void {
738740 const dbg_info = &dw.dbg_info;
739741 const index = dbg_info.items.len;
740742 try dbg_info.resize(index + 4); // DW.AT.type, DW.FORM.ref4
743 const mod = self.bin_file.options.module.?;
741744 const atom = switch (self.bin_file.tag) {
742 .elf => &self.mod_fn.owner_decl.link.elf.dbg_info_atom,
745 .elf => &mod.declPtr(self.mod_fn.owner_decl).link.elf.dbg_info_atom,
743746 .macho => unreachable,
744747 else => unreachable,
745748 };
......@@ -768,9 +771,9 @@ fn allocMem(self: *Self, inst: Air.Inst.Index, abi_size: u32, abi_align: u32) !u
768771/// Use a pointer instruction as the basis for allocating stack memory.
769772fn allocMemPtr(self: *Self, inst: Air.Inst.Index) !u32 {
770773 const elem_ty = self.air.typeOfIndex(inst).elemType();
771 const target = self.target.*;
772774 const abi_size = math.cast(u32, elem_ty.abiSize(self.target.*)) catch {
773 return self.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(target)});
775 const mod = self.bin_file.options.module.?;
776 return self.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(mod)});
774777 };
775778 // TODO swap this for inst.ty.ptrAlign
776779 const abi_align = elem_ty.abiAlignment(self.target.*);
......@@ -779,9 +782,9 @@ fn allocMemPtr(self: *Self, inst: Air.Inst.Index) !u32 {
779782
780783fn allocRegOrMem(self: *Self, inst: Air.Inst.Index, reg_ok: bool) !MCValue {
781784 const elem_ty = self.air.typeOfIndex(inst);
782 const target = self.target.*;
783785 const abi_size = math.cast(u32, elem_ty.abiSize(self.target.*)) catch {
784 return self.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(target)});
786 const mod = self.bin_file.options.module.?;
787 return self.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(mod)});
785788 };
786789 const abi_align = elem_ty.abiAlignment(self.target.*);
787790 if (abi_align > self.stack_align)
......@@ -1037,7 +1040,8 @@ fn binOp(
10371040 .Float => return self.fail("TODO binary operations on floats", .{}),
10381041 .Vector => return self.fail("TODO binary operations on vectors", .{}),
10391042 .Int => {
1040 assert(lhs_ty.eql(rhs_ty, self.target.*));
1043 const mod = self.bin_file.options.module.?;
1044 assert(lhs_ty.eql(rhs_ty, mod));
10411045 const int_info = lhs_ty.intInfo(self.target.*);
10421046 if (int_info.bits <= 64) {
10431047 // TODO immediate operands
......@@ -1679,11 +1683,13 @@ fn airCall(self: *Self, inst: Air.Inst.Index, modifier: std.builtin.CallOptions.
16791683
16801684 const ptr_bits = self.target.cpu.arch.ptrBitWidth();
16811685 const ptr_bytes: u64 = @divExact(ptr_bits, 8);
1686 const mod = self.bin_file.options.module.?;
1687 const fn_owner_decl = mod.declPtr(func.owner_decl);
16821688 const got_addr = if (self.bin_file.cast(link.File.Elf)) |elf_file| blk: {
16831689 const got = &elf_file.program_headers.items[elf_file.phdr_got_index.?];
1684 break :blk @intCast(u32, got.p_vaddr + func.owner_decl.link.elf.offset_table_index * ptr_bytes);
1690 break :blk @intCast(u32, got.p_vaddr + fn_owner_decl.link.elf.offset_table_index * ptr_bytes);
16851691 } else if (self.bin_file.cast(link.File.Coff)) |coff_file|
1686 coff_file.offset_table_virtual_address + func.owner_decl.link.coff.offset_table_index * ptr_bytes
1692 coff_file.offset_table_virtual_address + fn_owner_decl.link.coff.offset_table_index * ptr_bytes
16871693 else
16881694 unreachable;
16891695
......@@ -1768,7 +1774,8 @@ fn airCmp(self: *Self, inst: Air.Inst.Index, op: math.CompareOperator) !void {
17681774 if (self.liveness.isUnused(inst))
17691775 return self.finishAir(inst, .dead, .{ bin_op.lhs, bin_op.rhs, .none });
17701776 const ty = self.air.typeOf(bin_op.lhs);
1771 assert(ty.eql(self.air.typeOf(bin_op.rhs), self.target.*));
1777 const mod = self.bin_file.options.module.?;
1778 assert(ty.eql(self.air.typeOf(bin_op.rhs), mod));
17721779 if (ty.zigTypeTag() == .ErrorSet)
17731780 return self.fail("TODO implement cmp for errors", .{});
17741781
......@@ -2501,10 +2508,12 @@ fn getResolvedInstValue(self: *Self, inst: Air.Inst.Index) MCValue {
25012508 }
25022509}
25032510
2504fn lowerDeclRef(self: *Self, tv: TypedValue, decl: *Module.Decl) InnerError!MCValue {
2511fn lowerDeclRef(self: *Self, tv: TypedValue, decl_index: Module.Decl.Index) InnerError!MCValue {
25052512 const ptr_bits = self.target.cpu.arch.ptrBitWidth();
25062513 const ptr_bytes: u64 = @divExact(ptr_bits, 8);
2507 decl.alive = true;
2514 const mod = self.bin_file.options.module.?;
2515 const decl = mod.declPtr(decl_index);
2516 mod.markDeclAlive(decl);
25082517 if (self.bin_file.cast(link.File.Elf)) |elf_file| {
25092518 const got = &elf_file.program_headers.items[elf_file.phdr_got_index.?];
25102519 const got_addr = got.p_vaddr + decl.link.elf.offset_table_index * ptr_bytes;
......@@ -2517,7 +2526,7 @@ fn lowerDeclRef(self: *Self, tv: TypedValue, decl: *Module.Decl) InnerError!MCVa
25172526 const got_addr = coff_file.offset_table_virtual_address + decl.link.coff.offset_table_index * ptr_bytes;
25182527 return MCValue{ .memory = got_addr };
25192528 } else if (self.bin_file.cast(link.File.Plan9)) |p9| {
2520 try p9.seeDecl(decl);
2529 try p9.seeDecl(decl_index);
25212530 const got_addr = p9.bases.data + decl.link.plan9.got_index.? * ptr_bytes;
25222531 return MCValue{ .memory = got_addr };
25232532 } else {
......@@ -2534,7 +2543,7 @@ fn genTypedValue(self: *Self, typed_value: TypedValue) InnerError!MCValue {
25342543 return self.lowerDeclRef(typed_value, payload.data);
25352544 }
25362545 if (typed_value.val.castTag(.decl_ref_mut)) |payload| {
2537 return self.lowerDeclRef(typed_value, payload.data.decl);
2546 return self.lowerDeclRef(typed_value, payload.data.decl_index);
25382547 }
25392548 const target = self.target.*;
25402549 const ptr_bits = self.target.cpu.arch.ptrBitWidth();
......@@ -2544,7 +2553,8 @@ fn genTypedValue(self: *Self, typed_value: TypedValue) InnerError!MCValue {
25442553 var buf: Type.SlicePtrFieldTypeBuffer = undefined;
25452554 const ptr_type = typed_value.ty.slicePtrFieldType(&buf);
25462555 const ptr_mcv = try self.genTypedValue(.{ .ty = ptr_type, .val = typed_value.val });
2547 const slice_len = typed_value.val.sliceLen(target);
2556 const mod = self.bin_file.options.module.?;
2557 const slice_len = typed_value.val.sliceLen(mod);
25482558 // Codegen can't handle some kinds of indirection. If the wrong union field is accessed here it may mean
25492559 // the Sema code needs to use anonymous Decls or alloca instructions to store data.
25502560 const ptr_imm = ptr_mcv.memory;
src/arch/sparcv9/CodeGen.zig+16-10
......@@ -243,8 +243,10 @@ pub fn generate(
243243 @panic("Attempted to compile for architecture that was disabled by build configuration");
244244 }
245245
246 assert(module_fn.owner_decl.has_tv);
247 const fn_type = module_fn.owner_decl.ty;
246 const mod = bin_file.options.module.?;
247 const fn_owner_decl = mod.declPtr(module_fn.owner_decl);
248 assert(fn_owner_decl.has_tv);
249 const fn_type = fn_owner_decl.ty;
248250
249251 var branch_stack = std.ArrayList(Branch).init(bin_file.allocator);
250252 defer {
......@@ -871,7 +873,8 @@ fn airCall(self: *Self, inst: Air.Inst.Index, modifier: std.builtin.CallOptions.
871873 const ptr_bytes: u64 = @divExact(ptr_bits, 8);
872874 const got_addr = if (self.bin_file.cast(link.File.Elf)) |elf_file| blk: {
873875 const got = &elf_file.program_headers.items[elf_file.phdr_got_index.?];
874 break :blk @intCast(u32, got.p_vaddr + func.owner_decl.link.elf.offset_table_index * ptr_bytes);
876 const mod = self.bin_file.options.module.?;
877 break :blk @intCast(u32, got.p_vaddr + mod.declPtr(func.owner_decl).link.elf.offset_table_index * ptr_bytes);
875878 } else unreachable;
876879
877880 try self.genSetReg(Type.initTag(.usize), .o7, .{ .memory = got_addr });
......@@ -1026,9 +1029,9 @@ fn allocMemPtr(self: *Self, inst: Air.Inst.Index) !u32 {
10261029 return @as(u32, 0);
10271030 }
10281031
1029 const target = self.target.*;
10301032 const abi_size = math.cast(u32, elem_ty.abiSize(self.target.*)) catch {
1031 return self.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(target)});
1033 const mod = self.bin_file.options.module.?;
1034 return self.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(mod)});
10321035 };
10331036 // TODO swap this for inst.ty.ptrAlign
10341037 const abi_align = elem_ty.abiAlignment(self.target.*);
......@@ -1037,9 +1040,9 @@ fn allocMemPtr(self: *Self, inst: Air.Inst.Index) !u32 {
10371040
10381041fn allocRegOrMem(self: *Self, inst: Air.Inst.Index, reg_ok: bool) !MCValue {
10391042 const elem_ty = self.air.typeOfIndex(inst);
1040 const target = self.target.*;
10411043 const abi_size = math.cast(u32, elem_ty.abiSize(self.target.*)) catch {
1042 return self.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(target)});
1044 const mod = self.bin_file.options.module.?;
1045 return self.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(mod)});
10431046 };
10441047 const abi_align = elem_ty.abiAlignment(self.target.*);
10451048 if (abi_align > self.stack_align)
......@@ -1372,7 +1375,7 @@ fn genTypedValue(self: *Self, typed_value: TypedValue) InnerError!MCValue {
13721375 return self.lowerDeclRef(typed_value, payload.data);
13731376 }
13741377 if (typed_value.val.castTag(.decl_ref_mut)) |payload| {
1375 return self.lowerDeclRef(typed_value, payload.data.decl);
1378 return self.lowerDeclRef(typed_value, payload.data.decl_index);
13761379 }
13771380 const target = self.target.*;
13781381
......@@ -1422,7 +1425,7 @@ fn iterateBigTomb(self: *Self, inst: Air.Inst.Index, operand_count: usize) !BigT
14221425 };
14231426}
14241427
1425fn lowerDeclRef(self: *Self, tv: TypedValue, decl: *Module.Decl) InnerError!MCValue {
1428fn lowerDeclRef(self: *Self, tv: TypedValue, decl_index: Module.Decl.Index) InnerError!MCValue {
14261429 const ptr_bits = self.target.cpu.arch.ptrBitWidth();
14271430 const ptr_bytes: u64 = @divExact(ptr_bits, 8);
14281431
......@@ -1434,7 +1437,10 @@ fn lowerDeclRef(self: *Self, tv: TypedValue, decl: *Module.Decl) InnerError!MCVa
14341437 }
14351438 }
14361439
1437 decl.alive = true;
1440 const mod = self.bin_file.options.module.?;
1441 const decl = mod.declPtr(decl_index);
1442
1443 mod.markDeclAlive(decl);
14381444 if (self.bin_file.cast(link.File.Elf)) |elf_file| {
14391445 const got = &elf_file.program_headers.items[elf_file.phdr_got_index.?];
14401446 const got_addr = got.p_vaddr + decl.link.elf.offset_table_index * ptr_bytes;
src/arch/wasm/CodeGen.zig+52-35
......@@ -538,6 +538,10 @@ const Self = @This();
538538/// Reference to the function declaration the code
539539/// section belongs to
540540decl: *Decl,
541decl_index: Decl.Index,
542/// Current block depth. Used to calculate the relative difference between a break
543/// and block
544block_depth: u32 = 0,
541545air: Air,
542546liveness: Liveness,
543547gpa: mem.Allocator,
......@@ -559,9 +563,6 @@ local_index: u32 = 0,
559563arg_index: u32 = 0,
560564/// If codegen fails, an error messages will be allocated and saved in `err_msg`
561565err_msg: *Module.ErrorMsg,
562/// Current block depth. Used to calculate the relative difference between a break
563/// and block
564block_depth: u32 = 0,
565566/// List of all locals' types generated throughout this declaration
566567/// used to emit locals count at start of 'code' section.
567568locals: std.ArrayListUnmanaged(u8),
......@@ -644,7 +645,7 @@ fn resolveInst(self: *Self, ref: Air.Inst.Ref) InnerError!WValue {
644645 // In the other cases, we will simply lower the constant to a value that fits
645646 // into a single local (such as a pointer, integer, bool, etc).
646647 const result = if (isByRef(ty, self.target)) blk: {
647 const sym_index = try self.bin_file.lowerUnnamedConst(self.decl, .{ .ty = ty, .val = val });
648 const sym_index = try self.bin_file.lowerUnnamedConst(.{ .ty = ty, .val = val }, self.decl_index);
648649 break :blk WValue{ .memory = sym_index };
649650 } else try self.lowerConstant(val, ty);
650651
......@@ -838,7 +839,8 @@ pub fn generate(
838839 .liveness = liveness,
839840 .values = .{},
840841 .code = code,
841 .decl = func.owner_decl,
842 .decl_index = func.owner_decl,
843 .decl = bin_file.options.module.?.declPtr(func.owner_decl),
842844 .err_msg = undefined,
843845 .locals = .{},
844846 .target = bin_file.options.target,
......@@ -1022,8 +1024,9 @@ fn allocStack(self: *Self, ty: Type) !WValue {
10221024 }
10231025
10241026 const abi_size = std.math.cast(u32, ty.abiSize(self.target)) catch {
1027 const module = self.bin_file.base.options.module.?;
10251028 return self.fail("Type {} with ABI size of {d} exceeds stack frame size", .{
1026 ty.fmt(self.target), ty.abiSize(self.target),
1029 ty.fmt(module), ty.abiSize(self.target),
10271030 });
10281031 };
10291032 const abi_align = ty.abiAlignment(self.target);
......@@ -1056,8 +1059,9 @@ fn allocStackPtr(self: *Self, inst: Air.Inst.Index) !WValue {
10561059
10571060 const abi_alignment = ptr_ty.ptrAlignment(self.target);
10581061 const abi_size = std.math.cast(u32, pointee_ty.abiSize(self.target)) catch {
1062 const module = self.bin_file.base.options.module.?;
10591063 return self.fail("Type {} with ABI size of {d} exceeds stack frame size", .{
1060 pointee_ty.fmt(self.target), pointee_ty.abiSize(self.target),
1064 pointee_ty.fmt(module), pointee_ty.abiSize(self.target),
10611065 });
10621066 };
10631067 if (abi_alignment > self.stack_alignment) {
......@@ -1542,20 +1546,21 @@ fn airCall(self: *Self, inst: Air.Inst.Index, modifier: std.builtin.CallOptions.
15421546 const ret_ty = fn_ty.fnReturnType();
15431547 const first_param_sret = isByRef(ret_ty, self.target);
15441548
1545 const target: ?*Decl = blk: {
1549 const callee: ?*Decl = blk: {
15461550 const func_val = self.air.value(pl_op.operand) orelse break :blk null;
1551 const module = self.bin_file.base.options.module.?;
15471552
15481553 if (func_val.castTag(.function)) |func| {
1549 break :blk func.data.owner_decl;
1554 break :blk module.declPtr(func.data.owner_decl);
15501555 } else if (func_val.castTag(.extern_fn)) |extern_fn| {
1551 const ext_decl = extern_fn.data.owner_decl;
1556 const ext_decl = module.declPtr(extern_fn.data.owner_decl);
15521557 var func_type = try genFunctype(self.gpa, ext_decl.ty, self.target);
15531558 defer func_type.deinit(self.gpa);
15541559 ext_decl.fn_link.wasm.type_index = try self.bin_file.putOrGetFuncType(func_type);
15551560 try self.bin_file.addOrUpdateImport(ext_decl);
15561561 break :blk ext_decl;
15571562 } else if (func_val.castTag(.decl_ref)) |decl_ref| {
1558 break :blk decl_ref.data;
1563 break :blk module.declPtr(decl_ref.data);
15591564 }
15601565 return self.fail("Expected a function, but instead found type '{s}'", .{func_val.tag()});
15611566 };
......@@ -1580,7 +1585,7 @@ fn airCall(self: *Self, inst: Air.Inst.Index, modifier: std.builtin.CallOptions.
15801585 }
15811586 }
15821587
1583 if (target) |direct| {
1588 if (callee) |direct| {
15841589 try self.addLabel(.call, direct.link.wasm.sym_index);
15851590 } else {
15861591 // in this case we call a function pointer
......@@ -1837,16 +1842,16 @@ fn wrapBinOp(self: *Self, lhs: WValue, rhs: WValue, ty: Type, op: Op) InnerError
18371842fn lowerParentPtr(self: *Self, ptr_val: Value, ptr_child_ty: Type) InnerError!WValue {
18381843 switch (ptr_val.tag()) {
18391844 .decl_ref_mut => {
1840 const decl = ptr_val.castTag(.decl_ref_mut).?.data.decl;
1841 return self.lowerParentPtrDecl(ptr_val, decl);
1845 const decl_index = ptr_val.castTag(.decl_ref_mut).?.data.decl_index;
1846 return self.lowerParentPtrDecl(ptr_val, decl_index);
18421847 },
18431848 .decl_ref => {
1844 const decl = ptr_val.castTag(.decl_ref).?.data;
1845 return self.lowerParentPtrDecl(ptr_val, decl);
1849 const decl_index = ptr_val.castTag(.decl_ref).?.data;
1850 return self.lowerParentPtrDecl(ptr_val, decl_index);
18461851 },
18471852 .variable => {
1848 const decl = ptr_val.castTag(.variable).?.data.owner_decl;
1849 return self.lowerParentPtrDecl(ptr_val, decl);
1853 const decl_index = ptr_val.castTag(.variable).?.data.owner_decl;
1854 return self.lowerParentPtrDecl(ptr_val, decl_index);
18501855 },
18511856 .field_ptr => {
18521857 const field_ptr = ptr_val.castTag(.field_ptr).?.data;
......@@ -1918,24 +1923,31 @@ fn lowerParentPtr(self: *Self, ptr_val: Value, ptr_child_ty: Type) InnerError!WV
19181923 }
19191924}
19201925
1921fn lowerParentPtrDecl(self: *Self, ptr_val: Value, decl: *Module.Decl) InnerError!WValue {
1922 decl.markAlive();
1926fn lowerParentPtrDecl(self: *Self, ptr_val: Value, decl_index: Module.Decl.Index) InnerError!WValue {
1927 const module = self.bin_file.base.options.module.?;
1928 const decl = module.declPtr(decl_index);
1929 module.markDeclAlive(decl);
19231930 var ptr_ty_payload: Type.Payload.ElemType = .{
19241931 .base = .{ .tag = .single_mut_pointer },
19251932 .data = decl.ty,
19261933 };
19271934 const ptr_ty = Type.initPayload(&ptr_ty_payload.base);
1928 return self.lowerDeclRefValue(.{ .ty = ptr_ty, .val = ptr_val }, decl);
1935 return self.lowerDeclRefValue(.{ .ty = ptr_ty, .val = ptr_val }, decl_index);
19291936}
19301937
1931fn lowerDeclRefValue(self: *Self, tv: TypedValue, decl: *Module.Decl) InnerError!WValue {
1938fn lowerDeclRefValue(self: *Self, tv: TypedValue, decl_index: Module.Decl.Index) InnerError!WValue {
19321939 if (tv.ty.isSlice()) {
1933 return WValue{ .memory = try self.bin_file.lowerUnnamedConst(decl, tv) };
1934 } else if (decl.ty.zigTypeTag() != .Fn and !decl.ty.hasRuntimeBitsIgnoreComptime()) {
1940 return WValue{ .memory = try self.bin_file.lowerUnnamedConst(tv, decl_index) };
1941 }
1942
1943 const module = self.bin_file.base.options.module.?;
1944 const decl = module.declPtr(decl_index);
1945 if (decl.ty.zigTypeTag() != .Fn and !decl.ty.hasRuntimeBitsIgnoreComptime()) {
19351946 return WValue{ .imm32 = 0xaaaaaaaa };
19361947 }
19371948
1938 decl.markAlive();
1949 module.markDeclAlive(decl);
1950
19391951 const target_sym_index = decl.link.wasm.sym_index;
19401952 if (decl.ty.zigTypeTag() == .Fn) {
19411953 try self.bin_file.addTableFunction(target_sym_index);
......@@ -1946,12 +1958,12 @@ fn lowerDeclRefValue(self: *Self, tv: TypedValue, decl: *Module.Decl) InnerError
19461958fn lowerConstant(self: *Self, val: Value, ty: Type) InnerError!WValue {
19471959 if (val.isUndefDeep()) return self.emitUndefined(ty);
19481960 if (val.castTag(.decl_ref)) |decl_ref| {
1949 const decl = decl_ref.data;
1950 return self.lowerDeclRefValue(.{ .ty = ty, .val = val }, decl);
1961 const decl_index = decl_ref.data;
1962 return self.lowerDeclRefValue(.{ .ty = ty, .val = val }, decl_index);
19511963 }
1952 if (val.castTag(.decl_ref_mut)) |decl_ref| {
1953 const decl = decl_ref.data.decl;
1954 return self.lowerDeclRefValue(.{ .ty = ty, .val = val }, decl);
1964 if (val.castTag(.decl_ref_mut)) |decl_ref_mut| {
1965 const decl_index = decl_ref_mut.data.decl_index;
1966 return self.lowerDeclRefValue(.{ .ty = ty, .val = val }, decl_index);
19551967 }
19561968
19571969 const target = self.target;
......@@ -2347,8 +2359,9 @@ fn airStructFieldPtr(self: *Self, inst: Air.Inst.Index) InnerError!WValue {
23472359 const struct_ptr = try self.resolveInst(extra.data.struct_operand);
23482360 const struct_ty = self.air.typeOf(extra.data.struct_operand).childType();
23492361 const offset = std.math.cast(u32, struct_ty.structFieldOffset(extra.data.field_index, self.target)) catch {
2362 const module = self.bin_file.base.options.module.?;
23502363 return self.fail("Field type '{}' too big to fit into stack frame", .{
2351 struct_ty.structFieldType(extra.data.field_index).fmt(self.target),
2364 struct_ty.structFieldType(extra.data.field_index).fmt(module),
23522365 });
23532366 };
23542367 return self.structFieldPtr(struct_ptr, offset);
......@@ -2360,8 +2373,9 @@ fn airStructFieldPtrIndex(self: *Self, inst: Air.Inst.Index, index: u32) InnerEr
23602373 const struct_ty = self.air.typeOf(ty_op.operand).childType();
23612374 const field_ty = struct_ty.structFieldType(index);
23622375 const offset = std.math.cast(u32, struct_ty.structFieldOffset(index, self.target)) catch {
2376 const module = self.bin_file.base.options.module.?;
23632377 return self.fail("Field type '{}' too big to fit into stack frame", .{
2364 field_ty.fmt(self.target),
2378 field_ty.fmt(module),
23652379 });
23662380 };
23672381 return self.structFieldPtr(struct_ptr, offset);
......@@ -2387,7 +2401,8 @@ fn airStructFieldVal(self: *Self, inst: Air.Inst.Index) InnerError!WValue {
23872401 const field_ty = struct_ty.structFieldType(field_index);
23882402 if (!field_ty.hasRuntimeBitsIgnoreComptime()) return WValue{ .none = {} };
23892403 const offset = std.math.cast(u32, struct_ty.structFieldOffset(field_index, self.target)) catch {
2390 return self.fail("Field type '{}' too big to fit into stack frame", .{field_ty.fmt(self.target)});
2404 const module = self.bin_file.base.options.module.?;
2405 return self.fail("Field type '{}' too big to fit into stack frame", .{field_ty.fmt(module)});
23912406 };
23922407
23932408 if (isByRef(field_ty, self.target)) {
......@@ -2782,7 +2797,8 @@ fn airOptionalPayloadPtrSet(self: *Self, inst: Air.Inst.Index) InnerError!WValue
27822797 }
27832798
27842799 const offset = std.math.cast(u32, opt_ty.abiSize(self.target) - payload_ty.abiSize(self.target)) catch {
2785 return self.fail("Optional type {} too big to fit into stack frame", .{opt_ty.fmt(self.target)});
2800 const module = self.bin_file.base.options.module.?;
2801 return self.fail("Optional type {} too big to fit into stack frame", .{opt_ty.fmt(module)});
27862802 };
27872803
27882804 try self.emitWValue(operand);
......@@ -2811,7 +2827,8 @@ fn airWrapOptional(self: *Self, inst: Air.Inst.Index) InnerError!WValue {
28112827 return operand;
28122828 }
28132829 const offset = std.math.cast(u32, op_ty.abiSize(self.target) - payload_ty.abiSize(self.target)) catch {
2814 return self.fail("Optional type {} too big to fit into stack frame", .{op_ty.fmt(self.target)});
2830 const module = self.bin_file.base.options.module.?;
2831 return self.fail("Optional type {} too big to fit into stack frame", .{op_ty.fmt(module)});
28152832 };
28162833
28172834 // Create optional type, set the non-null bit, and store the operand inside the optional type
src/arch/x86_64/CodeGen.zig+32-21
......@@ -309,8 +309,10 @@ pub fn generate(
309309 @panic("Attempted to compile for architecture that was disabled by build configuration");
310310 }
311311
312 assert(module_fn.owner_decl.has_tv);
313 const fn_type = module_fn.owner_decl.ty;
312 const mod = bin_file.options.module.?;
313 const fn_owner_decl = mod.declPtr(module_fn.owner_decl);
314 assert(fn_owner_decl.has_tv);
315 const fn_type = fn_owner_decl.ty;
314316
315317 var branch_stack = std.ArrayList(Branch).init(bin_file.allocator);
316318 defer {
......@@ -396,14 +398,14 @@ pub fn generate(
396398
397399 if (builtin.mode == .Debug and bin_file.options.module.?.comp.verbose_mir) {
398400 const w = std.io.getStdErr().writer();
399 w.print("# Begin Function MIR: {s}:\n", .{module_fn.owner_decl.name}) catch {};
401 w.print("# Begin Function MIR: {s}:\n", .{fn_owner_decl.name}) catch {};
400402 const PrintMir = @import("PrintMir.zig");
401403 const print = PrintMir{
402404 .mir = mir,
403405 .bin_file = bin_file,
404406 };
405407 print.printMir(w, function.mir_to_air_map, air) catch {}; // we don't care if the debug printing fails
406 w.print("# End Function MIR: {s}\n\n", .{module_fn.owner_decl.name}) catch {};
408 w.print("# End Function MIR: {s}\n\n", .{fn_owner_decl.name}) catch {};
407409 }
408410
409411 if (function.err_msg) |em| {
......@@ -915,9 +917,9 @@ fn allocMemPtr(self: *Self, inst: Air.Inst.Index) !u32 {
915917 return self.allocMem(inst, @sizeOf(usize), @alignOf(usize));
916918 }
917919
918 const target = self.target.*;
919920 const abi_size = math.cast(u32, elem_ty.abiSize(self.target.*)) catch {
920 return self.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(target)});
921 const mod = self.bin_file.options.module.?;
922 return self.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(mod)});
921923 };
922924 // TODO swap this for inst.ty.ptrAlign
923925 const abi_align = ptr_ty.ptrAlignment(self.target.*);
......@@ -926,9 +928,9 @@ fn allocMemPtr(self: *Self, inst: Air.Inst.Index) !u32 {
926928
927929fn allocRegOrMem(self: *Self, inst: Air.Inst.Index, reg_ok: bool) !MCValue {
928930 const elem_ty = self.air.typeOfIndex(inst);
929 const target = self.target.*;
930931 const abi_size = math.cast(u32, elem_ty.abiSize(self.target.*)) catch {
931 return self.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(target)});
932 const mod = self.bin_file.options.module.?;
933 return self.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(mod)});
932934 };
933935 const abi_align = elem_ty.abiAlignment(self.target.*);
934936 if (abi_align > self.stack_align)
......@@ -2650,6 +2652,8 @@ fn loadMemPtrIntoRegister(self: *Self, reg: Register, ptr_ty: Type, ptr: MCValue
26502652 .direct_load => 0b01,
26512653 else => unreachable,
26522654 };
2655 const mod = self.bin_file.options.module.?;
2656 const fn_owner_decl = mod.declPtr(self.mod_fn.owner_decl);
26532657 _ = try self.addInst(.{
26542658 .tag = .lea_pie,
26552659 .ops = (Mir.Ops{
......@@ -2658,7 +2662,7 @@ fn loadMemPtrIntoRegister(self: *Self, reg: Register, ptr_ty: Type, ptr: MCValue
26582662 }).encode(),
26592663 .data = .{
26602664 .load_reloc = .{
2661 .atom_index = self.mod_fn.owner_decl.link.macho.local_sym_index,
2665 .atom_index = fn_owner_decl.link.macho.local_sym_index,
26622666 .sym_index = sym_index,
26632667 },
26642668 },
......@@ -3583,17 +3587,19 @@ fn airCall(self: *Self, inst: Air.Inst.Index, modifier: std.builtin.CallOptions.
35833587
35843588 // Due to incremental compilation, how function calls are generated depends
35853589 // on linking.
3590 const mod = self.bin_file.options.module.?;
35863591 if (self.bin_file.tag == link.File.Elf.base_tag or self.bin_file.tag == link.File.Coff.base_tag) {
35873592 if (self.air.value(callee)) |func_value| {
35883593 if (func_value.castTag(.function)) |func_payload| {
35893594 const func = func_payload.data;
35903595 const ptr_bits = self.target.cpu.arch.ptrBitWidth();
35913596 const ptr_bytes: u64 = @divExact(ptr_bits, 8);
3597 const fn_owner_decl = mod.declPtr(func.owner_decl);
35923598 const got_addr = if (self.bin_file.cast(link.File.Elf)) |elf_file| blk: {
35933599 const got = &elf_file.program_headers.items[elf_file.phdr_got_index.?];
3594 break :blk @intCast(u32, got.p_vaddr + func.owner_decl.link.elf.offset_table_index * ptr_bytes);
3600 break :blk @intCast(u32, got.p_vaddr + fn_owner_decl.link.elf.offset_table_index * ptr_bytes);
35953601 } else if (self.bin_file.cast(link.File.Coff)) |coff_file|
3596 @intCast(u32, coff_file.offset_table_virtual_address + func.owner_decl.link.coff.offset_table_index * ptr_bytes)
3602 @intCast(u32, coff_file.offset_table_virtual_address + fn_owner_decl.link.coff.offset_table_index * ptr_bytes)
35973603 else
35983604 unreachable;
35993605 _ = try self.addInst(.{
......@@ -3625,8 +3631,9 @@ fn airCall(self: *Self, inst: Air.Inst.Index, modifier: std.builtin.CallOptions.
36253631 if (self.air.value(callee)) |func_value| {
36263632 if (func_value.castTag(.function)) |func_payload| {
36273633 const func = func_payload.data;
3634 const fn_owner_decl = mod.declPtr(func.owner_decl);
36283635 try self.genSetReg(Type.initTag(.usize), .rax, .{
3629 .got_load = func.owner_decl.link.macho.local_sym_index,
3636 .got_load = fn_owner_decl.link.macho.local_sym_index,
36303637 });
36313638 // callq *%rax
36323639 _ = try self.addInst(.{
......@@ -3639,7 +3646,7 @@ fn airCall(self: *Self, inst: Air.Inst.Index, modifier: std.builtin.CallOptions.
36393646 });
36403647 } else if (func_value.castTag(.extern_fn)) |func_payload| {
36413648 const extern_fn = func_payload.data;
3642 const decl_name = extern_fn.owner_decl.name;
3649 const decl_name = mod.declPtr(extern_fn.owner_decl).name;
36433650 if (extern_fn.lib_name) |lib_name| {
36443651 log.debug("TODO enforce that '{s}' is expected in '{s}' library", .{
36453652 decl_name,
......@@ -3652,7 +3659,7 @@ fn airCall(self: *Self, inst: Air.Inst.Index, modifier: std.builtin.CallOptions.
36523659 .ops = undefined,
36533660 .data = .{
36543661 .extern_fn = .{
3655 .atom_index = self.mod_fn.owner_decl.link.macho.local_sym_index,
3662 .atom_index = mod.declPtr(self.mod_fn.owner_decl).link.macho.local_sym_index,
36563663 .sym_name = n_strx,
36573664 },
36583665 },
......@@ -3680,7 +3687,7 @@ fn airCall(self: *Self, inst: Air.Inst.Index, modifier: std.builtin.CallOptions.
36803687 const ptr_bits = self.target.cpu.arch.ptrBitWidth();
36813688 const ptr_bytes: u64 = @divExact(ptr_bits, 8);
36823689 const got_addr = p9.bases.data;
3683 const got_index = func_payload.data.owner_decl.link.plan9.got_index.?;
3690 const got_index = mod.declPtr(func_payload.data.owner_decl).link.plan9.got_index.?;
36843691 const fn_got_addr = got_addr + got_index * ptr_bytes;
36853692 _ = try self.addInst(.{
36863693 .tag = .call,
......@@ -4012,9 +4019,11 @@ fn addDbgInfoTypeReloc(self: *Self, ty: Type) !void {
40124019 const dbg_info = &dw.dbg_info;
40134020 const index = dbg_info.items.len;
40144021 try dbg_info.resize(index + 4); // DW.AT.type, DW.FORM.ref4
4022 const mod = self.bin_file.options.module.?;
4023 const fn_owner_decl = mod.declPtr(self.mod_fn.owner_decl);
40154024 const atom = switch (self.bin_file.tag) {
4016 .elf => &self.mod_fn.owner_decl.link.elf.dbg_info_atom,
4017 .macho => &self.mod_fn.owner_decl.link.macho.dbg_info_atom,
4025 .elf => &fn_owner_decl.link.elf.dbg_info_atom,
4026 .macho => &fn_owner_decl.link.macho.dbg_info_atom,
40184027 else => unreachable,
40194028 };
40204029 try dw.addTypeReloc(atom, ty, @intCast(u32, index), null);
......@@ -6124,7 +6133,7 @@ fn limitImmediateType(self: *Self, operand: Air.Inst.Ref, comptime T: type) !MCV
61246133 return mcv;
61256134}
61266135
6127fn lowerDeclRef(self: *Self, tv: TypedValue, decl: *Module.Decl) InnerError!MCValue {
6136fn lowerDeclRef(self: *Self, tv: TypedValue, decl_index: Module.Decl.Index) InnerError!MCValue {
61286137 log.debug("lowerDeclRef: ty = {}, val = {}", .{ tv.ty.fmtDebug(), tv.val.fmtDebug() });
61296138 const ptr_bits = self.target.cpu.arch.ptrBitWidth();
61306139 const ptr_bytes: u64 = @divExact(ptr_bits, 8);
......@@ -6137,7 +6146,9 @@ fn lowerDeclRef(self: *Self, tv: TypedValue, decl: *Module.Decl) InnerError!MCVa
61376146 }
61386147 }
61396148
6140 decl.markAlive();
6149 const module = self.bin_file.options.module.?;
6150 const decl = module.declPtr(decl_index);
6151 module.markDeclAlive(decl);
61416152
61426153 if (self.bin_file.cast(link.File.Elf)) |elf_file| {
61436154 const got = &elf_file.program_headers.items[elf_file.phdr_got_index.?];
......@@ -6152,7 +6163,7 @@ fn lowerDeclRef(self: *Self, tv: TypedValue, decl: *Module.Decl) InnerError!MCVa
61526163 const got_addr = coff_file.offset_table_virtual_address + decl.link.coff.offset_table_index * ptr_bytes;
61536164 return MCValue{ .memory = got_addr };
61546165 } else if (self.bin_file.cast(link.File.Plan9)) |p9| {
6155 try p9.seeDecl(decl);
6166 try p9.seeDecl(decl_index);
61566167 const got_addr = p9.bases.data + decl.link.plan9.got_index.? * ptr_bytes;
61576168 return MCValue{ .memory = got_addr };
61586169 } else {
......@@ -6189,7 +6200,7 @@ fn genTypedValue(self: *Self, typed_value: TypedValue) InnerError!MCValue {
61896200 return self.lowerDeclRef(typed_value, payload.data);
61906201 }
61916202 if (typed_value.val.castTag(.decl_ref_mut)) |payload| {
6192 return self.lowerDeclRef(typed_value, payload.data.decl);
6203 return self.lowerDeclRef(typed_value, payload.data.decl_index);
61936204 }
61946205
61956206 const target = self.target.*;
src/codegen.zig+15-9
......@@ -347,7 +347,9 @@ pub fn generateSymbol(
347347
348348 switch (container_ptr.tag()) {
349349 .decl_ref => {
350 const decl = container_ptr.castTag(.decl_ref).?.data;
350 const decl_index = container_ptr.castTag(.decl_ref).?.data;
351 const mod = bin_file.options.module.?;
352 const decl = mod.declPtr(decl_index);
351353 const addend = blk: {
352354 switch (decl.ty.tag()) {
353355 .@"struct" => {
......@@ -364,7 +366,7 @@ pub fn generateSymbol(
364366 },
365367 }
366368 };
367 return lowerDeclRef(bin_file, src_loc, typed_value, decl, code, debug_output, .{
369 return lowerDeclRef(bin_file, src_loc, typed_value, decl_index, code, debug_output, .{
368370 .parent_atom_index = reloc_info.parent_atom_index,
369371 .addend = (reloc_info.addend orelse 0) + addend,
370372 });
......@@ -400,8 +402,8 @@ pub fn generateSymbol(
400402
401403 switch (array_ptr.tag()) {
402404 .decl_ref => {
403 const decl = array_ptr.castTag(.decl_ref).?.data;
404 return lowerDeclRef(bin_file, src_loc, typed_value, decl, code, debug_output, .{
405 const decl_index = array_ptr.castTag(.decl_ref).?.data;
406 return lowerDeclRef(bin_file, src_loc, typed_value, decl_index, code, debug_output, .{
405407 .parent_atom_index = reloc_info.parent_atom_index,
406408 .addend = (reloc_info.addend orelse 0) + addend,
407409 });
......@@ -589,7 +591,8 @@ pub fn generateSymbol(
589591 }
590592
591593 const union_ty = typed_value.ty.cast(Type.Payload.Union).?.data;
592 const field_index = union_ty.tag_ty.enumTagFieldIndex(union_obj.tag, target).?;
594 const mod = bin_file.options.module.?;
595 const field_index = union_ty.tag_ty.enumTagFieldIndex(union_obj.tag, mod).?;
593596 assert(union_ty.haveFieldTypes());
594597 const field_ty = union_ty.fields.values()[field_index].ty;
595598 if (!field_ty.hasRuntimeBits()) {
......@@ -772,12 +775,13 @@ fn lowerDeclRef(
772775 bin_file: *link.File,
773776 src_loc: Module.SrcLoc,
774777 typed_value: TypedValue,
775 decl: *Module.Decl,
778 decl_index: Module.Decl.Index,
776779 code: *std.ArrayList(u8),
777780 debug_output: DebugInfoOutput,
778781 reloc_info: RelocInfo,
779782) GenerateSymbolError!Result {
780783 const target = bin_file.options.target;
784 const module = bin_file.options.module.?;
781785 if (typed_value.ty.isSlice()) {
782786 // generate ptr
783787 var buf: Type.SlicePtrFieldTypeBuffer = undefined;
......@@ -796,7 +800,7 @@ fn lowerDeclRef(
796800 // generate length
797801 var slice_len: Value.Payload.U64 = .{
798802 .base = .{ .tag = .int_u64 },
799 .data = typed_value.val.sliceLen(target),
803 .data = typed_value.val.sliceLen(module),
800804 };
801805 switch (try generateSymbol(bin_file, src_loc, .{
802806 .ty = Type.usize,
......@@ -813,14 +817,16 @@ fn lowerDeclRef(
813817 }
814818
815819 const ptr_width = target.cpu.arch.ptrBitWidth();
820 const decl = module.declPtr(decl_index);
816821 const is_fn_body = decl.ty.zigTypeTag() == .Fn;
817822 if (!is_fn_body and !decl.ty.hasRuntimeBits()) {
818823 try code.writer().writeByteNTimes(0xaa, @divExact(ptr_width, 8));
819824 return Result{ .appended = {} };
820825 }
821826
822 decl.markAlive();
823 const vaddr = try bin_file.getDeclVAddr(decl, .{
827 module.markDeclAlive(decl);
828
829 const vaddr = try bin_file.getDeclVAddr(decl_index, .{
824830 .parent_atom_index = reloc_info.parent_atom_index,
825831 .offset = code.items.len,
826832 .addend = reloc_info.addend orelse 0,
src/codegen/c.zig+43-44
......@@ -32,8 +32,8 @@ pub const CValue = union(enum) {
3232 /// Index into the parameters
3333 arg: usize,
3434 /// By-value
35 decl: *Decl,
36 decl_ref: *Decl,
35 decl: Decl.Index,
36 decl_ref: Decl.Index,
3737 /// An undefined (void *) pointer (cannot be dereferenced)
3838 undefined_ptr: void,
3939 /// Render the slice as an identifier (using fmtIdent)
......@@ -58,7 +58,7 @@ pub const TypedefMap = std.ArrayHashMap(
5858
5959const FormatTypeAsCIdentContext = struct {
6060 ty: Type,
61 target: std.Target,
61 mod: *Module,
6262};
6363
6464/// TODO make this not cut off at 128 bytes
......@@ -71,14 +71,14 @@ fn formatTypeAsCIdentifier(
7171 _ = fmt;
7272 _ = options;
7373 var buffer = [1]u8{0} ** 128;
74 var buf = std.fmt.bufPrint(&buffer, "{}", .{data.ty.fmt(data.target)}) catch &buffer;
74 var buf = std.fmt.bufPrint(&buffer, "{}", .{data.ty.fmt(data.mod)}) catch &buffer;
7575 return formatIdent(buf, "", .{}, writer);
7676}
7777
78pub fn typeToCIdentifier(ty: Type, target: std.Target) std.fmt.Formatter(formatTypeAsCIdentifier) {
78pub fn typeToCIdentifier(ty: Type, mod: *Module) std.fmt.Formatter(formatTypeAsCIdentifier) {
7979 return .{ .data = .{
8080 .ty = ty,
81 .target = target,
81 .mod = mod,
8282 } };
8383}
8484
......@@ -349,6 +349,7 @@ pub const DeclGen = struct {
349349 gpa: std.mem.Allocator,
350350 module: *Module,
351351 decl: *Decl,
352 decl_index: Decl.Index,
352353 fwd_decl: std.ArrayList(u8),
353354 error_msg: ?*Module.ErrorMsg,
354355 /// The key of this map is Type which has references to typedefs_arena.
......@@ -376,10 +377,8 @@ pub const DeclGen = struct {
376377 writer: anytype,
377378 ty: Type,
378379 val: Value,
379 decl: *Decl,
380 decl_index: Decl.Index,
380381 ) error{ OutOfMemory, AnalysisFail }!void {
381 const target = dg.module.getTarget();
382
383382 if (ty.isSlice()) {
384383 try writer.writeByte('(');
385384 try dg.renderTypecast(writer, ty);
......@@ -387,11 +386,12 @@ pub const DeclGen = struct {
387386 var buf: Type.SlicePtrFieldTypeBuffer = undefined;
388387 try dg.renderValue(writer, ty.slicePtrFieldType(&buf), val.slicePtr());
389388 try writer.writeAll(", ");
390 try writer.print("{d}", .{val.sliceLen(target)});
389 try writer.print("{d}", .{val.sliceLen(dg.module)});
391390 try writer.writeAll("}");
392391 return;
393392 }
394393
394 const decl = dg.module.declPtr(decl_index);
395395 assert(decl.has_tv);
396396 // We shouldn't cast C function pointers as this is UB (when you call
397397 // them). The analysis until now should ensure that the C function
......@@ -399,21 +399,21 @@ pub const DeclGen = struct {
399399 // somewhere and we should let the C compiler tell us about it.
400400 if (ty.castPtrToFn() == null) {
401401 // Determine if we must pointer cast.
402 if (ty.eql(decl.ty, target)) {
402 if (ty.eql(decl.ty, dg.module)) {
403403 try writer.writeByte('&');
404 try dg.renderDeclName(writer, decl);
404 try dg.renderDeclName(writer, decl_index);
405405 return;
406406 }
407407
408408 try writer.writeAll("((");
409409 try dg.renderTypecast(writer, ty);
410410 try writer.writeAll(")&");
411 try dg.renderDeclName(writer, decl);
411 try dg.renderDeclName(writer, decl_index);
412412 try writer.writeByte(')');
413413 return;
414414 }
415415
416 try dg.renderDeclName(writer, decl);
416 try dg.renderDeclName(writer, decl_index);
417417 }
418418
419419 fn renderInt128(
......@@ -471,13 +471,13 @@ pub const DeclGen = struct {
471471 try writer.writeByte(')');
472472 switch (ptr_val.tag()) {
473473 .decl_ref_mut, .decl_ref, .variable => {
474 const decl = switch (ptr_val.tag()) {
474 const decl_index = switch (ptr_val.tag()) {
475475 .decl_ref => ptr_val.castTag(.decl_ref).?.data,
476 .decl_ref_mut => ptr_val.castTag(.decl_ref_mut).?.data.decl,
476 .decl_ref_mut => ptr_val.castTag(.decl_ref_mut).?.data.decl_index,
477477 .variable => ptr_val.castTag(.variable).?.data.owner_decl,
478478 else => unreachable,
479479 };
480 try dg.renderDeclValue(writer, ptr_ty, ptr_val, decl);
480 try dg.renderDeclValue(writer, ptr_ty, ptr_val, decl_index);
481481 },
482482 .field_ptr => {
483483 const field_ptr = ptr_val.castTag(.field_ptr).?.data;
......@@ -685,7 +685,7 @@ pub const DeclGen = struct {
685685 var index: usize = 0;
686686 while (index < ai.len) : (index += 1) {
687687 if (index != 0) try writer.writeAll(",");
688 const elem_val = try val.elemValue(arena_allocator, index);
688 const elem_val = try val.elemValue(dg.module, arena_allocator, index);
689689 try dg.renderValue(writer, ai.elem_type, elem_val);
690690 }
691691 if (ai.sentinel) |s| {
......@@ -837,7 +837,7 @@ pub const DeclGen = struct {
837837 try writer.writeAll(".payload = {");
838838 }
839839
840 const index = union_ty.tag_ty.enumTagFieldIndex(union_obj.tag, target).?;
840 const index = union_ty.tag_ty.enumTagFieldIndex(union_obj.tag, dg.module).?;
841841 const field_ty = ty.unionFields().values()[index].ty;
842842 const field_name = ty.unionFields().keys()[index];
843843 if (field_ty.hasRuntimeBits()) {
......@@ -889,7 +889,7 @@ pub const DeclGen = struct {
889889 try w.writeAll("void");
890890 }
891891 try w.writeAll(" ");
892 try dg.renderDeclName(w, dg.decl);
892 try dg.renderDeclName(w, dg.decl_index);
893893 try w.writeAll("(");
894894 const param_len = dg.decl.ty.fnParamLen();
895895
......@@ -927,8 +927,7 @@ pub const DeclGen = struct {
927927 try bw.writeAll(" (*");
928928
929929 const name_start = buffer.items.len;
930 const target = dg.module.getTarget();
931 try bw.print("zig_F_{s})(", .{typeToCIdentifier(t, target)});
930 try bw.print("zig_F_{s})(", .{typeToCIdentifier(t, dg.module)});
932931 const name_end = buffer.items.len - 2;
933932
934933 const param_len = fn_info.param_types.len;
......@@ -982,11 +981,10 @@ pub const DeclGen = struct {
982981
983982 try bw.writeAll("; size_t len; } ");
984983 const name_index = buffer.items.len;
985 const target = dg.module.getTarget();
986984 if (t.isConstPtr()) {
987 try bw.print("zig_L_{s}", .{typeToCIdentifier(child_type, target)});
985 try bw.print("zig_L_{s}", .{typeToCIdentifier(child_type, dg.module)});
988986 } else {
989 try bw.print("zig_M_{s}", .{typeToCIdentifier(child_type, target)});
987 try bw.print("zig_M_{s}", .{typeToCIdentifier(child_type, dg.module)});
990988 }
991989 if (ptr_sentinel) |s| {
992990 try bw.writeAll("_s_");
......@@ -1009,7 +1007,7 @@ pub const DeclGen = struct {
10091007
10101008 fn renderStructTypedef(dg: *DeclGen, t: Type) error{ OutOfMemory, AnalysisFail }![]const u8 {
10111009 const struct_obj = t.castTag(.@"struct").?.data; // Handle 0 bit types elsewhere.
1012 const fqn = try struct_obj.getFullyQualifiedName(dg.typedefs.allocator);
1010 const fqn = try struct_obj.getFullyQualifiedName(dg.module);
10131011 defer dg.typedefs.allocator.free(fqn);
10141012
10151013 var buffer = std.ArrayList(u8).init(dg.typedefs.allocator);
......@@ -1072,8 +1070,7 @@ pub const DeclGen = struct {
10721070 try buffer.appendSlice("} ");
10731071
10741072 const name_start = buffer.items.len;
1075 const target = dg.module.getTarget();
1076 try writer.print("zig_T_{};\n", .{typeToCIdentifier(t, target)});
1073 try writer.print("zig_T_{};\n", .{typeToCIdentifier(t, dg.module)});
10771074
10781075 const rendered = buffer.toOwnedSlice();
10791076 errdefer dg.typedefs.allocator.free(rendered);
......@@ -1090,7 +1087,7 @@ pub const DeclGen = struct {
10901087
10911088 fn renderUnionTypedef(dg: *DeclGen, t: Type) error{ OutOfMemory, AnalysisFail }![]const u8 {
10921089 const union_ty = t.cast(Type.Payload.Union).?.data;
1093 const fqn = try union_ty.getFullyQualifiedName(dg.typedefs.allocator);
1090 const fqn = try union_ty.getFullyQualifiedName(dg.module);
10941091 defer dg.typedefs.allocator.free(fqn);
10951092
10961093 const target = dg.module.getTarget();
......@@ -1157,7 +1154,6 @@ pub const DeclGen = struct {
11571154 try dg.renderTypeAndName(bw, child_type, payload_name, .Mut, 0);
11581155 try bw.writeAll("; uint16_t error; } ");
11591156 const name_index = buffer.items.len;
1160 const target = dg.module.getTarget();
11611157 if (err_set_type.castTag(.error_set_inferred)) |inf_err_set_payload| {
11621158 const func = inf_err_set_payload.data.func;
11631159 try bw.writeAll("zig_E_");
......@@ -1165,7 +1161,7 @@ pub const DeclGen = struct {
11651161 try bw.writeAll(";\n");
11661162 } else {
11671163 try bw.print("zig_E_{s}_{s};\n", .{
1168 typeToCIdentifier(err_set_type, target), typeToCIdentifier(child_type, target),
1164 typeToCIdentifier(err_set_type, dg.module), typeToCIdentifier(child_type, dg.module),
11691165 });
11701166 }
11711167
......@@ -1195,8 +1191,7 @@ pub const DeclGen = struct {
11951191 try dg.renderType(bw, elem_type);
11961192
11971193 const name_start = buffer.items.len + 1;
1198 const target = dg.module.getTarget();
1199 try bw.print(" zig_A_{s}_{d}", .{ typeToCIdentifier(elem_type, target), c_len });
1194 try bw.print(" zig_A_{s}_{d}", .{ typeToCIdentifier(elem_type, dg.module), c_len });
12001195 const name_end = buffer.items.len;
12011196
12021197 try bw.print("[{d}];\n", .{c_len});
......@@ -1224,8 +1219,7 @@ pub const DeclGen = struct {
12241219 try dg.renderTypeAndName(bw, child_type, payload_name, .Mut, 0);
12251220 try bw.writeAll("; bool is_null; } ");
12261221 const name_index = buffer.items.len;
1227 const target = dg.module.getTarget();
1228 try bw.print("zig_Q_{s};\n", .{typeToCIdentifier(child_type, target)});
1222 try bw.print("zig_Q_{s};\n", .{typeToCIdentifier(child_type, dg.module)});
12291223
12301224 const rendered = buffer.toOwnedSlice();
12311225 errdefer dg.typedefs.allocator.free(rendered);
......@@ -1535,16 +1529,17 @@ pub const DeclGen = struct {
15351529 }
15361530 }
15371531
1538 fn renderDeclName(dg: DeclGen, writer: anytype, decl: *Decl) !void {
1539 decl.markAlive();
1532 fn renderDeclName(dg: DeclGen, writer: anytype, decl_index: Decl.Index) !void {
1533 const decl = dg.module.declPtr(decl_index);
1534 dg.module.markDeclAlive(decl);
15401535
1541 if (dg.module.decl_exports.get(decl)) |exports| {
1536 if (dg.module.decl_exports.get(decl_index)) |exports| {
15421537 return writer.writeAll(exports[0].options.name);
15431538 } else if (decl.val.tag() == .extern_fn) {
15441539 return writer.writeAll(mem.sliceTo(decl.name, 0));
15451540 } else {
15461541 const gpa = dg.module.gpa;
1547 const name = try decl.getFullyQualifiedName(gpa);
1542 const name = try decl.getFullyQualifiedName(dg.module);
15481543 defer gpa.free(name);
15491544 return writer.print("{ }", .{fmtIdent(name)});
15501545 }
......@@ -1616,7 +1611,11 @@ pub fn genDecl(o: *Object) !void {
16161611 try fwd_decl_writer.writeAll("zig_threadlocal ");
16171612 }
16181613
1619 const decl_c_value: CValue = if (is_global) .{ .bytes = mem.span(o.dg.decl.name) } else .{ .decl = o.dg.decl };
1614 const decl_c_value: CValue = if (is_global) .{
1615 .bytes = mem.span(o.dg.decl.name),
1616 } else .{
1617 .decl = o.dg.decl_index,
1618 };
16201619
16211620 try o.dg.renderTypeAndName(fwd_decl_writer, o.dg.decl.ty, decl_c_value, .Mut, o.dg.decl.@"align");
16221621 try fwd_decl_writer.writeAll(";\n");
......@@ -1641,7 +1640,7 @@ pub fn genDecl(o: *Object) !void {
16411640 // TODO ask the Decl if it is const
16421641 // https://github.com/ziglang/zig/issues/7582
16431642
1644 const decl_c_value: CValue = .{ .decl = o.dg.decl };
1643 const decl_c_value: CValue = .{ .decl = o.dg.decl_index };
16451644 try o.dg.renderTypeAndName(writer, tv.ty, decl_c_value, .Mut, o.dg.decl.@"align");
16461645
16471646 try writer.writeAll(" = ");
......@@ -2234,13 +2233,12 @@ fn airStore(f: *Function, inst: Air.Inst.Index) !CValue {
22342233 if (src_val_is_undefined)
22352234 return try airStoreUndefined(f, dest_ptr);
22362235
2237 const target = f.object.dg.module.getTarget();
22382236 const writer = f.object.writer();
22392237 if (lhs_child_type.zigTypeTag() == .Array) {
22402238 // For this memcpy to safely work we need the rhs to have the same
22412239 // underlying type as the lhs (i.e. they must both be arrays of the same underlying type).
22422240 const rhs_type = f.air.typeOf(bin_op.rhs);
2243 assert(rhs_type.eql(lhs_child_type, target));
2241 assert(rhs_type.eql(lhs_child_type, f.object.dg.module));
22442242
22452243 // If the source is a constant, writeCValue will emit a brace initialization
22462244 // so work around this by initializing into new local.
......@@ -2780,7 +2778,8 @@ fn airDbgInline(f: *Function, inst: Air.Inst.Index) !CValue {
27802778 const ty_pl = f.air.instructions.items(.data)[inst].ty_pl;
27812779 const writer = f.object.writer();
27822780 const function = f.air.values[ty_pl.payload].castTag(.function).?.data;
2783 try writer.print("/* dbg func:{s} */\n", .{function.owner_decl.name});
2781 const mod = f.object.dg.module;
2782 try writer.print("/* dbg func:{s} */\n", .{mod.declPtr(function.owner_decl).name});
27842783 return CValue.none;
27852784}
27862785
src/codegen/llvm.zig+134-113
......@@ -161,6 +161,7 @@ pub fn targetTriple(allocator: Allocator, target: std.Target) ![:0]u8 {
161161
162162pub const Object = struct {
163163 gpa: Allocator,
164 module: *Module,
164165 llvm_module: *const llvm.Module,
165166 di_builder: ?*llvm.DIBuilder,
166167 /// One of these mappings:
......@@ -181,7 +182,7 @@ pub const Object = struct {
181182 /// version of the name and incorrectly get function not found in the llvm module.
182183 /// * it works for functions not all globals.
183184 /// Therefore, this table keeps track of the mapping.
184 decl_map: std.AutoHashMapUnmanaged(*const Module.Decl, *const llvm.Value),
185 decl_map: std.AutoHashMapUnmanaged(Module.Decl.Index, *const llvm.Value),
185186 /// Maps Zig types to LLVM types. The table memory itself is backed by the GPA of
186187 /// the compiler, but the Type/Value memory here is backed by `type_map_arena`.
187188 /// TODO we need to remove entries from this map in response to incremental compilation
......@@ -340,6 +341,7 @@ pub const Object = struct {
340341
341342 return Object{
342343 .gpa = gpa,
344 .module = options.module.?,
343345 .llvm_module = llvm_module,
344346 .di_map = .{},
345347 .di_builder = opt_di_builder,
......@@ -568,18 +570,20 @@ pub const Object = struct {
568570 air: Air,
569571 liveness: Liveness,
570572 ) !void {
571 const decl = func.owner_decl;
573 const decl_index = func.owner_decl;
574 const decl = module.declPtr(decl_index);
572575
573576 var dg: DeclGen = .{
574577 .context = o.context,
575578 .object = o,
576579 .module = module,
580 .decl_index = decl_index,
577581 .decl = decl,
578582 .err_msg = null,
579583 .gpa = module.gpa,
580584 };
581585
582 const llvm_func = try dg.resolveLlvmFunction(decl);
586 const llvm_func = try dg.resolveLlvmFunction(decl_index);
583587
584588 if (module.align_stack_fns.get(func)) |align_info| {
585589 dg.addFnAttrInt(llvm_func, "alignstack", align_info.alignment);
......@@ -632,7 +636,7 @@ pub const Object = struct {
632636
633637 const line_number = decl.src_line + 1;
634638 const is_internal_linkage = decl.val.tag() != .extern_fn and
635 !dg.module.decl_exports.contains(decl);
639 !dg.module.decl_exports.contains(decl_index);
636640 const noret_bit: c_uint = if (fn_info.return_type.isNoReturn())
637641 llvm.DIFlags.NoReturn
638642 else
......@@ -684,48 +688,51 @@ pub const Object = struct {
684688 fg.genBody(air.getMainBody()) catch |err| switch (err) {
685689 error.CodegenFail => {
686690 decl.analysis = .codegen_failure;
687 try module.failed_decls.put(module.gpa, decl, dg.err_msg.?);
691 try module.failed_decls.put(module.gpa, decl_index, dg.err_msg.?);
688692 dg.err_msg = null;
689693 return;
690694 },
691695 else => |e| return e,
692696 };
693697
694 const decl_exports = module.decl_exports.get(decl) orelse &[0]*Module.Export{};
695 try o.updateDeclExports(module, decl, decl_exports);
698 const decl_exports = module.decl_exports.get(decl_index) orelse &[0]*Module.Export{};
699 try o.updateDeclExports(module, decl_index, decl_exports);
696700 }
697701
698 pub fn updateDecl(self: *Object, module: *Module, decl: *Module.Decl) !void {
702 pub fn updateDecl(self: *Object, module: *Module, decl_index: Module.Decl.Index) !void {
703 const decl = module.declPtr(decl_index);
699704 var dg: DeclGen = .{
700705 .context = self.context,
701706 .object = self,
702707 .module = module,
703708 .decl = decl,
709 .decl_index = decl_index,
704710 .err_msg = null,
705711 .gpa = module.gpa,
706712 };
707713 dg.genDecl() catch |err| switch (err) {
708714 error.CodegenFail => {
709715 decl.analysis = .codegen_failure;
710 try module.failed_decls.put(module.gpa, decl, dg.err_msg.?);
716 try module.failed_decls.put(module.gpa, decl_index, dg.err_msg.?);
711717 dg.err_msg = null;
712718 return;
713719 },
714720 else => |e| return e,
715721 };
716 const decl_exports = module.decl_exports.get(decl) orelse &[0]*Module.Export{};
717 try self.updateDeclExports(module, decl, decl_exports);
722 const decl_exports = module.decl_exports.get(decl_index) orelse &[0]*Module.Export{};
723 try self.updateDeclExports(module, decl_index, decl_exports);
718724 }
719725
720726 pub fn updateDeclExports(
721727 self: *Object,
722 module: *const Module,
723 decl: *const Module.Decl,
728 module: *Module,
729 decl_index: Module.Decl.Index,
724730 exports: []const *Module.Export,
725731 ) !void {
726732 // If the module does not already have the function, we ignore this function call
727733 // because we call `updateDeclExports` at the end of `updateFunc` and `updateDecl`.
728 const llvm_global = self.decl_map.get(decl) orelse return;
734 const llvm_global = self.decl_map.get(decl_index) orelse return;
735 const decl = module.declPtr(decl_index);
729736 if (decl.isExtern()) {
730737 llvm_global.setValueName(decl.name);
731738 llvm_global.setUnnamedAddr(.False);
......@@ -798,7 +805,7 @@ pub const Object = struct {
798805 }
799806 }
800807 } else {
801 const fqn = try decl.getFullyQualifiedName(module.gpa);
808 const fqn = try decl.getFullyQualifiedName(module);
802809 defer module.gpa.free(fqn);
803810 llvm_global.setValueName2(fqn.ptr, fqn.len);
804811 llvm_global.setLinkage(.Internal);
......@@ -814,8 +821,8 @@ pub const Object = struct {
814821 }
815822 }
816823
817 pub fn freeDecl(self: *Object, decl: *Module.Decl) void {
818 const llvm_value = self.decl_map.get(decl) orelse return;
824 pub fn freeDecl(self: *Object, decl_index: Module.Decl.Index) void {
825 const llvm_value = self.decl_map.get(decl_index) orelse return;
819826 llvm_value.deleteGlobal();
820827 }
821828
......@@ -847,7 +854,7 @@ pub const Object = struct {
847854 const gpa = o.gpa;
848855 // Be careful not to reference this `gop` variable after any recursive calls
849856 // to `lowerDebugType`.
850 const gop = try o.di_type_map.getOrPutContext(gpa, ty, .{ .target = o.target });
857 const gop = try o.di_type_map.getOrPutContext(gpa, ty, .{ .mod = o.module });
851858 if (gop.found_existing) {
852859 const annotated = gop.value_ptr.*;
853860 const di_type = annotated.toDIType();
......@@ -860,7 +867,7 @@ pub const Object = struct {
860867 };
861868 return o.lowerDebugTypeImpl(entry, resolve, di_type);
862869 }
863 errdefer assert(o.di_type_map.orderedRemoveContext(ty, .{ .target = o.target }));
870 errdefer assert(o.di_type_map.orderedRemoveContext(ty, .{ .mod = o.module }));
864871 // The Type memory is ephemeral; since we want to store a longer-lived
865872 // reference, we need to copy it here.
866873 gop.key_ptr.* = try ty.copy(o.type_map_arena.allocator());
......@@ -891,7 +898,7 @@ pub const Object = struct {
891898 .Int => {
892899 const info = ty.intInfo(target);
893900 assert(info.bits != 0);
894 const name = try ty.nameAlloc(gpa, target);
901 const name = try ty.nameAlloc(gpa, o.module);
895902 defer gpa.free(name);
896903 const dwarf_encoding: c_uint = switch (info.signedness) {
897904 .signed => DW.ATE.signed,
......@@ -902,13 +909,14 @@ pub const Object = struct {
902909 return di_type;
903910 },
904911 .Enum => {
905 const owner_decl = ty.getOwnerDecl();
912 const owner_decl_index = ty.getOwnerDecl();
913 const owner_decl = o.module.declPtr(owner_decl_index);
906914
907915 if (!ty.hasRuntimeBitsIgnoreComptime()) {
908 const enum_di_ty = try o.makeEmptyNamespaceDIType(owner_decl);
916 const enum_di_ty = try o.makeEmptyNamespaceDIType(owner_decl_index);
909917 // The recursive call to `lowerDebugType` via `makeEmptyNamespaceDIType`
910918 // means we can't use `gop` anymore.
911 try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.initFull(enum_di_ty), .{ .target = o.target });
919 try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.initFull(enum_di_ty), .{ .mod = o.module });
912920 return enum_di_ty;
913921 }
914922
......@@ -938,7 +946,7 @@ pub const Object = struct {
938946 const di_file = try o.getDIFile(gpa, owner_decl.src_namespace.file_scope);
939947 const di_scope = try o.namespaceToDebugScope(owner_decl.src_namespace);
940948
941 const name = try ty.nameAlloc(gpa, target);
949 const name = try ty.nameAlloc(gpa, o.module);
942950 defer gpa.free(name);
943951 var buffer: Type.Payload.Bits = undefined;
944952 const int_ty = ty.intTagType(&buffer);
......@@ -956,12 +964,12 @@ pub const Object = struct {
956964 "",
957965 );
958966 // The recursive call to `lowerDebugType` means we can't use `gop` anymore.
959 try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.initFull(enum_di_ty), .{ .target = o.target });
967 try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.initFull(enum_di_ty), .{ .mod = o.module });
960968 return enum_di_ty;
961969 },
962970 .Float => {
963971 const bits = ty.floatBits(target);
964 const name = try ty.nameAlloc(gpa, target);
972 const name = try ty.nameAlloc(gpa, o.module);
965973 defer gpa.free(name);
966974 const di_type = dib.createBasicType(name, bits, DW.ATE.float);
967975 gop.value_ptr.* = AnnotatedDITypePtr.initFull(di_type);
......@@ -1009,7 +1017,7 @@ pub const Object = struct {
10091017 const bland_ptr_ty = Type.initPayload(&payload.base);
10101018 const ptr_di_ty = try o.lowerDebugType(bland_ptr_ty, resolve);
10111019 // The recursive call to `lowerDebugType` means we can't use `gop` anymore.
1012 try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.init(ptr_di_ty, resolve), .{ .target = o.target });
1020 try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.init(ptr_di_ty, resolve), .{ .mod = o.module });
10131021 return ptr_di_ty;
10141022 }
10151023
......@@ -1018,7 +1026,7 @@ pub const Object = struct {
10181026 const ptr_ty = ty.slicePtrFieldType(&buf);
10191027 const len_ty = Type.usize;
10201028
1021 const name = try ty.nameAlloc(gpa, target);
1029 const name = try ty.nameAlloc(gpa, o.module);
10221030 defer gpa.free(name);
10231031 const di_file: ?*llvm.DIFile = null;
10241032 const line = 0;
......@@ -1089,12 +1097,12 @@ pub const Object = struct {
10891097 );
10901098 dib.replaceTemporary(fwd_decl, full_di_ty);
10911099 // The recursive call to `lowerDebugType` means we can't use `gop` anymore.
1092 try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.initFull(full_di_ty), .{ .target = o.target });
1100 try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.initFull(full_di_ty), .{ .mod = o.module });
10931101 return full_di_ty;
10941102 }
10951103
10961104 const elem_di_ty = try o.lowerDebugType(ptr_info.pointee_type, .fwd);
1097 const name = try ty.nameAlloc(gpa, target);
1105 const name = try ty.nameAlloc(gpa, o.module);
10981106 defer gpa.free(name);
10991107 const ptr_di_ty = dib.createPointerType(
11001108 elem_di_ty,
......@@ -1103,7 +1111,7 @@ pub const Object = struct {
11031111 name,
11041112 );
11051113 // The recursive call to `lowerDebugType` means we can't use `gop` anymore.
1106 try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.initFull(ptr_di_ty), .{ .target = o.target });
1114 try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.initFull(ptr_di_ty), .{ .mod = o.module });
11071115 return ptr_di_ty;
11081116 },
11091117 .Opaque => {
......@@ -1112,9 +1120,10 @@ pub const Object = struct {
11121120 gop.value_ptr.* = AnnotatedDITypePtr.initFull(di_ty);
11131121 return di_ty;
11141122 }
1115 const name = try ty.nameAlloc(gpa, target);
1123 const name = try ty.nameAlloc(gpa, o.module);
11161124 defer gpa.free(name);
1117 const owner_decl = ty.getOwnerDecl();
1125 const owner_decl_index = ty.getOwnerDecl();
1126 const owner_decl = o.module.declPtr(owner_decl_index);
11181127 const opaque_di_ty = dib.createForwardDeclType(
11191128 DW.TAG.structure_type,
11201129 name,
......@@ -1124,7 +1133,7 @@ pub const Object = struct {
11241133 );
11251134 // The recursive call to `lowerDebugType` va `namespaceToDebugScope`
11261135 // means we can't use `gop` anymore.
1127 try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.initFull(opaque_di_ty), .{ .target = o.target });
1136 try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.initFull(opaque_di_ty), .{ .mod = o.module });
11281137 return opaque_di_ty;
11291138 },
11301139 .Array => {
......@@ -1135,7 +1144,7 @@ pub const Object = struct {
11351144 @intCast(c_int, ty.arrayLen()),
11361145 );
11371146 // The recursive call to `lowerDebugType` means we can't use `gop` anymore.
1138 try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.initFull(array_di_ty), .{ .target = o.target });
1147 try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.initFull(array_di_ty), .{ .mod = o.module });
11391148 return array_di_ty;
11401149 },
11411150 .Vector => {
......@@ -1146,11 +1155,11 @@ pub const Object = struct {
11461155 ty.vectorLen(),
11471156 );
11481157 // The recursive call to `lowerDebugType` means we can't use `gop` anymore.
1149 try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.initFull(vector_di_ty), .{ .target = o.target });
1158 try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.initFull(vector_di_ty), .{ .mod = o.module });
11501159 return vector_di_ty;
11511160 },
11521161 .Optional => {
1153 const name = try ty.nameAlloc(gpa, target);
1162 const name = try ty.nameAlloc(gpa, o.module);
11541163 defer gpa.free(name);
11551164 var buf: Type.Payload.ElemType = undefined;
11561165 const child_ty = ty.optionalChild(&buf);
......@@ -1162,7 +1171,7 @@ pub const Object = struct {
11621171 if (ty.isPtrLikeOptional()) {
11631172 const ptr_di_ty = try o.lowerDebugType(child_ty, resolve);
11641173 // The recursive call to `lowerDebugType` means we can't use `gop` anymore.
1165 try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.initFull(ptr_di_ty), .{ .target = o.target });
1174 try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.initFull(ptr_di_ty), .{ .mod = o.module });
11661175 return ptr_di_ty;
11671176 }
11681177
......@@ -1235,7 +1244,7 @@ pub const Object = struct {
12351244 );
12361245 dib.replaceTemporary(fwd_decl, full_di_ty);
12371246 // The recursive call to `lowerDebugType` means we can't use `gop` anymore.
1238 try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.initFull(full_di_ty), .{ .target = o.target });
1247 try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.initFull(full_di_ty), .{ .mod = o.module });
12391248 return full_di_ty;
12401249 },
12411250 .ErrorUnion => {
......@@ -1244,10 +1253,10 @@ pub const Object = struct {
12441253 if (!payload_ty.hasRuntimeBitsIgnoreComptime()) {
12451254 const err_set_di_ty = try o.lowerDebugType(err_set_ty, .full);
12461255 // The recursive call to `lowerDebugType` means we can't use `gop` anymore.
1247 try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.initFull(err_set_di_ty), .{ .target = o.target });
1256 try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.initFull(err_set_di_ty), .{ .mod = o.module });
12481257 return err_set_di_ty;
12491258 }
1250 const name = try ty.nameAlloc(gpa, target);
1259 const name = try ty.nameAlloc(gpa, o.module);
12511260 defer gpa.free(name);
12521261 const di_file: ?*llvm.DIFile = null;
12531262 const line = 0;
......@@ -1332,7 +1341,7 @@ pub const Object = struct {
13321341 );
13331342 dib.replaceTemporary(fwd_decl, full_di_ty);
13341343 // The recursive call to `lowerDebugType` means we can't use `gop` anymore.
1335 try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.initFull(full_di_ty), .{ .target = o.target });
1344 try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.initFull(full_di_ty), .{ .mod = o.module });
13361345 return full_di_ty;
13371346 },
13381347 .ErrorSet => {
......@@ -1344,7 +1353,7 @@ pub const Object = struct {
13441353 },
13451354 .Struct => {
13461355 const compile_unit_scope = o.di_compile_unit.?.toScope();
1347 const name = try ty.nameAlloc(gpa, target);
1356 const name = try ty.nameAlloc(gpa, o.module);
13481357 defer gpa.free(name);
13491358
13501359 if (ty.castTag(.@"struct")) |payload| {
......@@ -1431,7 +1440,7 @@ pub const Object = struct {
14311440 );
14321441 dib.replaceTemporary(fwd_decl, full_di_ty);
14331442 // The recursive call to `lowerDebugType` means we can't use `gop` anymore.
1434 try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.initFull(full_di_ty), .{ .target = o.target });
1443 try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.initFull(full_di_ty), .{ .mod = o.module });
14351444 return full_di_ty;
14361445 }
14371446
......@@ -1445,23 +1454,23 @@ pub const Object = struct {
14451454 // into. Therefore we can satisfy this by making an empty namespace,
14461455 // rather than changing the frontend to unnecessarily resolve the
14471456 // struct field types.
1448 const owner_decl = ty.getOwnerDecl();
1449 const struct_di_ty = try o.makeEmptyNamespaceDIType(owner_decl);
1457 const owner_decl_index = ty.getOwnerDecl();
1458 const struct_di_ty = try o.makeEmptyNamespaceDIType(owner_decl_index);
14501459 dib.replaceTemporary(fwd_decl, struct_di_ty);
14511460 // The recursive call to `lowerDebugType` via `makeEmptyNamespaceDIType`
14521461 // means we can't use `gop` anymore.
1453 try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.initFull(struct_di_ty), .{ .target = o.target });
1462 try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.initFull(struct_di_ty), .{ .mod = o.module });
14541463 return struct_di_ty;
14551464 }
14561465 }
14571466
14581467 if (!ty.hasRuntimeBitsIgnoreComptime()) {
1459 const owner_decl = ty.getOwnerDecl();
1460 const struct_di_ty = try o.makeEmptyNamespaceDIType(owner_decl);
1468 const owner_decl_index = ty.getOwnerDecl();
1469 const struct_di_ty = try o.makeEmptyNamespaceDIType(owner_decl_index);
14611470 dib.replaceTemporary(fwd_decl, struct_di_ty);
14621471 // The recursive call to `lowerDebugType` via `makeEmptyNamespaceDIType`
14631472 // means we can't use `gop` anymore.
1464 try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.initFull(struct_di_ty), .{ .target = o.target });
1473 try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.initFull(struct_di_ty), .{ .mod = o.module });
14651474 return struct_di_ty;
14661475 }
14671476
......@@ -1516,14 +1525,14 @@ pub const Object = struct {
15161525 );
15171526 dib.replaceTemporary(fwd_decl, full_di_ty);
15181527 // The recursive call to `lowerDebugType` means we can't use `gop` anymore.
1519 try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.initFull(full_di_ty), .{ .target = o.target });
1528 try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.initFull(full_di_ty), .{ .mod = o.module });
15201529 return full_di_ty;
15211530 },
15221531 .Union => {
15231532 const compile_unit_scope = o.di_compile_unit.?.toScope();
1524 const owner_decl = ty.getOwnerDecl();
1533 const owner_decl_index = ty.getOwnerDecl();
15251534
1526 const name = try ty.nameAlloc(gpa, target);
1535 const name = try ty.nameAlloc(gpa, o.module);
15271536 defer gpa.free(name);
15281537
15291538 const fwd_decl = opt_fwd_decl orelse blk: {
......@@ -1540,11 +1549,11 @@ pub const Object = struct {
15401549 };
15411550
15421551 if (!ty.hasRuntimeBitsIgnoreComptime()) {
1543 const union_di_ty = try o.makeEmptyNamespaceDIType(owner_decl);
1552 const union_di_ty = try o.makeEmptyNamespaceDIType(owner_decl_index);
15441553 dib.replaceTemporary(fwd_decl, union_di_ty);
15451554 // The recursive call to `lowerDebugType` via `makeEmptyNamespaceDIType`
15461555 // means we can't use `gop` anymore.
1547 try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.initFull(union_di_ty), .{ .target = o.target });
1556 try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.initFull(union_di_ty), .{ .mod = o.module });
15481557 return union_di_ty;
15491558 }
15501559
......@@ -1572,7 +1581,7 @@ pub const Object = struct {
15721581 dib.replaceTemporary(fwd_decl, full_di_ty);
15731582 // The recursive call to `lowerDebugType` via `makeEmptyNamespaceDIType`
15741583 // means we can't use `gop` anymore.
1575 try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.initFull(full_di_ty), .{ .target = o.target });
1584 try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.initFull(full_di_ty), .{ .mod = o.module });
15761585 return full_di_ty;
15771586 }
15781587
......@@ -1626,7 +1635,7 @@ pub const Object = struct {
16261635 if (layout.tag_size == 0) {
16271636 dib.replaceTemporary(fwd_decl, union_di_ty);
16281637 // The recursive call to `lowerDebugType` means we can't use `gop` anymore.
1629 try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.initFull(union_di_ty), .{ .target = o.target });
1638 try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.initFull(union_di_ty), .{ .mod = o.module });
16301639 return union_di_ty;
16311640 }
16321641
......@@ -1685,7 +1694,7 @@ pub const Object = struct {
16851694 );
16861695 dib.replaceTemporary(fwd_decl, full_di_ty);
16871696 // The recursive call to `lowerDebugType` means we can't use `gop` anymore.
1688 try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.initFull(full_di_ty), .{ .target = o.target });
1697 try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.initFull(full_di_ty), .{ .mod = o.module });
16891698 return full_di_ty;
16901699 },
16911700 .Fn => {
......@@ -1733,7 +1742,7 @@ pub const Object = struct {
17331742 0,
17341743 );
17351744 // The recursive call to `lowerDebugType` means we can't use `gop` anymore.
1736 try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.initFull(fn_di_ty), .{ .target = o.target });
1745 try o.di_type_map.putContext(gpa, ty, AnnotatedDITypePtr.initFull(fn_di_ty), .{ .mod = o.module });
17371746 return fn_di_ty;
17381747 },
17391748 .ComptimeInt => unreachable,
......@@ -1762,7 +1771,8 @@ pub const Object = struct {
17621771 /// This is to be used instead of void for debug info types, to avoid tripping
17631772 /// Assertion `!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type"'
17641773 /// when targeting CodeView (Windows).
1765 fn makeEmptyNamespaceDIType(o: *Object, decl: *const Module.Decl) !*llvm.DIType {
1774 fn makeEmptyNamespaceDIType(o: *Object, decl_index: Module.Decl.Index) !*llvm.DIType {
1775 const decl = o.module.declPtr(decl_index);
17661776 const fields: [0]*llvm.DIType = .{};
17671777 return o.di_builder.?.createStructType(
17681778 try o.namespaceToDebugScope(decl.src_namespace),
......@@ -1787,6 +1797,7 @@ pub const DeclGen = struct {
17871797 object: *Object,
17881798 module: *Module,
17891799 decl: *Module.Decl,
1800 decl_index: Module.Decl.Index,
17901801 gpa: Allocator,
17911802 err_msg: ?*Module.ErrorMsg,
17921803
......@@ -1804,6 +1815,7 @@ pub const DeclGen = struct {
18041815
18051816 fn genDecl(dg: *DeclGen) !void {
18061817 const decl = dg.decl;
1818 const decl_index = dg.decl_index;
18071819 assert(decl.has_tv);
18081820
18091821 log.debug("gen: {s} type: {}, value: {}", .{
......@@ -1817,7 +1829,7 @@ pub const DeclGen = struct {
18171829 _ = try dg.resolveLlvmFunction(extern_fn.data.owner_decl);
18181830 } else {
18191831 const target = dg.module.getTarget();
1820 var global = try dg.resolveGlobalDecl(decl);
1832 var global = try dg.resolveGlobalDecl(decl_index);
18211833 global.setAlignment(decl.getAlignment(target));
18221834 assert(decl.has_tv);
18231835 const init_val = if (decl.val.castTag(.variable)) |payload| init_val: {
......@@ -1858,7 +1870,7 @@ pub const DeclGen = struct {
18581870 // old uses.
18591871 const new_global_ptr = new_global.constBitCast(global.typeOf());
18601872 global.replaceAllUsesWith(new_global_ptr);
1861 dg.object.decl_map.putAssumeCapacity(decl, new_global);
1873 dg.object.decl_map.putAssumeCapacity(decl_index, new_global);
18621874 new_global.takeName(global);
18631875 global.deleteGlobal();
18641876 global = new_global;
......@@ -1869,7 +1881,7 @@ pub const DeclGen = struct {
18691881 const di_file = try dg.object.getDIFile(dg.gpa, decl.src_namespace.file_scope);
18701882
18711883 const line_number = decl.src_line + 1;
1872 const is_internal_linkage = !dg.module.decl_exports.contains(decl);
1884 const is_internal_linkage = !dg.module.decl_exports.contains(decl_index);
18731885 const di_global = dib.createGlobalVariable(
18741886 di_file.toScope(),
18751887 decl.name,
......@@ -1888,12 +1900,10 @@ pub const DeclGen = struct {
18881900 /// If the llvm function does not exist, create it.
18891901 /// Note that this can be called before the function's semantic analysis has
18901902 /// completed, so if any attributes rely on that, they must be done in updateFunc, not here.
1891 fn resolveLlvmFunction(dg: *DeclGen, decl: *Module.Decl) !*const llvm.Value {
1892 return dg.resolveLlvmFunctionExtra(decl, decl.ty);
1893 }
1894
1895 fn resolveLlvmFunctionExtra(dg: *DeclGen, decl: *Module.Decl, zig_fn_type: Type) !*const llvm.Value {
1896 const gop = try dg.object.decl_map.getOrPut(dg.gpa, decl);
1903 fn resolveLlvmFunction(dg: *DeclGen, decl_index: Module.Decl.Index) !*const llvm.Value {
1904 const decl = dg.module.declPtr(decl_index);
1905 const zig_fn_type = decl.ty;
1906 const gop = try dg.object.decl_map.getOrPut(dg.gpa, decl_index);
18971907 if (gop.found_existing) return gop.value_ptr.*;
18981908
18991909 assert(decl.has_tv);
......@@ -1903,7 +1913,7 @@ pub const DeclGen = struct {
19031913
19041914 const fn_type = try dg.llvmType(zig_fn_type);
19051915
1906 const fqn = try decl.getFullyQualifiedName(dg.gpa);
1916 const fqn = try decl.getFullyQualifiedName(dg.module);
19071917 defer dg.gpa.free(fqn);
19081918
19091919 const llvm_addrspace = dg.llvmAddressSpace(decl.@"addrspace");
......@@ -1996,12 +2006,13 @@ pub const DeclGen = struct {
19962006 // TODO add target-cpu and target-features fn attributes
19972007 }
19982008
1999 fn resolveGlobalDecl(dg: *DeclGen, decl: *Module.Decl) Error!*const llvm.Value {
2000 const gop = try dg.object.decl_map.getOrPut(dg.gpa, decl);
2009 fn resolveGlobalDecl(dg: *DeclGen, decl_index: Module.Decl.Index) Error!*const llvm.Value {
2010 const gop = try dg.object.decl_map.getOrPut(dg.gpa, decl_index);
20012011 if (gop.found_existing) return gop.value_ptr.*;
2002 errdefer assert(dg.object.decl_map.remove(decl));
2012 errdefer assert(dg.object.decl_map.remove(decl_index));
20032013
2004 const fqn = try decl.getFullyQualifiedName(dg.gpa);
2014 const decl = dg.module.declPtr(decl_index);
2015 const fqn = try decl.getFullyQualifiedName(dg.module);
20052016 defer dg.gpa.free(fqn);
20062017
20072018 const llvm_type = try dg.llvmType(decl.ty);
......@@ -2122,7 +2133,7 @@ pub const DeclGen = struct {
21222133 },
21232134 .Opaque => switch (t.tag()) {
21242135 .@"opaque" => {
2125 const gop = try dg.object.type_map.getOrPutContext(gpa, t, .{ .target = target });
2136 const gop = try dg.object.type_map.getOrPutContext(gpa, t, .{ .mod = dg.module });
21262137 if (gop.found_existing) return gop.value_ptr.*;
21272138
21282139 // The Type memory is ephemeral; since we want to store a longer-lived
......@@ -2130,7 +2141,7 @@ pub const DeclGen = struct {
21302141 gop.key_ptr.* = try t.copy(dg.object.type_map_arena.allocator());
21312142
21322143 const opaque_obj = t.castTag(.@"opaque").?.data;
2133 const name = try opaque_obj.getFullyQualifiedName(gpa);
2144 const name = try opaque_obj.getFullyQualifiedName(dg.module);
21342145 defer gpa.free(name);
21352146
21362147 const llvm_struct_ty = dg.context.structCreateNamed(name);
......@@ -2191,7 +2202,7 @@ pub const DeclGen = struct {
21912202 return dg.context.intType(16);
21922203 },
21932204 .Struct => {
2194 const gop = try dg.object.type_map.getOrPutContext(gpa, t, .{ .target = target });
2205 const gop = try dg.object.type_map.getOrPutContext(gpa, t, .{ .mod = dg.module });
21952206 if (gop.found_existing) return gop.value_ptr.*;
21962207
21972208 // The Type memory is ephemeral; since we want to store a longer-lived
......@@ -2260,7 +2271,7 @@ pub const DeclGen = struct {
22602271 return int_llvm_ty;
22612272 }
22622273
2263 const name = try struct_obj.getFullyQualifiedName(gpa);
2274 const name = try struct_obj.getFullyQualifiedName(dg.module);
22642275 defer gpa.free(name);
22652276
22662277 const llvm_struct_ty = dg.context.structCreateNamed(name);
......@@ -2314,7 +2325,7 @@ pub const DeclGen = struct {
23142325 return llvm_struct_ty;
23152326 },
23162327 .Union => {
2317 const gop = try dg.object.type_map.getOrPutContext(gpa, t, .{ .target = target });
2328 const gop = try dg.object.type_map.getOrPutContext(gpa, t, .{ .mod = dg.module });
23182329 if (gop.found_existing) return gop.value_ptr.*;
23192330
23202331 // The Type memory is ephemeral; since we want to store a longer-lived
......@@ -2330,7 +2341,7 @@ pub const DeclGen = struct {
23302341 return enum_tag_llvm_ty;
23312342 }
23322343
2333 const name = try union_obj.getFullyQualifiedName(gpa);
2344 const name = try union_obj.getFullyQualifiedName(dg.module);
23342345 defer gpa.free(name);
23352346
23362347 const llvm_union_ty = dg.context.structCreateNamed(name);
......@@ -2439,7 +2450,7 @@ pub const DeclGen = struct {
24392450 // TODO this duplicates code with Pointer but they should share the handling
24402451 // of the tv.val.tag() and then Int should do extra constPtrToInt on top
24412452 .Int => switch (tv.val.tag()) {
2442 .decl_ref_mut => return lowerDeclRefValue(dg, tv, tv.val.castTag(.decl_ref_mut).?.data.decl),
2453 .decl_ref_mut => return lowerDeclRefValue(dg, tv, tv.val.castTag(.decl_ref_mut).?.data.decl_index),
24432454 .decl_ref => return lowerDeclRefValue(dg, tv, tv.val.castTag(.decl_ref).?.data),
24442455 else => {
24452456 var bigint_space: Value.BigIntSpace = undefined;
......@@ -2524,12 +2535,13 @@ pub const DeclGen = struct {
25242535 }
25252536 },
25262537 .Pointer => switch (tv.val.tag()) {
2527 .decl_ref_mut => return lowerDeclRefValue(dg, tv, tv.val.castTag(.decl_ref_mut).?.data.decl),
2538 .decl_ref_mut => return lowerDeclRefValue(dg, tv, tv.val.castTag(.decl_ref_mut).?.data.decl_index),
25282539 .decl_ref => return lowerDeclRefValue(dg, tv, tv.val.castTag(.decl_ref).?.data),
25292540 .variable => {
2530 const decl = tv.val.castTag(.variable).?.data.owner_decl;
2531 decl.markAlive();
2532 const val = try dg.resolveGlobalDecl(decl);
2541 const decl_index = tv.val.castTag(.variable).?.data.owner_decl;
2542 const decl = dg.module.declPtr(decl_index);
2543 dg.module.markDeclAlive(decl);
2544 const val = try dg.resolveGlobalDecl(decl_index);
25332545 const llvm_var_type = try dg.llvmType(tv.ty);
25342546 const llvm_addrspace = dg.llvmAddressSpace(decl.@"addrspace");
25352547 const llvm_type = llvm_var_type.pointerType(llvm_addrspace);
......@@ -2683,13 +2695,14 @@ pub const DeclGen = struct {
26832695 return dg.context.constStruct(&fields, fields.len, .False);
26842696 },
26852697 .Fn => {
2686 const fn_decl = switch (tv.val.tag()) {
2698 const fn_decl_index = switch (tv.val.tag()) {
26872699 .extern_fn => tv.val.castTag(.extern_fn).?.data.owner_decl,
26882700 .function => tv.val.castTag(.function).?.data.owner_decl,
26892701 else => unreachable,
26902702 };
2691 fn_decl.markAlive();
2692 return dg.resolveLlvmFunction(fn_decl);
2703 const fn_decl = dg.module.declPtr(fn_decl_index);
2704 dg.module.markDeclAlive(fn_decl);
2705 return dg.resolveLlvmFunction(fn_decl_index);
26932706 },
26942707 .ErrorSet => {
26952708 const llvm_ty = try dg.llvmType(tv.ty);
......@@ -2911,7 +2924,7 @@ pub const DeclGen = struct {
29112924 });
29122925 }
29132926 const union_obj = tv.ty.cast(Type.Payload.Union).?.data;
2914 const field_index = union_obj.tag_ty.enumTagFieldIndex(tag_and_val.tag, target).?;
2927 const field_index = union_obj.tag_ty.enumTagFieldIndex(tag_and_val.tag, dg.module).?;
29152928 assert(union_obj.haveFieldTypes());
29162929 const field_ty = union_obj.fields.values()[field_index].ty;
29172930 const payload = p: {
......@@ -3049,17 +3062,22 @@ pub const DeclGen = struct {
30493062 llvm_ptr: *const llvm.Value,
30503063 };
30513064
3052 fn lowerParentPtrDecl(dg: *DeclGen, ptr_val: Value, decl: *Module.Decl, ptr_child_ty: Type) Error!*const llvm.Value {
3053 decl.markAlive();
3065 fn lowerParentPtrDecl(
3066 dg: *DeclGen,
3067 ptr_val: Value,
3068 decl_index: Module.Decl.Index,
3069 ptr_child_ty: Type,
3070 ) Error!*const llvm.Value {
3071 const decl = dg.module.declPtr(decl_index);
3072 dg.module.markDeclAlive(decl);
30543073 var ptr_ty_payload: Type.Payload.ElemType = .{
30553074 .base = .{ .tag = .single_mut_pointer },
30563075 .data = decl.ty,
30573076 };
30583077 const ptr_ty = Type.initPayload(&ptr_ty_payload.base);
3059 const llvm_ptr = try dg.lowerDeclRefValue(.{ .ty = ptr_ty, .val = ptr_val }, decl);
3078 const llvm_ptr = try dg.lowerDeclRefValue(.{ .ty = ptr_ty, .val = ptr_val }, decl_index);
30603079
3061 const target = dg.module.getTarget();
3062 if (ptr_child_ty.eql(decl.ty, target)) {
3080 if (ptr_child_ty.eql(decl.ty, dg.module)) {
30633081 return llvm_ptr;
30643082 } else {
30653083 return llvm_ptr.constBitCast((try dg.llvmType(ptr_child_ty)).pointerType(0));
......@@ -3071,7 +3089,7 @@ pub const DeclGen = struct {
30713089 var bitcast_needed: bool = undefined;
30723090 const llvm_ptr = switch (ptr_val.tag()) {
30733091 .decl_ref_mut => {
3074 const decl = ptr_val.castTag(.decl_ref_mut).?.data.decl;
3092 const decl = ptr_val.castTag(.decl_ref_mut).?.data.decl_index;
30753093 return dg.lowerParentPtrDecl(ptr_val, decl, ptr_child_ty);
30763094 },
30773095 .decl_ref => {
......@@ -3123,7 +3141,7 @@ pub const DeclGen = struct {
31233141 },
31243142 .Struct => {
31253143 const field_ty = parent_ty.structFieldType(field_index);
3126 bitcast_needed = !field_ty.eql(ptr_child_ty, target);
3144 bitcast_needed = !field_ty.eql(ptr_child_ty, dg.module);
31273145
31283146 var ty_buf: Type.Payload.Pointer = undefined;
31293147 const llvm_field_index = llvmFieldIndex(parent_ty, field_index, target, &ty_buf).?;
......@@ -3139,7 +3157,7 @@ pub const DeclGen = struct {
31393157 .elem_ptr => blk: {
31403158 const elem_ptr = ptr_val.castTag(.elem_ptr).?.data;
31413159 const parent_llvm_ptr = try dg.lowerParentPtr(elem_ptr.array_ptr, elem_ptr.elem_ty);
3142 bitcast_needed = !elem_ptr.elem_ty.eql(ptr_child_ty, target);
3160 bitcast_needed = !elem_ptr.elem_ty.eql(ptr_child_ty, dg.module);
31433161
31443162 const llvm_usize = try dg.llvmType(Type.usize);
31453163 const indices: [1]*const llvm.Value = .{
......@@ -3153,7 +3171,7 @@ pub const DeclGen = struct {
31533171 var buf: Type.Payload.ElemType = undefined;
31543172
31553173 const payload_ty = opt_payload_ptr.container_ty.optionalChild(&buf);
3156 bitcast_needed = !payload_ty.eql(ptr_child_ty, target);
3174 bitcast_needed = !payload_ty.eql(ptr_child_ty, dg.module);
31573175
31583176 if (!payload_ty.hasRuntimeBitsIgnoreComptime() or payload_ty.isPtrLikeOptional()) {
31593177 // In this case, we represent pointer to optional the same as pointer
......@@ -3173,7 +3191,7 @@ pub const DeclGen = struct {
31733191 const parent_llvm_ptr = try dg.lowerParentPtr(eu_payload_ptr.container_ptr, eu_payload_ptr.container_ty);
31743192
31753193 const payload_ty = eu_payload_ptr.container_ty.errorUnionPayload();
3176 bitcast_needed = !payload_ty.eql(ptr_child_ty, target);
3194 bitcast_needed = !payload_ty.eql(ptr_child_ty, dg.module);
31773195
31783196 if (!payload_ty.hasRuntimeBitsIgnoreComptime()) {
31793197 // In this case, we represent pointer to error union the same as pointer
......@@ -3201,15 +3219,14 @@ pub const DeclGen = struct {
32013219 fn lowerDeclRefValue(
32023220 self: *DeclGen,
32033221 tv: TypedValue,
3204 decl: *Module.Decl,
3222 decl_index: Module.Decl.Index,
32053223 ) Error!*const llvm.Value {
3206 const target = self.module.getTarget();
32073224 if (tv.ty.isSlice()) {
32083225 var buf: Type.SlicePtrFieldTypeBuffer = undefined;
32093226 const ptr_ty = tv.ty.slicePtrFieldType(&buf);
32103227 var slice_len: Value.Payload.U64 = .{
32113228 .base = .{ .tag = .int_u64 },
3212 .data = tv.val.sliceLen(target),
3229 .data = tv.val.sliceLen(self.module),
32133230 };
32143231 const fields: [2]*const llvm.Value = .{
32153232 try self.genTypedValue(.{
......@@ -3229,8 +3246,9 @@ pub const DeclGen = struct {
32293246 // const bar = foo;
32303247 // ... &bar;
32313248 // `bar` is just an alias and we actually want to lower a reference to `foo`.
3249 const decl = self.module.declPtr(decl_index);
32323250 if (decl.val.castTag(.function)) |func| {
3233 if (func.data.owner_decl != decl) {
3251 if (func.data.owner_decl != decl_index) {
32343252 return self.lowerDeclRefValue(tv, func.data.owner_decl);
32353253 }
32363254 }
......@@ -3240,12 +3258,12 @@ pub const DeclGen = struct {
32403258 return self.lowerPtrToVoid(tv.ty);
32413259 }
32423260
3243 decl.markAlive();
3261 self.module.markDeclAlive(decl);
32443262
32453263 const llvm_val = if (is_fn_body)
3246 try self.resolveLlvmFunction(decl)
3264 try self.resolveLlvmFunction(decl_index)
32473265 else
3248 try self.resolveGlobalDecl(decl);
3266 try self.resolveGlobalDecl(decl_index);
32493267
32503268 const llvm_type = try self.llvmType(tv.ty);
32513269 if (tv.ty.zigTypeTag() == .Int) {
......@@ -4405,7 +4423,8 @@ pub const FuncGen = struct {
44054423 const ty_pl = self.air.instructions.items(.data)[inst].ty_pl;
44064424
44074425 const func = self.air.values[ty_pl.payload].castTag(.function).?.data;
4408 const decl = func.owner_decl;
4426 const decl_index = func.owner_decl;
4427 const decl = self.dg.module.declPtr(decl_index);
44094428 const di_file = try self.dg.object.getDIFile(self.gpa, decl.src_namespace.file_scope);
44104429 self.di_file = di_file;
44114430 const line_number = decl.src_line + 1;
......@@ -4417,10 +4436,10 @@ pub const FuncGen = struct {
44174436 .base_line = self.base_line,
44184437 });
44194438
4420 const fqn = try decl.getFullyQualifiedName(self.gpa);
4439 const fqn = try decl.getFullyQualifiedName(self.dg.module);
44214440 defer self.gpa.free(fqn);
44224441
4423 const is_internal_linkage = !self.dg.module.decl_exports.contains(decl);
4442 const is_internal_linkage = !self.dg.module.decl_exports.contains(decl_index);
44244443 const subprogram = dib.createFunction(
44254444 di_file.toScope(),
44264445 decl.name,
......@@ -4447,7 +4466,8 @@ pub const FuncGen = struct {
44474466 const ty_pl = self.air.instructions.items(.data)[inst].ty_pl;
44484467
44494468 const func = self.air.values[ty_pl.payload].castTag(.function).?.data;
4450 const decl = func.owner_decl;
4469 const mod = self.dg.module;
4470 const decl = mod.declPtr(func.owner_decl);
44514471 const di_file = try self.dg.object.getDIFile(self.gpa, decl.src_namespace.file_scope);
44524472 self.di_file = di_file;
44534473 const old = self.dbg_inlined.pop();
......@@ -5887,7 +5907,7 @@ pub const FuncGen = struct {
58875907 if (self.dg.object.di_builder) |dib| {
58885908 const src_index = self.getSrcArgIndex(self.arg_index - 1);
58895909 const func = self.dg.decl.getFunction().?;
5890 const lbrace_line = func.owner_decl.src_line + func.lbrace_line + 1;
5910 const lbrace_line = self.dg.module.declPtr(func.owner_decl).src_line + func.lbrace_line + 1;
58915911 const lbrace_col = func.lbrace_column + 1;
58925912 const di_local_var = dib.createParameterVariable(
58935913 self.di_scope.?,
......@@ -6430,8 +6450,9 @@ pub const FuncGen = struct {
64306450 const operand = try self.resolveInst(un_op);
64316451 const enum_ty = self.air.typeOf(un_op);
64326452
6453 const mod = self.dg.module;
64336454 const llvm_fn_name = try std.fmt.allocPrintZ(arena, "__zig_tag_name_{s}", .{
6434 try enum_ty.getOwnerDecl().getFullyQualifiedName(arena),
6455 try mod.declPtr(enum_ty.getOwnerDecl()).getFullyQualifiedName(mod),
64356456 });
64366457
64376458 const llvm_fn = try self.getEnumTagNameFunction(enum_ty, llvm_fn_name);
......@@ -6617,7 +6638,7 @@ pub const FuncGen = struct {
66176638
66186639 for (values) |*val, i| {
66196640 var buf: Value.ElemValueBuffer = undefined;
6620 const elem = mask.elemValueBuffer(i, &buf);
6641 const elem = mask.elemValueBuffer(self.dg.module, i, &buf);
66216642 if (elem.isUndef()) {
66226643 val.* = llvm_i32.getUndef();
66236644 } else {
src/codegen/spirv.zig+10-6
......@@ -633,7 +633,13 @@ pub const DeclGen = struct {
633633 return result_id.toRef();
634634 }
635635
636 fn airArithOp(self: *DeclGen, inst: Air.Inst.Index, comptime fop: Opcode, comptime sop: Opcode, comptime uop: Opcode) !IdRef {
636 fn airArithOp(
637 self: *DeclGen,
638 inst: Air.Inst.Index,
639 comptime fop: Opcode,
640 comptime sop: Opcode,
641 comptime uop: Opcode,
642 ) !IdRef {
637643 // LHS and RHS are guaranteed to have the same type, and AIR guarantees
638644 // the result to be the same as the LHS and RHS, which matches SPIR-V.
639645 const ty = self.air.typeOfIndex(inst);
......@@ -644,10 +650,8 @@ pub const DeclGen = struct {
644650 const result_id = self.spv.allocId();
645651 const result_type_id = try self.resolveTypeId(ty);
646652
647 const target = self.getTarget();
648
649 assert(self.air.typeOf(bin_op.lhs).eql(ty, target));
650 assert(self.air.typeOf(bin_op.rhs).eql(ty, target));
653 assert(self.air.typeOf(bin_op.lhs).eql(ty, self.module));
654 assert(self.air.typeOf(bin_op.rhs).eql(ty, self.module));
651655
652656 // Binary operations are generally applicable to both scalar and vector operations
653657 // in SPIR-V, but int and float versions of operations require different opcodes.
......@@ -694,7 +698,7 @@ pub const DeclGen = struct {
694698 const result_id = self.spv.allocId();
695699 const result_type_id = try self.resolveTypeId(Type.initTag(.bool));
696700 const op_ty = self.air.typeOf(bin_op.lhs);
697 assert(op_ty.eql(self.air.typeOf(bin_op.rhs), self.getTarget()));
701 assert(op_ty.eql(self.air.typeOf(bin_op.rhs), self.module));
698702
699703 // Comparisons are generally applicable to both scalar and vector operations in SPIR-V,
700704 // but int and float versions of operations require different opcodes.
src/crash_report.zig+9-6
......@@ -90,9 +90,11 @@ fn dumpStatusReport() !void {
9090
9191 const stderr = io.getStdErr().writer();
9292 const block: *Sema.Block = anal.block;
93 const mod = anal.sema.mod;
94 const block_src_decl = mod.declPtr(block.src_decl);
9395
9496 try stderr.writeAll("Analyzing ");
95 try writeFullyQualifiedDeclWithFile(block.src_decl, stderr);
97 try writeFullyQualifiedDeclWithFile(mod, block_src_decl, stderr);
9698 try stderr.writeAll("\n");
9799
98100 print_zir.renderInstructionContext(
......@@ -100,7 +102,7 @@ fn dumpStatusReport() !void {
100102 anal.body,
101103 anal.body_index,
102104 block.namespace.file_scope,
103 block.src_decl.src_node,
105 block_src_decl.src_node,
104106 6, // indent
105107 stderr,
106108 ) catch |err| switch (err) {
......@@ -115,13 +117,14 @@ fn dumpStatusReport() !void {
115117 while (parent) |curr| {
116118 fba.reset();
117119 try stderr.writeAll(" in ");
118 try writeFullyQualifiedDeclWithFile(curr.block.src_decl, stderr);
120 const curr_block_src_decl = mod.declPtr(curr.block.src_decl);
121 try writeFullyQualifiedDeclWithFile(mod, curr_block_src_decl, stderr);
119122 try stderr.writeAll("\n > ");
120123 print_zir.renderSingleInstruction(
121124 allocator,
122125 curr.body[curr.body_index],
123126 curr.block.namespace.file_scope,
124 curr.block.src_decl.src_node,
127 curr_block_src_decl.src_node,
125128 6, // indent
126129 stderr,
127130 ) catch |err| switch (err) {
......@@ -146,10 +149,10 @@ fn writeFilePath(file: *Module.File, stream: anytype) !void {
146149 try stream.writeAll(file.sub_file_path);
147150}
148151
149fn writeFullyQualifiedDeclWithFile(decl: *Decl, stream: anytype) !void {
152fn writeFullyQualifiedDeclWithFile(mod: *Module, decl: *Decl, stream: anytype) !void {
150153 try writeFilePath(decl.getFileScope(), stream);
151154 try stream.writeAll(": ");
152 try decl.renderFullyQualifiedDebugName(stream);
155 try decl.renderFullyQualifiedDebugName(mod, stream);
153156}
154157
155158pub fn compilerPanic(msg: []const u8, error_return_trace: ?*std.builtin.StackTrace) noreturn {
src/link.zig+51-47
......@@ -417,17 +417,18 @@ pub const File = struct {
417417 /// Called from within the CodeGen to lower a local variable instantion as an unnamed
418418 /// constant. Returns the symbol index of the lowered constant in the read-only section
419419 /// of the final binary.
420 pub fn lowerUnnamedConst(base: *File, tv: TypedValue, decl: *Module.Decl) UpdateDeclError!u32 {
420 pub fn lowerUnnamedConst(base: *File, tv: TypedValue, decl_index: Module.Decl.Index) UpdateDeclError!u32 {
421 const decl = base.options.module.?.declPtr(decl_index);
421422 log.debug("lowerUnnamedConst {*} ({s})", .{ decl, decl.name });
422423 switch (base.tag) {
423424 // zig fmt: off
424 .coff => return @fieldParentPtr(Coff, "base", base).lowerUnnamedConst(tv, decl),
425 .elf => return @fieldParentPtr(Elf, "base", base).lowerUnnamedConst(tv, decl),
426 .macho => return @fieldParentPtr(MachO, "base", base).lowerUnnamedConst(tv, decl),
427 .plan9 => return @fieldParentPtr(Plan9, "base", base).lowerUnnamedConst(tv, decl),
425 .coff => return @fieldParentPtr(Coff, "base", base).lowerUnnamedConst(tv, decl_index),
426 .elf => return @fieldParentPtr(Elf, "base", base).lowerUnnamedConst(tv, decl_index),
427 .macho => return @fieldParentPtr(MachO, "base", base).lowerUnnamedConst(tv, decl_index),
428 .plan9 => return @fieldParentPtr(Plan9, "base", base).lowerUnnamedConst(tv, decl_index),
428429 .spirv => unreachable,
429430 .c => unreachable,
430 .wasm => unreachable,
431 .wasm => return @fieldParentPtr(Wasm, "base", base).lowerUnnamedConst(tv, decl_index),
431432 .nvptx => unreachable,
432433 // zig fmt: on
433434 }
......@@ -435,19 +436,20 @@ pub const File = struct {
435436
436437 /// May be called before or after updateDeclExports but must be called
437438 /// after allocateDeclIndexes for any given Decl.
438 pub fn updateDecl(base: *File, module: *Module, decl: *Module.Decl) UpdateDeclError!void {
439 pub fn updateDecl(base: *File, module: *Module, decl_index: Module.Decl.Index) UpdateDeclError!void {
440 const decl = module.declPtr(decl_index);
439441 log.debug("updateDecl {*} ({s}), type={}", .{ decl, decl.name, decl.ty.fmtDebug() });
440442 assert(decl.has_tv);
441443 switch (base.tag) {
442444 // zig fmt: off
443 .coff => return @fieldParentPtr(Coff, "base", base).updateDecl(module, decl),
444 .elf => return @fieldParentPtr(Elf, "base", base).updateDecl(module, decl),
445 .macho => return @fieldParentPtr(MachO, "base", base).updateDecl(module, decl),
446 .c => return @fieldParentPtr(C, "base", base).updateDecl(module, decl),
447 .wasm => return @fieldParentPtr(Wasm, "base", base).updateDecl(module, decl),
448 .spirv => return @fieldParentPtr(SpirV, "base", base).updateDecl(module, decl),
449 .plan9 => return @fieldParentPtr(Plan9, "base", base).updateDecl(module, decl),
450 .nvptx => return @fieldParentPtr(NvPtx, "base", base).updateDecl(module, decl),
445 .coff => return @fieldParentPtr(Coff, "base", base).updateDecl(module, decl_index),
446 .elf => return @fieldParentPtr(Elf, "base", base).updateDecl(module, decl_index),
447 .macho => return @fieldParentPtr(MachO, "base", base).updateDecl(module, decl_index),
448 .c => return @fieldParentPtr(C, "base", base).updateDecl(module, decl_index),
449 .wasm => return @fieldParentPtr(Wasm, "base", base).updateDecl(module, decl_index),
450 .spirv => return @fieldParentPtr(SpirV, "base", base).updateDecl(module, decl_index),
451 .plan9 => return @fieldParentPtr(Plan9, "base", base).updateDecl(module, decl_index),
452 .nvptx => return @fieldParentPtr(NvPtx, "base", base).updateDecl(module, decl_index),
451453 // zig fmt: on
452454 }
453455 }
......@@ -455,8 +457,9 @@ pub const File = struct {
455457 /// May be called before or after updateDeclExports but must be called
456458 /// after allocateDeclIndexes for any given Decl.
457459 pub fn updateFunc(base: *File, module: *Module, func: *Module.Fn, air: Air, liveness: Liveness) UpdateDeclError!void {
460 const owner_decl = module.declPtr(func.owner_decl);
458461 log.debug("updateFunc {*} ({s}), type={}", .{
459 func.owner_decl, func.owner_decl.name, func.owner_decl.ty.fmtDebug(),
462 owner_decl, owner_decl.name, owner_decl.ty.fmtDebug(),
460463 });
461464 switch (base.tag) {
462465 // zig fmt: off
......@@ -492,19 +495,20 @@ pub const File = struct {
492495 /// TODO we're transitioning to deleting this function and instead having
493496 /// each linker backend notice the first time updateDecl or updateFunc is called, or
494497 /// a callee referenced from AIR.
495 pub fn allocateDeclIndexes(base: *File, decl: *Module.Decl) error{OutOfMemory}!void {
498 pub fn allocateDeclIndexes(base: *File, decl_index: Module.Decl.Index) error{OutOfMemory}!void {
499 const decl = base.options.module.?.declPtr(decl_index);
496500 log.debug("allocateDeclIndexes {*} ({s})", .{ decl, decl.name });
497501 switch (base.tag) {
498 .coff => return @fieldParentPtr(Coff, "base", base).allocateDeclIndexes(decl),
499 .elf => return @fieldParentPtr(Elf, "base", base).allocateDeclIndexes(decl),
500 .macho => return @fieldParentPtr(MachO, "base", base).allocateDeclIndexes(decl) catch |err| switch (err) {
502 .coff => return @fieldParentPtr(Coff, "base", base).allocateDeclIndexes(decl_index),
503 .elf => return @fieldParentPtr(Elf, "base", base).allocateDeclIndexes(decl_index),
504 .macho => return @fieldParentPtr(MachO, "base", base).allocateDeclIndexes(decl_index) catch |err| switch (err) {
501505 // remap this error code because we are transitioning away from
502506 // `allocateDeclIndexes`.
503507 error.Overflow => return error.OutOfMemory,
504508 error.OutOfMemory => return error.OutOfMemory,
505509 },
506 .wasm => return @fieldParentPtr(Wasm, "base", base).allocateDeclIndexes(decl),
507 .plan9 => return @fieldParentPtr(Plan9, "base", base).allocateDeclIndexes(decl),
510 .wasm => return @fieldParentPtr(Wasm, "base", base).allocateDeclIndexes(decl_index),
511 .plan9 => return @fieldParentPtr(Plan9, "base", base).allocateDeclIndexes(decl_index),
508512 .c, .spirv, .nvptx => {},
509513 }
510514 }
......@@ -621,17 +625,16 @@ pub const File = struct {
621625 }
622626
623627 /// Called when a Decl is deleted from the Module.
624 pub fn freeDecl(base: *File, decl: *Module.Decl) void {
625 log.debug("freeDecl {*} ({s})", .{ decl, decl.name });
628 pub fn freeDecl(base: *File, decl_index: Module.Decl.Index) void {
626629 switch (base.tag) {
627 .coff => @fieldParentPtr(Coff, "base", base).freeDecl(decl),
628 .elf => @fieldParentPtr(Elf, "base", base).freeDecl(decl),
629 .macho => @fieldParentPtr(MachO, "base", base).freeDecl(decl),
630 .c => @fieldParentPtr(C, "base", base).freeDecl(decl),
631 .wasm => @fieldParentPtr(Wasm, "base", base).freeDecl(decl),
632 .spirv => @fieldParentPtr(SpirV, "base", base).freeDecl(decl),
633 .plan9 => @fieldParentPtr(Plan9, "base", base).freeDecl(decl),
634 .nvptx => @fieldParentPtr(NvPtx, "base", base).freeDecl(decl),
630 .coff => @fieldParentPtr(Coff, "base", base).freeDecl(decl_index),
631 .elf => @fieldParentPtr(Elf, "base", base).freeDecl(decl_index),
632 .macho => @fieldParentPtr(MachO, "base", base).freeDecl(decl_index),
633 .c => @fieldParentPtr(C, "base", base).freeDecl(decl_index),
634 .wasm => @fieldParentPtr(Wasm, "base", base).freeDecl(decl_index),
635 .spirv => @fieldParentPtr(SpirV, "base", base).freeDecl(decl_index),
636 .plan9 => @fieldParentPtr(Plan9, "base", base).freeDecl(decl_index),
637 .nvptx => @fieldParentPtr(NvPtx, "base", base).freeDecl(decl_index),
635638 }
636639 }
637640
......@@ -656,20 +659,21 @@ pub const File = struct {
656659 pub fn updateDeclExports(
657660 base: *File,
658661 module: *Module,
659 decl: *Module.Decl,
662 decl_index: Module.Decl.Index,
660663 exports: []const *Module.Export,
661664 ) UpdateDeclExportsError!void {
665 const decl = module.declPtr(decl_index);
662666 log.debug("updateDeclExports {*} ({s})", .{ decl, decl.name });
663667 assert(decl.has_tv);
664668 switch (base.tag) {
665 .coff => return @fieldParentPtr(Coff, "base", base).updateDeclExports(module, decl, exports),
666 .elf => return @fieldParentPtr(Elf, "base", base).updateDeclExports(module, decl, exports),
667 .macho => return @fieldParentPtr(MachO, "base", base).updateDeclExports(module, decl, exports),
668 .c => return @fieldParentPtr(C, "base", base).updateDeclExports(module, decl, exports),
669 .wasm => return @fieldParentPtr(Wasm, "base", base).updateDeclExports(module, decl, exports),
670 .spirv => return @fieldParentPtr(SpirV, "base", base).updateDeclExports(module, decl, exports),
671 .plan9 => return @fieldParentPtr(Plan9, "base", base).updateDeclExports(module, decl, exports),
672 .nvptx => return @fieldParentPtr(NvPtx, "base", base).updateDeclExports(module, decl, exports),
669 .coff => return @fieldParentPtr(Coff, "base", base).updateDeclExports(module, decl_index, exports),
670 .elf => return @fieldParentPtr(Elf, "base", base).updateDeclExports(module, decl_index, exports),
671 .macho => return @fieldParentPtr(MachO, "base", base).updateDeclExports(module, decl_index, exports),
672 .c => return @fieldParentPtr(C, "base", base).updateDeclExports(module, decl_index, exports),
673 .wasm => return @fieldParentPtr(Wasm, "base", base).updateDeclExports(module, decl_index, exports),
674 .spirv => return @fieldParentPtr(SpirV, "base", base).updateDeclExports(module, decl_index, exports),
675 .plan9 => return @fieldParentPtr(Plan9, "base", base).updateDeclExports(module, decl_index, exports),
676 .nvptx => return @fieldParentPtr(NvPtx, "base", base).updateDeclExports(module, decl_index, exports),
673677 }
674678 }
675679
......@@ -683,14 +687,14 @@ pub const File = struct {
683687 /// The linker is passed information about the containing atom, `parent_atom_index`, and offset within it's
684688 /// memory buffer, `offset`, so that it can make a note of potential relocation sites, should the
685689 /// `Decl`'s address was not yet resolved, or the containing atom gets moved in virtual memory.
686 pub fn getDeclVAddr(base: *File, decl: *const Module.Decl, reloc_info: RelocInfo) !u64 {
690 pub fn getDeclVAddr(base: *File, decl_index: Module.Decl.Index, reloc_info: RelocInfo) !u64 {
687691 switch (base.tag) {
688 .coff => return @fieldParentPtr(Coff, "base", base).getDeclVAddr(decl, reloc_info),
689 .elf => return @fieldParentPtr(Elf, "base", base).getDeclVAddr(decl, reloc_info),
690 .macho => return @fieldParentPtr(MachO, "base", base).getDeclVAddr(decl, reloc_info),
691 .plan9 => return @fieldParentPtr(Plan9, "base", base).getDeclVAddr(decl, reloc_info),
692 .coff => return @fieldParentPtr(Coff, "base", base).getDeclVAddr(decl_index, reloc_info),
693 .elf => return @fieldParentPtr(Elf, "base", base).getDeclVAddr(decl_index, reloc_info),
694 .macho => return @fieldParentPtr(MachO, "base", base).getDeclVAddr(decl_index, reloc_info),
695 .plan9 => return @fieldParentPtr(Plan9, "base", base).getDeclVAddr(decl_index, reloc_info),
692696 .c => unreachable,
693 .wasm => return @fieldParentPtr(Wasm, "base", base).getDeclVAddr(decl, reloc_info),
697 .wasm => return @fieldParentPtr(Wasm, "base", base).getDeclVAddr(decl_index, reloc_info),
694698 .spirv => unreachable,
695699 .nvptx => unreachable,
696700 }
src/link/C.zig+36-27
......@@ -21,7 +21,7 @@ base: link.File,
2121/// This linker backend does not try to incrementally link output C source code.
2222/// Instead, it tracks all declarations in this table, and iterates over it
2323/// in the flush function, stitching pre-rendered pieces of C code together.
24decl_table: std.AutoArrayHashMapUnmanaged(*const Module.Decl, DeclBlock) = .{},
24decl_table: std.AutoArrayHashMapUnmanaged(Module.Decl.Index, DeclBlock) = .{},
2525/// Stores Type/Value data for `typedefs` to reference.
2626/// Accumulates allocations and then there is a periodic garbage collection after flush().
2727arena: std.heap.ArenaAllocator,
......@@ -87,9 +87,9 @@ pub fn deinit(self: *C) void {
8787 self.arena.deinit();
8888}
8989
90pub fn freeDecl(self: *C, decl: *Module.Decl) void {
90pub fn freeDecl(self: *C, decl_index: Module.Decl.Index) void {
9191 const gpa = self.base.allocator;
92 if (self.decl_table.fetchSwapRemove(decl)) |kv| {
92 if (self.decl_table.fetchSwapRemove(decl_index)) |kv| {
9393 var decl_block = kv.value;
9494 decl_block.deinit(gpa);
9595 }
......@@ -99,8 +99,8 @@ pub fn updateFunc(self: *C, module: *Module, func: *Module.Fn, air: Air, livenes
9999 const tracy = trace(@src());
100100 defer tracy.end();
101101
102 const decl = func.owner_decl;
103 const gop = try self.decl_table.getOrPut(self.base.allocator, decl);
102 const decl_index = func.owner_decl;
103 const gop = try self.decl_table.getOrPut(self.base.allocator, decl_index);
104104 if (!gop.found_existing) {
105105 gop.value_ptr.* = .{};
106106 }
......@@ -126,9 +126,10 @@ pub fn updateFunc(self: *C, module: *Module, func: *Module.Fn, air: Air, livenes
126126 .gpa = module.gpa,
127127 .module = module,
128128 .error_msg = null,
129 .decl = decl,
129 .decl_index = decl_index,
130 .decl = module.declPtr(decl_index),
130131 .fwd_decl = fwd_decl.toManaged(module.gpa),
131 .typedefs = typedefs.promoteContext(module.gpa, .{ .target = module.getTarget() }),
132 .typedefs = typedefs.promoteContext(module.gpa, .{ .mod = module }),
132133 .typedefs_arena = self.arena.allocator(),
133134 },
134135 .code = code.toManaged(module.gpa),
......@@ -150,7 +151,7 @@ pub fn updateFunc(self: *C, module: *Module, func: *Module.Fn, air: Air, livenes
150151
151152 codegen.genFunc(&function) catch |err| switch (err) {
152153 error.AnalysisFail => {
153 try module.failed_decls.put(module.gpa, decl, function.object.dg.error_msg.?);
154 try module.failed_decls.put(module.gpa, decl_index, function.object.dg.error_msg.?);
154155 return;
155156 },
156157 else => |e| return e,
......@@ -166,11 +167,11 @@ pub fn updateFunc(self: *C, module: *Module, func: *Module.Fn, air: Air, livenes
166167 code.shrinkAndFree(module.gpa, code.items.len);
167168}
168169
169pub fn updateDecl(self: *C, module: *Module, decl: *Module.Decl) !void {
170pub fn updateDecl(self: *C, module: *Module, decl_index: Module.Decl.Index) !void {
170171 const tracy = trace(@src());
171172 defer tracy.end();
172173
173 const gop = try self.decl_table.getOrPut(self.base.allocator, decl);
174 const gop = try self.decl_table.getOrPut(self.base.allocator, decl_index);
174175 if (!gop.found_existing) {
175176 gop.value_ptr.* = .{};
176177 }
......@@ -186,14 +187,17 @@ pub fn updateDecl(self: *C, module: *Module, decl: *Module.Decl) !void {
186187 typedefs.clearRetainingCapacity();
187188 code.shrinkRetainingCapacity(0);
188189
190 const decl = module.declPtr(decl_index);
191
189192 var object: codegen.Object = .{
190193 .dg = .{
191194 .gpa = module.gpa,
192195 .module = module,
193196 .error_msg = null,
197 .decl_index = decl_index,
194198 .decl = decl,
195199 .fwd_decl = fwd_decl.toManaged(module.gpa),
196 .typedefs = typedefs.promoteContext(module.gpa, .{ .target = module.getTarget() }),
200 .typedefs = typedefs.promoteContext(module.gpa, .{ .mod = module }),
197201 .typedefs_arena = self.arena.allocator(),
198202 },
199203 .code = code.toManaged(module.gpa),
......@@ -211,7 +215,7 @@ pub fn updateDecl(self: *C, module: *Module, decl: *Module.Decl) !void {
211215
212216 codegen.genDecl(&object) catch |err| switch (err) {
213217 error.AnalysisFail => {
214 try module.failed_decls.put(module.gpa, decl, object.dg.error_msg.?);
218 try module.failed_decls.put(module.gpa, decl_index, object.dg.error_msg.?);
215219 return;
216220 },
217221 else => |e| return e,
......@@ -287,14 +291,14 @@ pub fn flushModule(self: *C, comp: *Compilation, prog_node: *std.Progress.Node)
287291
288292 const decl_keys = self.decl_table.keys();
289293 const decl_values = self.decl_table.values();
290 for (decl_keys) |decl| {
291 assert(decl.has_tv);
292 f.remaining_decls.putAssumeCapacityNoClobber(decl, {});
294 for (decl_keys) |decl_index| {
295 assert(module.declPtr(decl_index).has_tv);
296 f.remaining_decls.putAssumeCapacityNoClobber(decl_index, {});
293297 }
294298
295299 while (f.remaining_decls.popOrNull()) |kv| {
296 const decl = kv.key;
297 try flushDecl(self, &f, decl);
300 const decl_index = kv.key;
301 try flushDecl(self, &f, decl_index);
298302 }
299303
300304 f.all_buffers.items[err_typedef_index] = .{
......@@ -305,7 +309,8 @@ pub fn flushModule(self: *C, comp: *Compilation, prog_node: *std.Progress.Node)
305309
306310 // Now the function bodies.
307311 try f.all_buffers.ensureUnusedCapacity(gpa, f.fn_count);
308 for (decl_keys) |decl, i| {
312 for (decl_keys) |decl_index, i| {
313 const decl = module.declPtr(decl_index);
309314 if (decl.getFunction() != null) {
310315 const decl_block = &decl_values[i];
311316 const buf = decl_block.code.items;
......@@ -325,7 +330,7 @@ pub fn flushModule(self: *C, comp: *Compilation, prog_node: *std.Progress.Node)
325330}
326331
327332const Flush = struct {
328 remaining_decls: std.AutoArrayHashMapUnmanaged(*const Module.Decl, void) = .{},
333 remaining_decls: std.AutoArrayHashMapUnmanaged(Module.Decl.Index, void) = .{},
329334 typedefs: Typedefs = .{},
330335 err_typedef_buf: std.ArrayListUnmanaged(u8) = .{},
331336 /// We collect a list of buffers to write, and write them all at once with pwritev 😎
......@@ -354,7 +359,9 @@ const FlushDeclError = error{
354359};
355360
356361/// Assumes `decl` was in the `remaining_decls` set, and has already been removed.
357fn flushDecl(self: *C, f: *Flush, decl: *const Module.Decl) FlushDeclError!void {
362fn flushDecl(self: *C, f: *Flush, decl_index: Module.Decl.Index) FlushDeclError!void {
363 const module = self.base.options.module.?;
364 const decl = module.declPtr(decl_index);
358365 // Before flushing any particular Decl we must ensure its
359366 // dependencies are already flushed, so that the order in the .c
360367 // file comes out correctly.
......@@ -364,15 +371,17 @@ fn flushDecl(self: *C, f: *Flush, decl: *const Module.Decl) FlushDeclError!void
364371 }
365372 }
366373
367 const decl_block = self.decl_table.getPtr(decl).?;
374 const decl_block = self.decl_table.getPtr(decl_index).?;
368375 const gpa = self.base.allocator;
369376
370377 if (decl_block.typedefs.count() != 0) {
371 try f.typedefs.ensureUnusedCapacity(gpa, @intCast(u32, decl_block.typedefs.count()));
378 try f.typedefs.ensureUnusedCapacityContext(gpa, @intCast(u32, decl_block.typedefs.count()), .{
379 .mod = module,
380 });
372381 var it = decl_block.typedefs.iterator();
373382 while (it.next()) |new| {
374383 const gop = f.typedefs.getOrPutAssumeCapacityContext(new.key_ptr.*, .{
375 .target = self.base.options.target,
384 .mod = module,
376385 });
377386 if (!gop.found_existing) {
378387 try f.err_typedef_buf.appendSlice(gpa, new.value_ptr.rendered);
......@@ -417,8 +426,8 @@ pub fn flushEmitH(module: *Module) !void {
417426 .iov_len = zig_h.len,
418427 });
419428
420 for (emit_h.decl_table.keys()) |decl| {
421 const decl_emit_h = decl.getEmitH(module);
429 for (emit_h.decl_table.keys()) |decl_index| {
430 const decl_emit_h = emit_h.declPtr(decl_index);
422431 const buf = decl_emit_h.fwd_decl.items;
423432 all_buffers.appendAssumeCapacity(.{
424433 .iov_base = buf.ptr,
......@@ -442,11 +451,11 @@ pub fn flushEmitH(module: *Module) !void {
442451pub fn updateDeclExports(
443452 self: *C,
444453 module: *Module,
445 decl: *Module.Decl,
454 decl_index: Module.Decl.Index,
446455 exports: []const *Module.Export,
447456) !void {
448457 _ = exports;
449 _ = decl;
458 _ = decl_index;
450459 _ = module;
451460 _ = self;
452461}
src/link/Coff.zig+32-17
......@@ -418,11 +418,12 @@ pub fn createEmpty(gpa: Allocator, options: link.Options) !*Coff {
418418 return self;
419419}
420420
421pub fn allocateDeclIndexes(self: *Coff, decl: *Module.Decl) !void {
421pub fn allocateDeclIndexes(self: *Coff, decl_index: Module.Decl.Index) !void {
422422 if (self.llvm_object) |_| return;
423423
424424 try self.offset_table.ensureUnusedCapacity(self.base.allocator, 1);
425425
426 const decl = self.base.options.module.?.declPtr(decl_index);
426427 if (self.offset_table_free_list.popOrNull()) |i| {
427428 decl.link.coff.offset_table_index = i;
428429 } else {
......@@ -674,7 +675,8 @@ pub fn updateFunc(self: *Coff, module: *Module, func: *Module.Fn, air: Air, live
674675 var code_buffer = std.ArrayList(u8).init(self.base.allocator);
675676 defer code_buffer.deinit();
676677
677 const decl = func.owner_decl;
678 const decl_index = func.owner_decl;
679 const decl = module.declPtr(decl_index);
678680 const res = try codegen.generateFunction(
679681 &self.base,
680682 decl.srcLoc(),
......@@ -688,7 +690,7 @@ pub fn updateFunc(self: *Coff, module: *Module, func: *Module.Fn, air: Air, live
688690 .appended => code_buffer.items,
689691 .fail => |em| {
690692 decl.analysis = .codegen_failure;
691 try module.failed_decls.put(module.gpa, decl, em);
693 try module.failed_decls.put(module.gpa, decl_index, em);
692694 return;
693695 },
694696 };
......@@ -696,24 +698,26 @@ pub fn updateFunc(self: *Coff, module: *Module, func: *Module.Fn, air: Air, live
696698 return self.finishUpdateDecl(module, func.owner_decl, code);
697699}
698700
699pub fn lowerUnnamedConst(self: *Coff, tv: TypedValue, decl: *Module.Decl) !u32 {
701pub fn lowerUnnamedConst(self: *Coff, tv: TypedValue, decl_index: Module.Decl.Index) !u32 {
700702 _ = self;
701703 _ = tv;
702 _ = decl;
704 _ = decl_index;
703705 log.debug("TODO lowerUnnamedConst for Coff", .{});
704706 return error.AnalysisFail;
705707}
706708
707pub fn updateDecl(self: *Coff, module: *Module, decl: *Module.Decl) !void {
709pub fn updateDecl(self: *Coff, module: *Module, decl_index: Module.Decl.Index) !void {
708710 if (build_options.skip_non_native and builtin.object_format != .coff) {
709711 @panic("Attempted to compile for object format that was disabled by build configuration");
710712 }
711713 if (build_options.have_llvm) {
712 if (self.llvm_object) |llvm_object| return llvm_object.updateDecl(module, decl);
714 if (self.llvm_object) |llvm_object| return llvm_object.updateDecl(module, decl_index);
713715 }
714716 const tracy = trace(@src());
715717 defer tracy.end();
716718
719 const decl = module.declPtr(decl_index);
720
717721 if (decl.val.tag() == .extern_fn) {
718722 return; // TODO Should we do more when front-end analyzed extern decl?
719723 }
......@@ -735,15 +739,16 @@ pub fn updateDecl(self: *Coff, module: *Module, decl: *Module.Decl) !void {
735739 .appended => code_buffer.items,
736740 .fail => |em| {
737741 decl.analysis = .codegen_failure;
738 try module.failed_decls.put(module.gpa, decl, em);
742 try module.failed_decls.put(module.gpa, decl_index, em);
739743 return;
740744 },
741745 };
742746
743 return self.finishUpdateDecl(module, decl, code);
747 return self.finishUpdateDecl(module, decl_index, code);
744748}
745749
746fn finishUpdateDecl(self: *Coff, module: *Module, decl: *Module.Decl, code: []const u8) !void {
750fn finishUpdateDecl(self: *Coff, module: *Module, decl_index: Module.Decl.Index, code: []const u8) !void {
751 const decl = module.declPtr(decl_index);
747752 const required_alignment = decl.ty.abiAlignment(self.base.options.target);
748753 const curr_size = decl.link.coff.size;
749754 if (curr_size != 0) {
......@@ -778,15 +783,18 @@ fn finishUpdateDecl(self: *Coff, module: *Module, decl: *Module.Decl, code: []co
778783 try self.base.file.?.pwriteAll(code, self.section_data_offset + self.offset_table_size + decl.link.coff.text_offset);
779784
780785 // Since we updated the vaddr and the size, each corresponding export symbol also needs to be updated.
781 const decl_exports = module.decl_exports.get(decl) orelse &[0]*Module.Export{};
782 return self.updateDeclExports(module, decl, decl_exports);
786 const decl_exports = module.decl_exports.get(decl_index) orelse &[0]*Module.Export{};
787 return self.updateDeclExports(module, decl_index, decl_exports);
783788}
784789
785pub fn freeDecl(self: *Coff, decl: *Module.Decl) void {
790pub fn freeDecl(self: *Coff, decl_index: Module.Decl.Index) void {
786791 if (build_options.have_llvm) {
787 if (self.llvm_object) |llvm_object| return llvm_object.freeDecl(decl);
792 if (self.llvm_object) |llvm_object| return llvm_object.freeDecl(decl_index);
788793 }
789794
795 const mod = self.base.options.module.?;
796 const decl = mod.declPtr(decl_index);
797
790798 // Appending to free lists is allowed to fail because the free lists are heuristics based anyway.
791799 self.freeTextBlock(&decl.link.coff);
792800 self.offset_table_free_list.append(self.base.allocator, decl.link.coff.offset_table_index) catch {};
......@@ -795,16 +803,17 @@ pub fn freeDecl(self: *Coff, decl: *Module.Decl) void {
795803pub fn updateDeclExports(
796804 self: *Coff,
797805 module: *Module,
798 decl: *Module.Decl,
806 decl_index: Module.Decl.Index,
799807 exports: []const *Module.Export,
800808) !void {
801809 if (build_options.skip_non_native and builtin.object_format != .coff) {
802810 @panic("Attempted to compile for object format that was disabled by build configuration");
803811 }
804812 if (build_options.have_llvm) {
805 if (self.llvm_object) |llvm_object| return llvm_object.updateDeclExports(module, decl, exports);
813 if (self.llvm_object) |llvm_object| return llvm_object.updateDeclExports(module, decl_index, exports);
806814 }
807815
816 const decl = module.declPtr(decl_index);
808817 for (exports) |exp| {
809818 if (exp.options.section) |section_name| {
810819 if (!mem.eql(u8, section_name, ".text")) {
......@@ -1474,8 +1483,14 @@ fn findLib(self: *Coff, arena: Allocator, name: []const u8) !?[]const u8 {
14741483 return null;
14751484}
14761485
1477pub fn getDeclVAddr(self: *Coff, decl: *const Module.Decl, reloc_info: link.File.RelocInfo) !u64 {
1486pub fn getDeclVAddr(
1487 self: *Coff,
1488 decl_index: Module.Decl.Index,
1489 reloc_info: link.File.RelocInfo,
1490) !u64 {
14781491 _ = reloc_info;
1492 const mod = self.base.options.module.?;
1493 const decl = mod.declPtr(decl_index);
14791494 assert(self.llvm_object == null);
14801495 return self.text_section_virtual_address + decl.link.coff.text_offset;
14811496}
src/link/Dwarf.zig+23-23
......@@ -67,7 +67,7 @@ pub const Atom = struct {
6767/// Decl's inner Atom is assigned an offset within the DWARF section.
6868pub const DeclState = struct {
6969 gpa: Allocator,
70 target: std.Target,
70 mod: *Module,
7171 dbg_line: std.ArrayList(u8),
7272 dbg_info: std.ArrayList(u8),
7373 abbrev_type_arena: std.heap.ArenaAllocator,
......@@ -81,10 +81,10 @@ pub const DeclState = struct {
8181 abbrev_relocs: std.ArrayListUnmanaged(AbbrevRelocation) = .{},
8282 exprloc_relocs: std.ArrayListUnmanaged(ExprlocRelocation) = .{},
8383
84 fn init(gpa: Allocator, target: std.Target) DeclState {
84 fn init(gpa: Allocator, mod: *Module) DeclState {
8585 return .{
8686 .gpa = gpa,
87 .target = target,
87 .mod = mod,
8888 .dbg_line = std.ArrayList(u8).init(gpa),
8989 .dbg_info = std.ArrayList(u8).init(gpa),
9090 .abbrev_type_arena = std.heap.ArenaAllocator.init(gpa),
......@@ -118,7 +118,7 @@ pub const DeclState = struct {
118118 addend: ?u32,
119119 ) !void {
120120 const resolv = self.abbrev_resolver.getContext(ty, .{
121 .target = self.target,
121 .mod = self.mod,
122122 }) orelse blk: {
123123 const sym_index = @intCast(u32, self.abbrev_table.items.len);
124124 try self.abbrev_table.append(self.gpa, .{
......@@ -128,10 +128,10 @@ pub const DeclState = struct {
128128 });
129129 log.debug("@{d}: {}", .{ sym_index, ty.fmtDebug() });
130130 try self.abbrev_resolver.putNoClobberContext(self.gpa, ty, sym_index, .{
131 .target = self.target,
131 .mod = self.mod,
132132 });
133133 break :blk self.abbrev_resolver.getContext(ty, .{
134 .target = self.target,
134 .mod = self.mod,
135135 }).?;
136136 };
137137 const add: u32 = addend orelse 0;
......@@ -153,8 +153,8 @@ pub const DeclState = struct {
153153 ) error{OutOfMemory}!void {
154154 const arena = self.abbrev_type_arena.allocator();
155155 const dbg_info_buffer = &self.dbg_info;
156 const target = self.target;
157 const target_endian = self.target.cpu.arch.endian();
156 const target = module.getTarget();
157 const target_endian = target.cpu.arch.endian();
158158
159159 switch (ty.zigTypeTag()) {
160160 .NoReturn => unreachable,
......@@ -181,7 +181,7 @@ pub const DeclState = struct {
181181 // DW.AT.byte_size, DW.FORM.data1
182182 dbg_info_buffer.appendAssumeCapacity(@intCast(u8, ty.abiSize(target)));
183183 // DW.AT.name, DW.FORM.string
184 try dbg_info_buffer.writer().print("{}\x00", .{ty.fmt(target)});
184 try dbg_info_buffer.writer().print("{}\x00", .{ty.fmt(module)});
185185 },
186186 .Optional => {
187187 if (ty.isPtrLikeOptional()) {
......@@ -192,7 +192,7 @@ pub const DeclState = struct {
192192 // DW.AT.byte_size, DW.FORM.data1
193193 dbg_info_buffer.appendAssumeCapacity(@intCast(u8, ty.abiSize(target)));
194194 // DW.AT.name, DW.FORM.string
195 try dbg_info_buffer.writer().print("{}\x00", .{ty.fmt(target)});
195 try dbg_info_buffer.writer().print("{}\x00", .{ty.fmt(module)});
196196 } else {
197197 // Non-pointer optionals are structs: struct { .maybe = *, .val = * }
198198 var buf = try arena.create(Type.Payload.ElemType);
......@@ -203,7 +203,7 @@ pub const DeclState = struct {
203203 const abi_size = ty.abiSize(target);
204204 try leb128.writeULEB128(dbg_info_buffer.writer(), abi_size);
205205 // DW.AT.name, DW.FORM.string
206 try dbg_info_buffer.writer().print("{}\x00", .{ty.fmt(target)});
206 try dbg_info_buffer.writer().print("{}\x00", .{ty.fmt(module)});
207207 // DW.AT.member
208208 try dbg_info_buffer.ensureUnusedCapacity(7);
209209 dbg_info_buffer.appendAssumeCapacity(@enumToInt(AbbrevKind.struct_member));
......@@ -242,7 +242,7 @@ pub const DeclState = struct {
242242 // DW.AT.byte_size, DW.FORM.sdata
243243 dbg_info_buffer.appendAssumeCapacity(@sizeOf(usize) * 2);
244244 // DW.AT.name, DW.FORM.string
245 try dbg_info_buffer.writer().print("{}\x00", .{ty.fmt(target)});
245 try dbg_info_buffer.writer().print("{}\x00", .{ty.fmt(module)});
246246 // DW.AT.member
247247 try dbg_info_buffer.ensureUnusedCapacity(5);
248248 dbg_info_buffer.appendAssumeCapacity(@enumToInt(AbbrevKind.struct_member));
......@@ -285,7 +285,7 @@ pub const DeclState = struct {
285285 // DW.AT.array_type
286286 try dbg_info_buffer.append(@enumToInt(AbbrevKind.array_type));
287287 // DW.AT.name, DW.FORM.string
288 try dbg_info_buffer.writer().print("{}\x00", .{ty.fmt(target)});
288 try dbg_info_buffer.writer().print("{}\x00", .{ty.fmt(module)});
289289 // DW.AT.type, DW.FORM.ref4
290290 var index = dbg_info_buffer.items.len;
291291 try dbg_info_buffer.resize(index + 4);
......@@ -312,7 +312,7 @@ pub const DeclState = struct {
312312 switch (ty.tag()) {
313313 .tuple, .anon_struct => {
314314 // DW.AT.name, DW.FORM.string
315 try dbg_info_buffer.writer().print("{}\x00", .{ty.fmt(target)});
315 try dbg_info_buffer.writer().print("{}\x00", .{ty.fmt(module)});
316316
317317 const fields = ty.tupleFields();
318318 for (fields.types) |field, field_index| {
......@@ -331,7 +331,7 @@ pub const DeclState = struct {
331331 },
332332 else => {
333333 // DW.AT.name, DW.FORM.string
334 const struct_name = try ty.nameAllocArena(arena, target);
334 const struct_name = try ty.nameAllocArena(arena, module);
335335 try dbg_info_buffer.ensureUnusedCapacity(struct_name.len + 1);
336336 dbg_info_buffer.appendSliceAssumeCapacity(struct_name);
337337 dbg_info_buffer.appendAssumeCapacity(0);
......@@ -372,7 +372,7 @@ pub const DeclState = struct {
372372 const abi_size = ty.abiSize(target);
373373 try leb128.writeULEB128(dbg_info_buffer.writer(), abi_size);
374374 // DW.AT.name, DW.FORM.string
375 const enum_name = try ty.nameAllocArena(arena, target);
375 const enum_name = try ty.nameAllocArena(arena, module);
376376 try dbg_info_buffer.ensureUnusedCapacity(enum_name.len + 1);
377377 dbg_info_buffer.appendSliceAssumeCapacity(enum_name);
378378 dbg_info_buffer.appendAssumeCapacity(0);
......@@ -410,7 +410,7 @@ pub const DeclState = struct {
410410 const payload_offset = if (layout.tag_align >= layout.payload_align) layout.tag_size else 0;
411411 const tag_offset = if (layout.tag_align >= layout.payload_align) 0 else layout.payload_size;
412412 const is_tagged = layout.tag_size > 0;
413 const union_name = try ty.nameAllocArena(arena, target);
413 const union_name = try ty.nameAllocArena(arena, module);
414414
415415 // TODO this is temporary to match current state of unions in Zig - we don't yet have
416416 // safety checks implemented meaning the implicit tag is not yet stored and generated
......@@ -491,7 +491,7 @@ pub const DeclState = struct {
491491 self.abbrev_type_arena.allocator(),
492492 module,
493493 ty,
494 self.target,
494 target,
495495 &self.dbg_info,
496496 );
497497 },
......@@ -507,7 +507,7 @@ pub const DeclState = struct {
507507 // DW.AT.byte_size, DW.FORM.sdata
508508 try leb128.writeULEB128(dbg_info_buffer.writer(), abi_size);
509509 // DW.AT.name, DW.FORM.string
510 const name = try ty.nameAllocArena(arena, target);
510 const name = try ty.nameAllocArena(arena, module);
511511 try dbg_info_buffer.writer().print("{s}\x00", .{name});
512512
513513 // DW.AT.member
......@@ -654,17 +654,17 @@ pub fn deinit(self: *Dwarf) void {
654654
655655/// Initializes Decl's state and its matching output buffers.
656656/// Call this before `commitDeclState`.
657pub fn initDeclState(self: *Dwarf, decl: *Module.Decl) !DeclState {
657pub fn initDeclState(self: *Dwarf, mod: *Module, decl: *Module.Decl) !DeclState {
658658 const tracy = trace(@src());
659659 defer tracy.end();
660660
661 const decl_name = try decl.getFullyQualifiedName(self.allocator);
661 const decl_name = try decl.getFullyQualifiedName(mod);
662662 defer self.allocator.free(decl_name);
663663
664664 log.debug("initDeclState {s}{*}", .{ decl_name, decl });
665665
666666 const gpa = self.allocator;
667 var decl_state = DeclState.init(gpa, self.target);
667 var decl_state = DeclState.init(gpa, mod);
668668 errdefer decl_state.deinit();
669669 const dbg_line_buffer = &decl_state.dbg_line;
670670 const dbg_info_buffer = &decl_state.dbg_info;
......@@ -2133,7 +2133,7 @@ fn addDbgInfoErrorSet(
21332133 const abi_size = ty.abiSize(target);
21342134 try leb128.writeULEB128(dbg_info_buffer.writer(), abi_size);
21352135 // DW.AT.name, DW.FORM.string
2136 const name = try ty.nameAllocArena(arena, target);
2136 const name = try ty.nameAllocArena(arena, module);
21372137 try dbg_info_buffer.writer().print("{s}\x00", .{name});
21382138
21392139 // DW.AT.enumerator
src/link/Elf.zig+57-41
......@@ -134,7 +134,7 @@ atom_free_lists: std.AutoHashMapUnmanaged(u16, std.ArrayListUnmanaged(*TextBlock
134134/// We store them here so that we can properly dispose of any allocated
135135/// memory within the atom in the incremental linker.
136136/// TODO consolidate this.
137decls: std.AutoHashMapUnmanaged(*Module.Decl, ?u16) = .{},
137decls: std.AutoHashMapUnmanaged(Module.Decl.Index, ?u16) = .{},
138138
139139/// List of atoms that are owned directly by the linker.
140140/// Currently these are only atoms that are the result of linking
......@@ -178,7 +178,7 @@ const Reloc = struct {
178178};
179179
180180const RelocTable = std.AutoHashMapUnmanaged(*TextBlock, std.ArrayListUnmanaged(Reloc));
181const UnnamedConstTable = std.AutoHashMapUnmanaged(*Module.Decl, std.ArrayListUnmanaged(*TextBlock));
181const UnnamedConstTable = std.AutoHashMapUnmanaged(Module.Decl.Index, std.ArrayListUnmanaged(*TextBlock));
182182
183183/// When allocating, the ideal_capacity is calculated by
184184/// actual_capacity + (actual_capacity / ideal_factor)
......@@ -389,7 +389,10 @@ pub fn deinit(self: *Elf) void {
389389 }
390390}
391391
392pub fn getDeclVAddr(self: *Elf, decl: *const Module.Decl, reloc_info: File.RelocInfo) !u64 {
392pub fn getDeclVAddr(self: *Elf, decl_index: Module.Decl.Index, reloc_info: File.RelocInfo) !u64 {
393 const mod = self.base.options.module.?;
394 const decl = mod.declPtr(decl_index);
395
393396 assert(self.llvm_object == null);
394397 assert(decl.link.elf.local_sym_index != 0);
395398
......@@ -2189,15 +2192,17 @@ fn allocateLocalSymbol(self: *Elf) !u32 {
21892192 return index;
21902193}
21912194
2192pub fn allocateDeclIndexes(self: *Elf, decl: *Module.Decl) !void {
2195pub fn allocateDeclIndexes(self: *Elf, decl_index: Module.Decl.Index) !void {
21932196 if (self.llvm_object) |_| return;
21942197
2198 const mod = self.base.options.module.?;
2199 const decl = mod.declPtr(decl_index);
21952200 if (decl.link.elf.local_sym_index != 0) return;
21962201
21972202 try self.offset_table.ensureUnusedCapacity(self.base.allocator, 1);
2198 try self.decls.putNoClobber(self.base.allocator, decl, null);
2203 try self.decls.putNoClobber(self.base.allocator, decl_index, null);
21992204
2200 const decl_name = try decl.getFullyQualifiedName(self.base.allocator);
2205 const decl_name = try decl.getFullyQualifiedName(mod);
22012206 defer self.base.allocator.free(decl_name);
22022207
22032208 log.debug("allocating symbol indexes for {s}", .{decl_name});
......@@ -2214,8 +2219,8 @@ pub fn allocateDeclIndexes(self: *Elf, decl: *Module.Decl) !void {
22142219 self.offset_table.items[decl.link.elf.offset_table_index] = 0;
22152220}
22162221
2217fn freeUnnamedConsts(self: *Elf, decl: *Module.Decl) void {
2218 const unnamed_consts = self.unnamed_const_atoms.getPtr(decl) orelse return;
2222fn freeUnnamedConsts(self: *Elf, decl_index: Module.Decl.Index) void {
2223 const unnamed_consts = self.unnamed_const_atoms.getPtr(decl_index) orelse return;
22192224 for (unnamed_consts.items) |atom| {
22202225 self.freeTextBlock(atom, self.phdr_load_ro_index.?);
22212226 self.local_symbol_free_list.append(self.base.allocator, atom.local_sym_index) catch {};
......@@ -2225,15 +2230,18 @@ fn freeUnnamedConsts(self: *Elf, decl: *Module.Decl) void {
22252230 unnamed_consts.clearAndFree(self.base.allocator);
22262231}
22272232
2228pub fn freeDecl(self: *Elf, decl: *Module.Decl) void {
2233pub fn freeDecl(self: *Elf, decl_index: Module.Decl.Index) void {
22292234 if (build_options.have_llvm) {
2230 if (self.llvm_object) |llvm_object| return llvm_object.freeDecl(decl);
2235 if (self.llvm_object) |llvm_object| return llvm_object.freeDecl(decl_index);
22312236 }
22322237
2233 const kv = self.decls.fetchRemove(decl);
2238 const mod = self.base.options.module.?;
2239 const decl = mod.declPtr(decl_index);
2240
2241 const kv = self.decls.fetchRemove(decl_index);
22342242 if (kv.?.value) |index| {
22352243 self.freeTextBlock(&decl.link.elf, index);
2236 self.freeUnnamedConsts(decl);
2244 self.freeUnnamedConsts(decl_index);
22372245 }
22382246
22392247 // Appending to free lists is allowed to fail because the free lists are heuristics based anyway.
......@@ -2274,14 +2282,17 @@ fn getDeclPhdrIndex(self: *Elf, decl: *Module.Decl) !u16 {
22742282 return phdr_index;
22752283}
22762284
2277fn updateDeclCode(self: *Elf, decl: *Module.Decl, code: []const u8, stt_bits: u8) !*elf.Elf64_Sym {
2278 const decl_name = try decl.getFullyQualifiedName(self.base.allocator);
2285fn updateDeclCode(self: *Elf, decl_index: Module.Decl.Index, code: []const u8, stt_bits: u8) !*elf.Elf64_Sym {
2286 const mod = self.base.options.module.?;
2287 const decl = mod.declPtr(decl_index);
2288
2289 const decl_name = try decl.getFullyQualifiedName(mod);
22792290 defer self.base.allocator.free(decl_name);
22802291
22812292 log.debug("updateDeclCode {s}{*}", .{ decl_name, decl });
22822293 const required_alignment = decl.ty.abiAlignment(self.base.options.target);
22832294
2284 const decl_ptr = self.decls.getPtr(decl).?;
2295 const decl_ptr = self.decls.getPtr(decl_index).?;
22852296 if (decl_ptr.* == null) {
22862297 decl_ptr.* = try self.getDeclPhdrIndex(decl);
22872298 }
......@@ -2355,10 +2366,11 @@ pub fn updateFunc(self: *Elf, module: *Module, func: *Module.Fn, air: Air, liven
23552366 var code_buffer = std.ArrayList(u8).init(self.base.allocator);
23562367 defer code_buffer.deinit();
23572368
2358 const decl = func.owner_decl;
2359 self.freeUnnamedConsts(decl);
2369 const decl_index = func.owner_decl;
2370 const decl = module.declPtr(decl_index);
2371 self.freeUnnamedConsts(decl_index);
23602372
2361 var decl_state: ?Dwarf.DeclState = if (self.dwarf) |*dw| try dw.initDeclState(decl) else null;
2373 var decl_state: ?Dwarf.DeclState = if (self.dwarf) |*dw| try dw.initDeclState(module, decl) else null;
23622374 defer if (decl_state) |*ds| ds.deinit();
23632375
23642376 const res = if (decl_state) |*ds|
......@@ -2372,11 +2384,11 @@ pub fn updateFunc(self: *Elf, module: *Module, func: *Module.Fn, air: Air, liven
23722384 .appended => code_buffer.items,
23732385 .fail => |em| {
23742386 decl.analysis = .codegen_failure;
2375 try module.failed_decls.put(module.gpa, decl, em);
2387 try module.failed_decls.put(module.gpa, decl_index, em);
23762388 return;
23772389 },
23782390 };
2379 const local_sym = try self.updateDeclCode(decl, code, elf.STT_FUNC);
2391 const local_sym = try self.updateDeclCode(decl_index, code, elf.STT_FUNC);
23802392 if (decl_state) |*ds| {
23812393 try self.dwarf.?.commitDeclState(
23822394 &self.base,
......@@ -2389,21 +2401,23 @@ pub fn updateFunc(self: *Elf, module: *Module, func: *Module.Fn, air: Air, liven
23892401 }
23902402
23912403 // Since we updated the vaddr and the size, each corresponding export symbol also needs to be updated.
2392 const decl_exports = module.decl_exports.get(decl) orelse &[0]*Module.Export{};
2393 return self.updateDeclExports(module, decl, decl_exports);
2404 const decl_exports = module.decl_exports.get(decl_index) orelse &[0]*Module.Export{};
2405 return self.updateDeclExports(module, decl_index, decl_exports);
23942406}
23952407
2396pub fn updateDecl(self: *Elf, module: *Module, decl: *Module.Decl) !void {
2408pub fn updateDecl(self: *Elf, module: *Module, decl_index: Module.Decl.Index) !void {
23972409 if (build_options.skip_non_native and builtin.object_format != .elf) {
23982410 @panic("Attempted to compile for object format that was disabled by build configuration");
23992411 }
24002412 if (build_options.have_llvm) {
2401 if (self.llvm_object) |llvm_object| return llvm_object.updateDecl(module, decl);
2413 if (self.llvm_object) |llvm_object| return llvm_object.updateDecl(module, decl_index);
24022414 }
24032415
24042416 const tracy = trace(@src());
24052417 defer tracy.end();
24062418
2419 const decl = module.declPtr(decl_index);
2420
24072421 if (decl.val.tag() == .extern_fn) {
24082422 return; // TODO Should we do more when front-end analyzed extern decl?
24092423 }
......@@ -2414,12 +2428,12 @@ pub fn updateDecl(self: *Elf, module: *Module, decl: *Module.Decl) !void {
24142428 }
24152429 }
24162430
2417 assert(!self.unnamed_const_atoms.contains(decl));
2431 assert(!self.unnamed_const_atoms.contains(decl_index));
24182432
24192433 var code_buffer = std.ArrayList(u8).init(self.base.allocator);
24202434 defer code_buffer.deinit();
24212435
2422 var decl_state: ?Dwarf.DeclState = if (self.dwarf) |*dw| try dw.initDeclState(decl) else null;
2436 var decl_state: ?Dwarf.DeclState = if (self.dwarf) |*dw| try dw.initDeclState(module, decl) else null;
24232437 defer if (decl_state) |*ds| ds.deinit();
24242438
24252439 // TODO implement .debug_info for global variables
......@@ -2446,12 +2460,12 @@ pub fn updateDecl(self: *Elf, module: *Module, decl: *Module.Decl) !void {
24462460 .appended => code_buffer.items,
24472461 .fail => |em| {
24482462 decl.analysis = .codegen_failure;
2449 try module.failed_decls.put(module.gpa, decl, em);
2463 try module.failed_decls.put(module.gpa, decl_index, em);
24502464 return;
24512465 },
24522466 };
24532467
2454 const local_sym = try self.updateDeclCode(decl, code, elf.STT_OBJECT);
2468 const local_sym = try self.updateDeclCode(decl_index, code, elf.STT_OBJECT);
24552469 if (decl_state) |*ds| {
24562470 try self.dwarf.?.commitDeclState(
24572471 &self.base,
......@@ -2464,16 +2478,18 @@ pub fn updateDecl(self: *Elf, module: *Module, decl: *Module.Decl) !void {
24642478 }
24652479
24662480 // Since we updated the vaddr and the size, each corresponding export symbol also needs to be updated.
2467 const decl_exports = module.decl_exports.get(decl) orelse &[0]*Module.Export{};
2468 return self.updateDeclExports(module, decl, decl_exports);
2481 const decl_exports = module.decl_exports.get(decl_index) orelse &[0]*Module.Export{};
2482 return self.updateDeclExports(module, decl_index, decl_exports);
24692483}
24702484
2471pub fn lowerUnnamedConst(self: *Elf, typed_value: TypedValue, decl: *Module.Decl) !u32 {
2485pub fn lowerUnnamedConst(self: *Elf, typed_value: TypedValue, decl_index: Module.Decl.Index) !u32 {
24722486 var code_buffer = std.ArrayList(u8).init(self.base.allocator);
24732487 defer code_buffer.deinit();
24742488
2475 const module = self.base.options.module.?;
2476 const gop = try self.unnamed_const_atoms.getOrPut(self.base.allocator, decl);
2489 const mod = self.base.options.module.?;
2490 const decl = mod.declPtr(decl_index);
2491
2492 const gop = try self.unnamed_const_atoms.getOrPut(self.base.allocator, decl_index);
24772493 if (!gop.found_existing) {
24782494 gop.value_ptr.* = .{};
24792495 }
......@@ -2485,7 +2501,7 @@ pub fn lowerUnnamedConst(self: *Elf, typed_value: TypedValue, decl: *Module.Decl
24852501 try self.managed_atoms.append(self.base.allocator, atom);
24862502
24872503 const name_str_index = blk: {
2488 const decl_name = try decl.getFullyQualifiedName(self.base.allocator);
2504 const decl_name = try decl.getFullyQualifiedName(mod);
24892505 defer self.base.allocator.free(decl_name);
24902506
24912507 const index = unnamed_consts.items.len;
......@@ -2510,7 +2526,7 @@ pub fn lowerUnnamedConst(self: *Elf, typed_value: TypedValue, decl: *Module.Decl
25102526 .appended => code_buffer.items,
25112527 .fail => |em| {
25122528 decl.analysis = .codegen_failure;
2513 try module.failed_decls.put(module.gpa, decl, em);
2529 try mod.failed_decls.put(mod.gpa, decl_index, em);
25142530 log.err("{s}", .{em.msg});
25152531 return error.AnalysisFail;
25162532 },
......@@ -2547,24 +2563,25 @@ pub fn lowerUnnamedConst(self: *Elf, typed_value: TypedValue, decl: *Module.Decl
25472563pub fn updateDeclExports(
25482564 self: *Elf,
25492565 module: *Module,
2550 decl: *Module.Decl,
2566 decl_index: Module.Decl.Index,
25512567 exports: []const *Module.Export,
25522568) !void {
25532569 if (build_options.skip_non_native and builtin.object_format != .elf) {
25542570 @panic("Attempted to compile for object format that was disabled by build configuration");
25552571 }
25562572 if (build_options.have_llvm) {
2557 if (self.llvm_object) |llvm_object| return llvm_object.updateDeclExports(module, decl, exports);
2573 if (self.llvm_object) |llvm_object| return llvm_object.updateDeclExports(module, decl_index, exports);
25582574 }
25592575
25602576 const tracy = trace(@src());
25612577 defer tracy.end();
25622578
25632579 try self.global_symbols.ensureUnusedCapacity(self.base.allocator, exports.len);
2580 const decl = module.declPtr(decl_index);
25642581 if (decl.link.elf.local_sym_index == 0) return;
25652582 const decl_sym = self.local_symbols.items[decl.link.elf.local_sym_index];
25662583
2567 const decl_ptr = self.decls.getPtr(decl).?;
2584 const decl_ptr = self.decls.getPtr(decl_index).?;
25682585 if (decl_ptr.* == null) {
25692586 decl_ptr.* = try self.getDeclPhdrIndex(decl);
25702587 }
......@@ -2633,12 +2650,11 @@ pub fn updateDeclExports(
26332650}
26342651
26352652/// Must be called only after a successful call to `updateDecl`.
2636pub fn updateDeclLineNumber(self: *Elf, module: *Module, decl: *const Module.Decl) !void {
2637 _ = module;
2653pub fn updateDeclLineNumber(self: *Elf, mod: *Module, decl: *const Module.Decl) !void {
26382654 const tracy = trace(@src());
26392655 defer tracy.end();
26402656
2641 const decl_name = try decl.getFullyQualifiedName(self.base.allocator);
2657 const decl_name = try decl.getFullyQualifiedName(mod);
26422658 defer self.base.allocator.free(decl_name);
26432659
26442660 log.debug("updateDeclLineNumber {s}{*}", .{ decl_name, decl });
src/link/MachO.zig+65-47
......@@ -247,14 +247,14 @@ unnamed_const_atoms: UnnamedConstTable = .{},
247247/// We store them here so that we can properly dispose of any allocated
248248/// memory within the atom in the incremental linker.
249249/// TODO consolidate this.
250decls: std.AutoArrayHashMapUnmanaged(*Module.Decl, ?MatchingSection) = .{},
250decls: std.AutoArrayHashMapUnmanaged(Module.Decl.Index, ?MatchingSection) = .{},
251251
252252const Entry = struct {
253253 target: Atom.Relocation.Target,
254254 atom: *Atom,
255255};
256256
257const UnnamedConstTable = std.AutoHashMapUnmanaged(*Module.Decl, std.ArrayListUnmanaged(*Atom));
257const UnnamedConstTable = std.AutoHashMapUnmanaged(Module.Decl.Index, std.ArrayListUnmanaged(*Atom));
258258
259259const PendingUpdate = union(enum) {
260260 resolve_undef: u32,
......@@ -3451,10 +3451,15 @@ pub fn deinit(self: *MachO) void {
34513451 }
34523452 self.atom_free_lists.deinit(self.base.allocator);
34533453 }
3454 for (self.decls.keys()) |decl| {
3455 decl.link.macho.deinit(self.base.allocator);
3454 if (self.base.options.module) |mod| {
3455 for (self.decls.keys()) |decl_index| {
3456 const decl = mod.declPtr(decl_index);
3457 decl.link.macho.deinit(self.base.allocator);
3458 }
3459 self.decls.deinit(self.base.allocator);
3460 } else {
3461 assert(self.decls.count() == 0);
34563462 }
3457 self.decls.deinit(self.base.allocator);
34583463
34593464 {
34603465 var it = self.unnamed_const_atoms.valueIterator();
......@@ -3652,13 +3657,14 @@ pub fn allocateTlvPtrEntry(self: *MachO, target: Atom.Relocation.Target) !u32 {
36523657 return index;
36533658}
36543659
3655pub fn allocateDeclIndexes(self: *MachO, decl: *Module.Decl) !void {
3660pub fn allocateDeclIndexes(self: *MachO, decl_index: Module.Decl.Index) !void {
36563661 if (self.llvm_object) |_| return;
3662 const decl = self.base.options.module.?.declPtr(decl_index);
36573663 if (decl.link.macho.local_sym_index != 0) return;
36583664
36593665 decl.link.macho.local_sym_index = try self.allocateLocalSymbol();
36603666 try self.atom_by_index_table.putNoClobber(self.base.allocator, decl.link.macho.local_sym_index, &decl.link.macho);
3661 try self.decls.putNoClobber(self.base.allocator, decl, null);
3667 try self.decls.putNoClobber(self.base.allocator, decl_index, null);
36623668
36633669 const got_target = .{ .local = decl.link.macho.local_sym_index };
36643670 const got_index = try self.allocateGotEntry(got_target);
......@@ -3676,8 +3682,9 @@ pub fn updateFunc(self: *MachO, module: *Module, func: *Module.Fn, air: Air, liv
36763682 const tracy = trace(@src());
36773683 defer tracy.end();
36783684
3679 const decl = func.owner_decl;
3680 self.freeUnnamedConsts(decl);
3685 const decl_index = func.owner_decl;
3686 const decl = module.declPtr(decl_index);
3687 self.freeUnnamedConsts(decl_index);
36813688
36823689 // TODO clearing the code and relocs buffer should probably be orchestrated
36833690 // in a different, smarter, more automatic way somewhere else, in a more centralised
......@@ -3690,7 +3697,7 @@ pub fn updateFunc(self: *MachO, module: *Module, func: *Module.Fn, air: Air, liv
36903697 defer code_buffer.deinit();
36913698
36923699 var decl_state = if (self.d_sym) |*d_sym|
3693 try d_sym.dwarf.initDeclState(decl)
3700 try d_sym.dwarf.initDeclState(module, decl)
36943701 else
36953702 null;
36963703 defer if (decl_state) |*ds| ds.deinit();
......@@ -3708,12 +3715,12 @@ pub fn updateFunc(self: *MachO, module: *Module, func: *Module.Fn, air: Air, liv
37083715 },
37093716 .fail => |em| {
37103717 decl.analysis = .codegen_failure;
3711 try module.failed_decls.put(module.gpa, decl, em);
3718 try module.failed_decls.put(module.gpa, decl_index, em);
37123719 return;
37133720 },
37143721 }
37153722
3716 const symbol = try self.placeDecl(decl, decl.link.macho.code.items.len);
3723 const symbol = try self.placeDecl(decl_index, decl.link.macho.code.items.len);
37173724
37183725 if (decl_state) |*ds| {
37193726 try self.d_sym.?.dwarf.commitDeclState(
......@@ -3728,22 +3735,23 @@ pub fn updateFunc(self: *MachO, module: *Module, func: *Module.Fn, air: Air, liv
37283735
37293736 // Since we updated the vaddr and the size, each corresponding export symbol also
37303737 // needs to be updated.
3731 const decl_exports = module.decl_exports.get(decl) orelse &[0]*Module.Export{};
3732 try self.updateDeclExports(module, decl, decl_exports);
3738 const decl_exports = module.decl_exports.get(decl_index) orelse &[0]*Module.Export{};
3739 try self.updateDeclExports(module, decl_index, decl_exports);
37333740}
37343741
3735pub fn lowerUnnamedConst(self: *MachO, typed_value: TypedValue, decl: *Module.Decl) !u32 {
3742pub fn lowerUnnamedConst(self: *MachO, typed_value: TypedValue, decl_index: Module.Decl.Index) !u32 {
37363743 var code_buffer = std.ArrayList(u8).init(self.base.allocator);
37373744 defer code_buffer.deinit();
37383745
37393746 const module = self.base.options.module.?;
3740 const gop = try self.unnamed_const_atoms.getOrPut(self.base.allocator, decl);
3747 const gop = try self.unnamed_const_atoms.getOrPut(self.base.allocator, decl_index);
37413748 if (!gop.found_existing) {
37423749 gop.value_ptr.* = .{};
37433750 }
37443751 const unnamed_consts = gop.value_ptr;
37453752
3746 const decl_name = try decl.getFullyQualifiedName(self.base.allocator);
3753 const decl = module.declPtr(decl_index);
3754 const decl_name = try decl.getFullyQualifiedName(module);
37473755 defer self.base.allocator.free(decl_name);
37483756
37493757 const name_str_index = blk: {
......@@ -3769,7 +3777,7 @@ pub fn lowerUnnamedConst(self: *MachO, typed_value: TypedValue, decl: *Module.De
37693777 .appended => code_buffer.items,
37703778 .fail => |em| {
37713779 decl.analysis = .codegen_failure;
3772 try module.failed_decls.put(module.gpa, decl, em);
3780 try module.failed_decls.put(module.gpa, decl_index, em);
37733781 log.err("{s}", .{em.msg});
37743782 return error.AnalysisFail;
37753783 },
......@@ -3800,16 +3808,18 @@ pub fn lowerUnnamedConst(self: *MachO, typed_value: TypedValue, decl: *Module.De
38003808 return atom.local_sym_index;
38013809}
38023810
3803pub fn updateDecl(self: *MachO, module: *Module, decl: *Module.Decl) !void {
3811pub fn updateDecl(self: *MachO, module: *Module, decl_index: Module.Decl.Index) !void {
38043812 if (build_options.skip_non_native and builtin.object_format != .macho) {
38053813 @panic("Attempted to compile for object format that was disabled by build configuration");
38063814 }
38073815 if (build_options.have_llvm) {
3808 if (self.llvm_object) |llvm_object| return llvm_object.updateDecl(module, decl);
3816 if (self.llvm_object) |llvm_object| return llvm_object.updateDecl(module, decl_index);
38093817 }
38103818 const tracy = trace(@src());
38113819 defer tracy.end();
38123820
3821 const decl = module.declPtr(decl_index);
3822
38133823 if (decl.val.tag() == .extern_fn) {
38143824 return; // TODO Should we do more when front-end analyzed extern decl?
38153825 }
......@@ -3824,7 +3834,7 @@ pub fn updateDecl(self: *MachO, module: *Module, decl: *Module.Decl) !void {
38243834 defer code_buffer.deinit();
38253835
38263836 var decl_state: ?Dwarf.DeclState = if (self.d_sym) |*d_sym|
3827 try d_sym.dwarf.initDeclState(decl)
3837 try d_sym.dwarf.initDeclState(module, decl)
38283838 else
38293839 null;
38303840 defer if (decl_state) |*ds| ds.deinit();
......@@ -3862,12 +3872,12 @@ pub fn updateDecl(self: *MachO, module: *Module, decl: *Module.Decl) !void {
38623872 },
38633873 .fail => |em| {
38643874 decl.analysis = .codegen_failure;
3865 try module.failed_decls.put(module.gpa, decl, em);
3875 try module.failed_decls.put(module.gpa, decl_index, em);
38663876 return;
38673877 },
38683878 }
38693879 };
3870 const symbol = try self.placeDecl(decl, code.len);
3880 const symbol = try self.placeDecl(decl_index, code.len);
38713881
38723882 if (decl_state) |*ds| {
38733883 try self.d_sym.?.dwarf.commitDeclState(
......@@ -3882,13 +3892,13 @@ pub fn updateDecl(self: *MachO, module: *Module, decl: *Module.Decl) !void {
38823892
38833893 // Since we updated the vaddr and the size, each corresponding export symbol also
38843894 // needs to be updated.
3885 const decl_exports = module.decl_exports.get(decl) orelse &[0]*Module.Export{};
3886 try self.updateDeclExports(module, decl, decl_exports);
3895 const decl_exports = module.decl_exports.get(decl_index) orelse &[0]*Module.Export{};
3896 try self.updateDeclExports(module, decl_index, decl_exports);
38873897}
38883898
38893899/// Checks if the value, or any of its embedded values stores a pointer, and thus requires
38903900/// a rebase opcode for the dynamic linker.
3891fn needsPointerRebase(ty: Type, val: Value, target: std.Target) bool {
3901fn needsPointerRebase(ty: Type, val: Value, mod: *Module) bool {
38923902 if (ty.zigTypeTag() == .Fn) {
38933903 return false;
38943904 }
......@@ -3903,8 +3913,8 @@ fn needsPointerRebase(ty: Type, val: Value, target: std.Target) bool {
39033913 if (ty.arrayLen() == 0) return false;
39043914 const elem_ty = ty.childType();
39053915 var elem_value_buf: Value.ElemValueBuffer = undefined;
3906 const elem_val = val.elemValueBuffer(0, &elem_value_buf);
3907 return needsPointerRebase(elem_ty, elem_val, target);
3916 const elem_val = val.elemValueBuffer(mod, 0, &elem_value_buf);
3917 return needsPointerRebase(elem_ty, elem_val, mod);
39083918 },
39093919 .Struct => {
39103920 const fields = ty.structFields().values();
......@@ -3912,7 +3922,7 @@ fn needsPointerRebase(ty: Type, val: Value, target: std.Target) bool {
39123922 if (val.castTag(.aggregate)) |payload| {
39133923 const field_values = payload.data;
39143924 for (field_values) |field_val, i| {
3915 if (needsPointerRebase(fields[i].ty, field_val, target)) return true;
3925 if (needsPointerRebase(fields[i].ty, field_val, mod)) return true;
39163926 } else return false;
39173927 } else return false;
39183928 },
......@@ -3921,18 +3931,18 @@ fn needsPointerRebase(ty: Type, val: Value, target: std.Target) bool {
39213931 const sub_val = payload.data;
39223932 var buffer: Type.Payload.ElemType = undefined;
39233933 const sub_ty = ty.optionalChild(&buffer);
3924 return needsPointerRebase(sub_ty, sub_val, target);
3934 return needsPointerRebase(sub_ty, sub_val, mod);
39253935 } else return false;
39263936 },
39273937 .Union => {
39283938 const union_obj = val.cast(Value.Payload.Union).?.data;
3929 const active_field_ty = ty.unionFieldType(union_obj.tag, target);
3930 return needsPointerRebase(active_field_ty, union_obj.val, target);
3939 const active_field_ty = ty.unionFieldType(union_obj.tag, mod);
3940 return needsPointerRebase(active_field_ty, union_obj.val, mod);
39313941 },
39323942 .ErrorUnion => {
39333943 if (val.castTag(.eu_payload)) |payload| {
39343944 const payload_ty = ty.errorUnionPayload();
3935 return needsPointerRebase(payload_ty, payload.data, target);
3945 return needsPointerRebase(payload_ty, payload.data, mod);
39363946 } else return false;
39373947 },
39383948 else => return false,
......@@ -3942,6 +3952,7 @@ fn needsPointerRebase(ty: Type, val: Value, target: std.Target) bool {
39423952fn getMatchingSectionAtom(self: *MachO, atom: *Atom, name: []const u8, ty: Type, val: Value) !MatchingSection {
39433953 const code = atom.code.items;
39443954 const target = self.base.options.target;
3955 const mod = self.base.options.module.?;
39453956 const alignment = ty.abiAlignment(target);
39463957 const align_log_2 = math.log2(alignment);
39473958 const zig_ty = ty.zigTypeTag();
......@@ -3969,7 +3980,7 @@ fn getMatchingSectionAtom(self: *MachO, atom: *Atom, name: []const u8, ty: Type,
39693980 };
39703981 }
39713982
3972 if (needsPointerRebase(ty, val, target)) {
3983 if (needsPointerRebase(ty, val, mod)) {
39733984 break :blk (try self.getMatchingSection(.{
39743985 .segname = makeStaticString("__DATA_CONST"),
39753986 .sectname = makeStaticString("__const"),
......@@ -4025,15 +4036,17 @@ fn getMatchingSectionAtom(self: *MachO, atom: *Atom, name: []const u8, ty: Type,
40254036 return match;
40264037}
40274038
4028fn placeDecl(self: *MachO, decl: *Module.Decl, code_len: usize) !*macho.nlist_64 {
4039fn placeDecl(self: *MachO, decl_index: Module.Decl.Index, code_len: usize) !*macho.nlist_64 {
4040 const module = self.base.options.module.?;
4041 const decl = module.declPtr(decl_index);
40294042 const required_alignment = decl.ty.abiAlignment(self.base.options.target);
40304043 assert(decl.link.macho.local_sym_index != 0); // Caller forgot to call allocateDeclIndexes()
40314044 const symbol = &self.locals.items[decl.link.macho.local_sym_index];
40324045
4033 const sym_name = try decl.getFullyQualifiedName(self.base.allocator);
4046 const sym_name = try decl.getFullyQualifiedName(module);
40344047 defer self.base.allocator.free(sym_name);
40354048
4036 const decl_ptr = self.decls.getPtr(decl).?;
4049 const decl_ptr = self.decls.getPtr(decl_index).?;
40374050 if (decl_ptr.* == null) {
40384051 decl_ptr.* = try self.getMatchingSectionAtom(&decl.link.macho, sym_name, decl.ty, decl.val);
40394052 }
......@@ -4101,19 +4114,20 @@ pub fn updateDeclLineNumber(self: *MachO, module: *Module, decl: *const Module.D
41014114pub fn updateDeclExports(
41024115 self: *MachO,
41034116 module: *Module,
4104 decl: *Module.Decl,
4117 decl_index: Module.Decl.Index,
41054118 exports: []const *Module.Export,
41064119) !void {
41074120 if (build_options.skip_non_native and builtin.object_format != .macho) {
41084121 @panic("Attempted to compile for object format that was disabled by build configuration");
41094122 }
41104123 if (build_options.have_llvm) {
4111 if (self.llvm_object) |llvm_object| return llvm_object.updateDeclExports(module, decl, exports);
4124 if (self.llvm_object) |llvm_object| return llvm_object.updateDeclExports(module, decl_index, exports);
41124125 }
41134126 const tracy = trace(@src());
41144127 defer tracy.end();
41154128
41164129 try self.globals.ensureUnusedCapacity(self.base.allocator, exports.len);
4130 const decl = module.declPtr(decl_index);
41174131 if (decl.link.macho.local_sym_index == 0) return;
41184132 const decl_sym = &self.locals.items[decl.link.macho.local_sym_index];
41194133
......@@ -4250,9 +4264,8 @@ pub fn deleteExport(self: *MachO, exp: Export) void {
42504264 global.n_value = 0;
42514265}
42524266
4253fn freeUnnamedConsts(self: *MachO, decl: *Module.Decl) void {
4254 log.debug("freeUnnamedConsts for decl {*}", .{decl});
4255 const unnamed_consts = self.unnamed_const_atoms.getPtr(decl) orelse return;
4267fn freeUnnamedConsts(self: *MachO, decl_index: Module.Decl.Index) void {
4268 const unnamed_consts = self.unnamed_const_atoms.getPtr(decl_index) orelse return;
42564269 for (unnamed_consts.items) |atom| {
42574270 self.freeAtom(atom, .{
42584271 .seg = self.text_segment_cmd_index.?,
......@@ -4267,15 +4280,17 @@ fn freeUnnamedConsts(self: *MachO, decl: *Module.Decl) void {
42674280 unnamed_consts.clearAndFree(self.base.allocator);
42684281}
42694282
4270pub fn freeDecl(self: *MachO, decl: *Module.Decl) void {
4283pub fn freeDecl(self: *MachO, decl_index: Module.Decl.Index) void {
42714284 if (build_options.have_llvm) {
4272 if (self.llvm_object) |llvm_object| return llvm_object.freeDecl(decl);
4285 if (self.llvm_object) |llvm_object| return llvm_object.freeDecl(decl_index);
42734286 }
4287 const mod = self.base.options.module.?;
4288 const decl = mod.declPtr(decl_index);
42744289 log.debug("freeDecl {*}", .{decl});
4275 const kv = self.decls.fetchSwapRemove(decl);
4290 const kv = self.decls.fetchSwapRemove(decl_index);
42764291 if (kv.?.value) |match| {
42774292 self.freeAtom(&decl.link.macho, match, false);
4278 self.freeUnnamedConsts(decl);
4293 self.freeUnnamedConsts(decl_index);
42794294 }
42804295 // Appending to free lists is allowed to fail because the free lists are heuristics based anyway.
42814296 if (decl.link.macho.local_sym_index != 0) {
......@@ -4307,7 +4322,10 @@ pub fn freeDecl(self: *MachO, decl: *Module.Decl) void {
43074322 }
43084323}
43094324
4310pub fn getDeclVAddr(self: *MachO, decl: *const Module.Decl, reloc_info: File.RelocInfo) !u64 {
4325pub fn getDeclVAddr(self: *MachO, decl_index: Module.Decl.Index, reloc_info: File.RelocInfo) !u64 {
4326 const mod = self.base.options.module.?;
4327 const decl = mod.declPtr(decl_index);
4328
43114329 assert(self.llvm_object == null);
43124330 assert(decl.link.macho.local_sym_index != 0);
43134331
src/link/NvPtx.zig+6-6
......@@ -74,27 +74,27 @@ pub fn updateFunc(self: *NvPtx, module: *Module, func: *Module.Fn, air: Air, liv
7474 try self.llvm_object.updateFunc(module, func, air, liveness);
7575}
7676
77pub fn updateDecl(self: *NvPtx, module: *Module, decl: *Module.Decl) !void {
77pub fn updateDecl(self: *NvPtx, module: *Module, decl_index: Module.Decl.Index) !void {
7878 if (!build_options.have_llvm) return;
79 return self.llvm_object.updateDecl(module, decl);
79 return self.llvm_object.updateDecl(module, decl_index);
8080}
8181
8282pub fn updateDeclExports(
8383 self: *NvPtx,
8484 module: *Module,
85 decl: *const Module.Decl,
85 decl_index: Module.Decl.Index,
8686 exports: []const *Module.Export,
8787) !void {
8888 if (!build_options.have_llvm) return;
8989 if (build_options.skip_non_native and builtin.object_format != .nvptx) {
9090 @panic("Attempted to compile for object format that was disabled by build configuration");
9191 }
92 return self.llvm_object.updateDeclExports(module, decl, exports);
92 return self.llvm_object.updateDeclExports(module, decl_index, exports);
9393}
9494
95pub fn freeDecl(self: *NvPtx, decl: *Module.Decl) void {
95pub fn freeDecl(self: *NvPtx, decl_index: Module.Decl.Index) void {
9696 if (!build_options.have_llvm) return;
97 return self.llvm_object.freeDecl(decl);
97 return self.llvm_object.freeDecl(decl_index);
9898}
9999
100100pub fn flush(self: *NvPtx, comp: *Compilation, prog_node: *std.Progress.Node) !void {
src/link/Plan9.zig+57-37
......@@ -59,9 +59,9 @@ path_arena: std.heap.ArenaAllocator,
5959/// If we group the decls by file, it makes it really easy to do this (put the symbol in the correct place)
6060fn_decl_table: std.AutoArrayHashMapUnmanaged(
6161 *Module.File,
62 struct { sym_index: u32, functions: std.AutoArrayHashMapUnmanaged(*Module.Decl, FnDeclOutput) = .{} },
62 struct { sym_index: u32, functions: std.AutoArrayHashMapUnmanaged(Module.Decl.Index, FnDeclOutput) = .{} },
6363) = .{},
64data_decl_table: std.AutoArrayHashMapUnmanaged(*Module.Decl, []const u8) = .{},
64data_decl_table: std.AutoArrayHashMapUnmanaged(Module.Decl.Index, []const u8) = .{},
6565
6666hdr: aout.ExecHdr = undefined,
6767
......@@ -162,11 +162,13 @@ pub fn createEmpty(gpa: Allocator, options: link.Options) !*Plan9 {
162162 return self;
163163}
164164
165fn putFn(self: *Plan9, decl: *Module.Decl, out: FnDeclOutput) !void {
165fn putFn(self: *Plan9, decl_index: Module.Decl.Index, out: FnDeclOutput) !void {
166166 const gpa = self.base.allocator;
167 const mod = self.base.options.module.?;
168 const decl = mod.declPtr(decl_index);
167169 const fn_map_res = try self.fn_decl_table.getOrPut(gpa, decl.getFileScope());
168170 if (fn_map_res.found_existing) {
169 try fn_map_res.value_ptr.functions.put(gpa, decl, out);
171 try fn_map_res.value_ptr.functions.put(gpa, decl_index, out);
170172 } else {
171173 const file = decl.getFileScope();
172174 const arena = self.path_arena.allocator();
......@@ -178,7 +180,7 @@ fn putFn(self: *Plan9, decl: *Module.Decl, out: FnDeclOutput) !void {
178180 break :blk @intCast(u32, self.syms.items.len - 1);
179181 },
180182 };
181 try fn_map_res.value_ptr.functions.put(gpa, decl, out);
183 try fn_map_res.value_ptr.functions.put(gpa, decl_index, out);
182184
183185 var a = std.ArrayList(u8).init(arena);
184186 errdefer a.deinit();
......@@ -229,9 +231,10 @@ pub fn updateFunc(self: *Plan9, module: *Module, func: *Module.Fn, air: Air, liv
229231 @panic("Attempted to compile for object format that was disabled by build configuration");
230232 }
231233
232 const decl = func.owner_decl;
234 const decl_index = func.owner_decl;
235 const decl = module.declPtr(decl_index);
233236
234 try self.seeDecl(decl);
237 try self.seeDecl(decl_index);
235238 log.debug("codegen decl {*} ({s})", .{ decl, decl.name });
236239
237240 var code_buffer = std.ArrayList(u8).init(self.base.allocator);
......@@ -262,7 +265,7 @@ pub fn updateFunc(self: *Plan9, module: *Module, func: *Module.Fn, air: Air, liv
262265 .appended => code_buffer.toOwnedSlice(),
263266 .fail => |em| {
264267 decl.analysis = .codegen_failure;
265 try module.failed_decls.put(module.gpa, decl, em);
268 try module.failed_decls.put(module.gpa, decl_index, em);
266269 return;
267270 },
268271 };
......@@ -272,19 +275,21 @@ pub fn updateFunc(self: *Plan9, module: *Module, func: *Module.Fn, air: Air, liv
272275 .start_line = start_line.?,
273276 .end_line = end_line,
274277 };
275 try self.putFn(decl, out);
278 try self.putFn(decl_index, out);
276279 return self.updateFinish(decl);
277280}
278281
279pub fn lowerUnnamedConst(self: *Plan9, tv: TypedValue, decl: *Module.Decl) !u32 {
282pub fn lowerUnnamedConst(self: *Plan9, tv: TypedValue, decl_index: Module.Decl.Index) !u32 {
280283 _ = self;
281284 _ = tv;
282 _ = decl;
285 _ = decl_index;
283286 log.debug("TODO lowerUnnamedConst for Plan9", .{});
284287 return error.AnalysisFail;
285288}
286289
287pub fn updateDecl(self: *Plan9, module: *Module, decl: *Module.Decl) !void {
290pub fn updateDecl(self: *Plan9, module: *Module, decl_index: Module.Decl.Index) !void {
291 const decl = module.declPtr(decl_index);
292
288293 if (decl.val.tag() == .extern_fn) {
289294 return; // TODO Should we do more when front-end analyzed extern decl?
290295 }
......@@ -295,7 +300,7 @@ pub fn updateDecl(self: *Plan9, module: *Module, decl: *Module.Decl) !void {
295300 }
296301 }
297302
298 try self.seeDecl(decl);
303 try self.seeDecl(decl_index);
299304
300305 log.debug("codegen decl {*} ({s})", .{ decl, decl.name });
301306
......@@ -315,13 +320,13 @@ pub fn updateDecl(self: *Plan9, module: *Module, decl: *Module.Decl) !void {
315320 .appended => code_buffer.items,
316321 .fail => |em| {
317322 decl.analysis = .codegen_failure;
318 try module.failed_decls.put(module.gpa, decl, em);
323 try module.failed_decls.put(module.gpa, decl_index, em);
319324 return;
320325 },
321326 };
322327 var duped_code = try self.base.allocator.dupe(u8, code);
323328 errdefer self.base.allocator.free(duped_code);
324 try self.data_decl_table.put(self.base.allocator, decl, duped_code);
329 try self.data_decl_table.put(self.base.allocator, decl_index, duped_code);
325330 return self.updateFinish(decl);
326331}
327332/// called at the end of update{Decl,Func}
......@@ -435,7 +440,8 @@ pub fn flushModule(self: *Plan9, comp: *Compilation, prog_node: *std.Progress.No
435440 while (it_file.next()) |fentry| {
436441 var it = fentry.value_ptr.functions.iterator();
437442 while (it.next()) |entry| {
438 const decl = entry.key_ptr.*;
443 const decl_index = entry.key_ptr.*;
444 const decl = mod.declPtr(decl_index);
439445 const out = entry.value_ptr.*;
440446 log.debug("write text decl {*} ({s}), lines {d} to {d}", .{ decl, decl.name, out.start_line + 1, out.end_line });
441447 {
......@@ -462,7 +468,7 @@ pub fn flushModule(self: *Plan9, comp: *Compilation, prog_node: *std.Progress.No
462468 mem.writeInt(u64, got_table[decl.link.plan9.got_index.? * 8 ..][0..8], off, self.base.options.target.cpu.arch.endian());
463469 }
464470 self.syms.items[decl.link.plan9.sym_index.?].value = off;
465 if (mod.decl_exports.get(decl)) |exports| {
471 if (mod.decl_exports.get(decl_index)) |exports| {
466472 try self.addDeclExports(mod, decl, exports);
467473 }
468474 }
......@@ -482,7 +488,8 @@ pub fn flushModule(self: *Plan9, comp: *Compilation, prog_node: *std.Progress.No
482488 {
483489 var it = self.data_decl_table.iterator();
484490 while (it.next()) |entry| {
485 const decl = entry.key_ptr.*;
491 const decl_index = entry.key_ptr.*;
492 const decl = mod.declPtr(decl_index);
486493 const code = entry.value_ptr.*;
487494 log.debug("write data decl {*} ({s})", .{ decl, decl.name });
488495
......@@ -498,7 +505,7 @@ pub fn flushModule(self: *Plan9, comp: *Compilation, prog_node: *std.Progress.No
498505 mem.writeInt(u64, got_table[decl.link.plan9.got_index.? * 8 ..][0..8], off, self.base.options.target.cpu.arch.endian());
499506 }
500507 self.syms.items[decl.link.plan9.sym_index.?].value = off;
501 if (mod.decl_exports.get(decl)) |exports| {
508 if (mod.decl_exports.get(decl_index)) |exports| {
502509 try self.addDeclExports(mod, decl, exports);
503510 }
504511 }
......@@ -564,24 +571,25 @@ fn addDeclExports(
564571 }
565572}
566573
567pub fn freeDecl(self: *Plan9, decl: *Module.Decl) void {
574pub fn freeDecl(self: *Plan9, decl_index: Module.Decl.Index) void {
568575 // TODO audit the lifetimes of decls table entries. It's possible to get
569576 // allocateDeclIndexes and then freeDecl without any updateDecl in between.
570577 // However that is planned to change, see the TODO comment in Module.zig
571578 // in the deleteUnusedDecl function.
579 const mod = self.base.options.module.?;
580 const decl = mod.declPtr(decl_index);
572581 const is_fn = (decl.val.tag() == .function);
573582 if (is_fn) {
574 var symidx_and_submap =
575 self.fn_decl_table.get(decl.getFileScope()).?;
583 var symidx_and_submap = self.fn_decl_table.get(decl.getFileScope()).?;
576584 var submap = symidx_and_submap.functions;
577 _ = submap.swapRemove(decl);
585 _ = submap.swapRemove(decl_index);
578586 if (submap.count() == 0) {
579587 self.syms.items[symidx_and_submap.sym_index] = aout.Sym.undefined_symbol;
580588 self.syms_index_free_list.append(self.base.allocator, symidx_and_submap.sym_index) catch {};
581589 submap.deinit(self.base.allocator);
582590 }
583591 } else {
584 _ = self.data_decl_table.swapRemove(decl);
592 _ = self.data_decl_table.swapRemove(decl_index);
585593 }
586594 if (decl.link.plan9.got_index) |i| {
587595 // TODO: if this catch {} is triggered, an assertion in flushModule will be triggered, because got_index_free_list will have the wrong length
......@@ -593,7 +601,9 @@ pub fn freeDecl(self: *Plan9, decl: *Module.Decl) void {
593601 }
594602}
595603
596pub fn seeDecl(self: *Plan9, decl: *Module.Decl) !void {
604pub fn seeDecl(self: *Plan9, decl_index: Module.Decl.Index) !void {
605 const mod = self.base.options.module.?;
606 const decl = mod.declPtr(decl_index);
597607 if (decl.link.plan9.got_index == null) {
598608 if (self.got_index_free_list.popOrNull()) |i| {
599609 decl.link.plan9.got_index = i;
......@@ -607,14 +617,13 @@ pub fn seeDecl(self: *Plan9, decl: *Module.Decl) !void {
607617pub fn updateDeclExports(
608618 self: *Plan9,
609619 module: *Module,
610 decl: *Module.Decl,
620 decl_index: Module.Decl.Index,
611621 exports: []const *Module.Export,
612622) !void {
613 try self.seeDecl(decl);
623 try self.seeDecl(decl_index);
614624 // we do all the things in flush
615625 _ = self;
616626 _ = module;
617 _ = decl;
618627 _ = exports;
619628}
620629pub fn deinit(self: *Plan9) void {
......@@ -709,14 +718,18 @@ pub fn writeSyms(self: *Plan9, buf: *std.ArrayList(u8)) !void {
709718 });
710719 }
711720 }
721
722 const mod = self.base.options.module.?;
723
712724 // write the data symbols
713725 {
714726 var it = self.data_decl_table.iterator();
715727 while (it.next()) |entry| {
716 const decl = entry.key_ptr.*;
728 const decl_index = entry.key_ptr.*;
729 const decl = mod.declPtr(decl_index);
717730 const sym = self.syms.items[decl.link.plan9.sym_index.?];
718731 try self.writeSym(writer, sym);
719 if (self.base.options.module.?.decl_exports.get(decl)) |exports| {
732 if (self.base.options.module.?.decl_exports.get(decl_index)) |exports| {
720733 for (exports) |e| {
721734 try self.writeSym(writer, self.syms.items[e.link.plan9.?]);
722735 }
......@@ -737,10 +750,11 @@ pub fn writeSyms(self: *Plan9, buf: *std.ArrayList(u8)) !void {
737750 // write all the decls come from the file of the z symbol
738751 var submap_it = symidx_and_submap.functions.iterator();
739752 while (submap_it.next()) |entry| {
740 const decl = entry.key_ptr.*;
753 const decl_index = entry.key_ptr.*;
754 const decl = mod.declPtr(decl_index);
741755 const sym = self.syms.items[decl.link.plan9.sym_index.?];
742756 try self.writeSym(writer, sym);
743 if (self.base.options.module.?.decl_exports.get(decl)) |exports| {
757 if (self.base.options.module.?.decl_exports.get(decl_index)) |exports| {
744758 for (exports) |e| {
745759 const s = self.syms.items[e.link.plan9.?];
746760 if (mem.eql(u8, s.name, "_start"))
......@@ -754,12 +768,18 @@ pub fn writeSyms(self: *Plan9, buf: *std.ArrayList(u8)) !void {
754768}
755769
756770/// this will be removed, moved to updateFinish
757pub fn allocateDeclIndexes(self: *Plan9, decl: *Module.Decl) !void {
771pub fn allocateDeclIndexes(self: *Plan9, decl_index: Module.Decl.Index) !void {
758772 _ = self;
759 _ = decl;
773 _ = decl_index;
760774}
761pub fn getDeclVAddr(self: *Plan9, decl: *const Module.Decl, reloc_info: link.File.RelocInfo) !u64 {
775pub fn getDeclVAddr(
776 self: *Plan9,
777 decl_index: Module.Decl.Index,
778 reloc_info: link.File.RelocInfo,
779) !u64 {
762780 _ = reloc_info;
781 const mod = self.base.options.module.?;
782 const decl = mod.declPtr(decl_index);
763783 if (decl.ty.zigTypeTag() == .Fn) {
764784 var start = self.bases.text;
765785 var it_file = self.fn_decl_table.iterator();
......@@ -767,7 +787,7 @@ pub fn getDeclVAddr(self: *Plan9, decl: *const Module.Decl, reloc_info: link.Fil
767787 var symidx_and_submap = fentry.value_ptr;
768788 var submap_it = symidx_and_submap.functions.iterator();
769789 while (submap_it.next()) |entry| {
770 if (entry.key_ptr.* == decl) return start;
790 if (entry.key_ptr.* == decl_index) return start;
771791 start += entry.value_ptr.code.len;
772792 }
773793 }
......@@ -776,7 +796,7 @@ pub fn getDeclVAddr(self: *Plan9, decl: *const Module.Decl, reloc_info: link.Fil
776796 var start = self.bases.data + self.got_len * if (!self.sixtyfour_bit) @as(u32, 4) else 8;
777797 var it = self.data_decl_table.iterator();
778798 while (it.next()) |kv| {
779 if (decl == kv.key_ptr.*) return start;
799 if (decl_index == kv.key_ptr.*) return start;
780800 start += kv.value_ptr.len;
781801 }
782802 unreachable;
src/link/SpirV.zig+14-10
......@@ -54,7 +54,7 @@ base: link.File,
5454/// This linker backend does not try to incrementally link output SPIR-V code.
5555/// Instead, it tracks all declarations in this table, and iterates over it
5656/// in the flush function.
57decl_table: std.AutoArrayHashMapUnmanaged(*Module.Decl, DeclGenContext) = .{},
57decl_table: std.AutoArrayHashMapUnmanaged(Module.Decl.Index, DeclGenContext) = .{},
5858
5959const DeclGenContext = struct {
6060 air: Air,
......@@ -145,29 +145,31 @@ pub fn updateFunc(self: *SpirV, module: *Module, func: *Module.Fn, air: Air, liv
145145 };
146146}
147147
148pub fn updateDecl(self: *SpirV, module: *Module, decl: *Module.Decl) !void {
148pub fn updateDecl(self: *SpirV, module: *Module, decl_index: Module.Decl.Index) !void {
149149 if (build_options.skip_non_native) {
150150 @panic("Attempted to compile for architecture that was disabled by build configuration");
151151 }
152152 _ = module;
153153 // Keep track of all decls so we can iterate over them on flush().
154 _ = try self.decl_table.getOrPut(self.base.allocator, decl);
154 _ = try self.decl_table.getOrPut(self.base.allocator, decl_index);
155155}
156156
157157pub fn updateDeclExports(
158158 self: *SpirV,
159159 module: *Module,
160 decl: *const Module.Decl,
160 decl_index: Module.Decl.Index,
161161 exports: []const *Module.Export,
162162) !void {
163163 _ = self;
164164 _ = module;
165 _ = decl;
165 _ = decl_index;
166166 _ = exports;
167167}
168168
169pub fn freeDecl(self: *SpirV, decl: *Module.Decl) void {
170 const index = self.decl_table.getIndex(decl).?;
169pub fn freeDecl(self: *SpirV, decl_index: Module.Decl.Index) void {
170 const index = self.decl_table.getIndex(decl_index).?;
171 const module = self.base.options.module.?;
172 const decl = module.declPtr(decl_index);
171173 if (decl.val.tag() == .function) {
172174 self.decl_table.values()[index].deinit(self.base.allocator);
173175 }
......@@ -208,7 +210,8 @@ pub fn flushModule(self: *SpirV, comp: *Compilation, prog_node: *std.Progress.No
208210 // TODO: We're allocating an ID unconditionally now, are there
209211 // declarations which don't generate a result?
210212 // TODO: fn_link is used here, but thats probably not the right field. It will work anyway though.
211 for (self.decl_table.keys()) |decl| {
213 for (self.decl_table.keys()) |decl_index| {
214 const decl = module.declPtr(decl_index);
212215 if (decl.has_tv) {
213216 decl.fn_link.spirv.id = spv.allocId();
214217 }
......@@ -220,7 +223,8 @@ pub fn flushModule(self: *SpirV, comp: *Compilation, prog_node: *std.Progress.No
220223
221224 var it = self.decl_table.iterator();
222225 while (it.next()) |entry| {
223 const decl = entry.key_ptr.*;
226 const decl_index = entry.key_ptr.*;
227 const decl = module.declPtr(decl_index);
224228 if (!decl.has_tv) continue;
225229
226230 const air = entry.value_ptr.air;
......@@ -228,7 +232,7 @@ pub fn flushModule(self: *SpirV, comp: *Compilation, prog_node: *std.Progress.No
228232
229233 // Note, if `decl` is not a function, air/liveness may be undefined.
230234 if (try decl_gen.gen(decl, air, liveness)) |msg| {
231 try module.failed_decls.put(module.gpa, decl, msg);
235 try module.failed_decls.put(module.gpa, decl_index, msg);
232236 return; // TODO: Attempt to generate more decls?
233237 }
234238 }
src/link/Wasm.zig+66-46
......@@ -48,7 +48,7 @@ host_name: []const u8 = "env",
4848/// List of all `Decl` that are currently alive.
4949/// This is ment for bookkeeping so we can safely cleanup all codegen memory
5050/// when calling `deinit`
51decls: std.AutoHashMapUnmanaged(*Module.Decl, void) = .{},
51decls: std.AutoHashMapUnmanaged(Module.Decl.Index, void) = .{},
5252/// List of all symbols generated by Zig code.
5353symbols: std.ArrayListUnmanaged(Symbol) = .{},
5454/// List of symbol indexes which are free to be used.
......@@ -429,9 +429,11 @@ pub fn deinit(self: *Wasm) void {
429429 if (self.llvm_object) |llvm_object| llvm_object.destroy(gpa);
430430 }
431431
432 const mod = self.base.options.module.?;
432433 var decl_it = self.decls.keyIterator();
433 while (decl_it.next()) |decl_ptr| {
434 decl_ptr.*.link.wasm.deinit(gpa);
434 while (decl_it.next()) |decl_index_ptr| {
435 const decl = mod.declPtr(decl_index_ptr.*);
436 decl.link.wasm.deinit(gpa);
435437 }
436438
437439 for (self.func_types.items) |*func_type| {
......@@ -476,12 +478,13 @@ pub fn deinit(self: *Wasm) void {
476478 self.string_table.deinit(gpa);
477479}
478480
479pub fn allocateDeclIndexes(self: *Wasm, decl: *Module.Decl) !void {
481pub fn allocateDeclIndexes(self: *Wasm, decl_index: Module.Decl.Index) !void {
480482 if (self.llvm_object) |_| return;
483 const decl = self.base.options.module.?.declPtr(decl_index);
481484 if (decl.link.wasm.sym_index != 0) return;
482485
483486 try self.symbols.ensureUnusedCapacity(self.base.allocator, 1);
484 try self.decls.putNoClobber(self.base.allocator, decl, {});
487 try self.decls.putNoClobber(self.base.allocator, decl_index, {});
485488
486489 const atom = &decl.link.wasm;
487490
......@@ -502,14 +505,15 @@ pub fn allocateDeclIndexes(self: *Wasm, decl: *Module.Decl) !void {
502505 try self.symbol_atom.putNoClobber(self.base.allocator, atom.symbolLoc(), atom);
503506}
504507
505pub fn updateFunc(self: *Wasm, module: *Module, func: *Module.Fn, air: Air, liveness: Liveness) !void {
508pub fn updateFunc(self: *Wasm, mod: *Module, func: *Module.Fn, air: Air, liveness: Liveness) !void {
506509 if (build_options.skip_non_native and builtin.object_format != .wasm) {
507510 @panic("Attempted to compile for object format that was disabled by build configuration");
508511 }
509512 if (build_options.have_llvm) {
510 if (self.llvm_object) |llvm_object| return llvm_object.updateFunc(module, func, air, liveness);
513 if (self.llvm_object) |llvm_object| return llvm_object.updateFunc(mod, func, air, liveness);
511514 }
512 const decl = func.owner_decl;
515 const decl_index = func.owner_decl;
516 const decl = mod.declPtr(decl_index);
513517 assert(decl.link.wasm.sym_index != 0); // Must call allocateDeclIndexes()
514518
515519 decl.link.wasm.clear();
......@@ -530,7 +534,7 @@ pub fn updateFunc(self: *Wasm, module: *Module, func: *Module.Fn, air: Air, live
530534 .appended => code_writer.items,
531535 .fail => |em| {
532536 decl.analysis = .codegen_failure;
533 try module.failed_decls.put(module.gpa, decl, em);
537 try mod.failed_decls.put(mod.gpa, decl_index, em);
534538 return;
535539 },
536540 };
......@@ -540,14 +544,15 @@ pub fn updateFunc(self: *Wasm, module: *Module, func: *Module.Fn, air: Air, live
540544
541545// Generate code for the Decl, storing it in memory to be later written to
542546// the file on flush().
543pub fn updateDecl(self: *Wasm, module: *Module, decl: *Module.Decl) !void {
547pub fn updateDecl(self: *Wasm, mod: *Module, decl_index: Module.Decl.Index) !void {
544548 if (build_options.skip_non_native and builtin.object_format != .wasm) {
545549 @panic("Attempted to compile for object format that was disabled by build configuration");
546550 }
547551 if (build_options.have_llvm) {
548 if (self.llvm_object) |llvm_object| return llvm_object.updateDecl(module, decl);
552 if (self.llvm_object) |llvm_object| return llvm_object.updateDecl(mod, decl_index);
549553 }
550554
555 const decl = mod.declPtr(decl_index);
551556 assert(decl.link.wasm.sym_index != 0); // Must call allocateDeclIndexes()
552557
553558 decl.link.wasm.clear();
......@@ -580,7 +585,7 @@ pub fn updateDecl(self: *Wasm, module: *Module, decl: *Module.Decl) !void {
580585 .appended => code_writer.items,
581586 .fail => |em| {
582587 decl.analysis = .codegen_failure;
583 try module.failed_decls.put(module.gpa, decl, em);
588 try mod.failed_decls.put(mod.gpa, decl_index, em);
584589 return;
585590 },
586591 };
......@@ -590,12 +595,13 @@ pub fn updateDecl(self: *Wasm, module: *Module, decl: *Module.Decl) !void {
590595
591596fn finishUpdateDecl(self: *Wasm, decl: *Module.Decl, code: []const u8) !void {
592597 if (code.len == 0) return;
598 const mod = self.base.options.module.?;
593599 const atom: *Atom = &decl.link.wasm;
594600 atom.size = @intCast(u32, code.len);
595601 atom.alignment = decl.ty.abiAlignment(self.base.options.target);
596602 const symbol = &self.symbols.items[atom.sym_index];
597603
598 const full_name = try decl.getFullyQualifiedName(self.base.allocator);
604 const full_name = try decl.getFullyQualifiedName(mod);
599605 defer self.base.allocator.free(full_name);
600606 symbol.name = try self.string_table.put(self.base.allocator, full_name);
601607 try atom.code.appendSlice(self.base.allocator, code);
......@@ -606,12 +612,15 @@ fn finishUpdateDecl(self: *Wasm, decl: *Module.Decl, code: []const u8) !void {
606612/// Lowers a constant typed value to a local symbol and atom.
607613/// Returns the symbol index of the local
608614/// The given `decl` is the parent decl whom owns the constant.
609pub fn lowerUnnamedConst(self: *Wasm, decl: *Module.Decl, tv: TypedValue) !u32 {
615pub fn lowerUnnamedConst(self: *Wasm, tv: TypedValue, decl_index: Module.Decl.Index) !u32 {
610616 assert(tv.ty.zigTypeTag() != .Fn); // cannot create local symbols for functions
611617
618 const mod = self.base.options.module.?;
619 const decl = mod.declPtr(decl_index);
620
612621 // Create and initialize a new local symbol and atom
613622 const local_index = decl.link.wasm.locals.items.len;
614 const fqdn = try decl.getFullyQualifiedName(self.base.allocator);
623 const fqdn = try decl.getFullyQualifiedName(mod);
615624 defer self.base.allocator.free(fqdn);
616625 const name = try std.fmt.allocPrintZ(self.base.allocator, "__unnamed_{s}_{d}", .{ fqdn, local_index });
617626 defer self.base.allocator.free(name);
......@@ -641,7 +650,6 @@ pub fn lowerUnnamedConst(self: *Wasm, decl: *Module.Decl, tv: TypedValue) !u32 {
641650 var value_bytes = std.ArrayList(u8).init(self.base.allocator);
642651 defer value_bytes.deinit();
643652
644 const module = self.base.options.module.?;
645653 const result = try codegen.generateSymbol(
646654 &self.base,
647655 decl.srcLoc(),
......@@ -658,7 +666,7 @@ pub fn lowerUnnamedConst(self: *Wasm, decl: *Module.Decl, tv: TypedValue) !u32 {
658666 .appended => value_bytes.items,
659667 .fail => |em| {
660668 decl.analysis = .codegen_failure;
661 try module.failed_decls.put(module.gpa, decl, em);
669 try mod.failed_decls.put(mod.gpa, decl_index, em);
662670 return error.AnalysisFail;
663671 },
664672 };
......@@ -672,9 +680,11 @@ pub fn lowerUnnamedConst(self: *Wasm, decl: *Module.Decl, tv: TypedValue) !u32 {
672680/// Returns the given pointer address
673681pub fn getDeclVAddr(
674682 self: *Wasm,
675 decl: *const Module.Decl,
683 decl_index: Module.Decl.Index,
676684 reloc_info: link.File.RelocInfo,
677685) !u64 {
686 const mod = self.base.options.module.?;
687 const decl = mod.declPtr(decl_index);
678688 const target_symbol_index = decl.link.wasm.sym_index;
679689 assert(target_symbol_index != 0);
680690 assert(reloc_info.parent_atom_index != 0);
......@@ -722,21 +732,23 @@ pub fn deleteExport(self: *Wasm, exp: Export) void {
722732
723733pub fn updateDeclExports(
724734 self: *Wasm,
725 module: *Module,
726 decl: *const Module.Decl,
735 mod: *Module,
736 decl_index: Module.Decl.Index,
727737 exports: []const *Module.Export,
728738) !void {
729739 if (build_options.skip_non_native and builtin.object_format != .wasm) {
730740 @panic("Attempted to compile for object format that was disabled by build configuration");
731741 }
732742 if (build_options.have_llvm) {
733 if (self.llvm_object) |llvm_object| return llvm_object.updateDeclExports(module, decl, exports);
743 if (self.llvm_object) |llvm_object| return llvm_object.updateDeclExports(mod, decl_index, exports);
734744 }
735745
746 const decl = mod.declPtr(decl_index);
747
736748 for (exports) |exp| {
737749 if (exp.options.section) |section| {
738 try module.failed_exports.putNoClobber(module.gpa, exp, try Module.ErrorMsg.create(
739 module.gpa,
750 try mod.failed_exports.putNoClobber(mod.gpa, exp, try Module.ErrorMsg.create(
751 mod.gpa,
740752 decl.srcLoc(),
741753 "Unimplemented: ExportOptions.section '{s}'",
742754 .{section},
......@@ -754,8 +766,8 @@ pub fn updateDeclExports(
754766 // are strong symbols, we have a linker error.
755767 // In the other case we replace one with the other.
756768 if (!exp_is_weak and !existing_sym.isWeak()) {
757 try module.failed_exports.put(module.gpa, exp, try Module.ErrorMsg.create(
758 module.gpa,
769 try mod.failed_exports.put(mod.gpa, exp, try Module.ErrorMsg.create(
770 mod.gpa,
759771 decl.srcLoc(),
760772 \\LinkError: symbol '{s}' defined multiple times
761773 \\ first definition in '{s}'
......@@ -773,8 +785,9 @@ pub fn updateDeclExports(
773785 }
774786 }
775787
776 const sym_index = exp.exported_decl.link.wasm.sym_index;
777 const sym_loc = exp.exported_decl.link.wasm.symbolLoc();
788 const exported_decl = mod.declPtr(exp.exported_decl);
789 const sym_index = exported_decl.link.wasm.sym_index;
790 const sym_loc = exported_decl.link.wasm.symbolLoc();
778791 const symbol = sym_loc.getSymbol(self);
779792 switch (exp.options.linkage) {
780793 .Internal => {
......@@ -786,8 +799,8 @@ pub fn updateDeclExports(
786799 },
787800 .Strong => {}, // symbols are strong by default
788801 .LinkOnce => {
789 try module.failed_exports.putNoClobber(module.gpa, exp, try Module.ErrorMsg.create(
790 module.gpa,
802 try mod.failed_exports.putNoClobber(mod.gpa, exp, try Module.ErrorMsg.create(
803 mod.gpa,
791804 decl.srcLoc(),
792805 "Unimplemented: LinkOnce",
793806 .{},
......@@ -813,13 +826,15 @@ pub fn updateDeclExports(
813826 }
814827}
815828
816pub fn freeDecl(self: *Wasm, decl: *Module.Decl) void {
829pub fn freeDecl(self: *Wasm, decl_index: Module.Decl.Index) void {
817830 if (build_options.have_llvm) {
818 if (self.llvm_object) |llvm_object| return llvm_object.freeDecl(decl);
831 if (self.llvm_object) |llvm_object| return llvm_object.freeDecl(decl_index);
819832 }
833 const mod = self.base.options.module.?;
834 const decl = mod.declPtr(decl_index);
820835 const atom = &decl.link.wasm;
821836 self.symbols_free_list.append(self.base.allocator, atom.sym_index) catch {};
822 _ = self.decls.remove(decl);
837 _ = self.decls.remove(decl_index);
823838 self.symbols.items[atom.sym_index].tag = .dead;
824839 for (atom.locals.items) |local_atom| {
825840 const local_symbol = &self.symbols.items[local_atom.sym_index];
......@@ -1414,8 +1429,8 @@ fn populateErrorNameTable(self: *Wasm) !void {
14141429
14151430 // Addend for each relocation to the table
14161431 var addend: u32 = 0;
1417 const module = self.base.options.module.?;
1418 for (module.error_name_list.items) |error_name| {
1432 const mod = self.base.options.module.?;
1433 for (mod.error_name_list.items) |error_name| {
14191434 const len = @intCast(u32, error_name.len + 1); // names are 0-termianted
14201435
14211436 const slice_ty = Type.initTag(.const_slice_u8_sentinel_0);
......@@ -1456,9 +1471,11 @@ fn resetState(self: *Wasm) void {
14561471 for (self.segment_info.items) |*segment_info| {
14571472 self.base.allocator.free(segment_info.name);
14581473 }
1474 const mod = self.base.options.module.?;
14591475 var decl_it = self.decls.keyIterator();
1460 while (decl_it.next()) |decl| {
1461 const atom = &decl.*.link.wasm;
1476 while (decl_it.next()) |decl_index_ptr| {
1477 const decl = mod.declPtr(decl_index_ptr.*);
1478 const atom = &decl.link.wasm;
14621479 atom.next = null;
14631480 atom.prev = null;
14641481
......@@ -1546,12 +1563,14 @@ pub fn flushModule(self: *Wasm, comp: *Compilation, prog_node: *std.Progress.Nod
15461563 defer self.resetState();
15471564 try self.setupStart();
15481565 try self.setupImports();
1566 const mod = self.base.options.module.?;
15491567 var decl_it = self.decls.keyIterator();
1550 while (decl_it.next()) |decl| {
1551 if (decl.*.isExtern()) continue;
1568 while (decl_it.next()) |decl_index_ptr| {
1569 const decl = mod.declPtr(decl_index_ptr.*);
1570 if (decl.isExtern()) continue;
15521571 const atom = &decl.*.link.wasm;
1553 if (decl.*.ty.zigTypeTag() == .Fn) {
1554 try self.parseAtom(atom, .{ .function = decl.*.fn_link.wasm });
1572 if (decl.ty.zigTypeTag() == .Fn) {
1573 try self.parseAtom(atom, .{ .function = decl.fn_link.wasm });
15551574 } else {
15561575 try self.parseAtom(atom, .data);
15571576 }
......@@ -2045,7 +2064,7 @@ fn linkWithLLD(self: *Wasm, comp: *Compilation, prog_node: *std.Progress.Node) !
20452064
20462065 // If there is no Zig code to compile, then we should skip flushing the output file because it
20472066 // will not be part of the linker line anyway.
2048 const module_obj_path: ?[]const u8 = if (self.base.options.module) |module| blk: {
2067 const module_obj_path: ?[]const u8 = if (self.base.options.module) |mod| blk: {
20492068 const use_stage1 = build_options.is_stage1 and self.base.options.use_stage1;
20502069 if (use_stage1) {
20512070 const obj_basename = try std.zig.binNameAlloc(arena, .{
......@@ -2054,7 +2073,7 @@ fn linkWithLLD(self: *Wasm, comp: *Compilation, prog_node: *std.Progress.Node) !
20542073 .output_mode = .Obj,
20552074 });
20562075 switch (self.base.options.cache_mode) {
2057 .incremental => break :blk try module.zig_cache_artifact_directory.join(
2076 .incremental => break :blk try mod.zig_cache_artifact_directory.join(
20582077 arena,
20592078 &[_][]const u8{obj_basename},
20602079 ),
......@@ -2253,7 +2272,7 @@ fn linkWithLLD(self: *Wasm, comp: *Compilation, prog_node: *std.Progress.Node) !
22532272 }
22542273
22552274 if (auto_export_symbols) {
2256 if (self.base.options.module) |module| {
2275 if (self.base.options.module) |mod| {
22572276 // when we use stage1, we use the exports that stage1 provided us.
22582277 // For stage2, we can directly retrieve them from the module.
22592278 const use_stage1 = build_options.is_stage1 and self.base.options.use_stage1;
......@@ -2264,14 +2283,15 @@ fn linkWithLLD(self: *Wasm, comp: *Compilation, prog_node: *std.Progress.Node) !
22642283 } else {
22652284 const skip_export_non_fn = target.os.tag == .wasi and
22662285 self.base.options.wasi_exec_model == .command;
2267 for (module.decl_exports.values()) |exports| {
2286 for (mod.decl_exports.values()) |exports| {
22682287 for (exports) |exprt| {
2269 if (skip_export_non_fn and exprt.exported_decl.ty.zigTypeTag() != .Fn) {
2288 const exported_decl = mod.declPtr(exprt.exported_decl);
2289 if (skip_export_non_fn and exported_decl.ty.zigTypeTag() != .Fn) {
22702290 // skip exporting symbols when we're building a WASI command
22712291 // and the symbol is not a function
22722292 continue;
22732293 }
2274 const symbol_name = exprt.exported_decl.name;
2294 const symbol_name = exported_decl.name;
22752295 const arg = try std.fmt.allocPrint(arena, "--export={s}", .{symbol_name});
22762296 try argv.append(arg);
22772297 }
src/main.zig+4-4
......@@ -3892,7 +3892,7 @@ pub fn cmdFmt(gpa: Allocator, arena: Allocator, args: []const []const u8) !void
38923892 .tree_loaded = true,
38933893 .zir = undefined,
38943894 .pkg = undefined,
3895 .root_decl = null,
3895 .root_decl = .none,
38963896 };
38973897
38983898 file.pkg = try Package.create(gpa, null, file.sub_file_path);
......@@ -4098,7 +4098,7 @@ fn fmtPathFile(
40984098 .tree_loaded = true,
40994099 .zir = undefined,
41004100 .pkg = undefined,
4101 .root_decl = null,
4101 .root_decl = .none,
41024102 };
41034103
41044104 file.pkg = try Package.create(fmt.gpa, null, file.sub_file_path);
......@@ -4757,7 +4757,7 @@ pub fn cmdAstCheck(
47574757 .tree = undefined,
47584758 .zir = undefined,
47594759 .pkg = undefined,
4760 .root_decl = null,
4760 .root_decl = .none,
47614761 };
47624762 if (zig_source_file) |file_name| {
47634763 var f = fs.cwd().openFile(file_name, .{}) catch |err| {
......@@ -4910,7 +4910,7 @@ pub fn cmdChangelist(
49104910 .tree = undefined,
49114911 .zir = undefined,
49124912 .pkg = undefined,
4913 .root_decl = null,
4913 .root_decl = .none,
49144914 };
49154915
49164916 file.pkg = try Package.create(gpa, null, file.sub_file_path);
src/print_air.zig+7-4
......@@ -7,7 +7,7 @@ const Value = @import("value.zig").Value;
77const Air = @import("Air.zig");
88const Liveness = @import("Liveness.zig");
99
10pub fn dump(gpa: Allocator, air: Air, liveness: Liveness) void {
10pub fn dump(module: *Module, air: Air, liveness: Liveness) void {
1111 const instruction_bytes = air.instructions.len *
1212 // Here we don't use @sizeOf(Air.Inst.Data) because it would include
1313 // the debug safety tag but we want to measure release size.
......@@ -41,11 +41,12 @@ pub fn dump(gpa: Allocator, air: Air, liveness: Liveness) void {
4141 liveness.special.count(), fmtIntSizeBin(liveness_special_bytes),
4242 });
4343 // zig fmt: on
44 var arena = std.heap.ArenaAllocator.init(gpa);
44 var arena = std.heap.ArenaAllocator.init(module.gpa);
4545 defer arena.deinit();
4646
4747 var writer: Writer = .{
48 .gpa = gpa,
48 .module = module,
49 .gpa = module.gpa,
4950 .arena = arena.allocator(),
5051 .air = air,
5152 .liveness = liveness,
......@@ -58,6 +59,7 @@ pub fn dump(gpa: Allocator, air: Air, liveness: Liveness) void {
5859}
5960
6061const Writer = struct {
62 module: *Module,
6163 gpa: Allocator,
6264 arena: Allocator,
6365 air: Air,
......@@ -591,7 +593,8 @@ const Writer = struct {
591593 fn writeDbgInline(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
592594 const ty_pl = w.air.instructions.items(.data)[inst].ty_pl;
593595 const function = w.air.values[ty_pl.payload].castTag(.function).?.data;
594 try s.print("{s}", .{function.owner_decl.name});
596 const owner_decl = w.module.declPtr(function.owner_decl);
597 try s.print("{s}", .{owner_decl.name});
595598 }
596599
597600 fn writeDbgVar(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
src/type.zig+150-124
......@@ -521,7 +521,7 @@ pub const Type = extern union {
521521 }
522522 }
523523
524 pub fn eql(a: Type, b: Type, target: Target) bool {
524 pub fn eql(a: Type, b: Type, mod: *Module) bool {
525525 // As a shortcut, if the small tags / addresses match, we're done.
526526 if (a.tag_if_small_enough == b.tag_if_small_enough) return true;
527527
......@@ -637,7 +637,7 @@ pub const Type = extern union {
637637 const a_info = a.fnInfo();
638638 const b_info = b.fnInfo();
639639
640 if (!eql(a_info.return_type, b_info.return_type, target))
640 if (!eql(a_info.return_type, b_info.return_type, mod))
641641 return false;
642642
643643 if (a_info.cc != b_info.cc)
......@@ -663,7 +663,7 @@ pub const Type = extern union {
663663 if (a_param_ty.tag() == .generic_poison) continue;
664664 if (b_param_ty.tag() == .generic_poison) continue;
665665
666 if (!eql(a_param_ty, b_param_ty, target))
666 if (!eql(a_param_ty, b_param_ty, mod))
667667 return false;
668668 }
669669
......@@ -681,13 +681,13 @@ pub const Type = extern union {
681681 if (a.arrayLen() != b.arrayLen())
682682 return false;
683683 const elem_ty = a.elemType();
684 if (!elem_ty.eql(b.elemType(), target))
684 if (!elem_ty.eql(b.elemType(), mod))
685685 return false;
686686 const sentinel_a = a.sentinel();
687687 const sentinel_b = b.sentinel();
688688 if (sentinel_a) |sa| {
689689 if (sentinel_b) |sb| {
690 return sa.eql(sb, elem_ty, target);
690 return sa.eql(sb, elem_ty, mod);
691691 } else {
692692 return false;
693693 }
......@@ -718,7 +718,7 @@ pub const Type = extern union {
718718
719719 const info_a = a.ptrInfo().data;
720720 const info_b = b.ptrInfo().data;
721 if (!info_a.pointee_type.eql(info_b.pointee_type, target))
721 if (!info_a.pointee_type.eql(info_b.pointee_type, mod))
722722 return false;
723723 if (info_a.@"align" != info_b.@"align")
724724 return false;
......@@ -741,7 +741,7 @@ pub const Type = extern union {
741741 const sentinel_b = info_b.sentinel;
742742 if (sentinel_a) |sa| {
743743 if (sentinel_b) |sb| {
744 if (!sa.eql(sb, info_a.pointee_type, target))
744 if (!sa.eql(sb, info_a.pointee_type, mod))
745745 return false;
746746 } else {
747747 return false;
......@@ -762,7 +762,7 @@ pub const Type = extern union {
762762
763763 var buf_a: Payload.ElemType = undefined;
764764 var buf_b: Payload.ElemType = undefined;
765 return a.optionalChild(&buf_a).eql(b.optionalChild(&buf_b), target);
765 return a.optionalChild(&buf_a).eql(b.optionalChild(&buf_b), mod);
766766 },
767767
768768 .anyerror_void_error_union, .error_union => {
......@@ -770,18 +770,18 @@ pub const Type = extern union {
770770
771771 const a_set = a.errorUnionSet();
772772 const b_set = b.errorUnionSet();
773 if (!a_set.eql(b_set, target)) return false;
773 if (!a_set.eql(b_set, mod)) return false;
774774
775775 const a_payload = a.errorUnionPayload();
776776 const b_payload = b.errorUnionPayload();
777 if (!a_payload.eql(b_payload, target)) return false;
777 if (!a_payload.eql(b_payload, mod)) return false;
778778
779779 return true;
780780 },
781781
782782 .anyframe_T => {
783783 if (b.zigTypeTag() != .AnyFrame) return false;
784 return a.childType().eql(b.childType(), target);
784 return a.childType().eql(b.childType(), mod);
785785 },
786786
787787 .empty_struct => {
......@@ -804,7 +804,7 @@ pub const Type = extern union {
804804
805805 for (a_tuple.types) |a_ty, i| {
806806 const b_ty = b_tuple.types[i];
807 if (!eql(a_ty, b_ty, target)) return false;
807 if (!eql(a_ty, b_ty, mod)) return false;
808808 }
809809
810810 for (a_tuple.values) |a_val, i| {
......@@ -820,7 +820,7 @@ pub const Type = extern union {
820820 if (b_val.tag() == .unreachable_value) {
821821 return false;
822822 } else {
823 if (!Value.eql(a_val, b_val, ty, target)) return false;
823 if (!Value.eql(a_val, b_val, ty, mod)) return false;
824824 }
825825 }
826826 }
......@@ -840,7 +840,7 @@ pub const Type = extern union {
840840
841841 for (a_struct_obj.types) |a_ty, i| {
842842 const b_ty = b_struct_obj.types[i];
843 if (!eql(a_ty, b_ty, target)) return false;
843 if (!eql(a_ty, b_ty, mod)) return false;
844844 }
845845
846846 for (a_struct_obj.values) |a_val, i| {
......@@ -856,7 +856,7 @@ pub const Type = extern union {
856856 if (b_val.tag() == .unreachable_value) {
857857 return false;
858858 } else {
859 if (!Value.eql(a_val, b_val, ty, target)) return false;
859 if (!Value.eql(a_val, b_val, ty, mod)) return false;
860860 }
861861 }
862862 }
......@@ -911,13 +911,13 @@ pub const Type = extern union {
911911 }
912912 }
913913
914 pub fn hash(self: Type, target: Target) u64 {
914 pub fn hash(self: Type, mod: *Module) u64 {
915915 var hasher = std.hash.Wyhash.init(0);
916 self.hashWithHasher(&hasher, target);
916 self.hashWithHasher(&hasher, mod);
917917 return hasher.final();
918918 }
919919
920 pub fn hashWithHasher(ty: Type, hasher: *std.hash.Wyhash, target: Target) void {
920 pub fn hashWithHasher(ty: Type, hasher: *std.hash.Wyhash, mod: *Module) void {
921921 switch (ty.tag()) {
922922 .generic_poison => unreachable,
923923
......@@ -1036,7 +1036,7 @@ pub const Type = extern union {
10361036 std.hash.autoHash(hasher, std.builtin.TypeId.Fn);
10371037
10381038 const fn_info = ty.fnInfo();
1039 hashWithHasher(fn_info.return_type, hasher, target);
1039 hashWithHasher(fn_info.return_type, hasher, mod);
10401040 std.hash.autoHash(hasher, fn_info.alignment);
10411041 std.hash.autoHash(hasher, fn_info.cc);
10421042 std.hash.autoHash(hasher, fn_info.is_var_args);
......@@ -1046,7 +1046,7 @@ pub const Type = extern union {
10461046 for (fn_info.param_types) |param_ty, i| {
10471047 std.hash.autoHash(hasher, fn_info.paramIsComptime(i));
10481048 if (param_ty.tag() == .generic_poison) continue;
1049 hashWithHasher(param_ty, hasher, target);
1049 hashWithHasher(param_ty, hasher, mod);
10501050 }
10511051 },
10521052
......@@ -1059,8 +1059,8 @@ pub const Type = extern union {
10591059
10601060 const elem_ty = ty.elemType();
10611061 std.hash.autoHash(hasher, ty.arrayLen());
1062 hashWithHasher(elem_ty, hasher, target);
1063 hashSentinel(ty.sentinel(), elem_ty, hasher, target);
1062 hashWithHasher(elem_ty, hasher, mod);
1063 hashSentinel(ty.sentinel(), elem_ty, hasher, mod);
10641064 },
10651065
10661066 .vector => {
......@@ -1068,7 +1068,7 @@ pub const Type = extern union {
10681068
10691069 const elem_ty = ty.elemType();
10701070 std.hash.autoHash(hasher, ty.vectorLen());
1071 hashWithHasher(elem_ty, hasher, target);
1071 hashWithHasher(elem_ty, hasher, mod);
10721072 },
10731073
10741074 .single_const_pointer_to_comptime_int,
......@@ -1092,8 +1092,8 @@ pub const Type = extern union {
10921092 std.hash.autoHash(hasher, std.builtin.TypeId.Pointer);
10931093
10941094 const info = ty.ptrInfo().data;
1095 hashWithHasher(info.pointee_type, hasher, target);
1096 hashSentinel(info.sentinel, info.pointee_type, hasher, target);
1095 hashWithHasher(info.pointee_type, hasher, mod);
1096 hashSentinel(info.sentinel, info.pointee_type, hasher, mod);
10971097 std.hash.autoHash(hasher, info.@"align");
10981098 std.hash.autoHash(hasher, info.@"addrspace");
10991099 std.hash.autoHash(hasher, info.bit_offset);
......@@ -1111,22 +1111,22 @@ pub const Type = extern union {
11111111 std.hash.autoHash(hasher, std.builtin.TypeId.Optional);
11121112
11131113 var buf: Payload.ElemType = undefined;
1114 hashWithHasher(ty.optionalChild(&buf), hasher, target);
1114 hashWithHasher(ty.optionalChild(&buf), hasher, mod);
11151115 },
11161116
11171117 .anyerror_void_error_union, .error_union => {
11181118 std.hash.autoHash(hasher, std.builtin.TypeId.ErrorUnion);
11191119
11201120 const set_ty = ty.errorUnionSet();
1121 hashWithHasher(set_ty, hasher, target);
1121 hashWithHasher(set_ty, hasher, mod);
11221122
11231123 const payload_ty = ty.errorUnionPayload();
1124 hashWithHasher(payload_ty, hasher, target);
1124 hashWithHasher(payload_ty, hasher, mod);
11251125 },
11261126
11271127 .anyframe_T => {
11281128 std.hash.autoHash(hasher, std.builtin.TypeId.AnyFrame);
1129 hashWithHasher(ty.childType(), hasher, target);
1129 hashWithHasher(ty.childType(), hasher, mod);
11301130 },
11311131
11321132 .empty_struct => {
......@@ -1145,10 +1145,10 @@ pub const Type = extern union {
11451145 std.hash.autoHash(hasher, tuple.types.len);
11461146
11471147 for (tuple.types) |field_ty, i| {
1148 hashWithHasher(field_ty, hasher, target);
1148 hashWithHasher(field_ty, hasher, mod);
11491149 const field_val = tuple.values[i];
11501150 if (field_val.tag() == .unreachable_value) continue;
1151 field_val.hash(field_ty, hasher, target);
1151 field_val.hash(field_ty, hasher, mod);
11521152 }
11531153 },
11541154 .anon_struct => {
......@@ -1160,9 +1160,9 @@ pub const Type = extern union {
11601160 const field_name = struct_obj.names[i];
11611161 const field_val = struct_obj.values[i];
11621162 hasher.update(field_name);
1163 hashWithHasher(field_ty, hasher, target);
1163 hashWithHasher(field_ty, hasher, mod);
11641164 if (field_val.tag() == .unreachable_value) continue;
1165 field_val.hash(field_ty, hasher, target);
1165 field_val.hash(field_ty, hasher, mod);
11661166 }
11671167 },
11681168
......@@ -1210,35 +1210,35 @@ pub const Type = extern union {
12101210 }
12111211 }
12121212
1213 fn hashSentinel(opt_val: ?Value, ty: Type, hasher: *std.hash.Wyhash, target: Target) void {
1213 fn hashSentinel(opt_val: ?Value, ty: Type, hasher: *std.hash.Wyhash, mod: *Module) void {
12141214 if (opt_val) |s| {
12151215 std.hash.autoHash(hasher, true);
1216 s.hash(ty, hasher, target);
1216 s.hash(ty, hasher, mod);
12171217 } else {
12181218 std.hash.autoHash(hasher, false);
12191219 }
12201220 }
12211221
12221222 pub const HashContext64 = struct {
1223 target: Target,
1223 mod: *Module,
12241224
12251225 pub fn hash(self: @This(), t: Type) u64 {
1226 return t.hash(self.target);
1226 return t.hash(self.mod);
12271227 }
12281228 pub fn eql(self: @This(), a: Type, b: Type) bool {
1229 return a.eql(b, self.target);
1229 return a.eql(b, self.mod);
12301230 }
12311231 };
12321232
12331233 pub const HashContext32 = struct {
1234 target: Target,
1234 mod: *Module,
12351235
12361236 pub fn hash(self: @This(), t: Type) u32 {
1237 return @truncate(u32, t.hash(self.target));
1237 return @truncate(u32, t.hash(self.mod));
12381238 }
12391239 pub fn eql(self: @This(), a: Type, b: Type, b_index: usize) bool {
12401240 _ = b_index;
1241 return a.eql(b, self.target);
1241 return a.eql(b, self.mod);
12421242 }
12431243 };
12441244
......@@ -1483,16 +1483,16 @@ pub const Type = extern union {
14831483 @compileError("do not format types directly; use either ty.fmtDebug() or ty.fmt()");
14841484 }
14851485
1486 pub fn fmt(ty: Type, target: Target) std.fmt.Formatter(format2) {
1486 pub fn fmt(ty: Type, module: *Module) std.fmt.Formatter(format2) {
14871487 return .{ .data = .{
14881488 .ty = ty,
1489 .target = target,
1489 .module = module,
14901490 } };
14911491 }
14921492
14931493 const FormatContext = struct {
14941494 ty: Type,
1495 target: Target,
1495 module: *Module,
14961496 };
14971497
14981498 fn format2(
......@@ -1503,7 +1503,7 @@ pub const Type = extern union {
15031503 ) !void {
15041504 comptime assert(unused_format_string.len == 0);
15051505 _ = options;
1506 return print(ctx.ty, writer, ctx.target);
1506 return print(ctx.ty, writer, ctx.module);
15071507 }
15081508
15091509 pub fn fmtDebug(ty: Type) std.fmt.Formatter(dump) {
......@@ -1579,27 +1579,39 @@ pub const Type = extern union {
15791579
15801580 .@"struct" => {
15811581 const struct_obj = ty.castTag(.@"struct").?.data;
1582 return struct_obj.owner_decl.renderFullyQualifiedName(writer);
1582 return writer.print("({s} decl={d})", .{
1583 @tagName(t), struct_obj.owner_decl,
1584 });
15831585 },
15841586 .@"union", .union_tagged => {
15851587 const union_obj = ty.cast(Payload.Union).?.data;
1586 return union_obj.owner_decl.renderFullyQualifiedName(writer);
1588 return writer.print("({s} decl={d})", .{
1589 @tagName(t), union_obj.owner_decl,
1590 });
15871591 },
15881592 .enum_full, .enum_nonexhaustive => {
15891593 const enum_full = ty.cast(Payload.EnumFull).?.data;
1590 return enum_full.owner_decl.renderFullyQualifiedName(writer);
1594 return writer.print("({s} decl={d})", .{
1595 @tagName(t), enum_full.owner_decl,
1596 });
15911597 },
15921598 .enum_simple => {
15931599 const enum_simple = ty.castTag(.enum_simple).?.data;
1594 return enum_simple.owner_decl.renderFullyQualifiedName(writer);
1600 return writer.print("({s} decl={d})", .{
1601 @tagName(t), enum_simple.owner_decl,
1602 });
15951603 },
15961604 .enum_numbered => {
15971605 const enum_numbered = ty.castTag(.enum_numbered).?.data;
1598 return enum_numbered.owner_decl.renderFullyQualifiedName(writer);
1606 return writer.print("({s} decl={d})", .{
1607 @tagName(t), enum_numbered.owner_decl,
1608 });
15991609 },
16001610 .@"opaque" => {
1601 // TODO use declaration name
1602 return writer.writeAll("opaque {}");
1611 const opaque_obj = ty.castTag(.@"opaque").?.data;
1612 return writer.print("({s} decl={d})", .{
1613 @tagName(t), opaque_obj.owner_decl,
1614 });
16031615 },
16041616
16051617 .anyerror_void_error_union => return writer.writeAll("anyerror!void"),
......@@ -1845,7 +1857,9 @@ pub const Type = extern union {
18451857 },
18461858 .error_set_inferred => {
18471859 const func = ty.castTag(.error_set_inferred).?.data.func;
1848 return writer.print("@typeInfo(@typeInfo(@TypeOf({s})).Fn.return_type.?).ErrorUnion.error_set", .{func.owner_decl.name});
1860 return writer.print("({s} func={d})", .{
1861 @tagName(t), func.owner_decl,
1862 });
18491863 },
18501864 .error_set_merged => {
18511865 const names = ty.castTag(.error_set_merged).?.data.keys();
......@@ -1871,15 +1885,15 @@ pub const Type = extern union {
18711885
18721886 pub const nameAllocArena = nameAlloc;
18731887
1874 pub fn nameAlloc(ty: Type, ally: Allocator, target: Target) Allocator.Error![:0]const u8 {
1888 pub fn nameAlloc(ty: Type, ally: Allocator, module: *Module) Allocator.Error![:0]const u8 {
18751889 var buffer = std.ArrayList(u8).init(ally);
18761890 defer buffer.deinit();
1877 try ty.print(buffer.writer(), target);
1891 try ty.print(buffer.writer(), module);
18781892 return buffer.toOwnedSliceSentinel(0);
18791893 }
18801894
18811895 /// Prints a name suitable for `@typeName`.
1882 pub fn print(ty: Type, writer: anytype, target: Target) @TypeOf(writer).Error!void {
1896 pub fn print(ty: Type, writer: anytype, mod: *Module) @TypeOf(writer).Error!void {
18831897 const t = ty.tag();
18841898 switch (t) {
18851899 .inferred_alloc_const => unreachable,
......@@ -1946,32 +1960,38 @@ pub const Type = extern union {
19461960
19471961 .empty_struct => {
19481962 const namespace = ty.castTag(.empty_struct).?.data;
1949 try namespace.renderFullyQualifiedName("", writer);
1963 try namespace.renderFullyQualifiedName(mod, "", writer);
19501964 },
19511965
19521966 .@"struct" => {
19531967 const struct_obj = ty.castTag(.@"struct").?.data;
1954 try struct_obj.owner_decl.renderFullyQualifiedName(writer);
1968 const decl = mod.declPtr(struct_obj.owner_decl);
1969 try decl.renderFullyQualifiedName(mod, writer);
19551970 },
19561971 .@"union", .union_tagged => {
19571972 const union_obj = ty.cast(Payload.Union).?.data;
1958 try union_obj.owner_decl.renderFullyQualifiedName(writer);
1973 const decl = mod.declPtr(union_obj.owner_decl);
1974 try decl.renderFullyQualifiedName(mod, writer);
19591975 },
19601976 .enum_full, .enum_nonexhaustive => {
19611977 const enum_full = ty.cast(Payload.EnumFull).?.data;
1962 try enum_full.owner_decl.renderFullyQualifiedName(writer);
1978 const decl = mod.declPtr(enum_full.owner_decl);
1979 try decl.renderFullyQualifiedName(mod, writer);
19631980 },
19641981 .enum_simple => {
19651982 const enum_simple = ty.castTag(.enum_simple).?.data;
1966 try enum_simple.owner_decl.renderFullyQualifiedName(writer);
1983 const decl = mod.declPtr(enum_simple.owner_decl);
1984 try decl.renderFullyQualifiedName(mod, writer);
19671985 },
19681986 .enum_numbered => {
19691987 const enum_numbered = ty.castTag(.enum_numbered).?.data;
1970 try enum_numbered.owner_decl.renderFullyQualifiedName(writer);
1988 const decl = mod.declPtr(enum_numbered.owner_decl);
1989 try decl.renderFullyQualifiedName(mod, writer);
19711990 },
19721991 .@"opaque" => {
19731992 const opaque_obj = ty.cast(Payload.Opaque).?.data;
1974 try opaque_obj.owner_decl.renderFullyQualifiedName(writer);
1993 const decl = mod.declPtr(opaque_obj.owner_decl);
1994 try decl.renderFullyQualifiedName(mod, writer);
19751995 },
19761996
19771997 .anyerror_void_error_union => try writer.writeAll("anyerror!void"),
......@@ -1990,7 +2010,8 @@ pub const Type = extern union {
19902010 const func = ty.castTag(.error_set_inferred).?.data.func;
19912011
19922012 try writer.writeAll("@typeInfo(@typeInfo(@TypeOf(");
1993 try func.owner_decl.renderFullyQualifiedName(writer);
2013 const owner_decl = mod.declPtr(func.owner_decl);
2014 try owner_decl.renderFullyQualifiedName(mod, writer);
19942015 try writer.writeAll(")).Fn.return_type.?).ErrorUnion.error_set");
19952016 },
19962017
......@@ -1999,7 +2020,7 @@ pub const Type = extern union {
19992020 try writer.writeAll("fn(");
20002021 for (fn_info.param_types) |param_ty, i| {
20012022 if (i != 0) try writer.writeAll(", ");
2002 try print(param_ty, writer, target);
2023 try print(param_ty, writer, mod);
20032024 }
20042025 if (fn_info.is_var_args) {
20052026 if (fn_info.param_types.len != 0) {
......@@ -2016,14 +2037,14 @@ pub const Type = extern union {
20162037 if (fn_info.alignment != 0) {
20172038 try writer.print("align({d}) ", .{fn_info.alignment});
20182039 }
2019 try print(fn_info.return_type, writer, target);
2040 try print(fn_info.return_type, writer, mod);
20202041 },
20212042
20222043 .error_union => {
20232044 const error_union = ty.castTag(.error_union).?.data;
2024 try print(error_union.error_set, writer, target);
2045 try print(error_union.error_set, writer, mod);
20252046 try writer.writeAll("!");
2026 try print(error_union.payload, writer, target);
2047 try print(error_union.payload, writer, mod);
20272048 },
20282049
20292050 .array_u8 => {
......@@ -2037,21 +2058,21 @@ pub const Type = extern union {
20372058 .vector => {
20382059 const payload = ty.castTag(.vector).?.data;
20392060 try writer.print("@Vector({d}, ", .{payload.len});
2040 try print(payload.elem_type, writer, target);
2061 try print(payload.elem_type, writer, mod);
20412062 try writer.writeAll(")");
20422063 },
20432064 .array => {
20442065 const payload = ty.castTag(.array).?.data;
20452066 try writer.print("[{d}]", .{payload.len});
2046 try print(payload.elem_type, writer, target);
2067 try print(payload.elem_type, writer, mod);
20472068 },
20482069 .array_sentinel => {
20492070 const payload = ty.castTag(.array_sentinel).?.data;
20502071 try writer.print("[{d}:{}]", .{
20512072 payload.len,
2052 payload.sentinel.fmtValue(payload.elem_type, target),
2073 payload.sentinel.fmtValue(payload.elem_type, mod),
20532074 });
2054 try print(payload.elem_type, writer, target);
2075 try print(payload.elem_type, writer, mod);
20552076 },
20562077 .tuple => {
20572078 const tuple = ty.castTag(.tuple).?.data;
......@@ -2063,9 +2084,9 @@ pub const Type = extern union {
20632084 if (val.tag() != .unreachable_value) {
20642085 try writer.writeAll("comptime ");
20652086 }
2066 try print(field_ty, writer, target);
2087 try print(field_ty, writer, mod);
20672088 if (val.tag() != .unreachable_value) {
2068 try writer.print(" = {}", .{val.fmtValue(field_ty, target)});
2089 try writer.print(" = {}", .{val.fmtValue(field_ty, mod)});
20692090 }
20702091 }
20712092 try writer.writeAll("}");
......@@ -2083,10 +2104,10 @@ pub const Type = extern union {
20832104 try writer.writeAll(anon_struct.names[i]);
20842105 try writer.writeAll(": ");
20852106
2086 try print(field_ty, writer, target);
2107 try print(field_ty, writer, mod);
20872108
20882109 if (val.tag() != .unreachable_value) {
2089 try writer.print(" = {}", .{val.fmtValue(field_ty, target)});
2110 try writer.print(" = {}", .{val.fmtValue(field_ty, mod)});
20902111 }
20912112 }
20922113 try writer.writeAll("}");
......@@ -2106,8 +2127,8 @@ pub const Type = extern union {
21062127
21072128 if (info.sentinel) |s| switch (info.size) {
21082129 .One, .C => unreachable,
2109 .Many => try writer.print("[*:{}]", .{s.fmtValue(info.pointee_type, target)}),
2110 .Slice => try writer.print("[:{}]", .{s.fmtValue(info.pointee_type, target)}),
2130 .Many => try writer.print("[*:{}]", .{s.fmtValue(info.pointee_type, mod)}),
2131 .Slice => try writer.print("[:{}]", .{s.fmtValue(info.pointee_type, mod)}),
21112132 } else switch (info.size) {
21122133 .One => try writer.writeAll("*"),
21132134 .Many => try writer.writeAll("[*]"),
......@@ -2129,7 +2150,7 @@ pub const Type = extern union {
21292150 if (info.@"volatile") try writer.writeAll("volatile ");
21302151 if (info.@"allowzero" and info.size != .C) try writer.writeAll("allowzero ");
21312152
2132 try print(info.pointee_type, writer, target);
2153 try print(info.pointee_type, writer, mod);
21332154 },
21342155
21352156 .int_signed => {
......@@ -2143,22 +2164,22 @@ pub const Type = extern union {
21432164 .optional => {
21442165 const child_type = ty.castTag(.optional).?.data;
21452166 try writer.writeByte('?');
2146 try print(child_type, writer, target);
2167 try print(child_type, writer, mod);
21472168 },
21482169 .optional_single_mut_pointer => {
21492170 const pointee_type = ty.castTag(.optional_single_mut_pointer).?.data;
21502171 try writer.writeAll("?*");
2151 try print(pointee_type, writer, target);
2172 try print(pointee_type, writer, mod);
21522173 },
21532174 .optional_single_const_pointer => {
21542175 const pointee_type = ty.castTag(.optional_single_const_pointer).?.data;
21552176 try writer.writeAll("?*const ");
2156 try print(pointee_type, writer, target);
2177 try print(pointee_type, writer, mod);
21572178 },
21582179 .anyframe_T => {
21592180 const return_type = ty.castTag(.anyframe_T).?.data;
21602181 try writer.print("anyframe->", .{});
2161 try print(return_type, writer, target);
2182 try print(return_type, writer, mod);
21622183 },
21632184 .error_set => {
21642185 const names = ty.castTag(.error_set).?.data.names.keys();
......@@ -3834,8 +3855,8 @@ pub const Type = extern union {
38343855 /// For [*]T, returns *T
38353856 /// For []T, returns *T
38363857 /// Handles const-ness and address spaces in particular.
3837 pub fn elemPtrType(ptr_ty: Type, arena: Allocator, target: Target) !Type {
3838 return try Type.ptr(arena, target, .{
3858 pub fn elemPtrType(ptr_ty: Type, arena: Allocator, mod: *Module) !Type {
3859 return try Type.ptr(arena, mod, .{
38393860 .pointee_type = ptr_ty.elemType2(),
38403861 .mutable = ptr_ty.ptrIsMutable(),
38413862 .@"addrspace" = ptr_ty.ptrAddressSpace(),
......@@ -3948,9 +3969,9 @@ pub const Type = extern union {
39483969 return union_obj.fields;
39493970 }
39503971
3951 pub fn unionFieldType(ty: Type, enum_tag: Value, target: Target) Type {
3972 pub fn unionFieldType(ty: Type, enum_tag: Value, mod: *Module) Type {
39523973 const union_obj = ty.cast(Payload.Union).?.data;
3953 const index = union_obj.tag_ty.enumTagFieldIndex(enum_tag, target).?;
3974 const index = union_obj.tag_ty.enumTagFieldIndex(enum_tag, mod).?;
39543975 assert(union_obj.haveFieldTypes());
39553976 return union_obj.fields.values()[index].ty;
39563977 }
......@@ -4970,20 +4991,20 @@ pub const Type = extern union {
49704991 /// Asserts `ty` is an enum. `enum_tag` can either be `enum_field_index` or
49714992 /// an integer which represents the enum value. Returns the field index in
49724993 /// declaration order, or `null` if `enum_tag` does not match any field.
4973 pub fn enumTagFieldIndex(ty: Type, enum_tag: Value, target: Target) ?usize {
4994 pub fn enumTagFieldIndex(ty: Type, enum_tag: Value, mod: *Module) ?usize {
49744995 if (enum_tag.castTag(.enum_field_index)) |payload| {
49754996 return @as(usize, payload.data);
49764997 }
49774998 const S = struct {
4978 fn fieldWithRange(int_ty: Type, int_val: Value, end: usize, tg: Target) ?usize {
4999 fn fieldWithRange(int_ty: Type, int_val: Value, end: usize, m: *Module) ?usize {
49795000 if (int_val.compareWithZero(.lt)) return null;
49805001 var end_payload: Value.Payload.U64 = .{
49815002 .base = .{ .tag = .int_u64 },
49825003 .data = end,
49835004 };
49845005 const end_val = Value.initPayload(&end_payload.base);
4985 if (int_val.compare(.gte, end_val, int_ty, tg)) return null;
4986 return @intCast(usize, int_val.toUnsignedInt(tg));
5006 if (int_val.compare(.gte, end_val, int_ty, m)) return null;
5007 return @intCast(usize, int_val.toUnsignedInt(m.getTarget()));
49875008 }
49885009 };
49895010 switch (ty.tag()) {
......@@ -4991,11 +5012,11 @@ pub const Type = extern union {
49915012 const enum_full = ty.cast(Payload.EnumFull).?.data;
49925013 const tag_ty = enum_full.tag_ty;
49935014 if (enum_full.values.count() == 0) {
4994 return S.fieldWithRange(tag_ty, enum_tag, enum_full.fields.count(), target);
5015 return S.fieldWithRange(tag_ty, enum_tag, enum_full.fields.count(), mod);
49955016 } else {
49965017 return enum_full.values.getIndexContext(enum_tag, .{
49975018 .ty = tag_ty,
4998 .target = target,
5019 .mod = mod,
49995020 });
50005021 }
50015022 },
......@@ -5003,11 +5024,11 @@ pub const Type = extern union {
50035024 const enum_obj = ty.castTag(.enum_numbered).?.data;
50045025 const tag_ty = enum_obj.tag_ty;
50055026 if (enum_obj.values.count() == 0) {
5006 return S.fieldWithRange(tag_ty, enum_tag, enum_obj.fields.count(), target);
5027 return S.fieldWithRange(tag_ty, enum_tag, enum_obj.fields.count(), mod);
50075028 } else {
50085029 return enum_obj.values.getIndexContext(enum_tag, .{
50095030 .ty = tag_ty,
5010 .target = target,
5031 .mod = mod,
50115032 });
50125033 }
50135034 },
......@@ -5020,7 +5041,7 @@ pub const Type = extern union {
50205041 .data = bits,
50215042 };
50225043 const tag_ty = Type.initPayload(&buffer.base);
5023 return S.fieldWithRange(tag_ty, enum_tag, fields_len, target);
5044 return S.fieldWithRange(tag_ty, enum_tag, fields_len, mod);
50245045 },
50255046 .atomic_order,
50265047 .atomic_rmw_op,
......@@ -5224,32 +5245,35 @@ pub const Type = extern union {
52245245 }
52255246 }
52265247
5227 pub fn declSrcLoc(ty: Type) Module.SrcLoc {
5228 return declSrcLocOrNull(ty).?;
5248 pub fn declSrcLoc(ty: Type, mod: *Module) Module.SrcLoc {
5249 return declSrcLocOrNull(ty, mod).?;
52295250 }
52305251
5231 pub fn declSrcLocOrNull(ty: Type) ?Module.SrcLoc {
5252 pub fn declSrcLocOrNull(ty: Type, mod: *Module) ?Module.SrcLoc {
52325253 switch (ty.tag()) {
52335254 .enum_full, .enum_nonexhaustive => {
52345255 const enum_full = ty.cast(Payload.EnumFull).?.data;
5235 return enum_full.srcLoc();
5256 return enum_full.srcLoc(mod);
5257 },
5258 .enum_numbered => {
5259 const enum_numbered = ty.castTag(.enum_numbered).?.data;
5260 return enum_numbered.srcLoc(mod);
52365261 },
5237 .enum_numbered => return ty.castTag(.enum_numbered).?.data.srcLoc(),
52385262 .enum_simple => {
52395263 const enum_simple = ty.castTag(.enum_simple).?.data;
5240 return enum_simple.srcLoc();
5264 return enum_simple.srcLoc(mod);
52415265 },
52425266 .@"struct" => {
52435267 const struct_obj = ty.castTag(.@"struct").?.data;
5244 return struct_obj.srcLoc();
5268 return struct_obj.srcLoc(mod);
52455269 },
52465270 .error_set => {
52475271 const error_set = ty.castTag(.error_set).?.data;
5248 return error_set.srcLoc();
5272 return error_set.srcLoc(mod);
52495273 },
52505274 .@"union", .union_tagged => {
52515275 const union_obj = ty.cast(Payload.Union).?.data;
5252 return union_obj.srcLoc();
5276 return union_obj.srcLoc(mod);
52535277 },
52545278 .atomic_order,
52555279 .atomic_rmw_op,
......@@ -5268,7 +5292,7 @@ pub const Type = extern union {
52685292 }
52695293 }
52705294
5271 pub fn getOwnerDecl(ty: Type) *Module.Decl {
5295 pub fn getOwnerDecl(ty: Type) Module.Decl.Index {
52725296 switch (ty.tag()) {
52735297 .enum_full, .enum_nonexhaustive => {
52745298 const enum_full = ty.cast(Payload.EnumFull).?.data;
......@@ -5357,30 +5381,30 @@ pub const Type = extern union {
53575381 }
53585382
53595383 /// Asserts the type is an enum.
5360 pub fn enumHasInt(ty: Type, int: Value, target: Target) bool {
5384 pub fn enumHasInt(ty: Type, int: Value, mod: *Module) bool {
53615385 const S = struct {
5362 fn intInRange(tag_ty: Type, int_val: Value, end: usize, tg: Target) bool {
5386 fn intInRange(tag_ty: Type, int_val: Value, end: usize, m: *Module) bool {
53635387 if (int_val.compareWithZero(.lt)) return false;
53645388 var end_payload: Value.Payload.U64 = .{
53655389 .base = .{ .tag = .int_u64 },
53665390 .data = end,
53675391 };
53685392 const end_val = Value.initPayload(&end_payload.base);
5369 if (int_val.compare(.gte, end_val, tag_ty, tg)) return false;
5393 if (int_val.compare(.gte, end_val, tag_ty, m)) return false;
53705394 return true;
53715395 }
53725396 };
53735397 switch (ty.tag()) {
5374 .enum_nonexhaustive => return int.intFitsInType(ty, target),
5398 .enum_nonexhaustive => return int.intFitsInType(ty, mod.getTarget()),
53755399 .enum_full => {
53765400 const enum_full = ty.castTag(.enum_full).?.data;
53775401 const tag_ty = enum_full.tag_ty;
53785402 if (enum_full.values.count() == 0) {
5379 return S.intInRange(tag_ty, int, enum_full.fields.count(), target);
5403 return S.intInRange(tag_ty, int, enum_full.fields.count(), mod);
53805404 } else {
53815405 return enum_full.values.containsContext(int, .{
53825406 .ty = tag_ty,
5383 .target = target,
5407 .mod = mod,
53845408 });
53855409 }
53865410 },
......@@ -5388,11 +5412,11 @@ pub const Type = extern union {
53885412 const enum_obj = ty.castTag(.enum_numbered).?.data;
53895413 const tag_ty = enum_obj.tag_ty;
53905414 if (enum_obj.values.count() == 0) {
5391 return S.intInRange(tag_ty, int, enum_obj.fields.count(), target);
5415 return S.intInRange(tag_ty, int, enum_obj.fields.count(), mod);
53925416 } else {
53935417 return enum_obj.values.containsContext(int, .{
53945418 .ty = tag_ty,
5395 .target = target,
5419 .mod = mod,
53965420 });
53975421 }
53985422 },
......@@ -5405,7 +5429,7 @@ pub const Type = extern union {
54055429 .data = bits,
54065430 };
54075431 const tag_ty = Type.initPayload(&buffer.base);
5408 return S.intInRange(tag_ty, int, fields_len, target);
5432 return S.intInRange(tag_ty, int, fields_len, mod);
54095433 },
54105434 .atomic_order,
54115435 .atomic_rmw_op,
......@@ -5937,7 +5961,9 @@ pub const Type = extern union {
59375961 pub const @"anyopaque" = initTag(.anyopaque);
59385962 pub const @"null" = initTag(.@"null");
59395963
5940 pub fn ptr(arena: Allocator, target: Target, data: Payload.Pointer.Data) !Type {
5964 pub fn ptr(arena: Allocator, mod: *Module, data: Payload.Pointer.Data) !Type {
5965 const target = mod.getTarget();
5966
59415967 var d = data;
59425968
59435969 if (d.size == .C) {
......@@ -5967,7 +5993,7 @@ pub const Type = extern union {
59675993 d.bit_offset == 0 and d.host_size == 0 and !d.@"allowzero" and !d.@"volatile")
59685994 {
59695995 if (d.sentinel) |sent| {
5970 if (!d.mutable and d.pointee_type.eql(Type.u8, target)) {
5996 if (!d.mutable and d.pointee_type.eql(Type.u8, mod)) {
59715997 switch (d.size) {
59725998 .Slice => {
59735999 if (sent.compareWithZero(.eq)) {
......@@ -5982,7 +6008,7 @@ pub const Type = extern union {
59826008 else => {},
59836009 }
59846010 }
5985 } else if (!d.mutable and d.pointee_type.eql(Type.u8, target)) {
6011 } else if (!d.mutable and d.pointee_type.eql(Type.u8, mod)) {
59866012 switch (d.size) {
59876013 .Slice => return Type.initTag(.const_slice_u8),
59886014 .Many => return Type.initTag(.manyptr_const_u8),
......@@ -6016,11 +6042,11 @@ pub const Type = extern union {
60166042 len: u64,
60176043 sent: ?Value,
60186044 elem_type: Type,
6019 target: Target,
6045 mod: *Module,
60206046 ) Allocator.Error!Type {
6021 if (elem_type.eql(Type.u8, target)) {
6047 if (elem_type.eql(Type.u8, mod)) {
60226048 if (sent) |some| {
6023 if (some.eql(Value.zero, elem_type, target)) {
6049 if (some.eql(Value.zero, elem_type, mod)) {
60246050 return Tag.array_u8_sentinel_0.create(arena, len);
60256051 }
60266052 } else {
......@@ -6067,11 +6093,11 @@ pub const Type = extern union {
60676093 arena: Allocator,
60686094 error_set: Type,
60696095 payload: Type,
6070 target: Target,
6096 mod: *Module,
60716097 ) Allocator.Error!Type {
60726098 assert(error_set.zigTypeTag() == .ErrorSet);
6073 if (error_set.eql(Type.@"anyerror", target) and
6074 payload.eql(Type.void, target))
6099 if (error_set.eql(Type.@"anyerror", mod) and
6100 payload.eql(Type.void, mod))
60756101 {
60766102 return Type.initTag(.anyerror_void_error_union);
60776103 }
src/value.zig+122-139
......@@ -731,16 +731,16 @@ pub const Value = extern union {
731731 .int_i64 => return std.fmt.formatIntValue(val.castTag(.int_i64).?.data, "", options, out_stream),
732732 .int_big_positive => return out_stream.print("{}", .{val.castTag(.int_big_positive).?.asBigInt()}),
733733 .int_big_negative => return out_stream.print("{}", .{val.castTag(.int_big_negative).?.asBigInt()}),
734 .function => return out_stream.print("(function '{s}')", .{val.castTag(.function).?.data.owner_decl.name}),
734 .function => return out_stream.print("(function decl={d})", .{val.castTag(.function).?.data.owner_decl}),
735735 .extern_fn => return out_stream.writeAll("(extern function)"),
736736 .variable => return out_stream.writeAll("(variable)"),
737737 .decl_ref_mut => {
738 const decl = val.castTag(.decl_ref_mut).?.data.decl;
739 return out_stream.print("(decl_ref_mut '{s}')", .{decl.name});
738 const decl_index = val.castTag(.decl_ref_mut).?.data.decl_index;
739 return out_stream.print("(decl_ref_mut {d})", .{decl_index});
740740 },
741741 .decl_ref => {
742 const decl = val.castTag(.decl_ref).?.data;
743 return out_stream.print("(decl ref '{s}')", .{decl.name});
742 const decl_index = val.castTag(.decl_ref).?.data;
743 return out_stream.print("(decl_ref {d})", .{decl_index});
744744 },
745745 .elem_ptr => {
746746 const elem_ptr = val.castTag(.elem_ptr).?.data;
......@@ -798,16 +798,17 @@ pub const Value = extern union {
798798 return .{ .data = val };
799799 }
800800
801 pub fn fmtValue(val: Value, ty: Type, target: Target) std.fmt.Formatter(TypedValue.format) {
801 pub fn fmtValue(val: Value, ty: Type, mod: *Module) std.fmt.Formatter(TypedValue.format) {
802802 return .{ .data = .{
803803 .tv = .{ .ty = ty, .val = val },
804 .target = target,
804 .mod = mod,
805805 } };
806806 }
807807
808808 /// Asserts that the value is representable as an array of bytes.
809809 /// Copies the value into a freshly allocated slice of memory, which is owned by the caller.
810 pub fn toAllocatedBytes(val: Value, ty: Type, allocator: Allocator, target: Target) ![]u8 {
810 pub fn toAllocatedBytes(val: Value, ty: Type, allocator: Allocator, mod: *Module) ![]u8 {
811 const target = mod.getTarget();
811812 switch (val.tag()) {
812813 .bytes => {
813814 const bytes = val.castTag(.bytes).?.data;
......@@ -823,25 +824,26 @@ pub const Value = extern union {
823824 return result;
824825 },
825826 .decl_ref => {
826 const decl = val.castTag(.decl_ref).?.data;
827 const decl_index = val.castTag(.decl_ref).?.data;
828 const decl = mod.declPtr(decl_index);
827829 const decl_val = try decl.value();
828 return decl_val.toAllocatedBytes(decl.ty, allocator, target);
830 return decl_val.toAllocatedBytes(decl.ty, allocator, mod);
829831 },
830832 .the_only_possible_value => return &[_]u8{},
831833 .slice => {
832834 const slice = val.castTag(.slice).?.data;
833 return arrayToAllocatedBytes(slice.ptr, slice.len.toUnsignedInt(target), allocator, target);
835 return arrayToAllocatedBytes(slice.ptr, slice.len.toUnsignedInt(target), allocator, mod);
834836 },
835 else => return arrayToAllocatedBytes(val, ty.arrayLen(), allocator, target),
837 else => return arrayToAllocatedBytes(val, ty.arrayLen(), allocator, mod),
836838 }
837839 }
838840
839 fn arrayToAllocatedBytes(val: Value, len: u64, allocator: Allocator, target: Target) ![]u8 {
841 fn arrayToAllocatedBytes(val: Value, len: u64, allocator: Allocator, mod: *Module) ![]u8 {
840842 const result = try allocator.alloc(u8, @intCast(usize, len));
841843 var elem_value_buf: ElemValueBuffer = undefined;
842844 for (result) |*elem, i| {
843 const elem_val = val.elemValueBuffer(i, &elem_value_buf);
844 elem.* = @intCast(u8, elem_val.toUnsignedInt(target));
845 const elem_val = val.elemValueBuffer(mod, i, &elem_value_buf);
846 elem.* = @intCast(u8, elem_val.toUnsignedInt(mod.getTarget()));
845847 }
846848 return result;
847849 }
......@@ -1164,7 +1166,7 @@ pub const Value = extern union {
11641166 var elem_value_buf: ElemValueBuffer = undefined;
11651167 var buf_off: usize = 0;
11661168 while (elem_i < len) : (elem_i += 1) {
1167 const elem_val = val.elemValueBuffer(elem_i, &elem_value_buf);
1169 const elem_val = val.elemValueBuffer(mod, elem_i, &elem_value_buf);
11681170 writeToMemory(elem_val, elem_ty, mod, buffer[buf_off..]);
11691171 buf_off += elem_size;
11701172 }
......@@ -1975,34 +1977,47 @@ pub const Value = extern union {
19751977
19761978 /// Asserts the values are comparable. Both operands have type `ty`.
19771979 /// Vector results will be reduced with AND.
1978 pub fn compare(lhs: Value, op: std.math.CompareOperator, rhs: Value, ty: Type, target: Target) bool {
1980 pub fn compare(lhs: Value, op: std.math.CompareOperator, rhs: Value, ty: Type, mod: *Module) bool {
19791981 if (ty.zigTypeTag() == .Vector) {
19801982 var i: usize = 0;
19811983 while (i < ty.vectorLen()) : (i += 1) {
1982 if (!compareScalar(lhs.indexVectorlike(i), op, rhs.indexVectorlike(i), ty.scalarType(), target)) {
1984 if (!compareScalar(lhs.indexVectorlike(i), op, rhs.indexVectorlike(i), ty.scalarType(), mod)) {
19831985 return false;
19841986 }
19851987 }
19861988 return true;
19871989 }
1988 return compareScalar(lhs, op, rhs, ty, target);
1990 return compareScalar(lhs, op, rhs, ty, mod);
19891991 }
19901992
19911993 /// Asserts the values are comparable. Both operands have type `ty`.
1992 pub fn compareScalar(lhs: Value, op: std.math.CompareOperator, rhs: Value, ty: Type, target: Target) bool {
1994 pub fn compareScalar(
1995 lhs: Value,
1996 op: std.math.CompareOperator,
1997 rhs: Value,
1998 ty: Type,
1999 mod: *Module,
2000 ) bool {
19932001 return switch (op) {
1994 .eq => lhs.eql(rhs, ty, target),
1995 .neq => !lhs.eql(rhs, ty, target),
1996 else => compareHetero(lhs, op, rhs, target),
2002 .eq => lhs.eql(rhs, ty, mod),
2003 .neq => !lhs.eql(rhs, ty, mod),
2004 else => compareHetero(lhs, op, rhs, mod.getTarget()),
19972005 };
19982006 }
19992007
20002008 /// Asserts the values are comparable vectors of type `ty`.
2001 pub fn compareVector(lhs: Value, op: std.math.CompareOperator, rhs: Value, ty: Type, allocator: Allocator, target: Target) !Value {
2009 pub fn compareVector(
2010 lhs: Value,
2011 op: std.math.CompareOperator,
2012 rhs: Value,
2013 ty: Type,
2014 allocator: Allocator,
2015 mod: *Module,
2016 ) !Value {
20022017 assert(ty.zigTypeTag() == .Vector);
20032018 const result_data = try allocator.alloc(Value, ty.vectorLen());
20042019 for (result_data) |*scalar, i| {
2005 const res_bool = compareScalar(lhs.indexVectorlike(i), op, rhs.indexVectorlike(i), ty.scalarType(), target);
2020 const res_bool = compareScalar(lhs.indexVectorlike(i), op, rhs.indexVectorlike(i), ty.scalarType(), mod);
20062021 scalar.* = if (res_bool) Value.@"true" else Value.@"false";
20072022 }
20082023 return Value.Tag.aggregate.create(allocator, result_data);
......@@ -2032,7 +2047,8 @@ pub const Value = extern union {
20322047 /// for `a`. This function must act *as if* `a` has been coerced to `ty`. This complication
20332048 /// is required in order to make generic function instantiation effecient - specifically
20342049 /// the insertion into the monomorphized function table.
2035 pub fn eql(a: Value, b: Value, ty: Type, target: Target) bool {
2050 pub fn eql(a: Value, b: Value, ty: Type, mod: *Module) bool {
2051 const target = mod.getTarget();
20362052 const a_tag = a.tag();
20372053 const b_tag = b.tag();
20382054 if (a_tag == b_tag) switch (a_tag) {
......@@ -2052,31 +2068,31 @@ pub const Value = extern union {
20522068 const a_payload = a.castTag(.opt_payload).?.data;
20532069 const b_payload = b.castTag(.opt_payload).?.data;
20542070 var buffer: Type.Payload.ElemType = undefined;
2055 return eql(a_payload, b_payload, ty.optionalChild(&buffer), target);
2071 return eql(a_payload, b_payload, ty.optionalChild(&buffer), mod);
20562072 },
20572073 .slice => {
20582074 const a_payload = a.castTag(.slice).?.data;
20592075 const b_payload = b.castTag(.slice).?.data;
2060 if (!eql(a_payload.len, b_payload.len, Type.usize, target)) return false;
2076 if (!eql(a_payload.len, b_payload.len, Type.usize, mod)) return false;
20612077
20622078 var ptr_buf: Type.SlicePtrFieldTypeBuffer = undefined;
20632079 const ptr_ty = ty.slicePtrFieldType(&ptr_buf);
20642080
2065 return eql(a_payload.ptr, b_payload.ptr, ptr_ty, target);
2081 return eql(a_payload.ptr, b_payload.ptr, ptr_ty, mod);
20662082 },
20672083 .elem_ptr => {
20682084 const a_payload = a.castTag(.elem_ptr).?.data;
20692085 const b_payload = b.castTag(.elem_ptr).?.data;
20702086 if (a_payload.index != b_payload.index) return false;
20712087
2072 return eql(a_payload.array_ptr, b_payload.array_ptr, ty, target);
2088 return eql(a_payload.array_ptr, b_payload.array_ptr, ty, mod);
20732089 },
20742090 .field_ptr => {
20752091 const a_payload = a.castTag(.field_ptr).?.data;
20762092 const b_payload = b.castTag(.field_ptr).?.data;
20772093 if (a_payload.field_index != b_payload.field_index) return false;
20782094
2079 return eql(a_payload.container_ptr, b_payload.container_ptr, ty, target);
2095 return eql(a_payload.container_ptr, b_payload.container_ptr, ty, mod);
20802096 },
20812097 .@"error" => {
20822098 const a_name = a.castTag(.@"error").?.data.name;
......@@ -2086,7 +2102,7 @@ pub const Value = extern union {
20862102 .eu_payload => {
20872103 const a_payload = a.castTag(.eu_payload).?.data;
20882104 const b_payload = b.castTag(.eu_payload).?.data;
2089 return eql(a_payload, b_payload, ty.errorUnionPayload(), target);
2105 return eql(a_payload, b_payload, ty.errorUnionPayload(), mod);
20902106 },
20912107 .eu_payload_ptr => @panic("TODO: Implement more pointer eql cases"),
20922108 .opt_payload_ptr => @panic("TODO: Implement more pointer eql cases"),
......@@ -2104,7 +2120,7 @@ pub const Value = extern union {
21042120 const types = ty.tupleFields().types;
21052121 assert(types.len == a_field_vals.len);
21062122 for (types) |field_ty, i| {
2107 if (!eql(a_field_vals[i], b_field_vals[i], field_ty, target)) return false;
2123 if (!eql(a_field_vals[i], b_field_vals[i], field_ty, mod)) return false;
21082124 }
21092125 return true;
21102126 }
......@@ -2113,7 +2129,7 @@ pub const Value = extern union {
21132129 const fields = ty.structFields().values();
21142130 assert(fields.len == a_field_vals.len);
21152131 for (fields) |field, i| {
2116 if (!eql(a_field_vals[i], b_field_vals[i], field.ty, target)) return false;
2132 if (!eql(a_field_vals[i], b_field_vals[i], field.ty, mod)) return false;
21172133 }
21182134 return true;
21192135 }
......@@ -2122,7 +2138,7 @@ pub const Value = extern union {
21222138 for (a_field_vals) |a_elem, i| {
21232139 const b_elem = b_field_vals[i];
21242140
2125 if (!eql(a_elem, b_elem, elem_ty, target)) return false;
2141 if (!eql(a_elem, b_elem, elem_ty, mod)) return false;
21262142 }
21272143 return true;
21282144 },
......@@ -2132,7 +2148,7 @@ pub const Value = extern union {
21322148 switch (ty.containerLayout()) {
21332149 .Packed, .Extern => {
21342150 const tag_ty = ty.unionTagTypeHypothetical();
2135 if (!a_union.tag.eql(b_union.tag, tag_ty, target)) {
2151 if (!a_union.tag.eql(b_union.tag, tag_ty, mod)) {
21362152 // In this case, we must disregard mismatching tags and compare
21372153 // based on the in-memory bytes of the payloads.
21382154 @panic("TODO comptime comparison of extern union values with mismatching tags");
......@@ -2140,13 +2156,13 @@ pub const Value = extern union {
21402156 },
21412157 .Auto => {
21422158 const tag_ty = ty.unionTagTypeHypothetical();
2143 if (!a_union.tag.eql(b_union.tag, tag_ty, target)) {
2159 if (!a_union.tag.eql(b_union.tag, tag_ty, mod)) {
21442160 return false;
21452161 }
21462162 },
21472163 }
2148 const active_field_ty = ty.unionFieldType(a_union.tag, target);
2149 return a_union.val.eql(b_union.val, active_field_ty, target);
2164 const active_field_ty = ty.unionFieldType(a_union.tag, mod);
2165 return a_union.val.eql(b_union.val, active_field_ty, mod);
21502166 },
21512167 else => {},
21522168 } else if (a_tag == .null_value or b_tag == .null_value) {
......@@ -2171,7 +2187,7 @@ pub const Value = extern union {
21712187 var buf_b: ToTypeBuffer = undefined;
21722188 const a_type = a.toType(&buf_a);
21732189 const b_type = b.toType(&buf_b);
2174 return a_type.eql(b_type, target);
2190 return a_type.eql(b_type, mod);
21752191 },
21762192 .Enum => {
21772193 var buf_a: Payload.U64 = undefined;
......@@ -2180,7 +2196,7 @@ pub const Value = extern union {
21802196 const b_val = b.enumToInt(ty, &buf_b);
21812197 var buf_ty: Type.Payload.Bits = undefined;
21822198 const int_ty = ty.intTagType(&buf_ty);
2183 return eql(a_val, b_val, int_ty, target);
2199 return eql(a_val, b_val, int_ty, mod);
21842200 },
21852201 .Array, .Vector => {
21862202 const len = ty.arrayLen();
......@@ -2189,9 +2205,9 @@ pub const Value = extern union {
21892205 var a_buf: ElemValueBuffer = undefined;
21902206 var b_buf: ElemValueBuffer = undefined;
21912207 while (i < len) : (i += 1) {
2192 const a_elem = elemValueBuffer(a, i, &a_buf);
2193 const b_elem = elemValueBuffer(b, i, &b_buf);
2194 if (!eql(a_elem, b_elem, elem_ty, target)) return false;
2208 const a_elem = elemValueBuffer(a, mod, i, &a_buf);
2209 const b_elem = elemValueBuffer(b, mod, i, &b_buf);
2210 if (!eql(a_elem, b_elem, elem_ty, mod)) return false;
21952211 }
21962212 return true;
21972213 },
......@@ -2215,7 +2231,7 @@ pub const Value = extern union {
22152231 .base = .{ .tag = .opt_payload },
22162232 .data = a,
22172233 };
2218 return eql(Value.initPayload(&buffer.base), b, ty, target);
2234 return eql(Value.initPayload(&buffer.base), b, ty, mod);
22192235 }
22202236 },
22212237 else => {},
......@@ -2225,7 +2241,7 @@ pub const Value = extern union {
22252241
22262242 /// This function is used by hash maps and so treats floating-point NaNs as equal
22272243 /// to each other, and not equal to other floating-point values.
2228 pub fn hash(val: Value, ty: Type, hasher: *std.hash.Wyhash, target: Target) void {
2244 pub fn hash(val: Value, ty: Type, hasher: *std.hash.Wyhash, mod: *Module) void {
22292245 const zig_ty_tag = ty.zigTypeTag();
22302246 std.hash.autoHash(hasher, zig_ty_tag);
22312247 if (val.isUndef()) return;
......@@ -2242,7 +2258,7 @@ pub const Value = extern union {
22422258
22432259 .Type => {
22442260 var buf: ToTypeBuffer = undefined;
2245 return val.toType(&buf).hashWithHasher(hasher, target);
2261 return val.toType(&buf).hashWithHasher(hasher, mod);
22462262 },
22472263 .Float, .ComptimeFloat => {
22482264 // Normalize the float here because this hash must match eql semantics.
......@@ -2263,11 +2279,11 @@ pub const Value = extern union {
22632279 const slice = val.castTag(.slice).?.data;
22642280 var ptr_buf: Type.SlicePtrFieldTypeBuffer = undefined;
22652281 const ptr_ty = ty.slicePtrFieldType(&ptr_buf);
2266 hash(slice.ptr, ptr_ty, hasher, target);
2267 hash(slice.len, Type.usize, hasher, target);
2282 hash(slice.ptr, ptr_ty, hasher, mod);
2283 hash(slice.len, Type.usize, hasher, mod);
22682284 },
22692285
2270 else => return hashPtr(val, hasher, target),
2286 else => return hashPtr(val, hasher, mod.getTarget()),
22712287 },
22722288 .Array, .Vector => {
22732289 const len = ty.arrayLen();
......@@ -2275,15 +2291,15 @@ pub const Value = extern union {
22752291 var index: usize = 0;
22762292 var elem_value_buf: ElemValueBuffer = undefined;
22772293 while (index < len) : (index += 1) {
2278 const elem_val = val.elemValueBuffer(index, &elem_value_buf);
2279 elem_val.hash(elem_ty, hasher, target);
2294 const elem_val = val.elemValueBuffer(mod, index, &elem_value_buf);
2295 elem_val.hash(elem_ty, hasher, mod);
22802296 }
22812297 },
22822298 .Struct => {
22832299 if (ty.isTupleOrAnonStruct()) {
22842300 const fields = ty.tupleFields();
22852301 for (fields.values) |field_val, i| {
2286 field_val.hash(fields.types[i], hasher, target);
2302 field_val.hash(fields.types[i], hasher, mod);
22872303 }
22882304 return;
22892305 }
......@@ -2292,13 +2308,13 @@ pub const Value = extern union {
22922308 switch (val.tag()) {
22932309 .empty_struct_value => {
22942310 for (fields) |field| {
2295 field.default_val.hash(field.ty, hasher, target);
2311 field.default_val.hash(field.ty, hasher, mod);
22962312 }
22972313 },
22982314 .aggregate => {
22992315 const field_values = val.castTag(.aggregate).?.data;
23002316 for (field_values) |field_val, i| {
2301 field_val.hash(fields[i].ty, hasher, target);
2317 field_val.hash(fields[i].ty, hasher, mod);
23022318 }
23032319 },
23042320 else => unreachable,
......@@ -2310,7 +2326,7 @@ pub const Value = extern union {
23102326 const sub_val = payload.data;
23112327 var buffer: Type.Payload.ElemType = undefined;
23122328 const sub_ty = ty.optionalChild(&buffer);
2313 sub_val.hash(sub_ty, hasher, target);
2329 sub_val.hash(sub_ty, hasher, mod);
23142330 } else {
23152331 std.hash.autoHash(hasher, false); // non-null
23162332 }
......@@ -2319,14 +2335,14 @@ pub const Value = extern union {
23192335 if (val.tag() == .@"error") {
23202336 std.hash.autoHash(hasher, false); // error
23212337 const sub_ty = ty.errorUnionSet();
2322 val.hash(sub_ty, hasher, target);
2338 val.hash(sub_ty, hasher, mod);
23232339 return;
23242340 }
23252341
23262342 if (val.castTag(.eu_payload)) |payload| {
23272343 std.hash.autoHash(hasher, true); // payload
23282344 const sub_ty = ty.errorUnionPayload();
2329 payload.data.hash(sub_ty, hasher, target);
2345 payload.data.hash(sub_ty, hasher, mod);
23302346 return;
23312347 } else unreachable;
23322348 },
......@@ -2339,15 +2355,15 @@ pub const Value = extern union {
23392355 .Enum => {
23402356 var enum_space: Payload.U64 = undefined;
23412357 const int_val = val.enumToInt(ty, &enum_space);
2342 hashInt(int_val, hasher, target);
2358 hashInt(int_val, hasher, mod.getTarget());
23432359 },
23442360 .Union => {
23452361 const union_obj = val.cast(Payload.Union).?.data;
23462362 if (ty.unionTagType()) |tag_ty| {
2347 union_obj.tag.hash(tag_ty, hasher, target);
2363 union_obj.tag.hash(tag_ty, hasher, mod);
23482364 }
2349 const active_field_ty = ty.unionFieldType(union_obj.tag, target);
2350 union_obj.val.hash(active_field_ty, hasher, target);
2365 const active_field_ty = ty.unionFieldType(union_obj.tag, mod);
2366 union_obj.val.hash(active_field_ty, hasher, mod);
23512367 },
23522368 .Fn => {
23532369 const func: *Module.Fn = val.castTag(.function).?.data;
......@@ -2372,30 +2388,30 @@ pub const Value = extern union {
23722388
23732389 pub const ArrayHashContext = struct {
23742390 ty: Type,
2375 target: Target,
2391 mod: *Module,
23762392
23772393 pub fn hash(self: @This(), val: Value) u32 {
2378 const other_context: HashContext = .{ .ty = self.ty, .target = self.target };
2394 const other_context: HashContext = .{ .ty = self.ty, .mod = self.mod };
23792395 return @truncate(u32, other_context.hash(val));
23802396 }
23812397 pub fn eql(self: @This(), a: Value, b: Value, b_index: usize) bool {
23822398 _ = b_index;
2383 return a.eql(b, self.ty, self.target);
2399 return a.eql(b, self.ty, self.mod);
23842400 }
23852401 };
23862402
23872403 pub const HashContext = struct {
23882404 ty: Type,
2389 target: Target,
2405 mod: *Module,
23902406
23912407 pub fn hash(self: @This(), val: Value) u64 {
23922408 var hasher = std.hash.Wyhash.init(0);
2393 val.hash(self.ty, &hasher, self.target);
2409 val.hash(self.ty, &hasher, self.mod);
23942410 return hasher.final();
23952411 }
23962412
23972413 pub fn eql(self: @This(), a: Value, b: Value) bool {
2398 return a.eql(b, self.ty, self.target);
2414 return a.eql(b, self.ty, self.mod);
23992415 }
24002416 };
24012417
......@@ -2434,9 +2450,9 @@ pub const Value = extern union {
24342450 /// Gets the decl referenced by this pointer. If the pointer does not point
24352451 /// to a decl, or if it points to some part of a decl (like field_ptr or element_ptr),
24362452 /// this function returns null.
2437 pub fn pointerDecl(val: Value) ?*Module.Decl {
2453 pub fn pointerDecl(val: Value) ?Module.Decl.Index {
24382454 return switch (val.tag()) {
2439 .decl_ref_mut => val.castTag(.decl_ref_mut).?.data.decl,
2455 .decl_ref_mut => val.castTag(.decl_ref_mut).?.data.decl_index,
24402456 .extern_fn => val.castTag(.extern_fn).?.data.owner_decl,
24412457 .function => val.castTag(.function).?.data.owner_decl,
24422458 .variable => val.castTag(.variable).?.data.owner_decl,
......@@ -2462,7 +2478,7 @@ pub const Value = extern union {
24622478 .function,
24632479 .variable,
24642480 => {
2465 const decl: *Module.Decl = ptr_val.pointerDecl().?;
2481 const decl: Module.Decl.Index = ptr_val.pointerDecl().?;
24662482 std.hash.autoHash(hasher, decl);
24672483 },
24682484
......@@ -2505,53 +2521,6 @@ pub const Value = extern union {
25052521 }
25062522 }
25072523
2508 pub fn markReferencedDeclsAlive(val: Value) void {
2509 switch (val.tag()) {
2510 .decl_ref_mut => return val.castTag(.decl_ref_mut).?.data.decl.markAlive(),
2511 .extern_fn => return val.castTag(.extern_fn).?.data.owner_decl.markAlive(),
2512 .function => return val.castTag(.function).?.data.owner_decl.markAlive(),
2513 .variable => return val.castTag(.variable).?.data.owner_decl.markAlive(),
2514 .decl_ref => return val.cast(Payload.Decl).?.data.markAlive(),
2515
2516 .repeated,
2517 .eu_payload,
2518 .opt_payload,
2519 .empty_array_sentinel,
2520 => return markReferencedDeclsAlive(val.cast(Payload.SubValue).?.data),
2521
2522 .eu_payload_ptr,
2523 .opt_payload_ptr,
2524 => return markReferencedDeclsAlive(val.cast(Payload.PayloadPtr).?.data.container_ptr),
2525
2526 .slice => {
2527 const slice = val.cast(Payload.Slice).?.data;
2528 markReferencedDeclsAlive(slice.ptr);
2529 markReferencedDeclsAlive(slice.len);
2530 },
2531
2532 .elem_ptr => {
2533 const elem_ptr = val.cast(Payload.ElemPtr).?.data;
2534 return markReferencedDeclsAlive(elem_ptr.array_ptr);
2535 },
2536 .field_ptr => {
2537 const field_ptr = val.cast(Payload.FieldPtr).?.data;
2538 return markReferencedDeclsAlive(field_ptr.container_ptr);
2539 },
2540 .aggregate => {
2541 for (val.castTag(.aggregate).?.data) |field_val| {
2542 markReferencedDeclsAlive(field_val);
2543 }
2544 },
2545 .@"union" => {
2546 const data = val.cast(Payload.Union).?.data;
2547 markReferencedDeclsAlive(data.tag);
2548 markReferencedDeclsAlive(data.val);
2549 },
2550
2551 else => {},
2552 }
2553 }
2554
25552524 pub fn slicePtr(val: Value) Value {
25562525 return switch (val.tag()) {
25572526 .slice => val.castTag(.slice).?.data.ptr,
......@@ -2561,11 +2530,12 @@ pub const Value = extern union {
25612530 };
25622531 }
25632532
2564 pub fn sliceLen(val: Value, target: Target) u64 {
2533 pub fn sliceLen(val: Value, mod: *Module) u64 {
25652534 return switch (val.tag()) {
2566 .slice => val.castTag(.slice).?.data.len.toUnsignedInt(target),
2535 .slice => val.castTag(.slice).?.data.len.toUnsignedInt(mod.getTarget()),
25672536 .decl_ref => {
2568 const decl = val.castTag(.decl_ref).?.data;
2537 const decl_index = val.castTag(.decl_ref).?.data;
2538 const decl = mod.declPtr(decl_index);
25692539 if (decl.ty.zigTypeTag() == .Array) {
25702540 return decl.ty.arrayLen();
25712541 } else {
......@@ -2599,18 +2569,19 @@ pub const Value = extern union {
25992569
26002570 /// Asserts the value is a single-item pointer to an array, or an array,
26012571 /// or an unknown-length pointer, and returns the element value at the index.
2602 pub fn elemValue(val: Value, arena: Allocator, index: usize) !Value {
2603 return elemValueAdvanced(val, index, arena, undefined);
2572 pub fn elemValue(val: Value, mod: *Module, arena: Allocator, index: usize) !Value {
2573 return elemValueAdvanced(val, mod, index, arena, undefined);
26042574 }
26052575
26062576 pub const ElemValueBuffer = Payload.U64;
26072577
2608 pub fn elemValueBuffer(val: Value, index: usize, buffer: *ElemValueBuffer) Value {
2609 return elemValueAdvanced(val, index, null, buffer) catch unreachable;
2578 pub fn elemValueBuffer(val: Value, mod: *Module, index: usize, buffer: *ElemValueBuffer) Value {
2579 return elemValueAdvanced(val, mod, index, null, buffer) catch unreachable;
26102580 }
26112581
26122582 pub fn elemValueAdvanced(
26132583 val: Value,
2584 mod: *Module,
26142585 index: usize,
26152586 arena: ?Allocator,
26162587 buffer: *ElemValueBuffer,
......@@ -2643,13 +2614,13 @@ pub const Value = extern union {
26432614 .repeated => return val.castTag(.repeated).?.data,
26442615
26452616 .aggregate => return val.castTag(.aggregate).?.data[index],
2646 .slice => return val.castTag(.slice).?.data.ptr.elemValueAdvanced(index, arena, buffer),
2617 .slice => return val.castTag(.slice).?.data.ptr.elemValueAdvanced(mod, index, arena, buffer),
26472618
2648 .decl_ref => return val.castTag(.decl_ref).?.data.val.elemValueAdvanced(index, arena, buffer),
2649 .decl_ref_mut => return val.castTag(.decl_ref_mut).?.data.decl.val.elemValueAdvanced(index, arena, buffer),
2619 .decl_ref => return mod.declPtr(val.castTag(.decl_ref).?.data).val.elemValueAdvanced(mod, index, arena, buffer),
2620 .decl_ref_mut => return mod.declPtr(val.castTag(.decl_ref_mut).?.data.decl_index).val.elemValueAdvanced(mod, index, arena, buffer),
26502621 .elem_ptr => {
26512622 const data = val.castTag(.elem_ptr).?.data;
2652 return data.array_ptr.elemValueAdvanced(index + data.index, arena, buffer);
2623 return data.array_ptr.elemValueAdvanced(mod, index + data.index, arena, buffer);
26532624 },
26542625
26552626 // The child type of arrays which have only one possible value need
......@@ -2661,18 +2632,24 @@ pub const Value = extern union {
26612632 }
26622633
26632634 // Asserts that the provided start/end are in-bounds.
2664 pub fn sliceArray(val: Value, arena: Allocator, start: usize, end: usize) error{OutOfMemory}!Value {
2635 pub fn sliceArray(
2636 val: Value,
2637 mod: *Module,
2638 arena: Allocator,
2639 start: usize,
2640 end: usize,
2641 ) error{OutOfMemory}!Value {
26652642 return switch (val.tag()) {
26662643 .empty_array_sentinel => if (start == 0 and end == 1) val else Value.initTag(.empty_array),
26672644 .bytes => Tag.bytes.create(arena, val.castTag(.bytes).?.data[start..end]),
26682645 .aggregate => Tag.aggregate.create(arena, val.castTag(.aggregate).?.data[start..end]),
2669 .slice => sliceArray(val.castTag(.slice).?.data.ptr, arena, start, end),
2646 .slice => sliceArray(val.castTag(.slice).?.data.ptr, mod, arena, start, end),
26702647
2671 .decl_ref => sliceArray(val.castTag(.decl_ref).?.data.val, arena, start, end),
2672 .decl_ref_mut => sliceArray(val.castTag(.decl_ref_mut).?.data.decl.val, arena, start, end),
2648 .decl_ref => sliceArray(mod.declPtr(val.castTag(.decl_ref).?.data).val, mod, arena, start, end),
2649 .decl_ref_mut => sliceArray(mod.declPtr(val.castTag(.decl_ref_mut).?.data.decl_index).val, mod, arena, start, end),
26732650 .elem_ptr => blk: {
26742651 const elem_ptr = val.castTag(.elem_ptr).?.data;
2675 break :blk sliceArray(elem_ptr.array_ptr, arena, start + elem_ptr.index, end + elem_ptr.index);
2652 break :blk sliceArray(elem_ptr.array_ptr, mod, arena, start + elem_ptr.index, end + elem_ptr.index);
26762653 },
26772654
26782655 .repeated,
......@@ -2718,7 +2695,13 @@ pub const Value = extern union {
27182695 }
27192696
27202697 /// Returns a pointer to the element value at the index.
2721 pub fn elemPtr(val: Value, ty: Type, arena: Allocator, index: usize, target: Target) Allocator.Error!Value {
2698 pub fn elemPtr(
2699 val: Value,
2700 ty: Type,
2701 arena: Allocator,
2702 index: usize,
2703 mod: *Module,
2704 ) Allocator.Error!Value {
27222705 const elem_ty = ty.elemType2();
27232706 const ptr_val = switch (val.tag()) {
27242707 .slice => val.castTag(.slice).?.data.ptr,
......@@ -2727,7 +2710,7 @@ pub const Value = extern union {
27272710
27282711 if (ptr_val.tag() == .elem_ptr) {
27292712 const elem_ptr = ptr_val.castTag(.elem_ptr).?.data;
2730 if (elem_ptr.elem_ty.eql(elem_ty, target)) {
2713 if (elem_ptr.elem_ty.eql(elem_ty, mod)) {
27312714 return Tag.elem_ptr.create(arena, .{
27322715 .array_ptr = elem_ptr.array_ptr,
27332716 .elem_ty = elem_ptr.elem_ty,
......@@ -5059,7 +5042,7 @@ pub const Value = extern union {
50595042
50605043 pub const Decl = struct {
50615044 base: Payload,
5062 data: *Module.Decl,
5045 data: Module.Decl.Index,
50635046 };
50645047
50655048 pub const Variable = struct {
......@@ -5079,7 +5062,7 @@ pub const Value = extern union {
50795062 data: Data,
50805063
50815064 pub const Data = struct {
5082 decl: *Module.Decl,
5065 decl_index: Module.Decl.Index,
50835066 runtime_index: u32,
50845067 };
50855068 };
......@@ -5215,7 +5198,7 @@ pub const Value = extern union {
52155198
52165199 base: Payload = .{ .tag = base_tag },
52175200 data: struct {
5218 decl: *Module.Decl,
5201 decl_index: Module.Decl.Index,
52195202 /// 0 means ABI-aligned.
52205203 alignment: u16,
52215204 },